text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix Memcachestat. Using wrong classname | <?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_Memcache::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?> | <?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_MemcacheStore::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?> |
Use page_published signal for cache invalidation instead of post_save | from django.db import models
from django.db.models.signals import post_delete
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.signals import page_published
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def page_published_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def post_delete_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def register_signal_handlers():
# Get list of models that are page types
indexed_models = [model for model in models.get_models() if issubclass(model, Page)]
# Loop through list and register signal handlers for each one
for model in indexed_models:
page_published.connect(page_published_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
| from django.db import models
from django.db.models.signals import post_save, post_delete
from wagtail.wagtailcore.models import Page
from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache
def post_save_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def post_delete_signal_handler(instance, **kwargs):
purge_page_from_cache(instance)
def register_signal_handlers():
# Get list of models that are page types
indexed_models = [model for model in models.get_models() if issubclass(model, Page)]
# Loop through list and register signal handlers for each one
for model in indexed_models:
post_save.connect(post_save_signal_handler, sender=model)
post_delete.connect(post_delete_signal_handler, sender=model)
|
Make replaceText() count the sub-groups.
Instead of requiring the number of capturing groups as an argument,
match the provided expression with the empty string to see how many
groups are captured.
(cburschka/cadence#235) | (function($){
var textNode = function(node, search, replace, capturing) {
var tokens = node.nodeValue.split(search);
if (tokens.length < 2) return false;
for (var i = 0; i+capturing < tokens.length; i += capturing+1) {
$(node).before(document.createTextNode(tokens[i]));
$(node).before(replace(tokens.slice(i+1, i+1+capturing)));
}
$(node).before(document.createTextNode(tokens[tokens.length-1]));
return true;
};
/**
* Replace substrings with HTML.
*
* @param node A text node.
* @param search A RegExp object that must have at least one capturing subgroup.
* @param replace A function that generates the replacement jQuery content.
*/
$.fn.replaceText = function(search, replace) {
var capturing = RegExp(search.source + '|').exec('').length - 1;
return this.each(function() {
var remove = [];
for (var node = this.firstChild; node; node = node.nextSibling) {
if (node.nodeType == document.TEXT_NODE && textNode(node, search, replace, capturing)) {
remove.push(node);
}
}
$(remove).remove();
});
}
})(jQuery);
| (function($){
var textNode = function(node, search, replace, capturing) {
var tokens = node.nodeValue.split(search);
if (tokens.length < 2) return false;
for (var i = 0; i+capturing < tokens.length; i += capturing+1) {
$(node).before(document.createTextNode(tokens[i]));
$(node).before(replace(tokens.slice(i+1, i+1+capturing)));
}
$(node).before(document.createTextNode(tokens[tokens.length-1]));
return true;
};
/**
* Replace substrings with HTML.
*
* @param node A text node.
* @param search A RegExp object that must have at least one capturing subgroup.
* @param replace A function that generates the replacement jQuery content.
* @param groups (optional) The number of capturing subgroups in the RegExp.
*/
$.fn.replaceText = function(search, replace, capturing) {
capturing = capturing || 1;
return this.each(function() {
var remove = [];
for (var node = this.firstChild; node; node = node.nextSibling) {
if (node.nodeType == document.TEXT_NODE && textNode(node, search, replace, capturing)) {
remove.push(node);
}
}
$(remove).remove();
});
}
})(jQuery);
|
Fix compatible bug: file() -> open(). | #!/usr/bin/env python
from distutils.core import setup
from catplot import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'scipy',
'matplotlib',
]
license = 'LICENSE'
long_description = open('README.md').read()
name = 'python-catplot'
packages = [
'catplot',
]
platforms = ['linux', 'windows']
url = 'https://github.com/PytLab/catplot'
download_url = 'https://github.com/PytLab/catplot/releases'
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
| #!/usr/bin/env python
from distutils.core import setup
from catplot import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'scipy',
'matplotlib',
]
license = 'LICENSE'
long_description = file('README.md').read()
name = 'python-catplot'
packages = [
'catplot',
]
platforms = ['linux', 'windows']
url = 'https://github.com/PytLab/catplot'
download_url = 'https://github.com/PytLab/catplot/releases'
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
|
Refactor for using the new Response class | <?php
namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank\V1;
use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\ToneAnalyser\V3\ToneAnalyserService;
class ToneAnalyserV3Test extends AbstractTestCase
{
/**
* @var ToneAnalyserService
*/
public $service;
public function setUp()
{
parent::setUp();
$this->service = new ToneAnalyserService();
}
public function test_if_url_is_set()
{
$this->assertEquals(
'https://watson-api-explorer.mybluemix.net/tone-analyzer/api',
$this->service->getUrl()
);
}
public function test_if_version_is_set()
{
$this->assertEquals(
'v3',
$this->service->getVersion()
);
}
public function test_can_analyse_plain_text()
{
$response = $this->service->plainText('Example text to analyse, duuh!');
$this->assertArrayHasKey('document_tone', json_decode($response->getContent(), true));
}
} | <?php
namespace PhpWatson\Sdk\Tests\Language\RetrieveAndRank\V1;
use PhpWatson\Sdk\Tests\AbstractTestCase;
use PhpWatson\Sdk\Language\ToneAnalyser\ToneAnalyserService;
class ToneAnalyserV3Test extends AbstractTestCase
{
/**
* @var ToneAnalyserService
*/
public $service;
public function setUp()
{
parent::setUp();
$this->service = new ToneAnalyserService();
}
public function test_if_url_is_set()
{
$this->assertEquals(
'https://watson-api-explorer.mybluemix.net/tone-analyzer/api',
$this->service->getUrl()
);
}
public function test_if_version_is_set()
{
$this->assertEquals(
'v3',
$this->service->getVersion()
);
}
public function test_can_analyse_plain_text()
{
$response = $this->service->plainText('Example text to analyse, duuh!');
$this->assertArrayHasKey('document_tone', json_decode($response->getBody()->getContents(), true));
}
} |
Complete tests for checking that no new enumerable properties are being added to new objects.
Added tests for array, number and regexp.
Extracted assertion to its own method. | 'use strict';
/**
* Run package tests.
* (C) 2013 Alex Fernández.
*/
// requires
var testing = require('testing');
var _prettyPrint = require('util').inspect;
/**
* Test that new objects, strings, arrays, numbers
* and regular expressions have no enumerable properties.
*/
function testCleanObjects(callback)
{
_assertIsClean({}, callback);
_assertIsClean('', callback);
_assertIsClean([], callback);
_assertIsClean(41.5, callback);
_assertIsClean(/abc/, callback);
testing.success(callback);
}
function _assertIsClean(newObject, callback) {
for (var key in newObject) {
testing.failure('New object ' +
_prettyPrint(newObject) +
' has enumerable property %s', key, callback);
}
}
/**
* Run all module tests.
*/
exports.test = function(callback)
{
var tests = {
cleanObjects: testCleanObjects,
};
var files = [ 'core', 'string', 'array', 'math', 'object' ];
files.forEach(function(file)
{
tests[file] = require('./test/' + file + '.js').test;
});
testing.run(tests, callback);
};
// run tests if invoked directly
if (__filename == process.argv[1])
{
exports.test(testing.show);
}
| 'use strict';
/**
* Run package tests.
* (C) 2013 Alex Fernández.
*/
// requires
var testing = require('testing');
/**
* Test that a new object is clean: has no functions.
* Same for string and array.
*/
function testCleanObjects(callback)
{
var object = {};
for (var key in object)
{
testing.fail('New object has attribute %s', key, callback);
}
var string = '';
for (key in string)
{
testing.fail('New string has attribute %s', key, callback);
}
testing.success(callback);
}
/**
* Run all module tests.
*/
exports.test = function(callback)
{
var tests = {
cleanObjects: testCleanObjects,
};
var files = [ 'core', 'string', 'array', 'math', 'object' ];
files.forEach(function(file)
{
tests[file] = require('./test/' + file + '.js').test;
});
testing.run(tests, callback);
};
// run tests if invoked directly
if (__filename == process.argv[1])
{
exports.test(testing.show);
}
|
Fix in string representation of unit of measurement. | from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
| from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.name)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
Add comments for getting vk token | /**
* Created by Андрей on 29.11.2015.
*/
var config = {};
config.vk = {};
config.mail = {};
config.mail.strings = {};
config.vk.appId = 5167405;
config.vk.appSecret = process.env.VK_APP_SECRET || "vk_app_secret";
//You need to get a token for STANDALONE APPLICATIONS with permissions 'messages' and 'offline'
//See more: https://vk.com/dev/permissions
config.vk.token = "user_access_token_who_sends_messages_to_vk";
config.vk.peerId = "user_or_chat_id";
config.mail.login = process.env.MAIL_USER || 'example@gmail.com';
config.mail.password = process.env.MAIL_PASSWORD || 'password';
config.mail.host = "imap.gmail.com"; //IMAP server host
config.mail.port = 993; // IMAP server port
config.mail.tls = true;
config.mail.markSeen = false;
config.mail.fetchUnreadOnStart = true;
config.mail.strings.subject = "Тема: ";
config.mail.strings.from = "От: ";
config.mail.strings.body = "Тело: ";
module.exports = config;
| /**
* Created by Андрей on 29.11.2015.
*/
var config = {};
config.vk = {};
config.mail = {};
config.mail.strings = {};
config.vk.appId = 5167405;
config.vk.appSecret = process.env.VK_APP_SECRET || "vk_app_secret";
config.vk.token = "user_access_token_who_sends_messages_to_vk";
config.vk.peerId = "user_or_chat_id";
config.mail.login = process.env.MAIL_USER || 'example@gmail.com';
config.mail.password = process.env.MAIL_PASSWORD || 'password';
config.mail.host = "imap.gmail.com"; //IMAP server host
config.mail.port = 993; // IMAP server port
config.mail.tls = true;
config.mail.markSeen = false;
config.mail.fetchUnreadOnStart = true;
config.mail.strings.subject = "Тема: ";
config.mail.strings.from = "От: ";
config.mail.strings.body = "Тело: ";
module.exports = config;
|
Set both jpg and m4v creation dates | const photos = Application('photos');
const terminal = Application('terminal');
const albums = photos.albums();
const pad = (val) => String(val).length < 2 ? '0' + val : String(val);
const app = Application.currentApplication()
app.includeStandardAdditions = true;
albums.forEach(album => {
const name = album.name();
const items = album.mediaItems();
const path = Path('./export/' + name);
items.forEach(item => {
const filename = item.filename();
const date = item.date();
const formattedDate = pad(date.getMonth() + 1) + '/' +
pad(date.getDate()) + '/' +
date.getFullYear() + ' ' +
pad(date.getHours()) + ':' +
pad(date.getMinutes()) + ':' +
pad(date.getSeconds());
console.log(filename + ' => ' + path);
photos.export([item], {to: path});
const fileRegex = /(.*)\.[0-9A-Za-z]+$/;
const target = (path + '/' + filename);
[
target.replace(fileRegex, '$1.m4v'),
target.replace(fileRegex, '$1.jpg')
].forEach((file) => {
const cmd = 'ls "' + file + '" && ' +
'SetFile -d "' + formattedDate + '" "' + file + '"';
try {
app.doShellScript(cmd);
} catch (e) {
}
});
});
});
| const photos = Application('photos');
const terminal = Application('terminal');
const albums = photos.albums();
const pad = (val) => String(val).length < 2 ? '0' + val : String(val);
const app = Application.currentApplication()
app.includeStandardAdditions = true;
albums.forEach(album => {
const name = album.name();
const items = album.mediaItems();
const path = Path('./export/' + name);
items.forEach(item => {
const filename = item.filename();
const date = item.date();
const formattedDate = pad(date.getMonth() + 1) + '/' +
pad(date.getDate()) + '/' +
date.getFullYear() + ' ' +
pad(date.getHours()) + ':' +
pad(date.getMinutes()) + ':' +
pad(date.getSeconds());
console.log(filename + ' => ' + path);
photos.export([item], {to: path});
const videoPath = (path + '/' + filename).replace(/(.*)\.[0-9A-Za-z]+$/, '$1.m4v');
const cmd = 'ls "' + videoPath + '" && ' +
'SetFile -d "' + formattedDate + '" "' + videoPath + '"';
try {
app.doShellScript(cmd);
console.log('Set creation date for video file');
} catch (e) {
}
});
});
|
Make some more changes to custom bpmnjs modeller | 'use strict';
// inlined diagram; load it from somewhere else if you like
var pizzaDiagram = require('../resources/pizza-collaboration.bpmn');
// custom elements JSON; load it from somewhere else if you like
var customElements = require('./custom-elements.json');
// our custom modeler
var CustomModeler = require('./custom-modeler');
var propertiesPanelModule = require('bpmn-js-properties-panel'),
propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/camunda'),
camundaModdleDescriptor = require('camunda-bpmn-moddle/resources/camunda');
var modeler = new CustomModeler({
container: '#canvas',
keyboard: { bindTo: document },
propertiesPanel: {
parent: '#js-properties-panel'
},
additionalModules: [propertiesPanelModule,propertiesProviderModule],
moddleExtensions: {
camunda: camundaModdleDescriptor
}
});
modeler.importXML(pizzaDiagram, function(err) {
if (err) {
console.error('something went wrong:', err);
}
modeler.get('canvas').zoom('fit-viewport');
modeler.addCustomElements(customElements);
});
// expose bpmnjs to window for debugging purposes
window.bpmnjs = modeler;
| 'use strict';
// inlined diagram; load it from somewhere else if you like
var pizzaDiagram = require('../resources/pizza-collaboration.bpmn');
// custom elements JSON; load it from somewhere else if you like
var customElements = require('./custom-elements.json');
// our custom modeler
var CustomModeler = require('./custom-modeler');
var propertiesPanelModule = require('bpmn-js-properties-panel'),
propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/camunda'),
camundaModdleDescriptor = require('camunda-bpmn-moddle/resources/camunda');
var modeler = new CustomModeler({
container: '#canvas',
keyboard: { bindTo: document },
propertiesPanel: {
parent: '#js-properties-panel'
},
additionalModules: [propertiesPanelModule,propertiesProviderModule],
moddleExtensions: {
magic: camundaModdleDescriptor
}
});
modeler.importXML(pizzaDiagram, function(err) {
if (err) {
console.error('something went wrong:', err);
}
modeler.get('canvas').zoom('fit-viewport');
modeler.addCustomElements(customElements);
});
// expose bpmnjs to window for debugging purposes
window.bpmnjs = modeler;
|
Fix link to checkout confirmation. | package purchase;
import common.contexts.UserContext;
import common.controllers.ControllerDependency;
import common.models.ProductDataConfig;
import common.pages.SunrisePageData;
import io.sphere.sdk.carts.Cart;
import play.i18n.Messages;
import play.libs.F;
import play.mvc.Result;
import javax.inject.Inject;
public class CheckoutPaymentController extends CartController {
private final ProductDataConfig productDataConfig;
@Inject
public CheckoutPaymentController(final ControllerDependency controllerDependency, final ProductDataConfig productDataConfig) {
super(controllerDependency);
this.productDataConfig = productDataConfig;
}
public F.Promise<Result> show(final String languageTag) {
final UserContext userContext = userContext(languageTag);
final F.Promise<Cart> cartPromise = getOrCreateCart(userContext, session());
return cartPromise.map(cart -> {
final Messages messages = messages(userContext);
final CheckoutPaymentPageContent content = new CheckoutPaymentPageContent(cart, userContext, productDataConfig, reverseRouter());
final SunrisePageData pageData = pageData(userContext, content, ctx());
return ok(templateService().renderToHtml("checkout-payment", pageData, userContext.locales()));
});
}
public Result process(final String language) {
return redirect(reverseRouter().showCheckoutConfirmationForm(language));
}
}
| package purchase;
import common.contexts.UserContext;
import common.controllers.ControllerDependency;
import common.models.ProductDataConfig;
import common.pages.SunrisePageData;
import io.sphere.sdk.carts.Cart;
import play.i18n.Messages;
import play.libs.F;
import play.mvc.Result;
import javax.inject.Inject;
public class CheckoutPaymentController extends CartController {
private final ProductDataConfig productDataConfig;
@Inject
public CheckoutPaymentController(final ControllerDependency controllerDependency, final ProductDataConfig productDataConfig) {
super(controllerDependency);
this.productDataConfig = productDataConfig;
}
public F.Promise<Result> show(final String languageTag) {
final UserContext userContext = userContext(languageTag);
final F.Promise<Cart> cartPromise = getOrCreateCart(userContext, session());
return cartPromise.map(cart -> {
final Messages messages = messages(userContext);
final CheckoutPaymentPageContent content = new CheckoutPaymentPageContent(cart, userContext, productDataConfig, reverseRouter());
final SunrisePageData pageData = pageData(userContext, content, ctx());
return ok(templateService().renderToHtml("checkout-payment", pageData, userContext.locales()));
});
}
public Result process(final String language) {
return redirect(reverseRouter().showCheckoutPaymentForm(language));
}
}
|
Add comment about kaggle_gcp module path. | import os
kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN")
bq_user_jwt = os.getenv("KAGGLE_BQ_USER_JWT")
if kaggle_proxy_token or bq_user_jwt:
from google.auth import credentials
from google.cloud import bigquery
from google.cloud.bigquery._http import Connection
# TODO: Update this to the correct kaggle.gcp path once we no longer inject modules
# from the worker.
from kaggle_gcp import PublicBigqueryClient
def monkeypatch_bq(bq_client, *args, **kwargs):
data_proxy_project = os.getenv("KAGGLE_DATA_PROXY_PROJECT")
specified_project = kwargs.get('project')
specified_credentials = kwargs.get('credentials')
if specified_project is None and specified_credentials is None:
print("Using Kaggle's public dataset BigQuery integration.")
return PublicBigqueryClient(*args, **kwargs)
else:
return bq_client(*args, **kwargs)
# Monkey patches BigQuery client creation to use proxy or user-connected GCP account.
# Deprecated in favor of Kaggle.DataProxyClient().
# TODO: Remove this once uses have migrated to that new interface.
bq_client = bigquery.Client
bigquery.Client = lambda *args, **kwargs: monkeypatch_bq(
bq_client, *args, **kwargs)
| import os
kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN")
bq_user_jwt = os.getenv("KAGGLE_BQ_USER_JWT")
if kaggle_proxy_token or bq_user_jwt:
from google.auth import credentials
from google.cloud import bigquery
from google.cloud.bigquery._http import Connection
from kaggle_gcp import PublicBigqueryClient
def monkeypatch_bq(bq_client, *args, **kwargs):
data_proxy_project = os.getenv("KAGGLE_DATA_PROXY_PROJECT")
specified_project = kwargs.get('project')
specified_credentials = kwargs.get('credentials')
if specified_project is None and specified_credentials is None:
print("Using Kaggle's public dataset BigQuery integration.")
return PublicBigqueryClient(*args, **kwargs)
else:
return bq_client(*args, **kwargs)
# Monkey patches BigQuery client creation to use proxy or user-connected GCP account.
# Deprecated in favor of Kaggle.DataProxyClient().
# TODO: Remove this once uses have migrated to that new interface.
bq_client = bigquery.Client
bigquery.Client = lambda *args, **kwargs: monkeypatch_bq(
bq_client, *args, **kwargs)
|
Update docs for build unit. | """Build unit from data pack."""
from tqdm import tqdm
from matchzoo import processor_units
from .data_pack import DataPack
def build_unit_from_data_pack(
unit: processor_units.StatefulProcessorUnit,
data_pack: DataPack, flatten: bool = True,
verbose: int = 1
) -> processor_units.StatefulProcessorUnit:
"""
Build a :class:`StatefulProcessorUnit` from a :class:`DataPack` object.
:param unit: :class:`StatefulProcessorUnit` object to be built.
:param data_pack: The input :class:`DataPack` object.
:param flatten: Flatten the datapack or not. `True` to organize the
:class:`DataPack` text as a list, and `False` to organize
:class:`DataPack` text as a list of list.
:param verbose: Verbosity.
:return: A built :class:`StatefulProcessorUnit` object.
"""
corpus = []
if flatten:
data_pack.apply_on_text(corpus.extend, verbose=verbose)
else:
data_pack.apply_on_text(corpus.append, verbose=verbose)
if verbose:
description = 'Building ' + unit.__class__.__name__ + \
' from a datapack.'
corpus = tqdm(corpus, desc=description)
unit.fit(corpus)
return unit
| from tqdm import tqdm
from .data_pack import DataPack
from matchzoo import processor_units
def build_unit_from_data_pack(
unit: processor_units.StatefulProcessorUnit,
data_pack: DataPack, flatten: bool = True,
verbose: int = 1
) -> processor_units.StatefulProcessorUnit:
"""
Build a :class:`StatefulProcessorUnit` from a :class:`DataPack` object.
:param unit: :class:`StatefulProcessorUnit` object to be built.
:param data_pack: The input :class:`DataPack` object.
:param flatten: Flatten the datapack or not. `True` to organize the
:class:`DataPack` text as a list, and `False` to organize
:class:`DataPack` text as a list of list.
:param verbose: Verbosity.
:return: A built :class:`StatefulProcessorUnit` object.
"""
corpus = []
if flatten:
data_pack.apply_on_text(corpus.extend, verbose=verbose)
else:
data_pack.apply_on_text(corpus.append, verbose=verbose)
if verbose:
description = 'Building ' + unit.__class__.__name__ + \
' from a datapack.'
corpus = tqdm(corpus, desc=description)
unit.fit(corpus)
return unit
|
Fix Int64 constructor to be documented as having optional params. | 'use strict';
// TODO: Make everything handle signed int64 properly...
/**
* A class for wrapping a 64-bit integer in Javascript to avoid loss
* of precision issues at high values.
*
* @constructor
* @param {number} [lo]
* @param {number} [hi]
*/
function Int64(lo, hi) {
if (lo === undefined && hi === undefined) {
lo = 0;
hi = 0;
}
this.lo = lo;
this.hi = hi;
}
Int64.prototype.isBitSet = function(bit) {
if (bit < 32) {
return this.lo & (1 << bit);
} else {
return this.hi & (1 << (bit-32));
}
};
Int64.prototype.toString = function(radix) {
if (radix === 10 || radix === undefined) {
return '?int64_tostring_badradix?';
} else if (radix === 16) {
var str = this.lo.toString(16);
while (str.length < 8) {
str = '0' + str;
}
return this.hi.toString(16) + str;
} else {
return '?int64_tostring_badradix?';
}
};
Int64.prototype.toNumber = function() {
return this.hi << 32 | this.lo;
};
| 'use strict';
// TODO: Make everything handle signed int64 properly...
/**
* A class for wrapping a 64-bit integer in Javascript to avoid loss
* of precision issues at high values.
*
* @constructor
* @param {number} lo
* @param {number} hi
*/
function Int64(lo, hi) {
if (lo === undefined && hi === undefined) {
lo = 0;
hi = 0;
}
this.lo = lo;
this.hi = hi;
}
Int64.prototype.isBitSet = function(bit) {
if (bit < 32) {
return this.lo & (1 << bit);
} else {
return this.hi & (1 << (bit-32));
}
};
Int64.prototype.toString = function(radix) {
if (radix === 10 || radix === undefined) {
return '?int64_tostring_badradix?';
} else if (radix === 16) {
var str = this.lo.toString(16);
while (str.length < 8) {
str = '0' + str;
}
return this.hi.toString(16) + str;
} else {
return '?int64_tostring_badradix?';
}
};
Int64.prototype.toNumber = function() {
return this.hi << 32 | this.lo;
};
|
Revert "Deactivate watchman on CI"
This reverts commit 140770d43013dd8ca54c2031f93c344ee5c59f89.
This did not fix CI problems | // @flow
/* eslint-disable require-await */
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* @format
*/
const path = require('path');
const sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/\.build[/\\].*/,
/ios[/\\]build[/\\].*/,
// /.*\/__tests__\/.*/,
];
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
resolver: {
blacklistRE: new RegExp(
'(' +
sharedBlacklist
.map(regexp => regexp.source.replace(/\//g, path.sep))
.join('|') +
')$',
),
},
};
| // @flow
/* eslint-disable require-await */
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* @format
*/
const path = require('path');
const { IS_CI } = process.env;
const sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/\.build[/\\].*/,
/ios[/\\]build[/\\].*/,
// /.*\/__tests__\/.*/,
];
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
resolver: {
blacklistRE: new RegExp(
'(' +
sharedBlacklist
.map(regexp => regexp.source.replace(/\//g, path.sep))
.join('|') +
')$',
),
},
useWatchman: IS_CI === undefined,
};
|
Move package declaration underneath license block | /*
* Copyright 2014 StormCloud Development Group
*
* 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 io.github.stormcloud_dev.stormcloud;
public class Player {
private double MId, objectIndex;
private String name;
private CrewMember clazz;
public Player(double MId, double objectIndex) {
this.MId = MId;
this.objectIndex = objectIndex;
this.clazz = CrewMember.COMMANDO;
this.name = "Anonymous";
}
public double getMId() {
return MId;
}
public double getObjectIndex() {
return objectIndex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CrewMember getClazz() {
return clazz;
}
public void setClazz(CrewMember clazz) {
this.clazz = clazz;
}
}
| package io.github.stormcloud_dev.stormcloud;
/*
* Copyright 2014 StormCloud Development Group
*
* 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.
*/
public class Player {
private double MId, objectIndex;
private String name;
private CrewMember clazz;
public Player(double MId, double objectIndex) {
this.MId = MId;
this.objectIndex = objectIndex;
this.clazz = CrewMember.COMMANDO;
this.name = "Anonymous";
}
public double getMId() {
return MId;
}
public double getObjectIndex() {
return objectIndex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CrewMember getClazz() {
return clazz;
}
public void setClazz(CrewMember clazz) {
this.clazz = clazz;
}
}
|
Use default config_handlers to load custom file | <?php
class sfRavenPluginConfiguration extends sfPluginConfiguration
{
const CONFIG_PATH = 'config/raven.yml';
protected $errorHandler;
/**
* Initializes the plugin.
*
* This method is called after the plugin's classes have been added to sfAutoload.
*/
public function initialize()
{
if ($this->configuration instanceof sfApplicationConfiguration)
{
require $this->configuration->getConfigCache()->checkConfig(self::CONFIG_PATH);
$dsn = sfConfig::get('raven_client_dsn', sfConfig::get('raven_dsn')); // Keep BC
$options = sfConfig::get('raven_client_options', array());
if (!$dsn)
{
return;
}
$client = new sfRavenClient($dsn, $options);
$this->errorHandler = new Raven_ErrorHandler($client);
$this->errorHandler->registerExceptionHandler();
$this->errorHandler->registerErrorHandler(true, E_ALL | E_STRICT);
$this->errorHandler->registerShutdownFunction(500);
$this->dispatcher->connect('application.throw_exception', array($this, 'listenToExceptions'));
}
}
public function listenToExceptions($event)
{
$this->errorHandler->handleException($event->getSubject());
}
}
| <?php
class sfRavenPluginConfiguration extends sfPluginConfiguration
{
const CONFIG_PATH = 'config/raven.yml';
protected $errorHandler;
/**
* Initializes the plugin.
*
* This method is called after the plugin's classes have been added to sfAutoload.
*/
public function initialize()
{
if ($this->configuration instanceof sfApplicationConfiguration)
{
$configCache = $this->configuration->getConfigCache();
$configCache->registerConfigHandler(self::CONFIG_PATH, 'sfDefineEnvironmentConfigHandler', array(
'prefix' => 'raven_',
));
require $configCache->checkConfig(self::CONFIG_PATH);
$dsn = sfConfig::get('raven_client_dsn', sfConfig::get('raven_dsn')); // Keep BC
$options = sfConfig::get('raven_client_options', array());
if (!$dsn)
{
return;
}
$client = new sfRavenClient($dsn, $options);
$this->errorHandler = new Raven_ErrorHandler($client);
$this->errorHandler->registerExceptionHandler();
$this->errorHandler->registerErrorHandler(true, E_ALL | E_STRICT);
$this->errorHandler->registerShutdownFunction(500);
$this->dispatcher->connect('application.throw_exception', array($this, 'listenToExceptions'));
}
}
public function listenToExceptions($event)
{
$this->errorHandler->handleException($event->getSubject());
}
}
|
Attach base math utils to sub-namespace | 'use strict';
// MODULES //
var baseDist = require( './base.dist.js' );
var baseRandom = require( './base.random.js' );
var baseSpecial = require( './base.special.js' );
var baseTools = require( './base.tools.js' );
var baseUtils = require( './base.utils.js' );
var genericRandom = require( './generics.random.js' );
var genericStats = require( './generics.statistics.js' );
var genericUtils = require( './generics.utils.js' );
// MAIN //
/**
* Assigns modules to a namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* assign( ns );
* // ns => {...}
*/
function assign( ns ) {
baseDist( ns );
baseRandom( ns );
baseSpecial( ns );
baseTools( ns );
ns.base = {};
baseUtils( ns.base );
genericRandom( ns );
genericUtils( ns );
genericStats( ns );
return ns;
} // end FUNCTION assign()
// EXPORTS //
module.exports = assign;
| 'use strict';
// MODULES //
var baseDist = require( './base.dist.js' );
var baseRandom = require( './base.random.js' );
var baseSpecial = require( './base.special.js' );
var baseTools = require( './base.tools.js' );
var baseUtils = require( './base.utils.js' );
var genericRandom = require( './generics.random.js' );
var genericStats = require( './generics.statistics.js' );
var genericUtils = require( './generics.utils.js' );
// MAIN //
/**
* Assigns modules to a namespace.
*
* @private
* @param {Object} ns - namespace
* @returns {Object} input namespace
*
* @example
* var ns = {};
* assign( ns );
* // ns => {...}
*/
function assign( ns ) {
baseDist( ns );
baseRandom( ns );
baseSpecial( ns );
baseTools( ns );
baseUtils( ns );
genericRandom( ns );
genericUtils( ns );
genericStats( ns );
return ns;
} // end FUNCTION assign()
// EXPORTS //
module.exports = assign;
|
Add missing code (var exp was removed and got back) | /**
* Created by stefas on 19/05/15.
*/
angular.module('myApp.controllers')
.controller('ParameterButtonCtrl', ['$sce', '$scope', '$http',
'defaults', '$controller', 'Session',
function ($sce, $scope, $http, defaults, $controller, Session) {
$controller('CommonCtrl', {
$scope: $scope,
$http: $http,
defaults: defaults,
Session: Session
});
// Store parameters in the cookies
$scope.saveVideoPreferences = function () {
var now = new Date();
var exp = new Date(now.getFullYear(),now.getMonth()+1, now.getDate());
Cookies.set("video.path", $scope.model.videoPath, {
expires: exp
});
};
}
]); | /**
* Created by stefas on 19/05/15.
*/
angular.module('myApp.controllers')
.controller('ParameterButtonCtrl', ['$sce', '$scope', '$http',
'defaults', '$controller', 'Session',
function ($sce, $scope, $http, defaults, $controller, Session) {
$controller('CommonCtrl', {
$scope: $scope,
$http: $http,
defaults: defaults,
Session: Session
});
// Store parameters in the cookies
$scope.saveVideoPreferences = function () {
var now = new Date();
Cookies.set("video.path", $scope.model.videoPath, {
expires: exp
});
};
}
]); |
Fix incorrect entity assignment in Role policy | <?php namespace GeneaLabs\LaravelGovernor\Policies;
use GeneaLabs\LaravelGovernor\Role;
class RolePolicy extends LaravelGovernorPolicy
{
public function create($user, Role $role)
{
return $this->validatePermissions($user, 'create', 'role', $role->created_by);
}
public function edit($user, Role $role)
{
return $this->validatePermissions($user, 'edit', 'role', $role->created_by);
}
public function view($user, Role $role)
{
return $this->validatePermissions($user, 'view', 'role', $role->created_by);
}
public function inspect($user, Role $role)
{
return $this->validatePermissions($user, 'inspect', 'role', $role->created_by);
}
public function remove($user, Role $role)
{
return $this->validatePermissions($user, 'remove', 'role', $role->created_by);
}
}
| <?php namespace GeneaLabs\LaravelGovernor\Policies;
use GeneaLabs\LaravelGovernor\Role;
class RolePolicy extends LaravelGovernorPolicy
{
public function create($user, Role $role)
{
return $this->validatePermissions($user, 'create', 'announcement', $role->created_by);
}
public function edit($user, Role $role)
{
return $this->validatePermissions($user, 'edit', 'announcement', $role->created_by);
}
public function view($user, Role $role)
{
return $this->validatePermissions($user, 'view', 'announcement', $role->created_by);
}
public function inspect($user, Role $role)
{
return $this->validatePermissions($user, 'inspect', 'announcement', $role->created_by);
}
public function remove($user, Role $role)
{
return $this->validatePermissions($user, 'remove', 'announcement', $role->created_by);
}
}
|
Add OSF_URL to send_email helper. | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL, OSF_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
context['osf_url'] = OSF_URL
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
|
Make dataNotFoundHook return if data not ready. | Router.hooks = {
dataNotFound: function (pause) {
var data = this.data();
var tmpl;
if (!this.ready())
return;
if (data === null || typeof data === 'undefined') {
tmpl = this.lookupProperty('notFoundTemplate');
if (tmpl) {
this.render(tmpl);
this.renderRegions();
pause();
}
}
},
loading: function (pause) {
var self = this;
var tmpl;
if (!this.ready()) {
tmpl = this.lookupProperty('loadingTemplate');
if (tmpl) {
this.render(tmpl);
this.renderRegions();
pause();
}
}
}
};
| Router.hooks = {
dataNotFound: function (pause) {
var data = this.data();
var tmpl;
if (data === null || typeof data === 'undefined') {
tmpl = this.lookupProperty('notFoundTemplate');
if (tmpl) {
this.render(tmpl);
this.renderRegions();
pause();
}
}
},
loading: function (pause) {
var self = this;
var tmpl;
if (!this.ready()) {
tmpl = this.lookupProperty('loadingTemplate');
if (tmpl) {
this.render(tmpl);
this.renderRegions();
pause();
}
}
}
};
|
Add boolean form element provider field | angular.module('app.services')
.provider('formElementProvider', function() {
'use strict';
var templates = {
'String': function(field) {
if(field && field.validation.allowedHtml) {
return 'partials/inputs/tinymce-input.html';
} else if(field && field.validation.oneOf) {
return 'partials/inputs/enum-input.html';
} else {
return 'partials/inputs/default-input.html';
}
},
'Link': function(field) {
if(field.kind.isArray) {
return 'partials/inputs/link-multiple-input.html';
}
else {
return 'partials/inputs/link-input.html';
}
},
'Date': 'partials/inputs/date-input.html',
'Boolean': 'partials/inputs/boolean-input.html'
};
return {
$get: function() {
return {
getTemplateUrl: function(field) {
var t = templates[field.kind.name];
if(_.isFunction(t)) {
return t(field);
} else {
return t || templates['String']();
}
}
};
}
};
});
| angular.module('app.services')
.provider('formElementProvider', function() {
'use strict';
var templates = {
'String': function(field) {
if(field && field.validation.allowedHtml) {
return 'partials/inputs/tinymce-input.html';
} else if(field && field.validation.oneOf) {
return 'partials/inputs/enum-input.html';
} else {
return 'partials/inputs/default-input.html';
}
},
'Link': function(field) {
if(field.kind.isArray) {
return 'partials/inputs/link-multiple-input.html';
}
else {
return 'partials/inputs/link-input.html';
}
},
'Date': 'partials/inputs/date-input.html'
};
return {
$get: function() {
return {
getTemplateUrl: function(field) {
var t = templates[field.kind.name];
if(_.isFunction(t)) {
return t(field);
} else {
return t || templates['String']();
}
}
};
}
};
});
|
Fix issue with Ember 2.5.0-beta.1.
Ember 2.5.0-beta.1 includes a "local lookup" feature, that calls
`componentFor` twice with different arguments:
1 `name, owner, { source }` -- Added options with `source` so that
resolver can do local lookup logic based on the invoking template
location.
2. `name, owner, { source: undefined }` -- Source is undefined meaning
that we should look for the "global" component.
The `componentFor` method is paired with `layoutFor` to return the
componet/layout pair. When the normal implementation of `layoutFor`
is called in scenario 1 above, it receives a `source` param, but the
default ember-cli resolver is not local lookup aware so `layoutFor`
with a `source` option always returns undefined. Unfortunately, our
override was not properly passing along all the arguments that we were
invoked with, so the lookup for item 1) above was returning the
component (since the `source` param was not found in options it was
assumed to be the **global** lookup).
This meant that we would return the Component class from the "local
lookup" version of `componentFor`, but that the `layoutFor` invocation
would **never** find a template.
**tldr;** Always call `this._super` with all the arguments... | Ember.ComponentLookup.reopen({
lookupFactory: function(name) {
var Component = this._super.apply(this, arguments);
if (!Component) { return; }
name = name.replace(".","/");
if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
return Component;
}
return Component.reopen({
classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
});
},
componentFor: function(name) {
var Component = this._super.apply(this, arguments);
if (!Component) { return; }
name = name.replace(".","/");
if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
return Component;
}
return Component.reopen({
classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
});
}
});
| Ember.ComponentLookup.reopen({
lookupFactory: function(name, container) {
var Component = this._super(name, container);
if (!Component) { return; }
name = name.replace(".","/");
if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
return Component;
}
return Component.reopen({
classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
});
},
componentFor: function(name, container) {
var Component = this._super(name, container);
if (!Component) { return; }
name = name.replace(".","/");
if (Component.prototype.classNames.indexOf(Ember.COMPONENT_CSS_LOOKUP[name]) > -1){
return Component;
}
return Component.reopen({
classNames: [Ember.COMPONENT_CSS_LOOKUP[name]]
});
}
}); |
Set the required flag for media filters | package gitmedia
import (
"../gitconfig"
"fmt"
"regexp"
)
type InitCommand struct {
*Command
}
var valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media")
func (c *InitCommand) Run() {
setFilter("clean")
setFilter("smudge")
requireFilters()
fmt.Println("git media initialized")
}
func setFilter(filterName string) {
key := fmt.Sprintf("filter.media.%s", filterName)
value := fmt.Sprintf("git media %s %%f", filterName)
existing := gitconfig.Find(key)
if shouldReset(existing) {
fmt.Printf("Installing %s filter\n", filterName)
gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, value)
} else if existing != value {
fmt.Printf("The %s filter should be \"%s\" but is \"%s\"\n", filterName, value, existing)
}
}
func requireFilters() {
key := "filter.media.required"
value := "true"
existing := gitconfig.Find(key)
if shouldReset(existing) {
gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, value)
} else if existing != value {
fmt.Printf("Media filter should be required but are not")
}
}
func shouldReset(value string) bool {
if len(value) == 0 {
return true
}
return valueRegexp.MatchString(value)
}
func init() {
registerCommand("init", func(c *Command) RunnableCommand {
return &InitCommand{Command: c}
})
}
| package gitmedia
import (
"../gitconfig"
"fmt"
"regexp"
)
type InitCommand struct {
*Command
}
var valueRegexp = regexp.MustCompile("\\Agit[\\-\\s]media")
func (c *InitCommand) Run() {
setFilter("clean")
setFilter("smudge")
fmt.Println("git media initialized")
}
func setFilter(filterName string) {
key := fmt.Sprintf("filter.media.%s", filterName)
value := fmt.Sprintf("git media %s %%f", filterName)
existing := gitconfig.Find(key)
if shouldReset(existing) {
fmt.Printf("Installing %s filter\n", filterName)
gitconfig.UnsetGlobal(key)
gitconfig.SetGlobal(key, value)
} else if existing != value {
fmt.Printf("The %s filter should be \"%s\" but is \"%s\"\n", filterName, value, existing)
}
}
func shouldReset(value string) bool {
if len(value) == 0 {
return true
}
return valueRegexp.MatchString(value)
}
func init() {
registerCommand("init", func(c *Command) RunnableCommand {
return &InitCommand{Command: c}
})
}
|
Support react-validation-mixin's new async-capable API. | import Joi from 'joi';
import union from 'lodash.union';
export default joiOptions => {
return {
validate: function(data = {}, joiSchema = {}, key, callback = () => {}) {
const options = {
abortEarly: false,
allowUnknown: true,
...joiOptions,
};
const errors = this._format(Joi.validate(data, joiSchema, options));
if (key === undefined) {
union(Object.keys(joiSchema), Object.keys(data)).forEach(function(error) {
errors[error] = errors[error] || [];
});
callback(errors);
}
const result = {};
result[key] = errors[key];
callback(result);
},
_format: function(joiResult) {
if (joiResult.error !== null) {
return joiResult.error.details.reduce(function(memo, detail) {
if (!Array.isArray(memo[detail.path])) {
memo[detail.path] = [];
}
memo[detail.path].push(detail.message);
return memo;
}, {});
}
return {};
},
};
};
| import Joi from 'joi';
import union from 'lodash.union';
export default joiOptions => {
return {
validate: function(data = {}, joiSchema = {}, key) {
const options = {
abortEarly: false,
allowUnknown: true,
...joiOptions,
};
const errors = this._format(Joi.validate(data, joiSchema, options));
if (key === undefined) {
union(Object.keys(joiSchema), Object.keys(data)).forEach(function(error) {
errors[error] = errors[error] || [];
});
return errors;
}
const result = {};
result[key] = errors[key];
return result;
},
_format: function(joiResult) {
if (joiResult.error !== null) {
return joiResult.error.details.reduce(function(memo, detail) {
if (!Array.isArray(memo[detail.path])) {
memo[detail.path] = [];
}
memo[detail.path].push(detail.message);
return memo;
}, {});
}
return {};
},
};
};
|
Fix it so it still works with a setter. | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class KeyValuePair(core.Resource):
_alias = 'Key'
_display_name = 'Key Value Pair'
_plural = 'Keys'
_plural_display_name = 'Key Value Pairs'
_repr_attributes = ['name', 'value']
# Note: This is a temporary hack until we refactor client and make it support non id PKs
def get_id(self):
return self.name
def set_id(self, value):
self.name = value
id = property(get_id, set_id)
| # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class KeyValuePair(core.Resource):
_alias = 'Key'
_display_name = 'Key Value Pair'
_plural = 'Keys'
_plural_display_name = 'Key Value Pairs'
_repr_attributes = ['name', 'value']
@property
def id(self):
# Note: This is a temporary hack until we refactor client and make it support non id PKs
return self.name
|
Improve loading of settings from database | <?php
namespace Croogo\Settings\Configure\Engine;
use Cake\Core\Configure\ConfigEngineInterface;
use Cake\Log\Log;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
class DatabaseConfig implements ConfigEngineInterface
{
private $_table;
/**
* @param Table $table
*/
function __construct(Table $table = null)
{
if (!$table) {
$table = TableRegistry::get('Croogo/Settings.Settings');
}
$this->_table = $table;
}
/**
* Read method is used for reading configuration information from sources.
* These sources can either be static resources like files, or dynamic ones like
* a database, or other datasource.
*
* @param string $key Key to read.
* @return array An array of data to merge into the runtime configuration
*/
public function read($key)
{
$settings = $this->_table->find('list', [
'keyField' => 'key',
'valueField' => 'value'
])->toArray();
return Hash::expand($settings);
}
/**
* Dumps the configure data into source.
*
* @param string $key The identifier to write to.
* @param array $data The data to dump.
* @return bool True on success or false on failure.
*/
public function dump($key, array $data)
{
Log::debug($key);
Log::debug($data);
return true;
}
}
| <?php
namespace Croogo\Settings\Configure\Engine;
use Cake\Core\Configure\ConfigEngineInterface;
use Cake\Log\Log;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
class DatabaseConfig implements ConfigEngineInterface
{
private $_table;
/**
* @param Table $table
*/
function __construct(Table $table = null)
{
if (!$table) {
$table = TableRegistry::get('Croogo/Settings.Settings');
}
$this->_table = $table;
}
/**
* Read method is used for reading configuration information from sources.
* These sources can either be static resources like files, or dynamic ones like
* a database, or other datasource.
*
* @param string $key Key to read.
* @return array An array of data to merge into the runtime configuration
*/
public function read($key)
{
$settings = $this->_table->find('all');
$config = [];
foreach ($settings as $setting) {
$config = Hash::insert($config, $setting->key, $setting->value);
}
return $config;
}
/**
* Dumps the configure data into source.
*
* @param string $key The identifier to write to.
* @param array $data The data to dump.
* @return bool True on success or false on failure.
*/
public function dump($key, array $data)
{
Log::debug($key);
Log::debug($data);
return true;
}
}
|
Fix invalid case of Rx(lower case, in fact) reference | 'use strict';
var Rx = require('rx');
var applyToDOM = require('./render-dom');
var makeInteractions = require('./interactions').makeInteractions;
function makeGet(interactions, rootElem$) {
return function get(selector, eventName, isSingle) {
if (selector === ':root') {
return rootElem$;
}
return interactions.get(selector, eventName, isSingle);
};
}
function makeDOMDriver(container) {
return function reactDOMDriver(definition$) {
if (!definition$) {
return {};
}
var rootElem$ = new Rx.Subject();
var interactions = makeInteractions(rootElem$);
var subscription = definition$.subscribe(function render(definitionFn) {
var renderMeta = applyToDOM(container, definitionFn);
rootElem$.onNext(renderMeta.container);
});
return {
get: makeGet(interactions, rootElem$),
dispose: function dispose() {
subscription.dispose();
rootElem$.dispose();
}
};
};
}
module.exports = makeDOMDriver;
| 'use strict';
var Rx = require('Rx');
var applyToDOM = require('./render-dom');
var makeInteractions = require('./interactions').makeInteractions;
function makeGet(interactions, rootElem$) {
return function get(selector, eventName, isSingle) {
if (selector === ':root') {
return rootElem$;
}
return interactions.get(selector, eventName, isSingle);
};
}
function makeDOMDriver(container) {
return function reactDOMDriver(definition$) {
if (!definition$) {
return {};
}
var rootElem$ = new Rx.Subject();
var interactions = makeInteractions(rootElem$);
var subscription = definition$.subscribe(function render(definitionFn) {
var renderMeta = applyToDOM(container, definitionFn);
rootElem$.onNext(renderMeta.container);
});
return {
get: makeGet(interactions, rootElem$),
dispose: function dispose() {
subscription.dispose();
rootElem$.dispose();
}
};
};
}
module.exports = makeDOMDriver;
|
Update to follower, reduce speed to motors. |
import sys
from time import time
class PID(object):
def __init__(self):
"""initizes value for the PID"""
self.kd = 0
self.ki = 0
self.kp = 1
self.previous_error = 0
self.integral_error = 0
def set_k_values(self, kp, kd, ki):
self.kp = kp
self.ki = ki
self.kd = kd
def pid(self, target, process_var, timestep):
current_error = (target - process_var)
p_error = self.kp * current_error
d_error = self.kd * (current_error - self.previous_error) \
/ timestep
self.integral_error = (
current_error + self.previous_error) / 2 \
+ self.integral_error
i_error = self.ki * self.integral_error
total_error = p_error + d_error + i_error
self.previous_error = current_error
return total_error
|
import sys
from time import time
class PID(object):
def __init__(self):
"""initizes value for the PID"""
self.kd = 0
self.ki = 0
self.kp = 1
self.previous_error = 0
self.integral_error = 0
def set_k_values(self, kp, kd, ki):
self.kp = kp
self.ki = ki
self.kd = kd
def pid(self, target, process_var, timestep):
current_error = (target + process_var)
p_error = self.kp * current_error
d_error = self.kd * (current_error - self.previous_error) \
/ timestep
self.integral_error = (
current_error + self.previous_error) / 2 \
+ self.integral_error
i_error = self.ki * self.integral_error
total_error = p_error + d_error + i_error
self.previous_error = current_error
return total_error
|
Fix mingw build, take 2 | #!/usr/bin/env python
# Build the project on AppVeyor.
import os
from subprocess import check_call
build = os.environ['BUILD']
config = os.environ['CONFIG']
cmake_command = ['cmake', '-DFMT_EXTRA_TESTS=ON', '-DCMAKE_BUILD_TYPE=' + config]
if build == 'mingw':
cmake_command.append('-GMinGW Makefiles')
build_command = ['mingw32-make', '-j4']
test_command = ['mingw32-make', 'test']
# Remove the path to Git bin directory from $PATH because it breaks MinGW config.
os.environ['PATH'] = os.environ['PATH'].replace(r'C:\Program Files (x86)\Git\bin', '')
else:
build_command = ['msbuild', '/m:4', '/p:Config=' + config, 'FORMAT.sln']
test_command = ['msbuild', 'RUN_TESTS.vcxproj']
check_call(cmake_command)
check_call(build_command)
check_call(test_command)
| #!/usr/bin/env python
# Build the project on AppVeyor.
import os
from subprocess import check_call
build = os.environ['BUILD']
config = os.environ['CONFIG']
cmake_command = ['cmake', '-DFMT_EXTRA_TESTS=ON', '-DCMAKE_BUILD_TYPE=' + config]
if build == 'mingw':
cmake_command.append('-GMinGW Makefiles')
build_command = ['mingw32-make', '-j4']
test_command = ['mingw32-make', 'test']
# Remove the path to Git bin directory from $PATH because it breaks MinGW config.
path = os.environ['PATH'].replace(r'C:\Program Files (x86)\Git\bin', '')
else:
build_command = ['msbuild', '/m:4', '/p:Config=' + config, 'FORMAT.sln']
test_command = ['msbuild', 'RUN_TESTS.vcxproj']
check_call(cmake_command)
check_call(build_command)
check_call(test_command)
|
Read client keys from environment variable rather than hardcoding in source | const RateLimiter = require("rolling-rate-limiter");
const prettyMs = require('pretty-ms');
const config = require('../config');
const validKeys = process.env.CLIENT_KEYS.split(',');
const limiter = RateLimiter({
interval: 60*60*1000, //1 hour in miliseconds
maxInInterval: config.max_requests_per_hour
});
const validator = {
validateKey: function(req, res, next){
if(validKeys.indexOf(req.query.key)===-1){
res.status(401);
res.json({"status":"401", "message":"invalid credentials"});
return;
}
next();
},
validateRate: function(req, res, next){
const timeLeft = limiter(req.query.key);
if (timeLeft > 0) {
// limit was exceeded, action should not be allowed
// timeLeft is the number of ms until the next action will be allowed
res.status(429);
res.json({"status":"429", "message":"Request limit excceded- try after "+prettyMs(timeLeft)});
} else {
next();
// limit was not exceeded, action should be allowed
}
}
};
module.exports = validator; | const RateLimiter = require("rolling-rate-limiter");
const prettyMs = require('pretty-ms');
const config = require('../config');
const validKeys = ['key1','key2', 'key3', 'key4', 'key5']; //TODO replace API keys in request with JWT-token?
const limiter = RateLimiter({
interval: 60*60*1000, //1 hour in miliseconds
maxInInterval: config.max_requests_per_hour
});
const validator = {
validateKey: function(req, res, next){
if(validKeys.indexOf(req.query.key)===-1){
res.status(401);
res.json({"status":"401", "message":"invalid credentials"});
return;
}
next();
},
validateRate: function(req, res, next){
const timeLeft = limiter(req.query.key);
if (timeLeft > 0) {
// limit was exceeded, action should not be allowed
// timeLeft is the number of ms until the next action will be allowed
res.status(429);
res.json({"status":"429", "message":"Request limit excceded- try after "+prettyMs(timeLeft)});
} else {
next();
// limit was not exceeded, action should be allowed
}
}
};
module.exports = validator; |
Add to download links ng-csv | var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3016',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3016
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
| var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');
module.exports = {
local: {
baseUrl: 'http://localhost:3030',
db: 'mongodb://localhost/rp_local',
rootPath: rootPath,
port: process.env.PORT || 3030
},
staging : {
baseUrl: 'http://dev.resourceprojects.org',
//db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true',
db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true',
rootPath: rootPath,
port: process.env.PORT || 80
}
};
|
Fix problem with action buttons without killOnRelease not starting again | package org.robockets.buttonmanager.buttons;
import org.robockets.buttonmanager.Button;
import edu.wpi.first.wpilibj.command.Command;
/**
* The basic press-to-run button
*/
public class ActionButton extends Button {
private boolean killOnRelease = true;
/**
* Class constructor
* @param joystickNumber The joystick port that the button will be bound to
* @param buttonNumber The button number that the button will be bound to
* @param command The command that the button will run when pressed
* @param killOnRelease true if the button should stop command execution when released
*/
public ActionButton(int joystickNumber, int buttonNumber, Command command, boolean killOnRelease) {
super(joystickNumber, buttonNumber, command);
this.killOnRelease = killOnRelease;
}
/**
* Ran when the button is not pressed
*/
protected void notPressed() {
if (killOnRelease) {
stop();
}
super.notPressed();
}
}
| package org.robockets.buttonmanager.buttons;
import org.robockets.buttonmanager.Button;
import edu.wpi.first.wpilibj.command.Command;
/**
* The basic press-to-run button
*/
public class ActionButton extends Button {
private boolean killOnRelease = true;
/**
* Class constructor
* @param joystickNumber The joystick port that the button will be bound to
* @param buttonNumber The button number that the button will be bound to
* @param command The command that the button will run when pressed
* @param killOnRelease true if the button should stop command execution when released
*/
public ActionButton(int joystickNumber, int buttonNumber, Command command, boolean killOnRelease) {
super(joystickNumber, buttonNumber, command);
this.killOnRelease = killOnRelease;
}
/**
* Ran when the button is notPressed
*/
protected void notPressed() {
if (killOnRelease) {
stop();
}
}
}
|
Add license statement to js | /*
clickTouch.js v0.1
Shawn Khameneh
MIT License
*/
var clickTouch = function(){
var isDown = false;
function createEvent(mouseEvent, name) {
var myEvent = document.createEvent('CustomEvent');
myEvent.initEvent(name, true, true);
myEvent.changedTouches = [mouseEvent];
myEvent.identifier = 'mouse';
(mouseEvent.target?mouseEvent.target:document).dispatchEvent(myEvent);
}
return {
init: function(preventDefault) {
function mousedown(event){
if(preventDefault)
event.preventDefault();
isDown = true;
clickTouch.createEvent(event, 'touchstart');
}
document.body.addEventListener('mousedown', mousedown);
function mouseup(event){
if(preventDefault)
event.preventDefault();
isDown = false;
clickTouch.createEvent(event, 'touchend');
}
document.body.addEventListener('mouseup', mouseup);
function mousemove(event){
if(preventDefault)
event.preventDefault();
if(isDown)
clickTouch.createEvent(event, 'touchmove');
}
document.body.addEventListener('mousemove', mousemove);
},
createEvent: createEvent
}
}(); | var clickTouch = function(){
var isDown = false;
function createEvent(mouseEvent, name) {
var myEvent = document.createEvent('CustomEvent');
myEvent.initEvent(name, true, true);
myEvent.changedTouches = [mouseEvent];
myEvent.identifier = 'mouse';
(mouseEvent.target?mouseEvent.target:document).dispatchEvent(myEvent);
}
return {
init: function(preventDefault) {
function mousedown(event){
if(preventDefault)
event.preventDefault();
isDown = true;
clickTouch.createEvent(event, 'touchstart');
}
document.body.addEventListener('mousedown', mousedown);
function mouseup(event){
if(preventDefault)
event.preventDefault();
isDown = false;
clickTouch.createEvent(event, 'touchend');
}
document.body.addEventListener('mouseup', mouseup);
function mousemove(event){
if(preventDefault)
event.preventDefault();
if(isDown)
clickTouch.createEvent(event, 'touchmove');
}
document.body.addEventListener('mousemove', mousemove);
},
createEvent: createEvent
}
}(); |
Change separator of sequense from tilda to slash | package main
import (
"regexp"
"strconv"
"strings"
)
var (
sequenses = regexp.MustCompile(`(?:[^/\\]|\\.)*`)
branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)
func newMatcher(expr string) (m *regexp.Regexp, err error) {
expr = strings.Replace(expr, `\,`, `\\,`, -1)
expr = strings.Replace(expr, `\/`, `\\/`, -1)
expr, err = strconv.Unquote(`"` + expr + `"`)
if err != nil {
return nil, err
}
sls := sequenses.FindAllString(expr, -1)
for si := 0; si < len(sls); si++ {
bls := branches.FindAllString(sls[si], -1)
for bi := 0; bi < len(bls); bi++ {
bls[bi] = strings.Replace(bls[bi], `\,`, `,`, -1)
bls[bi] = strings.Replace(bls[bi], `\/`, `/`, -1)
bls[bi] = regexp.QuoteMeta(bls[bi])
}
sls[si] = "(" + strings.Join(bls, "|") + ")"
}
return regexp.Compile(strings.Join(sls, ""))
}
| package main
import (
"regexp"
"strconv"
"strings"
)
var (
sequenses = regexp.MustCompile(`(?:[^~\\]|\\.)*`)
branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)
func newMatcher(expr string) (m *regexp.Regexp, err error) {
expr = strings.Replace(expr, `\,`, `\\,`, -1)
expr = strings.Replace(expr, `\~`, `\\~`, -1)
expr, err = strconv.Unquote(`"` + expr + `"`)
if err != nil {
return nil, err
}
sls := sequenses.FindAllString(expr, -1)
for si := 0; si < len(sls); si++ {
bls := branches.FindAllString(sls[si], -1)
for bi := 0; bi < len(bls); bi++ {
bls[bi] = strings.Replace(bls[bi], `\,`, `,`, -1)
bls[bi] = strings.Replace(bls[bi], `\~`, `~`, -1)
bls[bi] = regexp.QuoteMeta(bls[bi])
}
sls[si] = "(" + strings.Join(bls, "|") + ")"
}
return regexp.Compile(strings.Join(sls, ""))
}
|
Update copyright notice with MIT license | /*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--*/
package com.nasmlanguage.psi;
import com.intellij.psi.tree.IElementType;
import com.nasmlanguage.NASMLanguage;
import org.jetbrains.annotations.*;
public class NASMElementType extends IElementType {
public NASMElementType(@NotNull @NonNls String debugName) {
super(debugName, NASMLanguage.INSTANCE);
}
}
| /*++
NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--*/
package com.nasmlanguage.psi;
import com.intellij.psi.tree.IElementType;
import com.nasmlanguage.NASMLanguage;
import org.jetbrains.annotations.*;
public class NASMElementType extends IElementType {
public NASMElementType(@NotNull @NonNls String debugName) {
super(debugName, NASMLanguage.INSTANCE);
}
}
|
Use new core API for modifying WebAppView properties | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Embed;
use Flarum\Forum\WebApp;
class EmbedWebApp extends WebApp
{
/**
* {@inheritdoc}
*/
public function getView()
{
$view = parent::getView();
$view->getJs()->addFile(__DIR__.'/../js/forum/dist/extension.js');
$view->getCss()->addFile(__DIR__.'/../less/forum/extension.less');
$view->loadModule('flarum/embed/main');
$view->layout = __DIR__.'/../views/embed.blade.php';
return $view;
}
/**
* {@inheritdoc}
*/
public function getAssets()
{
return $this->assets->make('embed');
}
}
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Embed;
use Flarum\Forum\WebApp;
class EmbedWebApp extends WebApp
{
/**
* {@inheritdoc}
*/
public function getView()
{
$view = parent::getView();
$view->getJs()->addFile(__DIR__.'/../js/forum/dist/extension.js');
$view->getCss()->addFile(__DIR__.'/../less/forum/extension.less');
$view->loadModule('flarum/embed/main');
$view->setLayout(__DIR__.'/../views/embed.blade.php');
return $view;
}
/**
* {@inheritdoc}
*/
public function getAssets()
{
return $this->assets->make('embed');
}
}
|
Remove incorrect check for institution_id
Fixes https://sentry.cos.io/sentry/osf-iy/issues/273424/ | import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
| import logging
from website.notifications.exceptions import InvalidSubscriptionError
from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications
from website.project.signals import contributor_added, project_created
from framework.auth.signals import user_confirmed
logger = logging.getLogger(__name__)
@project_created.connect
def subscribe_creator(node):
if node.institution_id or node.is_collection or node.is_deleted:
return None
try:
subscribe_user_to_notifications(node, node.creator)
except InvalidSubscriptionError as err:
user = node.creator._id if node.creator else 'None'
logger.warn('Skipping subscription of user {} to node {}'.format(user, node._id))
logger.warn('Reason: {}'.format(str(err)))
@contributor_added.connect
def subscribe_contributor(node, contributor, auth=None, *args, **kwargs):
try:
subscribe_user_to_notifications(node, contributor)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to node {}'.format(contributor, node._id))
logger.warn('Reason: {}'.format(str(err)))
@user_confirmed.connect
def subscribe_confirmed_user(user):
try:
subscribe_user_to_global_notifications(user)
except InvalidSubscriptionError as err:
logger.warn('Skipping subscription of user {} to global subscriptions'.format(user))
logger.warn('Reason: {}'.format(str(err)))
|
Revert "updateMit" method name change | Meteor.methods({
// Tasks
createTask: function(task) {
// FIXME: Use collection hooks
task.createdAt = new Date()
task.userId = Meteor.userId()
Tasks.insert(task)
},
// Morning Gratitude
createGratitude: function(gratitude) {
// FIXME: Use collection hooks
gratitude.createdAt = new Date()
gratitude.userId = Meteor.userId()
Gratitude.insert(gratitude)
},
updateGratitude: function(id, newValue) {
Gratitude.update(id, {
$set: {"value": newValue}
})
},
// MITs
createMits: function(mits) {
// FIXME: Use collection hooks
mits.createdAt = new Date()
mits.userId = Meteor.userId()
Mits.insert(mits)
},
updateMits: function(id, newValue) {
Mits.update(id, {
$set: {"value": newValue}
})
}
});
| Meteor.methods({
// Tasks
createTask: function(task) {
// FIXME: Use collection hooks
task.createdAt = new Date()
task.userId = Meteor.userId()
Tasks.insert(task)
},
// Morning Gratitude
createGratitude: function(gratitude) {
// FIXME: Use collection hooks
gratitude.createdAt = new Date()
gratitude.userId = Meteor.userId()
Gratitude.insert(gratitude)
},
updateGratitude: function(id, newValue) {
Gratitude.update(id, {
$set: {"value": newValue}
})
},
// MITs
createMits: function(mits) {
// FIXME: Use collection hooks
mits.createdAt = new Date()
mits.userId = Meteor.userId()
Mits.insert(mits)
},
updateMit: function(id, newValue) {
Mits.update(id, {
$set: {"value": newValue}
})
}
});
|
Install .mo catalogs if available | import os
import glob
from setuptools import setup, find_packages
VERSION = '0.1.0dev'
def mo_files():
linguas = glob.glob('brew/translations/*/LC_MESSAGES/messages.mo')
lpaths = [os.path.dirname(d) for d in linguas]
return zip(lpaths, [[l] for l in linguas])
# Data files to be installed after build time
data_files = mo_files()
setup(
name='Brewmeister',
version=VERSION,
long_description=open('README.rst').read(),
packages=find_packages(),
include_package_data=True,
zip_safe=False,
scripts=['bin/brewmeister'],
data_files=data_files,
install_requires=[
'Babel>=1.3',
'docutils>=0.11',
'Flask>=0.10.1',
'Flask-Babel>=0.9',
'Flask-Cache>=0.12',
'Flask-PyMongo>=0.3.0',
'Flask-Script>=0.6.3',
'fysom>=1.0.14',
'jsonschema>=2.3.0',
'pyserial>=2.7',
'reportlab>=2.7',
]
)
| from setuptools import setup, find_packages
VERSION = '0.1.0dev'
setup(
name='Brewmeister',
version=VERSION,
long_description=open('README.rst').read(),
packages=find_packages(),
include_package_data=True,
zip_safe=False,
scripts=['bin/brewmeister'],
install_requires=[
'Babel>=1.3',
'docutils>=0.11',
'Flask>=0.10.1',
'Flask-Babel>=0.9',
'Flask-Cache>=0.12',
'Flask-PyMongo>=0.3.0',
'Flask-Script>=0.6.3',
'fysom>=1.0.14',
'jsonschema>=2.3.0',
'pyserial>=2.7',
'reportlab>=2.7',
]
)
|
Update for new mock database | """
Configuration, plugins and fixtures for `pytest`.
"""
from typing import Iterator
import pytest
from mock_vws import MockVWS
from mock_vws.database import VuforiaDatabase
from vws import VWS
pytest_plugins = [ # pylint: disable=invalid-name
'tests.fixtures.images',
]
@pytest.fixture()
def _mock_database() -> Iterator[VuforiaDatabase]:
with MockVWS() as mock:
database = VuforiaDatabase()
mock.add_database(database=database)
yield database
@pytest.fixture()
def client(_mock_database: VuforiaDatabase) -> Iterator[VWS]:
"""
# TODO rename this fixture
Yield a VWS client which connects to a mock.
"""
vws_client = VWS(
server_access_key=_mock_database.server_access_key,
server_secret_key=_mock_database.server_secret_key,
)
yield vws_client
@pytest.fixture()
def cloud_reco_client(_mock_database: VuforiaDatabase) -> Iterator[VWS]:
"""
# TODO rename this fixture
Yield a VWS client which connects to a mock.
"""
vws_client = VWS(
server_access_key=_mock_database.server_access_key,
server_secret_key=_mock_database.server_secret_key,
)
yield vws_client
| """
Configuration, plugins and fixtures for `pytest`.
"""
from typing import Iterator
import pytest
from mock_vws import MockVWS
from mock_vws.database import VuforiaDatabase
from vws import VWS
pytest_plugins = [ # pylint: disable=invalid-name
'tests.fixtures.images',
]
@pytest.fixture()
def _mock_database() -> Iterator[VuforiaDatabase]:
with MockVWS() as mock:
database = VuforiaDatabase()
mock.add_database(database=database)
yield database
@pytest.fixture()
def client(_mock_database: VuforiaDatabase) -> Iterator[VWS]:
"""
# TODO rename this fixture
Yield a VWS client which connects to a mock.
"""
vws_client = VWS(
server_access_key=_mock_database.server_access_key.decode(),
server_secret_key=_mock_database.server_secret_key.decode(),
)
yield vws_client
@pytest.fixture()
def cloud_reco_client(_mock_database: VuforiaDatabase) -> Iterator[VWS]:
"""
# TODO rename this fixture
Yield a VWS client which connects to a mock.
"""
vws_client = VWS(
server_access_key=_mock_database.server_access_key.decode(),
server_secret_key=_mock_database.server_secret_key.decode(),
)
yield vws_client
|
Fix loop in QueryIterator when row count is an exact multiple of page size
Summary: Ref T13152. The pager does a bit of magic here and doesn't populate `nextPageID` when it knows it got an exact final page. The logic misfired in this case and sent us back to the start.
Test Plan:
- Set page size to 1 to guarantee rows were an exact multiple of page size.
- Ran `rebuild-identities` (I no-op'd the actual logic to make it faster).
- Before: looped forever.
- After: clean exit after processing everything.
Reviewers: amckinley
Reviewed By: amckinley
Maniphest Tasks: T13152
Differential Revision: https://secure.phabricator.com/D19479 | <?php
final class PhabricatorQueryIterator extends PhutilBufferedIterator {
private $query;
private $pager;
public function __construct(PhabricatorCursorPagedPolicyAwareQuery $query) {
$this->query = $query;
}
protected function didRewind() {
$this->pager = new AphrontCursorPagerView();
}
public function key() {
return $this->current()->getID();
}
protected function loadPage() {
if (!$this->pager) {
return array();
}
$pager = clone $this->pager;
$query = clone $this->query;
$results = $query->executeWithCursorPager($pager);
// If we got less than a full page of results, this was the last set of
// results. Throw away the pager so we end iteration.
if (!$pager->getHasMoreResults()) {
$this->pager = null;
} else {
$this->pager->setAfterID($pager->getNextPageID());
}
return $results;
}
}
| <?php
final class PhabricatorQueryIterator extends PhutilBufferedIterator {
private $query;
private $pager;
public function __construct(PhabricatorCursorPagedPolicyAwareQuery $query) {
$this->query = $query;
}
protected function didRewind() {
$this->pager = new AphrontCursorPagerView();
}
public function key() {
return $this->current()->getID();
}
protected function loadPage() {
if (!$this->pager) {
return array();
}
$pager = clone $this->pager;
$query = clone $this->query;
$results = $query->executeWithCursorPager($pager);
// If we got less than a full page of results, this was the last set of
// results. Throw away the pager so we end iteration.
if (count($results) < $pager->getPageSize()) {
$this->pager = null;
} else {
$this->pager->setAfterID($pager->getNextPageID());
}
return $results;
}
}
|
Fix args option not functioning | var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')
/**
* @param {Object} options
* @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
* @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
*/
module.exports = function (opts) {
opts = opts || {}
// Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
if (opts.args) {
args = args.concat(opts.args.split(' '))
}
return dcp.spawn(mozjpeg, args)
}
| var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')
/**
* @param {Object} options
* @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
* @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
*/
module.exports = function (opts) {
opts = opts || {}
// Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
if (opts.args) args.push(opts.args.split[' '])
var foo = dcp.spawn(mozjpeg, args)
return foo
}
|
Remove verification skipping in Nose plugin for now. | from __future__ import absolute_import
import sys
from nose.plugins.base import Plugin
from doubles.lifecycle import setup, verify, teardown, current_space
from doubles.exceptions import MockExpectationError
class NoseIntegration(Plugin):
name = 'doubles'
def beforeTest(self, test):
setup()
def afterTest(self, test):
if current_space():
teardown()
def prepareTestCase(self, test):
def wrapped(result):
test.test.run()
try:
if current_space():
verify()
except MockExpectationError:
result.addFailure(test.test, sys.exc_info())
return wrapped
| from __future__ import absolute_import
import sys
from nose.plugins.base import Plugin
from doubles.lifecycle import setup, verify, teardown, current_space
from doubles.exceptions import MockExpectationError
class NoseIntegration(Plugin):
name = 'doubles'
def beforeTest(self, test):
setup()
def afterTest(self, test):
if current_space():
teardown()
def prepareTestCase(self, test):
def wrapped(result):
test.test.run()
if result.failures or result.errors:
return
try:
if current_space():
verify()
except MockExpectationError:
result.addFailure(test.test, sys.exc_info())
return wrapped
|
Remove setTimeout on version checker
That was just for testing. | $(document).ready(function() {
checkForUpdates();
});
function checkForUpdates() {
var updateChecker = $('#update-checker');
var updateCheckerBody = updateChecker.find('.panel-body');
$.get('/version', function(data) {
if (data.newer) {
var content = '<p>There is a new version of LBlog available (<strong>' + data.latestVersion + '</strong>)</p>';
var content = content + '<p><a href="#">Click here for more information.</a></p>';
updateChecker.removeClass('panel-default').addClass('panel-danger');
updateCheckerBody.html(content);
return;
}
var content = '<p>Your version of LBlog is up to date!</p>';
updateChecker.removeClass('panel-default').addClass('panel-success');
updateCheckerBody.html(content);
});
} | $(document).ready(function() {
setTimeout(function() {
var updateChecker = $('#update-checker');
var updateCheckerBody = updateChecker.find('.panel-body');
$.get('/version', function(data) {
if (data.newer) {
var content = '<p>There is a new version of LBlog available (<strong>' + data.latestVersion + '</strong>)</p>';
var content = content + '<p><a href="#">Click here for more information.</a></p>';
updateChecker.removeClass('panel-default').addClass('panel-danger');
updateCheckerBody.html(content);
return;
}
var content = '<p>Your version of LBlog is up to date!</p>';
updateChecker.removeClass('panel-default').addClass('panel-success');
updateCheckerBody.html(content);
});
}, 1000);
}); |
Revert debugging changes: clean up tempfiles | #!/usr/bin/env python
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
| #!/usr/bin/env python
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
#shutil.rmtree(self.temp_dir)
print(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
|
Fix issue with returning wrong date | from datetime import datetime
from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from .base import Base
class Game(Base):
# Table name
__tablename__ = 'sp_games'
#
# Columns
# -------------
id = Column(Integer, primary_key=True)
game_id = Column(Integer)
game_host = Column(String)
start_at = Column(DateTime)
end_at = Column(DateTime)
#
# Relationships
# -------------
map_id = Column(Integer, ForeignKey('sp_maps.id'))
map = relationship("Map", back_populates="games")
players = relationship("Player", back_populates="game", lazy="dynamic")
days = relationship("Day", back_populates="game")
relations = relationship("Relation", back_populates="game", lazy="dynamic")
coalitions = relationship("Coalition", back_populates="game")
#
# Attributes
# -------------
@hybrid_method
def day(self):
delta = datetime.today() - self.start_at
return delta.days + 1
#
# Representation
# -------------
def __repr__(self):
return "<Game(%s)>" % (self.id)
| from datetime import datetime
from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from .base import Base
class Game(Base):
# Table name
__tablename__ = 'sp_games'
#
# Columns
# -------------
id = Column(Integer, primary_key=True)
game_id = Column(Integer)
game_host = Column(String)
start_at = Column(DateTime)
end_at = Column(DateTime)
#
# Relationships
# -------------
map_id = Column(Integer, ForeignKey('sp_maps.id'))
map = relationship("Map", back_populates="games")
players = relationship("Player", back_populates="game", lazy="dynamic")
days = relationship("Day", back_populates="game")
relations = relationship("Relation", back_populates="game", lazy="dynamic")
coalitions = relationship("Coalition", back_populates="game")
#
# Attributes
# -------------
@hybrid_method
def day(self):
delta = datetime.today() - self.start_at
return delta.days
#
# Representation
# -------------
def __repr__(self):
return "<Game(%s)>" % (self.id)
|
OEE-54: Modify ACL. Refactor ACL Walker.
- Add set organization listener | <?php
namespace Oro\Bundle\SecurityBundle\Http\Firewall;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Oro\Bundle\OrganizationBundle\Entity\Manager\OrganizationManager;
use Oro\Bundle\SecurityBundle\Authentication\Token\UsernamePasswordOrganizationToken;
class ContextListener
{
/**
* @var SecurityContextInterface
*/
protected $context;
/**
* @var OrganizationManager
*/
protected $manager;
/**
* @param SecurityContextInterface $context
* @param OrganizationManager $manager
*/
public function __construct(SecurityContextInterface $context, OrganizationManager $manager)
{
$this->context = $context;
$this->manager = $manager;
}
/**
* Refresh organization context in token
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$token = $this->context->getToken();
if ($token instanceof UsernamePasswordOrganizationToken) {
$token->setOrganizationContext(
$this->manager->getOrganizationById($token->getOrganizationContext()->getId())
);
}
}
}
| <?php
namespace Oro\Bundle\SecurityBundle\Http\Firewall;
use Oro\Bundle\OrganizationBundle\Entity\Manager\OrganizationManager;
use Oro\Bundle\SecurityBundle\Authentication\Token\UsernamePasswordOrganizationToken;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;
class ContextListener
{
/**
* @var SecurityContextInterface
*/
protected $context;
/**
* @var OrganizationManager
*/
protected $manager;
/**
* @param SecurityContextInterface $context
* @param OrganizationManager $manager
*/
public function __construct(SecurityContextInterface $context, OrganizationManager $manager)
{
$this->context = $context;
$this->manager = $manager;
}
/**
* Refresh organization context in token
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$token = $this->context->getToken();
if ($token instanceof UsernamePasswordOrganizationToken) {
$token->setOrganizationContext(
$this->manager->getOrganizationById($token->getOrganizationContext()->getId())
);
}
}
}
|
Use the final endTime in getCurrent().
It might be good at some point to split this out, so that getCurrent() returns
null or undefined if the timer isn't running, and have a separate function
to get the final solve time. | var Timer = (function(Util) {
'use strict';
// Internal constants for the various timer states.
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
var startTime = undefined, endTime = undefined, solveTime = undefined;
var intervalID = undefined;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; }
function isRunning() { return state === Running; }
function onWaiting() {
endTime = undefined;
}
function onRunning() {
startTime = Util.getMilli();
intervalID = Util.setInterval(runningEmitter, 100);
}
function onStopped() {
endTime = Util.getMilli();
Util.clearInterval(intervalID);
setState(Waiting);
}
function setState(new_state) {
state = new_state;
switch(state) {
case Waiting: onWaiting(); break;
case Running: onRunning(); break;
case Stopped: onStopped(); break;
}
}
function runningEmitter() {
Event.emit("timer/running");
}
function triggerDown() {
if (isWaiting()) {
setState(Ready);
} else if (isRunning()) {
setState(Stopped);
}
}
function triggerUp() {
if (isReady()) {
setState(Running);
}
}
function getCurrent() {
return (endTime || Util.getMilli()) - startTime;
}
return {
triggerDown: triggerDown,
triggerUp: triggerUp,
getCurrent: getCurrent
};
});
| var Timer = (function(Util) {
'use strict';
// Internal constants for the various timer states.
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
var startTime = undefined, endTime = undefined, solveTime = undefined;
var intervalID = undefined;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; }
function isRunning() { return state === Running; }
function onRunning() {
startTime = Util.getMilli();
intervalID = Util.setInterval(runningEmitter, 100);
}
function onStopped() {
endTime = Util.getMilli();
Util.clearInterval(intervalID);
setState(Waiting);
}
function setState(new_state) {
state = new_state;
switch(state) {
case Running: onRunning(); break;
case Stopped: onStopped(); break;
}
}
function runningEmitter() {
Event.emit("timer/running");
}
function triggerDown() {
if (isWaiting()) {
setState(Ready);
} else if (isRunning()) {
setState(Stopped);
}
}
function triggerUp() {
if (isReady()) {
setState(Running);
}
}
function getCurrent() {
return Util.getMilli() - startTime;
}
return {
triggerDown: triggerDown,
triggerUp: triggerUp,
getCurrent: getCurrent
};
});
|
Print Empty proto message nicely.
Signed-off-by: Milan Lenco <fd44239370131ad5b8cae55d5f197286407fee30@pantheon.tech> | // Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 utils
import (
"github.com/gogo/protobuf/proto"
prototypes "github.com/gogo/protobuf/types"
)
// ProtoToString converts proto message to string.
func ProtoToString(message proto.Message) string {
if message == nil {
return "<NIL>"
}
if _, isEmpty := message.(*prototypes.Empty); isEmpty {
return "<EMPTY>"
}
// wrap with curly braces, it is easier to read
return "{ " + message.String() + " }"
}
// ErrorToString converts error to string.
func ErrorToString(err error) string {
if err == nil {
return "<NIL>"
}
return err.Error()
}
| // Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 utils
import (
"github.com/gogo/protobuf/proto"
)
// ProtoToString converts proto message to string.
func ProtoToString(message proto.Message) string {
if message == nil {
return "<NIL>"
}
// wrap with curly braces, it is easier to read
return "{ " + message.String() + " }"
}
// ErrorToString converts error to string.
func ErrorToString(err error) string {
if err == nil {
return "<NIL>"
}
return err.Error()
}
|
Fix compatibility with new parser. | """Request handler of the module."""
from functools import partial
from ppp_datamodel import Sentence, TraceItem, Response
from ppp_datamodel.parsers import parse_triples, ParseError
def tree_to_response(tree, measures, trace):
trace = trace + [TraceItem('DatamodelNotationParser',
tree, measures)]
return Response('en', tree, measures, trace)
class RequestHandler:
def __init__(self, request):
self.request = request
def answer(self):
if not isinstance(self.request.tree, Sentence):
return []
try:
tree = parse_triples(self.request.tree.value)
except ParseError:
return []
measures = {'accuracy': 1, 'relevance': 0.5}
return [tree_to_response(tree, measures, self.request.trace)]
| """Request handler of the module."""
from functools import partial
from ppp_datamodel import Sentence, TraceItem, Response
from ppp_datamodel.parsers import parse_triples, ParseError
def tree_to_response(measures, trace, tree):
trace = trace + [TraceItem('DatamodelNotationParser',
tree, measures)]
return Response('en', tree, measures, trace)
class RequestHandler:
def __init__(self, request):
self.request = request
def answer(self):
if not isinstance(self.request.tree, Sentence):
return []
try:
forest = parse_triples(self.request.tree.value)
except ParseError:
return []
measures = {'accuracy': 1, 'relevance': 0.5}
return map(partial(tree_to_response, measures, self.request.trace),
forest)
|
Fix copyright year, it should start from 2016 :( | # -*- coding: utf-8 -*-
from PyQt4.QtGui import QDialog, qApp
from ui.aboutdialog import Ui_AboutDialog
from common import dataDirPath
from version import VERSION
class AboutDialog(QDialog, Ui_AboutDialog):
def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent)
self.setupUi(self)
icon = qApp.windowIcon()
self.appIcon.setPixmap(icon.pixmap(64, 64))
self.tbAbout.setOpenExternalLinks(True)
self.tbLicense.setOpenExternalLinks(True)
self.__initTabs()
def __initTabs(self):
about = "<center><h3>gitc " + VERSION + "</h3></center>"
about += "<center>"
about += self.tr("Git file conflicts and logs viewer")
about += "</center>"
about += "<center><a href=https://github.com/timxx/gitc>"
about += self.tr("Visit project host")
about += "</a></center><br/>"
about += "<center>Copyright © 2016-2018 Weitian Leung</center>"
self.tbAbout.setHtml(about)
licenseFile = dataDirPath() + "/licenses/Apache-2.0.html"
with open(licenseFile) as f:
self.tbLicense.setHtml(f.read())
| # -*- coding: utf-8 -*-
from PyQt4.QtGui import QDialog, qApp
from ui.aboutdialog import Ui_AboutDialog
from common import dataDirPath
from version import VERSION
class AboutDialog(QDialog, Ui_AboutDialog):
def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent)
self.setupUi(self)
icon = qApp.windowIcon()
self.appIcon.setPixmap(icon.pixmap(64, 64))
self.tbAbout.setOpenExternalLinks(True)
self.tbLicense.setOpenExternalLinks(True)
self.__initTabs()
def __initTabs(self):
about = "<center><h3>gitc " + VERSION + "</h3></center>"
about += "<center>"
about += self.tr("Git file conflicts and logs viewer")
about += "</center>"
about += "<center><a href=https://github.com/timxx/gitc>"
about += self.tr("Visit project host")
about += "</a></center><br/>"
about += "<center>Copyright © 2017-2018 Weitian Leung</center>"
self.tbAbout.setHtml(about)
licenseFile = dataDirPath() + "/licenses/Apache-2.0.html"
with open(licenseFile) as f:
self.tbLicense.setHtml(f.read())
|
Add stubby test for getting a contact. | """
Tests for riak contacts backend and collection.
"""
from twisted.trial.unittest import TestCase
from zope.interface.verify import verifyObject
from go_api.collections import ICollection
from go_contacts.backends.riak import (
RiakContactsBackend, RiakContactsCollection)
class TestRiakContactsBackend(TestCase):
def test_get_contacts_collection(self):
backend = RiakContactsBackend()
collection = backend.get_contact_collection("owner-1")
self.assertEqual(collection.owner_id, "owner-1")
self.assertTrue(isinstance(collection, RiakContactsCollection))
class TestRiakContactsCollection(TestCase):
def test_collection_provides_ICollection(self):
"""
The return value of .get_row_collection() is an object that provides
ICollection.
"""
collection = RiakContactsCollection("owner-1")
verifyObject(ICollection, collection)
def test_init(self):
collection = RiakContactsCollection("owner-1")
self.assertEqual(collection.owner_id, "owner-1")
def test_get(self):
collection = RiakContactsCollection("owner-1")
self.assertEqual(collection.get("contact-1"), {})
| """
Tests for riak contacts backend and collection.
"""
from twisted.trial.unittest import TestCase
from zope.interface.verify import verifyObject
from go_api.collections import ICollection
from go_contacts.backends.riak import (
RiakContactsBackend, RiakContactsCollection)
class TestRiakContactsBackend(TestCase):
def test_get_contacts_collection(self):
backend = RiakContactsBackend()
collection = backend.get_contact_collection("owner-1")
self.assertEqual(collection.owner_id, "owner-1")
self.assertTrue(isinstance(collection, RiakContactsCollection))
class TestRiakContactsCollection(TestCase):
def test_collection_provides_ICollection(self):
"""
The return value of .get_row_collection() is an object that provides
ICollection.
"""
collection = RiakContactsCollection("owner-1")
verifyObject(ICollection, collection)
def test_init(self):
collection = RiakContactsCollection("owner-1")
self.assertEqual(collection.owner_id, "owner-1")
|
Create an RDP file on Mac OS X. | // The MIT License (MIT)
//
// Copyright (c) 2015 Douglas Thrift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"fmt"
)
func rdpLaunchNative(instance *Instance, private bool, index int, arguments []string, prompt bool, username string) error {
file, err := rdpCreateFile(instance, private, index, username)
if err != nil {
return err
}
fmt.Println(file, instance.AdminPassword)
return nil
}
| // The MIT License (MIT)
//
// Copyright (c) 2015 Douglas Thrift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
func rdpLaunchNative(instance *Instance, private bool, index int, arguments []string, prompt bool, username string) error {
return nil
}
|
Add default param name in TorrentImpl.Piece func | package storage
import (
"io"
"github.com/anacrolix/torrent/metainfo"
)
type ClientImplCloser interface {
ClientImpl
Close() error
}
// Represents data storage for an unspecified torrent.
type ClientImpl interface {
OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error)
}
// Data storage bound to a torrent.
type TorrentImpl struct {
Piece func(p metainfo.Piece) PieceImpl
Close func() error
// Storages that share the same value, will provide a pointer to the same function.
Capacity *func() *int64
}
// Interacts with torrent piece data. Optional interfaces to implement include io.WriterTo, such as
// when a piece supports a more efficient way to write out incomplete chunks
type PieceImpl interface {
// These interfaces are not as strict as normally required. They can
// assume that the parameters are appropriate for the dimensions of the
// piece.
io.ReaderAt
io.WriterAt
// Called when the client believes the piece data will pass a hash check.
// The storage can move or mark the piece data as read-only as it sees
// fit.
MarkComplete() error
MarkNotComplete() error
// Returns true if the piece is complete.
Completion() Completion
}
type Completion struct {
Complete bool
Ok bool
}
| package storage
import (
"io"
"github.com/anacrolix/torrent/metainfo"
)
type ClientImplCloser interface {
ClientImpl
Close() error
}
// Represents data storage for an unspecified torrent.
type ClientImpl interface {
OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error)
}
// Data storage bound to a torrent.
type TorrentImpl struct {
Piece func(metainfo.Piece) PieceImpl
Close func() error
// Storages that share the same value, will provide a pointer to the same function.
Capacity *func() *int64
}
// Interacts with torrent piece data. Optional interfaces to implement include io.WriterTo, such as
// when a piece supports a more efficient way to write out incomplete chunks
type PieceImpl interface {
// These interfaces are not as strict as normally required. They can
// assume that the parameters are appropriate for the dimensions of the
// piece.
io.ReaderAt
io.WriterAt
// Called when the client believes the piece data will pass a hash check.
// The storage can move or mark the piece data as read-only as it sees
// fit.
MarkComplete() error
MarkNotComplete() error
// Returns true if the piece is complete.
Completion() Completion
}
type Completion struct {
Complete bool
Ok bool
}
|
Remove this, it properly belongs to ASN1, and that's for a seperate PR | # 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.
INCLUDES = """
#include <openssl/bn.h>
"""
TYPES = """
typedef ... BIGNUM;
typedef ... BN_ULONG;
"""
FUNCTIONS = """
BIGNUM *BN_new();
void BN_free(BIGNUM *);
int BN_set_word(BIGNUM *, BN_ULONG);
char *BN_bn2hex(const BIGNUM *);
int BN_hex2bn(BIGNUM **, const char *);
"""
MACROS = """
"""
| # 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.
INCLUDES = """
#include <openssl/bn.h>
"""
TYPES = """
typedef ... BIGNUM;
typedef ... BN_ULONG;
// Possibly belongs in an asn1.py
typedef ... ASN1_INTEGER;
"""
FUNCTIONS = """
BIGNUM *BN_new();
void BN_free(BIGNUM *);
int BN_set_word(BIGNUM *, BN_ULONG);
char *BN_bn2hex(const BIGNUM *);
int BN_hex2bn(BIGNUM **, const char *);
"""
MACROS = """
ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *, ASN1_INTEGER *);
"""
|
Increase interrupt test wait time to 5s | module.exports = function(grunt) {
'use strict';
grunt.initConfig({
echo: {
one: { message: 'one has changed' },
two: { message: 'two has changed' },
wait: { message: 'I waited 2s', wait: 2000 },
interrupt: { message: 'I was interrupted', wait: 5000 },
},
watch: {
one: {
files: ['lib/one.js'],
tasks: ['echo:one']
},
two: {
files: ['lib/two.js'],
tasks: ['echo:two']
},
wait: {
files: ['lib/wait.js'],
tasks: ['echo:wait']
},
interrupt: {
files: ['lib/interrupt.js'],
tasks: ['echo:interrupt'],
options: { interrupt: true }
}
}
});
// Load the echo task
grunt.loadTasks('../tasks');
// Load this watch task
grunt.loadTasks('../../../tasks');
grunt.registerTask('default', ['echo']);
};
| module.exports = function(grunt) {
'use strict';
grunt.initConfig({
echo: {
one: { message: 'one has changed' },
two: { message: 'two has changed' },
wait: { message: 'I waited 2s', wait: 2000 },
interrupt: { message: 'I was interrupted', wait: 2000 },
},
watch: {
one: {
files: ['lib/one.js'],
tasks: ['echo:one']
},
two: {
files: ['lib/two.js'],
tasks: ['echo:two']
},
wait: {
files: ['lib/wait.js'],
tasks: ['echo:wait']
},
interrupt: {
files: ['lib/interrupt.js'],
tasks: ['echo:interrupt'],
options: { interrupt: true }
}
}
});
// Load the echo task
grunt.loadTasks('../tasks');
// Load this watch task
grunt.loadTasks('../../../tasks');
grunt.registerTask('default', ['echo']);
};
|
Use a singleton object for anonymous identities | /*
* digitalpetri OPC-UA SDK
*
* Copyright (C) 2015 Kevin Herron
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.digitalpetri.opcua.sdk.server.identity;
import com.digitalpetri.opcua.sdk.server.Session;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.channel.SecureChannel;
import com.digitalpetri.opcua.stack.core.types.structured.AnonymousIdentityToken;
import com.digitalpetri.opcua.stack.core.types.structured.UserTokenPolicy;
public class AnonymousIdentityValidator extends IdentityValidator {
public static final Object ANONYMOUS_IDENTITY_OBJECT = new Object();
@Override
public Object validateAnonymousToken(AnonymousIdentityToken token, UserTokenPolicy tokenPolicy,
SecureChannel channel, Session session) throws UaException {
return ANONYMOUS_IDENTITY_OBJECT;
}
}
| /*
* digitalpetri OPC-UA SDK
*
* Copyright (C) 2015 Kevin Herron
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.digitalpetri.opcua.sdk.server.identity;
import com.digitalpetri.opcua.sdk.server.Session;
import com.digitalpetri.opcua.stack.core.UaException;
import com.digitalpetri.opcua.stack.core.channel.SecureChannel;
import com.digitalpetri.opcua.stack.core.types.structured.AnonymousIdentityToken;
import com.digitalpetri.opcua.stack.core.types.structured.UserTokenPolicy;
public class AnonymousIdentityValidator extends IdentityValidator {
@Override
public Object validateAnonymousToken(AnonymousIdentityToken token, UserTokenPolicy tokenPolicy,
SecureChannel channel, Session session) throws UaException {
return new Object();
}
}
|
Fix all bugs with WOW | /**
* Created by George Ruan on May 22, 2016.
*
* Defines the routing behavior for the web application.
*/
(function() {
'use strict';
angular
.module('nobe', ['ngRoute']) // Set up app dependencies
.config(function($routeProvider) {
// Define Routes
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/404', {
templateUrl: '404.html',
})
.when('', {
redirectTo: '/404'
})
.otherwise({
redirectTo: '/404'
});
})
.run(['$rootScope', function($rootScope) {
let wow = new WOW({live : true});
wow.init();
}]);
})();
| /**
* Created by George Ruan on May 22, 2016.
*
* Defines the routing behavior for the web application.
*/
(function() {
'use strict';
angular
.module('nobe', ['ngRoute']) // Set up app dependencies
.config(function($routeProvider) {
// Define Routes
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/404', {
templateUrl: '404.html',
})
.otherwise({
redirectTo: '/404'
});
})
.run(['$rootScope', function($rootScope) {
let wow = new WOW({live : true}).init();
$rootScope.$on('$viewContentLoaded', function() {
wow.start();
});
}]);
})();
|
Add command line option to print a warning for each duplicate. | //
// SortList.java
//
import java.io.*;
import java.util.Arrays;
import java.util.Vector;
/** Sorts a text file alphabetically, removing duplicates. */
public class SortList {
public static void main(String[] args) throws Exception {
boolean showDups = args[0].equals("-v");
String file = args[showDups ? 1 : 0];
Vector v = new Vector();
BufferedReader fin = new BufferedReader(new FileReader(file));
while (true) {
String line = fin.readLine();
if (line == null) break;
v.add(line);
}
fin.close();
String[] lines = new String[v.size()];
v.copyInto(lines);
Arrays.sort(lines);
new File(file).renameTo(new File(file + ".old"));
PrintWriter fout = new PrintWriter(new FileWriter(file));
for (int i=0; i<lines.length; i++) {
if (i == 0 || !lines[i].equals(lines[i-1])) fout.println(lines[i]);
else if (showDups) System.out.println("Duplicate line: " + lines[i]);
}
fout.close();
}
}
| //
// SortList.java
//
import java.io.*;
import java.util.Arrays;
import java.util.Vector;
/** Sorts a text file alphabetically, removing duplicates. */
public class SortList {
public static void main(String[] args) throws Exception {
String file = args[0];
Vector v = new Vector();
BufferedReader fin = new BufferedReader(new FileReader(file));
while (true) {
String line = fin.readLine();
if (line == null) break;
v.add(line);
}
fin.close();
String[] lines = new String[v.size()];
v.copyInto(lines);
Arrays.sort(lines);
new File(file).renameTo(new File(file + ".old"));
PrintWriter fout = new PrintWriter(new FileWriter(file));
for (int i=0; i<lines.length; i++) {
if (i == 0 || !lines[i].equals(lines[i-1])) fout.println(lines[i]);
}
fout.close();
}
}
|
Stop feature extraction for reader mode when <body> isn't there yet
BUG=495318
Review URL: https://codereview.chromium.org/1251293002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#345389} | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function() {
function hasOGArticle() {
var elems = document.head.querySelectorAll(
'meta[property="og:type"],meta[name="og:type"]');
for (var i in elems) {
if (elems[i].content && elems[i].content.toUpperCase() == 'ARTICLE') {
return true;
}
}
return false;
}
var body = document.body;
if (!body) {
return false;
}
return JSON.stringify({
'opengraph': hasOGArticle(),
'url': document.location.href,
'numElements': body.querySelectorAll('*').length,
'numAnchors': body.querySelectorAll('a').length,
'numForms': body.querySelectorAll('form').length,
'innerText': body.innerText,
'textContent': body.textContent,
'innerHTML': body.innerHTML,
});
})()
| // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function() {
function hasOGArticle() {
var elems = document.head.querySelectorAll(
'meta[property="og:type"],meta[name="og:type"]');
for (var i in elems) {
if (elems[i].content && elems[i].content.toUpperCase() == 'ARTICLE') {
return true;
}
}
return false;
}
var body = document.body;
return JSON.stringify({
'opengraph': hasOGArticle(),
'url': document.location.href,
'numElements': body.querySelectorAll('*').length,
'numAnchors': body.querySelectorAll('a').length,
'numForms': body.querySelectorAll('form').length,
'innerText': body.innerText,
'textContent': body.textContent,
'innerHTML': body.innerHTML,
});
})()
|
Add new state for driving away from cone | #!/usr/bin/env python
#
# Copyright 2017 Robot Garden, 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.
#
# States and Transitions
from auto_number import AutoNumber
class STATE(AutoNumber):
Start = ()
Following_waypoint = ()
Avoiding_obstacle = ()
Driving_toward_cone = ()
Driving_away_from_cone = ()
Success = ()
Failure = ()
End = ()
class TRANSITION(AutoNumber):
obstacle_seen = ()
near_cone = ()
obstacle_cleared = ()
touched_cone = ()
passed_cone = ()
segment_timeout = ()
touched_last_cone = ()
passed_last_cone = ()
course_timeout = ()
cleared_cone = ()
| #!/usr/bin/env python
#
# Copyright 2017 Robot Garden, 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.
#
# States and Transitions
from auto_number import AutoNumber
class STATE(AutoNumber):
Start = ()
Following_waypoint = ()
Avoiding_obstacle = ()
Driving_toward_cone = ()
Driving_away_from_cone = ()
Success = ()
Failure = ()
End = ()
class TRANSITION(AutoNumber):
obstacle_seen = ()
near_cone = ()
obstacle_cleared = ()
touched_cone = ()
passed_cone = ()
segment_timeout = ()
touched_last_cone = ()
passed_last_cone = ()
course_timeout = ()
|
Fix psr naming convention for variables. | <?php
class UsersPosts extends Seeder
{
public function init()
{
$faker = $this->faker;
$this->define('users', function () use ($faker) {
return [
'name' => $faker->name,
];
}, $truncate = true);
$this->define('posts', function ($data) use ($faker) {
return [
'user_id' => $data->user_id,
'title' => $faker->sentence($nbWords = 6, $variableNbWords = true),
'content' => $faker->realText(500),
];
}, $truncate = true);
}
public function run()
{
$this->seed(function ($counter){
$userId = $this->factory('users')->create();
$data = ['user_id' => $userId];
$random = rand(1,10);
for ($i=0; $i < $random; $i++) {
$this->factory('posts')->create($data);
}
});
}
}
| <?php
class UsersPosts extends Seeder
{
public function init()
{
$faker = $this->faker;
$this->define('users', function () use ($faker) {
return [
'name' => $faker->name,
];
}, $truncate = true);
$this->define('posts', function ($data) use ($faker) {
return [
'user_id' => $data->user_id,
'title' => $faker->sentence($nbWords = 6, $variableNbWords = true),
'content' => $faker->realText(500),
];
}, $truncate = true);
}
public function run()
{
$this->seed(function ($counter){
$user_id = $this->factory('users')->create();
$data = ['user_id' => $user_id];
$random = rand(1,10);
for ($i=0; $i < $random; $i++) {
$this->factory('posts')->create($data);
}
});
}
}
|
Implement a test checking that options needs to be a non empty list | # -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
| # -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
|
Move callback notification 'after' return. | package org.jboss.pnc.jenkinsbuilddriver;
import org.jboss.pnc.core.spi.builddriver.BuildDriver;
import org.jboss.pnc.core.spi.repositorymanager.Repository;
import org.jboss.pnc.model.BuildResult;
import org.jboss.pnc.model.BuildType;
import org.jboss.pnc.model.Project;
import java.util.function.Consumer;
/**
* Created by <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> on 2014-11-23.
*/
//TODO implement me
public class JenkinsBuildDriver implements BuildDriver {
private Consumer<BuildResult> onBuildComplete;
@Override
public String getDriverId() {
return null;
}
@Override
public void setDeployRepository(Repository deployRepository) {
}
@Override
public void setSourceRepository(Repository repositoryProxy) {
}
@Override
public void buildProject(Project project, Consumer<BuildResult> onBuildComplete) {
this.onBuildComplete = onBuildComplete;
//TODO implement me
return;
}
@Override
public BuildType getBuildType() {
return BuildType.JAVA;
}
//TODO
private void notifyBuildComplete() {
//notify build complete
onBuildComplete.accept(new BuildResult());
}
}
| package org.jboss.pnc.jenkinsbuilddriver;
import org.jboss.pnc.core.spi.builddriver.BuildDriver;
import org.jboss.pnc.core.spi.repositorymanager.Repository;
import org.jboss.pnc.model.BuildResult;
import org.jboss.pnc.model.BuildType;
import org.jboss.pnc.model.Project;
import java.util.function.Consumer;
/**
* Created by <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> on 2014-11-23.
*/
//TODO implement me
public class JenkinsBuildDriver implements BuildDriver {
@Override
public String getDriverId() {
return null;
}
@Override
public void setDeployRepository(Repository deployRepository) {
}
@Override
public void setSourceRepository(Repository repositoryProxy) {
}
@Override
public void buildProject(Project project, Consumer<BuildResult> onBuildComplete) {
//TODO implement me
//notify build complete
onBuildComplete.accept(new BuildResult());
}
@Override
public BuildType getBuildType() {
return BuildType.JAVA;
}
}
|
Use 'latest' for typing versions. | /* eslint-env node */
const path = require('path');
module.exports = {
description: 'Initialize files needed for typescript compilation',
files() {
return [
path.join(this.path, 'files', 'tsconfig.json'),
path.join(this.path, 'files', 'app', 'config', 'environment.d.ts'),
];
},
mapFile() {
const result = this._super.mapFile.apply(this, arguments);
const tsconfigPattern = `${path.sep}tsconfig.json`;
const appPattern = `${path.sep}app${path.sep}`;
if (result.indexOf(tsconfigPattern) > -1) {
return 'tsconfig.json';
} else if (result.indexOf(appPattern) > -1) {
var pos = result.indexOf(appPattern);
return result.substring(pos + 1);
}
},
locals() {
return {
inRepoAddons: (this.project.pkg['ember-addon'] || {}).paths || [],
};
},
normalizeEntityName() {
// Entity name is optional right now, creating this hook avoids an error.
},
afterInstall() {
return this.addPackagesToProject([
{ name: 'typescript', target: 'latest' },
{ name: '@types/ember', target: 'latest' },
{ name: '@types/rsvp', target: 'latest' },
{ name: '@types/ember-testing-helpers', target: 'latest' },
]);
},
};
| /* eslint-env node */
const path = require('path');
module.exports = {
description: 'Initialize files needed for typescript compilation',
files() {
return [
path.join(this.path, 'files', 'tsconfig.json'),
path.join(this.path, 'files', 'app', 'config', 'environment.d.ts'),
];
},
mapFile() {
const result = this._super.mapFile.apply(this, arguments);
const tsconfigPattern = `${path.sep}tsconfig.json`;
const appPattern = `${path.sep}app${path.sep}`;
if (result.indexOf(tsconfigPattern) > -1) {
return 'tsconfig.json';
} else if (result.indexOf(appPattern) > -1) {
var pos = result.indexOf(appPattern);
return result.substring(pos + 1);
}
},
locals() {
return {
inRepoAddons: (this.project.pkg['ember-addon'] || {}).paths || []
};
},
normalizeEntityName() {
// Entity name is optional right now, creating this hook avoids an error.
},
afterInstall() {
return this.addPackagesToProject([
{ name: 'typescript', target: '^2.4.2' },
{ name: '@types/ember', target: '^2.7.43' },
{ name: '@types/rsvp', target: '^3.3.0' },
{ name: '@types/ember-testing-helpers' },
]);
},
};
|
Use Print instead of Printf. | package main
import (
"bufio"
"fmt"
"log"
"net"
)
const PORT = "2525"
func main() {
server := createServer(PORT)
defer server.Close()
for {
conn, err := server.Accept()
if err != nil {
log.Fatalf("Error accepting: %v\n", err)
}
go handleConnection(conn)
}
}
func createServer(port string) (net.Listener) {
server, err := net.Listen("tcp", ":" + PORT)
if err != nil {
log.Fatalf("Error listening to port %s\n", PORT)
}
return server
}
func handleConnection(conn net.Conn) {
defer conn.Close()
conn.Write([]byte("220 OK\n"))
buffer := bufio.NewReader(conn)
for {
str, _ := buffer.ReadString('\n')
if str == "DATA\r\n" {
break
}
conn.Write([]byte("250 OK\n"))
}
conn.Write([]byte("354 OK\n"))
buffer = bufio.NewReader(conn)
for {
str, _ := buffer.ReadString('\n')
if str == ".\r\n" {
break
}
fmt.Print(str)
}
conn.Write([]byte("250 OK\n"))
conn.Write([]byte("221 OK\n"))
}
| package main
import (
"bufio"
"fmt"
"log"
"net"
)
const PORT = "2525"
func main() {
server := createServer(PORT)
defer server.Close()
for {
conn, err := server.Accept()
if err != nil {
log.Fatalf("Error accepting: %v\n", err)
}
go handleConnection(conn)
}
}
func createServer(port string) (net.Listener) {
server, err := net.Listen("tcp", ":" + PORT)
if err != nil {
log.Fatalf("Error listening to port %s\n", PORT)
}
return server
}
func handleConnection(conn net.Conn) {
defer conn.Close()
conn.Write([]byte("220 OK\n"))
buffer := bufio.NewReader(conn)
for {
str, _ := buffer.ReadString('\n')
if str == "DATA\r\n" {
break
}
conn.Write([]byte("250 OK\n"))
}
conn.Write([]byte("354 OK\n"))
buffer = bufio.NewReader(conn)
for {
str, _ := buffer.ReadString('\n')
if str == ".\r\n" {
break
}
fmt.Printf(str)
}
conn.Write([]byte("250 OK\n"))
conn.Write([]byte("221 OK\n"))
}
|
Revert "BUGFIX: Removed broken findOneByID wrapper"
This reverts commit 8a069ac3d51473aab74d4bc2b2f1f8867fbef250. | /**
* Plugin which transforms most Monoxide objects into promise returns
*/
var promisify = require('util').promisify;
module.exports = function(finish, o) {
// Promisify all module methods
[
'connect',
'disconnect',
'create',
'update',
'delete',
'meta',
'runCommand',
'save',
].forEach(method => o[method] = promisify(o[method]));
// Promisify all model methods
o.on('modelCreate', (model, m) => {
[
'aggregate',
'checkIndexes',
'create',
'distinct',
'getIndexes',
'getSchemaIndexes',
'remove',
'update',
'findOneByID',
].forEach(method => m[method] = promisify(m[method]));
m.findOneByID = id => new Promise((resolve, reject) => {
if (!id) return reject('No ID specified');
o.internal.query({$collection: model, $id: id}, (err, result) => {
if (err) return reject(err);
resolve(result);
});
});
});
// Promisify all document methods
o.on('documentCreate', doc => {
[
'delete',
'populate',
'remove',
'save',
].forEach(method => doc.__proto__[method] = promisify(doc.__proto__[method]));
});
finish();
};
| /**
* Plugin which transforms most Monoxide objects into promise returns
*/
var promisify = require('util').promisify;
module.exports = function(finish, o) {
// Promisify all module methods
[
'connect',
'disconnect',
'create',
'update',
'delete',
'meta',
'runCommand',
'save',
].forEach(method => o[method] = promisify(o[method]));
// Promisify all model methods
o.on('modelCreate', (model, m) => {
[
'aggregate',
'checkIndexes',
'create',
'distinct',
'getIndexes',
'getSchemaIndexes',
'remove',
'update',
].forEach(method => m[method] = promisify(m[method]));
});
// Promisify all document methods
o.on('documentCreate', doc => {
[
'delete',
'populate',
'remove',
'save',
].forEach(method => doc.__proto__[method] = promisify(doc.__proto__[method]));
});
finish();
};
|
Modify test to reflect that api returns string response. | import pytest
from pygraylog.pygraylog import graylogapi
def test_get():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
res = api._get()
expected = "{\"one\": \"two\"}\n"
assert res == expected
def test_post():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
with pytest.raises(NotImplementedError):
api._post()
def test_put():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
with pytest.raises(NotImplementedError):
api._put()
def test_delete():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
with pytest.raises(NotImplementedError):
api._delete()
| import pytest
from pygraylog.pygraylog import graylogapi
def test_get():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
res = api._get()
expected = {
'one': 'two'
}
assert res == expected
def test_post():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
with pytest.raises(NotImplementedError):
api._post()
def test_put():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
with pytest.raises(NotImplementedError):
api._put()
def test_delete():
api = graylogapi.GraylogAPI('http://echo.jsontest.com/one/two',
username = 'Zack',
password = 'Zack')
with pytest.raises(NotImplementedError):
api._delete()
|
Rename McGillException to error (mcgill.error) | import mechanize
import os
class error(Exception):
pass
urls = {
'login': 'twbkwbis.P_WWWLogin',
'transcript': 'bzsktran.P_Display_Form?user_type=S&tran_type=V'
}
_base_url = 'https://banweb.mcgill.ca/pban1/%s'
urls = {k: _base_url % v for k,v in urls.items()}
browser = mechanize.Browser()
def login(sid=None, pin=None):
if sid is None:
sid = os.environ.get('MCGILL_SID', None)
if pin is None:
pin = os.environ.get('MCGILL_PIN', None)
if sid is None or pin is None:
raise error('McGill ID or PIN not provided.')
browser.open(urls['login'])
browser.select_form('loginform')
browser['sid'] = sid
browser['PIN'] = pin
response = browser.submit()
if 'Authorization Failure' in response.read():
raise error('Invalid McGill ID or PIN.')
| import mechanize
import os
class McGillException(Exception):
pass
urls = {
'login': 'twbkwbis.P_WWWLogin',
'transcript': 'bzsktran.P_Display_Form?user_type=S&tran_type=V'
}
_base_url = 'https://banweb.mcgill.ca/pban1/%s'
urls = {k: _base_url % v for k,v in urls.items()}
browser = mechanize.Browser()
def login(sid=None, pin=None):
if sid is None:
sid = os.environ.get('MCGILL_SID', None)
if pin is None:
pin = os.environ.get('MCGILL_PIN', None)
if sid is None or pin is None:
raise McGillException('McGill ID or PIN not provided.')
browser.open(urls['login'])
browser.select_form('loginform')
browser['sid'] = sid
browser['PIN'] = pin
response = browser.submit()
if 'Authorization Failure' in response.read():
raise McGillException('Invalid McGill ID or PIN.')
|
Update XMLRPC page factory to new page factory API.
svn commit r35170 | <?php
require_once 'Site/exceptions/SiteNotFoundException.php';
require_once 'Site/layouts/SiteXMLRPCServerLayout.php';
require_once 'Site/SitePageFactory.php';
/**
* @package Site
* @copyright 2006-2008 silverorange
*/
class SiteXMLRPCServerFactory extends SitePageFactory
{
// {{{ public function get()
public function ($source, SiteLayout $layout = null)
{
$layout = ($layout === null) ? $this->getLayout($source) : $layout;
$map = $this->getPageMap();
if (!isset($map[$source])) {
throw new SiteNotFoundException();
}
$class = $map[$source];
return $this->getPage($class, $layout);
}
// }}}
// {{{ protected function getPageMap()
protected function getPageMap()
{
return array(
'upload-status' => 'SiteUploadStatusServer',
);
}
// }}}
// {{{ protected function getLayout()
protected function getLayout($source)
{
return new SiteXMLRPCServerLayout($this->app);
}
// }}}
}
?>
| <?php
require_once 'Site/exceptions/SiteNotFoundException.php';
require_once 'Site/layouts/SiteXMLRPCServerLayout.php';
require_once 'Site/SitePageFactory.php';
/**
* @package Site
* @copyright 2006 silverorange
*/
class SiteXMLRPCServerFactory extends SitePageFactory
{
// {{{ public function __construct()
public function __construct()
{
$this->class_map['Site'] = 'Site/pages';
}
// }}}
// {{{ public function resolvePage()
public function resolvePage(SiteWebApplication $app, $source)
{
$layout = $this->resolveLayout($app, $source);
$map = $this->getPageMap();
if (isset($map[$source])) {
$class = $map[$source];
$params = array($app, $layout);
$page = $this->instantiatePage($app, $class, $params);
return $page;
}
throw new SiteNotFoundException();
}
// }}}
// {{{ protected function getPageMap()
protected function getPageMap()
{
return array(
'upload-status' => 'SiteUploadStatusServer',
);
}
// }}}
// {{{ protected function resolveLayout()
protected function resolveLayout($app, $source)
{
return new SiteXMLRPCServerLayout($app);
}
// }}}
}
?>
|
Make stratis an installable script.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com> | import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
scripts=['bin/stratis']
)
| import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
)
|
Add pre-execution script via message passing | let attachedTabs = {};
let textContentArr;
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
let tabId = tab.id;
// https://developer.chrome.com/extensions/content_scripts#pi
chrome.tabs.executeScript(tabId, {file: 'src/bg/textcontent.js'}, function (){
chrome.tabs.sendMessage(tabId, {}, function(response) {
textContentArr = response;
console.log(textContentArr);
});
});
if (!attachedTabs[tabId]) {
attachedTabs[tabId] = 'collapsed';
chrome.browserAction.setIcon({tabId: tabId, path:'icons/pause.png'});
chrome.browserAction.setTitle({tabId: tabId, title:'Pause collapsing'});
chrome.tabs.executeScript({file: 'src/bg/collapse.js'});
} else if (attachedTabs[tabId]) {
delete attachedTabs[tabId];
chrome.browserAction.setIcon({tabId: tabId, path:'icons/continue.png'});
chrome.browserAction.setTitle({tabId: tabId, title:'Enable collapsing'});
chrome.tabs.executeScript({file: 'src/bg/expand.js'});
}
});
| let attachedTabs = {};
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
let tabId = tab.id;
if (!attachedTabs[tabId]) {
attachedTabs[tabId] = 'collapsed';
chrome.browserAction.setIcon({tabId: tabId, path:'icons/pause.png'});
chrome.browserAction.setTitle({tabId: tabId, title:'Pause collapsing'});
chrome.tabs.executeScript({file: 'src/bg/collapse.js'});
} else if (attachedTabs[tabId]) {
delete attachedTabs[tabId];
chrome.browserAction.setIcon({tabId: tabId, path:'icons/continue.png'});
chrome.browserAction.setTitle({tabId: tabId, title:'Enable collapsing'});
chrome.tabs.executeScript({file: 'src/bg/expand.js'});
}
});
|
Declare a few more entry points | /**
* Turnpike.JS
*
* A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
* framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
*
* Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
* deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
* You shouldn't need or want to use or call any of the plumbing yourself.
* If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
* If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
* alter the plumbing interfaces at any time, even between minor versions and revisions.
*
* Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
* expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
* existing plumbing interfaces with few to no changes without a bump in the major version number.
*/
var turnpike = {};
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
turnpike.drive = require("./lib/Drive");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
turnpike.Connection = require("./lib/Connection");
module.exports = turnpike;
| /**
* Turnpike.JS
*
* A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
* framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
*
* Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
* deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
* You shouldn't need or want to use or call any of the plumbing yourself.
* If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
* If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
* alter the plumbing interfaces at any time, even between minor versions and revisions.
*
* Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
* expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
* existing plumbing interfaces with few to no changes without a bump in the major version number.
*/
var turnpike = {};
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
module.exports.turnpike = turnpike;
|
Modify hostname for web integration tests | import requests
import pytest
class TestWebUI(object):
def get_page(self, page):
return requests.get('http://nginx' + page)
pages = [
{
'page': '/',
'matching_text': 'Diamond',
},
{
'page': '/scoreboard',
},
{
'page': '/login',
'matching_text': 'Please sign in',
},
{
'page': '/about',
'matching_text': 'Use the following credentials to login',
},
{
'page': '/overview',
},
{
'page': '/api/overview/data'
}
]
@pytest.mark.parametrize("page_data", pages)
def test_page(self, page_data):
resp = self.get_page(page_data['page'])
assert resp.status_code == 200
if 'matching_text' in page_data:
assert page_data['matching_text'] in resp.text
| import requests
import pytest
class TestWebUI(object):
def get_page(self, page):
return requests.get('http://127.0.0.1' + page)
pages = [
{
'page': '/',
'matching_text': 'Diamond',
},
{
'page': '/scoreboard',
},
{
'page': '/login',
'matching_text': 'Please sign in',
},
{
'page': '/about',
'matching_text': 'Use the following credentials to login',
},
{
'page': '/overview',
},
{
'page': '/api/overview/data'
}
]
@pytest.mark.parametrize("page_data", pages)
def test_page(self, page_data):
resp = self.get_page(page_data['page'])
assert resp.status_code == 200
if 'matching_text' in page_data:
assert page_data['matching_text'] in resp.text
|
Reset state when user logs out | import { reducer as formReducer } from 'redux-form';
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {
organization,
starredBoard,
notification,
modals,
board,
home
} from '../app/routes/home/modules/index';
import { signUp } from '../app/routes/signUp/modules/index';
import { login } from '../app/routes/login/modules/index';
import {
boardsMenu,
popOver,
app
} from '../app/modules/index';
import {
boardView,
card
} from '../app/routes/home/routes/boardView/modules/index';
const appReducer = combineReducers({
organization,
starredBoard,
notification,
modals,
board,
home,
signUp,
login,
boardsMenu,
popOver,
app,
boardView,
card,
form: formReducer,
routing: routerReducer
})
const rootReducer = (state, action) => {
if (action.type === 'UN_AUTHENTICATE_USER') {
state = undefined
}
return appReducer(state, action)
}
export default rootReducer; | import { reducer as formReducer } from 'redux-form';
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {
organization,
starredBoard,
notification,
modals,
board,
home
} from '../app/routes/home/modules/index';
import { signUp } from '../app/routes/signUp/modules/index';
import { login } from '../app/routes/login/modules/index';
import {
boardsMenu,
popOver,
app
} from '../app/modules/index';
import {
boardView,
card
} from '../app/routes/home/routes/boardView/modules/index';
const rootReducer = combineReducers({
organization,
starredBoard,
notification,
modals,
board,
home,
signUp,
login,
boardsMenu,
popOver,
app,
boardView,
card,
form: formReducer,
routing: routerReducer
})
export default rootReducer; |
Remove typecast on setting Response | <?php
namespace Expressly\Event;
use Buzz\Message\Response;
use Symfony\Component\EventDispatcher\Event;
class ResponseEvent extends Event
{
private $response;
public function getResponse()
{
return $this->response;
}
public function setResponse($response)
{
$this->response = $response;
return $this;
}
public function isSuccessful()
{
if (!$this->response instanceof Response) {
return false;
}
return $this->response->isSuccessful();
}
public function getContent()
{
if (!$this->response instanceof Response) {
return null;
}
$content = $this->response->getContent();
if (is_array($content)) {
return $content;
}
$json = json_decode($content, true);
return (json_last_error() == JSON_ERROR_NONE) ? $json : $content;
}
} | <?php
namespace Expressly\Event;
use Buzz\Message\Response;
use Symfony\Component\EventDispatcher\Event;
class ResponseEvent extends Event
{
private $response;
public function getResponse()
{
return $this->response;
}
public function setResponse(Response $response)
{
$this->response = $response;
return $this;
}
public function isSuccessful()
{
if (!$this->response instanceof Response) {
return false;
}
return $this->response->isSuccessful();
}
public function getContent()
{
if (!$this->response instanceof Response) {
return null;
}
$content = $this->response->getContent();
if (is_array($content)) {
return $content;
}
$json = json_decode($content, true);
return (json_last_error() == JSON_ERROR_NONE) ? $json : $content;
}
} |
Update Service Provider to include drivers cofnig | <?php namespace Coreplex\Meta;
use Illuminate\Support\ServiceProvider;
class MetaServiceProvider extends ServiceProvider {
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// Set the files to publish
$this->publishes([
__DIR__.'/../config/meta.php' => config_path('meta.php'),
__DIR__.'/../config/drivers.php' => config_path('drivers.php'),
__DIR__.'/../database/migrations/' => base_path('database/migrations')
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/meta.php', 'meta');
$this->mergeConfigFrom(__DIR__.'/../config/drivers.php', 'drivers');
}
} | <?php namespace Coreplex\Meta;
use Illuminate\Support\ServiceProvider;
class MetaServiceProvider extends ServiceProvider {
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
// Set the files to publish
$this->publishes([
__DIR__.'/../config/meta.php' => config_path('meta.php'),
__DIR__.'/../config/drivers.php' => config_path('drivers.php'),
__DIR__.'/../database/migrations/' => base_path('database/migrations')
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/meta.php', 'meta');
}
} |
Add delay to guarentee that microtime has changed. | <?php
use Atto\Container;
class ContainerTest extends PHPUnit_Framework_TestCase
{
function testContainer()
{
$container = new Container();
$this->assertInstanceOf('Atto\Container', $container);
// Parameters
$container = $container->setParameter('hash_algo', 'sha256');
$this->assertInstanceOf('Atto\Container', $container);
$this->assertSame('sha256', $container->get('hash_algo'));
// Factory
$container = $container->setFactory('hash_time_factory', function($c)
{
return hash($c->get('hash_algo'), (string)microtime(true));
});
$timeA = $container->get('hash_time_factory');
$timeB = $container->get('hash_time_factory');
$this->assertNotSame($timeA, $timeB);
// Service
$container = $container->setService('hash_time_service', function($c)
{
return hash($c->get('hash_algo'), (string)microtime(true));
});
$timeC = $container->get('hash_time_service');
sleep(1);
$timeD = $container->get('hash_time_service');
$this->assertSame($timeC, $timeD);
}
}
| <?php
use Atto\Container;
class ContainerTest extends PHPUnit_Framework_TestCase
{
function testContainer()
{
$container = new Container();
$this->assertInstanceOf('Atto\Container', $container);
// Parameters
$container = $container->setParameter('hash_algo', 'sha256');
$this->assertInstanceOf('Atto\Container', $container);
$this->assertSame('sha256', $container->get('hash_algo'));
// Factory
$container = $container->setFactory('hash_time_factory', function($c)
{
return hash($c->get('hash_algo'), (string)microtime(true));
});
$timeA = $container->get('hash_time_factory');
$timeB = $container->get('hash_time_factory');
$this->assertNotSame($timeA, $timeB);
// Service
$container = $container->setService('hash_time_service', function($c)
{
return hash($c->get('hash_algo'), (string)microtime(true));
});
$timeC = $container->get('hash_time_service');
$timeD = $container->get('hash_time_service');
$this->assertSame($timeC, $timeD);
}
} |
Throw Omnipay NotFound in case resource not found on gateway | <?php
namespace Omnipay\Braintree\Message;
use Braintree\Exception\NotFound;
use Omnipay\Common\Exception\NotFoundException;
/**
* Find Customer Request
* @method CustomerResponse send()
*/
class FindCustomerRequest extends AbstractRequest
{
public function getData()
{
return $this->getCustomerData();
}
/**
* Send the request with specified data
*
* @param mixed $data
*
* @return \Omnipay\Braintree\Message\CustomerResponse|\Omnipay\Common\Message\ResponseInterface
* @throws \Omnipay\Common\Exception\NotFoundException
*/
public function sendData($data)
{
try {
$response = $this->braintree->customer()->find($this->getCustomerId());
} catch (NotFound $exception) {
throw new NotFoundException($exception->getMessage());
}
return $this->response = new CustomerResponse($this, $response);
}
} | <?php
namespace Omnipay\Braintree\Message;
use Braintree\Exception\NotFound;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Find Customer Request
* @method CustomerResponse send()
*/
class FindCustomerRequest extends AbstractRequest
{
public function getData()
{
return $this->getCustomerData();
}
/**
* Send the request with specified data
*
* @param mixed $data
*
* @return \Omnipay\Braintree\Message\CustomerResponse|\Omnipay\Common\Message\ResponseInterface
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function sendData($data)
{
try {
$response = $this->braintree->customer()->find($this->getCustomerId());
} catch (NotFound $exception) {
throw new NotFoundHttpException($exception->getMessage());
}
return $this->response = new CustomerResponse($this, $response);
}
} |
Fix embedded code being removed
no issue
- changed order of escaping | /* global Showdown, Handlebars, html_sanitize*/
import cajaSanitizers from 'ghost/utils/caja-sanitizers';
var showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm']});
var formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var escapedhtml = '';
// convert markdown to HTML
escapedhtml = showdown.makeHtml(markdown || '');
// replace script and iFrame
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// sanitize html
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
return new Handlebars.SafeString(escapedhtml);
});
export default formatMarkdown; | /* global Showdown, Handlebars, html_sanitize*/
import cajaSanitizers from 'ghost/utils/caja-sanitizers';
var showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm']});
var formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var html = '';
// replace script and iFrame
markdown = markdown.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
markdown = markdown.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// convert markdown to HTML
html = showdown.makeHtml(markdown || '');
// sanitize html
html = html_sanitize(html, cajaSanitizers.url, cajaSanitizers.id);
return new Handlebars.SafeString(html);
});
export default formatMarkdown; |
Add user_settings to serialized addon settings | from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user_addon is not None,
}
ret.update(user_addon.to_json(user) if user_addon else {})
return ret
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
| from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user.get_addon(config.short_name) is not None,
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
# short_name = addon_config.short_name
config = serialize_addon_config(addon_config, user)
'''
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings or {}
})
'''
addon_settings.append(config)
return addon_settings
|
Remove mouseLeave functionality from top nav | angular.module('genome.directive', [])
.directive('dstTopNav', function() {
return {
controller: function($scope, $cookies, $rootScope, $location, SelfFactory) {
$scope.user_first_name = $cookies.user_first_name;
$scope.expand = false;
$scope.onpoolpage = $location.$$path === '/pool' ? true : false;
$scope.onselfpage = $location.$$path === '/self' ? true : false;
$scope.getRelatives = function () {
$scope.onpoolpage = true;
$scope.onselfpage = false;
$location.path('/pool');
};
$scope.getSelf = function () {
$scope.onselfpage = true;
$scope.onpoolpage = false;
$location.path('/self');
};
},
templateUrl: '../static/app/directives/dst_top_nav.html'
};
}); | angular.module('genome.directive', [])
.directive('dstTopNav', function() {
return {
controller: function($scope, $cookies, $rootScope, $location, SelfFactory) {
$scope.user_first_name = $cookies.user_first_name;
$scope.expand = false;
// $scope.toggleNavList = function (ev) {
// if (!(ev.type === 'mouseleave' && $scope.lastEventType === 'click')) {
// $scope.expand = !$scope.expand;
// }
// $scope.lastEventType = ev.type;
// };
$scope.onpoolpage = $location.$$path === '/pool' ? true : false;
$scope.onselfpage = $location.$$path === '/self' ? true : false;
$scope.getRelatives = function () {
$scope.onpoolpage = true;
$scope.onselfpage = false;
$location.path('/pool');
};
$scope.getSelf = function () {
$scope.onselfpage = true;
$scope.onpoolpage = false;
$location.path('/self');
};
},
templateUrl: '../static/app/directives/dst_top_nav.html'
};
}); |
Change path references for angular-mocks | (function () {
'use strict';
module.exports = function(config){
config.set({
basePath : '../../',
files : [
'cla_frontend/assets-src/vendor/raven-js/dist/angular/raven.js',
'cla_frontend/assets/javascripts/lib.min.js',
'cla_frontend/assets/javascripts/cla.main.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'tests/angular-js/unit/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
reporters: ['progress', 'junit'],
junitReporter : {
outputFile: '../reports/karma.xml',
suite: 'unit'
}
});
};
})();
| (function () {
'use strict';
module.exports = function(config){
config.set({
basePath : '../../',
files : [
'cla_frontend/assets-src/vendor/raven-js/dist/angular/raven.js',
'cla_frontend/assets/javascripts/lib.min.js',
'cla_frontend/assets/javascripts/cla.main.min.js',
'cla_frontend/assets-src/vendor/angular-mocks/angular-mocks.js',
'tests/angular-js/unit/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
reporters: ['progress', 'junit'],
junitReporter : {
outputFile: '../reports/karma.xml',
suite: 'unit'
}
});
};
})();
|
Set smaller hitbox to player | import Ship from './Ship';
import Emitter from '../behaviours/Emitter';
import DamageEmitter from '../behaviours/DamageEmitter';
import EnemyDamage from '../behaviours/EnemyDamage';
import RegenerateHealth from '../behaviours/RegenerateHealth';
export default class extends Ship {
constructor(game, x, y) {
super(game, x, y, 'ship');
// Set a 32x32 hitbox
this.body.setSize(32, 32, 16, 16);
this.health = 100;
this.maxHealth = 100;
this.points = 0;
this.events.onKilled.add(() => {
// This is needed otherwise background can be rendered out of place
// http://www.html5gamedevs.com/topic/3359-camera-not-positioned-correctly-after-changing-start-away-from-scrolling/
this.game.world.setBounds(0, 0, this.game.width, this.game.height);
this.game.state.start('Menu');
});
this.addBehaviour(new Emitter(game, this));
this.addBehaviour(new RegenerateHealth(game, this));
this.addBehaviour(new DamageEmitter(game, this));
this.addBehaviour(new EnemyDamage(game, this));
}
}
| import Ship from './Ship';
import Emitter from '../behaviours/Emitter';
import DamageEmitter from '../behaviours/DamageEmitter';
import EnemyDamage from '../behaviours/EnemyDamage';
import RegenerateHealth from '../behaviours/RegenerateHealth';
export default class extends Ship {
constructor(game, x, y) {
super(game, x, y, 'ship');
this.health = 100;
this.maxHealth = 100;
this.points = 0;
this.events.onKilled.add(() => {
// This is needed otherwise background can be rendered out of place
// http://www.html5gamedevs.com/topic/3359-camera-not-positioned-correctly-after-changing-start-away-from-scrolling/
this.game.world.setBounds(0, 0, this.game.width, this.game.height);
this.game.state.start('Menu');
});
this.addBehaviour(new Emitter(game, this));
this.addBehaviour(new RegenerateHealth(game, this));
this.addBehaviour(new DamageEmitter(game, this));
this.addBehaviour(new EnemyDamage(game, this));
}
}
|
Correct path to openveo-api while generating documentation
Yuidoc needs the path to the openveo-api documentation to establish links between openveo-publish documentation and openveo-api. | module.exports = {
// Publish doc
publish : {
"name" : "<%= pkg.name %>",
"description" : "<%= pkg.description %>",
"version" : "<%= pkg.version %>",
"options" : {
"paths" : "app/server",
"outdir" : "./doc/openveo-publish",
"linkNatives" : true,
"external": {
"data": [
{
"base" : "../../doc/openveo-api/",
"json" : "../../doc/openveo-api/data.json"
}
]
}
}
}
}; | module.exports = {
// Publish doc
publish : {
"name" : "<%= pkg.name %>",
"description" : "<%= pkg.description %>",
"version" : "<%= pkg.version %>",
"options" : {
"paths" : "app/server",
"outdir" : "./doc/openveo-publish",
"linkNatives" : true,
"external": {
"data": [
{
"base" : "../../doc/openveo-api/",
"json" : "./doc/openveo-api/data.json"
}
]
}
}
}
}; |
Fix py3-incompatible test code that causes PY3 test failure. | from rdflib.graph import ConjunctiveGraph
from rdflib.term import Identifier, URIRef
from rdflib.parser import StringInputSource
from os import path
DATA = u"""
<http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> .
"""
PUBLIC_ID = u"http://example.org/record/1"
def test_graph_ids():
def check(kws):
cg = ConjunctiveGraph()
cg.parse(**kws)
for g in cg.contexts():
gid = g.identifier
assert isinstance(gid, Identifier)
yield check, dict(data=DATA, publicID=PUBLIC_ID, format="turtle")
source = StringInputSource(DATA.encode('utf8'))
source.setPublicId(PUBLIC_ID)
yield check, dict(source=source, format='turtle')
if __name__ == '__main__':
import nose
nose.main(defaultTest=__name__)
| from rdflib.graph import ConjunctiveGraph
from rdflib.term import Identifier, URIRef
from rdflib.parser import StringInputSource
from os import path
DATA = u"""
<http://example.org/record/1> a <http://xmlns.com/foaf/0.1/Document> .
"""
PUBLIC_ID = u"http://example.org/record/1"
def test_graph_ids():
def check(kws):
cg = ConjunctiveGraph()
cg.parse(**kws)
for g in cg.contexts():
gid = g.identifier
assert isinstance(gid, Identifier)
yield check, dict(data=DATA, publicID=PUBLIC_ID, format="turtle")
source = StringInputSource(DATA)
source.setPublicId(PUBLIC_ID)
yield check, dict(source=source, format='turtle')
if __name__ == '__main__':
import nose
nose.main(defaultTest=__name__)
|
Check for existing Last.fm creds before scrobbling | import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LASTFM_API_KEY"]
apiSecret = os.environ["LASTFM_API_SECRET"]
username = os.environ["LASTFM_USERNAME"]
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
if not apiKey:
print "No Last.fm API Key was found."
sys.exit(3)
if not apiSecret:
print "No Last.fm API Secret was found."
sys.exit(3)
if not username:
print "No Last.fm username was found."
sys.exit(3)
if not password:
print "No Last.fm password was found."
sys.exit(3)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
network = pylast.LastFMNetwork(api_key=apiKey, api_secret=apiSecret,
username=username, password_hash=passwordHash)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
network.scrobble(songArtist, songName, unixtime)
| import os, sys, json, pylast, calendar
from datetime import datetime
resultJson = json.loads(sys.stdin.read())
# exit immediately if recognition failed
if resultJson["status"]["msg"] != "Success":
print "Recognition failed."
sys.exit(2)
# load Last.fm auth details into environment variables
apiKey = os.environ["LASTFM_API_KEY"]
apiSecret = os.environ["LASTFM_API_SECRET"]
username = os.environ["LASTFM_USERNAME"]
password = os.environ["LASTFM_PASSWORD"]
passwordHash = pylast.md5(password)
# load song details from JSON object
songName = resultJson["metadata"]["music"][0]["title"]
songArtist = resultJson["metadata"]["music"][0]["artists"][0]["name"]
network = pylast.LastFMNetwork(api_key=apiKey, api_secret=apiSecret,
username=username, password_hash=passwordHash)
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
network.scrobble(songArtist, songName, unixtime)
|
Fix error in calculation on lorentz factor | # -*- coding: utf-8 -*-
from __future__ import division
import math
class LorentzFactor(object):
SPEED_OF_LIGHT = 299792458
@staticmethod
def get_beta(velocity, is_percent):
if is_percent:
return velocity
return velocity / SPEED_OF_LIGHT
@staticmethod
def lorentz_factor(velocity, is_percent):
beta = LorentzFactor.get_beta(velocity, is_percent)
return 1 / (math.sqrt(1 - beta ** 2))
class TimeDilation(LorentzFactor):
@staticmethod
def get_proper_time(time, velocity, is_percent=True):
return time * TimeDilation.lorentz_factor(velocity, is_percent)
@staticmethod
def get_time_relative_ex_observer(time, velocity, is_percent=True):
"""
Dilation relative to an external observer
"""
return time / TimeDilation.lorentz_factor(velocity, is_percent)
| # -*- coding: utf-8 -*-
from __future__ import division
import math
class LorentzFactor(object):
SPEED_OF_LIGHT = 299792458
@staticmethod
def get_beta(velocity, is_percent):
if is_percent:
return velocity
return velocity / SPEED_OF_LIGHT
@staticmethod
def lorentz_factor(time, velocity, is_percent):
beta = LorentzFactor.get_beta(velocity, is_percent)
return time / (math.sqrt(1 - beta ** 2))
class TimeDilation(LorentzFactor):
@staticmethod
def get_proper_time(time, velocity, is_percent=True):
return time * TimeDilation.lorentz_factor(time, velocity, is_percent)
@staticmethod
def get_time_relative_ex_observer(time, velocity, is_percent=True):
"""
Dilation relative to an external observer
"""
return time ** 2 / TimeDilation.lorentz_factor(time, velocity, is_percent)
|
Revert "Prevent link processing for dropdowns"
This reverts commit 2cb937a4405627c94c05c391dd610b85ba7e1cad. | 'use strict';
/**
* client
**/
/**
* client.common
**/
/*global $, _, nodeca, window, document*/
/**
* client.common.init()
*
* Assigns all necessary event listeners and handlers.
*
*
* ##### Example
*
* nodeca.client.common.init();
**/
module.exports = function () {
nodeca.io.init();
$(function () {
// Bootstrap.Collapse calls e.preventDefault() only when there's no
// data-target attribute. We don't want URL to be changed, so we are
// forcing prevention of default behavior.
$('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) {
e.preventDefault();
});
//
// Observe quicksearch focus to tweak icon style
//
$('.navbar-search .search-query')
.focus(function (){ $(this).next('div').addClass('focused'); })
.blur(function (){ $(this).next('div').removeClass('focused'); });
});
// history intercepts clicks on all `a` elements,
// so we initialize it as later as possible to have
// "lowest" priority of handlers
nodeca.client.common.init.history();
};
| 'use strict';
/**
* client
**/
/**
* client.common
**/
/*global $, _, nodeca, window, document*/
/**
* client.common.init()
*
* Assigns all necessary event listeners and handlers.
*
*
* ##### Example
*
* nodeca.client.common.init();
**/
module.exports = function () {
nodeca.io.init();
$(function () {
// Bootstrap.Collapse calls e.preventDefault() only when there's no
// data-target attribute. We don't want URL to be changed, so we are
// forcing prevention of default behavior.
$('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) {
e.preventDefault();
});
// Bootstrap.Dropdown don't calls e.preventDefault() by default
$('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) {
e.preventDefault();
});
//
// Observe quicksearch focus to tweak icon style
//
$('.navbar-search .search-query')
.focus(function (){ $(this).next('div').addClass('focused'); })
.blur(function (){ $(this).next('div').removeClass('focused'); });
});
// history intercepts clicks on all `a` elements,
// so we initialize it as later as possible to have
// "lowest" priority of handlers
nodeca.client.common.init.history();
};
|
Add item form cancel button resets validation context. | var addItem = function(){
var newItem = {
store: $('#itemStore').val(),
name: $('#itemName').val(),
weight: $('#itemWeight').val(),
weightType: $('#itemWeightType').val(),
qty: $('#itemQty').val(),
qtyType: $('#itemQtyType').val(),
price: $('#itemPrice').val()
};
Items.insert(newItem, {validationContext: 'insertForm'}, function(error, result) {
if(!error){
this.$('form').find('input:text').val('');
$('#itemStore').focus();
}
});
}
var resetForm = function(template){
template.$('form').find('input:text').val('');
template.$('#addItemAccordion').accordion('close', 0);
Items.simpleSchema().namedContext('insertForm').resetValidation();
}
Template.addItem.events({
'submit form': function(e, template){
addItem();
return false;
},
'click #cancelButton': function(e, template){
resetForm(template);
},
'keypress input': function(e, template){
if(e.keyCode === 27){
resetForm(template);
}
}
});
Template.addItem.rendered = function(){
var self = this;
$('#addItemAccordion.ui.accordion').accordion({
onOpen: function(){
self.$('#itemStore').focus();
}
});
}
| var addItem = function(){
var newItem = {
store: $('#itemStore').val(),
name: $('#itemName').val(),
weight: $('#itemWeight').val(),
weightType: $('#itemWeightType').val(),
qty: $('#itemQty').val(),
qtyType: $('#itemQtyType').val(),
price: $('#itemPrice').val()
};
Items.insert(newItem, {validationContext: 'insertForm'}, function(error, result) {
if(!error){
this.$('form').find('input:text').val('');
$('#itemStore').focus();
}
});
}
var resetForm = function(template){
template.$('form').find('input:text').val('');
template.$('#addItemAccordion').accordion('close', 0);
}
Template.addItem.events({
'submit form': function(e, template){
addItem();
return false;
},
'click #cancelButton': function(e, template){
resetForm(template);
},
'keypress input': function(e, template){
if(e.keyCode === 27){
resetForm(template);
}
}
});
Template.addItem.rendered = function(){
var self = this;
$('#addItemAccordion.ui.accordion').accordion({
onOpen: function(){
self.$('#itemStore').focus();
}
});
}
|
Make conveyor run backwards as disc is shooting to prevent jams | package com.team254.frc2013.commands;
import edu.wpi.first.wpilibj.Timer;
/**
* Shoots a disc that is already loaded into the shooter.
*
* @author tom@team254.com (Tom Bottiglieri)
* @author pat@team254.com (Patrick Fairbank)
*/
public class ShootCommand extends CommandBase {
private Timer shooterTimer;
public ShootCommand() {
requires(shooter);
shooterTimer = new Timer();
}
protected void initialize() {
// Don't fire the piston if the shooter is not turned on.
if (shooter.isOn()) {
shooter.extend();
shooterTimer.reset();
shooterTimer.start();
}
conveyor.setMotor(-.175);
intake.setIntakePower(-.1);
}
protected void execute() {
}
protected boolean isFinished() {
return shooterTimer.get() > 0.2 || !shooter.isOn();
}
protected void end() {
System.out.println("RPM of shot: " + shooter.getRpm());
shooter.retract();
}
protected void interrupted() {
}
}
| package com.team254.frc2013.commands;
import edu.wpi.first.wpilibj.Timer;
/**
* Shoots a disc that is already loaded into the shooter.
*
* @author tom@team254.com (Tom Bottiglieri)
* @author pat@team254.com (Patrick Fairbank)
*/
public class ShootCommand extends CommandBase {
private Timer shooterTimer;
public ShootCommand() {
requires(shooter);
shooterTimer = new Timer();
}
protected void initialize() {
// Don't fire the piston if the shooter is not turned on.
if (shooter.isOn()) {
shooter.extend();
shooterTimer.reset();
shooterTimer.start();
}
}
protected void execute() {
}
protected boolean isFinished() {
return shooterTimer.get() > 0.2 || !shooter.isOn();
}
protected void end() {
System.out.println("RPM of shot: " + shooter.getRpm());
shooter.retract();
}
protected void interrupted() {
}
}
|
Fix to support token based auth strategies | 'use strict';
const authentication = require('feathers-authentication');
<% for (var i = 0; i < authentication.length; i++) { %>
const <%= S(authentication[i].name).capitalize().s %>Strategy = require('<%= authentication[i].strategy %>').Strategy;<% if (authentication[i].tokenStrategy) { %>
const <%= S(authentication[i].name).capitalize().s %>TokenStrategy = require('<%= authentication[i].tokenStrategy %>');<% }} %>
module.exports = function() {
const app = this;
let config = app.get('auth');
<% for (var i = 0; i < authentication.length; i++) { %>
config.<%= authentication[i].name %>.strategy = <%= S(authentication[i].name).capitalize().s %>Strategy;<% if (authentication[i].tokenStrategy) { %>
config.<%= authentication[i].name %>.tokenStrategy = <%= S(authentication[i].name).capitalize().s %>TokenStrategy;<% }} %>
app.set('auth', config);
app.configure(authentication(config));
} | 'use strict';
const authentication = require('feathers-authentication');
<% for (var i = 0; i < authentication.length; i++) { %>
const <%= S(authentication[i].name).capitalize().s %>Strategy = require('<%= authentication[i].strategy %>').Strategy;<% if (authentication[i].tokenStrategy) { %>
const <%= S(authentication[i].name).capitalize().s %>TokenStrategy = require('<%= authentication[i].tokenStrategy %>').Strategy;<% }} %>
module.exports = function() {
const app = this;
let config = app.get('auth');
<% for (var i = 0; i < authentication.length; i++) { %>
config.<%= authentication[i].name %>.strategy = <%= S(authentication[i].name).capitalize().s %>Strategy;<% if (authentication[i].tokenStrategy) { %>
config.<%= authentication[i].name %>.tokenStrategy = <%= S(authentication[i].name).capitalize().s %>TokenStrategy;<% }} %>
app.set('auth', config);
app.configure(authentication(config));
} |
BUMP VERSION to ensure update | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='Flask-HTMLBuilder',
version='0.10',
url='http://github.com/majorz/flask-htmlbuilder',
license='MIT',
author='Zahari Petkov',
author_email='zarchaoz@gmail.com',
description='Flexible Python-only HTML generation for Flask',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
test_suite='nose.collector',
zip_safe=False,
platforms='any',
install_requires=[
'Flask'
],
tests_require=[
'nose'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='Flask-HTMLBuilder',
version='0.4',
url='http://github.com/majorz/flask-htmlbuilder',
license='MIT',
author='Zahari Petkov',
author_email='zarchaoz@gmail.com',
description='Flexible Python-only HTML generation for Flask',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
test_suite='nose.collector',
zip_safe=False,
platforms='any',
install_requires=[
'Flask'
],
tests_require=[
'nose'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
) |
Hide yet-to-be-activated usernames from listings | #
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users WHERE active=1
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
| #
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
Remove styling from start button | package eu.theunitry.fabula.launcher;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
public class UNLauncher extends JPanel
{
private JLabel label;
private JButton startBtn;
public UNLauncher()
{
this.setBackground(new Color(255,82,44));
this.setLayout(new BorderLayout());
this.setBorder(new EmptyBorder(10, 10, 10, 10));
label = new JLabel("Fabula");
label.setForeground(Color.white);
label.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 40));
label.setHorizontalAlignment(JLabel.CENTER);
startBtn = new JButton("Start");
startBtn.setPreferredSize(new Dimension(200,100));
/* Remove default styling */
startBtn.setFocusPainted(false);
startBtn.setBorderPainted(false);
startBtn.setBackground(Color.white);
startBtn.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20));
startBtn.setForeground(Color.white);
this.add(label, BorderLayout.CENTER);
this.add(startBtn, BorderLayout.SOUTH);
}
public JPanel getPanel() {
return this;
}
}
| package eu.theunitry.fabula.launcher;
import javax.swing.*;
import java.awt.*;
public class UNLauncher extends JPanel
{
private JLabel label;
private JButton startBtn;
public UNLauncher()
{
this.setBackground(new Color(255,82,44));
this.setLayout(new BorderLayout());
label = new JLabel("Fabula");
label.setForeground(Color.white);
label.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 40));
label.setHorizontalAlignment(JLabel.CENTER);
startBtn = new JButton("Start");
startBtn.setPreferredSize(new Dimension(200,100));
this.add(label, BorderLayout.CENTER);
this.add(startBtn, BorderLayout.SOUTH);
}
public JPanel getPanel() {
return this;
}
}
|
Fix block class post type prefix | <?php
/**
* Default hero template file.
*
* This is the default hero image for page templates, called
* 'block'. Strictly air specific.
*
* @Date: 2019-10-15 12:30:02
* @Last Modified by: Timi Wahalahti
* @Last Modified time: 2021-01-12 16:00:20
* @package air-light
*/
// Block settings
$block_class = is_front_page() ? ' block-hero-front' : ' block-hero-' . get_post_type();
// Featured image
$featured_image = has_post_thumbnail() ? wp_get_attachment_url( get_post_thumbnail_id() ) : THEME_SETTINGS['default_featured_image'];
?>
<section class="block block-hero<?php echo esc_attr( $block_class ); ?>" style="background-image: url('<?php echo esc_url( $featured_image ); ?>');">
<div class="shade" aria-hidden="true"></div>
<!-- <div class="container">
</div> -->
</section>
| <?php
/**
* Default hero template file.
*
* This is the default hero image for page templates, called
* 'block'. Strictly air specific.
*
* @Date: 2019-10-15 12:30:02
* @Last Modified by: Timi Wahalahti
* @Last Modified time: 2021-01-12 16:00:20
* @package air-light
*/
// Block settings
$block_class = is_front_page() ? ' block-front' : ' block-' . get_post_type();
// Featured image
$featured_image = has_post_thumbnail() ? wp_get_attachment_url( get_post_thumbnail_id() ) : THEME_SETTINGS['default_featured_image'];
?>
<section class="block block-hero<?php echo esc_attr( $block_class ); ?>" style="background-image: url('<?php echo esc_url( $featured_image ); ?>');">
<div class="shade" aria-hidden="true"></div>
<!-- <div class="container">
</div> -->
</section>
|
Update watts-strogatz call to match new NetworkX API | """Top-level init file for brainx package.
"""
def patch_nx():
"""Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3
"""
import networkx as nx
# Quick test to see if we get the broken version
g = nx.watts_strogatz_graph(2, 0, 0)
if g.number_of_nodes() != 2:
# Buggy version detected. Create a patched version and apply it to nx
nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph
def patched_ws(n, k, p, seed=None):
if k<2:
g = nx.Graph()
g.add_nodes_from(range(n))
return g
else:
return nx._watts_strogatz_graph_ori(n, k, p, seed)
patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__
# Applying monkeypatch now
import warnings
warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine")
nx.watts_strogatz_graph = patched_ws
patch_nx()
| """Top-level init file for brainx package.
"""
def patch_nx():
"""Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3
"""
import networkx as nx
# Quick test to see if we get the broken version
g = nx.watts_strogatz_graph(2, 0, 0)
if g.number_of_nodes() != 2:
# Buggy version detected. Create a patched version and apply it to nx
nx._watts_strogatz_graph_ori = nx.watts_strogatz_graph
def patched_ws(n, k, p, create_using=None, seed=None):
if k<2:
g = nx.Graph()
g.add_nodes_from(range(n))
return g
else:
return nx._watts_strogatz_graph_ori(n, k, p, create_using, seed)
patched_ws.__doc__ = nx._watts_strogatz_graph_ori.__doc__
# Applying monkeypatch now
import warnings
warnings.warn("Monkeypatching NetworkX's Watts-Strogatz routine")
nx.watts_strogatz_graph = patched_ws
patch_nx()
|
Implement http wrapper for vtdammin GetSchema
Signed-off-by: Andrew Mason <8a240ff75aa1467ba5eba4db0c8200b61262547e@slack-corp.com> | /*
Copyright 2021 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"context"
vtadminpb "vitess.io/vitess/go/vt/proto/vtadmin"
)
// GetSchema implements the http wrapper for the
// /schema/{cluster_id}/{keyspace}/{table} route.
func GetSchema(ctx context.Context, r Request, api *API) *JSONResponse {
vars := r.Vars()
schema, err := api.server.GetSchema(ctx, &vtadminpb.GetSchemaRequest{
ClusterId: vars["cluster_id"],
Keyspace: vars["keyspace"],
Table: vars["table"],
})
return NewJSONResponse(schema, err)
}
// GetSchemas implements the http wrapper for the /schemas[?cluster=[&cluster=]
// route.
func GetSchemas(ctx context.Context, r Request, api *API) *JSONResponse {
schemas, err := api.server.GetSchemas(ctx, &vtadminpb.GetSchemasRequest{
ClusterIds: r.URL.Query()["cluster"],
})
return NewJSONResponse(schemas, err)
}
| /*
Copyright 2021 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package http
import (
"context"
vtadminpb "vitess.io/vitess/go/vt/proto/vtadmin"
)
// GetSchema implements the http wrapper for the
// /schema/{cluster_id}/{keyspace}/{table} route.
func GetSchema(ctx context.Context, r Request, api *API) *JSONResponse {
panic("unimplemented!")
}
// GetSchemas implements the http wrapper for the /schemas[?cluster=[&cluster=]
// route.
func GetSchemas(ctx context.Context, r Request, api *API) *JSONResponse {
schemas, err := api.server.GetSchemas(ctx, &vtadminpb.GetSchemasRequest{
ClusterIds: r.URL.Query()["cluster"],
})
return NewJSONResponse(schemas, err)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.