text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Update database-uri and tweet-interval to use properties in config.js
|
var config = require('./config'),
Twit = require('twit'),
mongoose = require('mongoose');
var T = new Twit(config.oauth_creds),
quotes = mongoose.model('quotes', {msg: String, src: String});
var tweet = function () {
var promise = quotes.count().exec();
promise.then(function (cnt) {
var n = Math.floor(Math.random() * cnt);
return quotes.findOne({}).skip(n).exec();
}).then(function (quote) {
var msg = quote.msg + '\n' + quote.src;
T.post('statuses/update', {status: msg}, function (err, reply) {
if (err) console.dir(err);
console.log('--->>>');
console.log(new Date);
console.log(msg);
});
}).end();
};
mongoose.connect(config.db_uri);
setInterval(tweet, config.tweet_interval);
|
var config = require('./config'),
Twit = require('twit'),
mongoose = require('mongoose');
var T = new Twit(config.oauth_creds),
quotes = mongoose.model('quotes', {msg: String, src: String});
var tweet = function () {
var promise = quotes.count().exec();
promise.then(function (cnt) {
var n = Math.floor(Math.random() * cnt);
return quotes.findOne({}).skip(n).exec();
}).then(function (quote) {
var msg = quote.msg + '\n' + quote.src;
T.post('statuses/update', {status: msg}, function (err, reply) {
if (err) console.dir(err);
console.log('--->>>');
console.log(new Date);
console.log(msg);
});
}).end();
};
mongoose.connect('mongodb://tweetbot:kdznbmfsib@paulo.mongohq.com:10098/ntalbs-mongodb');
setInterval(tweet, 5000);
|
Test for expected and unexpected checks
|
from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
"com.google.fonts/check/038", # Fontforge
"com.google.fonts/check/039", # Fontforge
):
return False, "Skipping external tools."
return True, None
def test_external_specification():
"""Test the creation of external specifications."""
specification = spec_factory(default_section=Section("Dalton Maag OpenType"))
specification.set_check_filter(check_filter)
specification.auto_register(
globals(), spec_imports=["fontbakery.specifications.opentype"])
# Probe some tests
expected_tests = ["com.google.fonts/check/002", "com.google.fonts/check/180"]
specification.test_expected_checks(expected_tests)
# Probe tests we don't want
assert "com.google.fonts/check/035" not in specification._check_registry.keys()
assert len(specification.sections) > 1
|
from fontbakery.checkrunner import Section
from fontbakery.fonts_spec import spec_factory
def check_filter(checkid, font=None, **iterargs):
if checkid in (
"com.google.fonts/check/035", # ftxvalidator
"com.google.fonts/check/036", # ots-sanitize
"com.google.fonts/check/037", # Font Validator
"com.google.fonts/check/038", # Fontforge
"com.google.fonts/check/039", # Fontforge
):
return False, "Skipping external tools."
return True, None
def test_external_specification():
"""Test the creation of external specifications."""
specification = spec_factory(default_section=Section("Dalton Maag OpenType"))
specification.set_check_filter(check_filter)
specification.auto_register(
globals(), spec_imports=['fontbakery.specifications.opentype'])
assert len(specification.sections) > 1
|
Switch to regexp based matching of date instead of dateutil
|
import re
from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = "KAL's Cartoon"
language = 'en'
url = 'http://www.economist.com'
start_date = '2006-01-05'
rights = 'Kevin Kallaugher'
class Crawler(CrawlerBase):
history_capable_days = 1000
schedule = 'Th'
def crawl(self, pub_date):
article_list = self.parse_page('http://www.economist.com/research/articlesBySubject/display.cfm?id=8717275&startRow=1&endrow=500')
article_list.remove('.web-only')
for block in article_list.root.cssselect('.article-list .block'):
date = block.cssselect('.date')[0].text_content()
regexp = pub_date.strftime('%b %d(st|nd|rd|th) %Y')
if not re.match(regexp, date):
continue
anchor = block.cssselect('h2 a')[0]
if "KAL's cartoon" not in anchor.text_content():
continue
page = self.parse_page(anchor.get('href'))
return CrawlerResult(page.src('.content-image-full img'))
|
from dateutil.parser import parse
from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = "KAL's Cartoon"
language = 'en'
url = 'http://www.economist.com'
start_date = '2006-01-05'
rights = 'Kevin Kallaugher'
class Crawler(CrawlerBase):
history_capable_days = 1000
schedule = 'Th'
def crawl(self, pub_date):
article_list = self.parse_page('http://www.economist.com/research/articlesBySubject/display.cfm?id=8717275&startRow=1&endrow=500')
article_list.remove('.web-only')
for block in article_list.root.cssselect('.article-list .block'):
date = block.cssselect('.date')[0]
if pub_date != parse(date.text_content()).date():
continue
anchor = blockdate.cssselect('h2 a')[0]
if "KAL's cartoon" not in anchor.text_content():
continue
page = self.parse_page(anchor.get('href'))
return CrawlerResult(page.src('.content-image-full img'))
|
Make reverse migration for lot_type run
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations, connection
from lots.models import LotType, Lot
from revenue.models import Fee, Receipt
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", "LotType")
LotType(name="Casa").save()
LotType(name="Lote").save()
def remove_data(apps, schema_editor):
with connection.cursor() as cursor:
cursor.execute('DELETE FROM lots_lot_contacts')
cursor.execute('DELETE FROM lots_contact')
cursor.execute('DELETE FROM lots_lot')
cursor.execute('DELETE FROM lots_lottype')
class Migration(migrations.Migration):
dependencies = [
('lots', '0001_initial'),
]
operations = [
migrations.RunPython(load_data, remove_data)
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations
from lots.models import LotType, Lot
from revenue.models import Fee, Receipt
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", "LotType")
LotType(name="Casa").save()
LotType(name="Lote").save()
def remove_data(apps, schema_editor):
Receipt.objects.all().delete()
Fee.objects.all().delete()
Lot.objects.all().delete()
LotType.objects.all().delete()
class Migration(migrations.Migration):
dependencies = [
('lots', '0001_initial'),
]
operations = [
migrations.RunPython(load_data, remove_data)
]
|
Normalize module name before processing
|
<?php
namespace ZF\ApiFirstAdmin\Model;
use ZF\Configuration\ResourceFactory as ConfigResourceFactory;
use ZF\Configuration\ModuleUtils;
class CodeConnectedRpcFactory
{
/**
* @var ConfigResourceFactory
*/
protected $configFactory;
/**
* @var ModuleUtils
*/
protected $modules;
/**
* @param ModuleUtils $modules
* @param ConfigResource $config
*/
public function __construct(ModuleUtils $modules, ConfigResourceFactory $configFactory)
{
$this->modules = $modules;
$this->config = $config;
}
/**
* @param string $module
* @return CodeConnectedRpc
*/
public function factory($module)
{
$module = $this->normalizeModuleName($module);
if (isset($this->models[$module])) {
return $this->models[$module];
}
$config = $this->configFactory->factory($module);
$this->models[$module] = new CodeConnectedRpc($module, $this->modules, $config);
return $this->models[$module];
}
/**
* @param string $name
* @return string
*/
protected function normalizeModuleName($name)
{
return str_replace('\\', '.', $name);
}
}
|
<?php
namespace ZF\ApiFirstAdmin\Model;
use ZF\Configuration\ResourceFactory as ConfigResourceFactory;
use ZF\Configuration\ModuleUtils;
class CodeConnectedRpcFactory
{
/**
* @var ConfigResourceFactory
*/
protected $configFactory;
/**
* @var ModuleUtils
*/
protected $modules;
/**
* @param ModuleUtils $modules
* @param ConfigResource $config
*/
public function __construct(ModuleUtils $modules, ConfigResourceFactory $configFactory)
{
$this->modules = $modules;
$this->config = $config;
}
/**
* @param string $module
* @return CodeConnectedRpc
*/
public function factory($module)
{
if (isset($this->models[$module])) {
return $this->models[$module];
}
$config = $this->configFactory->factory($module);
$this->models[$module] = new CodeConnectedRpc($module, $this->modules, $config);
return $this->models[$module];
}
}
|
Set analyst default pprof port to 0
|
package config
import (
"log"
"github.com/bradylove/envstruct"
)
type Config struct {
Addr string `env:"ADDR,required"`
IntraAddr string `env:"INTRA_ADDR,required"`
TalariaNodeAddr string `env:"TALARIA_NODE_ADDR,required"`
TalariaSchedulerAddr string `env:"TALARIA_SCHEDULER_ADDR,required"`
TalariaNodeList []string `env:"TALARIA_NODE_LIST,required"`
IntraAnalystList []string `env:"INTRA_ANALYST_LIST,required"`
PprofAddr string `env:"PPROF_ADDR"`
ToAnalyst map[string]string
}
func Load() *Config {
conf := Config{
PprofAddr: "localhost:0",
}
if err := envstruct.Load(&conf); err != nil {
log.Fatalf("Invalid config: %s", err)
}
if len(conf.TalariaNodeList) != len(conf.IntraAnalystList) {
log.Fatalf("List lengths of TALARIA_NODE_LIST and INTRA_ANALYST_LIST must match")
}
conf.ToAnalyst = make(map[string]string)
for i := range conf.IntraAnalystList {
conf.ToAnalyst[conf.TalariaNodeList[i]] = conf.IntraAnalystList[i]
}
return &conf
}
|
package config
import (
"log"
"github.com/bradylove/envstruct"
)
type Config struct {
Addr string `env:"ADDR,required"`
IntraAddr string `env:"INTRA_ADDR,required"`
TalariaNodeAddr string `env:"TALARIA_NODE_ADDR,required"`
TalariaSchedulerAddr string `env:"TALARIA_SCHEDULER_ADDR,required"`
TalariaNodeList []string `env:"TALARIA_NODE_LIST,required"`
IntraAnalystList []string `env:"INTRA_ANALYST_LIST,required"`
PprofAddr string `env:"PPROF_ADDR"`
ToAnalyst map[string]string
}
func Load() *Config {
conf := Config{
PprofAddr: "localhost:6063",
}
if err := envstruct.Load(&conf); err != nil {
log.Fatalf("Invalid config: %s", err)
}
if len(conf.TalariaNodeList) != len(conf.IntraAnalystList) {
log.Fatalf("List lengths of TALARIA_NODE_LIST and INTRA_ANALYST_LIST must match")
}
conf.ToAnalyst = make(map[string]string)
for i := range conf.IntraAnalystList {
conf.ToAnalyst[conf.TalariaNodeList[i]] = conf.IntraAnalystList[i]
}
return &conf
}
|
Set light timer 1 hr back, 10pm-12am
|
import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, breather)
@scheduler.scheduled_job(trigger='cron', hour=22, minute=0)
def on_job():
"""Start at 10:00pm PT"""
print('STARTING BREATHER')
breather.restart()
@scheduler.scheduled_job(trigger='cron', hour=0, minute=1)
def off_job():
"""End at 12:01am PT"""
print("STOPPING BREATHER")
breather.shutdown()
if __name__ == '__main__':
scheduler.start()
waitress.serve(bottle_app, host='0.0.0.0', port=7000)
|
import bottle
import waitress
import controller
import breathe
from pytz import timezone
from apscheduler.schedulers.background import BackgroundScheduler
bottle_app = bottle.app()
scheduler = BackgroundScheduler()
scheduler.configure(timezone=timezone('US/Pacific'))
breather = breathe.Breathe()
my_controller = controller.Controller(bottle_app, breather)
@scheduler.scheduled_job(trigger='cron', hour=21, minute=0)
def on_job():
"""Start at 9:00pm PT"""
print('STARTING BREATHER')
breather.restart()
@scheduler.scheduled_job(trigger='cron', hour=23, minute=0)
def off_job():
"""End at 11:00pm PT"""
print("STOPPING BREATHER")
breather.shutdown()
if __name__ == '__main__':
scheduler.start()
waitress.serve(bottle_app, host='0.0.0.0', port=7000)
|
Reduce memory consumption by releasing binaries after a class is loaded
|
package loop;
import loop.runtime.Caller;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
public class LoopClassLoader extends ClassLoader {
final ConcurrentMap<String, byte[]> rawClasses = new ConcurrentHashMap<String, byte[]>();
final ConcurrentMap<String, Class<?>> loaded = new ConcurrentHashMap<String, Class<?>>();
public static volatile LoopClassLoader CLASS_LOADER = new LoopClassLoader();
public void put(String javaClass, byte[] bytes) {
if (null != rawClasses.putIfAbsent(javaClass, bytes))
throw new RuntimeException("Illegal attempt to define duplicate class");
}
@Override
protected Class findClass(String name)
throws ClassNotFoundException {
Class<?> clazz = loaded.get(name);
if (null != clazz)
return clazz;
final byte[] bytes = rawClasses.remove(name);
if (bytes != null) {
// We don't define loop classes in the parent class loader.
clazz = defineClass(name, bytes);
if (loaded.putIfAbsent(name, clazz) != null)
throw new RuntimeException("Attempted duplicate class definition for " + name);
return clazz;
}
return super.findClass(name);
}
public Class defineClass(String name, byte[] b) {
return defineClass(name, b, 0, b.length);
}
public static void reset() {
Caller.reset();
CLASS_LOADER = new LoopClassLoader();
Thread.currentThread().setContextClassLoader(CLASS_LOADER);
}
}
|
package loop;
import loop.runtime.Caller;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
public class LoopClassLoader extends ClassLoader {
final ConcurrentMap<String, byte[]> rawClasses = new ConcurrentHashMap<String, byte[]>();
final ConcurrentMap<String, Class<?>> loaded = new ConcurrentHashMap<String, Class<?>>();
public static volatile LoopClassLoader CLASS_LOADER = new LoopClassLoader();
public void put(String javaClass, byte[] bytes) {
if (null != rawClasses.putIfAbsent(javaClass, bytes))
throw new RuntimeException("Illegal attempt to define duplicate class");
}
@Override
protected Class findClass(String name)
throws ClassNotFoundException {
Class<?> clazz = loaded.get(name);
if (null != clazz)
return clazz;
final byte[] bytes = rawClasses.get(name);
if (bytes != null) {
// We don't define loop classes in the parent class loader.
clazz = defineClass(name, bytes);
if (loaded.putIfAbsent(name, clazz) != null)
throw new RuntimeException("Attempted duplicate class definition for " + name);
return clazz;
}
return super.findClass(name);
}
public Class defineClass(String name, byte[] b) {
return defineClass(name, b, 0, b.length);
}
public static void reset() {
Caller.reset();
CLASS_LOADER = new LoopClassLoader();
Thread.currentThread().setContextClassLoader(CLASS_LOADER);
}
}
|
Add Development Status :: 7 - Inactive classifier.
|
import os
import sys
from setuptools import setup, Extension
with open("README.rst") as fp:
long_description = fp.read()
extensions = []
if os.name == 'nt':
ext = Extension(
'trollius._overlapped', ['overlapped.c'], libraries=['ws2_32'],
)
extensions.append(ext)
requirements = ['six']
if sys.version_info < (3,):
requirements.append('futures')
setup(
name="trollius",
version="2.2.post2.dev0",
license="Apache License 2.0",
author='Victor Stinner',
author_email='victor.stinner@gmail.com',
description="Deprecated, unmaintained port of the asyncio module (PEP 3156) on Python 2",
long_description=long_description,
url="https://github.com/jamadden/trollius",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: Apache Software License",
"Development Status :: 7 - Inactive",
],
packages=[
"trollius",
],
zip_safe=False,
keywords="Deprecated Unmaintained asyncio backport",
ext_modules=extensions,
install_requires=requirements,
python_requires=">=2.7, < 3",
)
|
import os
import sys
from setuptools import setup, Extension
with open("README.rst") as fp:
long_description = fp.read()
extensions = []
if os.name == 'nt':
ext = Extension(
'trollius._overlapped', ['overlapped.c'], libraries=['ws2_32'],
)
extensions.append(ext)
requirements = ['six']
if sys.version_info < (3,):
requirements.append('futures')
setup(
name="trollius",
version="2.2.post2.dev0",
license="Apache License 2.0",
author='Victor Stinner',
author_email='victor.stinner@gmail.com',
description="Deprecated, unmaintained port of the asyncio module (PEP 3156) on Python 2",
long_description=long_description,
url="https://github.com/jamadden/trollius",
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: Apache Software License",
],
packages=[
"trollius",
],
zip_safe=False,
keywords="Deprecated Unmaintained asyncio backport",
ext_modules=extensions,
install_requires=requirements,
python_requires=">=2.7, < 3",
)
|
Modify arguments of post function
|
michishiki.api = {};
michishiki.api.uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/';
michishiki.api.getPost = function(options) {
var dfd = $.Deferred();
var api_uri = michishiki.api.uri + 'get_post.py';
var query_string = michishiki.api.utils.optionsToQueryString(options);
$.getJSON(api_uri + query_string, function(json) {
dfd.resolve(json);
});
return dfd.promise();
};
michishiki.api.post = function(posted_by, title, comment, localite, latitude, longitude) {
var dfd = $.Deferred();
var api_url = michishiki.api.uri + 'post.py';
var options = {
'posted_by': posted_by,
'title': title,
'comment': comment,
'localite': localite,
'latitude': latitude,
'longitude': longitude
};
var query_string = michishiki.api.utils.optionsToQueryString(options);
$.getJSON(api_uri + query_string, function(json) {
dfd.resolve(json);
});
return dfd.promise();
};
michishiki.api.utils = {};
michishiki.api.utils.optionsToQueryString = function(options) {
var querys = [];
for (var key in options) {
var q = key + '=' + options[key];
querys.push(q);
}
return '?' + querys.join('&');
};
|
michishiki.api = {};
michishiki.api.uri = 'http://amateras.wsd.kutc.kansai-u.ac.jp/~otsuka/michishiki_api_server/';
michishiki.api.getPost = function(options) {
var dfd = $.Deferred();
var api_uri = michishiki.api.uri + 'get_post.py';
var query_string = michishiki.api.utils.optionsToQueryString(options);
$.getJSON(api_uri + query_string, function(json) {
dfd.resolve(json);
});
return dfd.promise();
};
michishiki.api.post = function(options) {
var dfd = $.Deferred();
var api_url = michishiki.api.uri + 'post.py';
var query_string = michishiki.api.utils.optionsToQueryString(options);
$.getJSON(api_uri + query_string, function(json) {
dfd.resolve(json);
});
return dfd.promise();
};
michishiki.api.utils = {};
michishiki.api.utils.optionsToQueryString = function(options) {
var querys = [];
for (var key in options) {
var q = key + '=' + options[key];
querys.push(q);
}
return '?' + querys.join('&');
};
|
Use global classes for easier testing
|
// Webpack config to serve the JSX component with bundled styles
import path from 'path';
const demoPath = path.join(__dirname, './demo');
const sourcePath = path.join(__dirname, './src');
export default {
entry: {
js: [demoPath.concat('/render.js')],
},
output: {
path: demoPath,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.css$/,
loaders: [
'style-loader',
{
loader: 'css-loader',
query: {
modules: false,
},
},
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.resolve(__dirname, 'node_modules'),
sourcePath,
],
},
};
|
// Webpack config to serve the JSX component with bundled styles
import path from 'path';
const demoPath = path.join(__dirname, './demo');
const sourcePath = path.join(__dirname, './src');
export default {
entry: {
js: [demoPath.concat('/render.js')],
},
output: {
path: demoPath,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.css$/,
loaders: [
'style-loader',
{
loader: 'css-loader',
query: {
modules: true,
},
},
],
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.resolve(__dirname, 'node_modules'),
sourcePath,
],
},
};
|
Increase payload limit to 1.5MB
When editing a model, this allow the user to upload a 1MB file, rather
than something like a 925.3kB file, along with about 500kB of
description text.
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
let app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json({ limit: '1.5MB' }));
app.use('/api', api);
server = app.listen(port, () => {
resolve();
});
});
}
function stop() {
return new Promise((resolve, reject) => {
if (server === null) {
reject(new Error('The server is not running.'));
}
server.close(() => {
server = null;
resolve();
});
});
}
export default {
start,
stop
};
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
let app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json({ limit: '1MB' }));
app.use('/api', api);
server = app.listen(port, () => {
resolve();
});
});
}
function stop() {
return new Promise((resolve, reject) => {
if (server === null) {
reject(new Error('The server is not running.'));
}
server.close(() => {
server = null;
resolve();
});
});
}
export default {
start,
stop
};
|
Fix noqa location, bump version
|
"""
Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
import logging
# Add NullHandler to prevent logging warnings
logging.getLogger(__name__).addHandler(logging.NullHandler())
from rejected.consumer import ( # noqa: E402
Consumer,
ConsumerException,
MessageException,
ProcessingException,
PublishingConsumer,
SmartConsumer,
SmartPublishingConsumer)
__author__ = 'Gavin M. Roy <gavinmroy@gmail.com>'
__since__ = '2009-09-10'
__version__ = '3.20.8'
__all__ = [
'__author__',
'__since__',
'__version__',
'Consumer',
'ConsumerException',
'MessageException',
'ProcessingException',
'PublishingConsumer',
'SmartConsumer',
'SmartPublishingConsumer'
]
|
"""
Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
import logging
# Add NullHandler to prevent logging warnings
logging.getLogger(__name__).addHandler(logging.NullHandler())
from rejected.consumer import (
Consumer,
ConsumerException,
MessageException,
ProcessingException,
PublishingConsumer,
SmartConsumer,
SmartPublishingConsumer) # noqa E402
__author__ = 'Gavin M. Roy <gavinmroy@gmail.com>'
__since__ = '2009-09-10'
__version__ = '3.20.7'
__all__ = [
'__author__',
'__since__',
'__version__',
'Consumer',
'ConsumerException',
'MessageException',
'ProcessingException',
'PublishingConsumer',
'SmartConsumer',
'SmartPublishingConsumer'
]
|
feat(app): Improve electron template on devtools usage
|
import { app, BrowserWindow, nativeTheme } from 'electron'
import path from 'path'
try {
if (process.platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
require('fs').unlinkSync(require('path').join(app.getPath('userData'), 'DevTools Extensions'))
}
} catch (_) { }
let mainWindow
function createWindow () {
/**
* Initial window options
*/
mainWindow = new BrowserWindow({
width: 1000,
height: 600,
useContentSize: true,
webPreferences: {
contextIsolation: true,
// More info: /quasar-cli/developing-electron-apps/electron-preload-script
preload: path.resolve(__dirname, process.env.QUASAR_ELECTRON_PRELOAD)
}
})
mainWindow.loadURL(process.env.APP_URL)
if (process.env.DEBUGGING) {
// if on DEV or Production with debug enabled
mainWindow.webContents.openDevTools()
} else {
// we're on production; no access to devtools pls
mainWindow.webContents.on('devtools-opened', () => {
mainWindow.webContents.closeDevTools()
})
}
mainWindow.on('closed', () => {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
|
import { app, BrowserWindow, nativeTheme } from 'electron'
import path from 'path'
try {
if (process.platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
require('fs').unlinkSync(require('path').join(app.getPath('userData'), 'DevTools Extensions'))
}
} catch (_) { }
let mainWindow
function createWindow () {
/**
* Initial window options
*/
mainWindow = new BrowserWindow({
width: 1000,
height: 600,
useContentSize: true,
webPreferences: {
contextIsolation: true,
// More info: /quasar-cli/developing-electron-apps/electron-preload-script
preload: path.resolve(__dirname, process.env.QUASAR_ELECTRON_PRELOAD)
}
})
mainWindow.loadURL(process.env.APP_URL)
mainWindow.on('closed', () => {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
|
Create logs directory if not exists
|
'use strict';
const fs = require('fs');
const path = require('path');
const bunyan = require('bunyan');
const config = require('config');
const pkg = require('../../package.json');
const level = process.env.LOG_LEVEL || (config.has('logger.level') ? config.get('logger.level') : 'info');
try {
fs.access(config.get('logger.path'), fs.constants.R_OK | fs.constants.W_OK);
} catch (error) {
if (error.code === 'ENOENT') {
fs.mkdirSync(config.get('logger.path'));
}
}
module.exports = bunyan.createLogger({
name: pkg.name,
streams: [
{
level: level,
stream: process.stdout
},
{
level: level,
path: path.resolve(config.get('logger.path'), pkg.name + '.log')
},
{
level: 'error',
path: path.resolve(config.get('logger.path'), pkg.name + '.error')
}
],
serializers: bunyan.stdSerializers
});
|
'use strict';
const path = require('path');
const bunyan = require('bunyan');
const config = require('config');
const pkg = require('../../package.json');
const level = process.env.LOG_LEVEL || (config.has('logger.level') ? config.get('logger.level') : 'info');
module.exports = bunyan.createLogger({
name: pkg.name,
streams: [
{
level: level,
stream: process.stdout
},
{
level: level,
path: path.resolve(config.get('logger.path'), pkg.name + '.log')
},
{
level: 'error',
path: path.resolve(config.get('logger.path'), pkg.name + '.error')
}
],
serializers: bunyan.stdSerializers
});
|
Add use of Game.character.current_location to example
|
from vengeance.game import Direction
from vengeance.game import Game
from vengeance.game import Location
go_up = Direction('up')
go_down = Direction('down')
go_up.opposite = go_down
go_in = Direction('in')
go_out = Direction('out')
go_in.opposite = go_out
go_west = Direction('west')
go_east = Direction('east')
go_west.opposite = go_east
church = Location('A Church', 'Tiny place of worship')
crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi')
coffin = Location('A Coffin', 'A tight squeeze and pitch dark')
cave = Location('A Cave')
church.add_exit(go_down, crypt)
crypt.add_one_way_exit(go_in, coffin)
crypt.add_exit(go_west, cave)
game = Game([church, crypt, coffin, cave])
# Move the player down from the church to the crypt
print("Current location: " + game.character.current_location.name)
game.process_input('d')
print("Current location: " + game.character.current_location.name)
game.run()
|
from vengeance.game import Direction
from vengeance.game import Game
from vengeance.game import Location
go_up = Direction('up')
go_down = Direction('down')
go_up.opposite = go_down
go_in = Direction('in')
go_out = Direction('out')
go_in.opposite = go_out
go_west = Direction('west')
go_east = Direction('east')
go_west.opposite = go_east
church = Location('A Church', 'Tiny place of worship')
crypt = Location('The Crypt', 'Dusty tomb filled with empty sarcophagi')
coffin = Location('A Coffin', 'A tight squeeze and pitch dark')
cave = Location('A Cave')
church.add_exit(go_down, crypt)
crypt.add_one_way_exit(go_in, coffin)
crypt.add_exit(go_west, cave)
game = Game([church, crypt, coffin, cave])
# Move the player down from the church to the crypt
game.process_input('d')
game.run()
|
Add sessions reducer to main reducer
|
import { combineReducers } from 'redux';
import audio from '../containers/Audio/reducer';
import midi from '../containers/Midi/reducer';
import login from '../containers/Login/reducer';
import map from '../containers/Map/reducer';
import messagesBox from '../containers/MessagesBox/reducer';
import metronome from '../containers/Metronome/reducer';
import modal from '../containers/Modal/reducer';
import paths from '../containers/Paths/reducer';
import search from '../containers/Search/reducer';
import sessions from '../containers/Sessions/reducer';
import settings from '../containers/Settings/reducer';
import sidebar from '../containers/Sidebar/reducer';
import sounds from '../containers/Sounds/reducer';
import spaces from '../containers/Spaces/reducer';
const rootReducer = combineReducers({
audio,
login,
map,
messagesBox,
metronome,
midi,
modal,
paths,
search,
sessions,
settings,
sidebar,
sounds,
spaces,
});
export default rootReducer;
|
import { combineReducers } from 'redux';
import audio from '../containers/Audio/reducer';
import midi from '../containers/Midi/reducer';
import login from '../containers/Login/reducer';
import map from '../containers/Map/reducer';
import messagesBox from '../containers/MessagesBox/reducer';
import metronome from '../containers/Metronome/reducer';
import modal from '../containers/Modal/reducer';
import paths from '../containers/Paths/reducer';
import search from '../containers/Search/reducer';
import settings from '../containers/Settings/reducer';
import sidebar from '../containers/Sidebar/reducer';
import sounds from '../containers/Sounds/reducer';
import spaces from '../containers/Spaces/reducer';
const rootReducer = combineReducers({
audio,
login,
map,
messagesBox,
metronome,
midi,
modal,
paths,
search,
settings,
sidebar,
sounds,
spaces,
});
export default rootReducer;
|
Fix for non-existent character folder bug
|
import os
import json
from serializable import Serializable
class Saves: #Only partially implemembted- only works for PlayerCharacters
#Because we want the user to be able to play on whatever world they want with whatever character
#they want, characters have to be stored independently of everything else
#We need to implement an aspect of this for things like the map, item locations, npc locations,
#And everything that has to do with the world state in a different location.
@staticmethod
def store(obj): #Currently only works for player characters
serialization = obj.serialize()
if obj.__class__.__name__ == "PlayerCharacter":
if not os.path.isdir("characters"):
os.makedirs("characters")
with open(os.path.join("characters", obj.name), 'w+') as f:
json.dump(serialization, f)
else:
pass #Needs to be implemented for saving the map and world state
@staticmethod
def unstore(name, path): #Currently only works for player characters
if os.path.isfile(os.path.join(path, name)):
with open(os.path.join(path, name), 'r') as f:
saved = json.load(f)
return Serializable.deserialize(saved)
return None
|
import os
import json
from serializable import Serializable
class Saves: #Only partially implemembted- only works for PlayerCharacters
#Because we want the user to be able to play on whatever world they want with whatever character
#they want, characters have to be stored independently of everything else
#We need to implement an aspect of this for things like the map, item locations, npc locations,
#And everything that has to do with the world state in a different location.
@staticmethod
def store(obj): #Currently only works for player characters
serialization = obj.serialize()
if obj.__class__.__name__ == "PlayerCharacter":
with open(os.path.join("characters", obj.name), 'w') as f:
json.dump(serialization, f)
else:
pass #Needs to be implemented for saving the map and world state
@staticmethod
def unstore(name, path): #Currently only works for player characters
if os.path.isfile(os.path.join(path, name)):
with open(os.path.join(path, name), 'r') as f:
saved = json.load(f)
return Serializable.deserialize(saved)
return None
|
Use local database namespace instead of package.
|
from flask_sqlalchemy import Model
from __init__ import db
class User(Model):
__tablename__ = "user"
ROLE_ADMIN = 0
ROLE_USER = 1
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(64), index=True)
username = db.Column(db.Unicode(20), index=True)
password_hash = db.Column(db.Unicode(120))
role = db.Column(db.Integer, default=ROLE_USER)
postings = db.relationship("Posting", backref="user")
class Posting(Model):
__tablename__ = "posting"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Unicode(64), index=True)
description = db.Column(1200)
price = db.Column(db.Integer, default=100)
user_id = db.ForeignKey("user.id", index=True)
|
from flask_sqlalchemy import Model
from sqlalchemy import Column, Integer, Unicode, UnicodeText, ForeignKey
from sqlalchemy.orm import relationship
class User(Model):
__tablename__ = "user"
ROLE_ADMIN = 0
ROLE_USER = 1
id = Column(Integer, primary_key=True)
name = Column(Unicode(64), index=True)
username = Column(Unicode(20), index=True)
password_hash = Column(Unicode(120))
role = Column(Integer, default=ROLE_USER)
postings = relationship("Posting", backref="user")
class Posting(Model):
__tablename__ = "posting"
id = Column(Integer, primary_key=True)
title = Column(Unicode(64), index=True)
description = Column(1200)
price = Column(Integer, default=100)
user_id = ForeignKey("user.id", index=True)
|
Add missing comment and remove another redundant one
|
<?php
declare (strict_types = 1);
namespace Mihaeu\PhpDependencies;
use PhpParser\Parser as BaseParser;
class Parser
{
/** @var BaseParser */
private $parser;
/**
* @param $parser
*/
public function __construct(BaseParser $parser)
{
$this->parser = $parser;
}
/**
* @param PhpFileCollection $files
*
* @return Ast
*/
public function parse(PhpFileCollection $files) : Ast
{
$ast = new Ast();
$files->each(function (PhpFile $file) use ($ast) {
$node = $this->parser->parse($file->code());
$ast->add($file, $node);
});
return $ast;
}
}
|
<?php
declare (strict_types = 1);
namespace Mihaeu\PhpDependencies;
use PhpParser\Parser as BaseParser;
class Parser
{
/** @var BaseParser */
private $parser;
/**
* Parser constructor.
*
* @param $parser
*/
public function __construct(BaseParser $parser)
{
$this->parser = $parser;
}
public function parse(PhpFileCollection $files) : Ast
{
$ast = new Ast();
$files->each(function (PhpFile $file) use ($ast) {
$node = $this->parser->parse($file->code());
$ast->add($file, $node);
});
return $ast;
}
}
|
[Chaco] Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
|
from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
|
from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from drag_zoom import DragZoom
from enthought.enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool
from highlight_tool import HighlightTool
from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
from pan_tool import PanTool
from point_marker import PointMarker
from range_selection import RangeSelection
from range_selection_2d import RangeSelection2D
from range_selection_overlay import RangeSelectionOverlay
from regression_lasso import RegressionLasso, RegressionOverlay
from save_tool import SaveTool
from scatter_inspector import ScatterInspector
from select_tool import SelectTool
from simple_inspector import SimpleInspectorTool
from tracking_pan_tool import TrackingPanTool
from tracking_zoom import TrackingZoom
from traits_tool import TraitsTool
from zoom_tool import ZoomTool
# EOF
|
Add test for page that redirects
|
package com.opera.core.systems;
import org.junit.Assert;
import org.junit.Test;
public class NavigationTest extends TestBase
{
@Test
public void testBack()
{
getFixture("javascript.html");
getFixture("test.html");
getFixture("keys.html");
driver.navigate().back();
Assert.assertTrue(driver.getCurrentUrl().indexOf("test.html") > 0);
}
@Test
public void testForward()
{
driver.navigate().forward();
Assert.assertTrue(driver.getCurrentUrl().indexOf("keys.html") > 0);
}
@Test
public void testBack2()
{
driver.navigate().back();
driver.navigate().back();
Assert.assertTrue(driver.getCurrentUrl().indexOf("javascript.html") > 0);
}
@Test
public void testForward2()
{
driver.navigate().forward();
driver.navigate().forward();
Assert.assertTrue(driver.getCurrentUrl().indexOf("keys.html") > 0);
}
@Test
public void testHttpRedirect() throws Exception {
driver.get("http://t/core/bts/javascript/CORE-26410/003-2.php");
// Wait for redirect
Thread.sleep(1000);
Assert.assertEquals("http://t/core/bts/javascript/CORE-26410/001-3.php",
driver.getCurrentUrl());
}
}
|
package com.opera.core.systems;
import org.junit.Assert;
import org.junit.Test;
public class NavigationTest extends TestBase
{
@Test
public void testBack()
{
getFixture("javascript.html");
getFixture("test.html");
getFixture("keys.html");
driver.navigate().back();
Assert.assertTrue(driver.getCurrentUrl().indexOf("test.html") > 0);
}
@Test
public void testForward()
{
driver.navigate().forward();
Assert.assertTrue(driver.getCurrentUrl().indexOf("keys.html") > 0);
}
@Test
public void testBack2()
{
driver.navigate().back();
driver.navigate().back();
Assert.assertTrue(driver.getCurrentUrl().indexOf("javascript.html") > 0);
}
@Test
public void testForward2()
{
driver.navigate().forward();
driver.navigate().forward();
Assert.assertTrue(driver.getCurrentUrl().indexOf("keys.html") > 0);
}
}
|
Support for two headers with same name.
I found an example file with two different firmware version header lines. This caused a React error due to duplicate item keys.
Fixed by appending the index to the name.
|
import React, { PropTypes } from 'react';
import { Table } from 'react-bootstrap';
import { List } from 'immutable';
import moment from 'moment';
import HeaderRow from './HeaderRow';
function HeaderDisplay(props) {
let headers = props.headers;
const rows = headers.map((h, index) => {
const name = h.get('name');
const value = h.get('value').toString();
return (
<HeaderRow key={`${name}${index}`} name={name} value={value} />
);
});
const { flightDate, timezone } = props;
return (
<Table striped>
<tbody>
<HeaderRow key="Flight date" name="Flight date" value={flightDate.format('dddd, LL')} />
<HeaderRow key="Timezone" name="Time zone" value={`${timezone} (UTC ${flightDate.format('Z')})`} />
{rows}
</tbody>
</Table>
);
}
HeaderDisplay.propTypes = {
headers: PropTypes.instanceOf(List).isRequired,
flightDate: PropTypes.instanceOf(moment).isRequired,
timezone: PropTypes.string.isRequired
};
export default HeaderDisplay;
|
import React, { PropTypes } from 'react';
import { Table } from 'react-bootstrap';
import { List } from 'immutable';
import moment from 'moment';
import HeaderRow from './HeaderRow';
function HeaderDisplay(props) {
let headers = props.headers;
const rows = headers.map(h => {
const name = h.get('name');
const value = h.get('value').toString();
return (
<HeaderRow key={name} name={name} value={value} />
);
});
const { flightDate, timezone } = props;
return (
<Table striped>
<tbody>
<HeaderRow key="Flight date" name="Flight date" value={flightDate.format('dddd, LL')} />
<HeaderRow key="Timezone" name="Time zone" value={`${timezone} (UTC ${flightDate.format('Z')})`} />
{rows}
</tbody>
</Table>
);
}
HeaderDisplay.propTypes = {
headers: PropTypes.instanceOf(List).isRequired,
flightDate: PropTypes.instanceOf(moment).isRequired,
timezone: PropTypes.string.isRequired
};
export default HeaderDisplay;
|
Add source credit too footer.
|
import React from 'react';
class Footer extends React.Component {
render() {
// jshint ignore:start
return (
<footer>
<div className="logo" />
<h4>Holder de ord © 2014 - {new Date().getFullYear()}</h4>
<div>Referater fra <a href="http://data.stortinget.no">data.stortinget.no</a> under <a href="http://data.norge.no/NLOD">NLOD</a>.</div>
<div>
<a href="https://www.holderdeord.no/" alt="Holder de ord">holderdeord.no</a>
·
<a href="https://twitter.com/holderdeord/" alt="Holder de ord på Twitter">@holderdeord</a>
</div>
</footer>
);
// jshint ignore:end
}
}
module.exports = Footer;
|
import React from 'react';
class Footer extends React.Component {
render() {
// jshint ignore:start
return (
<footer>
<div className="logo" />
<h4>Holder de ord © 2014 - {new Date().getFullYear()}</h4>
<div>
<a href="https://www.holderdeord.no/" alt="Holder de ord">holderdeord.no</a>
·
<a href="https://twitter.com/holderdeord/" alt="Holder de ord på Twitter">@holderdeord</a>
</div>
</footer>
);
// jshint ignore:end
}
}
module.exports = Footer;
|
Fix failing runtime compiler tests
|
package org.twig.compiler;
import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigRuntimeException;
import org.twig.template.Template;
public class RuntimeTemplateCompilerTests {
@Test
public void testCompileJavaCode() throws TwigRuntimeException {
RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());
String sourceCode = "package org.twig.template;\n\n"
+ "public class TestTemplate extends org.twig.template.Template {\n"
+ " protected String doRender(Context context) { return \"foo\"; }\n"
+ " public String getTemplateName() { return \"foo\"; }\n"
+ "}\n";
Template template = runtimeCompiler.compile(sourceCode, "org.twig.template.TestTemplate");
Assert.assertEquals("Complied class method render() should return \"foo\"", "foo", template.render());
}
@Test(expected = TwigRuntimeException.class)
public void testThrowsRuntimeErrorExceptionOnFailToCompile() throws TwigRuntimeException {
RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());
String sourceCode = "invalid java code";
runtimeCompiler.compile(sourceCode, "something");
}
}
|
package org.twig.compiler;
import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigRuntimeException;
import org.twig.template.Template;
public class RuntimeTemplateCompilerTests {
@Test
public void testCompileJavaCode() throws TwigRuntimeException {
RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());
String sourceCode = "package org.twig.template;\n\n"
+ "public class TestTemplate extends org.twig.template.Template {\n"
+ " protected String doRender(java.util.Map<String, ?> context) { return \"foo\"; }\n"
+ " public String getTemplateName() { return \"foo\"; }\n"
+ "}\n";
Template template = runtimeCompiler.compile(sourceCode, "org.twig.template.TestTemplate");
Assert.assertEquals("Complied class method render() should return \"foo\"", "foo", template.render());
}
@Test(expected = TwigRuntimeException.class)
public void testThrowsRuntimeErrorExceptionOnFailToCompile() throws TwigRuntimeException {
RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());
String sourceCode = "invalid java code";
runtimeCompiler.compile(sourceCode, "something");
}
}
|
Check final count of statements.
|
from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations, "Missing annotations."
assert 'agents' in ev.annotations.keys()
assert 'trigger' in ev.annotations.keys()
def test_ungrounded_usage():
rp = rlimsp.process_from_webservice('PMC3717945', with_grounding=False)
assert len(rp.statements) == 33, len(rp.statements)
def test_grounded_endpoint_with_pmids():
pmid_list = ['16403219', '22258404', '16961925', '22096607']
stmts = []
for pmid in pmid_list:
rp = rlimsp.process_from_webservice(pmid, id_type='pmid',
with_grounding=False)
assert len(rp.statements) > 10, len(rp.statements)
stmts.extend(rp.statements)
assert len(stmts) == 397, len(stmts)
return
|
from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations, "Missing annotations."
assert 'agents' in ev.annotations.keys()
assert 'trigger' in ev.annotations.keys()
def test_ungrounded_usage():
rp = rlimsp.process_from_webservice('PMC3717945', with_grounding=False)
assert len(rp.statements) == 33, len(rp.statements)
def test_grounded_endpoint_with_pmids():
pmid_list = ['16403219', '22258404', '16961925', '22096607']
for pmid in pmid_list:
rp = rlimsp.process_from_webservice(pmid, id_type='pmid',
with_grounding=False)
assert len(rp.statements) > 10, len(rp.statements)
|
Transform values in string.Template engine before substitution.
|
#!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, **kwargs):
"""Initialize string.Template."""
super(StringTemplate, self).__init__(**kwargs)
self.template = Template(template)
self.tolerant = tolerant
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
mapping = {name: self.str(value, tolerant=self.tolerant)
for name, value in mapping.items()
if value is not None or self.tolerant}
if self.tolerant:
return self.template.safe_substitute(mapping)
return self.template.substitute(mapping)
|
#!/usr/bin/env python
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False, **kwargs):
"""Initialize string.Template."""
super(StringTemplate, self).__init__(**kwargs)
self.template = Template(template)
self.tolerant = tolerant
def apply(self, mapping):
"""Apply a mapping of name-value-pairs to a template."""
if self.tolerant:
return self.template.safe_substitute(mapping)
return self.template.substitute(mapping)
|
Fix a bug introduced in the last commit
|
import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
appconfig = dev_appserver.LoadAppConfig(PROJECT_DIR, {},
default_partition='dev')[0]
def appid():
if have_appserver:
return get_application_id()
else:
try:
return appconfig.application.split('~', 1)[-1]
except ImportError, e:
raise Exception("Could not get appid. Is your app.yaml file missing? "
"Error was: %s" % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
|
import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
def appid():
if have_appserver:
return get_application_id()
else:
try:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
appconfig = dev_appserver.LoadAppConfig(PROJECT_DIR, {},
default_partition='dev')[0]
return appconfig.application.split('~', 1)[-1]
except ImportError, e:
raise Exception("Could not get appid. Is your app.yaml file missing? "
"Error was: %s" % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
|
Change transform option to jsx and not ts
|
module.exports = {
transform: {
"^.+\\.jsx?$": `<rootDir>/jest-preprocess.js`,
},
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`
},
testPathIgnorePatterns: [`node_modules`, `\\.cache`, `<rootDir>.*/public`],
transformIgnorePatterns: [`node_modules/(?!(gatsby|gatsby-script)/)`],
globals: {
__PATH_PREFIX__: ``,
},
testEnvironmentOptions: {
url: `http://localhost`
},
setupFiles: [`<rootDir>/loadershim.js`],
}
|
module.exports = {
transform: {
"^.+\\.[jt]sx?$": "<rootDir>/jest-preprocess.js",
},
moduleNameMapper: {
".+\\.(css|styl|less|sass|scss)$": `identity-obj-proxy`,
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": `<rootDir>/__mocks__/file-mock.js`
},
testPathIgnorePatterns: [`node_modules`, `\\.cache`, `<rootDir>.*/public`],
transformIgnorePatterns: [`node_modules/(?!(gatsby|gatsby-script)/)`],
globals: {
__PATH_PREFIX__: ``,
},
testEnvironmentOptions: {
url: `http://localhost`
},
setupFiles: [`<rootDir>/loadershim.js`],
}
|
Update Grunt deploy to use bundle
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
secret: grunt.file.readJSON('secret.json'),
// TODO: This won't rm removed resources automatically!
sftp: {
options: {
path: '<%= secret.path %>',
host: '<%= secret.host %>',
username: '<%= secret.username %>',
agent: process.env.SSH_AUTH_SOCK,
showProgress: true,
srcBasePath: '_site/',
createDirectories: true
},
all: {
files: {
'./': ['_site/**']
}
}
},
exec: {
build: 'bundle exec jekyll build'
}
});
grunt.registerTask('deploy', ['exec:build', 'sftp']);
};
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
secret: grunt.file.readJSON('secret.json'),
// TODO: This won't rm removed resources automatically!
sftp: {
options: {
path: '<%= secret.path %>',
host: '<%= secret.host %>',
username: '<%= secret.username %>',
agent: process.env.SSH_AUTH_SOCK,
showProgress: true,
srcBasePath: '_site/',
createDirectories: true
},
all: {
files: {
'./': ['_site/**']
}
}
},
exec: {
build: 'jekyll b'
}
});
grunt.registerTask('deploy', ['exec:build', 'sftp']);
};
|
Revert "added version for templating"
This reverts commit 57693cd93e51b1ddcedb6be33a8e125c431371e5.
|
Package.describe({
name: 'ox2:chart',
summary: 'TESTING_DO_NOT_USE Chart components',
version: '2.0.0',
git: ' /* Fill me in! */ '
});
var S = 'server';
var C = 'client';
var CS = [C, S];
Npm.depends({
'chart.js': '2.6.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.4');
// Core
api.use([
'templating',
'ecmascript',
'underscore',
'less'
]);
// 3rd party
api.use([
'mquandalle:jade@0.4.9']);
api.addFiles('lib/oo-chart.jade', C);
api.addFiles('lib/oo-chart.js', C);
api.addFiles('lib/oo-chart.less', C);
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('ox2:chart');
api.addFiles('tests/oo-chart-tests.js');
});
|
Package.describe({
name: 'ox2:chart',
summary: 'TESTING_DO_NOT_USE Chart components',
version: '2.0.0',
git: ' /* Fill me in! */ '
});
var S = 'server';
var C = 'client';
var CS = [C, S];
Npm.depends({
'chart.js': '2.6.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.3.1');
// Core
api.use([
'templating@1.3.2',
'ecmascript',
'underscore',
'less'
]);
// 3rd party
api.use([
'mquandalle:jade@0.4.9']);
api.addFiles('lib/oo-chart.jade', C);
api.addFiles('lib/oo-chart.js', C);
api.addFiles('lib/oo-chart.less', C);
});
Package.onTest(function(api) {
api.use('tinytest');
api.use('ox2:chart');
api.addFiles('tests/oo-chart-tests.js');
});
|
Add @MappedSuperclass so user information is serialized.
|
package models;
import java.util.List;
import java.util.UUID;
import javax.persistence.MappedSuperclass;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* The base class for all of the models used by GTFS Data Manager.
* We don't use the Play model object because we're not saving things to a relational database.
* @author mattwigway
*/
@MappedSuperclass
public abstract class Model {
public Model () {
this.id = UUID.randomUUID().toString();
}
public String id;
/**
* The ID of the user who owns this object.
* For accountability, every object is owned by a user.
*/
@JsonIgnore
public String userId;
/**
* Notes on this object
*/
public List<Note> notes;
/**
* Get the user who owns this object.
* @return the User object
*/
public User getUser () {
return User.getUser(userId);
}
/**
* Set the owner of this object
*/
public void setUser (User user) {
userId = user.id != null ? user.id : User.getUserId(user.username);
}
}
|
package models;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* The base class for all of the models used by GTFS Data Manager.
* We don't use the Play model object because we're not saving things to a relational database.
* @author mattwigway
*/
public abstract class Model {
public Model () {
this.id = UUID.randomUUID().toString();
}
public String id;
/**
* The ID of the user who owns this object.
* For accountability, every object is owned by a user.
*/
@JsonIgnore
public String userId;
/**
* Notes on this object
*/
public List<Note> notes;
/**
* Get the user who owns this object.
* @return the User object
*/
public User getUser () {
return User.getUser(userId);
}
/**
* Set the owner of this object
*/
public void setUser (User user) {
userId = user.id != null ? user.id : User.getUserId(user.username);
}
}
|
Set research level in ticker
|
"""Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for entry in queue_entries:
if entry.module:
entry.module.level = entry.level
db.session.add(entry.module)
entry.module.pod.update_resources()
elif entry.research:
entry.research.level = entry.level
entry.research.researched = True
db.session.add(entry.research)
queue = entry.queue
db.session.delete(entry)
queue = queue.next_entry()
db.session.commit()
|
"""Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for entry in queue_entries:
if entry.module:
entry.module.level = entry.level
db.session.add(entry.module)
entry.module.pod.update_resources()
elif entry.research:
entry.research.level += 1
entry.research.researched = True
db.session.add(entry.research)
queue = entry.queue
db.session.delete(entry)
queue = queue.next_entry()
db.session.commit()
|
Add hint on improved API in 7.2
|
package com.camunda.bpm.demo.extension_attributes_for_user_tasks;
import java.util.Collection;
import java.util.Date;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty;
public class EscalationStartTaskListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
UserTask userTask = delegateTask.getBpmnModelElementInstance();
ExtensionElements extensionElements = userTask.getExtensionElements();
Collection<CamundaProperty> properties = extensionElements.getElementsQuery()
.filterByType(CamundaProperties.class)
.singleResult()
.getCamundaProperties();
for (CamundaProperty property : properties) {
if ("escalation1".equals(property.getAttributeValue("name"))) { // in 7.2 one can use: property.getCamundaName()
delegateTask.setDueDate(new Date());
}
}
}
}
|
package com.camunda.bpm.demo.extension_attributes_for_user_tasks;
import java.util.Collection;
import java.util.Date;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty;
public class EscalationStartTaskListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
UserTask userTask = delegateTask.getBpmnModelElementInstance();
ExtensionElements extensionElements = userTask.getExtensionElements();
Collection<CamundaProperty> properties = extensionElements.getElementsQuery()
.filterByType(CamundaProperties.class)
.singleResult()
.getCamundaProperties();
for (CamundaProperty property : properties) {
if ("escalation1".equals(property.getAttributeValue("name"))) {
delegateTask.setDueDate(new Date());
}
}
}
}
|
Make Nodes use TextLayoutBuilder's LayoutMeasureUtil
Summary:
Make Nodes use TextLayoutBuilder's LayoutMeasureUtil.
This cuts down a dependency.
Reviewed By: ahmedre
Differential Revision: D4151599
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.flat;
import android.graphics.Canvas;
import android.text.Layout;
import com.facebook.fbui.textlayoutbuilder.util.LayoutMeasureUtil;
/**
* DrawTextLayout is a DrawCommand that draw {@link Layout}.
*/
/* package */ final class DrawTextLayout extends AbstractDrawCommand {
private Layout mLayout;
private float mLayoutWidth;
private float mLayoutHeight;
/* package */ DrawTextLayout(Layout layout) {
setLayout(layout);
}
/**
* Assigns a new {@link Layout} to draw.
*/
public void setLayout(Layout layout) {
mLayout = layout;
mLayoutWidth = layout.getWidth();
mLayoutHeight = LayoutMeasureUtil.getHeight(layout);
}
public Layout getLayout() {
return mLayout;
}
public float getLayoutWidth() {
// mLayout.getWidth() doesn't return correct width of the text Layout
return mLayoutWidth;
}
public float getLayoutHeight() {
return mLayoutHeight;
}
@Override
protected void onDraw(Canvas canvas) {
float left = getLeft();
float top = getTop();
canvas.translate(left, top);
mLayout.draw(canvas);
canvas.translate(-left, -top);
}
}
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.flat;
import android.graphics.Canvas;
import android.text.Layout;
import com.facebook.fbui.widget.text.LayoutMeasureUtil;
/**
* DrawTextLayout is a DrawCommand that draw {@link Layout}.
*/
/* package */ final class DrawTextLayout extends AbstractDrawCommand {
private Layout mLayout;
private float mLayoutWidth;
private float mLayoutHeight;
/* package */ DrawTextLayout(Layout layout) {
setLayout(layout);
}
/**
* Assigns a new {@link Layout} to draw.
*/
public void setLayout(Layout layout) {
mLayout = layout;
mLayoutWidth = layout.getWidth();
mLayoutHeight = LayoutMeasureUtil.getHeight(layout);
}
public Layout getLayout() {
return mLayout;
}
public float getLayoutWidth() {
// mLayout.getWidth() doesn't return correct width of the text Layout
return mLayoutWidth;
}
public float getLayoutHeight() {
return mLayoutHeight;
}
@Override
protected void onDraw(Canvas canvas) {
float left = getLeft();
float top = getTop();
canvas.translate(left, top);
mLayout.draw(canvas);
canvas.translate(-left, -top);
}
}
|
Add name filter to expert requests [WAL-989]
|
import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.ExpertProvider
fields = []
class ExpertRequestFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
project = core_filters.URLFilter(view_name='project-detail', name='project__uuid')
project_uuid = django_filters.UUIDFilter(name='project__uuid')
class Meta(object):
model = models.ExpertRequest
fields = []
class ExpertBidFilter(django_filters.FilterSet):
expert_request = core_filters.URLFilter(view_name='expert-request-detail', name='expert__uuid')
expert_request_uuid = django_filters.UUIDFilter(name='expert__uuid')
class Meta(object):
model = models.ExpertBid
fields = []
|
import django_filters
from nodeconductor.core import filters as core_filters
from . import models
class ExpertProviderFilter(django_filters.FilterSet):
customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid')
customer_uuid = django_filters.UUIDFilter(name='customer__uuid')
class Meta(object):
model = models.ExpertProvider
fields = []
class ExpertRequestFilter(django_filters.FilterSet):
project = core_filters.URLFilter(view_name='project-detail', name='project__uuid')
project_uuid = django_filters.UUIDFilter(name='project__uuid')
class Meta(object):
model = models.ExpertRequest
fields = []
class ExpertBidFilter(django_filters.FilterSet):
expert_request = core_filters.URLFilter(view_name='expert-request-detail', name='expert__uuid')
expert_request_uuid = django_filters.UUIDFilter(name='expert__uuid')
class Meta(object):
model = models.ExpertBid
fields = []
|
Use compression on server side
|
const express = require('express');
const compression = require('compression');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
const Metascraper = require('metascraper');
// gzip the static resources before seding to browser, if the browser supports gzip compression
// Verification : Observe the response header Content-Encoding: gzip
app.use(compression());
// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../teletobit/build')));
// Answer API requests.
// app.get('/api', function (req, res) {
// res.send('{"message":"Hello from the custom server!"}');
// });
// Answer API requests.
app.get('/b/:url', function (req, res) {
// Get meta data from URL
Metascraper
.scrapeUrl(req.params.url)
.then((metadata) => {
res.set('Content-Type', 'application/json');
res.send(metadata);
})
.catch((error) => {
console.log("fail");
res.status(500).send({ error: error })
})
});
// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, '../teletobit/build', 'index.html'));
});
app.listen(PORT, function () {
console.log(`Listening on port ${PORT}`);
});
|
const express = require('express');
const compression = require('compression');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
const Metascraper = require('metascraper');
// gzip the static resources before seding to browser, if the browser supports gzip compression
// Verification : Observe the response header Content-Encoding: gzip
// app.use(compression());
// Priority serve any static files.
app.use(express.static(path.resolve(__dirname, '../teletobit/build')));
// Answer API requests.
// app.get('/api', function (req, res) {
// res.send('{"message":"Hello from the custom server!"}');
// });
// Answer API requests.
app.get('/b/:url', function (req, res) {
// Get meta data from URL
Metascraper
.scrapeUrl(req.params.url)
.then((metadata) => {
res.set('Content-Type', 'application/json');
res.send(metadata);
})
.catch((error) => {
console.log("fail");
res.status(500).send({ error: error })
})
});
// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
response.sendFile(path.resolve(__dirname, '../teletobit/build', 'index.html'));
});
app.listen(PORT, function () {
console.log(`Listening on port ${PORT}`);
});
|
Fix Node 10 localstorage in tests
|
// 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.
require('jest');
require('whatwg-fetch');
require('mock-local-storage');
Object.defineProperty(window, 'localStorage', {
value: global.localStorage,
configurable:true,
enumerable:true,
writable:true
});
window.$ = window.jQuery = require('jquery');
window._ = require('lodash');
window.Backbone = require('backbone');
// URL.createObjectURL() and Worker are referenced by brace so we add mock objects to prevent
// long warning messages from being printed while running the tests.
if (!window.URL) {
window.URL = {};
}
if (!window.URL.createObjectURL) {
window.URL.createObjectURL = function() {
return 'http://localhost';
};
}
window.Worker = function FakeWorker() {
this.postMessage = function () { };
this.onmessage = undefined;
};
window.alert = () => {};
// Setup enzyme's react adapter
const Enzyme = require('enzyme');
const EnzymeAdapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new EnzymeAdapter() });
|
// 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.
require('jest');
require('whatwg-fetch');
require('mock-local-storage');
window.localStorage = global.localStorage;
window.$ = window.jQuery = require('jquery');
window._ = require('lodash');
window.Backbone = require('backbone');
// URL.createObjectURL() and Worker are referenced by brace so we add mock objects to prevent
// long warning messages from being printed while running the tests.
if (!window.URL) {
window.URL = {};
}
if (!window.URL.createObjectURL) {
window.URL.createObjectURL = function() {
return 'http://localhost';
};
}
window.Worker = function FakeWorker() {
this.postMessage = function () { };
this.onmessage = undefined;
};
window.alert = () => {};
// Setup enzyme's react adapter
const Enzyme = require('enzyme');
const EnzymeAdapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new EnzymeAdapter() });
|
Fix: Make source of error clear in the message
|
/*
* Cordova Device Name Plugin
*
* ZeroConf plugin for Cordova/Phonegap
* by Sylvain Brejeon
*/
var argscheck = require('cordova/argscheck');
var channel = require('cordova/channel');
var utils = require('cordova/utils');
var exec = require('cordova/exec');
var cordova = require('cordova');
channel.createSticky('onDeviceNameReady');
// Tell cordova channel to wait on the DeviceNameReady event
channel.waitForInitialization('onDeviceNameReady');
function DeviceName() {
this.name = null;
var me = this;
channel.onCordovaReady.subscribe(function() {
me.get(function(info) {
me.name = info.name;
channel.onDeviceNameReady.fire();
}, function(e) {
utils.alert("[DeviceName] Error initializing Cordova: " + e);
});
});
}
DeviceName.prototype.get = function(successCallback, errorCallback) {
argscheck.checkArgs('fF', 'DeviceName.get', arguments);
exec(successCallback, errorCallback, "DeviceName", "get", []);
};
module.exports = new DeviceName();
|
/*
* Cordova Device Name Plugin
*
* ZeroConf plugin for Cordova/Phonegap
* by Sylvain Brejeon
*/
var argscheck = require('cordova/argscheck');
var channel = require('cordova/channel');
var utils = require('cordova/utils');
var exec = require('cordova/exec');
var cordova = require('cordova');
channel.createSticky('onDeviceNameReady');
// Tell cordova channel to wait on the DeviceNameReady event
channel.waitForInitialization('onDeviceNameReady');
function DeviceName() {
this.name = null;
var me = this;
channel.onCordovaReady.subscribe(function() {
me.get(function(info) {
me.name = info.name;
channel.onDeviceNameReady.fire();
}, function(e) {
utils.alert("[ERROR] Error initializing Cordova: " + e);
});
});
}
DeviceName.prototype.get = function(successCallback, errorCallback) {
argscheck.checkArgs('fF', 'DeviceName.get', arguments);
exec(successCallback, errorCallback, "DeviceName", "get", []);
};
module.exports = new DeviceName();
|
Fix DiscoveryManager for DI tests
|
package com.netflix.appinfo.providers;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.archaius.api.Config;
import com.netflix.discovery.DiscoveryManager;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
@Singleton
public class CustomAmazonInfoProviderInstanceConfigFactory implements EurekaInstanceConfigFactory {
private final Config configInstance;
private final Provider<AmazonInfo> amazonInfoProvider;
private EurekaInstanceConfig eurekaInstanceConfig;
@Inject
public CustomAmazonInfoProviderInstanceConfigFactory(Config configInstance, AmazonInfoProviderFactory amazonInfoProviderFactory) {
this.configInstance = configInstance;
this.amazonInfoProvider = amazonInfoProviderFactory.get();
}
@Override
public EurekaInstanceConfig get() {
if (eurekaInstanceConfig == null) {
eurekaInstanceConfig = new Ec2EurekaArchaius2InstanceConfig(configInstance, amazonInfoProvider);
// Copied from CompositeInstanceConfigFactory.get
DiscoveryManager.getInstance().setEurekaInstanceConfig(eurekaInstanceConfig);
}
return eurekaInstanceConfig;
}
}
|
package com.netflix.appinfo.providers;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.Ec2EurekaArchaius2InstanceConfig;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.archaius.api.Config;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
@Singleton
public class CustomAmazonInfoProviderInstanceConfigFactory implements EurekaInstanceConfigFactory {
private final Config configInstance;
private final Provider<AmazonInfo> amazonInfoProvider;
private EurekaInstanceConfig eurekaInstanceConfig;
@Inject
public CustomAmazonInfoProviderInstanceConfigFactory(Config configInstance, AmazonInfoProviderFactory amazonInfoProviderFactory) {
this.configInstance = configInstance;
this.amazonInfoProvider = amazonInfoProviderFactory.get();
}
@Override
public EurekaInstanceConfig get() {
if (eurekaInstanceConfig == null) {
eurekaInstanceConfig = new Ec2EurekaArchaius2InstanceConfig(configInstance, amazonInfoProvider);
}
return eurekaInstanceConfig;
}
}
|
Set the Project in code
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import mock
import pytest
PROJECT = 'python-docs-samples'
@pytest.fixture
def api_client_inject_project_id():
"""Patches all googleapiclient requests to replace 'YOUR_PROJECT_ID' with
the project ID."""
import googleapiclient.http
old_execute = googleapiclient.http.HttpRequest.execute
def new_execute(self, http=None, num_retries=0):
self.uri = self.uri.replace('YOUR_PROJECT_ID', PROJECT)
return old_execute(self, http=http, num_retries=num_retries)
with mock.patch(
'googleapiclient.http.HttpRequest.execute',
new=new_execute):
yield
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import mock
import pytest
PROJECT = os.environ['GCLOUD_PROJECT']
@pytest.fixture
def api_client_inject_project_id():
"""Patches all googleapiclient requests to replace 'YOUR_PROJECT_ID' with
the project ID."""
import googleapiclient.http
old_execute = googleapiclient.http.HttpRequest.execute
def new_execute(self, http=None, num_retries=0):
self.uri = self.uri.replace('YOUR_PROJECT_ID', PROJECT)
return old_execute(self, http=http, num_retries=num_retries)
with mock.patch(
'googleapiclient.http.HttpRequest.execute',
new=new_execute):
yield
|
FIX: Remove outdated function from list.
|
"""
This module defines styles redefine matplotlib rc parameters. In addition, you
can override pre-defined styles with "mplstyle" files in the current
directory and your home directory. The priority of style files is:
1. ./mplstyle
2. ~/.mplstyle
3. mpltools/style/
Style names should be specified as sections in "mplstyle" files. A simple
"mplstyle" file would look like:
[style1]
text.fontsize = 12
figure.dpi = 150
[style2]
text.fontsize = 10
font.family = 'serif'
Note that we use ConfigObj for parsing rc files so, unlike Matplotlib,
key/value pairs are separated by an equals sign and strings must be quoted.
Functions
=========
use
Redefine rc parameters using specified style.
lib
Style library.
baselib
Style library defined by mpltools (i.e. before user definitions).
"""
from core import *
|
"""
This module defines styles redefine matplotlib rc parameters. In addition, you
can override pre-defined styles with "mplstyle" files in the current
directory and your home directory. The priority of style files is:
1. ./mplstyle
2. ~/.mplstyle
3. mpltools/style/
Style names should be specified as sections in "mplstyle" files. A simple
"mplstyle" file would look like:
[style1]
text.fontsize = 12
figure.dpi = 150
[style2]
text.fontsize = 10
font.family = 'serif'
Note that we use ConfigObj for parsing rc files so, unlike Matplotlib,
key/value pairs are separated by an equals sign and strings must be quoted.
Functions
=========
use
Redefine rc parameters using specified style.
reset
Reset rc parameters to matplotlib defaults.
lib
Style library.
baselib
Style library defined by mpltools (i.e. before user definitions).
"""
from core import *
|
Fix bad typo (doesn't fix bug)
|
/*
* 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.
*/
package ca.joshuatacoma.bluesky;
import android.content.Context;
import android.util.Log;
import com.getpebble.android.kit.PebbleKit;
import ca.joshuatacoma.bluesky.BlueSkyConstants;
public class PebbleAckReceiver extends PebbleKit.PebbleAckReceiver
{
static final String TAG = "BlueSky";
public PebbleAckReceiver() {
super(BlueSkyConstants.APP_UUID);
}
@Override
public void receiveAck(
Context context,
int transactionId)
{
Log.d(TAG, "receiveAck(" + String.valueOf(transactionId) + ")");
PebbleState.recordAck(context, transactionId);
}
};
|
/*
* 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.
*/
package ca.joshuatacoma.bluesky;
import android.content.Context;
import android.util.Log;
import com.getpebble.android.kit.PebbleKit;
import ca.joshuatacoma.bluesky.BlueSkyConstants;
public class PebbleAckReceiver extends PebbleKit.PebbleAckReceiver
{
static final String TAG = "BlueSky";
public PebbleAckReceiver() {
super(BlueSkyConstants.APP_UUID);
}
@Override
public void receiveAck(
Context context,
int transactionId)
{
Log.d(TAG, "receiveAck(" + String.valueOf(transactionId) + ")");
PebbleState.recordNack(context, transactionId);
}
};
|
Replace function calls with set literals
|
import hashlib
class Algorithms(object):
NONE = 'none'
HS256 = 'HS256'
HS384 = 'HS384'
HS512 = 'HS512'
RS256 = 'RS256'
RS384 = 'RS384'
RS512 = 'RS512'
ES256 = 'ES256'
ES384 = 'ES384'
ES512 = 'ES512'
HMAC = {HS256, HS384, HS512}
RSA = {RS256, RS384, RS512}
EC = {ES256, ES384, ES512}
SUPPORTED = HMAC.union(RSA).union(EC)
ALL = SUPPORTED.union([NONE])
HASHES = {
HS256: hashlib.sha256,
HS384: hashlib.sha384,
HS512: hashlib.sha512,
RS256: hashlib.sha256,
RS384: hashlib.sha384,
RS512: hashlib.sha512,
ES256: hashlib.sha256,
ES384: hashlib.sha384,
ES512: hashlib.sha512,
}
KEYS = {}
ALGORITHMS = Algorithms()
|
import hashlib
class Algorithms(object):
NONE = 'none'
HS256 = 'HS256'
HS384 = 'HS384'
HS512 = 'HS512'
RS256 = 'RS256'
RS384 = 'RS384'
RS512 = 'RS512'
ES256 = 'ES256'
ES384 = 'ES384'
ES512 = 'ES512'
HMAC = set([HS256, HS384, HS512])
RSA = set([RS256, RS384, RS512])
EC = set([ES256, ES384, ES512])
SUPPORTED = HMAC.union(RSA).union(EC)
ALL = SUPPORTED.union([NONE])
HASHES = {
HS256: hashlib.sha256,
HS384: hashlib.sha384,
HS512: hashlib.sha512,
RS256: hashlib.sha256,
RS384: hashlib.sha384,
RS512: hashlib.sha512,
ES256: hashlib.sha256,
ES384: hashlib.sha384,
ES512: hashlib.sha512,
}
KEYS = {}
ALGORITHMS = Algorithms()
|
Fix for reflected XSS security issue.
|
<?php
// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');
if ($setting->getValue('maintenance') && !$user->isAdmin($user->getUserId($_POST['username']))) {
$_SESSION['POPUP'][] = array('CONTENT' => 'You are not allowed to login during maintenace.', 'TYPE' => 'info');
} else if ($user->checkLogin(@$_POST['username'], @$_POST['password']) ) {
empty($_POST['to']) ? $to = $_SERVER['PHP_SELF'] : $to = $_POST['to'];
$port = ($_SERVER["SERVER_PORT"] == "80" or $_SERVER["SERVER_PORT"] == "443") ? "" : (":".$_SERVER["SERVER_PORT"]);
$location = @$_SERVER['HTTPS'] === true ? 'https://' . $_SERVER['SERVER_NAME'] . $port . $to : 'http://' . $_SERVER['SERVER_NAME'] . $port . $to;
if (!headers_sent()) header('Location: ' . $location);
exit('<meta http-equiv="refresh" content="0; url=' . htmlspecialchars($location) . '"/>');
} else if (@$_POST['username'] && @$_POST['password']) {
$_SESSION['POPUP'][] = array('CONTENT' => 'Unable to login: '. $user->getError(), 'TYPE' => 'errormsg');
}
// Load login template
$smarty->assign('CONTENT', 'default.tpl');
?>
|
<?php
// Make sure we are called from index.php
if (!defined('SECURITY')) die('Hacking attempt');
if ($setting->getValue('maintenance') && !$user->isAdmin($user->getUserId($_POST['username']))) {
$_SESSION['POPUP'][] = array('CONTENT' => 'You are not allowed to login during maintenace.', 'TYPE' => 'info');
} else if ($user->checkLogin(@$_POST['username'], @$_POST['password']) ) {
empty($_POST['to']) ? $to = $_SERVER['PHP_SELF'] : $to = $_POST['to'];
$port = ($_SERVER["SERVER_PORT"] == "80" or $_SERVER["SERVER_PORT"] == "443") ? "" : (":".$_SERVER["SERVER_PORT"]);
$location = @$_SERVER['HTTPS'] === true ? 'https://' . $_SERVER['SERVER_NAME'] . $port . $to : 'http://' . $_SERVER['SERVER_NAME'] . $port . $to;
if (!headers_sent()) header('Location: ' . $location);
exit('<meta http-equiv="refresh" content="0; url=' . $location . '"/>');
} else if (@$_POST['username'] && @$_POST['password']) {
$_SESSION['POPUP'][] = array('CONTENT' => 'Unable to login: '. $user->getError(), 'TYPE' => 'errormsg');
}
// Load login template
$smarty->assign('CONTENT', 'default.tpl');
?>
|
Add URL and long-desc to metadata
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='pytest-relaxed',
version='0.0.1',
description='Relaxed test discovery/organization for pytest',
license='BSD',
url="https://github.com/bitprophet/pytest-relaxed",
author='Jeff Forcier',
author_email='jeff@bitprophet.org',
long_description="\n" + open('README.rst').read(),
packages=find_packages(),
entry_points={
# TODO: do we need to name the LHS 'pytest_relaxed' too? meh
'pytest11': ['relaxed = pytest_relaxed'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='pytest-relaxed',
version='0.0.1',
description='Relaxed test discovery/organization for pytest',
license='BSD',
author='Jeff Forcier',
author_email='jeff@bitprophet.org',
packages=find_packages(),
entry_points={
# TODO: do we need to name the LHS 'pytest_relaxed' too? meh
'pytest11': ['relaxed = pytest_relaxed'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python',
'Topic :: Software Development :: Testing',
],
)
|
Remove ES6 from ws/factor for stupid old browsers
|
var isNode = typeof window === 'undefined';
var WebSocket = isNode ? require('ws') : window.WebSocket;
/**
* Wraps a DOM socket with EventEmitter-like syntax.
* @param {Socket} socket
* @return {Socket}
*/
function wrapDOM(socket) {
function wrapHandler(event, fn) {
return function(ev) {
if (event === 'message') {
fn(ev.data);
} else {
fn(ev);
}
};
}
socket.on = function (event, listener) {
const wrapped = wrapHandler(event, listener);
socket.addEventListener(event, wrapped);
};
socket.once = function (event, listener) {
const wrapped = wrapHandler(event, listener);
socket.addEventListener(event, function(ev) {
wrapped(ev);
socket.removeEventListener(event, wrapped);
});
};
return socket;
}
/**
* Factory function to create a websocket. Lets us mock it later.
* @param {String} address
* @return {WebSocket}
*/
module.exports.create = function (address) {
var ws = new WebSocket(address);
if (!isNode) {
ws = wrapDOM(ws);
}
return ws;
};
|
var isNode = typeof window === 'undefined';
var WebSocket = isNode ? require('ws') : window.WebSocket;
/**
* Wraps a DOM socket with EventEmitter-like syntax.
* @param {Socket} socket
* @return {Socket}
*/
function wrapDOM(socket) {
function wrapHandler(event, fn) {
return (ev) => {
if (event === 'message') {
fn(ev.data);
} else {
fn(ev);
}
};
}
socket.on = function (event, listener) {
const wrapped = wrapHandler(event, listener);
socket.addEventListener(event, wrapped);
};
socket.once = function (event, listener) {
const wrapped = wrapHandler(event, listener);
socket.addEventListener(event, (ev) => {
wrapped(ev);
socket.removeEventListener(event, wrapped);
});
};
return socket;
}
/**
* Factory function to create a websocket. Lets us mock it later.
* @param {String} address
* @return {WebSocket}
*/
module.exports.create = function (address) {
var ws = new WebSocket(address);
if (!isNode) {
ws = wrapDOM(ws);
}
return ws;
};
|
Switch to hash-based history, fix redirect to /build on boot
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Redirect } from 'react-router';
import { syncReduxAndRouter } from 'redux-simple-router';
import createHashHistory from 'history/lib/createHashHistory';
import createStore from './store';
import App from './app';
import Build from './build';
import Json from './json';
import Html from './html';
import forms from './forms';
const history = createHashHistory();
const store = createStore({});
syncReduxAndRouter(history, store);
function mapFormsToRoutes({section, component}) {
return <Route path={section} component={component} />;
}
ReactDOM.render((
<Provider store={store} >
<Router history={history}>
<Redirect from="/" to="/build" />
<Route path="/" component={App}>
<Route path="build" component={Build}>
{
forms.map(mapFormsToRoutes)
}
</Route>
<Route path="output" component={Html}/>
<Route path="json" component={Json}/>
</Route>
</Router>
</Provider>
), document.getElementById('app'));
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Redirect } from 'react-router';
import { syncReduxAndRouter } from 'redux-simple-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import createStore from './store';
import App from './app';
import Build from './build';
import Json from './json';
import Html from './html';
import forms from './forms';
const history = createBrowserHistory();
const store = createStore({});
syncReduxAndRouter(history, store);
function mapFormsToRoutes({section, component}) {
return <Route path={section} component={component} />;
}
ReactDOM.render((
<Provider store={store} >
<Router history={history}>
<Route path="/" component={App}>
<Redirect from="" to="build" />
<Route path="build" component={Build}>
{
forms.map(mapFormsToRoutes)
}
</Route>
<Route path="output" component={Html}/>
<Route path="json" component={Json}/>
</Route>
</Router>
</Provider>
), document.getElementById('app'));
|
Add more time to mqtt.test.client
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTT1(MQTTTestCase):
def test(self):
self.assertEqual(True, True)
class TestMQTT2(MQTTTestCase):
def test(self):
self.assertEqual(True, True)
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
Fix typo in sg context menu selector
|
"use strict";
angular.module('arethusa.sg').directive('sgContextMenuSelector', [
'sg',
function(sg) {
return {
restrict: 'A',
scope: {
obj: '='
},
link: function(scope, element, attrs) {
scope.sg = sg;
function ancestorChain(chain) {
return arethusaUtil.map(chain, function(el) {
return el.short;
}).join(' > ');
}
scope.$watchCollection('obj.ancestors', function(newVal, oldVal) {
scope.heading = (newVal.length === 0) ?
'Select Smyth Categories' :
ancestorChain(newVal);
});
},
templateUrl: 'templates/arethusa.sg/sg_context_menu_selector.html'
};
}
]);
|
"use strict";
angular.module('arethusa.sg').directive('sgContextMenuSelector', [
'sg',
function(sg) {
return {
restrict: 'A',
scope: {
obj: '='
},
link: function(scope, element, attrs) {
scope.sg = sg;
function ancestorChain(chain) {
arethusaUtil.map(chain, function(el) {
return el.short;
}).join(' > ');
}
scope.$watchCollection('obj.ancestors', function(newVal, oldVal) {
scope.heading = (newVal.length === 0) ?
'Select Smyth Categories' :
ancestorChain(newVal);
});
},
templateUrl: 'templates/arethusa.sg/sg_context_menu_selector.html'
};
}
]);
|
Fix undefined in homepage, bugs and repo url
|
'use strict';
/**
* Ask for Github account info.
*/
module.exports = function () {
const done = this.async();
let suggestedGithubUsername;
if (this.authorName && 'string' === typeof this.authorName) {
suggestedGithubUsername = this.authorName.toLowerCase().replace(/\s/g, '');
}
this.prompt([
{
name: 'githubConfirm',
type: 'confirm',
default: true,
message: 'Are you going to use github?'
},
{
name: 'githubUsername',
message: 'What is your github username?',
default: suggestedGithubUsername,
when: props => props.githubConfirm
}
], props => {
let
homepage = '',
bugs = '',
url = '';
if (props.githubConfirm) {
homepage = `https://github.com/${props.githubUsername}/${this.pkg.name}`;
bugs = `${homepage}/issues`;
url = `${homepage}.git`;
}
Object.assign(this.pkg, { homepage, bugs, repository: { type: 'git', url } });
done();
});
};
|
'use strict';
/**
* Ask for Github account info.
*/
module.exports = function () {
const done = this.async();
let suggestedGithubUsername;
if (this.authorName && 'string' === typeof this.authorName) {
suggestedGithubUsername = this.authorName.toLowerCase().replace(/\s/g, '');
}
this.prompt([
{
name: 'githubConfirm',
type: 'confirm',
default: true,
message: 'Are you going to use github?'
},
{
name: 'githubUsername',
message: 'What is your github username?',
default: suggestedGithubUsername,
when: props => props.githubConfirm
}
], props => {
if (props.githubConfirm) {
this.pkg.homepage = `https://github.com/${props.githubUsername}/${this.pkg.name}`;
this.pkg.bugs = `${this.pkg.homepage}/issues`;
this.pkg.repository = `${this.pkg.homepage}.git`;
}
done();
});
};
|
Add check around splashscreen object
Minor cleanup.
From: https://gist.github.com/jperl/60d02a5d4301c1e29eec
|
// Hook into the hot-reload to
// 1) wait until the application has resumed to reload the app
// 2) show the splashscreen while the app is reloading
var hasResumed = false;
var retryReloadFunc = null;
var retryReloadOnResume = function () {
// Set hasResumed to true so _onMigrate performs the reload
hasResumed = true;
// Show the splashscreen during the reload
// it will hide when the app starts
if (navigator.splashscreen) {
navigator.splashscreen.show();
}
// Re-run the onMigrate hooks
retryReloadFunc();
};
Reload._onMigrate(function (retry) {
retryReloadFunc = retry;
// Prevent duplicate listeners in case _onMigrate is called multiple times
document.removeEventListener("resume", retryReloadOnResume, false);
if (!hasResumed) {
document.addEventListener("resume", retryReloadOnResume, false);
}
// Reload the app if we resumed
return [hasResumed];
});
|
// Hook into the hot-reload to
// 1) wait until the application has resumed to reload the app
// 2) show the splashscreen while the app is reloading
var hasResumed = false;
var retryReloadFunc = null;
var retryReloadOnResume = function () {
// Set resumed to true so _onMigrate performs the reload
hasResumed = true;
// Show the splashscreen during the reload
// it will be hidden when the app starts
navigator.splashscreen.show();
// Re-run the onMigrate hooks
retryReloadFunc();
};
Reload._onMigrate(function (retryReload) {
retryReloadFunc = retryReload;
// Prevent duplicate listeners in case _onMigrate is called multiple times
document.removeEventListener("resume", retryReloadOnResume, false);
if (!hasResumed) {
document.addEventListener("resume", retryReloadOnResume, false);
}
// Reload the app if we have resumed
return [hasResumed];
});
|
Fix value assigned when marking interface as having no properties
See #142. Thanks @angrybrad
|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\models;
/**
* Represents API documentation information for an `interface`.
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class InterfaceDoc extends TypeDoc
{
public $parentInterfaces = [];
// will be set by Context::updateReferences()
public $implementedBy = [];
/**
* @param \phpDocumentor\Reflection\InterfaceReflector $reflector
* @param Context $context
* @param array $config
*/
public function __construct($reflector = null, $context = null, $config = [])
{
parent::__construct($reflector, $context, $config);
if ($reflector === null) {
return;
}
foreach ($reflector->getParentInterfaces() as $interface) {
$this->parentInterfaces[] = ltrim($interface, '\\');
}
foreach ($this->methods as $method) {
$method->isAbstract = true;
}
// interface can not have properties
$this->properties = [];
}
}
|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\apidoc\models;
/**
* Represents API documentation information for an `interface`.
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class InterfaceDoc extends TypeDoc
{
public $parentInterfaces = [];
// will be set by Context::updateReferences()
public $implementedBy = [];
/**
* @param \phpDocumentor\Reflection\InterfaceReflector $reflector
* @param Context $context
* @param array $config
*/
public function __construct($reflector = null, $context = null, $config = [])
{
parent::__construct($reflector, $context, $config);
if ($reflector === null) {
return;
}
foreach ($reflector->getParentInterfaces() as $interface) {
$this->parentInterfaces[] = ltrim($interface, '\\');
}
foreach ($this->methods as $method) {
$method->isAbstract = true;
}
// interface can not have properties
$this->properties = null;
}
}
|
Change version because of an important bugfix
|
#!/usr/bin/env python
"""Package setup script; requires setuptools (or Python >=3.4 which
bundles it)."""
from setuptools import setup
setup(name='Treepace',
version='0.3',
description='Tree Transformation Language',
author='Matúš Sulír',
url='https://github.com/sulir/treepace',
packages=['treepace', 'treepace.examples'],
test_suite='tests',
install_requires=['parsimonious>=0.5'],
extras_require={
'ipython': ['ipython>=2.0.0']
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
]
)
|
#!/usr/bin/env python
"""Package setup script; requires setuptools (or Python >=3.4 which
bundles it)."""
from setuptools import setup
setup(name='Treepace',
version='0.2',
description='Tree Transformation Language',
author='Matúš Sulír',
url='https://github.com/sulir/treepace',
packages=['treepace', 'treepace.examples'],
test_suite='tests',
install_requires=['parsimonious==0.5'],
extras_require={
'ipython': ['ipython>=1.0.0']
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
]
)
|
Add CORS headers to main studio Flask application, to allow initial API version request
Remove before_request from main application
|
import webbrowser
from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer
from qiime_studio.api.security import make_url
from qiime_studio.api.cors import add_cors_headers
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files
studio = Flask('qiime_studio')
studio.register_blueprint(v1, url_prefix='/api/0.0.1')
studio.debug = True
studio.after_request(add_cors_headers)
@studio.route("/api/", methods=['GET'])
def available_api():
return jsonify(available=["/api/0.0.1/"])
@studio.route("/", methods=['GET'])
def hello():
return "Hello World!"
def start_server(port, domain, in_dev, run_local, skip_open):
host = "%s:%d/api/" % (domain, port)
ihost = "qiime.studio/"
if run_local:
ihost = "%s:%d" % (domain, port)
studio.register_blueprint(static_files)
elif in_dev:
ihost = "localhost:4242"
url = make_url(host, ihost)
print("Your QIIME Studio server is starting.")
print("Please visit the following URL to access:\n")
print(url)
if not skip_open:
webbrowser.open(url)
WSGIServer((domain, port), studio).serve_forever()
|
import webbrowser
from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer
from qiime_studio.api.security import make_url
from qiime_studio.api.v1 import v1
from qiime_studio.static import static_files
studio = Flask('qiime_studio')
studio.register_blueprint(v1, url_prefix='/api/0.0.1')
studio.debug = True
@studio.route("/api/", methods=['GET'])
def available_api():
return jsonify(available=["/api/0.0.1/"])
@studio.route("/", methods=['GET'])
def hello():
return "Hello World!"
def start_server(port, domain, in_dev, run_local, skip_open):
host = "%s:%d/api/" % (domain, port)
ihost = "qiime.studio/"
if run_local:
ihost = "%s:%d" % (domain, port)
studio.register_blueprint(static_files)
elif in_dev:
ihost = "localhost:4242"
url = make_url(host, ihost)
print("Your QIIME Studio server is starting.")
print("Please visit the following URL to access:\n")
print(url)
if not skip_open:
webbrowser.open(url)
WSGIServer((domain, port), studio).serve_forever()
|
Change ping trigger to need exclaimation point
|
const Discord = require('discord.io');
const bot = new Discord.Client({
token: process.env.DISCORD_TOKEN,
autorun: true,
});
const previousMessages = [];
bot.on('ready', () => {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('disconnect', () => {
bot.connect();
});
bot.on('message', (user, userId, channelId, message, event) => {
if (message === '!ping') {
bot.sendMessage({
to: channelId,
message: 'pong',
});
} else if (user !== bot.username) {
if (previousMessages.includes(message)) {
bot.deleteMessage({
channelID: channelId,
messageID: event.d.id,
}, (err) => {
console.log(err);
});
} else {
previousMessages.push(message);
}
}
});
|
const Discord = require('discord.io');
const bot = new Discord.Client({
token: process.env.DISCORD_TOKEN,
autorun: true,
});
const previousMessages = [];
bot.on('ready', () => {
console.log('Logged in as %s - %s\n', bot.username, bot.id);
});
bot.on('disconnect', () => {
bot.connect();
});
bot.on('message', (user, userId, channelId, message, event) => {
if (message === 'ping') {
bot.sendMessage({
to: channelId,
message: 'pong',
});
} else if (user !== bot.username) {
if (previousMessages.includes(message)) {
bot.deleteMessage({
channelID: channelId,
messageID: event.d.id,
}, (err) => {
console.log(err);
});
} else {
previousMessages.push(message);
}
}
});
|
Move NumPy dependency to optional rastertoolz dependency
|
import os.path
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.1dev',
description='Spatial Analysis and Data Exploration',
long_description=long_description,
author='Synthicity',
author_email='ejanowicz@synthicity.com',
license='BSD',
url='https://github.com/synthicity/spandex',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: BSD License'
],
packages=find_packages(exclude=['*.tests']),
install_requires=[
'gdal>=1.8.0',
'pandas>=0.13.1',
'psycopg2>=2.5',
],
extras_require={
'rastertoolz': ['numpy>=1.8.0', 'rasterio>=0.12', 'rasterstats>=0.4',
'shapely>=1.3.2']
}
)
|
import os.path
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.1dev',
description='Spatial Analysis and Data Exploration',
long_description=long_description,
author='Synthicity',
author_email='ejanowicz@synthicity.com',
license='BSD',
url='https://github.com/synthicity/spandex',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: BSD License'
],
packages=find_packages(exclude=['*.tests']),
install_requires=[
'gdal>=1.8.0',
'numpy>=1.8.0',
'pandas>=0.13.1',
'psycopg2>=2.5',
],
extras_require={
'rastertoolz': ['rasterio>=0.12', 'rasterstats>=0.4',
'shapely>=1.3.2']
}
)
|
Fix tests. Add SSL test.
|
package irc
import (
// "github.com/thoj/go-ircevent"
"testing"
)
func TestConnection(t *testing.T) {
irccon := IRC("go-eventirc", "go-eventirc")
irccon.VerboseCallbackHandler = true
err := irccon.Connect("irc.freenode.net:6667")
if err != nil {
t.Fatal("Can't connect to freenode.")
}
irccon.AddCallback("001", func(e *Event) { irccon.Join("#go-eventirc") })
irccon.AddCallback("366" , func(e *Event) {
irccon.Privmsg("#go-eventirc", "Test Message\n")
irccon.Quit();
})
irccon.Loop()
}
func TestConnectionSSL(t *testing.T) {
irccon := IRC("go-eventirc", "go-eventirc")
irccon.VerboseCallbackHandler = true
irccon.UseSSL = true
err := irccon.Connect("irc.freenode.net:7000")
if err != nil {
t.Fatal("Can't connect to freenode.")
}
irccon.AddCallback("001", func(e *Event) { irccon.Join("#go-eventirc") })
irccon.AddCallback("366" , func(e *Event) {
irccon.Privmsg("#go-eventirc", "Test Message\n")
irccon.Quit();
})
irccon.Loop()
}
|
package irc
import (
// irc "github.com/thoj/Go-IRC-Client-Library"
"fmt"
"testing"
)
func TestConnection(t *testing.T) {
irccon := IRC("invisible", "invisible")
fmt.Printf("Testing connection\n")
err := irccon.Connect("irc.freenode.net:6667")
fmt.Printf("Connecting...")
if err != nil {
t.Fatal("Can't connect to freenode.")
}
irccon.AddCallback("001", func(e *Event) { irccon.Join("#invisible") })
irccon.AddCallback("PRIVMSG" , func(e *Event) {
irccon.Privmsg("#invisible", "WHAT IS THIS\n")
fmt.Printf("Got private message, likely should respond!\n")
irccon.Privmsg(e.Nick , "WHAT")
})
irccon.Loop()
}
|
Build vehicle with motor hat.
|
from Adafruit_MotorHAT import Adafruit_MotorHAT
class Vehicle:
def __init__(self, motor_hat=Adafruit_MotorHAT()):
self.motor_hat = motor_hat
self.motors = []
def release(self):
self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)
def update_motor(self, index, command, speed):
with self.motor_hat.getMotor(index) as motor:
motor.run(command)
motor.setSpeed(speed)
motor = {"location": index, "command": command, "speed": speed}
n = len(self.motors)
if index < n:
self.motors[index] = motor
elif index == n:
self.motors.append(motor)
else:
raise IndexError()
|
from Adafruit_MotorHAT import Adafruit_MotorHAT
class Vehicle:
def __init__(self, motor_hat=None):
self.motor_hat = motor_hat
self.motors = []
def release(self):
self.motor_hat.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
self.motor_hat.getMotor(4).run(Adafruit_MotorHAT.RELEASE)
def update_motor(self, index, command, speed):
with self.motor_hat.getMotor(index) as motor:
motor.run(command)
motor.setSpeed(speed)
motor = {"location": index, "command": command, "speed": speed}
n = len(self.motors)
if index < n:
self.motors[index] = motor
elif index == n:
self.motors.append(motor)
else:
raise IndexError()
|
Fix test after changing array structure
|
from __future__ import print_function
from numba.ctypes_support import *
import numpy
import numba.unittest_support as unittest
from numba._numpyadapt import get_ndarray_adaptor
class ArrayStruct3D(Structure):
_fields_ = [
("data", c_void_p),
("shape", (c_ssize_t * 3)),
("strides", (c_ssize_t * 3)),
("parent", c_void_p),
]
class TestArrayAdaptor(unittest.TestCase):
def test_array_adaptor(self):
arystruct = ArrayStruct3D()
adaptorptr = get_ndarray_adaptor()
adaptor = PYFUNCTYPE(c_int, py_object, c_void_p)(adaptorptr)
ary = numpy.arange(60).reshape(2, 3, 10)
status = adaptor(ary, byref(arystruct))
self.assertEqual(status, 0)
self.assertEqual(arystruct.data, ary.ctypes.data)
for i in range(3):
self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i])
self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i])
if __name__ == '__main__':
unittest.main()
|
from __future__ import print_function
from numba.ctypes_support import *
import numpy
import numba.unittest_support as unittest
from numba._numpyadapt import get_ndarray_adaptor
class ArrayStruct3D(Structure):
_fields_ = [
("data", c_void_p),
("shape", (c_ssize_t * 3)),
("strides", (c_ssize_t * 3)),
]
class TestArrayAdaptor(unittest.TestCase):
def test_array_adaptor(self):
arystruct = ArrayStruct3D()
adaptorptr = get_ndarray_adaptor()
adaptor = PYFUNCTYPE(c_int, py_object, c_void_p)(adaptorptr)
ary = numpy.arange(60).reshape(2, 3, 10)
status = adaptor(ary, byref(arystruct))
self.assertEqual(status, 0)
self.assertEqual(arystruct.data, ary.ctypes.data)
for i in range(3):
self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i])
self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i])
|
Change constant variables to fit new template
|
import string
ROWS = 12
COLUMNS = 14
TMPL_OPTIONS = {
'page-size': 'Letter'
}
PERCENTAGE_TO_CROP_SCAN_IMG = 0.005
PERCENTAGE_TO_CROP_CHAR_IMG = 0.1
CROPPED_IMG_NAME = "cropped_picture.bmp"
CUT_CHAR_IMGS_DIR = "cutting_output_images"
MAX_COLUMNS_PER_PAGE = 14
MAX_ROWS_PER_PAEG = 12
RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30
RELA_PIXELS_WRITING_BOX_HEIGHT = 70
RELA_PIXELS_WRITING_BOX_WIDTH = 70
RELA_PIXELS_BORDER_WIDTH = 2
def get_flat_chars():
chars = unicode(string.lowercase)
chars += unicode(string.uppercase)
chars += unicode(string.digits)
chars += unicode(string.punctuation)
print chars
return chars
def get_chars():
chars = get_flat_chars()
result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)]
result[-1] = result[-1].ljust(COLUMNS)
result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)])
return result
def get_sample_chars():
return iter("AaBb")
|
import string
ROWS = 12
COLUMNS = 14
TMPL_OPTIONS = {
'page-size': 'Letter'
}
PERCENTAGE_TO_CROP_SCAN_IMG = 0.005
PERCENTAGE_TO_CROP_CHAR_IMG = 0.1
CROPPED_IMG_NAME = "cropped_picture.bmp"
CUT_CHAR_IMGS_DIR = "cutting_output_images"
MAX_COLUMNS_PER_PAGE = 14
MAX_ROWS_PER_PAEG = 12
RELA_PIXELS_CHARACTER_BAR_HEIGHT = 30
RELA_PIXELS_WRITING_BOX_HEIGHT = 100
RELA_PIXELS_WRITING_BOX_WIDTH = 100
RELA_PIXELS_BORDER_WIDTH = 1
def get_flat_chars():
chars = unicode(string.lowercase)
chars += unicode(string.uppercase)
chars += unicode(string.digits)
chars += unicode(string.punctuation)
print chars
return chars
def get_chars():
chars = get_flat_chars()
result = [chars[i:i + COLUMNS] for i in xrange(0, len(chars), COLUMNS)]
result[-1] = result[-1].ljust(COLUMNS)
result.extend([' ' * COLUMNS for i in xrange(len(result), ROWS)])
return result
def get_sample_chars():
return iter("AaBb")
|
Adjust doc to be more google like
|
package cfgfile
import (
"flag"
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
// Command line flags
var configfile *string
var testConfig *bool
func CmdLineFlags(flags *flag.FlagSet, name string) {
configfile = flags.String("c", fmt.Sprintf("/etc/%s/%s.yml", name, name), "Configuration file")
testConfig = flags.Bool("test", false, "Test configuration and exit.")
}
// Read reads the configuration from a yaml file into the given interface structure.
// In case path is not set this method reads from the default configuration file for the beat.
func Read(out interface{}, path string) error {
if path == "" {
path = *configfile
}
filecontent, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("Failed to read %s: %v. Exiting.", path, err)
}
if err = yaml.Unmarshal(filecontent, out); err != nil {
return fmt.Errorf("YAML config parsing failed on %s: %v. Exiting.", path, err)
}
return nil
}
func IsTestConfig() bool {
return *testConfig
}
|
package cfgfile
import (
"flag"
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
// Command line flags
var configfile *string
var testConfig *bool
func CmdLineFlags(flags *flag.FlagSet, name string) {
configfile = flags.String("c", fmt.Sprintf("/etc/%s/%s.yml", name, name), "Configuration file")
testConfig = flags.Bool("test", false, "Test configuration and exit.")
}
// Reads config from yaml file into the given interface structure.
// In case path is not set this method reads from the default configuration file for the beat.
func Read(out interface{}, path string) error {
if path == "" {
path = *configfile
}
filecontent, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("Failed to read %s: %v. Exiting.", path, err)
}
if err = yaml.Unmarshal(filecontent, out); err != nil {
return fmt.Errorf("YAML config parsing failed on %s: %v. Exiting.", path, err)
}
return nil
}
func IsTestConfig() bool {
return *testConfig
}
|
Make _CustomAnalyzer a private class
|
from hoomd.python_action import _PythonAction, _InternalPythonAction
from hoomd.custom_action import _CustomAction, _InternalCustomAction
class _CustomAnalyzer(_CustomAction):
def analyze(self, timestep):
return self.act(timestep)
class _InternalCustomAnayzer(_InternalCustomAction):
def analyze(self, timestep):
return self.act(timestep)
class _PythonAnalyzer(_PythonAction):
_cpp_list_name = 'analyzers'
_cpp_class_name = 'PythonAnalyzer'
_cpp_action = 'analyze'
@property
def analyzer(self):
return self._action
@analyzer.setter
def analyzer(self, analyzer):
if isinstance(analyzer, _CustomAction):
self._action = analyzer
else:
raise ValueError("analyzer must be an instance of _CustomAction")
class _InternalPythonAnalyzer(_InternalPythonAction):
_cpp_list_name = 'analyzers'
_cpp_class_name = 'PythonAnalyzer'
_cpp_action = 'analyze'
@property
def analyzer(self):
return self._action
@analyzer.setter
def analyzer(self, analyzer):
if isinstance(analyzer, _CustomAction):
self._action = analyzer
else:
raise ValueError("analyzer must be an instance of _CustomAction")
|
from hoomd.python_action import _PythonAction, _InternalPythonAction
from hoomd.custom_action import _CustomAction, _InternalCustomAction
class CustomAnalyzer(_CustomAction):
def analyze(self, timestep):
return self.act(timestep)
class _InternalCustomAnayzer(_InternalCustomAction):
def analyze(self, timestep):
return self.act(timestep)
class _PythonAnalyzer(_PythonAction):
_cpp_list_name = 'analyzers'
_cpp_class_name = 'PythonAnalyzer'
_cpp_action = 'analyze'
@property
def analyzer(self):
return self._action
@analyzer.setter
def analyzer(self, analyzer):
if isinstance(analyzer, _CustomAction):
self._action = analyzer
else:
raise ValueError("analyzer must be an instance of _CustomAction")
class _InternalPythonAnalyzer(_InternalPythonAction):
_cpp_list_name = 'analyzers'
_cpp_class_name = 'PythonAnalyzer'
_cpp_action = 'analyze'
@property
def analyzer(self):
return self._action
@analyzer.setter
def analyzer(self, analyzer):
if isinstance(analyzer, _CustomAction):
self._action = analyzer
else:
raise ValueError("analyzer must be an instance of _CustomAction")
|
Update plugin information (name, description, version, author)
|
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import OctoPrintOutputDevicePlugin
from . import DiscoverOctoPrintAction
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "extension",
"plugin": {
"name": "OctoPrint connection",
"author": "fieldOfView",
"version": "1.0",
"description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"),
"api": 3
}
}
def register(app):
return {
"output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(),
"machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction()
}
|
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import OctoPrintOutputDevicePlugin
from . import DiscoverOctoPrintAction
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "extension",
"plugin": {
"name": "Wifi connection",
"author": "Ultimaker",
"description": catalog.i18nc("Wifi connection", "Wifi connection"),
"api": 3
}
}
def register(app):
return {
"output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(),
"machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction()
}
|
Enable users management in SQU mode (SAAS-787)
|
'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modeSquStudentCloud',
toBeFeatures: [
'monitoring',
'backups',
'password',
'services',
'providers',
'premiumSupport',
'servicesadd',
'import',
'templates',
'monitoring',
'projectGroups',
'plans'
],
featuresVisible: false,
appStoreCategories: [
{
name: 'VMs',
type: 'provider',
icon: 'desktop',
services: ['Azure']
},
{
name: 'APPLICATIONS',
type: 'provider',
icon: 'database',
services: ['GitLab']
}
],
emailMask: 'squ.edu.om',
serviceCategories: [],
homeTemplate: 'views/home/squ-student-cloud/home.html',
homeHeaderTemplate: 'views/partials/squ-student-cloud/site-header.html',
homeLoginTemplate: 'views/home/squ-student-cloud/login.html',
enablePurchaseCostDisplay: false,
VmProviderSettingsUuid: "Set UUID of a shared service setting for VMs",
gitLabProviderSettingsUuid: "Set UUID of a shared service setting for GitLab"
});
|
'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modeSquStudentCloud',
toBeFeatures: [
'monitoring',
'backups',
'password',
'services',
'providers',
'premiumSupport',
'users',
'people',
'servicesadd',
'import',
'templates',
'monitoring',
'projectGroups',
'plans'
],
featuresVisible: false,
appStoreCategories: [
{
name: 'VMs',
type: 'provider',
icon: 'desktop',
services: ['Azure']
},
{
name: 'APPLICATIONS',
type: 'provider',
icon: 'database',
services: ['GitLab']
}
],
emailMask: 'squ.edu.om',
serviceCategories: [],
homeTemplate: 'views/home/squ-student-cloud/home.html',
homeHeaderTemplate: 'views/partials/squ-student-cloud/site-header.html',
homeLoginTemplate: 'views/home/squ-student-cloud/login.html',
enablePurchaseCostDisplay: false,
VmProviderSettingsUuid: "Set UUID of a shared service setting for VMs",
gitLabProviderSettingsUuid: "Set UUID of a shared service setting for GitLab"
});
|
Set "public static void" for "main" :thumbsup:
|
public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(){}
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
Add comment to domain stripping regular experssion
For all of those who don't speak Kleene star
|
var WebFont = require("webfont"),
stripDomain = new RegExp("^(.*://[^/]*/)?(.*)$");
// scheme^ domain^ font^
exports.locate = function(load) {
return decodeURI(load.name.match(stripDomain)[2]);
}
exports.fetch = function(load) {
return new Promise(function(resolve, reject) {
var fontName = load.address.split(" ")[0],
params = load.address.substr(fontName.length + 1).split(",").map(function(str) {
return str.trim();
}),
font = {},
config = {
active: function() { resolve("") },
inactive: function() { reject() }
};
config[fontName] = font
switch (fontName) {
case "fontdeck":
case "typekit":
font.id = params.join(",");
break;
case "google":
font.families = params;
break;
case "monotype":
font.projectId = params[0];
font.version = params[1];
}
WebFont.load(config);
});
}
|
var WebFont = require("webfont"),
stripDomain = new RegExp("^(.*://[^/]*/)?(.*)$");
exports.locate = function(load) {
return decodeURI(load.name.match(stripDomain)[2]);
}
exports.fetch = function(load) {
return new Promise(function(resolve, reject) {
var fontName = load.address.split(" ")[0],
params = load.address.substr(fontName.length + 1).split(",").map(function(str) {
return str.trim();
}),
font = {},
config = {
active: function() { resolve("") },
inactive: function() { reject() }
};
config[fontName] = font
switch (fontName) {
case "fontdeck":
case "typekit":
font.id = params.join(",");
break;
case "google":
font.families = params;
break;
case "monotype":
font.projectId = params[0];
font.version = params[1];
}
WebFont.load(config);
});
}
|
Make local variable name more concise.
|
// Copyright © 2011 - 2013 Forerunner Games
package com.forerunnergames.tools;
/**
*
* @author Aaron Mahan
*/
public class Point2D
{
public Point2D (final int x, final int y)
{
x_ = x;
y_ = y;
}
@Override
public boolean equals (Object object)
{
if (this == object)
{
return true;
}
boolean equals = false;
if (object != null && object.getClass() == getClass())
{
Point2D point = (Point2D) object;
if (x_ == point.getX() && y_ == point.getY())
{
equals = true;
}
}
return equals;
}
public int getX()
{
return x_;
}
public int getY()
{
return y_;
}
@Override
public int hashCode()
{
int hash = 7;
hash = 47 * hash + x_;
hash = 47 * hash + y_;
return hash;
}
@Override
public String toString()
{
return String.format (getClass().getSimpleName() + ": (x: %1$6s, y: %2$6s)",
getX(), getY());
}
private final int x_;
private final int y_;
}
|
// Copyright © 2011 - 2013 Forerunner Games
package com.forerunnergames.tools;
/**
*
* @author Aaron Mahan
*/
public class Point2D
{
public Point2D (final int x, final int y)
{
x_ = x;
y_ = y;
}
@Override
public boolean equals (Object object)
{
if (this == object)
{
return true;
}
boolean equals = false;
if (object != null && object.getClass() == getClass())
{
Point2D point2D = (Point2D) object;
if (x_ == point2D.getX() && y_ == point2D.getY())
{
equals = true;
}
}
return equals;
}
public int getX()
{
return x_;
}
public int getY()
{
return y_;
}
@Override
public int hashCode()
{
int hash = 7;
hash = 47 * hash + x_;
hash = 47 * hash + y_;
return hash;
}
@Override
public String toString()
{
return String.format (getClass().getSimpleName() + ": (x: %1$6s, y: %2$6s)",
getX(), getY());
}
private final int x_;
private final int y_;
}
|
Correct the version number in LiSE too
|
# This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a7",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"allegedb>=0.10.0",
],
)
|
# This file is part of LiSE, a framework for life simulation games.
# Copyright (c) Zachary Spector, zacharyspector@gmail.com
import sys
if sys.version_info[0] < 3 or (
sys.version_info[0] == 3 and
sys.version_info[1] < 3
):
raise RuntimeError("LiSE requires Python 3.3 or later")
from setuptools import setup
setup(
name="LiSE",
version="0.0.0a6",
description="Rules engine for life simulation games",
author="Zachary Spector",
author_email="zacharyspector@gmail.com",
license="GPL3",
keywords="game simulation",
url="https://github.com/LogicalDash/LiSE",
packages=[
"LiSE",
"LiSE.server",
"LiSE.examples"
],
package_data={
'LiSE': ['sqlite.json']
},
install_requires=[
"allegedb>=0.10.0",
],
)
|
Handle that Path can be none
|
import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s = sublime.load_settings("Fuse.sublime-settings")
s.set(key, value)
sublime.save_settings("Fuse.sublime-settings")
def isSupportedSyntax(syntaxName):
return syntaxName == "Uno" or syntaxName == "UX"
def getExtension(path):
if path is None:
return ""
base = os.path.basename(path)
ext = os.path.splitext(base)
if ext is None:
return ""
else:
return ext[0]
def getRowCol(view, pos):
rowcol = view.rowcol(pos)
rowcol = (rowcol[0] + 1, rowcol[1] + 1)
return {"Line": rowcol[0], "Character": rowcol[1]}
|
import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s = sublime.load_settings("Fuse.sublime-settings")
s.set(key, value)
sublime.save_settings("Fuse.sublime-settings")
def isSupportedSyntax(syntaxName):
return syntaxName == "Uno" or syntaxName == "UX"
def getExtension(path):
base = os.path.basename(path)
ext = os.path.splitext(base)
if ext is None:
return ""
else:
return ext[0]
def getRowCol(view, pos):
rowcol = view.rowcol(pos)
rowcol = (rowcol[0] + 1, rowcol[1] + 1)
return {"Line": rowcol[0], "Character": rowcol[1]}
|
Fix JS validation. No idea why it doesn't work the other way. Bleh.
|
(function($) {
$(document).ready(function() {
$('.player-link').click(function(e) {
$.get($(this).attr('href'));
e.preventDefault();
});
$('#uploader input').change(validateUploadForm);
$('#uploader input[type="text"]').on('keyup', validateUploadForm);
$('#uploader input[type="text"]').on('blur', validateUploadForm);
$('#talk input[type="text"]').on('keyup', validateTalkForm);
$('#talk input[type="text"]').on('blur', validateTalkForm);
});
var validateUploadForm = function()
{
validateForm('uploader', function() {
var valid =
$('#input-title').val() != '' &&
$('#input-image').val() != '' &&
$('#input-audio').val() != '';
return valid;
});
}
var validateTalkForm = function()
{
validateForm('talk', function() {
return $('#input-txtmsg').val() != '';
});
}
var validateForm = function(formName, validityCheckFunc)
{
$formSubmit = $('#' + formName + '-submit');
if (validityCheckFunc())
$formSubmit.removeAttr('disabled');
else
$formSubmit.attr('disabled', 'true');
}
})(jQuery);
|
(function($) {
$(document).ready(function() {
$('.player-link').click(function(e) {
$.get($(this).attr('href'));
e.preventDefault();
});
$('#uploader input').change(validateUploadForm);
$('#uploader input[type="text"]').on('keyup', validateUploadForm);
$('#uploader input[type="text"]').on('blur', validateUploadForm);
$('#talk input[type="text"]').on('keyup', validateTalkForm);
$('#talk input[type="text"]').on('blur', validateTalkForm);
});
var validateUploadForm = function()
{
validateForm('uploader', function() {
return
$('#input-title').val() != '' &&
$('#input-image').val() != '' &&
$('#input-audio').val() != '';
});
}
var validateTalkForm = function()
{
validateForm('talk', function() {
return $('#input-txtmsg').val() != '';
});
}
var validateForm = function(formName, validityCheckFunc)
{
$formSubmit = $('#' + formName + '-submit');
if (validityCheckFunc())
$formSubmit.removeAttr('disabled');
else
$formSubmit.attr('disabled', 'true');
}
})(jQuery);
|
Update the django path to flatatt module
|
from django import forms
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.forms.utils import flatatt
from django.utils.encoding import force_text
from taggit.utils import parse_tags, edit_string_for_tags
from django.utils import six
class TagsInput(forms.TextInput):
class Media:
css = { 'all': ('css/bootstrap-tagsinput.css','css/typeahead.css') }
js = ('js/typeahead.jquery.min.js', 'js/bootstrap-tagsinput.min.js')
def render(self, name, value, attrs={}):
if value is not None and not isinstance(value, six.string_types):
value = edit_string_for_tags([o.tag for o in value.select_related("tag")])
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(render_to_string('taggit_bootstrap/widget.html', {
'final_attrs': flatatt(final_attrs),
'value': value if value else '',
'id': final_attrs['id']
}))
|
from django import forms
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.forms.util import flatatt
from django.utils.encoding import force_text
from taggit.utils import parse_tags, edit_string_for_tags
from django.utils import six
class TagsInput(forms.TextInput):
class Media:
css = { 'all': ('css/bootstrap-tagsinput.css','css/typeahead.css') }
js = ('js/typeahead.jquery.min.js', 'js/bootstrap-tagsinput.min.js')
def render(self, name, value, attrs={}):
if value is not None and not isinstance(value, six.string_types):
value = edit_string_for_tags([o.tag for o in value.select_related("tag")])
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(render_to_string('taggit_bootstrap/widget.html', {
'final_attrs': flatatt(final_attrs),
'value': value if value else '',
'id': final_attrs['id']
}))
|
Allow scheme/protocol to be passed to script
Googles GTM now seems to redirect any http request to https, this now causes an extra redirect which seems wasteful.
This proposal is to allow someone to pass in the scheme they desire so someone can always call https if they want.
The alternative would be to always use https hardcoded in the scripts, however i'm not sure if people want that and would prefer to keep it as it currently sits.
|
function convertToKeyValueString(obj) {
return JSON.stringify(obj).slice(1, -1);
}
function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {}, scheme = '' }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
<iframe src="${scheme}//www.googletagmanager.com/ns.html?id=${id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
const script = `
(function(w,d,s,l,i){w[l]=w[l]||[];
w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js', ${convertToKeyValueString(additionalEvents)}});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;j.src='${scheme}//www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}','${id}');`;
return {
iframe,
script
};
}
export default buildParts;
|
function convertToKeyValueString(obj) {
return JSON.stringify(obj).slice(1, -1);
}
function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {} }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
<iframe src="//www.googletagmanager.com/ns.html?id=${id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
const script = `
(function(w,d,s,l,i){w[l]=w[l]||[];
w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js', ${convertToKeyValueString(additionalEvents)}});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}','${id}');`;
return {
iframe,
script
};
}
export default buildParts;
|
controller: Fix break scope in StreamFormations
Signed-off-by: Jonathan Rudenberg <3692bfa45759a67d83aedf0045f6cb635a966abf@titanous.com>
|
package main
import (
"net/http"
"time"
ct "github.com/flynn/flynn/controller/types"
"github.com/flynn/flynn/pkg/rpcplus"
rpc "github.com/flynn/flynn/pkg/rpcplus/comborpc"
)
func rpcHandler(repo *FormationRepo) http.Handler {
rpcplus.RegisterName("Controller", &ControllerRPC{formations: repo})
return rpc.New(rpcplus.DefaultServer)
}
type ControllerRPC struct {
formations *FormationRepo
}
func (s *ControllerRPC) StreamFormations(since time.Time, stream rpcplus.Stream) error {
ch := make(chan *ct.ExpandedFormation)
done := make(chan struct{})
go func() {
outer:
for {
select {
case f := <-ch:
select {
case stream.Send <- f:
case <-stream.Error:
break outer
}
case <-stream.Error:
break outer
}
}
close(done)
}()
if err := s.formations.Subscribe(ch, since); err != nil {
return err
}
defer func() {
go func() {
// drain to prevent deadlock while removing the listener
for _ = range ch {
}
}()
s.formations.Unsubscribe(ch)
close(ch)
}()
<-done
return nil
}
|
package main
import (
"net/http"
"time"
ct "github.com/flynn/flynn/controller/types"
"github.com/flynn/flynn/pkg/rpcplus"
rpc "github.com/flynn/flynn/pkg/rpcplus/comborpc"
)
func rpcHandler(repo *FormationRepo) http.Handler {
rpcplus.RegisterName("Controller", &ControllerRPC{formations: repo})
return rpc.New(rpcplus.DefaultServer)
}
type ControllerRPC struct {
formations *FormationRepo
}
func (s *ControllerRPC) StreamFormations(since time.Time, stream rpcplus.Stream) error {
ch := make(chan *ct.ExpandedFormation)
done := make(chan struct{})
go func() {
for {
select {
case f := <-ch:
select {
case stream.Send <- f:
case <-stream.Error:
break
}
case <-stream.Error:
break
}
}
close(done)
}()
if err := s.formations.Subscribe(ch, since); err != nil {
return err
}
defer func() {
go func() {
// drain to prevent deadlock while removing the listener
for _ = range ch {
}
}()
s.formations.Unsubscribe(ch)
close(ch)
}()
<-done
return nil
}
|
Remove unecessary code in cache backend _set
|
# -*- coding: utf-8 -*-
class BaseCacheBackend(object):
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._get(thumbnail_name)
def set(self, thumbnail):
return self._set(thumbnail.name, thumbnail)
def _get(self, thumbnail_name):
raise NotImplementedError
def _set(self, thumbnail_name, thumbnail):
raise NotImplementedError
class SimpleCacheBackend(BaseCacheBackend):
thumbnails = {}
def _get(self, thumbnail_name):
if thumbnail_name in self.thumbnails:
return self.thumbnails[thumbnail_name]
def _set(self, thumbnail_name, thumbnail):
self.thumbnails[thumbnail_name] = thumbnail
class DjangoCacheBackend(BaseCacheBackend):
def __init__(self):
from django.core.cache import cache # noqa isort:skip
self.cache = cache
def _get(self, thumbnail_name):
return self.cache.get(thumbnail_name.replace('/', ''))
def _set(self, thumbnail_name, thumbnail):
self.cache.set(thumbnail_name.replace('/', ''), thumbnail)
|
# -*- coding: utf-8 -*-
class BaseCacheBackend(object):
def get(self, thumbnail_name):
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._get(thumbnail_name)
def set(self, thumbnail):
thumbnail_name = thumbnail.name
if isinstance(thumbnail_name, list):
thumbnail_name = ''.join(thumbnail_name)
return self._set(thumbnail_name, thumbnail)
def _get(self, thumbnail_name):
raise NotImplementedError
def _set(self, thumbnail_name, thumbnail):
raise NotImplementedError
class SimpleCacheBackend(BaseCacheBackend):
thumbnails = {}
def _get(self, thumbnail_name):
if thumbnail_name in self.thumbnails:
return self.thumbnails[thumbnail_name]
def _set(self, thumbnail_name, thumbnail):
self.thumbnails[thumbnail_name] = thumbnail
class DjangoCacheBackend(BaseCacheBackend):
def __init__(self):
from django.core.cache import cache # noqa isort:skip
self.cache = cache
def _get(self, thumbnail_name):
return self.cache.get(thumbnail_name.replace('/', ''))
def _set(self, thumbnail_name, thumbnail):
self.cache.set(thumbnail_name.replace('/', ''), thumbnail)
|
Document self-usage of public methods per `Effective Java`
|
/*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2016 Simmetrics 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.
* #L%
*/
package org.simmetrics.tokenizers;
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
/**
* Convenience tokenizer. Provides default implementation to tokenize to set and
* multiset that calls {@link Tokenizer#tokenizeToList(String)}.
*/
public abstract class AbstractTokenizer implements Tokenizer {
@Override
public Set<String> tokenizeToSet(final String input) {
return new HashSet<>(tokenizeToList(input));
}
@Override
public Multiset<String> tokenizeToMultiset(final String input) {
return HashMultiset.create(tokenizeToList(input));
}
}
|
/*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2016 Simmetrics 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.
* #L%
*/
package org.simmetrics.tokenizers;
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
/**
* Convenience tokenizer. Provides default implementation to tokenize to set and
* multiset.
*/
public abstract class AbstractTokenizer implements Tokenizer {
@Override
public Set<String> tokenizeToSet(final String input) {
return new HashSet<>(tokenizeToList(input));
}
@Override
public Multiset<String> tokenizeToMultiset(final String input) {
return HashMultiset.create(tokenizeToList(input));
}
}
|
ENH: Add diagnose to f2py package. This makes the tests a bit easier to fix.
|
#!/usr/bin/env python
__all__ = ['run_main','compile','f2py_testing']
import os
import sys
import commands
import f2py2e
import f2py_testing
import diagnose
from info import __doc__
run_main = f2py2e.run_main
main = f2py2e.main
def compile(source,
modulename = 'untitled',
extra_args = '',
verbose = 1,
source_fn = None
):
''' Build extension module from processing source with f2py.
Read the source of this function for more information.
'''
from numpy.distutils.exec_command import exec_command
import tempfile
if source_fn is None:
fname = os.path.join(tempfile.mktemp()+'.f')
else:
fname = source_fn
f = open(fname,'w')
f.write(source)
f.close()
args = ' -c -m %s %s %s'%(modulename,fname,extra_args)
c = '%s -c "import numpy.f2py as f2py2e;f2py2e.main()" %s' %(sys.executable,args)
s,o = exec_command(c)
if source_fn is None:
try: os.remove(fname)
except OSError: pass
return s
|
#!/usr/bin/env python
__all__ = ['run_main','compile','f2py_testing']
import os
import sys
import commands
from info import __doc__
import f2py2e
run_main = f2py2e.run_main
main = f2py2e.main
import f2py_testing
def compile(source,
modulename = 'untitled',
extra_args = '',
verbose = 1,
source_fn = None
):
''' Build extension module from processing source with f2py.
Read the source of this function for more information.
'''
from numpy.distutils.exec_command import exec_command
import tempfile
if source_fn is None:
fname = os.path.join(tempfile.mktemp()+'.f')
else:
fname = source_fn
f = open(fname,'w')
f.write(source)
f.close()
args = ' -c -m %s %s %s'%(modulename,fname,extra_args)
c = '%s -c "import numpy.f2py as f2py2e;f2py2e.main()" %s' %(sys.executable,args)
s,o = exec_command(c)
if source_fn is None:
try: os.remove(fname)
except OSError: pass
return s
|
Add serial id to seat
|
package data.trainnetwork;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* A class representing a Seat within section
* @author Balazs Pete
*
*/
public class Seat implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3197202742981022435L;
private String id, sectionId = null;
/**
* Create a new Seat
* @param id
*/
public Seat() {
this.id = new BigInteger(130, new SecureRandom()).toString(32);
}
/**
* Get the ID of the Seat
* @return
*/
public String getId() {
return id;
}
/**
* Add the corresponding {@link Section} (will be stored as an ID reference)
* @param section The section the seat belongs to
*/
public void addSection(Section section) {
sectionId = section.getID();
}
/**
* Get the ID of the corresponding {@link Section}
* @return The id of the section
*/
public String getSectionId() {
return sectionId;
}
/**
* Compare another seat with this one
* @param seat The other seat to compare with
* @return True if the two seats are identical
*/
public boolean equals(Seat seat) {
return id.equals(seat.getId());
}
}
|
package data.trainnetwork;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* A class representing a Seat within section
* @author Balazs Pete
*
*/
public class Seat implements Serializable {
private String id, sectionId = null;
/**
* Create a new Seat
* @param id
*/
public Seat() {
this.id = new BigInteger(130, new SecureRandom()).toString(32);
}
/**
* Get the ID of the Seat
* @return
*/
public String getId() {
return id;
}
/**
* Add the corresponding {@link Section} (will be stored as an ID reference)
* @param section The section the seat belongs to
*/
public void addSection(Section section) {
sectionId = section.getID();
}
/**
* Get the ID of the corresponding {@link Section}
* @return The id of the section
*/
public String getSectionId() {
return sectionId;
}
/**
* Compare another seat with this one
* @param seat The other seat to compare with
* @return True if the two seats are identical
*/
public boolean equals(Seat seat) {
return id.equals(seat.getId());
}
}
|
Simplify and improve -v/-q handling.
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 1
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
v = 0
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
"""Alternate way of running the unittests, for Python 2.5 or Windows."""
__author__ = 'Beech Horn'
import sys
import unittest
def suite():
mods = ['context', 'eventloop', 'key', 'model', 'query', 'tasklets', 'thread']
test_mods = ['%s_test' % name for name in mods]
ndb = __import__('ndb', fromlist=test_mods, level=1)
loader = unittest.TestLoader()
suite = unittest.TestSuite()
for mod in [getattr(ndb, name) for name in test_mods]:
for name in set(dir(mod)):
if name.endswith('Tests'):
test_module = getattr(mod, name)
tests = loader.loadTestsFromTestCase(test_module)
suite.addTests(tests)
return suite
def main():
v = 0
q = 0
for arg in sys.argv[1:]:
if arg.startswith('-v'):
v += arg.count('v')
elif arg == '-q':
q += 1
if q:
v = 0
else:
v = max(v, 1)
unittest.TextTestRunner(verbosity=v).run(suite())
if __name__ == '__main__':
main()
|
Add tests to confirm message retrieval
|
var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('database storage', function() {
var testData = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var invalidTestData = {
x: 37.783599,
y: -122.408974,
z: 69
};
var testLocation = {
x: 37.183549,
y: -122.108974,
};
it('should validate user input', function(done) {
models.insert(invalidTestData, function(msg) {
expect(msg).to.equal('Could not insert new message: invalid input.');
done();
})
});
it('should add messages to the database', function(done) {
models.insert(testData, function(msg) {
expect(msg).to.equal('Successfully inserted new message and mark to database.');
done();
})
});
it('should retrieve messages from the database', function(done) {
models.retrieve(testLocation, function(messages) {
expect(messages).to.be.instanceof(Array);
done();
})
});
});
|
var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('database storage', function() {
var testData = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var invalidTestData = {
x: 37.783599,
y: -122.408974,
z: 69
};
it('should validate user input', function(done) {
models.insert(invalidTestData, function(msg) {
expect(msg).to.equal('Could not insert new message: invalid input.');
done();
})
});
it('should add messages to the database', function(done) {
models.insert(testData, function(msg) {
expect(msg).to.equal('Successfully inserted new message and mark to database.');
done();
})
});
});
|
Switch from go-flags to flag
|
package main
import (
"flag"
)
type Option struct {
Delimiter string
UseRegexp bool
Count int
Margin string
Justify string
IsHelp bool
IsVersion bool
Files []string
}
func ParseOption(args []string) (*Option, error) {
opt := &Option{}
f := flag.NewFlagSet("alita", flag.ContinueOnError)
f.StringVar(&opt.Delimiter, "d", "", "")
f.StringVar(&opt.Delimiter, "delimiter", "", "")
f.BoolVar(&opt.UseRegexp, "r", false, "")
f.BoolVar(&opt.UseRegexp, "regexp", false, "")
f.IntVar(&opt.Count, "c", 0, "")
f.IntVar(&opt.Count, "count", 0, "")
f.StringVar(&opt.Margin, "m", "", "")
f.StringVar(&opt.Margin, "margin", "", "")
f.StringVar(&opt.Justify, "j", "", "")
f.StringVar(&opt.Justify, "justify", "", "")
f.BoolVar(&opt.IsHelp, "h", false, "")
f.BoolVar(&opt.IsHelp, "help", false, "")
f.BoolVar(&opt.IsVersion, "version", false, "")
if err := f.Parse(args); err != nil {
return nil, err
}
opt.Files = f.Args()
return opt, nil
}
|
package main
import (
"github.com/jessevdk/go-flags"
)
type Option struct {
Delimiter string `short:"d" long:"delimiter" default:""`
UseRegexp bool `short:"r" long:"regexp" default:"false"`
Count int `short:"c" long:"count" default:"-1"`
Margin string `short:"m" long:"margin" default:"1:1"`
Justify string `short:"j" long:"justify" default:"l"`
IsHelp bool `short:"h" long:"help" default:"false"`
IsVersion bool ` long:"version" default:"false"`
Files []string
}
func ParseOption(args []string) (*Option, error) {
opt := &Option{}
files, err := flags.ParseArgs(opt, args)
if err != nil {
return nil, err
}
opt.Files = files
return opt, nil
}
|
Convert to ArrayBuffer for when fs gives back Node buffers.
|
export const build = false
export function fetch (load) {
if (load.address.substr(0, 8) === 'file:///') {
return System.import('fs').then(function (fs) {
return new Promise(function (resolve, reject) {
fs.readFile(load.address.substr(7), function (err, data) {
if (err) {
reject(err)
} else {
load.metadata.buffer = new Uint8Array(data).buffer
resolve('')
}
})
})
})
} else {
return System.import('fetch').then(function (_fetch) {
return window.fetch(load.address)
}).then(function (data) {
return data.arrayBuffer()
}).then(function (buffer) {
load.metadata.buffer = buffer
return ''
})
}
}
export function instantiate (load) {
return load.metadata.buffer
}
|
export const build = false
export function fetch (load) {
if (load.address.substr(0, 8) === 'file:///') {
return System.import('fs').then(function (fs) {
return new Promise(function (resolve, reject) {
fs.readFile(load.address.substr(7), function (err, data) {
if (err) {
reject(err)
} else {
load.metadata.buffer = data
resolve('')
}
})
})
})
} else {
return System.import('fetch').then(function (_fetch) {
return window.fetch(load.address)
}).then(function (data) {
return data.arrayBuffer()
}).then(function (buffer) {
load.metadata.buffer = buffer
return ''
})
}
}
export function instantiate (load) {
return load.metadata.buffer
}
|
Change virtual prop to an instance method
|
'use strict';
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// export a mongoose model
var userSchema = new Schema({
userName : String,
passwordDigest : String
});
userSchema.methods.setPassword = function(password) {
var self = this;
var saltPromise = new Promise(function saltExec(res, rej) {
bcrypt.genSalt(16, function(err, salt) {
if(err) {
rej(err);
return;
}
res(salt);
});
});
var returnedPromise = saltPromise.then(function(salt) {
return new Promise(function hashExec(res, rej) {
bcrypt.hash(password, salt, function(err, digest) {
if(err) {
rej(err);
return;
}
res(digest);
});
});
}).then(function(digest) {
self.passwordDigest = digest;
return self.save();
});
return returnedPromise;
};
module.exports = userSchema;
|
'use strict';
var bcrypt = require('bcrypt');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// export a mongoose model
var userSchema = new Schema({
userName : String,
passwordDigest : String
});
userSchema.virtual('password').set(function(password) {
var self = this;
var saltPromise = new Promise(function saltExec(res, rej) {
bcrypt.genSalt(16, function(err, salt) {
if(err) {
rej(err);
return;
}
res(salt);
});
});
var returnedPromise = saltPromise.then(function(salt) {
return new Promise(function hashExec(res, rej) {
bcrypt.hash(password, salt, function(err, digest) {
if(err) {
rej(err);
return;
}
res(digest);
});
});
}).then(function(digest) {
self.passwordDigest = digest;
});
return returnedPromise;
});
module.exports = userSchema;
|
Remove unnecessary line from detect
|
######################## BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
return detector.close()
|
######################## BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
detector.close()
return detector.result
|
Add empty default implementations for notification service
|
package net.brutus5000.bireus.service;
import org.jgrapht.GraphPath;
import org.jgrapht.graph.DefaultEdge;
import java.net.URL;
import java.nio.file.Path;
public interface NotificationService {
default void error(String message) {
}
default void beginCheckoutVersion(String version) {
}
default void finishCheckoutVersion(String version) {
}
default void checkedOutAlready(String version) {
}
default void versionUnknown(String version) {
}
default void noPatchPath(String version) {
}
default void beginApplyPatch(String fromVersion, String toVersion) {
}
default void finishApplyPatch(String fromVersion, String toVersion) {
}
default void beginDownloadPatch(URL url) {
}
default void finishDownloadPatch(URL url) {
}
default void beginPatchingDirectory(Path path) {
}
default void finishPatchingDirectory(Path path) {
}
default void beginPatchingFile(Path path) {
}
default void finishPatchingFile(Path path) {
}
default void foundPatchPath(GraphPath<String, DefaultEdge> patchPath) {
}
default void crcMismatch(Path patchPath) {
}
}
|
package net.brutus5000.bireus.service;
import org.jgrapht.GraphPath;
import org.jgrapht.graph.DefaultEdge;
import java.net.URL;
import java.nio.file.Path;
public interface NotificationService {
void error(String message);
void beginCheckoutVersion(String version);
void finishCheckoutVersion(String version);
void checkedOutAlready(String version);
void versionUnknown(String version);
void noPatchPath(String version);
void beginApplyPatch(String fromVersion, String toVersion);
void finishApplyPatch(String fromVersion, String toVersion);
void beginDownloadPatch(URL url);
void finishDownloadPatch(URL url);
void beginPatchingDirectory(Path path);
void finishPatchingDirectory(Path path);
void beginPatchingFile(Path path);
void finishPatchingFile(Path path);
void foundPatchPath(GraphPath<String, DefaultEdge> patchPath);
void crcMismatch(Path patchPath);
}
|
Add non undefinded check to team names on GameCard
|
import React from 'react'
import GameCard from './GameCard'
export default (props) => {
const userId = props.userId
const teams = props.teams
const games = []
const gamesObj = props.games
console.log('teams', teams)
for (let key in gamesObj) {
const game = gamesObj[key]
game.gameKey = key
game.ownedByCurrentUser = game.owner_id === userId
games.push(game)
}
const fetchingGames = props.fetchingGames
const deleteGame = props.deleteGame
return (
<div className='games'>
{!fetchingGames
? (games.length
? games.map((game, key) => <GameCard key={key} game={game} deleteGame={deleteGame}
homeTeam={game.status_initialized ? teams[game.home_team.key] && teams[game.home_team.key].name || '???' : teams[game.home_team] && teams[game.home_team].name || "Can't find team"}
awayTeam={game.status_initialized ? teams[game.away_team.key] && teams[game.away_team.key].name || '???' : teams[game.away_team] && teams[game.away_team].name || "Can't find team"} />)
: <h3>No Games Found</h3>)
: <h3>Loading Games...</h3>
}
</div>
)
}
|
import React from 'react'
import GameCard from './GameCard'
export default (props) => {
const userId = props.userId
const teams = props.teams
const games = []
const gamesObj = props.games
console.log('teams', teams)
for (let key in gamesObj) {
const game = gamesObj[key]
game.gameKey = key
game.ownedByCurrentUser = game.owner_id === userId
games.push(game)
}
const fetchingGames = props.fetchingGames
const deleteGame = props.deleteGame
return (
<div className='games'>
{!fetchingGames
? (games.length
? games.map((game, key) => <GameCard key={key} game={game} deleteGame={deleteGame}
homeTeam={game.status_initialized ? teams[game.home_team.key] && teams[game.home_team.key].name || '???' : teams[game.home_team].name}
awayTeam={game.status_initialized ? teams[game.away_team.key] && teams[game.away_team.key].name || '???' : teams[game.away_team].name} />)
: <h3>No Games Found</h3>)
: <h3>Loading Games...</h3>
}
</div>
)
}
|
Fix script to pass pep8
|
#!/usr/bin/env python3
import argparse
import random
import sys
DESCRIPTION = '''Shuffle the arguments received, if called without arguments
the lines read from stdin will be shuffled and printed to
stdout'''
def get_list():
return sys.stdin.readlines()
def print_list(list_):
for elem in list_:
print(elem.rstrip())
def main():
parser = argparse.ArgumentParser(description=DESCRIPTION)
(args, list_) = parser.parse_known_args()
r = random.SystemRandom()
if not list_:
list_ = get_list()
r.shuffle(list_)
print_list(list_)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import argparse
import random
import sys
DESCRIPTION = '''Shuffle the arguments received, if called without arguments
the lines read from stdin will be shuffled and printed to
stdout'''
def get_list():
return sys.stdin.readlines()
def print_list(list_):
for elem in list_:
print(elem.rstrip())
def main():
parser = argparse.ArgumentParser(description=DESCRIPTION)
(args, list_) = parser.parse_known_args()
r = random.SystemRandom()
if not list_:
list_ = get_list()
r.shuffle(list_)
print_list(list_)
if __name__ == '__main__':
main()
|
Update script to include name
|
// ==UserScript==
// @name WT_Integration
// @namespace https://wholetale.org/
// @version 0.1.1
// @description Mock WT integration
// @author Xarthisius
// @match https://dataverse.harvard.edu/dataset.xhtml*
// @grant none
// ==/UserScript==
$(document).ready(function() {
var citeButton = document.getElementsByClassName("downloadCitation")[0];
if (citeButton) {
var title = document.getElementById('title').innerHTML;
var myOtherUrl = "https://dashboard.stage.wholetale.org/compose?uri=" + encodeURIComponent(window.location.href) + "&name=" + encodeURIComponent(title);
var node = document.getElementsByClassName('dropdown')[1];
var placeHolder = document.createElement("span");
placeHolder.onclick = function() { console.log('balh'); };
node.insertBefore(placeHolder, citeButton);
var magic = '<button type="button" class="btn btn-default dropdown-toggle fake" data-toggle="dropdown" aria-expanded="false"><span class="glyphicon glyphicon-equalizer"></span>Explore <span class="caret"></span></button><ul class="dropdown-menu reddy" role="menu"><li><a href="' + myOtherUrl + '">Analyze in WT</a></li></ul>';
placeHolder.innerHTML = magic;
}
});
|
// ==UserScript==
// @name WT_Integration
// @namespace https://wholetale.org/
// @version 0.1.0
// @description Mock WT integration
// @author Xarthisius
// @match https://dataverse.harvard.edu/dataset.xhtml*
// @grant none
// ==/UserScript==
$(document).ready(function() {
var citeButton = document.getElementsByClassName("downloadCitation")[0];
if (citeButton) {
var myOtherUrl = "https://dashboard.stage.wholetale.org/compose?uri=" + encodeURIComponent(window.location.href);
var node = document.getElementsByClassName('dropdown')[1];
var placeHolder = document.createElement("span");
placeHolder.onclick = function() { console.log('balh'); };
node.insertBefore(placeHolder, citeButton);
var magic = '<button type="button" class="btn btn-default dropdown-toggle fake" data-toggle="dropdown" aria-expanded="false"><span class="glyphicon glyphicon-equalizer"></span>Explore <span class="caret"></span></button><ul class="dropdown-menu reddy" role="menu"><li><a href="' + myOtherUrl + '">Analyze in WT</a></li></ul>';
placeHolder.innerHTML = magic;
}
});
|
Correct the Message in `skipIfPhp5`
Which said something non-sensical before.
|
<?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue;
abstract class UnitTestCase extends \PHPUnit_Framework_TestCase
{
protected function skipIfPhp7()
{
if (self::isPhp7()) {
$this->markTestSkipped(sprintf('PHP < 7.X is required, have %s', PHP_VERSION));
}
}
protected function skipIfPhp5()
{
if (!self::isPhp7()) {
$this->markTestSkipped(sprintf('PHP 7.X is required, have %s', PHP_VERSION));
}
}
protected static function isPhp7()
{
return PHP_VERSION_ID >= 70000;
}
}
|
<?php
/**
* This file is part of PMG\Queue
*
* Copyright (c) PMG <https://www.pmg.com>
*
* For full copyright information see the LICENSE file distributed
* with this source code.
*
* @license http://opensource.org/licenses/Apache-2.0 Apache-2.0
*/
namespace PMG\Queue;
abstract class UnitTestCase extends \PHPUnit_Framework_TestCase
{
protected function skipIfPhp7()
{
if (self::isPhp7()) {
$this->markTestSkipped(sprintf('PHP < 7.X is required, have %s', PHP_VERSION));
}
}
protected function skipIfPhp5()
{
if (!self::isPhp7()) {
$this->markTestSkipped(sprintf('PHP 5.X is required, have %s', PHP_VERSION));
}
}
protected static function isPhp7()
{
return PHP_VERSION_ID >= 70000;
}
}
|
Fix undefined images when there is file index out of range of available files
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { assetClick } from '../../actions/assets';
import map from 'lodash/map';
import ColorPicker from './colorpicker';
const getImage = (asset, profile, assets) => {
if ( ! assets.data) return;
const color = profile[asset.id].color;
const files = assets.data[asset.id].colors[color].files;
const fileIndex = profile[asset.id].fileIndex % files.length;
const fileName = files[fileIndex];
return `svg/${asset.id}/${color}/${fileName}`;
};
class Profile extends Component {
render() {
const { dispatch, profile, assets } = this.props;
if ( ! assets.data) return <div />;
const data = map(assets.data);
data.sort((a, b) => a.sortOrder - b.sortOrder);
return (
<div className="profile">
<div className="character">
{map(data, asset => (
<img
key={asset.id}
src={getImage(asset, profile, assets)}
onClick={() => dispatch(assetClick(asset.id))}
/>
))}
</div>
<ColorPicker />
</div>
);
}
}
export default connect(({ profile, assets }) => ({ profile, assets }))(Profile);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { assetClick } from '../../actions/assets';
import map from 'lodash/map';
import ColorPicker from './colorpicker';
const getImage = (asset, profile, assets) => {
if ( ! assets.data) return;
const color = profile[asset.id].color;
const fileIndex = profile[asset.id].fileIndex;
const fileName = assets.data[asset.id].colors[color].files[fileIndex];
return `svg/${asset.id}/${color}/${fileName}`;
};
class Profile extends Component {
render() {
const { dispatch, profile, assets } = this.props;
if ( ! assets.data) return <div />;
const data = map(assets.data);
data.sort((a, b) => a.sortOrder - b.sortOrder);
return (
<div className="profile">
<div className="character">
{map(data, asset => (
<img
key={asset.id}
src={getImage(asset, profile, assets)}
onClick={() => dispatch(assetClick(asset.id))}
/>
))}
</div>
<ColorPicker />
</div>
);
}
}
export default connect(({ profile, assets }) => ({ profile, assets }))(Profile);
|
Revert "ativation by adress mail"
This reverts commit 16724a7f849b1110103b05f6d964a79dc2af344d.
|
<?php
require_once(__DIR__. '/class/DatabaseManager.php');
$hostname = "localhost";
$database = "aen";
$username = "root";
$password = "";
try{
$connect = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password);
}catch (PDOException $e){
exit('problème de connexion à la base');
}
if( !isset($_GET['activationKey'])){
die("Pas de token");
}
$activationKey = $_GET['activationKey'];
$query = $connect->prepare("SELECT id FROM user WHERE activation_key='$activationKey'");
//Executer et récupérer l'information
$query->execute(["activationKey"=>$_GET['activationKey']]);
$results = $query->fetch();
if( !empty($results) ){
//il existe on prépare une autre requête
$query = $connect->prepare("UPDATE user SET active = 1 WHERE activation_key='$activationKey'");
//On execute la nouvelle requete
$query->execute(["activation_key"=>$_GET['activationKey']]);
header("Location: index.php");
}else{
die("Erreur a la fin, bdd pas mise a jour");
}
//et si il n'existe pas on die
?>
|
<?php
require_once(__DIR__. '/class/DatabaseManager.php');
$hostname = "localhost";
$database = "aen";
$username = "root";
$password = "";
try{
$connect = new PDO('mysql:host='.$hostname.';dbname='.$database, $username, $password);
}catch (PDOException $e){
exit('problème de connexion à la base');
}
if( !isset($_GET['activationKey']) && !isset($_GET['mail'])){
die("Pas de token");
}
$activationKey = $_GET['activationKey'];
$mail = $_GET['mail'];
echo $activationKey;
echo $mail;
$query = $connect->prepare("SELECT id FROM user WHERE mail='$mail'");
//Executer et récupérer l'information
$query->execute(["mail"=>$_GET['mail']]);
$results = $query->fetch();
if( !empty($results) ){
//il existe on prépare une autre requête
$query = $connect->prepare("UPDATE user SET active = 1 WHERE mail='$mail'");
//On execute la nouvelle requete
$query->execute(["mail"=>$_GET['mail']]);
header("Location: index.php");
}else{
die("Erreur a la fin, bdd pas mise a jour");
}
//et si il n'existe pas on die
?>
|
Add a further path inside /sys to test
On (at least) a Debian "stretch" system, the charliecloud image contains
none of the tested paths inside /sys. This patch adds one that does
exist there.
Signed-off-by: Matthew Vernon <d2337109245c21c6e400ba5f0470cfb01956d9f2@sanger.ac.uk>
|
#!/usr/bin/env python3
import os.path
import sys
# File in /sys seem to vary between Linux systems. Thus, try a few candidates
# and use the first one that exists. What we want is any file under /sys with
# permissions root:root -rw-------.
sys_file = None
for f in ("/sys/devices/cpu/rdpmc",
"/sys/kernel/mm/page_idle/bitmap",
"/sys/kernel/slab/request_sock_TCP/red_zone",
"sys/kernel/debug/kprobes/enabled"):
if (os.path.exists(f)):
sys_file = f
break
if (sys_file is None):
print("ERROR\tno test candidates in /sys exist")
sys.exit(1)
problem_ct = 0
for f in ("/dev/mem", "/proc/kcore", sys_file):
try:
open(f, "rb").read(1)
print("RISK\t%s: read allowed" % f)
problem_ct += 1
except PermissionError:
print("SAFE\t%s: read not allowed" % f)
except OSError as x:
print("ERROR\t%s: exception: %s" % (f, x))
problem_ct += 1
sys.exit(problem_ct != 0)
|
#!/usr/bin/env python3
import os.path
import sys
# File in /sys seem to vary between Linux systems. Thus, try a few candidates
# and use the first one that exists. What we want is any file under /sys with
# permissions root:root -rw-------.
sys_file = None
for f in ("/sys/devices/cpu/rdpmc",
"/sys/kernel/mm/page_idle/bitmap",
"/sys/kernel/slab/request_sock_TCP/red_zone"):
if (os.path.exists(f)):
sys_file = f
break
if (sys_file is None):
print("ERROR\tno test candidates in /sys exist")
sys.exit(1)
problem_ct = 0
for f in ("/dev/mem", "/proc/kcore", sys_file):
try:
open(f, "rb").read(1)
print("RISK\t%s: read allowed" % f)
problem_ct += 1
except PermissionError:
print("SAFE\t%s: read not allowed" % f)
except OSError as x:
print("ERROR\t%s: exception: %s" % (f, x))
problem_ct += 1
sys.exit(problem_ct != 0)
|
Check for null value before appending
|
package com.hubspot.jinjava.util;
import com.hubspot.jinjava.interpret.OutputTooBigException;
import java.io.Serializable;
import java.util.stream.IntStream;
public class LengthLimitingStringBuilder implements Serializable, CharSequence {
private static final long serialVersionUID = -1891922886257965755L;
private final StringBuilder builder;
private long length = 0;
private final long maxLength;
public LengthLimitingStringBuilder(long maxLength) {
builder = new StringBuilder();
this.maxLength = maxLength;
}
@Override
public int length() {
return builder.length();
}
@Override
public char charAt(int index) {
return builder.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return builder.subSequence(start, end);
}
@Override
public String toString() {
return builder.toString();
}
@Override
public IntStream chars() {
return builder.chars();
}
@Override
public IntStream codePoints() {
return builder.codePoints();
}
public void append(Object obj) {
append(String.valueOf(obj));
}
public void append(String str) {
if (str == null) {
return;
}
length += str.length();
if (maxLength > 0 && length > maxLength) {
throw new OutputTooBigException(maxLength, length);
}
builder.append(str);
}
}
|
package com.hubspot.jinjava.util;
import com.hubspot.jinjava.interpret.OutputTooBigException;
import java.io.Serializable;
import java.util.stream.IntStream;
public class LengthLimitingStringBuilder implements Serializable, CharSequence {
private static final long serialVersionUID = -1891922886257965755L;
private final StringBuilder builder;
private long length = 0;
private final long maxLength;
public LengthLimitingStringBuilder(long maxLength) {
builder = new StringBuilder();
this.maxLength = maxLength;
}
@Override
public int length() {
return builder.length();
}
@Override
public char charAt(int index) {
return builder.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return builder.subSequence(start, end);
}
@Override
public String toString() {
return builder.toString();
}
@Override
public IntStream chars() {
return builder.chars();
}
@Override
public IntStream codePoints() {
return builder.codePoints();
}
public void append(Object obj) {
append(String.valueOf(obj));
}
public void append(String str) {
length += str.length();
if (maxLength > 0 && length > maxLength) {
throw new OutputTooBigException(maxLength, length);
}
builder.append(str);
}
}
|
Add missing whitespace in license header
|
/**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.types;
import java.util.Objects;
/**
* <h1>6 ECMAScript Data Types and Values</h1><br>
* <h2>6.1 ECMAScript Language Types</h2>
* <ul>
* <li>6.1.5 The Symbol Type
* </ul>
*/
public final class Symbol {
/** [[Description]] */
private final String description;
public Symbol(String description) {
this.description = description;
}
/** [[Description]] */
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Symbol(" + Objects.toString(getDescription(), "") + ")";
}
}
|
/**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.types;
import java.util.Objects;
/**
* <h1>6 ECMAScript Data Types and Values</h1><br>
* <h2>6.1 ECMAScript Language Types</h2>
* <ul>
* <li>6.1.5 The Symbol Type
* </ul>
*/
public final class Symbol {
/** [[Description]] */
private final String description;
public Symbol(String description) {
this.description = description;
}
/** [[Description]] */
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Symbol(" + Objects.toString(getDescription(), "") + ")";
}
}
|
Add delete old sessions command
|
from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... print "{0} records left".format(Session.objects.filter(expire_date__lt=now).count())
...
"""
class Command(BaseCommand):
args = '<count count ...>'
help = "Delete old sessions"
def handle(self, *args, **options):
old_sessions = Session.objects.filter(expire_date__lt=datetime.now())
self.stdout.write("Deleting {0} expired sessions".format(
old_sessions.count()
)
)
for index, session in enumerate(old_sessions):
session.delete()
if str(idx).endswith('000'):
self.stdout.write("{0} records deleted".format(index))
self.stdout.write("{0} expired sessions remaining".format(
Session.objects.filter(expire_date__lt=datetime.now())
)
)
|
from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... print "{0} records left".format(Session.objects.filter(expire_date__lt=now).count())
...
"""
class Command(NoArgsCommand):
args = '<count count ...>'
help = "Delete old sessions"
def handle(self, *args, **options):
old_sessions = Session.objects.filter(expire_date__lt=datetime.now())
self.stdout.write("Deleting {0} expired sessions".format(
old_sessions.count()
)
)
for index, session in enumerate(old_sessions):
session.delete()
if str(idx).endswith('000'):
self.stdout.write("{0} records deleted".format(index))
self.stdout.write("{0} expired sessions remaining".format(
Session.objects.filter(expire_date__lt=datetime.now())
)
)
|
Reduce padding for address-list to make it fit on mobile displays
|
// @flow
import type { AddressMap, KnxAddress } from '../types';
import React from 'react';
import createStore from '../lib/create-store';
import withRedux from 'next-redux-wrapper';
import App from '../components/App';
import WithBusSubsribe from '../components/WithBusSubribe';
import AddressList from '../components/AddressList';
import AppBar from '../components/AppBar';
import { compose, reject } from 'ramda';
const styles = {
container: {
textAlign: 'center',
padding: '10px',
},
};
/* Built address-list, remove some address-types which should not be displayed */
const addrFilter = reject((addr: KnxAddress) => addr.type === 'fb');
const IndexPage = props => {
const { livestate }: AddressMap = addrFilter(props.smartHome);
return (
<App>
<div className="app">
<AppBar />
<div style={styles.container}>
<AddressList addresses={livestate} />
</div>
</div>
</App>
);
};
export default compose(
withRedux(createStore, state => ({ smartHome: state.smartHome })),
WithBusSubsribe
)(IndexPage);
|
// @flow
import type { AddressMap, KnxAddress } from '../types';
import React from 'react';
import createStore from '../lib/create-store';
import withRedux from 'next-redux-wrapper';
import App from '../components/App';
import WithBusSubsribe from '../components/WithBusSubribe';
import AddressList from '../components/AddressList';
import AppBar from '../components/AppBar';
import { compose, reject } from 'ramda';
const styles = {
container: {
textAlign: 'center',
padding: '50px',
},
};
/* Built address-list, remove some address-types which should not be displayed */
const addrFilter = reject((addr: KnxAddress) => addr.type === 'fb');
const IndexPage = props => {
const { livestate }: AddressMap = addrFilter(props.smartHome);
return (
<App>
<div className="app">
<AppBar />
<div style={styles.container}>
<AddressList addresses={livestate} />
</div>
</div>
</App>
);
};
export default compose(
withRedux(createStore, state => ({ smartHome: state.smartHome })),
WithBusSubsribe
)(IndexPage);
|
Fix & W3 Validation Fail in a Links
|
<?php
/**
* Url.php
* Contains the Thinker\Http\Url class
*
* @author Cory Gehr
*/
namespace Thinker\Http;
class Url {
/**
* __construct()
* Constructor for the Thinker\Http\Url class
* This is intentionally private, so that it cannot be
* instantiated
*
* @author Cory Gehr
* @access private
*/
private function __construct() {}
/**
* create()
* Creates an internal site URL
*
* @author Cory Gehr
* @access public
* @static
* @param string $section Section Name
* @param string $subsection Subsection Name (default: null)
* @param string[] $params URL Parameters (default: empty array)
* @return string Full URL to Item
*/
public static function create($section, $subsection = null, $params = array())
{
$url = BASE_URL . 'index.php?s=' . urlencode($section);
if($subsection)
{
$url .= "&su=" . urlencode($subsection);
}
// Add URL Parameters
if(count($params) > 0)
{
foreach($params as $key => $value)
{
$url .= ("&$key=" . urlencode($value));
}
}
return $url;
}
}
?>
|
<?php
/**
* Url.php
* Contains the Thinker\Http\Url class
*
* @author Cory Gehr
*/
namespace Thinker\Http;
class Url {
/**
* __construct()
* Constructor for the Thinker\Http\Url class
* This is intentionally private, so that it cannot be
* instantiated
*
* @author Cory Gehr
* @access private
*/
private function __construct() {}
/**
* create()
* Creates an internal site URL
*
* @author Cory Gehr
* @access public
* @static
* @param string $section Section Name
* @param string $subsection Subsection Name (default: null)
* @param string[] $params URL Parameters (default: empty array)
* @return string Full URL to Item
*/
public static function create($section, $subsection = null, $params = array())
{
$url = BASE_URL . 'index.php?s=' . urlencode($section);
if($subsection)
{
$url .= "&su=" . urlencode($subsection);
}
// Add URL Parameters
if(count($params) > 0)
{
foreach($params as $key => $value)
{
$url .= ("&$key=" . urlencode($value));
}
}
return $url;
}
}
?>
|
Fix a bug in browser detection
|
// FeatureDetection
// IE 9 or older
const isIE9OrOlder = () => {
return (navigator.appVersion.indexOf('MSIE') !== -1) &&
(parseFloat(navigator.appVersion.split('MSIE')[1]) < 10);
};
// IE 10
const isIE10 = () => {
if (Function('/*@cc_on return document.documentMode===10@*/')()) {
return true;
}
return false;
};
// IE 10 or older
const isIE10OrOlder = () => {
return isIE10() || isIE9OrOlder();
};
// CSS transforms
const supportsCSSTransforms = () => {
const transforms = [
'transform',
'webkitTransform',
'WebkitTransform',
'mozTransform',
'MozTransform',
'oTransform',
'OTransform',
'msTransform'
];
let div = document.createElement('div');
for (let i = 0; i < transforms.length; i++) {
if ((typeof div.style[transforms[i]]) !== 'undefined') {
return true;
}
}
return false;
};
// SVG
const supportsSVG = () => {
return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');
}
export default {
isIE9OrOlder,
isIE10,
isIE10OrOlder,
supportsCSSTransforms,
supportsSVG
};
|
// FeatureDetection
// IE 9 or older
const isIE9OrOlder = () => {
return (navigator.appVersion.indexOf('MSIE') !== -1) &&
(parseFloat(navigator.appVersion.split('MSIE')[1]) < 10);
};
// IE 10
const isIE10 = () => {
if (Function('/*@cc_on return document.documentMode===10@*/')()) {
return true;
}
return false;
};
// IE 10 or older
const isIE10OrOlder = () => {
return isIE10() && isIE9OrOlder();
};
// CSS transforms
const supportsCSSTransforms = () => {
const transforms = [
'transform',
'webkitTransform',
'WebkitTransform',
'mozTransform',
'MozTransform',
'oTransform',
'OTransform',
'msTransform'
];
let div = document.createElement('div');
for (let i = 0; i < transforms.length; i++) {
if ((typeof div.style[transforms[i]]) !== 'undefined') {
return true;
}
}
return false;
};
// SVG
const supportsSVG = () => {
return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1');
}
export default {
isIE9OrOlder,
isIE10,
isIE10OrOlder,
supportsCSSTransforms,
supportsSVG
};
|
Allow for ranged enemies to define what exactly they do when they shoot
|
package com.ezardlabs.lostsector.ai;
import com.ezardlabs.dethsquare.Transform;
import com.ezardlabs.lostsector.ai.RangedBehaviour.Builder.ShootAction;
public class RangedBehaviour extends Behaviour {
private final float range;
private final ShootAction shootAction;
RangedBehaviour(float moveSpeed, boolean willPatrol, float visionRange, float range, ShootAction shootAction) {
super(moveSpeed, willPatrol, visionRange);
this.range = range;
this.shootAction = shootAction;
}
@Override
protected CombatState onEnemySighted(Transform self, Transform enemy) {
if (Math.abs(self.position.x - enemy.position.x) <= range) {
return CombatState.ATTACKING;
} else {
return CombatState.TRACKING;
}
}
@Override
protected CombatState attack(Transform self, Transform target) {
shootAction.onShoot(self, target);
return CombatState.ATTACKING;
}
public static class Builder extends Behaviour.Builder<Builder> {
private float range = 1500;
private ShootAction shootAction;
public Builder setRange(float range) {
this.range = range;
return this;
}
public Builder setShootAction(ShootAction shootAction) {
this.shootAction = shootAction;
return this;
}
@Override
public RangedBehaviour create() {
return new RangedBehaviour(moveSpeed, willPatrol, visionRange, range, shootAction);
}
public interface ShootAction {
void onShoot(Transform self, Transform target);
}
}
}
|
package com.ezardlabs.lostsector.ai;
import com.ezardlabs.dethsquare.Transform;
public class RangedBehaviour extends Behaviour {
private final float range;
RangedBehaviour(float moveSpeed, boolean willPatrol, float visionRange, float range) {
super(moveSpeed, willPatrol, visionRange);
this.range = range;
}
@Override
protected CombatState onEnemySighted(Transform self, Transform enemy) {
if (Math.abs(self.position.x - enemy.position.x) <= range) {
return CombatState.ATTACKING;
} else {
return CombatState.TRACKING;
}
}
@Override
protected CombatState attack(Transform self, Transform target) {
return null;
}
public static class Builder extends Behaviour.Builder<Builder> {
private float range = 1500;
public Builder setRange(float range) {
this.range = range;
return this;
}
@Override
public RangedBehaviour create() {
return new RangedBehaviour(moveSpeed, willPatrol, visionRange, range);
}
}
}
|
Fix neutron server crash introduced by trunk code
When running pre-stable/ocata neutron code the networking_cisco trunk
code was crashing due to incorrect backwards_compatibility implementation.
Change-Id: I8188f8d16313166418d207c99124e2763eb669a1
|
# Copyright (c) 2017 Cisco Systems, 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.
# Stub module containing the networking_cisco trunk APIs.
#
# Required for tox testing for neutron stable/mitaka.
# TODO(rcurran): Remove once networking_cisco is no longer supporting
# stable/mitaka.
TRUNK_SUBPORT_OWNER = ""
VLAN = ""
class DriverBase(object):
def __init__(self, name, interfaces, segmentation_types,
agent_type=None, can_trunk_bound_port=False):
pass
|
# Copyright (c) 2017 Cisco Systems, 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.
# Stub module containing the networking_cisco trunk APIs.
#
# Required for tox testing for neutron stable/mitaka.
# TODO(rcurran): Remove once networking_cisco is no longer supporting
# stable/mitaka.
TRUNK_SUBPORT_OWNER = ""
class NexusMDTrunkHandler(object):
def _stub_trunk(self, *args):
return False
is_trunk_parentport = _stub_trunk
is_trunk_subport = _stub_trunk
class NexusTrunkDriver(object):
def create(self):
pass
class DriverBase(object):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.