text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Allow presents to be placed inside container items
|
package net.mcft.copy.betterstorage.item.tile;
import java.util.List;
import net.mcft.copy.betterstorage.tile.entity.TileEntityPresent;
import net.mcft.copy.betterstorage.utils.StackUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemPresent extends ItemCardboardBox {
public ItemPresent(Block block) {
super(block);
}
@Override
public EnumRarity getRarity(ItemStack stack) { return EnumRarity.uncommon; }
@Override
public boolean showDurabilityBar(ItemStack stack) { return false; }
@Override
@SideOnly(Side.CLIENT)
public int getColorFromItemStack(ItemStack stack, int renderPass) { return 0xFFFFFF; }
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) {
String nameTag = StackUtils.get(stack, null, TileEntityPresent.TAG_NAMETAG);
if (nameTag != null) list.add("for " + nameTag);
}
@Override
public boolean canBeStoredInContainerItem(ItemStack item) { return true; }
}
|
package net.mcft.copy.betterstorage.item.tile;
import java.util.List;
import net.mcft.copy.betterstorage.tile.entity.TileEntityPresent;
import net.mcft.copy.betterstorage.utils.StackUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemPresent extends ItemCardboardBox {
public ItemPresent(Block block) {
super(block);
}
@Override
public EnumRarity getRarity(ItemStack stack) { return EnumRarity.uncommon; }
@Override
public boolean showDurabilityBar(ItemStack stack) { return false; }
@Override
@SideOnly(Side.CLIENT)
public int getColorFromItemStack(ItemStack stack, int renderPass) { return 0xFFFFFF; }
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) {
String nameTag = StackUtils.get(stack, null, TileEntityPresent.TAG_NAMETAG);
if (nameTag != null) list.add("for " + nameTag);
}
}
|
Use date_url for .dates(), as Django 1.6 doesn't like DateTimeField here
|
from django import template
from django.utils import timezone
from blanc_basic_news.news import get_post_model
from blanc_basic_news.news.models import Category
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return get_post_model().objects.filter(
published=True, date__lte=timezone.now()).dates('date_url', 'month')
@register.assignment_tag
def get_latest_news(count, category=None):
post_list = get_post_model().objects.select_related().filter(
published=True, date__lte=timezone.now())
# Optional filter by category
if category is not None:
post_list = post_list.filter(category__slug=category)
return post_list[:count]
|
from django import template
from django.utils import timezone
from blanc_basic_news.news import get_post_model
from blanc_basic_news.news.models import Category
register = template.Library()
@register.assignment_tag
def get_news_categories():
return Category.objects.all()
@register.assignment_tag
def get_news_months():
return get_post_model().objects.filter(
published=True, date__lte=timezone.now()).dates('date', 'month')
@register.assignment_tag
def get_latest_news(count, category=None):
post_list = get_post_model().objects.select_related().filter(
published=True, date__lte=timezone.now())
# Optional filter by category
if category is not None:
post_list = post_list.filter(category__slug=category)
return post_list[:count]
|
Make the whole div clickable
|
import { default as React, Component } from 'react'
import { render } from 'react-dom'
export class List extends Component {
constructor(props) {
super(props);
}
render() {
let items = this.props.items;
var itemsComponent = []
Object.keys(items).forEach(function (key) {
itemsComponent.push(<Item key={key} value={items[key]} _id={key} onClick={this.props.onClick} />);
}.bind(this));
return (
<div>
{itemsComponent}
</div>
);
}
}
class Item extends Component {
constructor(props) {
super(props);
}
render() {
// var status = (this.props.complete) ? 'complete' : 'pending';
return (
<div onClick={this.props.onClick.bind(null, this.props._id) }>
<label ><input type="checkbox" />{this.props.value}</label>
</div>
);
}
}
|
import { default as React, Component } from 'react'
import { render } from 'react-dom'
export class List extends Component {
constructor(props) {
super(props);
}
render() {
let items = this.props.items;
var itemsComponent = []
Object.keys(items).forEach(function (key) {
itemsComponent.push(<Item key={key} value={items[key]} _id={key} onClick={this.props.onClick} />);
}.bind(this));
return (
<div>
{itemsComponent}
</div>
);
}
}
class Item extends Component {
constructor(props) {
super(props);
}
render() {
// var status = (this.props.complete) ? 'complete' : 'pending';
return (
<div onClick={this.props.onClick.bind(null, this.props._id) }>
<input type="checkbox" />
<label >{this.props.value}</label>
</div>
);
}
}
|
Make autopagination functions work for listLineItems and listUpcomingLineItems
|
'use strict';
const StripeResource = require('../StripeResource');
const stripeMethod = StripeResource.method;
module.exports = StripeResource.extend({
path: 'invoices',
includeBasic: ['create', 'del', 'list', 'retrieve', 'update'],
finalizeInvoice: stripeMethod({
method: 'POST',
path: '{id}/finalize',
}),
listLineItems: stripeMethod({
method: 'GET',
path: '{id}/lines',
methodType: 'list',
}),
listUpcomingLineItems: stripeMethod({
method: 'GET',
path: 'upcoming/lines',
methodType: 'list',
}),
markUncollectible: stripeMethod({
method: 'POST',
path: '{id}/mark_uncollectible',
}),
pay: stripeMethod({
method: 'POST',
path: '{id}/pay',
}),
retrieveUpcoming: stripeMethod({
method: 'GET',
path: 'upcoming',
}),
sendInvoice: stripeMethod({
method: 'POST',
path: '{id}/send',
}),
voidInvoice: stripeMethod({
method: 'POST',
path: '{id}/void',
}),
});
|
'use strict';
const StripeResource = require('../StripeResource');
const stripeMethod = StripeResource.method;
module.exports = StripeResource.extend({
path: 'invoices',
includeBasic: ['create', 'del', 'list', 'retrieve', 'update'],
finalizeInvoice: stripeMethod({
method: 'POST',
path: '{id}/finalize',
}),
listLineItems: stripeMethod({
method: 'GET',
path: '{id}/lines',
}),
listUpcomingLineItems: stripeMethod({
method: 'GET',
path: 'upcoming/lines',
}),
markUncollectible: stripeMethod({
method: 'POST',
path: '{id}/mark_uncollectible',
}),
pay: stripeMethod({
method: 'POST',
path: '{id}/pay',
}),
retrieveUpcoming: stripeMethod({
method: 'GET',
path: 'upcoming',
}),
sendInvoice: stripeMethod({
method: 'POST',
path: '{id}/send',
}),
voidInvoice: stripeMethod({
method: 'POST',
path: '{id}/void',
}),
});
|
Remove index on field that no longer exists
[skip ci]
|
# Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCENDING),
])
db['node'].create_index([
('is_deleted', ASCENDING),
('is_collection', ASCENDING),
('is_public', ASCENDING),
('institution_id', ASCENDING),
('is_registration', ASCENDING),
('contributors', ASCENDING),
])
db['node'].create_index([
('tags', ASCENDING),
('is_public', ASCENDING),
('is_deleted', ASCENDING),
('institution_id', ASCENDING),
])
|
# Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['nodelog'].create_index([
('__backrefs.logged.node.logs', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCENDING),
])
db['node'].create_index([
('is_deleted', ASCENDING),
('is_collection', ASCENDING),
('is_public', ASCENDING),
('institution_id', ASCENDING),
('is_registration', ASCENDING),
('contributors', ASCENDING),
])
db['node'].create_index([
('tags', ASCENDING),
('is_public', ASCENDING),
('is_deleted', ASCENDING),
('institution_id', ASCENDING),
])
|
Make turbinia-psq the default pubsub queue name
|
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dummy Turbinia config file."""
# Turbinia Config
# Valid values are 'PSQ' or 'Celery'
TASK_MANAGER = u'PSQ'
# Time between heartbeats in seconds
WORKER_HEARTBEAT = 600
# Timeout between heartbeats for Workers to be considered inactive
WORKER_TIMEOUT = 3600
# GCE configuration
PROJECT = None
ZONE = None
INSTANCE = None
DEVICE_NAME = None
SCRATCH_PATH = None
BUCKET_NAME = None
PSQ_TOPIC = u'turbinia-psq'
# Topic Turbinia will listen on for new Artifact events
PUBSUB_TOPIC = None
# Redis configuration
REDIS_HOST = None
REDIS_PORT = None
# Timesketch configuration
TIMESKETCH_HOST = None
TIMESKETCH_USER = None
TIMESKETCH_PASSWORD = None
|
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dummy Turbinia config file."""
# Turbinia Config
# Valid values are 'PSQ' or 'Celery'
TASK_MANAGER = 'PSQ'
# Time between heartbeats in seconds
WORKER_HEARTBEAT = 600
# Timeout between heartbeats for Workers to be considered inactive
WORKER_TIMEOUT = 3600
# GCE configuration
PROJECT = None
ZONE = None
INSTANCE = None
DEVICE_NAME = None
SCRATCH_PATH = None
BUCKET_NAME = None
PSQ_TOPIC = None
# Topic Turbinia will listen on for new Artifact events
PUBSUB_TOPIC = None
# Redis configuration
REDIS_HOST = None
REDIS_PORT = None
# Timesketch configuration
TIMESKETCH_HOST = None
TIMESKETCH_USER = None
TIMESKETCH_PASSWORD = None
|
Jenkins: Test für den Email-Versand angepasst
|
package de.pentasys.SilverPen.util.test;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import de.pentasys.SilverPen.util.Email;
public class EmailTest {
private static String mailHost = "127.0.0.1";
private static Email email;
@BeforeClass
public static void setUp() throws Exception {
email = new Email(mailHost, 25, "root", "SilverPen2016");
}
@Test
public void testSendRegistrationConfirmationMail() {
try {
email.sendRegistrationConfirmationMail("JUnit-TestMail", "thomas.bankiel@pentasys.de");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package de.pentasys.SilverPen.util.test;
import javax.mail.MessagingException;
import org.junit.BeforeClass;
import org.junit.Test;
import de.pentasys.SilverPen.util.Email;
public class EmailTest {
private static String mailHost = "172.30.2.29";
private static Email email;
@BeforeClass
public static void setUp() throws Exception {
email = new Email(mailHost, 25, "root", "SilverPen2016");
}
@Test
public void testSendRegistrationConfirmationMail() {
try {
email.sendRegistrationConfirmationMail("test", "tobias.johannes.endres@pentasys.de");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Load spritesheet middleware for atlas support
|
import settings from './settings';
import { SCALE_MODES } from './const';
import { is_webgl_supported } from './utils/index';
import { loader_use_procs } from 'engine/registry';
import WebGLRenderer from './renderers/WebGLRenderer';
import texture_parser from 'engine/textures/texture_parser';
import spritesheet_parser from 'engine/textures/spritesheet_parser';
// Texture and spritesheet parsers are mandatory
loader_use_procs.push(texture_parser);
loader_use_procs.push(spritesheet_parser);
export default class VisualServer {
constructor() {
this.is_initialized = false;
this.renderer = null;
}
init(config) {
if (this.is_initialized) {
return;
}
this.is_initialized = true;
if (config.scale_mode === 'linear') {
settings.SCALE_MODE = SCALE_MODES.LINEAR;
} else {
settings.SCALE_MODE = SCALE_MODES.NEAREST;
}
if (!is_webgl_supported()) {
throw 'Voltar only support WebGL rendering!';
} else {
this.renderer = new WebGLRenderer(config);
}
}
render(viewport) {
this.renderer.render(viewport, undefined, true, undefined, true);
}
}
|
import settings from './settings';
import { SCALE_MODES } from './const';
import { is_webgl_supported } from './utils/index';
import { loader_use_procs } from 'engine/registry';
import WebGLRenderer from './renderers/WebGLRenderer';
import texture_parser from 'engine/textures/texture_parser';
// Texture parser is mandatory
loader_use_procs.push(texture_parser);
export default class VisualServer {
constructor() {
this.is_initialized = false;
this.renderer = null;
}
init(config) {
if (this.is_initialized) {
return;
}
this.is_initialized = true;
if (config.scale_mode === 'linear') {
settings.SCALE_MODE = SCALE_MODES.LINEAR;
} else {
settings.SCALE_MODE = SCALE_MODES.NEAREST;
}
if (!is_webgl_supported()) {
throw 'Voltar only support WebGL rendering!';
} else {
this.renderer = new WebGLRenderer(config);
}
}
render(viewport) {
this.renderer.render(viewport, undefined, true, undefined, true);
}
}
|
Update Sami theme as default.
|
<?php
use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;
$iterator = Finder::create()
->files()
->name('*.php')
->exclude('Resources')
->in($dir = 'src');
$versions = GitVersionCollection::create($dir)
->add('develop', 'develop branch')
->add('master', 'master branch')
->addFromTags('*');
return new Sami($iterator, array(
'theme' => 'default',
'versions' => $versions,
'title' => 'AuthBucket\OAuth2 API',
'build_dir' => __DIR__ . '/build/sami/%version%',
'cache_dir' => __DIR__ . '/build/cache/sami/%version%',
'include_parent_data' => false,
'default_opened_level' => 2,
));
|
<?php
use Sami\Sami;
use Sami\Version\GitVersionCollection;
use Symfony\Component\Finder\Finder;
$iterator = Finder::create()
->files()
->name('*.php')
->exclude('Resources')
->in($dir = 'src');
$versions = GitVersionCollection::create($dir)
->add('develop', 'develop branch')
->add('master', 'master branch')
->addFromTags('*');
return new Sami($iterator, array(
'theme' => 'enhanced',
'versions' => $versions,
'title' => 'AuthBucket\OAuth2 API',
'build_dir' => __DIR__ . '/build/sami/%version%',
'cache_dir' => __DIR__ . '/build/cache/sami/%version%',
'include_parent_data' => false,
'default_opened_level' => 2,
));
|
Fix PeriodicTask interval sleep calculation
|
from ..vtask import VTask
import time
from ..sparts import option
from threading import Event
class PeriodicTask(VTask):
INTERVAL = None
interval = option('interval', type=float, metavar='SECONDS',
default=lambda cls: cls.INTERVAL,
help='How often this task should run [%(default)s] (s)')
def initTask(self):
super(PeriodicTask, self).initTask()
assert self.getTaskOption('interval') is not None
self.stop_event = Event()
def stop(self):
self.stop_event.set()
super(PeriodicTask, self).stop()
def _runloop(self):
while not self.service._stop:
t0 = time.time()
self.execute()
to_sleep = (t0 + self.interval) - time.time()
if to_sleep > 0:
if self.stop_event.wait(to_sleep):
return
else:
#self.incrementCounter('n_slow_intervals')
pass
def execute(self, context=None):
self.logger.debug('execute')
|
from ..vtask import VTask
import time
from ..sparts import option
from threading import Event
class PeriodicTask(VTask):
INTERVAL = None
interval = option('interval', type=float, metavar='SECONDS',
default=lambda cls: cls.INTERVAL,
help='How often this task should run [%(default)s] (s)')
def initTask(self):
super(PeriodicTask, self).initTask()
assert self.getTaskOption('interval') is not None
self.stop_event = Event()
def stop(self):
self.stop_event.set()
super(PeriodicTask, self).stop()
def _runloop(self):
while not self.service._stop:
t0 = time.time()
self.execute()
to_sleep = time.time() - (t0 + self.interval)
if to_sleep > 0:
if self.stop_event.wait(to_sleep):
return
def execute(self, context=None):
self.logger.debug('execute')
|
Add a guard to better express the intention
Also added a name to the handler to avoid anonymous function in
stack traces.
|
import Em from 'ember';
import HrefTo from 'ember-href-to/href-to';
let hrefToClickHandler;
function closestLink(el) {
if (el.closest) {
return el.closest('a');
} else {
el = el.parentElement;
while (el && el.tagName !== 'A') {
el = el.parentElement;
}
return el;
}
}
export default {
name: 'ember-href-to',
initialize(applicationInstance) {
if (hrefToClickHandler !== undefined) {
document.body.removeEventListener('click', hrefToClickHandler);
}
hrefToClickHandler = function _hrefToClickHandler(e) {
let link = e.target.tagName === 'A' ? e.target : closestLink(e.target);
if (link) {
let hrefTo = new HrefTo(applicationInstance, e, link);
hrefTo.maybeHandle();
}
}
document.body.addEventListener('click', hrefToClickHandler);
}
};
|
import Em from 'ember';
import HrefTo from 'ember-href-to/href-to';
let hrefToClickHandler;
function closestLink(el) {
if (el.closest) {
return el.closest('a');
} else {
el = el.parentElement;
while (el && el.tagName !== 'A') {
el = el.parentElement;
}
return el;
}
}
export default {
name: 'ember-href-to',
initialize(applicationInstance) {
document.body.removeEventListener('click', hrefToClickHandler);
hrefToClickHandler = function(e) {
let link = e.target.tagName === 'A' ? e.target : closestLink(e.target);
if (link) {
let hrefTo = new HrefTo(applicationInstance, e, link);
hrefTo.maybeHandle();
}
}
document.body.addEventListener('click', hrefToClickHandler);
}
};
|
Update Jest test setup to add mock document.createRance method and refactor global exposed methods
|
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import renderer from 'react-test-renderer';
// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() });
// Make Enzyme functions available in all test files without importing
global.React = React;
global.shallow = shallow;
global.render = render;
global.mount = mount;
global.renderer = renderer;
if (global.document) {
// To resolve createRange not defined issue https://github.com/airbnb/enzyme/issues/1626#issuecomment-398588616
document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
}
|
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import TestRenderer from 'react-test-renderer';
import Configs from '../../site/public/theme/defaultTheme';
// React 16 Enzyme adapter
Enzyme.configure({ adapter: new Adapter() });
// Make Enzyme functions available in all test files without importing
global.React = React;
global.shallow = shallow;
global.render = render;
global.mount = mount;
global.testRenderer = TestRenderer;
|
Add a login svc and url
|
/**
* Created by kelvin on 3/12/2014.
*/
(function () {
angular.module('fc.login').config([
'$stateProvider',
'$urlRouterProvider',
routeConfig
]).config([
"authSvcProvider",
svcConfig
]);
function routeConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.state('login', {
url: '/?returnUrl',
views: {
'': {
templateUrl: 'login/login.tpl.html'
},
'top-bar': {
templateUrl: 'common/header.tpl.html'
}
}
});
}
function svcConfig(loginSvcProvider){
loginSvcProvider.loginUrl = "api/login";
};
})();
|
/**
* Created by Caleb on 9/25/2014.
*/
(function () {
angular.module('fc.login').config([
'$stateProvider',
'$urlRouterProvider',
routeConfig
]);
function routeConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.state('login', {
url: '/?returnUrl',
views: {
'': {
templateUrl: 'login/login.tpl.html'
},
'top-bar': {
templateUrl: 'common/header.tpl.html'
}
}
});
}
})();
|
Set explicit caching when watching
|
var path = require('path');
var webpackConfig = require('../webpack.config.js');
var defaultResolve = webpackConfig.resolve;
function noddyClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
var buildResolve = noddyClone(defaultResolve);
buildResolve.modules.push('src/');
var testConfig = {
entry: './tests/runner.js',
output: {
path: path.join(__dirname, '../dist'),
filename: 'tests.js',
},
};
module.exports = {
options: webpackConfig,
build: {
resolve: buildResolve,
},
buildwatch: {
watch: true,
cache: true,
keepalive: true,
resolve: buildResolve,
},
test: {
entry: testConfig.entry,
output: testConfig.output,
resolve: buildResolve,
},
coverage: {
entry: testConfig.entry,
output: testConfig.output,
resolve: buildResolve,
module: {
rules: [
{
use: 'babel-istanbul-loader',
// babel options are in .babelrc
exclude: /(node_modules|bower_components|tests)/,
enforce: 'pre',
test: /\.js$/,
},
],
},
},
};
|
var path = require('path');
var webpackConfig = require('../webpack.config.js');
var defaultResolve = webpackConfig.resolve;
function noddyClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
var buildResolve = noddyClone(defaultResolve);
buildResolve.modules.push('src/');
var testConfig = {
entry: './tests/runner.js',
output: {
path: path.join(__dirname, '../dist'),
filename: 'tests.js',
},
};
module.exports = {
options: webpackConfig,
build: {
resolve: buildResolve,
},
buildwatch: {
watch: true,
keepalive: true,
resolve: buildResolve,
},
test: {
entry: testConfig.entry,
output: testConfig.output,
resolve: buildResolve,
},
coverage: {
entry: testConfig.entry,
output: testConfig.output,
resolve: buildResolve,
module: {
rules: [
{
use: 'babel-istanbul-loader',
// babel options are in .babelrc
exclude: /(node_modules|bower_components|tests)/,
enforce: 'pre',
test: /\.js$/,
},
],
},
},
};
|
Fix detecting class access of descriptor. Set name on attr, not env class!
|
import os
class env(object):
def __init__(self, default=None):
self.name = None
self.default = default
def __get__(self, obj, cls=None):
if not obj:
return self
return os.environ.get(self.name.upper(), self.default)
class MetaConfig(type):
'''Quickly tell the env attrs their names.'''
def __new__(mcs, name, bases, attrs):
for name, attr in attrs.items():
if isinstance(attr, env):
attr.name = name
return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs)
class Conf(dict):
'''
Handy wrapper and placeholder of config values.
'''
__metaclass__ = MetaConfig
def __getattr__(self, key):
return os.environ[key]
|
import os
class env(object):
def __init__(self, default=None):
self.name = None
self.default = default
def __get__(self, obj, cls=None):
if cls:
return os.environ.get(self.name.upper(), self.default)
class MetaConfig(type):
'''Quickly tell the env attrs their names.'''
def __new__(mcs, name, bases, attrs):
for name, attr in attrs.items():
if isinstance(attr, env):
env.name = name
return super(MetaConfig, mcs).__new__(mcs, name, bases, attrs)
class Conf(dict):
'''
Handy wrapper and placeholder of config values.
'''
__metaclass__ = MetaConfig
def __getattr__(self, key):
return os.environ[key]
|
Upgrade ParameterEscaper. Fix some issues by translate.
|
<?php
namespace Exercise\GoogleTranslateBundle;
class ParametersEscaper
{
/** @var \ArrayObject */
protected $parametersArray;
/** @var \ArrayIterator */
protected $iterator;
public function escapeParameters($string)
{
$this->parametersArray = new \ArrayObject();
return preg_replace_callback(
"|%[\S]*%|",
array($this, 'escapeParametersCallback'),
$string);
}
public function unEscapeParameters($string)
{
if (!$this->parametersArray) {
throw new \Exception('You try unescape string that not be escaped');
}
$this->iterator = $this->parametersArray->getIterator();
return preg_replace_callback(
"|NotTranslatedString|",
array($this, 'unEscapeParametersCallback'),
$string);
}
private function escapeParametersCallback($matches)
{
$this->parametersArray->append($matches['0']);
return 'NotTranslatedString';
}
private function unEscapeParametersCallback($matches)
{
$value = $this->iterator->current();
$this->iterator->next();
return $value;
}
}
|
<?php
namespace Exercise\GoogleTranslateBundle;
class ParametersEscaper
{
/** @var \ArrayObject */
protected $parametersArray;
/** @var \ArrayIterator */
protected $iterator;
public function escapeParameters($string)
{
$this->parametersArray = new \ArrayObject();
return preg_replace_callback(
"|%[\S]*%|",
array($this, 'escapeParametersCallback'),
$string);
}
public function unEscapeParameters($string)
{
if (!$this->parametersArray) {
throw new \Exception('You try unescape string that not be escaped');
}
$this->iterator = $this->parametersArray->getIterator();
return preg_replace_callback(
"|%[\S]*%|",
array($this, 'unEscapeParametersCallback'),
$string);
}
private function escapeParametersCallback($matches)
{
$this->parametersArray->append($matches['0']);
return '%%%%';
}
private function unEscapeParametersCallback($matches)
{
$value = $this->iterator->current();
$this->iterator->next();
return $value;
}
}
|
Fix integration test for 'component:checkbox-for'
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('checkbox-for', 'Integration | Component | checkbox for', {
integration: true
});
test('it renders', function(assert) {
this.render(hbs`{{checkbox-for}}`);
assert.ok(this.$("input[type='checkbox']").length,
'renders a checkbox input');
});
test('works', function(assert) {
this.set("something", Ember.Object.create());
this.render(hbs`{{checkbox-for data=something field="foo"}}`);
this.$("label").click();
this.$("input").trigger("change");
assert.ok(this.get("something.foo"));
this.$("label").click();
this.$("input").trigger("change");
assert.notOk(this.get("something.foo"));
});
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('checkbox-for', 'Integration | Component | checkbox for', {
integration: true
});
test('it renders', function(assert) {
this.render(hbs`{{checkbox-for}}`);
assert.ok(this.$("input[type='checkbox']").length,
'renders a checkbox input');
});
test('works', function(assert) {
this.set("something", Ember.Object.create());
this.render(hbs`{{checkbox-for data=something field="foo"}}`);
this.$("label").click();
this.$("input").trigger("input");
assert.ok(this.get("something.foo"));
this.$("input").click();
this.$("input").trigger("input");
assert.notOk(this.get("something.foo"));
});
|
Fix module packaging thanks to landscape.io hint
|
# -*- encoding: utf-8 -*-
#
# In here you will find all the handlers that are tasked with handling the
# requests specified in the API.
#
# From these handlers we will be instantiating models objects that will take care
# of our business logic and the generation of the output to be sent to GLClient.
#
# In here we are also tasked with doing the validation of the user supplied
# input. This must be done before instantiating any models object.
# Validation of input may be done with the functions inside of
# globaleaks.rest.
#
# See base.BaseHandler for details on the handlers.
__all__ = ['admin',
'base',
'files',
'node',
'receiver',
'rtip',
'submission',
'wbtip']
|
# -*- encoding: utf-8 -*-
#
# In here you will find all the handlers that are tasked with handling the
# requests specified in the API.
#
# From these handlers we will be instantiating models objects that will take care
# of our business logic and the generation of the output to be sent to GLClient.
#
# In here we are also tasked with doing the validation of the user supplied
# input. This must be done before instantiating any models object.
# Validation of input may be done with the functions inside of
# globaleaks.rest.
#
# See base.BaseHandler for details on the handlers.
__all__ = ['admin',
'base',
'css',
'files',
'node',
'receiver',
'rtip',
'submission',
'wbtip']
|
Set only one view for all request which always return index.html
|
/**
* Module dependencies
*/
var express = require('express'),
http = require('http'),
path = require('path');
var app = module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3000);
app.locals({rootUrl: process.env.ROOTURL || '/'});
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
};
/**
* Routes
* serve everything to mod0 index
*/
app.get('*', function(req,res) {
res.sendfile('public/index.html');
});
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
|
/**
* Module dependencies
*/
var express = require('express'),
http = require('http'),
path = require('path');
var app = module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.locals({rootUrl: process.env.ROOTURL || '/'});
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
};
/**
* Routes
* serve view partial and edirect everything to mod0 index
*/
app.get('/partials/:name', function (req, res) {
var name = req.params.name;
res.render('partials/' + name);
});
app.get('/', function(req,res) {
res.redirect(app.locals.rootUrl+'mod0');
});
app.get('*', function(req,res) {
res.render('index');
});
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
|
Fix decimal limit of total to 2
Decimal limit is fixed to 2 as earlier at some values the decimal limit were crossing this limit
|
function update_price($this){
var id = $this.data('id');
// Calculate price for row
var value = $this.val();
var price = $('#price_' + id).text();
$('#total_row_' + id).text((value * price).toFixed(2));
// Calculate total price
var total = 0;
$('.total_row').each(function( index ) {
total += parseFloat($(this).text());
});
$('#total_price').text(total.toFixed(2));
}
$( document ).ready(function() {
$('.quantity').each(function() {
update_price($(this));
});
$('.quantity').change(function() {
update_price($(this));
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
});
|
function update_price($this){
var id = $this.data('id');
// Calculate price for row
var value = $this.val();
var price = $('#price_' + id).text();
$('#total_row_' + id).text((value * price).toFixed(2));
// Calculate total price
var total = 0;
$('.total_row').each(function( index ) {
total += parseFloat($(this).text());
});
$('#total_price').text(total);
}
$( document ).ready(function() {
$('.quantity').each(function() {
update_price($(this));
});
$('.quantity').change(function() {
update_price($(this));
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
});
|
Change shebang to /usr/bin/env for better venv support
|
#!/usr/bin/env python3
"""Setup.py for dirbrowser."""
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="dirbrowser",
version="1.0b1",
description="Command line based directory browser",
long_description=long_description,
url="https://github.com/campenr/dirbrowser",
author="Richard Campen",
author_email="richard@campen.co",
license="BSD License",
# TODO add more classifiers (e.g. platform)
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: User Interfaces",
"License :: OSI Approved :: BSD License",
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords="directory browser interface",
packages=find_packages(),
include_package_data=True
# TODO add entry into scripts folder
)
|
#!/usr/bin/python3
"""Setup.py for dirbrowser."""
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="dirbrowser",
version="1.0b1",
description="Command line based directory browser",
long_description=long_description,
url="https://github.com/campenr/dirbrowser",
author="Richard Campen",
author_email="richard@campen.co",
license="BSD License",
# TODO add more classifiers (e.g. platform)
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development :: User Interfaces",
"License :: OSI Approved :: BSD License",
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords="directory browser interface",
packages=find_packages(),
include_package_data=True
# TODO add entry into scripts folder
)
|
Support loading env file from custom file path
|
// Copyright 2014 GoIncremental Limited. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import "github.com/joho/godotenv"
type Environment interface {
Load(filenames ...string) error
}
type environment struct{}
func (e *environment) Load(s ...string) (err error) {
err = godotenv.Load(s...)
return
}
func newEnvironment() Environment {
return &environment{}
}
func LoadEnv(filenames ...string) error {
env := newEnvironment()
return env.Load(filenames...)
}
|
// Copyright 2014 GoIncremental Limited. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import "github.com/joho/godotenv"
type Environment interface {
Load(filenames ...string) error
}
type environment struct{}
func (e *environment) Load(s ...string) (err error) {
err = godotenv.Load(s...)
return
}
func newEnvironment() Environment {
return &environment{}
}
func LoadEnv() error {
env := newEnvironment()
return env.Load()
}
|
Revert use rememberToken() because not possible to chain the return value at the moment.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class OrchestraAuthAddRememberTokenToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('remember_token', 100)->nullable()->after('status');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('remember_token');
});
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class OrchestraAuthAddRememberTokenToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->rememberToken()->after('status');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('remember_token');
});
}
}
|
Fix reticle render order and depthTest
|
(function(){
/**
* Reticle 3D Sprite
* @param {THREE.Color} [color=0xfffff] - Color of the reticle sprite
* @param {string} [url=PANOLENS.DataImage.Reticle] - Image asset url
*/
PANOLENS.Reticle = function ( color, url ) {
var map, material;
color = color || 0xffffff;
url = url || PANOLENS.DataImage.Reticle;
map = PANOLENS.Utils.TextureLoader.load( url );
material = new THREE.SpriteMaterial( { map: map, color: color, depthTest: false } );
THREE.Sprite.call( this, material );
this.visible = false;
this.renderOrder = 10;
}
PANOLENS.Reticle.prototype = Object.create( THREE.Sprite.prototype );
PANOLENS.Reticle.prototype.constructor = PANOLENS.Reticle;
PANOLENS.Reticle.prototype.show = function () {
this.visible = true;
};
PANOLENS.Reticle.prototype.hide = function () {
this.visible = false;
};
})();
|
(function(){
/**
* Reticle 3D Sprite
* @param {THREE.Color} [color=0xfffff] - Color of the reticle sprite
* @param {string} [url=PANOLENS.DataImage.Reticle] - Image asset url
*/
PANOLENS.Reticle = function ( color, url ) {
var map, material;
color = color || 0xffffff;
url = url || PANOLENS.DataImage.Reticle;
map = PANOLENS.Utils.TextureLoader.load( url );
material = new THREE.SpriteMaterial( { map: map, color: color } );
THREE.Sprite.call( this, material );
this.visible = false;
}
PANOLENS.Reticle.prototype = Object.create( THREE.Sprite.prototype );
PANOLENS.Reticle.prototype.constructor = PANOLENS.Reticle;
PANOLENS.Reticle.prototype.show = function () {
this.visible = true;
};
PANOLENS.Reticle.prototype.hide = function () {
this.visible = false;
};
})();
|
Add Mac OS X stub for rdpLaunchNative.
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Douglas Thrift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
func rdpLaunchNative(instance *Instance, private bool, index int, arguments []string, prompt bool, username string) error {
return nil
}
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Douglas Thrift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
|
Fix issue - load README.md, not .rst
|
from codecs import open as codecs_open
from setuptools import setup, find_packages
# Get the long description from the relevant file
with codecs_open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(name='borica',
version='0.0.1',
description=u"Python integration for Borica",
long_description=long_description,
classifiers=[],
keywords='',
author=u"Jordan Jambazov",
author_email='jordan.jambazov@era.io',
url='https://github.com/IOEra/borica',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'click', 'pycrypto',
],
extras_require={
'test': ['pytest'],
},
entry_points="""
[console_scripts]
borica=borica.scripts.cli:cli
"""
)
|
from codecs import open as codecs_open
from setuptools import setup, find_packages
# Get the long description from the relevant file
with codecs_open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(name='borica',
version='0.0.1',
description=u"Python integration for Borica",
long_description=long_description,
classifiers=[],
keywords='',
author=u"Jordan Jambazov",
author_email='jordan.jambazov@era.io',
url='https://github.com/IOEra/borica',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'click', 'pycrypto',
],
extras_require={
'test': ['pytest'],
},
entry_points="""
[console_scripts]
borica=borica.scripts.cli:cli
"""
)
|
Correct comment about codepoints in Dashycode unit tests
|
'use strict';
const assert = require('assert');
const Dashycode = require('./../../.lib-dist/dashycode');
describe('Dashycode', function () {
// Technically we should be testing for values up to 0x10FFFF, but since
// node.js uses UTF-16, codepoints higher than 0xFFFF would be represented
// as surrogate pairs, making it pointless to test them since we've already
// tested the surrogate codepoints.
const codepoints = Array.from({length: 0x10000}, (v, k) => k);
const encoded = new Map();
const encode = (codepoint) => {
const character = String.fromCodePoint(codepoint);
const dashycode = Dashycode.encode(character);
assert.strictEqual(encoded.has(dashycode), false);
encoded.set(dashycode, character);
};
const decode = (dashycode) => {
const character = Dashycode.decode(dashycode);
assert.strictEqual(encoded.get(dashycode), character);
};
it('should encode all codepoints uniquely', function () {
return codepoints.reduce((p, codepoint) => (
p.then(v => encode(codepoint))
), Promise.resolve());
});
it('should decode all codepoints accurately', function () {
return [...encoded.keys()].reduce((p, dashycode) => (
p.then(v => decode(dashycode))
), Promise.resolve());
});
after(function () {
encoded.clear();
});
});
|
'use strict';
const assert = require('assert');
const Dashycode = require('./../../.lib-dist/dashycode');
describe('Dashycode', function () {
// Technically we should be testing for values up to 0x10FFFF, but we will
// never see any above 0xFFFF because of how SockJS works.
const codepoints = Array.from({length: 0x10000}, (v, k) => k);
const encoded = new Map();
const encode = (codepoint) => {
const character = String.fromCodePoint(codepoint);
const dashycode = Dashycode.encode(character);
assert.strictEqual(encoded.has(dashycode), false);
encoded.set(dashycode, character);
};
const decode = (dashycode) => {
const character = Dashycode.decode(dashycode);
assert.strictEqual(encoded.get(dashycode), character);
};
it('should encode all codepoints uniquely', function () {
return codepoints.reduce((p, codepoint) => (
p.then(v => encode(codepoint))
), Promise.resolve());
});
it('should decode all codepoints accurately', function () {
return [...encoded.keys()].reduce((p, dashycode) => (
p.then(v => decode(dashycode))
), Promise.resolve());
});
after(function () {
encoded.clear();
});
});
|
Add auto-reading from Hacker News
Every hour, read the best ~20 posts from the past 24 hours from Hacker News.
|
//var queue = new PowerQueue();
var hn = Meteor.require('hacker-news-api');
var readHn = function () {
"use strict";
console.log('Reading last 24 hours of Hacker News');
var now = Date.now() / 1000;
var query = 'search?tags=story&numericFilters=created_at_i>' +
(now - 86400) + ',created_at_i<' +
now;
hn.call(query, Meteor.bindEnvironment(
function (error, data) {
if (error) {
throw error;
}
_(data.hits).forEach(function (item) {
/*jshint camelcase: false */
var obj = {
oldId: parseInt(item.objectID, 10),
oldPoints: parseInt(item.points, 10),
createdAt: new Date(item.created_at),
site: 'hn',
author: item.author,
title: item.title,
url: item.url,
comments: parseInt(item.num_comments, 10),
};
Posts.upsert({
oldId: obj.oldId
},{ $set: obj });
});
}, function (e) {
throw e;
})
);
}
// read last 24 hours of hn
readHn();
// reread hn every hour
Meteor.setInterval(readHn, 3600 * 1000)
|
//var queue = new PowerQueue();
var hn = Meteor.require('hacker-news-api');
Meteor.methods({
"readHn": function () {
"use strict";
hn.getStories(Meteor.bindEnvironment(
function (error, data) {
if (error) {
throw error;
}
_(data.hits).forEach(function (item) {
/*jshint camelcase: false */
var obj = {
oldId: parseInt(item.objectID, 10),
oldPoints: parseInt(item.points, 10),
createdAt: new Date(item.created_at),
site: 'hn',
author: item.author,
title: item.title,
url: item.url,
comments: parseInt(item.num_comments, 10),
};
Posts.upsert({
oldId: obj.oldId
},{ $set: obj });
});
}, function (e) {
throw e;
})
);
}
});
|
Update to use env port
|
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var config = require('./webpack.config');
var port = process.env.PORT || 3000;
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(data) {
io.emit('chat message', data);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
server.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
}
});
|
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var config = require('./webpack.config');
var port = 3000;
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(data) {
io.emit('chat message', data);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
server.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info('==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
}
});
|
Set error message at the bottom, if input field is filled.
|
/**
* Created by elisahilprecht on 09/04/15.
*/
(function(){
var clickOnErrorMessage = function(e) {
e.toElement.setAttribute('class','help-inline display-none');
document.getElementById(e.toElement.id.replace('ErrorText','')).focus();
};
var clickOnInputField = function(e){
document.getElementById(e.toElement.id+'ErrorText').setAttribute('class','help-inline display-none');
};
var helpInlines = document.getElementsByClassName('help-inline');
for(var i=0; i<helpInlines.length; i++){
var ele = helpInlines[i];
if(ele.getAttribute('class')==='help-inline'){
ele.onclick = clickOnErrorMessage;
var inputId = ele.id.replace('ErrorText', '');
var inputValue = document.getElementById(inputId).value;
if(inputValue!==undefined && inputValue!==''){
ele.setAttribute('class', 'help-inline help-inline__bottom' )
}
}
}
var inputFields = document.getElementsByTagName('input');
for(var j=0; j<inputFields.length; j++){
ele.onclick = clickOnInputField;
}
})();
|
/**
* Created by elisahilprecht on 09/04/15.
*/
(function(){
var clickOnErrorMessage = function(e) {
e.toElement.setAttribute('class','help-inline display-none');
document.getElementById(e.toElement.id.replace('ErrorText','')).focus();
};
var clickOnInputField = function(e){
document.getElementById(e.toElement.id+'ErrorText').setAttribute('class','help-inline display-none');
};
var helpInlines = document.getElementsByClassName('help-inline');
for(var i=0; i<helpInlines.length; i++){
var ele = helpInlines[i];
if(ele.getAttribute('class')==='help-inline'){
ele.onclick = clickOnErrorMessage;
}
}
var inputFields = document.getElementsByTagName('input');
for(var j=0; j<inputFields.length; j++){
ele.onclick = clickOnInputField;
}
})();
|
Use new dev server instead of staging, because we don't know the staging version number any more.
|
'use strict';
define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() {
/* Services */
angular.module('scooter.services', [])
.constant('Repo', {
owner: "ucam-cl-dtg",
name: "rutherford-content"
})
.constant('ApiServer', "https://dev.isaacphysics.org/api/docker/api")
.service('LoginChecker', require("app/services/LoginChecker"))
.factory('FileLoader', require("app/services/FileLoader"))
.factory('FigureUploader', require("app/services/FigureUploader"))
.service('SnippetLoader', require("app/services/SnippetLoader"))
.factory('TagLoader', require("app/services/TagLoader"))
.factory('IdLoader', require("app/services/IdLoader"))
});
|
'use strict';
define(["angular", "app/services/LoginChecker", "app/services/FileLoader", "app/services/FigureUploader", "app/services/SnippetLoader", "app/services/TagLoader", "app/services/IdLoader"], function() {
/* Services */
angular.module('scooter.services', [])
.constant('Repo', {
owner: "ucam-cl-dtg",
name: "rutherford-content"
})
.constant('ApiServer', "https://staging.isaacphysics.org/api")
.service('LoginChecker', require("app/services/LoginChecker"))
.factory('FileLoader', require("app/services/FileLoader"))
.factory('FigureUploader', require("app/services/FigureUploader"))
.service('SnippetLoader', require("app/services/SnippetLoader"))
.factory('TagLoader', require("app/services/TagLoader"))
.factory('IdLoader', require("app/services/IdLoader"))
});
|
Generalize adding a data source
Instead of using data source specific methods for DataManager, use
just one: add_datasource(). The type of data source is defined by
the keyword argument 'type'.
|
import logging
from collections import OrderedDict
from egpackager.datasources import GspreadDataSource
class DataManager(object):
def __init__(self, debug=False):
# Set up logging
if debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
self.logger.debug("Initializing new registry manager")
self._data = OrderedDict()
def add_datasource(self, *args, **kwargs):
if 'type' not in kwargs:
raise TypeError("Missing require keyword argument: 'type")
if kwargs['type'] == 'gspread':
# Remove keyword argument 'type' as it us not needed anymore
del kwargs['type']
self.logger.debug('Adding Google Sheets data source')
self._data[kwargs['uri']] = GspreadDataSource(*args, **kwargs)
elif kwargs['type'] == 'raster':
pass
@property
def data(self):
return self._data
|
import logging
from collections import OrderedDict
from egpackager.datasources import GspreadDataSource
class DataManager(object):
def __init__(self, debug=False):
# Set up logging
if debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
self.logger.debug("Initializing new registry manager")
self._data = OrderedDict()
def add_gpsread_datasource(self, *args, **kwargs):
self.logger.debug('Adding Google Sheets data source')
self._data[kwargs['uri']] = GspreadDataSource(*args, **kwargs)
@property
def data(self):
return self._data
|
Add comment on header component
|
import React from 'react';
import styled from 'styled-components';
import {Link} from 'react-router';
import Wrapper from './Wrapper';
import Navigation from './Navigation';
// Main Header Component Styles
const MainHeader = styled.header`
padding: 1em 0;
border-bottom: 1px solid #C5C5C5;
overflow: auto;
zoom: 1;
`;
// Logo Link Component Styles
const Logo = styled(Link)`
float: left;
margin: 0;
color: #4A4A4A;
font-family: 'Volte Sans Rounded';
font-size: 20px;
font-weight: 600;
letter-spacing: -0.30px;
`;
// Header Component
const Header = () => {
return(
<MainHeader>
<Wrapper>
<Logo to="/">Austin Lauritsen</Logo>
<Navigation />
</Wrapper>
</MainHeader>
);
};
export default Header;
|
import React from 'react';
import styled from 'styled-components';
import {Link} from 'react-router';
import Wrapper from './Wrapper';
import Navigation from './Navigation';
// Main Header Component Styles
const MainHeader = styled.header`
padding: 1em 0;
border-bottom: 1px solid #C5C5C5;
overflow: auto;
zoom: 1;
`;
// Logo Link Component Styles
const Logo = styled(Link)`
float: left;
margin: 0;
color: #4A4A4A;
font-family: 'Volte Sans Rounded';
font-size: 20px;
font-weight: 600;
letter-spacing: -0.30px;
`;
const Header = () => {
return(
<MainHeader>
<Wrapper>
<Logo to="/">Austin Lauritsen</Logo>
<Navigation />
</Wrapper>
</MainHeader>
);
};
export default Header;
|
Raise DRF ValidationError to get APIException base
|
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework import serializers
from apps.approval.models import CommitteeApplication, CommitteePriority
class CommitteeSerializer(serializers.ModelSerializer):
group_name = serializers.SerializerMethodField(source='group')
class Meta(object):
model = CommitteePriority
fields = ('group', 'group_name', 'priority')
def get_group_name(self, instance):
return instance.group.name
class CommitteeApplicationSerializer(serializers.ModelSerializer):
committees = CommitteeSerializer(many=True, source='committeepriority_set')
class Meta(object):
model = CommitteeApplication
fields = ('name', 'email', 'application_text', 'prioritized', 'committees')
def create(self, validated_data):
committees = validated_data.pop('committeepriority_set')
application = CommitteeApplication(**validated_data)
try:
application.clean()
except DjangoValidationError as django_error:
raise serializers.ValidationError(django_error.message)
application.save()
for committee in committees:
CommitteePriority.objects.create(committee_application=application, **committee)
return CommitteeApplication.objects.get(pk=application.pk)
|
from rest_framework import serializers
from apps.approval.models import CommitteeApplication, CommitteePriority
class CommitteeSerializer(serializers.ModelSerializer):
group_name = serializers.SerializerMethodField(source='group')
class Meta(object):
model = CommitteePriority
fields = ('group', 'group_name', 'priority')
def get_group_name(self, instance):
return instance.group.name
class CommitteeApplicationSerializer(serializers.ModelSerializer):
committees = CommitteeSerializer(many=True, source='committeepriority_set')
class Meta(object):
model = CommitteeApplication
fields = ('name', 'email', 'application_text', 'prioritized', 'committees')
def create(self, validated_data):
committees = validated_data.pop('committeepriority_set')
application = CommitteeApplication.objects.create(**validated_data)
for committee in committees:
CommitteePriority.objects.create(committee_application=application, **committee)
return CommitteeApplication.objects.get(pk=application.pk)
|
Add name to the required inputs
|
/*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Validates a JSON object against a prepared set of types.
*/
var jsch = require('../extern/json-schema');
var log = require('./log');
var sys = require('sys');
var schemas = {
'service': {
type:"object",
properties:{
name: {tyoe: 'string'},
type: {type:"string"},
address: {type:"string"},
port: {type:'number'}
}
}
};
exports.validate = function(name, inst)
{
/* TODO: provide better message on errors ?*/
return jsch.validate(inst, schemas[name]);
};
|
/*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Validates a JSON object against a prepared set of types.
*/
var jsch = require('../extern/json-schema');
var log = require('./log');
var sys = require('sys');
var schemas = {
'service': {
type:"object",
properties:{
type: {type:"string"},
address: {type:"string"},
port: {type:'number'}
}
}
};
exports.validate = function(name, inst)
{
/* TODO: provide better message on errors ?*/
return jsch.validate(inst, schemas[name]);
};
|
Put door monitoring in a function, use channels.
|
package main
import (
"fmt"
"github.com/stianeikeland/go-rpio"
"net/http"
)
type DoorStatus int
const (
OPEN DoorStatus = iota
CLOSED
)
type StatusRequest struct {
resultChan chan DoorStatus
}
func main() {
statusChan := make(chan *StatusRequest)
go doorMonitor(statusChan)
http.Handle("/", &StatusPage{statusChan})
http.ListenAndServe(":80", nil)
}
func doorMonitor(queue chan *StatusRequest) {
// Open and map memory to access gpio, check for errors
if err := rpio.Open(); err != nil {
panic(err)
}
pin := rpio.Pin(23)
// Pull up pin
pin.PullUp()
for req := range queue {
doorStatus := pin.Read()
if doorStatus == 0 {
req.resultChan <- CLOSED
} else {
req.resultChan <- OPEN
}
}
// Unmap gpio memory when done
defer rpio.Close()
}
type StatusPage struct {
statusChan chan *StatusRequest
}
func (s *StatusPage) ServeHTTP(w http.ResponseWriter, r *http.Request) {
req := &StatusRequest{make(chan DoorStatus)}
s.statusChan <- req
doorStatus := <-req.resultChan
var doorString string
if doorStatus == CLOSED {
doorString = "closed"
} else {
doorString = "open"
}
fmt.Fprintln(w, "Garage door is:", doorString)
}
|
package main
import (
"fmt"
"github.com/stianeikeland/go-rpio"
"net/http"
"os"
)
var (
pin = rpio.Pin(23)
)
func main() {
// Open and map memory to access gpio, check for errors
if err := rpio.Open(); err != nil {
fmt.Println(err)
os.Exit(1)
}
// Pull up pin
pin.PullUp()
// Unmap gpio memory when done
defer rpio.Close()
http.HandleFunc("/", handler)
http.ListenAndServe(":80", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
doorStatus := pin.Read()
var doorString string
if doorStatus == 0 {
doorString = "closed"
} else {
doorString = "open"
}
fmt.Fprintln(w, "Garage door is:", doorString)
}
|
Fix escapeTag for non-string values
|
// https://docs.influxdata.com/influxdb/v1.5/write_protocols/line_protocol_tutorial/#special-characters-and-keywords
export function stringifyPoints(points) {
return points.map(_stringifyPoint).join("\n");
}
export function _stringifyPoint({ measurement, values, tags, timestamp }) {
const tagsString = Object.entries(tags)
.map(([key, value]) => {
return `${escapeTag(key)}=${escapeTag(value)}`;
})
.join(",");
const valuesString = Object.entries(values)
.map(([key, value]) => {
return `${escapeTag(key)}=${_formatValue(value)}`;
})
.join(",");
return `${measurement},${tagsString} ${valuesString} ${timestamp}`;
}
const _formatValue = value => {
if (typeof value === "string") {
return `"${value.replace('"', '\\"')}"`;
}
return value;
};
const escapeTag = value => {
if (typeof value === "string") {
return value
.replace(",", "\\,")
.replace(" ", "\\ ")
.replace("=", "\\=");
}
return value;
};
|
// https://docs.influxdata.com/influxdb/v1.5/write_protocols/line_protocol_tutorial/#special-characters-and-keywords
export function stringifyPoints(points) {
return points.map(_stringifyPoint).join("\n");
}
export function _stringifyPoint({ measurement, values, tags, timestamp }) {
const tagsString = Object.entries(tags)
.map(([key, value]) => {
return `${escapeTag(key)}=${escapeTag(value)}`;
})
.join(",");
const valuesString = Object.entries(values)
.map(([key, value]) => {
return `${escapeTag(key)}=${_formatValue(value)}`;
})
.join(",");
return `${measurement},${tagsString} ${valuesString} ${timestamp}`;
}
const _formatValue = value => {
if (typeof value === "string") {
return `"${value.replace('"', '\\"')}"`;
}
return value;
};
const escapeTag = value =>
value
.replace(",", "\\,")
.replace(" ", "\\ ")
.replace("=", "\\=");
|
Fix Account import in management command
|
from django.core.management.base import BaseCommand, CommandError
from backend.models.account import Account
from backend.tasks import get_all_contributions
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def add_arguments(self, parser):
parser.add_argument('--username', dest='username', default=None)
def handle(self, *args, **options):
if options.get('username'):
username = options.get('username')
try:
account = Account.objects.get(username=username)
except Account.DoesNotExist:
raise CommandError('Account "%s" does not exist' % username)
get_all_contributions(account)
self.stdout.write(
'Successfully fetched all user "%s" contributions' % username)
else:
get_all_contributions()
self.stdout.write('Successfully fetched all users contributions')
|
from django.core.management.base import BaseCommand, CommandError
from backend.models import Account
from backend.tasks import get_all_contributions
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def add_arguments(self, parser):
parser.add_argument('--username', dest='username', default=None)
def handle(self, *args, **options):
if options.get('username'):
username = options.get('username')
try:
account = Account.objects.get(username=username)
except Account.DoesNotExist:
raise CommandError('Account "%s" does not exist' % username)
get_all_contributions(account)
self.stdout.write(
'Successfully fetched all user "%s" contributions' % username)
else:
get_all_contributions()
self.stdout.write('Successfully fetched all users contributions')
|
Update payload to match
new parser for file relationship
|
import OsfSerializer from 'ember-osf/serializers/osf-serializer';
export default OsfSerializer.extend({
serialize(snapshot) {
// Normal OSF serializer strips out relationships. We need to add back primaryFile for this endpoint
let res = this._super(...arguments);
res.data.relationships = {
primary_file: {
data: {
id: snapshot.belongsTo('primaryFile', { id: true }),
type: 'file'
}
}
};
return res;
}
});
|
import OsfSerializer from 'ember-osf/serializers/osf-serializer';
export default OsfSerializer.extend({
serialize(snapshot) {
// Normal OSF serializer strips out relationships. We need to add back primaryFile for this endpoint
let res = this._super(...arguments);
res.data.relationships = {
// Not sure what the name of this key comes from, but it's required.
preprint_file: {
data: {
id: snapshot.belongsTo('primaryFile', { id: true }),
type: 'primary_file'
}
}
};
return res;
}
});
|
Comment out unused buildHeader code in taskItemView
|
jsio('from shared.javascript import Class')
jsio('import fan.ui.Button')
jsio('import fan.ui.RadioButtons')
jsio('import fan.tasks.views.View')
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
this._minWidth = 390
this._maxWidth = 740
this._headerHeight = 0
this.init = function(itemId) {
supr(this, 'init')
this._itemId = itemId
}
this.getTaskId = function() { return this._itemId }
// this._buildHeader = function() {
// new fan.ui.RadioButtons()
// .addButton({ text: 'Normal', payload: 'normal' })
// .addButton({ text: 'Crucial', payload: 'crucial' })
// .addButton({ text: 'Backlog', payload: 'backlog' })
// .addButton({ text: 'Done', payload: 'done' })
// .subscribe('Click', this, '_toggleTaskState')
// .appendTo(this._header)
// }
this._buildBody = function() {
gUtil.withTemplate('task-panel', bind(this, function(template) {
this._body.innerHTML = ''
this._body.appendChild(fin.applyTemplate(template, this._itemId))
}))
}
this._toggleTaskState = function(newState) {
console.log("TOGGLE STATE", newState)
}
})
|
jsio('from shared.javascript import Class')
jsio('import fan.ui.Button')
jsio('import fan.ui.RadioButtons')
jsio('import fan.tasks.views.View')
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
this._minWidth = 390
this._maxWidth = 740
this._headerHeight = 0
this.init = function(itemId) {
supr(this, 'init')
this._itemId = itemId
}
this.getTaskId = function() { return this._itemId }
this._buildHeader = function() {
new fan.ui.RadioButtons()
.addButton({ text: 'Normal', payload: 'normal' })
.addButton({ text: 'Crucial', payload: 'crucial' })
.addButton({ text: 'Backlog', payload: 'backlog' })
.addButton({ text: 'Done', payload: 'done' })
.subscribe('Click', this, '_toggleTaskState')
.appendTo(this._header)
}
this._buildBody = function() {
gUtil.withTemplate('task-panel', bind(this, function(template) {
this._body.innerHTML = ''
this._body.appendChild(fin.applyTemplate(template, this._itemId))
}))
}
this._toggleTaskState = function(newState) {
console.log("TOGGLE STATE", newState)
}
})
|
Embed Reference interface in NetworkReference
|
/*
Copyright (c) 2014 VMware, 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.
*/
package object
import (
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
Reference
EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}
|
/*
Copyright (c) 2014 VMware, 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.
*/
package object
import (
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
)
// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}
|
Use approrpiate transform implementation in canvas backend.
|
/**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.html;
import com.google.gwt.canvas.dom.client.Context2d;
import playn.core.AbstractLayer;
import playn.core.StockInternalTransform;
abstract class HtmlLayerCanvas extends AbstractLayer {
abstract void paint(Context2d ctx, float parentAlpha);
protected HtmlLayerCanvas() {
super(HtmlPlatform.hasTypedArraySupport ?
new HtmlInternalTransform() : new StockInternalTransform());
}
void transform(Context2d ctx) {
ctx.translate(originX, originY);
ctx.transform(transform.m00(), transform.m01(), transform.m10(),
transform.m11(), transform.tx() - originX, transform.ty() - originY);
ctx.translate(-originX, -originY);
}
}
|
/**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.html;
import com.google.gwt.canvas.dom.client.Context2d;
import playn.core.AbstractLayer;
abstract class HtmlLayerCanvas extends AbstractLayer {
abstract void paint(Context2d ctx, float parentAlpha);
protected HtmlLayerCanvas() {
super(new HtmlInternalTransform());
}
void transform(Context2d ctx) {
ctx.translate(originX, originY);
ctx.transform(transform.m00(), transform.m01(), transform.m10(),
transform.m11(), transform.tx() - originX, transform.ty() - originY);
ctx.translate(-originX, -originY);
}
}
|
Fix issue where ENABLED is not defined
|
import re
from django_seo_js import settings
from django_seo_js.backends import SelectedBackend
from django_seo_js.helpers import request_should_be_ignored
import logging
logger = logging.getLogger(__name__)
class UserAgentMiddleware(SelectedBackend):
def __init__(self, *args, **kwargs):
super(UserAgentMiddleware, self).__init__(*args, **kwargs)
regex_str = "|".join(settings.USER_AGENTS)
regex_str = ".*?(%s)" % regex_str
self.USER_AGENT_REGEX = re.compile(regex_str, re.IGNORECASE)
def process_request(self, request):
if not hasattr(request, 'ENABLED') or not request.ENABLED:
return
if request_should_be_ignored(request):
return
if "HTTP_USER_AGENT" not in request.META:
return
if not self.USER_AGENT_REGEX.match(request.META["HTTP_USER_AGENT"]):
return
url = request.build_absolute_uri()
try:
return self.backend.get_response_for_url(url)
except Exception as e:
logger.exception(e)
|
import re
from django_seo_js import settings
from django_seo_js.backends import SelectedBackend
from django_seo_js.helpers import request_should_be_ignored
import logging
logger = logging.getLogger(__name__)
class UserAgentMiddleware(SelectedBackend):
def __init__(self, *args, **kwargs):
super(UserAgentMiddleware, self).__init__(*args, **kwargs)
regex_str = "|".join(settings.USER_AGENTS)
regex_str = ".*?(%s)" % regex_str
self.USER_AGENT_REGEX = re.compile(regex_str, re.IGNORECASE)
def process_request(self, request):
if not request.ENABLED:
return
if request_should_be_ignored(request):
return
if "HTTP_USER_AGENT" not in request.META:
return
if not self.USER_AGENT_REGEX.match(request.META["HTTP_USER_AGENT"]):
return
url = request.build_absolute_uri()
try:
return self.backend.get_response_for_url(url)
except Exception as e:
logger.exception(e)
|
Change comments to reflect changes in PSR
|
<?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var ServerMiddlewareInterface
*/
protected $middleware;
protected $next;
/**
* MiddlewareDelegate constructor.
*
* @param ServerMiddlewareInterface $middleware Middleware of the frame
* @param Delegate $delegate The next frame
*
*/
public function __construct(ServerMiddlewareInterface $middleware, DelegateInterface $delegate = null)
{
$this->middleware = $middleware;
$this->next = $delegate;
}
/**
* @param Message\RequestInterface $request
*
* @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface
* @return Message\ResponseInterface
*/
public function process(Message\RequestInterface $request): Message\ResponseInterface
{
return $this->middleware->process($request, $this->next);
}
}
|
<?php
declare(strict_types=1);
namespace Onion\Framework\Http\Middleware;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message;
final class Delegate implements DelegateInterface
{
/**
* @var MiddlewareInterface|ServerMiddlewareInterface
*/
protected $middleware;
protected $next;
/**
* MiddlewareDelegate constructor.
*
* @param MiddlewareInterface|ServerMiddlewareInterface $middleware Middleware of the frame
* @param Delegate $delegate The next frame
*
*/
public function __construct(ServerMiddlewareInterface $middleware, DelegateInterface $delegate = null)
{
$this->middleware = $middleware;
$this->next = $delegate;
}
/**
* @param Message\RequestInterface $request
*
* @throws Exceptions\MiddlewareException if returned response is not instance of ResponseInterface
* @return Message\ResponseInterface
*/
public function process(Message\RequestInterface $request): Message\ResponseInterface
{
return $this->middleware->process($request, $this->next);
}
}
|
Fix event delegation on mouseover events
|
function recipeSearch(input) {
$.ajax({
url: "/recipes",
data: input,
}).done(function(recipeItemPartial) {
$(recipeItemPartial).appendTo(".main-searchbar");
});
}
var throttledSearch = _.throttle(recipeSearch, 300);
$( document ).ready(function() {
$(".form-control").keyup(function(event){
$(".drop-down").remove();
event.preventDefault();
var input = $(this).serialize();
if ($(this).val().length > 1) {
throttledSearch(input);
}
});
$(document).on("mouseover", "mark", function(){
// console.log("yes");
$("div").removeClass("hovered-term");
text = $(this).text();
termCard = $(".terms-box").find("#"+text);
termCard.addClass("hovered-term");
});
});
|
function recipeSearch(input) {
$.ajax({
url: "/recipes",
data: input,
}).done(function(recipeItemPartial) {
$(recipeItemPartial).appendTo(".main-searchbar");
});
}
var throttledSearch = _.throttle(recipeSearch, 300);
$( document ).ready(function() {
$(".form-control").keyup(function(event){
$(".drop-down").remove();
event.preventDefault();
var input = $(this).serialize();
if ($(this).val().length > 1) {
throttledSearch(input);
}
});
$("mark").on("mouseover", function(){
$("div").removeClass("hovered-term");
text = $(this).text();
termCard = $(".terms-box").find("#"+text);
termCard.addClass("hovered-term");
});
});
|
Switch debug mode from configuration
|
package com.bukkit.plugin.java.Component;
import java.util.logging.Logger;
import org.bukkit.plugin.Plugin;
/**
* Provide multi type log function
* @author Decker
*
*/
public class PluginLogger
{
Plugin ProvidePlugin;
Logger PluginLogger;
Boolean IsDebug;
private PluginLogger(Plugin plugin)
{
this.ProvidePlugin = plugin;
this.PluginLogger = this.ProvidePlugin.getLogger();
this.IsDebug=ConfigManager.GetConfig().getBoolean("DebugMode");
}
private static PluginLogger _Instance;
public static PluginLogger Init(Plugin plugin)
{
if(_Instance==null)
{
_Instance =new PluginLogger(plugin);
}
return _Instance;
}
public static void Info(String messege)
{
if(_Instance.IsDebug)
{
_Instance.PluginLogger.info(messege);
}
}
public static void Warning(String messege)
{
_Instance.PluginLogger.warning(messege);
}
public static void Warning(Exception exception)
{
_Instance.PluginLogger.warning(exception.toString());
}
}
|
package com.bukkit.plugin.java.Component;
import java.util.logging.Logger;
import org.bukkit.plugin.Plugin;
/**
* Provide multi type log function
* @author Decker
*
*/
public class PluginLogger
{
Plugin ProvidePlugin;
Logger PluginLogger;
private PluginLogger(Plugin plugin)
{
this.ProvidePlugin = plugin;
this.PluginLogger = this.ProvidePlugin.getLogger();
}
private static PluginLogger _Instance;
public static PluginLogger Init(Plugin plugin)
{
if(_Instance==null)
{
_Instance =new PluginLogger(plugin);
}
return _Instance;
}
public static void Info(String messege)
{
_Instance.PluginLogger.info(messege);
}
public static void Warning(String messege)
{
_Instance.PluginLogger.warning(messege);
}
public static void Warning(Exception exception)
{
_Instance.PluginLogger.warning(exception.toString());
}
}
|
Use tornado settings, webapp deprecated
|
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True
# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.tornado_settings = {
'headers': {
'X-Frame-Options': 'ALLOW FROM nature.com'
},
'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
'/srv/ipython/IPython/html/templates']
}
|
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True
# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
'headers': {
'X-Frame-Options': 'ALLOW FROM nature.com'
},
'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
'/srv/ipython/IPython/html/templates']
}
|
vtgate/buffer: Add matching for errno 1290 if no error message is present.
The error message can be omitted if -queryserver-config-terse-errors is enabled.
|
package buffer
import (
"strings"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/vt/vterrors"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)
// This function is in a separate file to make it easier to swap out an
// open-source implementation with any internal Google-only implementation.
func causedByFailover(err error) bool {
log.V(2).Infof("Checking error (type: %T) if it is caused by a failover. err: %v", err, err)
if vtErr, ok := err.(vterrors.VtError); ok {
if vtErr.VtErrorCode() == vtrpcpb.ErrorCode_QUERY_NOT_SERVED {
if strings.Contains(err.Error(), "retry: operation not allowed in state NOT_SERVING") ||
strings.Contains(err.Error(), "retry: operation not allowed in state SHUTTING_DOWN") ||
strings.Contains(err.Error(), "retry: The MariaDB server is running with the --read-only option so it cannot execute this statement (errno 1290) (sqlstate HY000)") ||
// Match 1290 if -queryserver-config-terse-errors explicitly hid the error message (which it does to avoid logging the original query including any PII).
strings.Contains(err.Error(), "retry: (errno 1290) (sqlstate HY000) during query:") {
return true
}
}
}
return false
}
|
package buffer
import (
"strings"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/vt/vterrors"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)
// This function is in a separate file to make it easier to swap out an
// open-source implementation with any internal Google-only implementation.
func causedByFailover(err error) bool {
log.V(2).Infof("Checking error (type: %T) if it is caused by a failover. err: %v", err, err)
if vtErr, ok := err.(vterrors.VtError); ok {
if vtErr.VtErrorCode() == vtrpcpb.ErrorCode_QUERY_NOT_SERVED {
if strings.Contains(err.Error(), "retry: operation not allowed in state NOT_SERVING") ||
strings.Contains(err.Error(), "retry: operation not allowed in state SHUTTING_DOWN") ||
strings.Contains(err.Error(), "retry: The MariaDB server is running with the --read-only option so it cannot execute this statement (errno 1290) (sqlstate HY000)") {
return true
}
}
}
return false
}
|
[tools] Format codepoints according to the Namelist spec.
|
#!/usr/bin/env python
# Copyright 2015, Google Inc.
# Author: Dave Crossland (dave@understandinglimited.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# namelist.py: A fontTools python script for generating namelist files
#
# Usage:
#
# $ namelist.py Font.ttf > NameList.nam
import sys
from fontTools.ttLib import TTFont
from fontTools.unicode import Unicode
def main(file_name):
excluded_chars = ["????", "SPACE", "NO-BREAK SPACE"]
font = TTFont(file_name)
for cmap in font["cmap"].tables:
char_list = sorted(cmap.cmap.items())
for item in char_list:
item_description = Unicode[item[0]]
if item_description not in excluded_chars:
print '0x{0:04X}'.format(item[0]), item_description
font.close()
if __name__ == '__main__':
main(sys.argv[1])
|
#!/usr/bin/env python
# Copyright 2015, Google Inc.
# Author: Dave Crossland (dave@understandinglimited.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# namelist.py: A fontTools python script for generating namelist files
#
# Usage:
#
# $ namelist.py Font.ttf > NameList.nam
import sys
from fontTools.ttLib import TTFont
from fontTools.unicode import Unicode
def main(file_name):
excluded_chars = ["????", "SPACE", "NO-BREAK SPACE"]
font = TTFont(file_name)
for cmap in font["cmap"].tables:
char_list = sorted(cmap.cmap.items())
for item in char_list:
item_description = Unicode[item[0]]
if item_description not in excluded_chars:
print hex(item[0]), item_description
font.close()
if __name__ == '__main__':
main(sys.argv[1])
|
Change xfail to skipIf. The exact condition is really difficult to get
right and doesn't add much signal.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@340574 91177308-0d34-0410-b5e6-96231b3b80d8
|
# coding=utf8
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.decorators import *
class TestUnicodeSymbols(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipIf(compiler="clang", compiler_version=['<', '7.0'])
def test_union_members(self):
self.build()
spec = lldb.SBModuleSpec()
spec.SetFileSpec(lldb.SBFileSpec(self.getBuildArtifact("a.out")))
module = lldb.SBModule(spec)
self.assertTrue(module.IsValid())
mytype = module.FindFirstType("foobár")
self.assertTrue(mytype.IsValid())
self.assertTrue(mytype.IsPointerType())
|
# coding=utf8
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.decorators import *
class TestUnicodeSymbols(TestBase):
mydir = TestBase.compute_mydir(__file__)
@expectedFailureAll(compiler="clang", compiler_version=['<', '7.0'])
def test_union_members(self):
self.build()
spec = lldb.SBModuleSpec()
spec.SetFileSpec(lldb.SBFileSpec(self.getBuildArtifact("a.out")))
module = lldb.SBModule(spec)
self.assertTrue(module.IsValid())
mytype = module.FindFirstType("foobár")
self.assertTrue(mytype.IsValid())
self.assertTrue(mytype.IsPointerType())
|
Fix display of full user name at least on current user's settings page
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@property
def full_name(self) -> Optional[str]:
names = [self.first_names, self.last_name]
return ' '.join(filter(None, names)) or None
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserID
screen_name: Optional[str]
suspended: bool
deleted: bool
locale: Optional[str]
avatar_url: Optional[str]
is_orga: bool
@dataclass(frozen=True)
class UserDetail:
first_names: Optional[str]
last_name: Optional[str]
date_of_birth: Optional[date]
country: Optional[str]
zip_code: Optional[str]
city: Optional[str]
street: Optional[str]
phone_number: Optional[str]
internal_comment: Optional[str]
extras: dict[str, Any]
@dataclass(frozen=True)
class UserWithDetail(User):
detail: UserDetail
|
Add babel polyfills as a direct dependency
|
/**
* Main application file of Fittable
* - Requires React.js to be loaded before loading this
*
* @author Marián Hlaváč
*/
// https://babeljs.io/docs/usage/polyfill/
require('babel/polyfill');
import React from 'react';
import Fittable from './components/Fittable.component';
import Counterpart from 'counterpart';
import Moment from 'moment';
import Momentcslocale from 'moment/locale/cs';
import LocaleCS from '../lang/cs.json';
import LocaleEN from '../lang/en.json';
function fittable ( containerElId, options )
{
// Register translations
Counterpart.registerTranslations( 'en', LocaleEN );
Counterpart.registerTranslations( 'cs', Object.assign( LocaleCS, {
counterpart: { pluralize: ( entry, count ) => entry[ (count === 0 && 'zero' in entry) ? 'zero' : (count === 1) ? 'one' : 'other' ] }
} ) );
// Set locale
Counterpart.setLocale( options.locale );
Moment.locale( options.locale );
// Create root fittable element
var element = React.createElement( Fittable, options );
var rendered = React.render( element, document.getElementById( containerElId ) );
// Return fittable instance
return rendered;
}
global.fittable = fittable;
export default fittable;
|
/**
* Main application file of Fittable
* - Requires React.js to be loaded before loading this
*
* @author Marián Hlaváč
*/
import React from 'react';
import Fittable from './components/Fittable.component';
import Counterpart from 'counterpart';
import Moment from 'moment';
import Momentcslocale from 'moment/locale/cs';
import LocaleCS from '../lang/cs.json';
import LocaleEN from '../lang/en.json';
function fittable ( containerElId, options )
{
// Register translations
Counterpart.registerTranslations( 'en', LocaleEN );
Counterpart.registerTranslations( 'cs', Object.assign( LocaleCS, {
counterpart: { pluralize: ( entry, count ) => entry[ (count === 0 && 'zero' in entry) ? 'zero' : (count === 1) ? 'one' : 'other' ] }
} ) );
// Set locale
Counterpart.setLocale( options.locale );
Moment.locale( options.locale );
// Create root fittable element
var element = React.createElement( Fittable, options );
var rendered = React.render( element, document.getElementById( containerElId ) );
// Return fittable instance
return rendered;
}
global.fittable = fittable;
export default fittable;
|
Include timestamp in audit logs
|
import cherrypy
import datetime
import logging
from girder import auditLogger
from girder.models.model_base import Model
from girder.api.rest import getCurrentUser
class Record(Model):
def initialize(self):
self.name = 'audit_log_record'
def validate(self, doc):
return doc
class AuditLogHandler(logging.Handler):
def handle(self, record):
user = getCurrentUser()
Record().save({
'type': record.msg,
'details': record.details,
'ip': cherrypy.request.remote.ip,
'userId': user and user['_id'],
'when': datetime.datetime.utcnow()
})
def load(info):
auditLogger.addHandler(AuditLogHandler())
|
import cherrypy
import logging
from girder import auditLogger
from girder.models.model_base import Model
from girder.api.rest import getCurrentUser
class Record(Model):
def initialize(self):
self.name = 'audit_log_record'
def validate(self, doc):
return doc
class AuditLogHandler(logging.Handler):
def handle(self, record):
user = getCurrentUser()
Record().save({
'type': record.msg,
'details': record.details,
'ip': cherrypy.request.remote.ip,
'userId': user and user['_id']
})
def load(info):
auditLogger.addHandler(AuditLogHandler())
|
Make test cover header/footer too.
|
/**
* Copyright 2008 Matthew Hillsdon
*
* 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 net.hillsdon.reviki.webtests;
import net.hillsdon.reviki.vc.PageReference;
import net.hillsdon.reviki.web.vcintegration.SpecialPagePopulatingPageStore;
public class TestMisc extends WebTestSupport {
public void testWikiRootRedirectsToFrontPage() throws Exception {
assertTrue(getWebPage("pages/test/").getTitleText().contains("Front Page"));
assertTrue(getWebPage("pages/test").getTitleText().contains("Front Page"));
}
public void testNoBackLinkToSelf() throws Exception {
assertTrue(getWikiPage("FrontPage")
.getByXPath("id('backlinks')//a[@href = 'FrontPage']").isEmpty());
}
public void testSidebarEtc() throws Exception {
for (PageReference page : SpecialPagePopulatingPageStore.COMPLIMENTARY_CONTENT_PAGES) {
final String expect = "T" + System.currentTimeMillis() + page.getPath().toLowerCase();
editWikiPage(page.getPath(), expect, "Some new content", null);
assertTrue(getWikiPage("FrontPage").asText().contains(expect));
}
}
}
|
/**
* Copyright 2008 Matthew Hillsdon
*
* 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 net.hillsdon.reviki.webtests;
public class TestMisc extends WebTestSupport {
public void testWikiRootRedirectsToFrontPage() throws Exception {
assertTrue(getWebPage("pages/test/").getTitleText().contains("Front Page"));
assertTrue(getWebPage("pages/test").getTitleText().contains("Front Page"));
}
public void testNoBackLinkToSelf() throws Exception {
assertTrue(getWikiPage("FrontPage")
.getByXPath("id('backlinks')//a[@href = 'FrontPage']").isEmpty());
}
public void testSidebar() throws Exception {
String expect = "T" + System.currentTimeMillis();
editWikiPage("ConfigSideBar", expect, "Some new content", null);
assertTrue(getWikiPage("FrontPage").asText().contains(expect));
}
}
|
Use Boolean type in conditional
|
/*
* Believe it or not, you can declare and use functions in EJS templates too.
*/
var ejs = require('../')
, read = require('fs').readFileSync
, join = require('path').join
, path = join(__dirname, '/functions.ejs')
, data = {
users: [
{ name: 'Tobi', age: 2, species: 'ferret' }
, { name: 'Loki', age: 2, species: 'ferret' }
, { name: 'Jane', age: 6, species: 'ferret' }
]
};
if (true) {
var ret = ejs.compile(read(path, 'utf8'), {filename: path})(data);
console.log(ret);
}
else {
// Alternatively, you can use the renderFile() function. They should produce
// the same result.
ejs.renderFile(path, data, function (err, html) {
if (err) {
throw err;
}
console.log(html);
});
}
|
/*
* Believe it or not, you can declare and use functions in EJS templates too.
*/
var ejs = require('../')
, read = require('fs').readFileSync
, join = require('path').join
, path = join(__dirname, '/functions.ejs')
, data = {
users: [
{ name: 'Tobi', age: 2, species: 'ferret' }
, { name: 'Loki', age: 2, species: 'ferret' }
, { name: 'Jane', age: 6, species: 'ferret' }
]
};
if (1) {
var ret = ejs.compile(read(path, 'utf8'), {filename: path})(data);
console.log(ret);
}
else {
// Alternatively, you can use the renderFile() function. They should produce
// the same result.
ejs.renderFile(path, data, function (err, html) {
if (err) {
throw err;
}
console.log(html);
});
}
|
Set angular as default in blueprint
|
// jshint node:true
// For details on each option run `ember help release`
module.exports = {
// ember style guide: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#commit-tagging
// angular style guide: https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit
// jquery style guide: https://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines
style: 'angular', // 'ember' 'jquery'
head: 'master',
base: '-last', // a branch or tag name, `-last` defaults to the version in package.json
hooks: {
/*
parser: function(commit) { return commit; }
filter: function(commit) { return true; },
groupSort: function(commits) { return { commits: commits }; },
format: function(commit) { return commit.title; },
*/
}
};
|
// jshint node:true
// For details on each option run `ember help release`
module.exports = {
// ember style guide: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#commit-tagging
// angular style guide: https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit
// jquery style guide: https://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines
style: 'ember', // 'angular' 'jquery'
head: 'master',
base: '-last', // a branch or tag name, `-last` defaults to the version in package.json
hooks: {
/*
parser: function(commit) { return commit; }
filter: function(commit) { return true; },
groupSort: function(commits) { return { commits: commits }; },
format: function(commit) { return commit.title; },
*/
}
};
|
Remove connected prooperty from client
|
/**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
let counter = 0
/**
* Represent connected client
* @type {Client}
*/
module.exports = class Client {
constructor(socket) {
this.socket = socket
this.name = 'anonymous'
this.id = counter++
this.groups = {}
}
/**
* Disconnect client from server
*/
disconnect() {
this.socket.destroy()
}
/**
* Check, if is user in specific group
* @param {string} name Name of group to check
* @returns {boolean} True if is user in group, false otherwise
*/
isInGroup(name) {
return this.groups.hasOwnProperty(name)
}
}
|
/**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
let counter = 0
/**
* Represent connected client
* @type {Client}
*/
module.exports = class Client {
constructor(socket) {
this.socket = socket
this.name = 'anonymous'
this.connected = true
this.id = counter++
this.groups = {}
}
/**
* Disconnect client from server
*/
disconnect() {
this.connected = false
this.socket.destroy()
}
/**
* Check, if is user in specific group
* @param {string} name Name of group to check
* @returns {boolean} True if is user in group, false otherwise
*/
isInGroup(name) {
return this.groups.hasOwnProperty(name)
}
}
|
[TwitchIO] Use f-string for define command
|
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['text']}")
else:
await ctx.send("Definition not found.")
|
from twitchio.ext import commands
@commands.cog()
class Words:
def __init__(self, bot):
self.bot = bot
@commands.command()
async def audiodefine(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/audio"
params = {"useCanonical": "false", "limit": 1, "api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(f"{data[0]['word'].capitalize()}: {data[0]['fileUrl']}")
else:
await ctx.send("Word or audio not found.")
@commands.command()
async def define(self, ctx, word):
url = f"http://api.wordnik.com:80/v4/word.json/{word}/definitions"
params = {"limit": 1, "includeRelated": "false", "useCanonical": "false", "includeTags": "false",
"api_key": self.bot.WORDNIK_API_KEY}
async with self.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.json()
if data:
await ctx.send(data[0]["word"].capitalize() + ": " + data[0]["text"])
else:
await ctx.send("Definition not found.")
|
Fix test for Laravel 7
|
<?php
namespace Code16\Sharp\Tests\Feature;
use Code16\Sharp\Tests\Feature\Api\BaseApiTest;
class AssetViewComposerTest extends BaseApiTest
{
/** @test */
public function we_can_define_assets_to_render_in_views()
{
$this->withoutExceptionHandling();
$this->buildTheWorld();
$this->app['config']->set(
'sharp.extensions.assets.head',
['/path/to/asset.css']
);
$this->get(route('code16.sharp.login'))
->assertViewHas('injectedAssets')
->assertSee('<link rel="stylesheet" href="/path/to/asset.css">', false);
}
}
|
<?php
namespace Code16\Sharp\Tests\Feature;
use Code16\Sharp\Tests\Feature\Api\BaseApiTest;
class AssetViewComposerTest extends BaseApiTest
{
/** @test */
public function we_can_define_assets_to_render_in_views()
{
$this->withoutExceptionHandling();
$this->buildTheWorld();
$this->app['config']->set(
'sharp.extensions.assets.head',
['/path/to/asset.css']
);
$this->get(route('code16.sharp.login'))
->assertViewHas('injectedAssets')
->assertSee('<link rel="stylesheet" href="/path/to/asset.css">');
}
}
|
DBServer: Change BDB test to match naming scheme
|
#!/usr/bin/env python2
import unittest
from socket import *
from common import *
from testdc import *
from test_dbserver import DatabaseBaseTests
CONFIG = """\
messagedirector:
bind: 127.0.0.1:57123
general:
dc_files:
- %r
roles:
- type: database
control: 777
generate:
min: 1000000
max: 1001000
storage:
type: bdb
filename: main_database.db
""" % test_dc
class TestDatabaseServerBerkeley(unittest.TestCase, DatabaseBaseTests):
@classmethod
def setUpClass(cls):
cls.daemon = Daemon(CONFIG)
cls.daemon.start()
sock = socket(AF_INET, SOCK_STREAM)
sock.connect(('127.0.0.1', 57123))
cls.conn = MDConnection(sock)
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python2
import unittest
from socket import *
from common import *
from testdc import *
from test_dbserver import DatabaseBaseTests
CONFIG = """\
messagedirector:
bind: 127.0.0.1:57123
general:
dc_files:
- %r
roles:
- type: database
control: 777
generate:
min: 1000000
max: 1001000
storage:
type: bdb
filename: main_database.db
""" % test_dc
class TestDatabaseServerBDB(unittest.TestCase, DatabaseBaseTests):
@classmethod
def setUpClass(cls):
cls.daemon = Daemon(CONFIG)
cls.daemon.start()
sock = socket(AF_INET, SOCK_STREAM)
sock.connect(('127.0.0.1', 57123))
cls.conn = MDConnection(sock)
if __name__ == '__main__':
unittest.main()
|
Fix call to super for py2.7
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super(SensitiveDjangoClient, self).get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
from django.views.debug import SafeExceptionReporterFilter
from raven.contrib.django.client import DjangoClient
class SensitiveDjangoClient(DjangoClient):
"""
Hide sensitive request data from being logged by Sentry.
Borrowed from http://stackoverflow.com/a/23966581/240995
"""
def get_data_from_request(self, request):
request.POST = SafeExceptionReporterFilter().get_post_parameters(request)
result = super().get_data_from_request(request)
# override the request.data with POST data
# POST data contains no sensitive info in it
result['request']['data'] = request.POST
# remove the whole cookie as it contains DRF auth token and session id
if 'cookies' in result['request']:
del result['request']['cookies']
if 'Cookie' in result['request']['headers']:
del result['request']['headers']['Cookie']
return result
|
Make Transfer Consistent w/ Views
|
import * as http_data from "./http-data";
import * as urlModule from "url";
function transfer(request) {
// url - the resource URI to send a message to
// options.method - the method to use for transferring
// options.form - the Form API object representing the form data submission
// converted to a message body via encoding (see: options.enctype)
// options.enctype - the encoding to use to encode form into message body
// options.body - an already encoded message body
// if both body and form are present, form is ignored
if (!request) throw new Error("'request' param is required.");
var url = request.url;
var options = request.options;
if (!url) throw new Error("'request.url' param is required.");
var protocol = urlModule.parse(url).protocol;
if (!protocol) throw new Error("'request.url' param must have a protocol scheme.");
protocol = protocol.replace(":", "");
if (protocol in transfer.registrations === false) throw new Error("No transferrer registered for protocol: " + protocol);
var transferrer = transfer.registrations[protocol];
return transferrer(request);
}
transfer.registrations = {};
transfer.register = function registerTransferrer(protocol, transferrer) {
transfer.registrations[protocol] = transferrer;
};
transfer.register("http", http_data.transfer);
transfer.register("data", http_data.transfer);
export { transfer };
|
import * as http_data from "./http-data";
import * as urlModule from "url";
const transferrers = {};
function transfer(request) {
// url - the resource URI to send a message to
// options.method - the method to use for transferring
// options.form - the Form API object representing the form data submission
// converted to a message body via encoding (see: options.enctype)
// options.enctype - the encoding to use to encode form into message body
// options.body - an already encoded message body
// if both body and form are present, form is ignored
if (!request) throw new Error("'request' param is required.");
var url = request.url;
var options = request.options;
if (!url) throw new Error("'request.url' param is required.");
var protocol = urlModule.parse(url).protocol;
if (!protocol) throw new Error("'request.url' param must have a protocol scheme.");
protocol = protocol.replace(":", "");
if (protocol in transferrers === false) throw new Error("No transferrer registered for protocol: " + protocol);
var transferrer = transferrers[protocol];
return transferrer(request);
}
transfer.register = function registerTransferrer(scheme, transferrer) {
transferrers[scheme] = transferrer;
};
transfer.register("http", http_data.transfer);
transfer.register("data", http_data.transfer);
export { transfer };
|
Add log of total counts
|
console.log('hello')
const css = require('../style/app.scss');
import _ from 'lodash';
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
cardinality: 0,
counts: {}
};
}
counts(arr) {
return _.countBy(arr, (x) => x)
}
cardinality(str) {
return _.uniq(str.split('')).length;
}
textInput(e) {
const input = this.refs.input.value.replace(/\s+/g, '');
const cardinality = this.cardinality(input);
const counts = this.counts(input.split(''));
this.setState({input, cardinality, counts});
}
render() {
const counts = _.map(
this.state.counts, (v, k) => <li key={k}>{k}: {v}</li>
);
return (
<div>
<textarea ref="input" onKeyUp={this.textInput.bind(this)}/>
Unique: <span>{this.state.cardinality}</span>
<div>
Counts:
<ul>{counts}</ul>
</div>
</div>
)
}
}
// main
ReactDOM.render(<App/>, document.getElementById('app'));
|
console.log('hello')
const css = require('../style/app.scss');
import _ from 'lodash';
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
cardinality: 0
};
}
cardinality(str) {
return _.uniq(str.split('')).length;
}
textInput(e) {
var input = this.refs.input.value.replace(/\s+/g, '');
var cardinality = this.cardinality(input);
this.setState({input, cardinality});
}
render() {
return (
<div>
<textarea ref="input" onKeyUp={this.textInput.bind(this)}/>
Unique: <span>{this.state.cardinality}</span>
</div>
)
}
}
// main
ReactDOM.render(<App/>, document.getElementById('app'));
|
Replace apostrophe to proper HTML char
|
<h2>#Laravel IRC Chat</h2>
@if(Auth::check() or Session::has('userLazilyOptsOutOfAuthOnChat'))
<iframe src="https://kiwiirc.com/client/irc.freenode.net/?&nick={{ Auth::check() ? Auth::user()->name : 'laravelnewbie'}}#laravel" style="border:0; width:100%; height:450px;"></iframe>
<a href="http://irclogs.laravel.io" target="_NEW">Search the chat logs</a> to see if your question has already been answered. You can use your own IRC client at Freenode.net in #Laravel.<br>
Channel Moderators are: TaylorOtwell, ShawnMcCool, PhillSparks, daylerees, JasonLewis, machuga and JesseOBrien.
@else
{{-- look at how much I don't give a crap --}}
<?Session::put('userLazilyOptsOutOfAuthOnChat', 1)?>
<p>
Before you use chat, it'd be best if you logged into Laravel.IO. The signup process is a painless authentication with GitHub, you don't actually have to enter anything. <a href="{{ action('AuthController@getLogin') }}">Authenticate with GitHub</a>
</p>
<p>
Or, if you can't be arsed to authenticate (just do it) then..
</p>
@endif
|
<h2>#Laravel IRC Chat</h2>
@if(Auth::check() or Session::has('userLazilyOptsOutOfAuthOnChat'))
<iframe src="https://kiwiirc.com/client/irc.freenode.net/?&nick={{ Auth::check() ? Auth::user()->name : 'laravelnewbie'}}#laravel" style="border:0; width:100%; height:450px;"></iframe>
<a href="http://irclogs.laravel.io" target="_NEW">Search the chat logs</a> to see if your question has already been answered. You can use your own IRC client at Freenode.net in #Laravel.<br>
Channel Moderators are: TaylorOtwell, ShawnMcCool, PhillSparks, daylerees, JasonLewis, machuga and JesseOBrien.
@else
{{-- look at how much I don't give a crap --}}
<?Session::put('userLazilyOptsOutOfAuthOnChat', 1)?>
<p>
Before you use chat, it'd be best if you logged into Laravel.IO. The signup process is a painless authentication with GitHub, you don't actually have to enter anything. <a href="{{ action('AuthController@getLogin') }}">Authenticate with GitHub</a>
</p>
<p>
Or, if you can't be arsed to authenticate (just do it) then..
</p>
@endif
|
Add error log on bundling error
|
module.exports = function(config) {
'use strict';
config.set({
browsers: ['Chrome'],
reporters: ['progress', 'notify'],
frameworks: ['browserify' ,'mocha', 'chai-sinon', 'sinon'],
// list of files / patterns to load in the browser
files: ['tests-index.js'],
preprocessors: {
'tests-index.js': ['browserify']
},
client: {
mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter
},
browserify: {
debug: true,
configure: function(bundle) {
bundle.on('bundled', function(error) {
if (error != null)
console.error(error.message);
});
}
},
notifyReporter: {
reportEachFailure: true,
reportSuccess: true
}
});
};
|
module.exports = function(config) {
'use strict';
config.set({
browsers: ['Chrome'],
reporters: ['progress', 'notify'],
frameworks: ['browserify' ,'mocha', 'chai-sinon', 'sinon'],
// list of files / patterns to load in the browser
files: ['tests-index.js'],
preprocessors: {
'tests-index.js': ['browserify']
},
client: {
mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter
},
browserify: {
debug: true
},
notifyReporter: {
reportEachFailure: true,
reportSuccess: true,
},
});
};
|
Return value is an array
|
<?php
namespace phtamas\yii2\imagecontroller;
use yii\web\CompositeUrlRule;
class UrlRule extends CompositeUrlRule
{
/**
* @var string
*/
public $controllerId;
public $prefix;
protected function createRules()
{
$rules = [];
$controller = \Yii::$app->createController($this->controllerId)[0];
/* @var $controller Controller */
foreach ($controller->actions as $id => $action) {
$rules[$this->prefix . '/' . $id . '/<filename>'] = [$this->controllerId . '/' . $id];
}
return $rules;
}
/**
* @inheritdoc
*/
public function parseRequest($manager, $request)
{
if (strpos($request->pathInfo . '/', $this->prefix . '/') === 0) {
return parent::parseRequest($manager, $request);
} else {
return false;
}
}
public function createUrl($manager, $route, $params)
{
if (strpos($route, $this->controllerId . '/') === 0) {
return parent::createUrl($manager, $route, $params);
} else {
return false;
}
}
}
|
<?php
namespace phtamas\yii2\imagecontroller;
use yii\web\CompositeUrlRule;
class UrlRule extends CompositeUrlRule
{
/**
* @var string
*/
public $controllerId;
public $prefix;
protected function createRules()
{
$rules = [];
$controller = \Yii::$app->createController($this->controllerId);
/* @var $controller Controller */
foreach ($controller->actions as $id => $action) {
$rules[$this->prefix . '/' . $id . '/<filename>'] = [$this->controllerId . '/' . $id];
}
return $rules;
}
/**
* @inheritdoc
*/
public function parseRequest($manager, $request)
{
if (strpos($request->pathInfo . '/', $this->prefix . '/') === 0) {
return parent::parseRequest($manager, $request);
} else {
return false;
}
}
public function createUrl($manager, $route, $params)
{
if (strpos($route, $this->controllerId . '/') === 0) {
return parent::createUrl($manager, $route, $params);
} else {
return false;
}
}
}
|
Make 'UserRegistrationRequest' order by 'created_at'
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserRegistrationRequest;
class UserRegistrationRequestController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
$this->middleware('admin');
}
public function index(Request $request)
{
if (isset($request->key))
return response()->json(UserRegistrationRequest::where('id', 'LIKE', '%' . $request->key . '%')->offset($request->skip)->limit($request->take)->orderBy('created_at', 'desc')->get());
else
return response()->json(UserRegistrationRequest::offset($request->skip)->limit($request->take)->orderBy('created_at', 'desc')->get());
}
public function store(Request $request)
{
$this->validate($request, [
'new_student_id' => 'required|integer|max:9999999|min:1000000|unique:user_registration_requests,id',
]);
$user = new UserRegistrationRequest();
$user->id = $request->new_student_id;
$user->code = strtoupper(substr(md5(time()), 0, 5) . '-' . substr(md5($request->new_student_id), 0, 5) . '-' . str_random(5));
$user->save();
return response()->json($user);
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\UserRegistrationRequest;
class UserRegistrationRequestController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
$this->middleware('admin');
}
public function index(Request $request)
{
if (isset($request->key))
return response()->json(UserRegistrationRequest::where('id', 'LIKE', '%' . $request->key . '%')->offset($request->skip)->limit($request->take)->orderBy('id')->get());
else
return response()->json(UserRegistrationRequest::offset($request->skip)->limit($request->take)->orderBy('id')->get());
}
public function store(Request $request)
{
$this->validate($request, [
'new_student_id' => 'required|integer|max:9999999|min:1000000|unique:user_registration_requests,id',
]);
$user = new UserRegistrationRequest();
$user->id = $request->new_student_id;
$user->code = strtoupper(substr(md5(time()), 0, 5) . '-' . substr(md5($request->new_student_id), 0, 5) . '-' . str_random(5));
$user->save();
return response()->json($user);
}
}
|
Fix error in node v0.10 missing Promises.
|
'use strict';
var Promise = require('bluebird'),
extractCss = require('extract-css'),
inlineCss = require('./inline-css');
module.exports = function inlineContent(src, options) {
return new Promise(function (resolve, reject) {
var content;
if (!options.url) {
reject('options.url is required');
}
extractCss(src, options, function (err, html, css) {
var extraCss;
if (err) {
return reject(err);
}
extraCss = css + '\n' + options.extraCss;
content = inlineCss(html, extraCss, options);
resolve(content);
});
});
};
|
'use strict';
var extractCss = require('extract-css'),
inlineCss = require('./inline-css');
module.exports = function inlineContent(src, options) {
return new Promise(function (resolve, reject) {
var content;
if (!options.url) {
reject('options.url is required');
}
extractCss(src, options, function (err, html, css) {
var extraCss;
if (err) {
return reject(err);
}
extraCss = css + '\n' + options.extraCss;
content = inlineCss(html, extraCss, options);
resolve(content);
});
});
};
|
Add ratio as a config option
|
import React from 'react';
import Chartist from 'chartist';
export default class Chart extends React.Component {
componentDidMount() {
this.updateChart(this.props);
}
componentWillReceiveProps(newProps) {
this.updateChart(newProps);
}
componentWillUnmount() {
this.chartist && this.chartist.detach();
}
render() {
return <div className = {['ct-chart', this.props.ratio].join(' ').trim()}></div>;
}
updateChart(configs) {
const {type, data, options = {}, responsiveOptions = []} = configs;
data.series && (this.chartist = new Chartist[type](React.findDOMNode(this), data, options, responsiveOptions));
}
}
Chart.propTypes = {
type: React.PropTypes.string.isRequired,
ratio: React.PropTypes.string,
data: React.PropTypes.object.isRequired,
options: React.PropTypes.object,
responsiveOptions: React.PropTypes.array
};
|
import React from 'react';
import Chartist from 'chartist';
export default class Chart extends React.Component {
componentDidMount() {
this.updateChart(this.props);
}
componentWillReceiveProps(newProps) {
this.updateChart(newProps);
}
componentWillUnmount() {
this.chartist && this.chartist.detach();
}
render() {
return <div className = "ct-chart"></div>;
}
updateChart(configs) {
const {type, data, options = {}, responsiveOptions = []} = configs;
data.series && (this.chartist = new Chartist[type](React.findDOMNode(this), data, options, responsiveOptions));
}
}
Chart.propTypes = {
type: React.PropTypes.string.isRequired,
data: React.PropTypes.object.isRequired,
options: React.PropTypes.object,
responsiveOptions: React.PropTypes.array
};
|
Add a comment for robin
|
import re
from htmlentitydefs import name2codepoint
# From http://wiki.python.org/moin/EscapingHtml
_HTMLENT_CODEPOINT_RE = re.compile('&({0}|#\d+);'.format(
'|'.join(name2codepoint.keys())))
def recodeText(text):
"""Parses things like & and ὔ into real characters."""
def _entToUnichr(match):
ent = match.group(1)
try:
if ent.startswith("#"):
char = unichr(int(ent[1:]))
else:
char = unichr(name2codepoint[ent])
except:
char = match.group(0)
return char
return _HTMLENT_CODEPOINT_RE.sub(_entToUnichr, text)
|
import re
from htmlentitydefs import name2codepoint
# From http://wiki.python.org/moin/EscapingHtml
_HTMLENT_CODEPOINT_RE = re.compile('&({0}|#\d+);'.format(
'|'.join(name2codepoint.keys())))
def recodeText(text):
def _entToUnichr(match):
ent = match.group(1)
try:
if ent.startswith("#"):
char = unichr(int(ent[1:]))
else:
char = unichr(name2codepoint[ent])
except:
char = match.group(0)
return char
return _HTMLENT_CODEPOINT_RE.sub(_entToUnichr, text)
|
Store binding as local variable
|
package com.chaos.databinding.activities;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.chaos.databinding.R;
import com.chaos.databinding.models.User;
import com.chaos.databinding.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
this.updateUser();
}
private void updateUser() {
binding.setUser(this.getUser());
}
private User getUser() {
return new User("Ash Davies", "Berlin");
}
}
|
package com.chaos.databinding.activities;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.chaos.databinding.R;
import com.chaos.databinding.models.User;
import com.chaos.databinding.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final User user = this.getUser();
binding.setUser(user);
}
private User getUser() {
return new User("Ash Davies", "Berlin");
}
}
|
Add missing dependency on darwin
|
// +build !linux
/*
Copyright 2017 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package monitoring
import "github.com/gravitational/trace"
// NewOSChecker returns a new checker to verify OS distribution
// against the list of supported releases.
//
// The checker only supports Linux.
func NewOSChecker(releases ...OSRelease) noopChecker {
return noopChecker{}
}
// OSRelease describes an OS distribution.
// It only supports Linux.
type OSRelease struct {
// ID identifies the distributor: ubuntu, redhat/centos, etc.
ID string
// VersionID is the release version i.e. 16.04 for Ubuntu
VersionID string
// Like specifies the list of root OS distributions this
// distribution is a descendant of
Like []string
}
// GetOSRelease deteremines the OS distribution release information.
//
// It only supports Linux.
func GetOSRelease() (*OSRelease, error) {
return nil, trace.BadParameter("not implemented")
}
|
// +build !linux
/*
Copyright 2017 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package monitoring
// NewOSChecker returns a new checker to verify OS distribution
// against the list of supported releases.
//
// The checker only supports Linux.
func NewOSChecker(releases ...OSRelease) noopChecker {
return noopChecker{}
}
// OSRelease describes an OS distribution.
// It only supports Linux.
type OSRelease struct {
// ID identifies the distributor: ubuntu, redhat/centos, etc.
ID string
// VersionID is the release version i.e. 16.04 for Ubuntu
VersionID string
// Like specifies the list of root OS distributions this
// distribution is a descendant of
Like []string
}
// GetOSRelease deteremines the OS distribution release information.
//
// It only supports Linux.
func GetOSRelease() (*OSRelease, error) {
return nil, trace.BadParameter("not implemented")
}
|
Add coverage the Hello World client example.
This is now free-standing and also covers edge cases like timestamps.
b/124437335
Change-Id: I9496504b638ae6af3885a20aeedf18e267aca683
GitOrigin-RevId: b7c8694f2f920371ee228bb53a6e499e3b727783
|
package com.cloudrobotics.hello_world_client;
import cloudrobotics.hello_world.v1alpha1.K8sHelloWorldGrpc;
import cloudrobotics.hello_world.v1alpha1.Service;
import io.grpc.ManagedChannelBuilder;
import java.util.logging.Logger;
/** */
final class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
K8sHelloWorldGrpc.K8sHelloWorldBlockingStub stub =
K8sHelloWorldGrpc.newBlockingStub(
ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build());
Service.CreateHelloWorldRequest.Builder req = Service.CreateHelloWorldRequest.newBuilder();
req.getObjectBuilder().getMetadataBuilder().setName("foo");
stub.create(req.build());
Service.HelloWorld world =
stub.get(Service.GetHelloWorldRequest.newBuilder().setName("foo").build());
System.out.println(world.getMetadata().getResourceVersion());
stub.delete(Service.DeleteHelloWorldRequest.newBuilder().setName("foo").build());
}
}
|
package com.cloudrobotics.hello_world_client;
import cloudrobotics.hello_world.v1alpha1.K8sHelloWorldGrpc;
import cloudrobotics.hello_world.v1alpha1.Service;
import io.grpc.ManagedChannelBuilder;
import java.util.logging.Logger;
/** */
final class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
K8sHelloWorldGrpc.K8sHelloWorldBlockingStub stub =
K8sHelloWorldGrpc.newBlockingStub(
ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build());
Service.HelloWorld world =
stub.get(Service.GetHelloWorldRequest.newBuilder().setName("foo").build());
System.out.println(world.getMetadata().getResourceVersion());
}
}
|
Fix ValidatedTextFieldListCell to use the actual edited text
|
package org.hildan.fx.components;
import java.util.function.Predicate;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.util.StringConverter;
import org.hildan.fxlog.themes.Css;
public class ValidatingTextFieldListCell<T> extends TextFieldListCell<T> {
private final Predicate<String> validator;
public ValidatingTextFieldListCell(StringConverter<T> converter, Predicate<String> validator) {
super(converter);
this.validator = validator;
}
public void commitEdit(T item) {
if (!isEditing()) {
return;
}
// the edited text is not in getText() but in the TextField used as Graphic for this cell
TextField textField = (TextField) getGraphic();
String editedText = textField.getText();
boolean itemIsValid = validator.test(editedText);
pseudoClassStateChanged(Css.INVALID, !itemIsValid);
if (itemIsValid) {
// only commit if the item is valid, otherwise we stay in edit state
super.commitEdit(item);
}
}
}
|
package org.hildan.fx.components;
import java.util.function.Predicate;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.util.StringConverter;
import org.hildan.fxlog.themes.Css;
public class ValidatingTextFieldListCell<T> extends TextFieldListCell<T> {
private final Predicate<String> validator;
public ValidatingTextFieldListCell(StringConverter<T> converter, Predicate<String> validator) {
super(converter);
this.validator = validator;
}
public void commitEdit(T item) {
if (!isEditing()) {
return;
}
boolean itemIsValid = validator.test(getText());
pseudoClassStateChanged(Css.INVALID, !itemIsValid);
if (itemIsValid) {
// only commit if the item is valid, otherwise we stay in edit state
super.commitEdit(item);
}
}
}
|
Use ActiveRecord from root namespace for param typehint
|
<?php
namespace Emergence\CMS;
use ActiveRecord;
class Page extends AbstractContent
{
// ActiveRecord configuration
public static $defaultClass = __CLASS__;
public static $singularNoun = 'page';
public static $pluralNoun = 'pages';
public static $collectionRoute = '/pages';
public static $fields = array(
'LayoutClass' => array(
'type' => 'enum'
,'values' => array('OneColumn')
,'default' => 'OneColumn'
)
,'LayoutConfig' => 'json'
);
public static function getAllPublishedByContextObject(ActiveRecord $Context, $options = array())
{
$options = array_merge(array(
'conditions' => array()
), $options);
$options['conditions']['Class'] = __CLASS__;
return parent::getAllPublishedByContextObject($Context, $options);
}
}
|
<?php
namespace Emergence\CMS;
class Page extends AbstractContent
{
// ActiveRecord configuration
public static $defaultClass = __CLASS__;
public static $singularNoun = 'page';
public static $pluralNoun = 'pages';
public static $collectionRoute = '/pages';
public static $fields = array(
'LayoutClass' => array(
'type' => 'enum'
,'values' => array('OneColumn')
,'default' => 'OneColumn'
)
,'LayoutConfig' => 'json'
);
public static function getAllPublishedByContextObject(ActiveRecord $Context, $options = array())
{
$options = array_merge(array(
'conditions' => array()
), $options);
$options['conditions']['Class'] = __CLASS__;
return parent::getAllPublishedByContextObject($Context, $options);
}
}
|
Remove the beacon for now
|
from .game_manager import GameManager
from .robot_controller import RobotController
from .snake_board import SnakeBoard
from .snake_robot import SnakeRobot
from .snake_beacon import SnakeBeacon
def launch_robot(robot_module, myrobot, board_size=(8,16)):
'''
Creates a robot controller, a board, and sets things up
'''
game_manager = GameManager()
# create the robot controller
controller = RobotController(robot_module, myrobot)
# add it to the manager
game_manager.add_robot(controller)
# create the robot
snake_robot = SnakeRobot(controller)
#snake_beacon = SnakeBeacon(controller, snake_robot)
# start the robot controller (does not block)
controller.run()
# create the board
snake_board = SnakeBoard(game_manager, board_size)
snake_board.add_game_element(snake_robot)
#snake_board.add_game_element(snake_beacon)
# launch the board last (blocks until game is over)
snake_board.run()
# once it has finished, try to shut the robot down
# -> if it can't, then the user messed up
if not controller.stop():
print('Error: could not stop the robot code! Check your code')
|
from .game_manager import GameManager
from .robot_controller import RobotController
from .snake_board import SnakeBoard
from .snake_robot import SnakeRobot
from .snake_beacon import SnakeBeacon
def launch_robot(robot_module, myrobot, board_size=(8,16)):
'''
Creates a robot controller, a board, and sets things up
'''
game_manager = GameManager()
# create the robot controller
controller = RobotController(robot_module, myrobot)
# add it to the manager
game_manager.add_robot(controller)
# create the robot
snake_robot = SnakeRobot(controller)
snake_beacon = SnakeBeacon(controller, snake_robot)
# start the robot controller (does not block)
controller.run()
# create the board
snake_board = SnakeBoard(game_manager, board_size)
snake_board.add_game_element(snake_robot)
snake_board.add_game_element(snake_beacon)
# launch the board last (blocks until game is over)
snake_board.run()
# once it has finished, try to shut the robot down
# -> if it can't, then the user messed up
if not controller.stop():
print('Error: could not stop the robot code! Check your code')
|
Fix path to where views are published.
Larval will automatically pick up overwrites from
`resources/views/vendor/<package-name>/` (where `<package-name>` is set
as the second parameter of `$this->loadViewsFrom()`).
Signed-off-by: Micheal Mand <4a52646cf58d42dd1882775751ea450b8cf7f96f@kmdwebdesigns.com>
|
<?php
namespace Gaaarfild\LaravelNotifications;
use Illuminate\Support\ServiceProvider;
class LaravelNotificationsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/laravel-notifications.php' => config_path('laravel-notifications.php'),
], 'config');
$this->publishes([
__DIR__.'/../views' => resource_path('views/vendor/laravel-notifications'),
], 'views');
$this->loadViewsFrom(__DIR__.'/../views', 'laravel-notifications');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->registerLaravelNotifications();
$this->app->alias('Notifications', \Gaaarfild\LaravelNotifications\Notifications::class);
}
private function registerLaravelNotifications()
{
$this->app->singleton('Notifications', function ($app) {
return new Notifications();
});
}
}
|
<?php
namespace Gaaarfild\LaravelNotifications;
use Illuminate\Support\ServiceProvider;
class LaravelNotificationsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/laravel-notifications.php' => config_path('laravel-notifications.php'),
], 'config');
$this->publishes([
__DIR__.'/../views' => base_path('resources/views/laravel-notifications'),
], 'views');
$this->loadViewsFrom(__DIR__.'/../views', 'laravel-notifications');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->registerLaravelNotifications();
$this->app->alias('Notifications', \Gaaarfild\LaravelNotifications\Notifications::class);
}
private function registerLaravelNotifications()
{
$this->app->singleton('Notifications', function ($app) {
return new Notifications();
});
}
}
|
webhook: Fix "logging before flag.Parse" errors
Fixes #932
Signed-off-by: Benjamin Staffin <7ff02effd2e7aa57491d2da194ef1ab398b1a4cf@gmail.com>
|
/*
Copyright 2018 The Jetstack cert-manager contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"github.com/jetstack/cert-manager/pkg/apis/certmanager/validation/webhooks"
"github.com/openshift/generic-admission-server/pkg/cmd"
)
var certHook cmd.ValidatingAdmissionHook = &webhooks.CertificateAdmissionHook{}
var issuerHook cmd.ValidatingAdmissionHook = &webhooks.IssuerAdmissionHook{}
var clusterIssuerHook cmd.ValidatingAdmissionHook = &webhooks.ClusterIssuerAdmissionHook{}
func main() {
// Avoid "logging before flag.Parse" errors from glog
flag.CommandLine.Parse([]string{})
cmd.RunAdmissionServer(
certHook,
issuerHook,
clusterIssuerHook,
)
}
|
/*
Copyright 2018 The Jetstack cert-manager contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"github.com/jetstack/cert-manager/pkg/apis/certmanager/validation/webhooks"
"github.com/openshift/generic-admission-server/pkg/cmd"
)
var certHook cmd.ValidatingAdmissionHook = &webhooks.CertificateAdmissionHook{}
var issuerHook cmd.ValidatingAdmissionHook = &webhooks.IssuerAdmissionHook{}
var clusterIssuerHook cmd.ValidatingAdmissionHook = &webhooks.ClusterIssuerAdmissionHook{}
func main() {
cmd.RunAdmissionServer(
certHook,
issuerHook,
clusterIssuerHook,
)
}
|
Fix deprecation notice in PHP 8 for libxml_disable_entity_loader
PHP 8 [deprecates `libxml_disable_entity_loader`](https://php.watch/versions/8.0/libxml_disable_entity_loader-deprecation) function, and this fixes the deprecation notice by not calling the function on libxml 2.9, where external entity loader is disabled by default and is not necessary to explicitly disable it.
|
<?php
namespace DiDom;
class Errors
{
/**
* @var bool
*/
protected static $internalErrors;
/**
* @var bool
*/
protected static $disableEntities;
/**
* Disable error reporting.
*/
public static function disable()
{
self::$internalErrors = libxml_use_internal_errors(true);
if (\LIBXML_VERSION < 20900) {
self::$disableEntities = libxml_disable_entity_loader(true);
}
}
/**
* Restore error reporting.
*
* @param bool $clear
*/
public static function restore($clear = true)
{
if ($clear) {
libxml_clear_errors();
}
libxml_use_internal_errors(self::$internalErrors);
if (\LIBXML_VERSION < 20900) {
libxml_disable_entity_loader(self::$disableEntities);
}
}
}
|
<?php
namespace DiDom;
class Errors
{
/**
* @var bool
*/
protected static $internalErrors;
/**
* @var bool
*/
protected static $disableEntities;
/**
* Disable error reporting.
*/
public static function disable()
{
self::$internalErrors = libxml_use_internal_errors(true);
self::$disableEntities = libxml_disable_entity_loader(true);
}
/**
* Restore error reporting.
*
* @param bool $clear
*/
public static function restore($clear = true)
{
if ($clear) {
libxml_clear_errors();
}
libxml_use_internal_errors(self::$internalErrors);
libxml_disable_entity_loader(self::$disableEntities);
}
}
|
Update pinback URL and reporter message
|
const Report = require('./Report');
const Notification = require('./Notification');
async function Reporter( request, reply ) {
// Params https://sites.google.com/a/webpagetest.org/docs/advanced-features/webpagetest-restful-apis
const base = process.env.BASE || 'http://localhost:8080';
const pinback = `${base}/verification/${request.query.hipchat}/`;
const result = await new Report({
k: process.env.WEB_PAGE_TEST_KEY || '', // k means KEY
url: request.query.site,
pingback: pinback,
}).run();
console.log(`Pinback: ${pinback}`);
// Set error as default.
let notificationOpts = {
status: 'Error',
description: `There was an error proccesing <a href="${request.query.site}">${request.query.site}</a>`,
room: request.query.hipchat,
url: request.query.site,
}
// Update notificationOptions if was a success
console.log('Response from API', result);
if ( 'statusCode' in result && result.statusCode === 200 ) {
let { data } = result;
notificationOpts = Object.assign({}, notificationOpts, {
status: 'Started',
description: `The performance tests for <a href="${request.query.site}">${request.query.site}</a> has started. (<a href="${data.userUrl}">Click for more details or the title).</a>`,
url: data.userUrl,
});
}
const notificationResult = await Notification(notificationOpts);
return reply(notificationResult);
}
module.exports = Reporter;
|
const Report = require('./Report');
const Notification = require('./Notification');
async function Reporter( request, reply ) {
// Params https://sites.google.com/a/webpagetest.org/docs/advanced-features/webpagetest-restful-apis
const base = process.env.BASE || 'http://localhost:8080';
const result = await new Report({
k: process.env.WEB_PAGE_TEST_KEY || '', // k means KEY
url: request.query.site,
pingback: `${base}/verification/`,
}).run();
console.log(`Pinback: ${base}/verification/?hipchat=${request.query.hipchat}`);
// Set error as default.
let notificationOpts = {
status: 'Error',
description: `There was an error proccesing ${request.query.site}`,
room: request.query.hipchat,
url: request.query.site,
}
// Update notificationOptions if was a success
if ( 'statusCode' in result && result.statusCode === 200 ) {
notificationOpts = Object.assign({}, notificationOpts, {
status: 'Started',
description: `The performance tests for ${request.query.site} has started.`,
url: result.data.userUrl,
});
}
const notificationResult = await Notification(notificationOpts);
return reply(notificationResult);
}
module.exports = Reporter;
|
Add unique constraints to Enum definitions
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from enum import Enum, unique
@unique
class Context(Enum):
DUP_DATABASE = 1
CONVERT_CONFIG = 5
INDEX_LIST = 10
ADD_PRIMARY_KEY_NAME = 15
TYPE_INFERENCE = 19
TYPE_HINT_HEADER = 20
LOG_LEVEL = 30
OUTPUT_PATH = 40
VERBOSITY_LEVEL = 50
SYMBOL_REPLACE_VALUE = 60
class ExitCode(object):
SUCCESS = 0
FAILED_LOADER_NOT_FOUND = 1
FAILED_CONVERT = 2
FAILED_HTTP = 3
NO_INPUT = 10
@unique
class DupDatabase(Enum):
OVERWRITE = 1
APPEND = 2
SKIP = 3 # TODO
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from enum import Enum
class Context(Enum):
DUP_DATABASE = 1
CONVERT_CONFIG = 5
INDEX_LIST = 10
ADD_PRIMARY_KEY_NAME = 15
TYPE_INFERENCE = 19
TYPE_HINT_HEADER = 20
LOG_LEVEL = 30
OUTPUT_PATH = 40
VERBOSITY_LEVEL = 50
SYMBOL_REPLACE_VALUE = 60
class ExitCode(object):
SUCCESS = 0
FAILED_LOADER_NOT_FOUND = 1
FAILED_CONVERT = 2
FAILED_HTTP = 3
NO_INPUT = 10
class DupDatabase(Enum):
OVERWRITE = 1
APPEND = 2
SKIP = 3 # TODO
|
Fix return error correctly in NewSharedStateSink
|
package core
import (
"fmt"
)
// writer points a shared state. sharedStateSink will point to the same shared state
// even after the state is removed from the context.
type sharedStateSink struct {
writer Writer
}
// NewSharedStateSink creates a sink that writes to SharedState.
func NewSharedStateSink(ctx *Context, name string) (Sink, error) {
// Get SharedState by name
state, err := ctx.SharedStates.Get(name)
if err != nil {
return nil, err
}
// It fails if the shared state cannot be written
writer, ok := state.(Writer)
if !ok {
return nil, fmt.Errorf("'%v' state cannot be written", name)
}
s := &sharedStateSink{
writer: writer,
}
return s, nil
}
func (s *sharedStateSink) Write(ctx *Context, t *Tuple) error {
return s.writer.Write(ctx, t)
}
func (s *sharedStateSink) Close(ctx *Context) error {
return nil
}
}
|
package core
import (
"fmt"
)
// writer points a shared state. sharedStateSink will point to the same shared state
// even after the state is removed from the context.
type sharedStateSink struct {
writer Writer
}
// NewSharedStateSink creates a sink that writes to SharedState.
func NewSharedStateSink(ctx *Context, name string) (Sink, error) {
// Get SharedState by name
state, err := ctx.SharedStates.Get(name)
if err != nil {
return nil, err
}
// It fails if the shared state cannot be written
writer, ok := state.(Writer)
if !ok {
return nil, fmt.Errorf("'%v' state cannot be written")
}
s := &sharedStateSink{
writer: writer,
}
return s, nil
}
func (s *sharedStateSink) Write(ctx *Context, t *Tuple) error {
return s.writer.Write(ctx, t)
}
func (s *sharedStateSink) Close(ctx *Context) error {
return nil
}
}
|
Add a few more cases of "not value"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
import pep8
class UtilTestCase(unittest.TestCase):
def test_normalize_paths(self):
cwd = os.getcwd()
self.assertEquals(pep8.normalize_paths(''), [])
self.assertEquals(pep8.normalize_paths([]), [])
self.assertEquals(pep8.normalize_paths(None), [])
self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
self.assertEquals(pep8.normalize_paths('foo, bar '), ['foo', 'bar'])
self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'),
['/foo/bar', cwd + '/bat'])
self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"),
['.pyc', cwd + '/build/*'])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
import pep8
class UtilTestCase(unittest.TestCase):
def test_normalize_paths(self):
cwd = os.getcwd()
self.assertEquals(pep8.normalize_paths(''), [])
self.assertEquals(pep8.normalize_paths(['foo']), ['foo'])
self.assertEquals(pep8.normalize_paths('foo'), ['foo'])
self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar'])
self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'),
['/foo/bar', cwd + '/bat'])
self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"),
['.pyc', cwd + '/build/*'])
|
Create test-results folder, to make Jenkins happy
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import gen_csharp
import gen_docs_json
import gen_java
import gen_python
import gen_thrift
import bindings
import sys, os
sys.path.insert(0, "../../scripts")
import run
# Create results folder, where H2OCloud stores its logs, and ../build/test-results where Jenkins stores its stuff
if not os.path.exists("results"):
os.mkdir("results")
os.mkdir("results/failed")
if not os.path.exists("../build/test-results"):
os.mkdir("../build/test-results")
# Start H2O cloud
print("Starting H2O cloud...")
cloud = run.H2OCloud(
cloud_num=0,
use_client=False,
nodes_per_cloud=1,
h2o_jar=os.path.abspath("../../build/h2o.jar"),
base_port=48000,
xmx="4g",
cp="",
output_dir="results"
)
cloud.start()
cloud.wait_for_cloud_to_be_up()
# Manipulate the command line arguments, so that bindings module would know which cloud to use
sys.argv.insert(1, "--usecloud")
sys.argv.insert(2, "%s:%s" % (cloud.get_ip(), cloud.get_port()))
# Actually generate all the bindings
print()
gen_java.main()
gen_python.main()
gen_docs_json.main()
gen_thrift.main()
gen_csharp.main()
bindings.done()
print()
# The END
cloud.stop()
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
import gen_csharp
import gen_docs_json
import gen_java
import gen_python
import gen_thrift
import bindings
import sys, os
sys.path.insert(0, "../../scripts")
import run
# Create results/ folder, where H2OCloud stores its logs
if not os.path.exists("results"):
os.mkdir("results")
# Start H2O cloud
print("Starting H2O cloud...")
cloud = run.H2OCloud(
cloud_num=0,
use_client=False,
nodes_per_cloud=1,
h2o_jar=os.path.abspath("../../build/h2o.jar"),
base_port=48000,
xmx="4g",
cp="",
output_dir="results"
)
cloud.start()
cloud.wait_for_cloud_to_be_up()
# Manipulate the command line arguments, so that bindings module would know which cloud to use
sys.argv.insert(1, "--usecloud")
sys.argv.insert(2, "%s:%s" % (cloud.get_ip(), cloud.get_port()))
# Actually generate all the bindings
print()
gen_java.main()
gen_python.main()
gen_docs_json.main()
gen_thrift.main()
gen_csharp.main()
bindings.done()
print()
# The END
cloud.stop()
|
Change subject and content of registration email.
|
from celery import task
from django.core.mail import EmailMessage
from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from
@task()
def send_verification_token(ureporter):
if ureporter.token:
subject = 'U-Report Registration'
body = 'Thank you for registering with U-Report. ' \
'Here is your code to complete your U-Report profile: ' + str(ureporter.token) + ' .' \
'\n\nWe are so happy for you to join us to speak out on the important issues ' \
'affecting young people in your community.'
signature = '\n\n-----\nU-Report\nVoice Matters' \
'\n\nThis is an automated email so please don\'t reply.' \
'\nFor more information about U-Report go to www.ureport.in/about ' \
'or follow us on Twitter @UReportGlobal'
recipients = [ureporter.user.email]
message = EmailMessage(subject, body + signature, to=recipients)
message.send()
@task()
def delete_user_from_rapidpro(ureporter):
delete_from(ureporter)
|
from celery import task
from django.core.mail import EmailMessage
from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from
@task()
def send_verification_token(ureporter):
if ureporter.token:
subject = 'Hello'
body = 'Welcome to ureport. To complete the registration process, ' \
'use this code to verify your account: ' + str(ureporter.token) + ' .' \
'\n\n-----\nThanks'
signature = '\nureport team'
recipients = [ureporter.user.email]
message = EmailMessage(subject, body + signature, to=recipients)
message.send()
@task()
def delete_user_from_rapidpro(ureporter):
delete_from(ureporter)
|
Add email to demonstrate spam capabilities ... lol
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'dara.hyemin@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Add the ability to send logs to syslog
|
package main
import (
"flag"
"fmt"
log "github.com/Sirupsen/logrus"
logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
"github.com/bobtfish/AWSnycast/daemon"
"log/syslog"
"os"
)
var (
debug = flag.Bool("debug", false, "Enable debugging")
f = flag.String("f", "/etc/awsnycast.yaml", "Configration file")
oneshot = flag.Bool("oneshot", false, "Run route table manipulation exactly once, ignoring healthchecks, then exit")
noop = flag.Bool("noop", false, "Don't actually *do* anything, just print what would be done")
printVersion = flag.Bool("version", false, "Print the version number")
syslog = flag.Bool("syslog", false, "Log to syslog")
)
func main() {
flag.Parse()
if *printVersion {
fmt.Printf("%s\n", version)
os.Exit(0)
}
d := new(daemon.Daemon)
if *debug {
log.SetLevel(log.DebugLevel)
}
if *syslog {
hook, err := logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
if err == nil {
log.Hooks.Add(hook)
}
}
d.Debug = *debug
d.ConfigFile = *f
os.Exit(d.Run(*oneshot, *noop))
}
|
package main
import (
"flag"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/bobtfish/AWSnycast/daemon"
"os"
)
var (
debug = flag.Bool("debug", false, "Enable debugging")
f = flag.String("f", "/etc/awsnycast.yaml", "Configration file")
oneshot = flag.Bool("oneshot", false, "Run route table manipulation exactly once, ignoring healthchecks, then exit")
noop = flag.Bool("noop", false, "Don't actually *do* anything, just print what would be done")
printVersion = flag.Bool("version", false, "Print the version number")
)
func main() {
flag.Parse()
if *printVersion {
fmt.Printf("%s\n", version)
os.Exit(0)
}
d := new(daemon.Daemon)
if *debug {
log.SetLevel(log.DebugLevel)
}
d.Debug = *debug
d.ConfigFile = *f
os.Exit(d.Run(*oneshot, *noop))
}
|
Fix Metadata serialization (serialize null values)
|
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client.v3;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.AllowNulls;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;
import java.util.Map;
/**
* The metadata payload for a resource
*/
@JsonDeserialize
@Value.Immutable
abstract class _Metadata {
/**
* The metadata annotations
*/
@JsonProperty("annotations")
@JsonInclude
@AllowNulls
@Nullable
abstract Map<String, String> getAnnotations();
/**
* The metadata labels
*/
@JsonProperty("labels")
@JsonInclude
@AllowNulls
@Nullable
abstract Map<String, String> getLabels();
}
|
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client.v3;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.AllowNulls;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;
import java.util.Map;
/**
* The metadata payload for a resource
*/
@JsonDeserialize
@Value.Immutable
abstract class _Metadata {
/**
* The metadata annotations
*/
@JsonProperty("annotations")
@AllowNulls
@Nullable
abstract Map<String, String> getAnnotations();
/**
* The metadata labels
*/
@JsonProperty("labels")
@AllowNulls
@Nullable
abstract Map<String, String> getLabels();
}
|
Update output parameters for Click to Call
|
<?php
/**
* Click to Call
*
* @url https://platform.x-onweb.com/#clicktocall
*/
require __DIR__ . '/../vendor/autoload.php';
/**
* Your API Token
*/
$token = 'ExampleTokenHere';
/**
* Required Parameters
* - destination
* - target
*/
$destinationPhoneNumber = '0333 332 0000';
$target = 'U0050';
$guzzle = new GuzzleHttp\Client(['base_uri' => 'https://platform.x-onweb.com/api/v1/']);
$res = $guzzle->post(
'clicktocall',
[
'headers' => [
'Authorization' => 'Bearer ' . $token
],
'json' => [
'destination' => $destinationPhoneNumber,
'target' => $target,
]
]
);
echo $res->getStatusCode();
// 202
echo $res->getBody();
// {"status":"OK","callId":"20626903"}
|
<?php
/**
* Click to Call
*
* @url https://platform.x-onweb.com/#clicktocall
*/
require __DIR__ . '/../vendor/autoload.php';
/**
* Your API Token
*/
$token = 'ExampleTokenHere';
/**
* Required Parameters
* - destination
* - target
*/
$destinationPhoneNumber = '0333 332 0000';
$target = 'U0050';
$guzzle = new GuzzleHttp\Client(['base_uri' => 'https://platform.x-onweb.com/api/v1/']);
$res = $guzzle->post(
'clicktocall',
[
'headers' => [
'Authorization' => 'Bearer ' . $token
],
'json' => [
'destination' => $destinationPhoneNumber,
'target' => $target,
]
]
);
echo $res->getStatusCode();
// "200"
echo $res->getBody();
// "OK"
|
Add TcpSocketReceiverTest into Test Suite
|
package com.dianping.cat;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.dianping.cat.message.spi.core.HtmlMessageCodecTest;
import com.dianping.cat.message.spi.core.TcpSocketReceiverTest;
import com.dianping.cat.message.spi.core.WaterfallMessageCodecTest;
import com.dianping.cat.storage.dump.LocalMessageBucketManagerTest;
import com.dianping.cat.storage.dump.LocalMessageBucketTest;
import com.dianping.cat.storage.report.LocalReportBucketTest;
import com.dianping.cat.task.TaskManagerTest;
@RunWith(Suite.class)
@SuiteClasses({
HtmlMessageCodecTest.class,
WaterfallMessageCodecTest.class,
/* .storage.dump */
LocalMessageBucketTest.class,
LocalMessageBucketManagerTest.class,
/* .storage.report */
LocalReportBucketTest.class,
/* .task */
TaskManagerTest.class,
TcpSocketReceiverTest.class
})
public class AllTests {
}
|
package com.dianping.cat;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.dianping.cat.message.spi.core.HtmlMessageCodecTest;
import com.dianping.cat.message.spi.core.WaterfallMessageCodecTest;
import com.dianping.cat.storage.dump.LocalMessageBucketManagerTest;
import com.dianping.cat.storage.dump.LocalMessageBucketTest;
import com.dianping.cat.storage.report.LocalReportBucketTest;
import com.dianping.cat.task.TaskManagerTest;
@RunWith(Suite.class)
@SuiteClasses({
HtmlMessageCodecTest.class,
WaterfallMessageCodecTest.class,
/* .storage.dump */
LocalMessageBucketTest.class,
LocalMessageBucketManagerTest.class,
/* .storage.report */
LocalReportBucketTest.class,
/* .task */
TaskManagerTest.class
})
public class AllTests {
}
|
Add Windows 6.3 (8.1) to the list of known versions.
Change-Id: I4989605776cf6dbbc8a8852d88f0fc6262f08f0b
Reviewed-by: Jake Petroules <2d627e1cecd5435752fa500bacbe05f7cc90c369@petroules.com>
Reviewed-by: Joerg Bornemann <47777b9406dbddd02a3fdca8341789a013805a11@digia.com>
|
function characterSetDefines(charset) {
var defines = [];
if (charset === "unicode")
defines.push("UNICODE", "_UNICODE");
else if (charset === "mbcs")
defines.push("_MBCS");
return defines;
}
function isValidWindowsVersion(systemVersion) {
// Add new Windows versions to this list when they are released
var realVersions = [ '6.3', '6.2', '6.1', '6.0', '5.2', '5.1', '5.0', '4.0' ];
for (i in realVersions)
if (systemVersion === realVersions[i])
return true;
return false;
}
function getWindowsVersionInFormat(systemVersion, format) {
if (!isValidWindowsVersion(systemVersion))
return undefined;
var major = parseInt(systemVersion.split('.')[0]);
var minor = parseInt(systemVersion.split('.')[1]);
if (format === 'hex') {
return '0x' + major + (minor < 10 ? '0' : '') + minor;
} else if (format === 'subsystem') {
// http://msdn.microsoft.com/en-us/library/fcc1zstk.aspx
return major + '.' + (minor < 10 ? '0' : '') + minor;
} else {
throw ("Unrecognized Windows version format " + format + ". Must be in {hex, subsystem}.");
}
}
|
function characterSetDefines(charset) {
var defines = [];
if (charset === "unicode")
defines.push("UNICODE", "_UNICODE");
else if (charset === "mbcs")
defines.push("_MBCS");
return defines;
}
function isValidWindowsVersion(systemVersion) {
// Add new Windows versions to this list when they are released
var realVersions = [ '6.2', '6.1', '6.0', '5.2', '5.1', '5.0', '4.0' ];
for (i in realVersions)
if (systemVersion === realVersions[i])
return true;
return false;
}
function getWindowsVersionInFormat(systemVersion, format) {
if (!isValidWindowsVersion(systemVersion))
return undefined;
var major = parseInt(systemVersion.split('.')[0]);
var minor = parseInt(systemVersion.split('.')[1]);
if (format === 'hex') {
return '0x' + major + (minor < 10 ? '0' : '') + minor;
} else if (format === 'subsystem') {
// http://msdn.microsoft.com/en-us/library/fcc1zstk.aspx
return major + '.' + (minor < 10 ? '0' : '') + minor;
} else {
throw ("Unrecognized Windows version format " + format + ". Must be in {hex, subsystem}.");
}
}
|
Add radii mean and standard deviation
|
from __future__ import division
import numpy as np
import FreeCAD as FC
import Part
import Draft
import os
doc = FC.newDocument("ellipses")
folder = os.path.dirname(__file__) #+ "/.."
fname = folder + "/vor_ellipses.txt"
data = np.loadtxt(fname)
shapes = []
area = 0
radii = []
for ellipse in data:
cx, cy, b, a, ang = ellipse
ang = ang*np.pi/180
place = FC.Placement()
place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2))
place.Base = FC.Vector(100*cx, 100*cy, 0)
ellipse = Draft.makeEllipse(100*a, 100*b, placement=place)
radii.append([100*a, 100*b])
shapes.append(ellipse)
area = area + np.pi*a*b*100*100
print "area: %g " % (area/500/70)
print "radius: %g +/- %g" % (np.mean(radii), np.std(radii))
part = Part.makeCompound(shapes)
|
from __future__ import division
import numpy as np
import FreeCAD as FC
import Part
import Draft
import os
doc = FC.newDocument("ellipses")
folder = os.path.dirname(__file__) + ".\.."
fname = folder + "/vor_ellipses.txt"
data = np.loadtxt(fname)
shapes = []
area = 0
for ellipse in data:
cx, cy, b, a, ang = ellipse
ang = ang*np.pi/180
place = FC.Placement()
place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2))
place.Base = FC.Vector(100*cx, 100*cy, 0)
ellipse = Draft.makeEllipse(100*a, 100*b, placement=place)
shapes.append(ellipse)
area = area + np.pi*a*b*100*100
print area, " ", area/500/70
part = Part.makeCompound(shapes)
|
FIX sparse OneClassSVM was using the wrong parameter
|
import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
return super(SparseBaseLibSVM, self).fit(X, y,
sample_weight=sample_weight)
|
import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
return super(SparseBaseLibSVM, self).fit(X, y, sample_weight)
|
Move the clone function closer to it's usage.
|
export default class FlatMetaData {
static to(data) {
return buildMetaData(data);
}
}
function buildMetaData(all) {
const items = buildItems(extractAllItems(all));
return {items: items};
}
function extractAllItems(all) {
const groups = all.groups;
let extractedItems = {};
for (let groupName in groups) {
extractItemsFromGroup(groups, groupName, extractedItems);
}
return extractedItems;
}
const cloneObject = (obj) => JSON.parse(JSON.stringify(obj));
function extractItemsFromGroup(groups, groupName, addItemsTo) {
const items = groups[groupName].items;
for (let key in items) {
const item = cloneObject(items[key]);
item.groupName = groupName;
addItemsTo[key] = item;
}
}
const toInt = (string) => Number.parseInt(string, 10);
function buildItems(flattenedItems) {
const items = [];
const ids = Object.keys(flattenedItems).map(toInt);
const sortedIds = ids.sort((id1, id2) => id1 - id2);
for (let id of sortedIds) {
let item = flattenedItems[id];
item.id = id;
items.push(item);
}
return items;
}
|
export default class FlatMetaData {
static to(data) {
return buildMetaData(data);
}
}
function buildMetaData(all) {
const items = buildItems(extractAllItems(all));
return {items: items};
}
function extractAllItems(all) {
const groups = all.groups;
let extractedItems = {};
for (let groupName in groups) {
extractItemsFromGroup(groups, groupName, extractedItems);
}
return extractedItems;
}
function extractItemsFromGroup(groups, groupName, addItemsTo) {
const items = groups[groupName].items;
for (let key in items) {
const item = cloneObject(items[key]);
item.groupName = groupName;
addItemsTo[key] = item;
}
}
const toInt = (string) => Number.parseInt(string, 10);
function buildItems(flattenedItems) {
const items = [];
const ids = Object.keys(flattenedItems).map(toInt);
const sortedIds = ids.sort((id1, id2) => id1 - id2);
for (let id of sortedIds) {
let item = flattenedItems[id];
item.id = id;
items.push(item);
}
return items;
}
function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj));
}
|
Remove ranking from denormalization command
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
|
Update services by gsim aesthetics
|
import React, { PropTypes } from 'react'
import { connectFromRoute } from '../routes'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADED } from 'sparql-connect'
import ServiceList from './service-list.js'
function ServicesByGsimInputOrOutput({ loaded, services }){
if (loaded !== LOADED) return <span>loading services</span>
return <ServiceList services={services} />
}
const ServicesByGsimInput =
sparqlConnect.gsimInputServices(ServicesByGsimInputOrOutput)
const ServicesByGsimOuput =
sparqlConnect.gsimOutputServices(ServicesByGsimInputOrOutput)
function ServicesByGsimInputAndOutput({ gsimClass }) {
return (
<div>
<h2>Services with { gsimClass } as</h2>
Input:
<ServicesByGsimInput gsimClass={gsimClass} />
Output:
<ServicesByGsimOuput gsimClass={gsimClass} />
</div>
)
}
ServicesByGsimInputAndOutput.propTypes = {
gsimClass: PropTypes.string.isRequired
}
export default connectFromRoute(ServicesByGsimInputAndOutput)
|
import React, { PropTypes } from 'react'
import { connectFromRoute } from '../routes'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADED } from 'sparql-connect'
import ServiceList from './service-list.js'
function ServicesByGsimInputOrOutput({ loaded, services }){
if (loaded !== LOADED) return <span>loading services</span>
return <ServiceList services={services} />
}
const ServicesByGsimInput =
sparqlConnect.gsimInputServices(ServicesByGsimInputOrOutput)
const ServicesByGsimOuput =
sparqlConnect.gsimOutputServices(ServicesByGsimInputOrOutput)
function ServicesByGsimInputAndOutput({ gsimClass }) {
return (
<div>
<h2>Inputs</h2>
<ServicesByGsimInput gsimClass={gsimClass} />
<h2>Output</h2>
<ServicesByGsimOuput gsimClass={gsimClass} />
</div>
)
}
ServicesByGsimInputAndOutput.propTypes = {
gsimClass: PropTypes.string.isRequired
}
export default connectFromRoute(ServicesByGsimInputAndOutput)
|
Correct instructions for setting the view script
|
<?php
/**
* An alternative view script for the 'home' template
*
* This view script renders predefined page properties as JSON. This view can
* be triggered by specifying view programmatically or by requesting the page
* with GET param 'view':
*
* Option A: (via $view object) $view->script = 'json';
* Option B: http://www.example.com/?view=json
* Option C: (via $page object) $page->view('json');
*
*/
// skip layout for this view
$this->layout = null;
// fill $data array with page properties
$data = array(
'id' => $page->id,
'name' => $page->name,
'url' => $page->url,
'title' => $page->title,
'body' => $page->body,
'sidebar' => $page->sidebar,
);
// output $data array as JSON string
header('Content-Type: application/json');
echo json_encode($data);
|
<?php
/**
* An alternative view script for the 'home' template
*
* This view script renders predefined page properties as JSON. This view can
* be triggered by specifying view programmatically or by requesting the page
* with GET param 'view':
*
* Option A: (via $view object) $view->view = 'json';
* Option B: http://www.example.com/?view=json
* Option C: (via $page object) $page->view = 'json';
*
*/
// skip layout for this view
$this->layout = null;
// fill $data array with page properties
$data = array(
'id' => $page->id,
'name' => $page->name,
'url' => $page->url,
'title' => $page->title,
'body' => $page->body,
'sidebar' => $page->sidebar,
);
// output $data array as JSON string
header('Content-Type: application/json');
echo json_encode($data);
|
Create path if it doesnt exists
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
path = "downloads"
class OnlineparticipationdatasetPipeline(object):
def process_item(self, item, spider):
return item
class JsonWriterPipeline(object):
def open_spider(self, spider):
if not os.path.isdir(path):
os.makedirs(path)
self.file = open("downloads/items_"+spider.name+".json", 'wb')
self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter
class OnlineparticipationdatasetPipeline(object):
def process_item(self, item, spider):
return item
class JsonWriterPipeline(object):
def open_spider(self, spider):
self.file = open("downloads/items_"+spider.name+".json", 'wb')
self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
|
Set the secure flag for both our cookies
|
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.environ.get('SENTRY_DSN'),
}
ip_check = os.environ.get('RESTRICT_IPS', False)
RESTRICT_IPS = ip_check == 'True' or ip_check == '1'
ALLOWED_IPS = []
ALLOWED_IP_RANGES = ['165.225.80.0/22', '193.240.203.32/29']
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
|
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.environ.get('SENTRY_DSN'),
}
ip_check = os.environ.get('RESTRICT_IPS', False)
RESTRICT_IPS = ip_check == 'True' or ip_check == '1'
ALLOWED_IPS = []
ALLOWED_IP_RANGES = ['165.225.80.0/22', '193.240.203.32/29']
SECURE_SSL_REDIRECT = True
# XXX: This needs to be made longer once it is confirmed it works as desired
SECURE_HSTS_SECONDS = 31536000
|
Fix running individual tests with 'test' task
Undo overwriting of existing 'test' task from commit 3d70678, while preserving
intention of linting before tests.
|
/*
* grunt-contrib-watch
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/**/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
watch: {
all: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'nodeunit'],
},
},
nodeunit: {
tests: ['test/tasks/*_test.js'],
},
});
// Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
grunt.registerTask('test', function(file) {
grunt.task.run('jshint');
grunt.config('nodeunit.tests', String(grunt.config('nodeunit.tests')).replace('*', file || '*'));
grunt.task.run('nodeunit');
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-internal');
grunt.registerTask('default', ['test', 'build-contrib']);
};
|
/*
* grunt-contrib-watch
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/**/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
watch: {
all: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'nodeunit'],
},
},
nodeunit: {
tests: ['test/tasks/*_test.js'],
},
});
// Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
grunt.registerTask('test', function(file) {
grunt.config('nodeunit.tests', String(grunt.config('nodeunit.tests')).replace('*', file || '*'));
grunt.task.run('nodeunit');
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-internal');
grunt.registerTask('test', ['jshint', 'nodeunit']);
grunt.registerTask('default', ['test', 'build-contrib']);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.