text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Remove @version that uses svn revision as it makes useless differences when comparing svn with github
git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1788653 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) 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.
*
*/
package org.apache.jmeter.protocol.jms.sampler;
import javax.jms.JMSException;
import javax.jms.Message;
/**
* Executor for (pseudo) synchronous communication. <br>
* Created on: October 28, 2004
*
*/
public interface QueueExecutor {
/**
* Sends and receives a message.
*
* @param request the message to send
* @param deliveryMode the delivery mode to use
* @param priority the priority for this message
* @param expiration messages lifetime in ms
* @return the received message or <code>null</code>
* @throws JMSException
* in case of an exception from the messaging system
*/
Message sendAndReceive(Message request,
int deliveryMode,
int priority,
long expiration) throws JMSException;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) 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.
*
*/
package org.apache.jmeter.protocol.jms.sampler;
import javax.jms.JMSException;
import javax.jms.Message;
/**
* Executor for (pseudo) synchronous communication. <br>
* Created on: October 28, 2004
*
* @version $Revision$
*/
public interface QueueExecutor {
/**
* Sends and receives a message.
*
* @param request the message to send
* @param deliveryMode the delivery mode to use
* @param priority the priority for this message
* @param expiration messages lifetime in ms
* @return the received message or <code>null</code>
* @throws JMSException
* in case of an exception from the messaging system
*/
Message sendAndReceive(Message request,
int deliveryMode,
int priority,
long expiration) throws JMSException;
}
|
Remove redundant method. Use your first lambda expression.
|
package pl.niekoniecznie.polar.filesystem;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ak on 07.04.15.
*/
public class PolarFile {
private final PolarFileSystem fs = new PolarFileSystem();
private final String path;
public PolarFile(String path) {
this.path = path;
}
public String getPath() {
return this.path;
}
public boolean isDirectory() {
return fs.isDirectory(this);
}
public List<PolarFile> listFiles() throws IOException {
if (!isDirectory()) {
return null;
}
List<PolarFile> result = new ArrayList<>();
fs.list(this).forEach((x) -> result.add(new PolarFile(x)));
return result;
}
}
|
package pl.niekoniecznie.polar.filesystem;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ak on 07.04.15.
*/
public class PolarFile {
private final PolarFileSystem fs = new PolarFileSystem();
private final String path;
public PolarFile(String path) {
this.path = path;
}
public String getPath() {
return this.path;
}
public boolean isDirectory() {
return fs.isDirectory(this);
}
public List<String> list() throws IOException {
return fs.list(this);
}
public List<PolarFile> listFiles() throws IOException {
if (!isDirectory()) {
return null;
}
List<PolarFile> result = new ArrayList<>();
for (String child : list()) {
result.add(new PolarFile(child));
}
return result;
}
}
|
Fix browsable API in test project - add staticfiles app.
|
import os
DEBUG = True
BASE_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
SECRET_KEY = '_'
MIDDLEWARE_CLASSES = ()
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'djoser',
'testapp',
)
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
DJOSER = {
'DOMAIN': 'frontend.com',
'SITE_NAME': 'Frontend',
'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}',
}
|
import os
DEBUG = True
BASE_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
SECRET_KEY = '_'
MIDDLEWARE_CLASSES = ()
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'rest_framework',
'rest_framework.authtoken',
'djoser',
'testapp',
)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
DJOSER = {
'DOMAIN': 'frontend.com',
'SITE_NAME': 'Frontend',
'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}',
}
|
Remove support for Python 2, bump version to 3.0.0
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='pycron',
version='3.0.0',
description='Simple cron-like parser, which determines if current datetime matches conditions.',
author='Kimmo Huoman',
author_email='kipenroskaposti@gmail.com',
license='MIT',
keywords='cron parser',
url='https://github.com/kipe/pycron',
packages=[
'pycron',
],
python_requires='>=3.4',
tests_require=[
"arrow>=0.12.0",
"coverage>=4.4.2",
"coveralls>=1.2.0",
"Delorean>=0.6.0",
"nose>=1.0",
"pendulum>=1.3.2",
"pytz>=2017.3",
"udatetime>=0.0.14"
]
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='pycron',
version='1.0.0',
description='Simple cron-like parser, which determines if current datetime matches conditions.',
author='Kimmo Huoman',
author_email='kipenroskaposti@gmail.com',
license='MIT',
keywords='cron parser',
url='https://github.com/kipe/pycron',
packages=[
'pycron',
],
setup_requires=['nose>=1.0'],
tests_require=[
"arrow>=0.12.0",
"coverage>=4.4.2",
"coveralls>=1.2.0",
"Delorean>=0.6.0",
"nose>=1.0",
"pendulum>=1.3.2",
"pytz>=2017.3",
"udatetime>=0.0.14"
]
)
|
Set content title for photo uploader.
|
<?php
include_once("../includes/start.php");
$title = 'Photo Uploader';
$tpl->set('title', $title);
$tpl->set('contenttitle',
$title . "<sup style='color: green;'>Beta</sup>");
$tpl->set('js', 'uploader.js');
$tpl->set('previous', false, true);
if (isset($_GET['previous'])) {
$previous = array();
$query = "SELECT `Filename`, `DateUploaded` FROM `photo_processing` ";
$query .= "WHERE `Uploader` = '$username' ORDER BY `DateUploaded` ASC";
$result = do_query($query);
while ($row = fetch_row($result)) {
$previous[] = array("filename" => $row['Filename'], "date" => howLong($row['DateUploaded']));
}
$tpl->set('oldFiles', $previous, true);
$tpl->set('previous', true, true);
} else {
$tpl->set('warning', "This is a friendly reminder: upload <strong>all</strong> of the photos you have (including terrible photos), or Sam will hunt you down and take them from you.<br />Alternatively, just give Sam your memory card and he will copy them over manually.");
}
fetch();
?>
|
<?php
include_once("../includes/start.php");
$title = 'Photo Uploader';
$tpl->set('title', $title);
$tpl->set('js', 'uploader.js');
$tpl->set('previous', false, true);
if (isset($_GET['previous'])) {
$previous = array();
$query = "SELECT `Filename`, `DateUploaded` FROM `photo_processing` ";
$query .= "WHERE `Uploader` = '$username' ORDER BY `DateUploaded` ASC";
$result = do_query($query);
while ($row = fetch_row($result)) {
$previous[] = array("filename" => $row['Filename'], "date" => howLong($row['DateUploaded']));
}
$tpl->set('oldFiles', $previous, true);
$tpl->set('previous', true, true);
} else {
$tpl->set('warning', "This is a friendly reminder: upload <strong>all</strong> of the photos you have (including terrible photos), or Sam will hunt you down and take them from you.<br />Alternatively, just give Sam your memory card and he will copy them over manually.");
}
fetch();
?>
|
Fix failing imports in Python 2
|
from __future__ import absolute_import
import logging
import os
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
from svg.exceptions import SVGNotFound
logger = logging.getLogger(__name__)
register = template.Library()
@register.simple_tag
def svg(filename):
path = finders.find(os.path.join('svg', '%s.svg' % filename), all=True)
if not path:
message = "SVG 'svg/%s.svg' not found" % filename
if settings.DEBUG:
raise SVGNotFound(message)
else:
logger.warning(message)
return ''
if isinstance(path, (list, tuple)):
path = path[0]
with open(path) as svg_file:
svg = mark_safe(svg_file.read())
return svg
|
import logging
import os
from django import template
from django.conf import settings
from django.contrib.staticfiles import finders
from django.utils.safestring import mark_safe
from svg.exceptions import SVGNotFound
logger = logging.getLogger(__name__)
register = template.Library()
@register.simple_tag
def svg(filename):
path = finders.find(os.path.join('svg', '%s.svg' % filename), all=True)
if not path:
message = "SVG 'svg/%s.svg' not found" % filename
if settings.DEBUG:
raise SVGNotFound(message)
else:
logger.warning(message)
return ''
if isinstance(path, (list, tuple)):
path = path[0]
with open(path) as svg_file:
svg = mark_safe(svg_file.read())
return svg
|
Reimplement Blob, switch to sha256
|
import json
import hashlib
from wdim import exceptions
from wdim.client import fields
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self):
return self._id
|
import json
import hashlib
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha1'
@classmethod
def _create(cls, data):
sha = hashlib(cls.HASH_METHOD, json.dumps(data))
return cls(sha, data)
@classmethod
def _from_document(cls, document):
return cls(document['data'])
@property
def hash(self):
return self._id
def __init__(self, data):
self.data = data
def to_document(self):
return {
'_id': self.hash,
'data': self.data
}
|
Set default balance to be 0.0
OPEN - task 79: Create Party Module
http://github.com/DevOpsDistilled/OpERP/issues/issue/79
|
package devopsdistilled.operp.server.data.entity.account;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import devopsdistilled.operp.server.data.entity.Entiti;
@MappedSuperclass
public abstract class Account extends Entiti<Long> {
private static final long serialVersionUID = -8130237994739975187L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long accountId;
private Double balance = 0.0;
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public Long id() {
return getAccountId();
}
@Override
public String toString() {
return new String(getAccountId() + ": " + getBalance().toString());
}
}
|
package devopsdistilled.operp.server.data.entity.account;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import devopsdistilled.operp.server.data.entity.Entiti;
@MappedSuperclass
public abstract class Account extends Entiti<Long> {
private static final long serialVersionUID = -8130237994739975187L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long accountId;
private Double balance;
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public Long id() {
return getAccountId();
}
@Override
public String toString() {
return new String(getAccountId() + ": " + getBalance().toString());
}
}
|
Fix determination of article owner userID for article comment notifications
See #2649
|
<?php
namespace wcf\system\user\notification\object\type;
use wcf\data\comment\Comment;
use wcf\data\comment\CommentList;
use wcf\system\user\notification\object\CommentUserNotificationObject;
use wcf\system\WCF;
/**
* Represents a comment notification object type for comments on articles.
*
* @author Joshua Ruesweg
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\User\Notification\Object\Type
* @since 3.2
*/
class ArticleCommentUserNotificationObjectType extends AbstractUserNotificationObjectType implements ICommentUserNotificationObjectType {
/**
* @inheritDoc
*/
protected static $decoratorClassName = CommentUserNotificationObject::class;
/**
* @inheritDoc
*/
protected static $objectClassName = Comment::class;
/**
* @inheritDoc
*/
protected static $objectListClassName = CommentList::class;
/**
* @inheritDoc
*/
public function getOwnerID($objectID) {
$sql = "SELECT article.userID
FROM wcf".WCF_N."_comment comment
LEFT JOIN wcf".WCF_N."_article article
ON (article.articleID = comment.objectID)
WHERE comment.commentID = ?";
$statement = WCF::getDB()->prepareStatement($sql);
$statement->execute([$objectID]);
return $statement->fetchSingleColumn() ?: 0;
}
}
|
<?php
namespace wcf\system\user\notification\object\type;
use wcf\data\comment\Comment;
use wcf\data\comment\CommentList;
use wcf\system\user\notification\object\CommentUserNotificationObject;
use wcf\system\WCF;
/**
* Represents a comment notification object type for comments on articles.
*
* @author Joshua Ruesweg
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\User\Notification\Object\Type
* @since 3.2
*/
class ArticleCommentUserNotificationObjectType extends AbstractUserNotificationObjectType implements ICommentUserNotificationObjectType {
/**
* @inheritDoc
*/
protected static $decoratorClassName = CommentUserNotificationObject::class;
/**
* @inheritDoc
*/
protected static $objectClassName = Comment::class;
/**
* @inheritDoc
*/
protected static $objectListClassName = CommentList::class;
/**
* @inheritDoc
*/
public function getOwnerID($objectID) {
$sql = "SELECT objectID
FROM wcf".WCF_N."_comment
WHERE commentID = ?";
$statement = WCF::getDB()->prepareStatement($sql);
$statement->execute([$objectID]);
$row = $statement->fetchArray();
return ($row ? $row['objectID'] : 0);
}
}
|
Add test case for iter_source_code
|
import os
import sys
import pytest
from hypothesis_auto import auto_pytest_magic
from isort import main
from isort.settings import DEFAULT_CONFIG
auto_pytest_magic(main.sort_imports)
def test_iter_source_code(tmpdir):
tmp_file = tmpdir.join("file.py")
tmp_file.write("import os, sys\n")
assert tuple(main.iter_source_code((tmp_file,), DEFAULT_CONFIG, [])) == (tmp_file,)
def test_is_python_file():
assert main.is_python_file("file.py")
assert main.is_python_file("file.pyi")
assert main.is_python_file("file.pyx")
assert not main.is_python_file("file.pyc")
assert not main.is_python_file("file.txt")
assert not main.is_python_file("file.pex")
@pytest.mark.skipif(sys.platform == "win32", reason="cannot create fifo file on Windows platform")
def test_is_python_file_fifo(tmpdir):
fifo_file = os.path.join(tmpdir, "fifo_file")
os.mkfifo(fifo_file)
assert not main.is_python_file(fifo_file)
def test_isort_command():
"""Ensure ISortCommand got registered, otherwise setuptools error must have occured"""
assert main.ISortCommand
|
import os
import sys
import pytest
from hypothesis_auto import auto_pytest_magic
from isort import main
auto_pytest_magic(main.sort_imports)
def test_is_python_file():
assert main.is_python_file("file.py")
assert main.is_python_file("file.pyi")
assert main.is_python_file("file.pyx")
assert not main.is_python_file("file.pyc")
assert not main.is_python_file("file.txt")
assert not main.is_python_file("file.pex")
@pytest.mark.skipif(sys.platform == "win32", reason="cannot create fifo file on Windows platform")
def test_is_python_file_fifo(tmpdir):
fifo_file = os.path.join(tmpdir, "fifo_file")
os.mkfifo(fifo_file)
assert not main.is_python_file(fifo_file)
def test_isort_command():
"""Ensure ISortCommand got registered, otherwise setuptools error must have occured"""
assert main.ISortCommand
|
Update binding for lint test
|
<?php
namespace TwigBridge\Tests\Command\Lint;
use TwigBridge\Tests\Base as BridgeBase;
use Mockery as m;
use Symfony\Component\Console\Output\StreamOutput;
use TwigBridge\Command\Lint;
class Base extends BridgeBase
{
protected function getApplication(array $customConfig = [])
{
$app = parent::getApplication($customConfig);
$app['twig.extension'] = 'twig';
$app['twig'] = m::mock('TwigBridge\Bridge');
$finder = m::mock('Illuminate\View\ViewFinderInterface');
$finder->shouldReceive('name');
$finder->shouldReceive('in')->andReturn($finder);
$viewFinder = m::mock('Illuminate\View\ViewFinderInterface');
$viewFinder->shouldReceive('getPaths')->andReturn([]); // paths
$viewFinder->shouldReceive('files')->andReturn($finder);
$app['view'] = m::mock('Illuminate\View\Factory');
$app['view']->shouldReceive('getFinder')->andReturn($viewFinder);
return $app;
}
}
|
<?php
namespace TwigBridge\Tests\Command\Lint;
use TwigBridge\Tests\Base as BridgeBase;
use Mockery as m;
use Symfony\Component\Console\Output\StreamOutput;
use TwigBridge\Command\Lint;
class Base extends BridgeBase
{
protected function getApplication(array $customConfig = [])
{
$app = parent::getApplication($customConfig);
$app['twig.extension'] = 'twig';
$app['twig.bridge'] = m::mock('TwigBridge\Bridge');
$finder = m::mock('Illuminate\View\ViewFinderInterface');
$finder->shouldReceive('name');
$finder->shouldReceive('in')->andReturn($finder);
$viewFinder = m::mock('Illuminate\View\ViewFinderInterface');
$viewFinder->shouldReceive('getPaths')->andReturn([]); // paths
$viewFinder->shouldReceive('files')->andReturn($finder);
$app['view'] = m::mock('Illuminate\View\Factory');
$app['view']->shouldReceive('getFinder')->andReturn($viewFinder);
return $app;
}
}
|
Fix missing page action (popup icon) on page reload
Related to #25.
|
import openDevToolsWindow from './openWindow';
const menus = [
{ id: 'devtools-left', title: 'To left' },
{ id: 'devtools-right', title: 'To right' },
{ id: 'devtools-bottom', title: 'To bottom' },
{ id: 'devtools-panel', title: 'In panel' }
];
let pageUrl;
let pageTab;
let shortcuts = {};
chrome.commands.getAll(commands => {
commands.forEach(({ name, shortcut }) => {
shortcuts[name] = shortcut;
});
});
export default function createMenu(forUrl, tabId) {
if (typeof tabId !== 'number') return; // It is an extension's background page
chrome.pageAction.show(tabId);
if (tabId === pageTab) return;
let url = forUrl;
let hash = forUrl.indexOf('#');
if (hash !== -1) url = forUrl.substr(0, hash);
if (pageUrl === url) return;
pageUrl = url; pageTab = tabId;
chrome.contextMenus.removeAll();
menus.forEach(({ id, title }) => {
chrome.contextMenus.create({
id: id,
title: title + ' (' + shortcuts[id] + ')',
contexts: ['all'],
documentUrlPatterns: [url],
onclick: () => { openDevToolsWindow(id); }
});
});
}
|
import openDevToolsWindow from './openWindow';
const menus = [
{ id: 'devtools-left', title: 'To left' },
{ id: 'devtools-right', title: 'To right' },
{ id: 'devtools-bottom', title: 'To bottom' },
{ id: 'devtools-panel', title: 'In panel' }
];
let pageUrl;
let pageTab;
let shortcuts = {};
chrome.commands.getAll(commands => {
commands.forEach(({ name, shortcut }) => {
shortcuts[name] = shortcut;
});
});
export default function createMenu(forUrl, tabId) {
if (typeof tabId !== 'number' || tabId === pageTab) return;
let url = forUrl;
let hash = forUrl.indexOf('#');
if (hash !== -1) url = forUrl.substr(0, hash);
if (pageUrl === url) return;
pageUrl = url; pageTab = tabId;
chrome.contextMenus.removeAll();
menus.forEach(({ id, title }) => {
chrome.contextMenus.create({
id: id,
title: title + ' (' + shortcuts[id] + ')',
contexts: ['all'],
documentUrlPatterns: [url],
onclick: () => { openDevToolsWindow(id); }
});
});
chrome.pageAction.show(tabId);
}
|
Allow setting schema version to -1.
|
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package org.jsimpledb.cli.cmd;
import java.util.Map;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.parse.ParseException;
import org.jsimpledb.util.ParseContext;
public class SetSchemaVersionCommand extends AbstractCommand {
public SetSchemaVersionCommand() {
super("set-schema-version version:int");
}
@Override
public String getHelpSummary() {
return "Sets the expected schema version";
}
@Override
public String getHelpDetail() {
return "Sets the expected schema version version number. If no such schema version is recorded in the database,"
+ " and `set-allow-new-schema true' has been invoked, then the current schema will be recorded anew under the"
+ " specified version number.";
}
@Override
public CliSession.Action getAction(CliSession session0, ParseContext ctx, boolean complete, Map<String, Object> params) {
final int version = (Integer)params.get("version");
if (version < -1)
throw new ParseException(ctx, "invalid negative schema version");
return session -> {
session.setSchemaVersion(version);
session.getWriter().println("Set schema version to " + version);
};
}
}
|
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package org.jsimpledb.cli.cmd;
import java.util.Map;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.parse.ParseException;
import org.jsimpledb.util.ParseContext;
public class SetSchemaVersionCommand extends AbstractCommand {
public SetSchemaVersionCommand() {
super("set-schema-version version:int");
}
@Override
public String getHelpSummary() {
return "Sets the expected schema version";
}
@Override
public String getHelpDetail() {
return "Sets the expected schema version version number. If no such schema version is recorded in the database,"
+ " and `set-allow-new-schema true' has been invoked, then the current schema will be recorded anew under the"
+ " specified version number.";
}
@Override
public CliSession.Action getAction(CliSession session0, ParseContext ctx, boolean complete, Map<String, Object> params) {
final int version = (Integer)params.get("version");
if (version < 0)
throw new ParseException(ctx, "invalid negative schema version");
return session -> {
session.setSchemaVersion(version);
session.getWriter().println("Set schema version to " + version);
};
}
}
|
Make `injectBabelPlugin` compatible with older webpack versions
Specifically, this is needed for people using React StoryBook.
|
const path = require('path');
const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf(`babel-loader${path.sep}`) != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
// Older versions of webpack have `plugins` on `loader.query` instead of `loader.options`.
const options = loader.options || loader.query;
options.plugins = [pluginName].concat(options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
|
const path = require('path');
const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf(`babel-loader${path.sep}`) != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
|
Use the JsonMixin for the names model.
|
from flask import url_for
from standard_names import StandardName
from ..core import db, JsonMixin
class NameJsonSerializer(JsonMixin):
__public_fields__ = set(['href', 'id', 'name', 'object', 'quantity',
'operators'])
class Name(NameJsonSerializer, db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
@property
def href(self):
return url_for('names.name', id=self.id)
@property
def object(self):
return StandardName(self.name).object
@property
def quantity(self):
return StandardName(self.name).quantity
@property
def operators(self):
return StandardName(self.name).operators
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
|
#from flask_security import UserMixin, RoleMixin
from standard_names import StandardName
from ..core import db
class Name(db.Model):
__tablename__ = 'names'
__bind_key__ = 'names'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
def to_resource(self, brief=False):
if brief:
return {'id': self.id, 'name': self.name}
else:
sn = StandardName(self.name)
return {
'id': self.id,
'href': '/api/names/%d' % self.id,
'name': self.name,
'object': sn.object,
'quantity': sn.quantity,
'operators': sn.operators,
}
|
Attach GitHubPolyglot to root and remove this.init()
|
// This file generates the client script
// Dependencies
var Fs = require("fs")
, GitHubColors = require("github-colors")
, UglifyJS = require("uglify-js")
;
const TEMPLATE = "(function (root) {\n"
+ " var GitHubColors = __GITHUB_COLORS__;\n"
+ " __GITHUB_POLYGLOT__\n"
+ "})(window);";
// Configurations
GitHubColors.init();
var ghPolyglot = Fs.readFileSync(__dirname + "/../lib/index.js", "utf-8")
, lines = ghPolyglot.split("\n")
, replace = {
__GITHUB_POLYGLOT__: lines.slice(lines.indexOf("/**")).join("\n")
, __GITHUB_COLORS__: "{ get: " + GitHubColors.get.toString() + ",\n"
+ "colors: " + JSON.stringify(GitHubColors.colors) + "}"
}
, client = TEMPLATE
;
Object.keys(replace).forEach(function (c) {
client = client.replace(new RegExp(c), replace[c]);
});
client = client.replace("module.exports = ", "root.GitHubPolyglot = ");
client = client.replace("this.init();", "");
Fs.writeFileSync(__dirname + "/../dist/gh-polyglot.js", client);
Fs.writeFileSync(__dirname + "/../dist/gh-polyglot.min.js", UglifyJS.minify(client, { fromString: true }).code);
|
// This file generates the client script
// Dependencies
var Fs = require("fs")
, GitHubColors = require("github-colors")
, UglifyJS = require("uglify-js")
;
const TEMPLATE = "(function (root) {\n"
+ " var GitHubColors = __GITHUB_COLORS__;\n"
+ " __GITHUB_POLYGLOT__\n"
+ "})(window);";
// Configurations
GitHubColors.init();
var ghPolyglot = Fs.readFileSync(__dirname + "/../lib/index.js", "utf-8")
, lines = ghPolyglot.split("\n")
, replace = {
__GITHUB_POLYGLOT__: lines.slice(lines.indexOf("/**")).join("\n")
, __GITHUB_COLORS__: "{ get: " + GitHubColors.get.toString() + ",\n"
+ "colors: " + JSON.stringify(GitHubColors.colors) + "}"
}
, client = TEMPLATE
;
Object.keys(replace).forEach(function (c) {
client = client.replace(new RegExp(c), replace[c]);
});
Fs.writeFileSync(__dirname + "/../dist/gh-polyglot.js", client);
Fs.writeFileSync(__dirname + "/../dist/gh-polyglot.min.js", UglifyJS.minify(client, { fromString: true }).code);
|
Allow any king of geometry to data observatory analysis
|
'use strict';
var dot = require('dot');
dot.templateSettings.strip = false;
var Node = require('../node');
var TYPE = 'data-observatory-measure';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.ANY),
final_column: Node.PARAM.STRING,
segment_name: Node.PARAM.STRING,
percent: Node.PARAM.NULLABLE(Node.PARAM.BOOLEAN),
};
var DataObservatoryMeasure = Node.create(TYPE, PARAMS, { cache: true });
module.exports = DataObservatoryMeasure;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
DataObservatoryMeasure.prototype.sql = function() {
return query({
columns: this.source.getColumns().join(', '),
source: this.source.getQuery(),
final_column: this.final_column,
segment_name: this.segment_name,
percent: this.percent ? 'denominator' : undefined
});
};
var queryTemplate = dot.template([
'SELECT',
' {{=it.columns}},',
' OBS_GetMeasure(' +
' the_geom,' +
' \'{{=it.segment_name}}\'{{?it.percent}},',
' \'{{=it.percent}}\'{{?}}',
' ) AS {{=it.final_column}}',
'FROM ({{=it.source}}) AS _camshaft_do_measure_analysis'
].join('\n'));
function query(it) {
return queryTemplate(it);
}
|
'use strict';
var dot = require('dot');
dot.templateSettings.strip = false;
var Node = require('../node');
var TYPE = 'data-observatory-measure';
var PARAMS = {
source: Node.PARAM.NODE(Node.GEOMETRY.POLYGON),
final_column: Node.PARAM.STRING,
segment_name: Node.PARAM.STRING,
percent: Node.PARAM.NULLABLE(Node.PARAM.BOOLEAN),
};
var DataObservatoryMeasure = Node.create(TYPE, PARAMS, { cache: true });
module.exports = DataObservatoryMeasure;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
DataObservatoryMeasure.prototype.sql = function() {
return query({
columns: this.source.getColumns().join(', '),
source: this.source.getQuery(),
final_column: this.final_column,
segment_name: this.segment_name,
percent: this.percent ? 'denominator' : undefined
});
};
var queryTemplate = dot.template([
'SELECT',
' {{=it.columns}},',
' OBS_GetMeasure(' +
' the_geom,' +
' \'{{=it.segment_name}}\'{{?it.percent}},',
' \'{{=it.percent}}\'{{?}}',
' ) AS {{=it.final_column}}',
'FROM ({{=it.source}}) AS _camshaft_do_measure_analysis'
].join('\n'));
function query(it) {
return queryTemplate(it);
}
|
Remove mention of user data in bt test
|
var bt = require('../src/bluetooth').Bluetooth;
var remote_addr = "<BT device address";
function findDevice(item) {
return item.address == remote_addr;
}
bt.on('started', function() {
console.log('onstarted');
bt.start_scan();
});
bt.on('scan', function(device) {
console.log('onscan: '+ device);
var device = JSON.parse(device).find(findDevice);
if (device) {
console.log('Bonding to ' + remote_addr);
bt.stop_scan();
bt.start_bond(device.address);
}
});
bt.on('bond', function(paired) {
console.log('bonded: '+ paired);
bt.connect(remote_addr);
});
bt.on('connect', function(connected) {
console.log('connected: '+ connected);
});
process.on('SIGINT', function () {
bt.stop_scan();
process.exit(0);
});
|
var bt = require('../src/bluetooth').Bluetooth;
var remote_addr = "A4:E4:B8:6C:38:B9";
function findDevice(item) {
return item.address == remote_addr;
}
bt.on('started', function() {
console.log('onstarted');
bt.start_scan();
});
bt.on('scan', function(device) {
console.log('onscan: '+ device);
var device = JSON.parse(device).find(findDevice);
if (device) {
console.log('Bonding to ' + remote_addr);
bt.stop_scan();
bt.start_bond(device.address);
}
});
bt.on('bond', function(paired) {
console.log('bonded: '+ paired);
bt.connect(remote_addr);
});
bt.on('connect', function(connected) {
console.log('connected: '+ connected);
});
process.on('SIGINT', function () {
bt.stop_scan();
process.exit(0);
});
|
Add homebrew redux middleware to catch all errors..
|
import {createStore, applyMiddleware, compose} from 'redux'
import {electronEnhancer} from 'redux-electron-enhancer'
import createLogger from 'redux-cli-logger'
import createSagaMiddleware from 'redux-saga'
import sagas from '../sagas'
import reducer from '../reducers'
import env from '../env'
const crashGetter = (store) => (next) => (action) => {
try {
if (action && !action.type) {
throw new Error(`refusing to dispatch action with null type: `, action)
}
return next(action)
} catch (e) {
console.log(`Uncaught redux: ${e.stack}`)
}
}
const middleware = [
crashGetter,
createSagaMiddleware(...sagas)
]
const beChatty = process.env.MARCO_POLO === '1'
const devMiddleware = []
if (env.name === 'development' && beChatty) {
const logger = createLogger({
predicate: (getState, action) => !action.MONITOR_ACTION && !/^WINDOW_/.test(action.type),
stateTransformer: (state) => ''
})
devMiddleware.push(logger)
}
const inject = (action) => store.dispatch(action)
const enhancer = compose(
applyMiddleware(...middleware),
electronEnhancer({inject}),
applyMiddleware(...devMiddleware)
)
const initialState = {}
const store = createStore(reducer, initialState, enhancer)
export default store
|
import {createStore, applyMiddleware, compose} from 'redux'
import {electronEnhancer} from 'redux-electron-enhancer'
import createLogger from 'redux-cli-logger'
import createSagaMiddleware from 'redux-saga'
import sagas from '../sagas'
import reducer from '../reducers'
import env from '../env'
const middleware = [
createSagaMiddleware(...sagas)
]
const beChatty = process.env.MARCO_POLO === '1'
const devMiddleware = []
if (env.name === 'development' && beChatty) {
const logger = createLogger({
predicate: (getState, action) => !action.MONITOR_ACTION && !/^WINDOW_/.test(action.type),
stateTransformer: (state) => ''
})
devMiddleware.push(logger)
}
const inject = (action) => store.dispatch(action)
const enhancer = compose(
applyMiddleware(...middleware),
electronEnhancer({inject}),
applyMiddleware(...devMiddleware)
)
const initialState = {}
const store = createStore(reducer, initialState, enhancer)
export default store
|
Increase the timeout for connecting to html5test.com
|
<?php
namespace HTML5test\Automate;
use GuzzleHttp\Client;
class HTML5test {
public function __construct($config) {
$this->config = $config;
$this->client = new Client([
'base_uri' => $this->config['endpoint'],
'timeout' => 20.0
]);
}
public function getIdentifiers($source) {
$response = $this->client->get('getIdentifiers', [
'query' => [ 'source' => $source ]
]);
return json_decode((string) $response->getBody());
}
public function getTask($source, $identifier) {
$response = $this->client->get('getTask', [
'query' => [ 'source' => $source, 'identifier' => $identifier ]
]);
return json_decode((string) $response->getBody());
}
public function hasTask($task) {
$response = $this->client->get('hasTask', [
'query' => [ 'task' => $task ]
]);
return json_decode((string) $response->getBody());
}
}
|
<?php
namespace HTML5test\Automate;
use GuzzleHttp\Client;
class HTML5test {
public function __construct($config) {
$this->config = $config;
$this->client = new Client([
'base_uri' => $this->config['endpoint'],
'timeout' => 5.0
]);
}
public function getIdentifiers($source) {
$response = $this->client->get('getIdentifiers', [
'query' => [ 'source' => $source ]
]);
return json_decode((string) $response->getBody());
}
public function getTask($source, $identifier) {
$response = $this->client->get('getTask', [
'query' => [ 'source' => $source, 'identifier' => $identifier ]
]);
return json_decode((string) $response->getBody());
}
public function hasTask($task) {
$response = $this->client->get('hasTask', [
'query' => [ 'task' => $task ]
]);
return json_decode((string) $response->getBody());
}
}
|
Make waiting message more precise
|
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/../vendor/autoload.php';
$connected = false;
while (!$connected) {
try {
$app = \eCampApp::CreateSetup();
$sm = $app->getServiceManager();
/** @var \Doctrine\ORM\EntityManager $em */
$em = $sm->get('doctrine.entitymanager.orm_default');
$conn = $em->getConnection();
$conn->connect();
$connected = true;
echo "DB is online\n";
$conn->close();
} catch (\Exception $e) {
echo "Could not yet connect to DB...\n";
echo $e->getMessage();
echo "\n";
sleep(5);
}
}
|
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/../vendor/autoload.php';
$connected = false;
while (!$connected) {
try {
$app = \eCampApp::CreateSetup();
$sm = $app->getServiceManager();
/** @var \Doctrine\ORM\EntityManager $em */
$em = $sm->get('doctrine.entitymanager.orm_default');
$conn = $em->getConnection();
$conn->connect();
$connected = true;
echo "DB is online\n";
$conn->close();
} catch (\Exception $e) {
echo "Waiting for DB to come online...\n";
echo $e->getMessage();
echo "\n";
sleep(5);
}
}
|
Load statics like posts and pages. Documentation.
|
#!/usr/bin/python3
import argparse, sys
from src import Configurator, Builder, Loader
def main():
""" Parse command line arguments and execute passed subcommands. """
# Parse subcommand
parser = argparse.ArgumentParser(description='Pythonic static sites generator')
subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed")
parser_build = subparsers.add_parser('build', help="Build static site from local directory")
args = parser.parse_args()
# Execute passed sub-command or return error
if(args.sp == "build"):
build(args)
def build(args):
""" Build website to configured location. """
# Parse configuration
config = {}
config["site"] = Configurator.getConfig()
# Load articles, pages and static elements from the files
config["posts"] = Loader.getFromFolder("posts/", args)
config["pages"] = Loader.getFromFolder("pages/", args)
config["statics"] = Loader.getFromFolder("themes/" + config["site"]["theme"] + "/statics/", args)
# Configure Jinja2 environment
jinjaEnv = Configurator.configureJinja(config["site"])
print(config)
# Build statics
Builder.buildStatics(config)
# Build posts and pages
Builder.buildPosts(config, jinjaEnv)
Builder.buildPages(config, jinjaEnv)
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
import argparse, sys
from src import Configurator, Builder, Loader
def main():
""" Parse command line arguments and execute passed subcommands. """
# Parse subcommand
parser = argparse.ArgumentParser(description='Pythonic static sites generator')
subparsers = parser.add_subparsers(dest="sp", help="sub-command to be executed")
parser_build = subparsers.add_parser('build', help="Build static site from local directory")
args = parser.parse_args()
# Execute passed sub-command or return error
if(args.sp == "build"):
build(args)
def build(args):
""" Build website to configured location. """
# Parse configuration and define Environment
config = {}
config["site"] = Configurator.getConfig()
config["posts"] = Loader.getFromFolder("posts/", args)
config["pages"] = Loader.getFromFolder("pages/", args)
jinjaEnv = Configurator.configureJinja(config["site"])
print(config)
# Build statics
Builder.buildStatics(config)
# Build posts and pages
Builder.buildPosts(config, jinjaEnv)
# Build page and pages
#Builder.buildPages(config, jinjaEnv)
if __name__ == "__main__":
main()
|
Set response content type of a json response to application/json
|
import os
import json
from flask import Flask
from flask import make_response
from flask import request
from flask import json
import services
app = Flask(__name__)
digitransitAPIService = services.DigitransitAPIService()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/test')
def digitransit_test():
return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573))
@app.route('/stops', methods=['GET'])
def stops():
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
resp = make_response(json.dumps(result))
resp.mimetype = 'application/json'
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
|
import os
import json
from flask import Flask
from flask import request
from flask import json
import services
app = Flask(__name__)
digitransitAPIService = services.DigitransitAPIService()
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/test')
def digitransit_test():
return json.dumps(digitransitAPIService.get_stops(60.203978, 24.9633573))
@app.route('/stops', methods=['GET'])
def stops():
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
result = digitransitAPIService.get_stops(lat, lon)
print(result)
return json.dumps(result)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.getenv('PORT', '5000'))
|
Throw exception if no login credentials are provided
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from helpers.driver import HamperDriver
from helpers.error import HamperError
from termcolor import colored
class HamperAuthenticator(object):
def __init__(self):
super(HamperAuthenticator, self).__init__()
def sign_in(self, email=None, password=None):
print colored("Authenticating user...", "blue")
# If no login credentials were provided
if not email or not password:
raise Exception(HamperError(HamperError.HECodeLogInError, "Either the email and/or password wasn't provided. Call 'hamper auth login' with the login credentials."))
# Grab the HamperDriver singleton
driver = HamperDriver()
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(password)
driver.find_element_by_id("submitButton2").click()
if len(driver.find_elements_by_class_name("dserror")) > 0:
raise Exception(HamperError(HamperError.HECodeLogInError, driver.find_element_by_class_name("dserror").get_attribute("innerHTML")))
|
#
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from helpers.driver import HamperDriver
from helpers.error import HamperError
from termcolor import colored
class HamperAuthenticator(object):
def __init__(self):
super(HamperAuthenticator, self).__init__()
def sign_in(self, email=None, password=None):
# Grab the HamperDriver singleton
driver = HamperDriver()
print colored("Authenticating user...", "blue")
# Open the profile URL. This will forward to the sign in page if session is invalid
driver.get("https://developer.apple.com/account/ios/profile/")
email_element = driver.find_element_by_name("appleId")
email_element.send_keys(email)
password_element = driver.find_element_by_name("accountPassword")
password_element.send_keys(password)
driver.find_element_by_id("submitButton2").click()
if len(driver.find_elements_by_class_name("dserror")) > 0:
raise Exception(HamperError(HamperError.HECodeLogInError, driver.find_element_by_class_name("dserror").get_attribute("innerHTML")))
|
Convert exceptions in a type-safe manner to string before string cats
|
"""This module is about testing the logger."""
import sys
from unittest import TestCase
LOGGER = sys.modules["Rainmeter.logger"]
class TestFunctions(TestCase):
"""Test class wrapper using unittest."""
# pylint: disable=W0703; This is acceptable since we are testing it not failing
def test_info(self):
"""Info should not through exceptions due to settings."""
try:
LOGGER.info("info test")
except Exception as error:
self.fail("logger.info() raised exception '" + str(error) + "'")
def test_error(self):
"""Error should not through exception due to settings."""
try:
LOGGER.error("error test")
except Exception as error:
self.fail("logger.error() raised exception '" + str(error) + "'")
|
"""This module is about testing the logger."""
import sys
from unittest import TestCase
LOGGER = sys.modules["Rainmeter.logger"]
class TestFunctions(TestCase):
"""Test class wrapper using unittest."""
# pylint: disable=W0703; This is acceptable since we are testing it not failing
def test_info(self):
"""Info should not through exceptions due to settings."""
try:
LOGGER.info("info test")
except Exception as error:
self.fail("logger.info() raised exception '" + error + "'")
def test_error(self):
"""Error should not through exception due to settings."""
try:
LOGGER.error("error test")
except Exception as error:
self.fail("logger.error() raised exception '" + error + "'")
|
Improve the code, return most collisions. Work on hex strings.
|
from matasano.util.converters import hex_to_bytestr
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
coll_count = {}
for idx, line in enumerate(chal_file):
count = 0
ct = line[:-1]
for i in range(0, len(ct), 32):
for j in range(i+32, len(ct), 32):
if ct[i:i+32] == ct[j:j+32]:
print("Block collision found in ciphertext: {} Block {} == Block {}".format(idx, i//16, j//16))
count += 1
coll_count[idx] = count
most_coll = max(coll_count, key=coll_count.get)
print("Ciphertext {} had the most collisions with {}".format(most_coll, coll_count[most_coll]))
|
from matasano.util.converters import hex_to_bytestr
from Crypto.Cipher import AES
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
for line in chal_file:
ct = hex_to_bytestr(line[:-1])
for i in range(0, len(ct), 16):
for j in range(i+16, len(ct), 16):
if ct[i:i+16] == ct[j:j+16]:
print("Block collision found in ciphertext: {} Block {} == Block {}".format(line, i//16, j//16))
break
else:
continue
break
else:
continue
break
|
Allow user to be retrieved from JWT with passport (req.user)
|
var passport = require('passport');
var passportJWT = require('passport-jwt');
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;
var jwtSecret = require('./localvars.js').jwtSecret;
var User = require('../../db/models/User');
// passport-jwt config
var cfg = {
jwtSecret: jwtSecret,
jwtSession: { session: false }
};
var params = {
secretOrKey: jwtSecret,
jwtFromRequest: ExtractJwt.fromAuthHeader()
};
var strategy = new Strategy(params, function(payload, done) {
User.query().where('id', payload.id)
.then(function(user) {
var user = user[0];
if (!user) {
done(null, false);
} else {
done(null, user);
}
})
.catch(function(err) {
done(err, false);
});
});
passport.use(strategy);
exports.initialize = function() {
return passport.initialize();
};
exports.authenticate = function() {
return passport.authenticate('jwt', cfg.jwtSession);
};
exports.cfg = cfg;
|
var passport = require('passport');
var passportJWT = require('passport-jwt');
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;
var jwtSecret = require('./localvars.js').jwtSecret;
// passport-jwt config
var cfg = {
jwtSecret: jwtSecret,
jwtSession: { session: false }
};
var params = {
secretOrKey: jwtSecret,
jwtFromRequest: ExtractJwt.fromAuthHeader()
};
var strategy = new Strategy(params, function(payload, done) {
var user = users[payload.id] || null;
if (user) {
return done(null, {
id: user.id
});
} else {
return done(new Error('User not found'), null);
}
});
passport.use(strategy);
exports.initialize = function() {
return passport.initialize();
};
exports.authenticate = function() {
return passport.authenticate('jwt', cfg.jwtSession);
};
exports.cfg = cfg;
|
Add todo for integrating shariff.
|
export default class Home {
render() {
return (
<footer className="pure-u-2-3 center">
<ul>
<li>
<div className="shariff" data-theme="grey"
data-services="["twitter","googleplus","facebook","mail","info"]"></div>
RENDER WITH SHARIFF!!!!
</li>
<li>
<a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/de/" target="_blank"><img
title="CC-BY-SA" src="http://cosmowiki.de/img/cc-by-sa-88x31.png" alt="CC-By-SA"/></a>
</li>
<li>
<small>v. 0.9 beta</small>
</li>
</ul>
</footer>
)
}
}
|
export default class Home {
render() {
return (
<footer className="pure-u-2-3 center">
<ul>
<li>
<div className="shariff" data-theme="grey"
data-services="["twitter","googleplus","facebook","mail","info"]"></div>
</li>
<li>
<a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/de/" target="_blank"><img
title="CC-BY-SA" src="http://cosmowiki.de/img/cc-by-sa-88x31.png" alt="CC-By-SA"/></a>
</li>
<li>
<small>v. 0.9 beta</small>
</li>
</ul>
</footer>
)
}
}
|
Update deps to use new UI helpers
|
Package.describe({
"summary": "Add feature flagging to Meteor"
});
Package.on_use(function (api) {
api.use('coffeescript', ['server', 'client']);
api.use(['deps','ui','templating', 'jquery'], 'client');
api.use('underscore', 'server');
api.use('accounts-base', ['client'])
api.add_files('server/server_flag.coffee', 'server')
api.add_files('client/client_flag.coffee', 'client')
if (typeof api.export !== 'undefined'){
api.export('FeatureFlag', 'server');
}
});
Package.on_test(function(api) {
api.use('coffeescript', ['server', 'client']);
api.use(['meteor-feature-flag',"tinytest", "test-helpers"])
api.use('underscore', 'server');
api.add_files('test/feature_flag.coffee', 'server')
});
|
Package.describe({
"summary": "Add feature flagging to Meteor"
});
Package.on_use(function (api) {
api.use('coffeescript', ['server', 'client']);
api.use(['deps','handlebars','jquery'], 'client');
api.use('underscore', 'server');
api.use('accounts-base', ['client'])
api.add_files('server/server_flag.coffee', 'server')
api.add_files('client/client_flag.coffee', 'client')
if (typeof api.export !== 'undefined'){
api.export('FeatureFlag', 'server');
}
});
Package.on_test(function(api) {
api.use('coffeescript', ['server', 'client']);
api.use(['meteor-feature-flag',"tinytest", "test-helpers"])
api.use('underscore', 'server');
api.add_files('test/feature_flag.coffee', 'server')
});
|
Clear the transaction after committing it
|
<?php
namespace PhpInPractice\Matters\Aggregate\Transaction;
use EventStore\EventStoreInterface;
use EventStore\WritableEvent;
use EventStore\WritableEventCollection;
use PhpInPractice\Matters\Aggregate\Transaction as TransactionInterface;
class SingleStream implements TransactionInterface
{
/** @var EventStoreInterface */
private $eventstore;
/** @var string */
private $streamUri = '';
/** @var WritableEvent[] */
private $events = [];
public function __construct(EventStoreInterface $eventstore)
{
$this->eventstore = $eventstore;
$this->resetTransaction();
}
public function push($streamUri, array $writeableEvents)
{
if ($this->streamUri && $streamUri !== $this->streamUri) {
throw new TransactionLimitedToASingleStreamException();
}
$this->streamUri = $streamUri;
$this->events = array_merge($this->events, $writeableEvents);
}
public function commit()
{
$collection = new WritableEventCollection($this->events);
$this->eventstore->writeToStream($this->streamUri, $collection);
$this->resetTransaction();
}
private function resetTransaction()
{
$this->streamUri = '';
$this->events = [];
}
}
|
<?php
namespace PhpInPractice\Matters\Aggregate\Transaction;
use EventStore\EventStoreInterface;
use EventStore\WritableEvent;
use EventStore\WritableEventCollection;
use PhpInPractice\Matters\Aggregate\Transaction as TransactionInterface;
class SingleStream implements TransactionInterface
{
/**
* @var EventStoreInterface
*/
private $eventstore;
/** @var string */
private $streamUri = '';
/** @var WritableEvent[] */
private $events = [];
public function __construct(EventStoreInterface $eventstore)
{
$this->eventstore = $eventstore;
}
public function push($streamUri, array $writeableEvents)
{
if ($this->streamUri && $streamUri !== $this->streamUri) {
throw new TransactionLimitedToASingleStreamException();
}
$this->streamUri = $streamUri;
$this->events = array_merge($this->events, $writeableEvents);
}
public function commit()
{
$collection = new WritableEventCollection($this->events);
$this->eventstore->writeToStream($this->streamUri, $collection);
}
}
|
fix(not-found-component): Make menu available in not-found routes
Move NotFound component back into App children
|
import React from 'react';
import {render} from 'react-dom';
import { Router, Route, applyRouterMiddleware} from 'react-router';
let history;
if(typeof process !== "undefined" && process.env.NODE_ENV === "production") {
history = require('react-router/lib/hashHistory');
} else {
history = require('react-router/lib/browserHistory');
}
// console.log(typeof process !== "undefined" && process.env.NODE_ENV);
import App from './components/App';
import NotFound from './components/NotFound';
import Footer from './components/Footer';
// TODO maybe change browserHistory to hashHitory when deploying
import useScroll from 'react-router-scroll/lib/useScroll';
import routes from './helpers/routemap';
render((
<Router history={history} render={applyRouterMiddleware(useScroll())}>
<Route path="/" component={App}>
{routes}
<Route path="*" component={NotFound}/>
</Route>
</Router>
),
document.getElementById("app"));
render(<Footer history= {history}/>, document.getElementById("footer-mount"));
|
import React from 'react';
import {render} from 'react-dom';
import { Router, Route, applyRouterMiddleware} from 'react-router';
let history;
if(typeof process !== "undefined" && process.env.NODE_ENV === "production") {
history = require('react-router/lib/hashHistory');
} else {
history = require('react-router/lib/browserHistory');
}
// console.log(typeof process !== "undefined" && process.env.NODE_ENV);
import App from './components/App';
import NotFound from './components/NotFound';
import Footer from './components/Footer';
// TODO maybe change browserHistory to hashHitory when deploying
import useScroll from 'react-router-scroll/lib/useScroll';
import routes from './helpers/routemap';
render((
<Router history={history} render={applyRouterMiddleware(useScroll())}>
<Route path="/" component={App} children={routes}/>
<Route path="*" component={NotFound}/>
</Router>
),
document.getElementById("app"));
render(<Footer history= {history}/>, document.getElementById("footer-mount"));
|
SDC-6927: Add additional data formats to DataParser processor
Added all data formats that seems "plausible" for a processor. E.g.
all of them except of:
* SDC_JSON
* BINARY
* TEXT
* DATAGRAM
* WHOLE_FILE
Change-Id: Ibbc048f7171d34141715a84e29300b0d2fa364ff
Reviewed-on: https://review.streamsets.net/9604
Tested-by: StreamSets CI <809627f37325a679986bd660c7713476a56d59cd@streamsets.com>
Reviewed-by: Jeff Evans <f3e731dfa293c7a83119d8aacfa41b5d2d780be9@streamsets.com>
|
/**
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.processor.parser;
import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
import com.streamsets.pipeline.config.DataFormat;
public class DataFormatChooserValues extends BaseEnumChooserValues<DataFormat> {
public DataFormatChooserValues() {
super(
DataFormat.AVRO,
DataFormat.DELIMITED,
DataFormat.JSON,
DataFormat.LOG,
DataFormat.NETFLOW,
DataFormat.PROTOBUF,
DataFormat.SYSLOG,
DataFormat.XML
);
}
}
|
/**
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.processor.parser;
import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
import com.streamsets.pipeline.config.DataFormat;
public class DataFormatChooserValues extends BaseEnumChooserValues<DataFormat> {
public DataFormatChooserValues() {
super(
DataFormat.SYSLOG,
DataFormat.NETFLOW
);
}
}
|
Fix calendarId not being returned in response
|
package com.google.step.coffee.data;
import com.google.appengine.api.datastore.*;
import com.google.step.coffee.entity.Event;
public class EventStore {
private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
/**
* Saves the event to the database. Returns an <code>Event</code>
* that has its id set, which the group passed to the function might not.
*/
public Event put(Event event) {
Key key = event.key();
Entity entity = key != null ? new Entity(key) : new Entity("event");
entity.setProperty("description", new Text(event.description()));
entity.setProperty("start", event.start().getEpochSecond());
entity.setProperty("duration", event.duration().toMinutes());
entity.setProperty("group", KeyFactory.stringToKey(event.groupId()));
entity.setProperty("calendarId", event.calendarId());
datastore.put(entity);
return event.modify()
.setId(KeyFactory.keyToString(entity.getKey()))
.build();
}
}
|
package com.google.step.coffee.data;
import com.google.appengine.api.datastore.*;
import com.google.step.coffee.entity.Event;
public class EventStore {
private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
/**
* Saves the event to the database. Returns an <code>Event</code>
* that has its id set, which the group passed to the function might not.
*/
public Event put(Event event) {
Key key = event.key();
Entity entity = key != null ? new Entity(key) : new Entity("event");
entity.setProperty("description", new Text(event.description()));
entity.setProperty("start", event.start().getEpochSecond());
entity.setProperty("duration", event.duration().toMinutes());
entity.setProperty("group", KeyFactory.stringToKey(event.groupId()));
entity.setProperty("calendarId", event.calendarId());
datastore.put(entity);
return Event.fromEntity(entity);
}
}
|
Add plain Python 2 and 3 to package metadata
|
import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.5',
description='Factories for Django, creating valid instances every time',
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
install_requires=[
'Django>=1.8',
'factory_boy>=2.7',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
import os
import setuptools
setuptools.setup(
name='factory_djoy',
version='0.5',
description='Factories for Django, creating valid instances every time',
url='http://github.com/jamescooke/factory_djoy',
author='James Cooke',
author_email='github@jamescooke.info',
license='MIT',
packages=setuptools.find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
install_requires=[
'Django>=1.8',
'factory_boy>=2.7',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Use Heroku instance of webapp if not in DEBUG mode.
|
import logging
import logging.handlers
DEBUG = True
LOG_FORMAT = '[%(asctime)s: %(levelname)s] %(message)s'
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.WARN
LOG_COLOR = True
PORT = 8000
TORNADO_SETTINGS = {}
TORNADO_SETTINGS['debug'] = DEBUG
TORNADO_SETTINGS['xsrf_cookies'] = False
TORNADO_SETTINGS['port'] = PORT
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.INFO
USE_SYSLOG = False
LOGGING_CONFIG = 'astral.conf.logconfig.initialize_logging'
LOGGING = {
'loggers': {
'astral': {},
},
'syslog_facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
'syslog_tag': "astral",
'log_level': LOG_LEVEL,
'use_syslog': USE_SYSLOG,
}
if DEBUG:
ASTRAL_WEBSERVER = "http://localhost:4567"
else:
ASTRAL_WEBSERVER = "http://astral-video.heroku.com"
BOOTSTRAP_NODES = [
]
DOWNSTREAM_CHECK_LIMIT = 1024 * 1024 * 2
UPSTREAM_CHECK_LIMIT = 1024 * 256
OUTGOING_STREAM_LIMIT = 2
|
import logging
import logging.handlers
DEBUG = True
LOG_FORMAT = '[%(asctime)s: %(levelname)s] %(message)s'
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.WARN
LOG_COLOR = True
PORT = 8000
TORNADO_SETTINGS = {}
TORNADO_SETTINGS['debug'] = DEBUG
TORNADO_SETTINGS['xsrf_cookies'] = False
TORNADO_SETTINGS['port'] = PORT
if DEBUG:
LOG_LEVEL = logging.DEBUG
else:
LOG_LEVEL = logging.INFO
USE_SYSLOG = False
LOGGING_CONFIG = 'astral.conf.logconfig.initialize_logging'
LOGGING = {
'loggers': {
'astral': {},
},
'syslog_facility': logging.handlers.SysLogHandler.LOG_LOCAL0,
'syslog_tag': "astral",
'log_level': LOG_LEVEL,
'use_syslog': USE_SYSLOG,
}
ASTRAL_WEBSERVER = "http://localhost:4567"
BOOTSTRAP_NODES = [
]
DOWNSTREAM_CHECK_LIMIT = 1024 * 1024 * 2
UPSTREAM_CHECK_LIMIT = 1024 * 256
OUTGOING_STREAM_LIMIT = 2
|
Add a todo item to run()
|
import argparse
import importlib
import logging
import os
logger = logging.getLogger(__name__)
description = "An automated grading tool for programming assignments."
subcommands = {
"init": "grader.init",
"new": "grader.new",
"image": "grader.image",
"grade": "grader.grade"
}
def run():
"""Script entry point
.. todo::
Add a "verbose" flag
"""
# Configure logging
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--path', default=os.getcwd(),
help='Path to the root of a grader')
# If no arguments are provided, show the usage screen
parser.set_defaults(run=lambda x: parser.print_usage())
# Set up subcommands for each package
subparsers = parser.add_subparsers(title="subcommands")
for name, path in subcommands.items():
module = importlib.import_module(path)
subparser = subparsers.add_parser(name, help=module.help)
module.setup_parser(subparser)
# The 'help' command shows the help screen
help_parser = subparsers.add_parser("help", help="Show this help screen")
help_parser.set_defaults(run=lambda x: parser.print_help())
# Parse CLI args
args = parser.parse_args()
# Do it
args.run(args)
if __name__ == '__main__':
run()
|
import argparse
import importlib
import logging
import os
logger = logging.getLogger(__name__)
description = "An automated grading tool for programming assignments."
subcommands = {
"init": "grader.init",
"new": "grader.new",
"image": "grader.image",
"grade": "grader.grade"
}
def run():
# Configure logging
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--path', default=os.getcwd(),
help='Path to the root of a grader')
# If no arguments are provided, show the usage screen
parser.set_defaults(run=lambda x: parser.print_usage())
# Set up subcommands for each package
subparsers = parser.add_subparsers(title="subcommands")
for name, path in subcommands.items():
module = importlib.import_module(path)
subparser = subparsers.add_parser(name, help=module.help)
module.setup_parser(subparser)
# The 'help' command shows the help screen
help_parser = subparsers.add_parser("help", help="Show this help screen")
help_parser.set_defaults(run=lambda x: parser.print_help())
# Parse CLI args
args = parser.parse_args()
# Do it
args.run(args)
if __name__ == '__main__':
run()
|
Mark resuable uploads as broken if they are
|
"""Download from urls any uploads from outside sources"""
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand, CommandError
from apps.uploads.models import DropboxUploadFile, ManualUploadFile, ResumableUploadFile
LOGGER = logging.getLogger('apps.uploads')
class Command(BaseCommand):
"""Run command for uploads"""
help = __doc__ + """:
manage.py process_uploads
"""
@staticmethod
def handle(**_):
"""Handle script call"""
for cls in (DropboxUploadFile, ManualUploadFile):
for d_file in cls.objects.filter(retrieval_start__isnull=True):
print " + Downloading: %s" % d_file.url
d_file.download_now()
if d_file.retrieval_error:
print " ! Error downloading"
count = ResumableUploadFile.objects.filter(retrieval_start__isnull=True).update(
retrieval_error='Retry resumable upload, can not happen in server.',
retrieval_start=now(),
)
if count:
print(" * Resumable uploads marked as impossible: {}".format(count))
|
import logging
LOGGER = logging.getLogger('apps.uploads')
from django.core.management.base import BaseCommand, CommandError
from apps.uploads.models import DropboxUploadFile, ManualUploadFile
class Command(BaseCommand):
help = """Regular run of new dropbox links:
manage.py process_uploads
"""
def handle(self, **options):
for cls in [DropboxUploadFile, ManualUploadFile]:
for d_file in cls.objects.filter(retrieval_start__isnull=True):
print " + Downloading: %s" % d_file.url
d_file.download_now()
if d_file.retrieval_error:
print " ! Error downloading"
|
Mark fields except appropriateness as readonly
|
from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
readonly=True,
)
stage = fields.Field(
attribute='stage',
readonly=True,
)
vote = fields.Field(
attribute='vote',
readonly=True,
)
comment = fields.Field(
attribute='comment',
readonly=True,
)
discloses_comment = fields.Field(
attribute='discloses_comment',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness)
|
from import_export import fields, resources
from .models import Review
class ReviewResource(resources.ModelResource):
reviewer = fields.Field(
attribute='reviewer__email',
readonly=True,
)
proposal = fields.Field(
attribute='proposal__title',
readonly=True,
)
class Meta:
model = Review
fields = [
'id', 'reviewer', 'proposal', 'stage', 'vote', 'comment',
'discloses_comment', 'appropriateness',
]
export_order = fields
def dehydrate_discloses_comment(self, instance):
return int(instance.discloses_comment)
def dehydrate_appropriateness(self, instance):
return int(instance.appropriateness)
|
Fix virtual scrolling for table with local data.
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { getContext, mapProps, compose } from 'recompose';
import { visibleRowIdsSelector, classNamesForComponentSelector, stylesForComponentSelector } from '../selectors/localSelectors';
const ComposedTableBodyContainer = OriginalComponent => compose(
getContext({
components: PropTypes.object,
selectors: PropTypes.object,
}),
mapProps(props => ({
Row: props.components.Row,
visibleRowIdsSelector: props.selectors.visibleRowIdsSelector,
...props
})),
connect((state, props) => ({
visibleRowIds: props.visibleRowIdsSelector(state),
className: classNamesForComponentSelector(state, 'TableBody'),
style: stylesForComponentSelector(state, 'TableBody'),
})),
// withHandlers({
// Row: props => props.components.Row
// })
)(({ Row, visibleRowIds, style, className }) => (
<OriginalComponent
rowIds={visibleRowIds}
Row={Row}
style={style}
className={className}
/>
));
export default ComposedTableBodyContainer;
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { getContext, mapProps, compose } from 'recompose';
import { visibleRowIdsSelector, classNamesForComponentSelector, stylesForComponentSelector } from '../selectors/localSelectors';
const ComposedTableBodyContainer = OriginalComponent => compose(
getContext({
components: PropTypes.object,
selectors: PropTypes.object,
}),
connect(state => ({
visibleRowIds: visibleRowIdsSelector(state),
className: classNamesForComponentSelector(state, 'TableBody'),
style: stylesForComponentSelector(state, 'TableBody'),
})),
mapProps(props => ({
Row: props.components.Row,
...props
})),
// withHandlers({
// Row: props => props.components.Row
// })
)(({ Row, visibleRowIds, style, className }) => (
<OriginalComponent
rowIds={visibleRowIds}
Row={Row}
style={style}
className={className}
/>
));
export default ComposedTableBodyContainer;
|
Disable test untestable without x server
|
package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Ignore;
import org.junit.Test;
@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
|
package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Test;
//@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
|
Add missing file level doc-block
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Config;
use Zend\ServiceManager\AbstractPluginManager;
class WriterPluginManager extends AbstractPluginManager
{
protected $invokableClasses = array(
'php' => 'Zend\Config\Writer\PhpArray',
'ini' => 'Zend\Config\Writer\Ini',
'json' => 'Zend\Config\Writer\Json',
'yaml' => 'Zend\Config\Writer\Yaml',
'xml' => 'Zend\Config\Writer\Xml',
);
public function validatePlugin($plugin)
{
if ($plugin instanceOf Writer\AbstractWriter) {
return;
}
$type = is_object($plugin) ? get_class($plugin) : gettype($plugin);
throw new Exception\InvalidArgumentException(
"Plugin of type {$type} is invalid. Plugin must extend ".
__NAMESPACE__.'\Writer\AbstractWriter'
);
}
}
|
<?php
namespace Zend\Config;
use Zend\ServiceManager\AbstractPluginManager;
class WriterPluginManager extends AbstractPluginManager
{
protected $invokableClasses = array(
'php' => 'Zend\Config\Writer\PhpArray',
'ini' => 'Zend\Config\Writer\Ini',
'json' => 'Zend\Config\Writer\Json',
'yaml' => 'Zend\Config\Writer\Yaml',
'xml' => 'Zend\Config\Writer\Xml',
);
public function validatePlugin($plugin)
{
if ($plugin instanceOf Writer\AbstractWriter) {
return;
}
$type = is_object($plugin) ? get_class($plugin) : gettype($plugin);
throw new Exception\InvalidArgumentException(
"Plugin of type {$type} is invalid. Plugin must extend ".
__NAMESPACE__.'\Writer\AbstractWriter'
);
}
}
|
Fix uglify script no longer running.
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Project settings
simg: {
// configurable paths
scriptPath: 'src',
distPath: 'dist',
bowerPath: 'lib',
testPath: 'test'
},
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
report: 'min'
},
build: {
src: [
'<%= simg.scriptPath %>/simg.js'
],
dest: '<%= simg.distPath %>/simg.min.js'
}
},
jshint: {
options: {
jshintrc: true
},
all: [
'<%= simg.scriptPath %>/*.js'
]
}
});
// Load tasks
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['uglify']);
grunt.registerTask('lint', ['jshint']);
};
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Project settings
simg: {
// configurable paths
scriptPath: 'src',
distPath: 'dist',
bowerPath: 'lib',
testPath: 'test'
},
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n',
report: 'gzip'
},
build: {
src: [
'<%= simg.scriptPath %>/simg.js'
],
dest: '<%= simg.distPath %>/simg.min.js'
}
},
jshint: {
options: {
jshintrc: true
},
all: [
'<%= simg.scriptPath %>/*.js'
]
}
});
// Load tasks
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['uglify']);
grunt.registerTask('lint', ['jshint']);
};
|
Change typo in inactivate provider service
|
package com.smcpartners.shape.usecases.inactivate_provider;
import com.smcpartners.shape.shared.dto.common.BooleanValueDTO;
import com.smcpartners.shape.shared.dto.shape.request.IntEntityIdRequestDTO;
import com.smcpartners.shape.shared.usecasecommon.UseCaseException;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* Responsible:<br/>
* 1.
* <p>
* Created by johndestefano on 11/4/15.
* <p>
* Changes:<b/>
*/
@Path("admin")
public interface InactivateProviderService {
@POST
@Path("/provider/inactivate")
@Produces("application/json")
@Consumes("application/json")
BooleanValueDTO inactivateProvider(IntEntityIdRequestDTO id) throws UseCaseException;
}
|
package com.smcpartners.shape.usecases.inactivate_provider;
import com.smcpartners.shape.shared.dto.common.BooleanValueDTO;
import com.smcpartners.shape.shared.dto.shape.request.IntEntityIdRequestDTO;
import com.smcpartners.shape.shared.usecasecommon.UseCaseException;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* Responsible:<br/>
* 1.
* <p>
* Created by johndestefano on 11/4/15.
* <p>
* Changes:<b/>
*/
@Path("admin")
public interface InactivateProviderService {
@POST
@Path("/organization/inactivate")
@Produces("application/json")
@Consumes("application/json")
BooleanValueDTO inactivateProvider(IntEntityIdRequestDTO id) throws UseCaseException;
}
|
Load connectors before saving operator
|
/* global App */
App.OperatorController = Ember.ObjectController.extend({
fullType: function() {
return this.get('package') + '::' + this.get('type');
}.property('type', 'package'),
statusLabel: function() {
var status = this.get('model').get('status');
if (status === 'none')
return 'Not initialized';
else if (status === 'initialized')
return 'Initialized';
else if (status === 'active')
return 'Active';
else
return 'Not defined';
}.property('status'),
isEditingName: false,
actions: {
editName: function() {
this.set('isEditingName', true);
},
saveName: function() {
this.set('isEditingName', false);
var model = this.get('model');
model.save();
},
save: function() {
var model = this.get('model');
var inputs = model.get('inputs');
var outputs = model.get('outputs');
Ember.RSVP.all([inputs, outputs]).then( function(values){
model.set('inputs', values[0]);
model.set('outputs', values[1]);
model.save();
})
}
}
});
|
/* global App */
App.OperatorController = Ember.ObjectController.extend({
fullType: function() {
return this.get('package') + '::' + this.get('type');
}.property('type', 'package'),
statusLabel: function() {
var status = this.get('model').get('status');
if (status === 'none')
return 'Not initialized';
else if (status === 'initialized')
return 'Initialized';
else if (status === 'active')
return 'Active';
else
return 'Not defined';
}.property('status'),
isEditingName: false,
actions: {
editName: function() {
this.set('isEditingName', true);
},
saveName: function() {
this.set('isEditingName', false);
var model = this.get('model');
model.save();
},
save: function() {
var model = this.get('model');
model.save();
}
}
});
|
Add missing Station super() call
|
import { EventEmitter } from 'events'
import PouchDB from 'pouchdb'
import Serial from '../serial'
import Classifier from './classifier'
import { parser, dataHandler } from './data-handler'
/**
* Handles everything a Station should.
* Brings Serial, data parsing and database saving together.
*/
export default class Station extends EventEmitter {
/**
* Sets up all relevant class instances (Serial, parsers...) and events listeners.
*/
constructor () {
super()
/**
* Database instance, internal to the station.
*/
this.db = new PouchDB('station-db')
/**
* {@link Serial} instance with the {@link parser} attached
*/
this.serial = new Serial(parser())
/**
* {@link Classifier} instance.
*/
this.classifier = new Classifier()
// Handle incoming packets
this.serial.on('data', this::dataHandler)
}
}
|
import { EventEmitter } from 'events'
import PouchDB from 'pouchdb'
import Serial from '../serial'
import Classifier from './classifier'
import { parser, dataHandler } from './data-handler'
/**
* Handles everything a Station should.
* Brings Serial, data parsing and database saving together.
*/
export default class Station extends EventEmitter {
/**
* Sets up all relevant class instances (Serial, parsers...) and events listeners.
*/
constructor () {
/**
* Database instance, internal to the station.
*/
this.db = new PouchDB('station-db')
/**
* {@link Serial} instance with the {@link parser} attached
*/
this.serial = new Serial(parser())
/**
* {@link Classifier} instance.
*/
this.classifier = new Classifier()
// Handle incoming packets
this.serial.on('data', this::dataHandler)
}
}
|
Add modal for ipad links
|
<?php
function ipadPopUpScript(){
?>
jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscription/']").attr('data-reveal-id', 'ipadPopUp');
<?php
}
function ipadPopUpModal(){
?>
jQuery('#colophon').after('<div id="ipadPopUp" class="reveal-modal"><h2>We'+
'are opening a new tab.</h2><p class="lead">The following link will open a'+
' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+
'zine from there.</p><p>If you have any items in your shopping cart, they '+
'won\'t go anywhere (as long as you don\'t close the window).</p><a href="'+
'https://itunes.apple.com/us/app/bullett/id557294227?mt=8" class="button" '+
'target="_blank"><\/a><a class="close-reveal-modal">×<\/a><\/div>');
<?php
}
function PopUpModal(){
?>
<script>
<?php ipadPopUpScript(); ?>
<?php ipadPopUpModal(); ?>
</script>
<?php
}
add_action('wp_footer', 'PopUpModal', 33);
?>
|
<?php
function ipadPopUpScript(){
?>
jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscription/']").attr('data-reveal-id', 'ipadPopUp');
<?php
}
function ipadPopUpModal(){
?>
jQuery('#colophon').after('<div id="ipadPopUp" class="reveal-modal"><h2>We'+
'are opening a new tab.</h2><p class="lead">The following link will open a'+
' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+
'zine from there.</p><p>If you have any items in your shopping cart, they '+
'won\'t go anywhere (as long as you don\'t close the window).</p><a href="'+
'https://itunes.apple.com/us/app/bullett/id557294227?mt=8" class="button" '+
'target="_blank"><\/a><a class="close-reveal-modal">×<\/a><\/div>');
<?php
}
function PopUpModal(){
?>
<script>
ipadPopUpScript();
ipadPopUpModal();
</script>
<?php
}
add_action('wp_footer', 'PopUpModal', 33);
?>
|
Add example text to CLI --help
|
#!/usr/bin/env node
'use strict';
var pkg = require('./package.json');
var shelfiesAmazonLinker = require('./');
var argv = process.argv.slice(2);
var copypaste = require('copy-paste').silent();
var chalk = require('chalk');
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Example',
' shelfies-amazon-linker why nations fail',
'',
' Looking up: "why nations fail"',
' [Why Nations Fail](http://www.amazon.com/Why-Nations-Fail-Origins-Prosperity/dp/0307719227) - *The Origins of Power, Prosperity, and Poverty*',
'',
' Copied to your clipboard',
''
].join('\n'));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
console.log('Looking up: "' + argv.join(' ') + '"');
shelfiesAmazonLinker(argv.join(' '), function(err, result){
if(err){
return console.log(chalk.red('\nAn error occured, please try again.'));
}
console.log(chalk.inverse(result.markdown));
copypaste.copy(result.markdown);
console.log(chalk.green('\nCopied to your clipboard'));
});
|
#!/usr/bin/env node
'use strict';
var pkg = require('./package.json');
var shelfiesAmazonLinker = require('./');
var argv = process.argv.slice(2);
var copypaste = require('copy-paste').silent();
var chalk = require('chalk');
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Example',
' shelfies-amazon-linker ',
''
].join('\n'));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
console.log('Looking up: "' + argv.join(' ') + '"');
shelfiesAmazonLinker(argv.join(' '), function(err, result){
if(err){
return console.log(chalk.red('\nAn error occured, please try again.'));
}
console.log(chalk.inverse(result.markdown));
copypaste.copy(result.markdown);
console.log(chalk.green('\nCopied to your clipboard'));
});
|
Fix the order issue of menu items
|
console.log("menu-fill");
var menu_env = $("#menu-env");
function createLinkItem (item) {
var _a = $("<a/>", { href: item.link });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
return _a;
}
function createSingleLevelMenuItem (item) {
return $("<li/>").append(createLinkItem(item));
}
function createMultiLevelMenuItem (item) {
item.link = "#";
var _a = createLinkItem(item);
$("<span/>", { class: "label label-primary pull-right", text: item.sub.length - 1 }).appendTo(_a);
var _ul = $("<ul/>", { class: "treeview-menu" });
$.each(item.sub, function (index) {
this.icon = index == 0 ? "fa fa-certificate" : "fa fa-circle-o";
_ul.append(createSingleLevelMenuItem(this));
});
return $("<li/>", { class: "treeview" }).append(_a).append(_ul);
}
var item_list = []
$.each(menu_env_data, function (index) {
item_list.push(this.sub
? createMultiLevelMenuItem(this)
: createSingleLevelMenuItem(this)
);
});
$.each(item_list.reverse(), function () {
menu_env.after(this);
});
|
console.log("menu-fill");
var menu_env = $("#menu-env");
var item1 = menu_env_data[0];
var item2 = menu_env_data[1];
function createLinkItem (item) {
var _a = $("<a/>", { href: item.link });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
return _a;
}
function createSingleLevelMenuItem (item) {
return $("<li/>").append(createLinkItem(item));
}
function createMultiLevelMenuItem (item) {
item.link = "#";
var _a = createLinkItem(item);
$("<span/>", { class: "label label-primary pull-right", text: item.sub.length - 1 }).appendTo(_a);
var _ul = $("<ul/>", { class: "treeview-menu" });
$.each(item.sub, function (index) {
this.icon = index == 0 ? "fa fa-certificate" : "fa fa-circle-o";
_ul.append(createSingleLevelMenuItem(this));
});
return $("<li/>", { class: "treeview" }).append(_a).append(_ul);
}
$.each(menu_env_data, function (index) {
if (this.sub) {
menu_env.after(createMultiLevelMenuItem(this));
}
else {
menu_env.after(createSingleLevelMenuItem(this));
}
});
|
Remove kansface repo from input.
|
package floobits;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.util.text.StringUtil;
public class JoinWorkspace extends AnAction {
private static class URLInputValidator implements InputValidator {
@Override
public boolean canClose(String inputString) {
return true;
}
@Override
public boolean checkInput(String inputString) {
try {
final URL url = new URL(inputString);
return StringUtil.isNotEmpty(url.getHost());
} catch (MalformedURLException e) {
return false;
}
}
}
public void actionPerformed(AnActionEvent e) {
String inputValue = JOptionPane.showInputDialog("Workspace URL", "https://floobits.com/");
Flog.info(inputValue);
FloobitsPlugin.joinWorkspace(inputValue);
}
}
|
package floobits;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.util.text.StringUtil;
public class JoinWorkspace extends AnAction {
private static class URLInputValidator implements InputValidator {
@Override
public boolean canClose(String inputString) {
return true;
}
@Override
public boolean checkInput(String inputString) {
try {
final URL url = new URL(inputString);
return StringUtil.isNotEmpty(url.getHost());
} catch (MalformedURLException e) {
return false;
}
}
}
public void actionPerformed(AnActionEvent e) {
String inputValue = JOptionPane.showInputDialog("Workspace URL", "https://floobits.com/kansface/asdf");
Flog.info(inputValue);
FloobitsPlugin.joinWorkspace(inputValue);
}
}
|
Remove manual alias because it is added automatically with config plugin
|
<?php
/**
* HiDev plugin for license generation.
*
* @link https://github.com/hiqdev/hidev-license
* @package hidev-license
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
return [
'controllerMap' => [
'LICENSE' => [
'class' => \hidev\license\console\LicenseController::class,
],
],
'components' => [
'license' => [
'class' => \hidev\license\components\License::class,
],
'view' => [
'theme' => [
'pathMap' => [
'@hidev/views' => ['@hidev/license/views'],
],
],
],
],
];
|
<?php
/**
* HiDev plugin for license generation.
*
* @link https://github.com/hiqdev/hidev-license
* @package hidev-license
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
return [
'controllerMap' => [
'LICENSE' => [
'class' => \hidev\license\console\LicenseController::class,
],
],
'components' => [
'license' => [
'class' => \hidev\license\components\License::class,
],
'view' => [
'theme' => [
'pathMap' => [
'@hidev/views' => ['@hidev/license/views'],
],
],
],
],
'aliases' => [
'@hidev/license' => dirname(__DIR__) . '/src',
],
];
|
Fix test error when coverage is not installed
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
try:
import coverage
from ..coverage import Coverage
except ImportError:
coverage = None
Coverage = None
from mock import Mock, patch
from ..testing import unittest
@unittest.skipIf(coverage is None, 'Coverage is not installed')
class TestCoverage(unittest.TestCase):
@patch('coverage.coverage')
def test_coverage(self, coverage_func):
coverage_object = Mock()
coverage_func.return_value = coverage_object
coverage_object.start = Mock()
coverage_object.stop = Mock()
coverage_object.save = Mock()
cov = Coverage()
coverage_func.assert_called_once_with()
cov.setup()
coverage_object.start.assert_called_once_with()
self.assertFalse(coverage_object.stop.called)
self.assertFalse(coverage_object.save.called)
cov.teardown()
coverage_object.stop.assert_called_once_with()
coverage_object.save.assert_called_once_with()
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
try:
import coverage
except ImportError:
coverage = None
from mock import Mock, patch
from ..coverage import Coverage
from ..testing import unittest
@unittest.skipIf(coverage is None, 'Coverage is not installed')
class TestCoverage(unittest.TestCase):
@patch('coverage.coverage')
def test_coverage(self, coverage_func):
coverage_object = Mock()
coverage_func.return_value = coverage_object
coverage_object.start = Mock()
coverage_object.stop = Mock()
coverage_object.save = Mock()
cov = Coverage()
coverage_func.assert_called_once_with()
cov.setup()
coverage_object.start.assert_called_once_with()
self.assertFalse(coverage_object.stop.called)
self.assertFalse(coverage_object.save.called)
cov.teardown()
coverage_object.stop.assert_called_once_with()
coverage_object.save.assert_called_once_with()
|
Change != to !=== in Rule.channelMatches
|
/* jshint node: true */
'use strict';
module.exports = Rule;
function Rule(configRule) {
for (var property in configRule) {
if (configRule.hasOwnProperty(property)) {
this[property] = configRule[property];
}
}
}
// This expects just the rawMessage from a SlackTextMessage.
Rule.prototype.match = function(message, slackClient) {
return (this.reactionMatches(message) &&
!this.issueAlreadyFiled(message) &&
this.channelMatches(message, slackClient));
};
Rule.prototype.reactionMatches = function(message) {
return message.name === this.reactionName;
};
Rule.prototype.issueAlreadyFiled = function(message) {
// Presume that an issue already exists if this isn't the first reaction.
var that = this,
reaction = message.item.message.reactions.find(function(reaction) {
return reaction.name === that.reactionName;
});
// reaction should never be undefined, but we need to handle it anyway.
return reaction === undefined || reaction.count !== 1;
};
Rule.prototype.channelMatches = function(message, slackClient) {
var channels = this.channelNames;
return channels === undefined ||
channels.indexOf(slackClient.getChannelName(message.item.channel)) !== -1;
};
|
/* jshint node: true */
'use strict';
module.exports = Rule;
function Rule(configRule) {
for (var property in configRule) {
if (configRule.hasOwnProperty(property)) {
this[property] = configRule[property];
}
}
}
// This expects just the rawMessage from a SlackTextMessage.
Rule.prototype.match = function(message, slackClient) {
return (this.reactionMatches(message) &&
!this.issueAlreadyFiled(message) &&
this.channelMatches(message, slackClient));
};
Rule.prototype.reactionMatches = function(message) {
return message.name === this.reactionName;
};
Rule.prototype.issueAlreadyFiled = function(message) {
// Presume that an issue already exists if this isn't the first reaction.
var that = this,
reaction = message.item.message.reactions.find(function(reaction) {
return reaction.name === that.reactionName;
});
// reaction should never be undefined, but we need to handle it anyway.
return reaction === undefined || reaction.count !== 1;
};
Rule.prototype.channelMatches = function(message, slackClient) {
var channels = this.channelNames;
return channels === undefined ||
channels.indexOf(slackClient.getChannelName(message.item.channel)) != -1;
};
|
Add constructor that does not require id.
|
/*
* Copyright 2016 Attribyte, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.attribyte.wp.model;
/**
* Metadata associated with a post, user, or
* other object.
*/
public class Meta {
/**
* Creates metadata with no assigned id.
* @param key The key.
* @param value The value.
*/
public Meta(final String key, final String value) {
this(0L, key, value);
}
/**
* Creates metadata.
* @param id The id.
* @param key The key.
* @param value The value.
*/
public Meta(final long id, final String key, final String value) {
this.id = id;
this.key = key;
this.value = value;
}
/**
* The unique id.
*/
public final long id;
/**
* The key.
*/
public final String key;
/**
* The value.
*/
public final String value;
}
|
/*
* Copyright 2016 Attribyte, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.attribyte.wp.model;
/**
* Metadata associated with a post, user, or
* other object.
*/
public class Meta {
/**
* Creates metadata.
* @param id The id.
* @param key The key.
* @param value The value.
*/
public Meta(final long id, final String key, final String value) {
this.id = id;
this.key = key;
this.value = value;
}
/**
* The unique id.
*/
public final long id;
/**
* The key.
*/
public final String key;
/**
* The value.
*/
public final String value;
}
|
Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.
|
from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = subprocess.Popen(
args,
env={'PYTHONPATH': os.path.join(mopidy_dir, '..')},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
|
from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
process = subprocess.Popen(
args,
env={'PYTHONPATH': ':'.join(python_path)},
stdout=subprocess.PIPE)
output = process.communicate()[0]
self.assertIn('--version', output)
self.assertIn('--help', output)
self.assertIn('--quiet', output)
self.assertIn('--verbose', output)
self.assertIn('--save-debug-log', output)
self.assertIn('--config', output)
self.assertIn('--option', output)
|
Fix missing new line symbol for last line in notebook cell
|
# coding: utf-8
import sys, getopt
import os
import json
import datetime
from subprocess import call
current_date = str(datetime.datetime.now()).replace(' ', '!')
output_file_name = './tmp_itorch_exec-'+current_date+'.lua'
if __name__ == "__main__":
if len(sys.argv) > 0:
input_file = open(sys.argv[1], 'r')
with input_file as json_file:
json_data = json.load(json_file)
input_file.close()
sources = []
for item in json_data['cells']:
if item['cell_type'] == 'code' and len(item['source']) > 0:
item['source'][-1] = item['source'][-1]+'\n'
sources = sources + item['source']
output_file = open(output_file_name, 'w')
output_file.writelines(sources)
output_file.close()
call(["th", output_file_name])
os.remove(output_file_name)
|
# coding: utf-8
import sys, getopt
import os
import json
import datetime
from subprocess import call
current_date = str(datetime.datetime.now()).replace(' ', '!')
output_file_name = './tmp_itorch_exec-'+current_date+'.lua'
if __name__ == "__main__":
if len(sys.argv) > 0:
input_file = open(sys.argv[1], 'r')
with input_file as json_file:
json_data = json.load(json_file)
input_file.close()
sources = []
for item in json_data['cells']:
if item['cell_type'] == 'code':
sources = sources + item['source']
output_file = open(output_file_name, 'w')
output_file.writelines(sources)
output_file.close()
call(["th", output_file_name])
os.remove(output_file_name)
|
Revert "adding JSON to the list of extensions that should be compressed"
This reverts commit c90513519febf8feeea78b06da6a467bb1085948.
|
'use strict';
var es = require('event-stream'),
path = require('path'),
zlib = require('zlib');
var compressibles = [
'.js',
'.css',
'.html'
];
function isCompressibleFile( file ) {
var ext = path.extname( file.path ).toLowerCase();
return ( compressibles.indexOf( ext ) > -1 );
}
module.exports = function() {
return es.map( function( file, cb ) {
if( !isCompressibleFile( file ) ) {
cb( null, file );
return;
}
zlib.gzip( file.contents, function( err, result ) {
if( err ) {
cb( err, null );
return;
}
file.path += '.gz';
file.contents = result;
cb( null, file );
} );
} );
};
module.exports._isCompressibleFile = isCompressibleFile;
|
'use strict';
var es = require('event-stream'),
path = require('path'),
zlib = require('zlib');
var compressibles = [
'.js',
'.json',
'.css',
'.html'
];
function isCompressibleFile( file ) {
var ext = path.extname( file.path ).toLowerCase();
return ( compressibles.indexOf( ext ) > -1 );
}
module.exports = function() {
return es.map( function( file, cb ) {
if( !isCompressibleFile( file ) ) {
cb( null, file );
return;
}
zlib.gzip( file.contents, function( err, result ) {
if( err ) {
cb( err, null );
return;
}
file.path += '.gz';
file.contents = result;
cb( null, file );
} );
} );
};
module.exports._isCompressibleFile = isCompressibleFile;
|
Change string formatting to use format
|
from django.db import models
from .. import abstract_models
from ..manager import PageManager
class PageType(abstract_models.AbstractPageType):
class Meta:
app_label = 'fancypages'
class VisibilityType(abstract_models.AbstractVisibilityType):
class Meta:
app_label = 'fancypages'
class FancyPage(abstract_models.AbstractTreeNode,
abstract_models.AbstractFancyPage):
objects = PageManager()
class Meta:
app_label = 'fancypages'
class Container(abstract_models.AbstractContainer):
class Meta:
app_label = 'fancypages'
unique_together = (('name', 'content_type', 'object_id'),)
class OrderedContainer(Container):
display_order = models.PositiveIntegerField()
def __unicode__(self):
return u"Container #{0} '{1}' in '{2}'".format(
self.display_order,
self.name,
self.content_type
)
class Meta:
app_label = 'fancypages'
|
from django.db import models
from .. import abstract_models
from ..manager import PageManager
class PageType(abstract_models.AbstractPageType):
class Meta:
app_label = 'fancypages'
class VisibilityType(abstract_models.AbstractVisibilityType):
class Meta:
app_label = 'fancypages'
class FancyPage(abstract_models.AbstractTreeNode,
abstract_models.AbstractFancyPage):
objects = PageManager()
class Meta:
app_label = 'fancypages'
class Container(abstract_models.AbstractContainer):
class Meta:
app_label = 'fancypages'
unique_together = (('name', 'content_type', 'object_id'),)
class OrderedContainer(Container):
display_order = models.PositiveIntegerField()
def __unicode__(self):
return u"Container #%d '%s' in '%s'" % (
self.display_order,
self.name,
self.content_type
)
class Meta:
app_label = 'fancypages'
|
Move back session storage creation
|
import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, useAuthentication } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
import * as config from './config';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';
import './app.scss';
sentry(config);
const Setup = () => {
const { UID, login, logout } = useAuthentication();
if (UID) {
return <PrivateApp onLogout={logout} />;
}
return <PublicApp onLogin={login} />;
};
const App = () => {
return (
<ProtonApp config={config}>
<Setup />
</ProtonApp>
);
};
export default hot(App);
|
import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, useAuthentication, useInstance } from 'react-components';
import createSecureSessionStorage from 'proton-shared/lib/createSecureSessionStorage';
import { MAILBOX_PASSWORD_KEY, UID_KEY } from 'proton-shared/lib/constants';
import sentry from 'proton-shared/lib/helpers/sentry';
import * as config from './config';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';
import './app.scss';
sentry(config);
const Setup = () => {
const { UID, login, logout } = useAuthentication();
if (UID) {
return <PrivateApp onLogout={logout} />;
}
return <PublicApp onLogin={login} />;
};
const App = () => {
const storage = useInstance(() => createSecureSessionStorage([MAILBOX_PASSWORD_KEY, UID_KEY]));
return (
<ProtonApp config={config} storage={storage}>
<Setup />
</ProtonApp>
);
};
export default hot(App);
|
Add explicit language specifier to test.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@354048 91177308-0d34-0410-b5e6-96231b3b80d8
|
"""Test that importing modules in C++ works as expected."""
from __future__ import print_function
from distutils.version import StrictVersion
import unittest2
import os
import time
import lldb
import platform
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class CXXModulesImportTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUnlessDarwin
@skipIf(macos_version=["<", "10.12"])
def test_expr(self):
self.build()
exe = self.getBuildArtifact("a.out")
target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(
self, 'break here', lldb.SBFileSpec('main.cpp'))
self.expect("expr -l Objective-C++ -- @import Bar")
self.expect("expr -- Bar()", substrs = ["success"])
|
"""Test that importing modules in C++ works as expected."""
from __future__ import print_function
from distutils.version import StrictVersion
import unittest2
import os
import time
import lldb
import platform
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class CXXModulesImportTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@skipUnlessDarwin
@skipIf(macos_version=["<", "10.12"])
def test_expr(self):
self.build()
exe = self.getBuildArtifact("a.out")
target, process, thread, bkpt = lldbutil.run_to_source_breakpoint(
self, 'break here', lldb.SBFileSpec('main.cpp'))
self.expect("expr -- @import Bar")
self.expect("expr -- Bar()", substrs = ["success"])
|
Remove --dev from composer install.
composer install installs dev dependencies by default.
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$phpcsCommand = './vendor/bin/phpcs --standard=' . __DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS -n src tests *.php';
passthru($phpcsCommand, $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-html coverage --coverage-clover clover.xml', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
}
echo "Code coverage was 100%\n";
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$phpcsCommand = './vendor/bin/phpcs --standard=' . __DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS -n src tests *.php';
passthru($phpcsCommand, $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-html coverage --coverage-clover clover.xml', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
}
echo "Code coverage was 100%\n";
|
Support `thread_ts` parameter for Incoming Webhook
|
package slack
import (
"bytes"
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
type WebhookMessage struct {
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
IconURL string `json:"icon_url,omitempty"`
Channel string `json:"channel,omitempty"`
ThreadTS string `json:"thread_ts,omitempty"`
Text string `json:"text,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
}
func PostWebhook(url string, msg *WebhookMessage) error {
raw, err := json.Marshal(msg)
if err != nil {
return errors.Wrap(err, "marshal failed")
}
response, err := http.Post(url, "application/json", bytes.NewReader(raw))
if err != nil {
return errors.Wrap(err, "failed to post webhook")
}
if response.StatusCode != http.StatusOK {
return statusCodeError{Code: response.StatusCode, Status: response.Status}
}
return nil
}
|
package slack
import (
"bytes"
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
type WebhookMessage struct {
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
IconURL string `json:"icon_url,omitempty"`
Channel string `json:"channel,omitempty"`
Text string `json:"text,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
}
func PostWebhook(url string, msg *WebhookMessage) error {
raw, err := json.Marshal(msg)
if err != nil {
return errors.Wrap(err, "marshal failed")
}
response, err := http.Post(url, "application/json", bytes.NewReader(raw))
if err != nil {
return errors.Wrap(err, "failed to post webhook")
}
if response.StatusCode != http.StatusOK {
return statusCodeError{Code: response.StatusCode, Status: response.Status}
}
return nil
}
|
Add animation to toggle presentation video block
|
(function(){
generateHTML();
$(document).ready(function(){
$('a.node.expanded').each(expandListToggle);
$('.my-name').fadeIn("slow");
$('.headlogolinks a').hover(fadeInLink, fadeOutLink);
$('.menu-button').on('click', showMainContent);
$('a.node').on('click', expandListToggle);
$('.video-link').on('click', showLaunchVideo);
$('.about-me').on('click', toggleAboutMeContent);
});
function fadeInLink() {
$(this).fadeTo("fast", 1.0);
}
function fadeOutLink() {
$(this).fadeTo("fast", 0.6);
}
function showLaunchVideo() {
$('.video-block').slideToggle();
}
function showMainContent() {
$(".main-content").fadeIn();
$('.menu-button').hide();
$('.logo').fadeIn();
}
function expandListToggle() {
$(this).toggleClass("expanded");
$(this).next('ul').toggle('fast');
};
function toggleAboutMeContent() {
$('.about-me-content').slideToggle();
}
})();
|
(function(){
generateHTML();
$(document).ready(function(){
$('a.node.expanded').each(expandListToggle);
$('.my-name').fadeIn("slow");
$('.headlogolinks a').hover(fadeInLink, fadeOutLink);
$('.menu-button').on('click', showMainContent);
$('a.node').on('click', expandListToggle);
$('.about-me').on('click', toggleAboutMeContent);
});
function fadeInLink() {
$(this).fadeTo("fast", 1.0);
}
function fadeOutLink() {
$(this).fadeTo("fast", 0.6);
}
function showMainContent() {
$(".main-content").fadeIn();
$('.menu-button').hide();
$('.logo').fadeIn();
}
function expandListToggle() {
$(this).toggleClass("expanded");
$(this).next('ul').toggle('fast');
};
function toggleAboutMeContent() {
$('.about-me-content').slideToggle();
}
})();
|
Add error listeners to socket server
|
var ws = require('nodejs-websocket');
/**
* Triggers when connections is established
* @param connection
* @private
*/
function _onConnection(connection) {
console.log('Connections is established');
connection.on('error', console.error.bind(console.error));
connection.on('close', console.log.bind(console.log, 'Connection is closed -'));
}
/**
* Returns Server
* @param {String} port
* @returns {Object}
*/
function WebSocketServer(port) {
this._setServer(ws.createServer().listen(port));
this._getServer().on('connection', _onConnection);
this._getServer().on('error', console.error.bind(console.error));
}
/**
* Get native server
* @returns {*}
* @private
*/
WebSocketServer.prototype._getServer = function () {
return this._server;
};
/**
* Set new native server
* @param server
* @returns {WebSocketServer}
* @private
*/
WebSocketServer.prototype._setServer = function (server) {
this._server = server;
return this;
};
/**
* Send message to all connections
* @param {*} data
* @returns {WebSocketServer}
*/
WebSocketServer.prototype.send = function (data) {
this._getServer().connections.forEach(function (connection) {
connection.sendText(JSON.stringify(data));
});
return this;
};
module.exports = WebSocketServer;
|
var ws = require('nodejs-websocket');
/**
* Triggers when connections is established
* @param connection
* @private
*/
function _onConnection(connection) {
connection.on('close', console.log.bind(console.log, 'Connection is closed -'));
}
/**
* Returns Server
* @param {String} port
* @returns {Object}
*/
function WebSocketServer(port) {
this._setServer(ws.createServer().listen(port));
this._getServer().on('connection', _onConnection);
}
/**
* Get native server
* @returns {*}
* @private
*/
WebSocketServer.prototype._getServer = function () {
return this._server;
};
/**
* Set new native server
* @param server
* @returns {WebSocketServer}
* @private
*/
WebSocketServer.prototype._setServer = function (server) {
this._server = server;
return this;
};
/**
* Send message to all connections
* @param {*} data
* @returns {WebSocketServer}
*/
WebSocketServer.prototype.send = function (data) {
this._getServer().connections.forEach(function (connection) {
connection.sendText(JSON.stringify(data));
});
return this;
};
module.exports = WebSocketServer;
|
Fix an issue with parameter validation
|
var isFunction = require('lodash.isfunction');
var joi = require('joi');
var pc = require('pascal-case');
/* Public */
function attach(schema) {
var attachments = {};
schema &&
schema._inner &&
schema._inner.children &&
schema._inner.children.forEach(function (child) {
attachments[pc(child.key)] = {
get: function () {
return child.schema;
}
};
});
return Object.defineProperties(schema, attachments);
}
function spec(type, params) {
var after, spec;
if (!params) {
params = type || {};
type = params.type;
delete params.type;
}
if (isFunction(params.after)) {
after = params.after;
delete params.after;
}
spec = joi[type]();
Object.keys(params).forEach(function (key) {
spec = Array.isArray(params[key])
? spec[key].apply(spec, params[key])
: spec[key](params[key]);
});
if (after) {
after(spec);
}
return spec;
}
/* Exports */
module.exports.attach = attach;
module.exports.spec = spec;
|
var isFunction = require('lodash.isfunction');
var joi = require('joi');
var pc = require('pascal-case');
/* Public */
function attach(schema) {
var attachments = {};
schema &&
schema._inner &&
schema._inner.children &&
schema._inner.children.forEach(function (child) {
attachments[pc(child.key)] = {
get: function () {
return child.schema;
}
};
});
return Object.defineProperties(schema, attachments);
}
function spec(type, params) {
var after, spec;
if (arguments.length === 1) {
params = type;
type = params.type;
delete params.type;
}
if (isFunction(params.after)) {
after = params.after;
delete params.after;
}
spec = joi[type]();
Object.keys(params).forEach(function (key) {
spec = Array.isArray(params[key])
? spec[key].apply(spec, params[key])
: spec[key](params[key]);
});
if (after) {
after(spec);
}
return spec;
}
/* Exports */
module.exports.attach = attach;
module.exports.spec = spec;
|
Set frameset to 100%,0% on load.
|
function receiveMessage(event) {
var commentPath,
frameURL;
// get url of comment
commentPath = event.data.commentURL;
frameURL = "https://news.ycombinator.com/" + commentPath;
showComments( frameURL )
}
var showComments = function( URL ) {
var commentFrame,
frameset;
frameset = document.querySelector( "frameset" );
frameset.setAttribute( "cols", "50%,50%" );
commentFrame = document.querySelector( "#comment-frame" );
commentFrame.setAttribute( "src", URL );
}
var drawIframe = function() {
var frameset,
pageURL,
pageFrame,
commentFrame,
html,
body;
html = document.querySelector( "html" );
body = document.querySelector( "body" );
frameset = document.createElement( "frameset" );
pageFrame = document.createElement( "frame" );
commentFrame = document.createElement( "frame" );
pageFrame.setAttribute( "id", "page-frame" );
commentFrame.setAttribute( "id", "comment-frame" );
pageURL = document.URL;
if ( body )
body.parentNode.removeChild( body );
frameset.appendChild( pageFrame );
frameset.appendChild( commentFrame );
frameset.setAttribute( "cols", "100%,0%" );
html.appendChild( frameset );
pageFrame.setAttribute( "src", pageURL );
}
drawIframe();
window.addEventListener("message", receiveMessage, false);
|
function receiveMessage(event) {
var commentPath,
frameURL;
// get url of comment
commentPath = event.data.commentURL;
frameURL = "https://news.ycombinator.com/" + commentPath;
showComments( frameURL )
}
var showComments = function( URL ) {
var commentFrame,
frameset;
frameset = document.querySelector( "frameset" );
frameset.setAttribute( "cols", "50%,50%" );
commentFrame = document.querySelector( "#comment-frame" );
commentFrame.setAttribute( "src", URL );
}
var drawIframe = function() {
var frameset,
pageURL,
pageFrame,
commentFrame,
html,
body;
html = document.querySelector( "html" );
body = document.querySelector( "body" );
frameset = document.createElement( "frameset" );
pageFrame = document.createElement( "frame" );
commentFrame = document.createElement( "frame" );
pageFrame.setAttribute( "id", "page-frame" );
commentFrame.setAttribute( "id", "comment-frame" );
pageURL = document.URL;
if ( body )
body.parentNode.removeChild( body );
frameset.appendChild( pageFrame );
frameset.appendChild( commentFrame );
html.appendChild( frameset );
pageFrame.setAttribute( "src", pageURL );
}
drawIframe();
window.addEventListener("message", receiveMessage, false);
|
Update test depending on environment (BO or FO)
|
<?php
namespace OpenOrchestra\ModelBundle\Tests\Functional\Repository;
use OpenOrchestra\ModelInterface\Repository\ContentTypeRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Class ContentTypeRepositoryTest
*
* @group integrationTest
*/
class ContentTypeRepositoryTest extends KernelTestCase
{
/**
* @var ContentTypeRepositoryInterface
*/
protected $repository;
/**
* Set up the test
*/
public function setUp()
{
parent::setUp();
static::bootKernel();
$this->repository = static::$kernel->getContainer()->get('open_orchestra_model.repository.content_type');
}
/**
* @param string $contentType
* @param int $version
*
* @dataProvider provideContentTypeAndVersionNumber
*/
public function testFindOneByContentTypeIdInLastVersion($contentType, $version)
{
$contentTypeElement = $this->repository->findOneByContentTypeIdInLastVersion($contentType);
$this->assertEquals($version, $contentTypeElement->getVersion());
}
/**
* @return array
*/
public function provideContentTypeAndVersionNumber()
{
return array(
array('car', 2),
array('customer', 1),
);
}
}
|
<?php
namespace OpenOrchestra\ModelBundle\Tests\Functional\Repository;
use OpenOrchestra\ModelInterface\Repository\ContentTypeRepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Class ContentTypeRepositoryTest
*
* @group integrationTest
*/
class ContentTypeRepositoryTest extends KernelTestCase
{
/**
* @var ContentTypeRepositoryInterface
*/
protected $repository;
/**
* Set up the test
*/
public function setUp()
{
parent::setUp();
static::bootKernel();
$this->repository = static::$kernel->getContainer()->get('open_orchestra_model.repository.content_type');
}
/**
* @param string $contentType
* @param int $version
*
* @dataProvider provideContentTypeAndVersionNumber
*/
public function testFindOneByContentTypeIdInLastVersion($contentType, $version)
{
$contentTypeElement = $this->repository->findOneByContentTypeIdInLastVersion($contentType);
$this->assertEquals($version, $contentTypeElement->getVersion());
}
/**
* @return array
*/
public function provideContentTypeAndVersionNumber()
{
return array(
array('news', 2),
array('customer', 1),
);
}
}
|
Remove test for adding feedback
|
# -*- coding: utf-8 -*-
from django.test import TestCase, client
from .models import Feedback
client = client.Client()
class FeedbackTest(TestCase):
def test_add_feedback(self):
pass
# before_add = Feedback.objects.count()
# response = client.post('/feedback/add/', {
# 'name': 'Пандо Пандев',
# 'email': 'panda@panda.com',
# 'information': 'Тука се разхожда една панда по екрана'})
# after_add = Feedback.objects.count()
# self.assertEqual(response.status_code, 302)
# self.assertEqual(before_add + 1, after_add)
def test_user_add_feedback(self):
pass
|
# -*- coding: utf-8 -*-
from django.test import TestCase, client
from .models import Feedback
client = client.Client()
class FeedbackTest(TestCase):
def test_add_feedback(self):
before_add = Feedback.objects.count()
response = client.post('/feedback/add/', {
'name': 'Пандо Пандев',
'email': 'panda@panda.com',
'information': 'Тука се разхожда една панда по екрана'})
after_add = Feedback.objects.count()
self.assertEqual(response.status_code, 302)
self.assertEqual(before_add + 1, after_add)
def test_user_add_feedback(self):
pass
|
Use managed transfer for uploading
|
import pandas as pd
import gzip
import boto3
import re
import io
def default_key_map(key):
return re.sub('_input', '_output', key)
class S3Dest():
def __init__(self, key_map=default_key_map):
self.key_map = key_map
def skip_keys(self, bucket, source_prefix):
s3 = boto3.resource('s3')
objs = s3.Bucket(bucket).objects.filter(Prefix=self.key_map(source_prefix))
return [obj.key for obj in objs]
def put(self, data, obj):
body = self.generate_output_file(data)
dest_key = self.key_map(obj.key)
s3 = boto3.resource('s3')
s3.Object(obj.bucket_name, dest_key).upload_fileobj(io.BytesIO(body))
def generate_output_file(self, data):
df = pd.DataFrame(data)
tsv = df.to_csv(sep='\t', header=False, index=False)
return gzip.compress(tsv.encode())
|
import pandas as pd
import gzip
import boto3
import re
def default_key_map(key):
return re.sub('_input', '_output', key)
class S3Dest():
def __init__(self, key_map=default_key_map):
self.key_map = key_map
def skip_keys(self, bucket, source_prefix):
s3 = boto3.resource('s3')
objs = s3.Bucket(bucket).objects.filter(Prefix=self.key_map(source_prefix))
return [obj.key for obj in objs]
def put(self, data, obj):
body = self.generate_output_file(data)
dest_key = self.key_map(obj.key)
s3 = boto3.resource('s3')
s3.Object(obj.bucket_name, dest_key).put(Body=body)
def generate_output_file(self, data):
df = pd.DataFrame(data)
tsv = df.to_csv(sep='\t', header=False, index=False)
return gzip.compress(tsv.encode())
|
Make search parameter match template parameter name
|
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('q', None)
page = request.GET.get('page', 1)
# Search
if search_query:
search_results = Page.objects.live().search(search_query)
query = Query.get(search_query)
# Record hit
query.add_hit()
else:
search_results = Page.objects.none()
# Pagination
paginator = Paginator(search_results, 10)
try:
search_results = paginator.page(page)
except PageNotAnInteger:
search_results = paginator.page(1)
except EmptyPage:
search_results = paginator.page(paginator.num_pages)
return render(request, 'search/search.html', {
'search_query': search_query,
'search_results': search_results,
})
|
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# Search
if search_query:
search_results = Page.objects.live().search(search_query)
query = Query.get(search_query)
# Record hit
query.add_hit()
else:
search_results = Page.objects.none()
# Pagination
paginator = Paginator(search_results, 10)
try:
search_results = paginator.page(page)
except PageNotAnInteger:
search_results = paginator.page(1)
except EmptyPage:
search_results = paginator.page(paginator.num_pages)
return render(request, 'search/search.html', {
'search_query': search_query,
'search_results': search_results,
})
|
Add missing package name and bump version
|
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='housecanary',
version='0.5.1',
description='Client Wrapper for the HouseCanary API',
long_description=readme(),
url='http://github.com/housecanary/hc-api-python',
author='HouseCanary',
author_email='techops@housecanary.com',
license='MIT',
packages=['housecanary', 'housecanary.excel'],
install_requires=['requests','docopt', 'openpyxl'],
zip_safe=False,
test_suite='nose.collector',
tests_require=['nose', 'mock'],
scripts=['bin/hc_api_export'])
|
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='housecanary',
version='0.5',
description='Client Wrapper for the HouseCanary API',
long_description=readme(),
url='http://github.com/housecanary/hc-api-python',
author='HouseCanary',
author_email='techops@housecanary.com',
license='MIT',
packages=['housecanary'],
install_requires=['requests','docopt', 'openpyxl'],
zip_safe=False,
test_suite='nose.collector',
tests_require=['nose', 'mock'],
scripts=['bin/hc_api_export'])
|
Add comment to new safe_execute function
|
#!/usr/bin/env python
from time import sleep, time
from fabric.api import execute, task, env
import app_config
import sys
import traceback
def safe_execute(*args, **kwargs):
"""
Wrap execute() so that all exceptions are caught and logged.
"""
try:
execute(*args, **kwargs)
except:
print "ERROR [timestamp: %d]: Here's the traceback" % time()
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
del tb
@task
def deploy():
"""
Harvest data and deploy slides indefinitely
"""
while True:
safe_execute('ap.update')
safe_execute('data.load_updates', 'data/update.json')
safe_execute('liveblog.update')
safe_execute('deploy_slides')
safe_execute('deploy_big_boards')
sleep(app_config.DEPLOY_INTERVAL)
|
#!/usr/bin/env python
from time import sleep, time
from fabric.api import execute, task, env
import app_config
import sys
import traceback
def safe_execute(*args, **kwargs):
try:
execute(*args, **kwargs)
except:
print "ERROR [timestamp: %d]: Here's the traceback" % time()
ex_type, ex, tb = sys.exc_info()
traceback.print_tb(tb)
del tb
@task
def deploy():
"""
Harvest data and deploy slides indefinitely
"""
while True:
safe_execute('ap.update')
safe_execute('data.load_updates', 'data/update.json')
safe_execute('liveblog.update')
safe_execute('deploy_slides')
safe_execute('deploy_big_boards')
sleep(app_config.DEPLOY_INTERVAL)
|
parse(): Allow passing a string since we're just going to .read() the FH
|
#!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(int, re.split('[,:]', time))
return datetime.timedelta(
hours=hours,
minutes=minutes,
seconds=seconds,
milliseconds=milliseconds,
)
def parse(srt):
for match in SUBTITLE_REGEX.finditer(srt):
raw_index, raw_start, raw_end, content = match.groups()
yield Subtitle(
index=int(raw_index), start=parse_time(raw_start),
end=parse_time(raw_end), content=content,
)
|
#!/usr/bin/env python
import re
import datetime
from collections import namedtuple
SUBTITLE_REGEX = re.compile(r'''\
(\d+)
(\d+:\d+:\d+,\d+) --> (\d+:\d+:\d+,\d+)
(.+)
''')
Subtitle = namedtuple('Subtitle', ['index', 'start', 'end', 'content'])
def parse_time(time):
hours, minutes, seconds, milliseconds = map(int, re.split('[,:]', time))
return datetime.timedelta(
hours=hours,
minutes=minutes,
seconds=seconds,
milliseconds=milliseconds,
)
def parse(srt_file_handle):
for match in SUBTITLE_REGEX.finditer(srt_file_handle.read()):
raw_index, raw_start, raw_end, content = match.groups()
yield Subtitle(
index=int(raw_index), start=parse_time(raw_start),
end=parse_time(raw_end), content=content,
)
|
Clarify variable naming for below
|
'use strict'
var EventEmitter = require('events').EventEmitter
var dot = require('dot-prop')
var Symbol = require('es6-symbol')
var traverse = require('traverse')
module.exports = EventsTree
var EVENTS = Symbol('events')
function EventsTree () {
this.tree = {}
}
EventsTree.prototype.node = function node (path) {
return path ? dot.get(this.tree, path) : this.tree
}
EventsTree.prototype.at = function at (path) {
var node = this.node(path)
if (!node) {
node = {}
dot.set(this.tree, path, node)
}
if (!node[EVENTS]) {
node[EVENTS] = new EventEmitter()
}
return node[EVENTS]
}
EventsTree.prototype.below = function (path, callback) {
if (typeof path === 'function') {
callback = path
path = ''
}
var node = this.node(path)
if (!hasChildren(node)) return
traverse(node).forEach(function eachNode (node) {
var state = this
var emitter = node[EVENTS]
if (!emitter) return
var currentPath = (path ? [path] : []).concat(state.path).join('.')
callback(currentPath, emitter)
})
}
function hasChildren (node) {
return node && !!Object.keys(node).length
}
|
'use strict'
var EventEmitter = require('events').EventEmitter
var dot = require('dot-prop')
var Symbol = require('es6-symbol')
var traverse = require('traverse')
module.exports = EventsTree
var EVENTS = Symbol('events')
function EventsTree () {
this.tree = {}
}
EventsTree.prototype.node = function node (path) {
return path ? dot.get(this.tree, path) : this.tree
}
EventsTree.prototype.at = function at (path) {
var node = this.node(path)
if (!node) {
node = {}
dot.set(this.tree, path, node)
}
if (!node[EVENTS]) {
node[EVENTS] = new EventEmitter()
}
return node[EVENTS]
}
EventsTree.prototype.below = function (path, callback) {
if (typeof path === 'function') {
callback = path
path = ''
}
var node = this.node(path)
if (!hasChildren(node)) return
traverse(node).forEach(function eachNode (node) {
var state = this
var emitter = node[EVENTS]
if (!emitter) return
var fullPath = (path ? [path] : []).concat(state.path).join('.')
callback(fullPath, emitter)
})
}
function hasChildren (node) {
return node && !!Object.keys(node).length
}
|
Fix up reference to moved module.
|
compiler.modulator.compiled = def(
[
ephox.bolt.kernel.modulator.compiled,
compiler.tools.io
],
function (delegate, io) {
var create = function () {
var instance = delegate.create.apply(null, arguments);
var can = function () {
return instance.can.apply(null, arguments);
};
var get = function (id) {
var spec = instance.get.apply(null, arguments);
var url = spec.url;
var serial = spec.serial;
var render = function () {
return io.read(url);
};
var load = function (define) {
// FIX sort out implicit definition behaviour.
define(id, [], function () {});
};
return {
serial: serial,
url: url,
load: load,
render: render
};
};
return {
can: can,
get: get
};
};
return {
create: create
};
}
);
|
compiler.modulator.compiled = def(
[
ephox.bolt.module.modulator.compiled,
compiler.tools.io
],
function (delegate, io) {
var create = function () {
var instance = delegate.create.apply(null, arguments);
var can = function () {
return instance.can.apply(null, arguments);
};
var get = function (id) {
var spec = instance.get.apply(null, arguments);
var url = spec.url;
var serial = spec.serial;
var render = function () {
return io.read(url);
};
var load = function (define) {
// FIX sort out implicit definition behaviour.
define(id, [], function () {});
};
return {
serial: serial,
url: url,
load: load,
render: render
};
};
return {
can: can,
get: get
};
};
return {
create: create
};
}
);
|
Use better type definitions for the array API custom types
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack',
'SupportsBufferProtocol', 'PyCapsule']
from typing import Any, Sequence, Type, Union
from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32,
uint64, float32, float64)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = Any
Dtype = Type[Union[[int8, int16, int32, int64, uint8, uint16,
uint32, uint64, float32, float64]]]
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack',
'SupportsBufferProtocol', 'PyCapsule']
from typing import Any, Sequence, Type, Union
from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32,
uint64, float32, float64)
Array = ndarray
Device = TypeVar('device')
Dtype = Literal[int8, int16, int32, int64, uint8, uint16,
uint32, uint64, float32, float64]
SupportsDLPack = TypeVar('SupportsDLPack')
SupportsBufferProtocol = TypeVar('SupportsBufferProtocol')
PyCapsule = TypeVar('PyCapsule')
|
Fix file not found error on directory
|
import subprocess
from functools import wraps
import os
extensions = {}
def extension(f):
# keep unwrapped function
unwrapped = f
@wraps(f)
def wrapper(**kwargs):
wrapper.settings = dict(kwargs)
return unwrapped
extensions[f.__name__] = wrapper
return wrapper
@extension
def coffee(filename, data):
command = ['coffee', '-c', '-s']
bare = coffee.settings.get('bare')
if bare:
command.append('-b')
process = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate(data)
if process.returncode:
return None, err
else:
_, ext = os.path.splitext(filename)
dest = filename.replace(ext, '.js')
return dest, out
@extension
def dest(filename, data):
destination = dest.settings.get('destination')
if destination:
if not os.path.exists(destination):
os.mkdir(destination)
_, tail = os.path.split(filename)
filename = os.path.join(destination, tail)
fo = open(filename, 'w')
fo.write(data)
fo.close()
|
import subprocess
from functools import wraps
import os
extensions = {}
def extension(f):
# keep unwrapped function
unwrapped = f
@wraps(f)
def wrapper(**kwargs):
wrapper.settings = dict(kwargs)
return unwrapped
extensions[f.__name__] = wrapper
return wrapper
@extension
def coffee(filename, data):
command = ['coffee', '-c', '-s']
bare = coffee.settings.get('bare')
if bare:
command.append('-b')
process = subprocess.Popen(command, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate(data)
if process.returncode:
return None, err
else:
_, ext = os.path.splitext(filename)
dest = filename.replace(ext, '.js')
return dest, out
@extension
def dest(filename, data):
destination = dest.settings.get('destination')
if destination:
filename = os.path.join(destination, tail)
fo = open(filename, 'w')
fo.write(data)
fo.close()
|
Add failing test case regarding input.value($Element)
|
describe("value", function() {
"use strict";
var div, input;
beforeEach(function() {
div = DOM.create("div>a+a");
input = DOM.create("input[value=foo]");
});
it("should replace child element(s) from node with provided element", function() {
expect(div[0].childNodes.length).toBe(2);
expect(div.value(DOM.create("b"))).toBe(div);
expect(div[0].childNodes.length).toBe(1);
expect(div.child(0)).toHaveTag("b");
});
it("should return innerHTML string from node when called with no args", function() {
expect(div.value()).toBe("<a></a><a></a>");
});
it("should set value of text input to provided string value", function () {
expect(input.value("bar")).toBe(input);
expect(input[0].value).toBe("bar");
});
it("should set value of text input to string value of provided element", function () {
expect(input.value(DOM.create("div"))).toBe(input);
expect(input[0].value).toBe("<div>");
expect(input[0].childNodes.length).toBe(0);
});
});
|
describe("value", function() {
"use strict";
var div, input;
beforeEach(function() {
div = DOM.create("div>a+a");
input = DOM.create("input[value=foo]");
});
it("should replace child element(s) from node with provided element", function() {
expect(div[0].childNodes.length).toBe(2);
expect(div.value(DOM.create("b"))).toBe(div);
expect(div[0].childNodes.length).toBe(1);
expect(div.child(0)).toHaveTag("b");
});
it("should return innerHTML string from node when called with no args", function() {
expect(div.value()).toBe("<a></a><a></a>");
});
it("should set value of text input to provided string value", function () {
expect(input.value("bar")).toBe(input);
expect(input[0].value).toBe("bar");
});
});
|
Update quote on the Blog page
|
<div class="page-header">
<h2 class="text-center text-orange">
<?php echo i4web_title(); ?>
</h2>
<?php
if ( is_post_type_archive('i4web_portfolio') ){ //If the page displayed is the portfolio archive of the Porftolio Custom Post Type
echo '<p class="text-center">Here you will find examples of my work past, present, and maybe even the future!</p>';
}
elseif (get_post_type( $post ) == 'post'){
echo '<p class="text-center">This is the dimension of imagination. It is an area which we call the Twilight Zone.</p>';
}
elseif(is_tax()){ //Taxonomy archive pages
$description = term_description(); // grab the term description
echo '<p class="text-center">'.$description .'</p>';
}?>
<div class="header-chevron text-center">
<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/img/down-chevron.png">
</div>
</div> <!-- end page-header -->
|
<div class="page-header">
<h2 class="text-center text-orange">
<?php echo i4web_title(); ?>
</h2>
<?php
if ( is_post_type_archive('i4web_portfolio') ){ //If the page displayed is the portfolio archive of the Porftolio Custom Post Type
echo '<p class="text-center">Here you will find examples of my work past, present, and maybe even the future!</p>';
}
elseif (get_post_type( $post ) == 'post'){
echo '<p class="text-center">Blog Description Goes Here!</p>';
}
elseif(is_tax()){ //Taxonomy archive pages
$description = term_description(); // grab the term description
echo '<p class="text-center">'.$description .'</p>';
}?>
<div class="header-chevron text-center">
<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/img/down-chevron.png">
</div>
</div> <!-- end page-header -->
|
fix: Update data explorations data sets to samples
|
# importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_products__prior_df.head())
order_products__train_df = pd.read_csv('Data/order_products__train_sample.csv')
print(order_products__train_df.head())
orders_df = pd.read_csv('Data/orders_sample.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
# importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__prior_df = pd.read_csv('Data/order_products__prior.csv')
print(order_products__prior_df.head())
#n = 1384617
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__train_df = pd.read_csv('Data/order_products__train.csv')
print(order_products__train_df.head())
#n = 3421083
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
orders_df = pd.read_csv('Data/orders.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
Fix backward compatibility of migrations
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
from django.db import migrations, models
try:
import django.contrib.auth.validators
extra_kwargs = {'validators': [django.contrib.auth.validators.ASCIIUsernameValidator()]}
except ImportError:
extra_kwargs = {}
class Migration(migrations.Migration):
dependencies = [
('users', '0013_profile_event_reminder_time'),
]
operations = [
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(error_messages={'unique': 'A user with that username already exists.'},
help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.',
max_length=150, unique=True, verbose_name='username', **extra_kwargs),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-17 18:27
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0013_profile_event_reminder_time'),
]
operations = [
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.ASCIIUsernameValidator()], verbose_name='username'),
),
]
|
Add more info to interface
|
<?php
namespace Tonic\Component\ApiLayer\ModelTransformer;
/**
* Responsible for object transformation.
*/
interface ModelTransformerInterface
{
/**
* Does transformer support transformation to target class?
*
* @param object|array|\Traversable $object
* @param string $targetClass
*
* @return bool
*/
public function supports($object, $targetClass);
/**
* Transforms object to supported class.
*
* @param object|array|\Traversable $object
* @param string $targetClass
*
* @return object|object[]|array
*/
public function transform($object, $targetClass);
}
|
<?php
namespace Tonic\Component\ApiLayer\ModelTransformer;
/**
* Responsible for object transformation.
*/
interface ModelTransformerInterface
{
/**
* Does transformer support transformation to target class?
*
* @param object|array|\Traversable $object
* @param string $targetClass
*
* @return bool
*/
public function supports($object, $targetClass);
/**
* Transforms object to supported class.
*
* @param object|array|\Traversable $object
* @param string $targetClass
*
* @return object|object[]
*/
public function transform($object, $targetClass);
}
|
Allow telegram bot name to be configured
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => eien\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
'telegram-bot-api' => [
'token' => env('TELEGRAM_BOT_TOKEN'),
'username' => env('TELEGRAM_BOT_USERNAME'),
],
];
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => eien\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
'telegram-bot-api' => [
'token' => env('TELEGRAM_BOT_TOKEN'),
],
];
|
:art: Make installPackages work with buffers
|
'use babel'
import {BufferedProcess} from 'atom'
export function installPackages(packageNames, callback, failedCallback) {
const extractionRegex = /Installing (.*?) to .*? (.*)/
return new Promise(function(resolve, reject) {
let errorContents = []
const parameters = ['install'].concat(packageNames)
parameters.push('--production', '--color', 'false')
new BufferedProcess({
command: atom.packages.getApmPath(),
args: parameters,
options: {},
stdout: function(contents) {
const matches = extractionRegex.exec(contents)
if (matches[2] === '✓' || matches[2] === 'done') {
callback(matches[1])
} else {
errorContents.push("Error Installing " + matches[1] + "\n")
}
},
stderr: function(contents) {
errorContents.push(contents)
},
exit: function() {
if (errorContents.length) {
errorContents = errorContents.join('')
failedCallback(errorContents)
return reject(new Error(errorContents))
} else resolve()
}
})
})
}
|
'use babel'
import {BufferedProcess} from 'atom'
export function installPackages(packageNames, callback) {
return new Promise(function(resolve, reject) {
const stdErr = []
new BufferedProcess({
command: atom.packages.getApmPath(),
args: ['--production', 'install'].concat(packageNames),
options: {},
stdout: function(contents) {
console.log(contents)
},
stderr: function(contents) {
stdErr.push(contents)
},
exit: function() {
if (stdErr.length) {
return reject(new Error(stdErr.join('')))
} else resolve()
}
})
})
}
|
Add a test for the validate-collated tree output
|
# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2016, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
import io
import mimetypes
import os.path
import sys
import tempfile
import unittest
from lxml import etree
from ...html_parsers import HTML_DOCUMENT_NAMESPACES
from ...testing import TEST_DATA_DIR, captured_output
class CollatedSingleHTMLTestCase(unittest.TestCase):
maxDiff = None
@property
def target(self):
from ...scripts.collated_single_html.main import main
return main
@property
def path_to_xhtml(self):
return os.path.join(TEST_DATA_DIR, 'desserts-single-page.xhtml')
def test_valid(self):
return_code = self.target([self.path_to_xhtml])
self.assertEqual(return_code, 0)
def test_valid_with_tree(self):
# Capture stdout
orig_stdout = sys.stdout
self.addCleanup(setattr, sys, 'stdout', orig_stdout)
stdout = sys.stdout = io.BytesIO()
return_code = self.target([self.path_to_xhtml, '-d'])
self.assertEqual(return_code, 0)
stdout.seek(0)
self.assertIn('Fruity', stdout.read())
|
# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2016, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
import mimetypes
import os.path
import tempfile
import unittest
try:
from unittest import mock
except ImportError:
import mock
from lxml import etree
from ...html_parsers import HTML_DOCUMENT_NAMESPACES
from ...testing import TEST_DATA_DIR, captured_output
class CollatedSingleHTMLTestCase(unittest.TestCase):
maxDiff = None
@property
def target(self):
from ...scripts.collated_single_html.main import main
return main
@property
def path_to_xhtml(self):
return os.path.join(TEST_DATA_DIR, 'desserts-single-page.xhtml')
def test_valid(self):
return_code = self.target([self.path_to_xhtml])
self.assertEqual(return_code, 0)
|
Remove unneeded jinja2 import in markdown example
|
# build.py
#!/usr/bin/env python3
import os
# Markdown to HTML library
# https://pypi.org/project/Markdown/
import markdown
from staticjinja import Site
markdowner = markdown.Markdown(output_format="html5")
def md_context(template):
with open(template.filename) as f:
markdown_content = f.read()
return {'post_content_html': markdowner.convert(markdown_content)}
def render_md(site, template, **kwargs):
# Given a template such as posts/post1.md
# Determine the post's title (post1) and it's directory (posts/)
directory, fname = os.path.split(template.name)
post_title, _ = fname.split(".")
# Determine where the result will be streamed (build/posts/post1.html)
out_dir = os.path.join(site.outpath, directory)
post_fname = "{}.html".format(post_title)
out = os.path.join(out_dir, post_fname)
# Render and stream the result
if not os.path.exists(out_dir):
os.makedirs(out_dir)
post_template = site.get_template("_post.html")
post_template.stream(**kwargs).dump(out, encoding="utf-8")
site = Site.make_site(
searchpath='src',
outpath='build',
contexts=[('.*.md', md_context)],
rules = [('.*.md', render_md)],
)
site.render()
|
# build.py
#!/usr/bin/env python3
import os
import jinja2
# Markdown to HTML library
# https://pypi.org/project/Markdown/
import markdown
from staticjinja import Site
markdowner = markdown.Markdown(output_format="html5")
def md_context(template):
with open(template.filename) as f:
markdown_content = f.read()
return {'post_content_html': markdowner.convert(markdown_content)}
def render_md(site, template, **kwargs):
# Given a template such as posts/post1.md
# Determine the post's title (post1) and it's directory (posts/)
directory, fname = os.path.split(template.name)
post_title, _ = fname.split(".")
# Determine where the result will be streamed (build/posts/post1.html)
out_dir = os.path.join(site.outpath, directory)
post_fname = "{}.html".format(post_title)
out = os.path.join(out_dir, post_fname)
# Render and stream the result
if not os.path.exists(out_dir):
os.makedirs(out_dir)
post_template = site.get_template("_post.html")
post_template.stream(**kwargs).dump(out, encoding="utf-8")
site = Site.make_site(
searchpath='src',
outpath='build',
contexts=[('.*.md', md_context)],
rules = [('.*.md', render_md)],
)
site.render()
|
Fix lint issue and review comments
Change-Id: I02a53961b6411247ef06d84dad7b533cb97d89f7
|
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
# Import py.test hooks and fixtures for App Engine
from gcp.testing.appengine import (
login,
pytest_configure,
pytest_runtest_call,
run_tasks,
testbed)
import six
(login)
(pytest_configure)
(pytest_runtest_call)
(run_tasks)
(testbed)
def pytest_ignore_collect(path, config):
"""Skip App Engine tests in python 3 or if no SDK is available."""
if 'appengine/standard' in str(path):
if six.PY3:
return True
if 'GAE_SDK_PATH' not in os.environ:
return True
return False
|
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import six
# Import py.test hooks and fixtures for App Engine
from gcp.testing.appengine import (
login,
pytest_configure,
pytest_runtest_call,
run_tasks,
testbed)
(login)
(pytest_configure)
(pytest_runtest_call)
(run_tasks)
(testbed)
def pytest_ignore_collect(path, config):
"""Skip App Engine tests in python 3 and if no SDK is available."""
if 'appengine/standard' in str(path):
if six.PY3:
return True
if 'GAE_SDK_PATH' not in os.environ:
return True
return False
|
Add `-v` and `--version` flags
Closes #18
|
#!/usr/bin/env node
var path = require('path');
var findup = require('findup-sync');
var minimist = require('minimist');
var resolve = require('resolve').sync;
var logger = require('../lib/core/logger');
var argv = minimist(process.argv.slice(2), {
alias: {v: 'version'}
});
if (argv._[0] === 'init') {
require('./init')();
}
else if (argv.v) {
logger.info(require('../package.json').version);
}
else {
var base = process.cwd();
var nwitchPath;
try {
nwitchPath = resolve('nwitch', {basedir: base});
} catch (error) {
nwitchPath = findup('lib/index.js');
}
if (!nwitchPath) {
logger.error('Unable to find local nwitch.');
logger.error('Did you run `npm install nwitch`?');
}
else {
var configFile = path.resolve(base, './config.toml');
require(nwitchPath)(configFile);
}
}
|
#!/usr/bin/env node
var path = require('path');
var findup = require('findup-sync');
var minimist = require('minimist');
var resolve = require('resolve').sync;
var logger = require('../lib/core/logger');
var argv = minimist(process.argv.slice(2));
if (argv._[0] === 'init') {
require('./init')();
}
else {
var base = process.cwd();
var nwitchPath;
try {
nwitchPath = resolve('nwitch', {basedir: base});
} catch (error) {
nwitchPath = findup('lib/index.js');
}
if (!nwitchPath) {
logger.error('Unable to find local nwitch.');
logger.error('Did you run `npm install nwitch`?');
}
else {
var configFile = path.resolve(base, './config.toml');
require(nwitchPath)(configFile);
}
}
|
fix(sqlite): Update metadata filename when writing
After https://github.com/pelias/whosonfirst/pull/389 and
https://github.com/pelias/wof-admin-lookup/pull/229, WOF metafiles are
expected to follow the pattern `whosonfirst-data-${layer}-latest.csv`. We
missed the code that creates fake metafiles after exporting from SQLite.
|
const fs = require('fs');
const path = require('path');
// handler for all metatdata streams
module.exports.MetaDataFiles = function MetaDataFiles( metaDir ){
let streams = {};
this.stats = {};
this.write = function( row ){
let keys = Object.keys(row);
// first time writing to this meta file
if( !streams.hasOwnProperty( row.placetype ) ){
// create write stream
streams[row.placetype] = fs.createWriteStream(
path.join( metaDir, `whosonfirst-data-${row.placetype}-latest.csv` )
);
// init stats
this.stats[row.placetype] = 0;
// write csv header
streams[row.placetype].write( keys.join(',') + '\n' );
}
// write csv row
streams[row.placetype].write( keys.map(key => {
// quote fields containing comma or newline, escape internal quotes
// https://gist.github.com/getify/3667624
if( /[,\n]/.test( row[key] ) ) {
return '"' + row[key].replace(/\\([\s\S])|(")/g,'\\$1$2') + '"';
}
return row[key];
}).join(',') + '\n' );
// increment stats
this.stats[row.placetype]++;
};
};
|
const fs = require('fs');
const path = require('path');
// handler for all metatdata streams
module.exports.MetaDataFiles = function MetaDataFiles( metaDir ){
let streams = {};
this.stats = {};
this.write = function( row ){
let keys = Object.keys(row);
// first time writing to this meta file
if( !streams.hasOwnProperty( row.placetype ) ){
// create write stream
streams[row.placetype] = fs.createWriteStream(
path.join( metaDir, `wof-${row.placetype}-latest.csv` )
);
// init stats
this.stats[row.placetype] = 0;
// write csv header
streams[row.placetype].write( keys.join(',') + '\n' );
}
// write csv row
streams[row.placetype].write( keys.map(key => {
// quote fields containing comma or newline, escape internal quotes
// https://gist.github.com/getify/3667624
if( /[,\n]/.test( row[key] ) ) {
return '"' + row[key].replace(/\\([\s\S])|(")/g,'\\$1$2') + '"';
}
return row[key];
}).join(',') + '\n' );
// increment stats
this.stats[row.placetype]++;
};
};
|
[DEL] Remove required property on some fields
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class Employee(models.Model):
_name = 'tmc.hr.employee'
_order = 'name'
name = fields.Char()
internal_number = fields.Char(
size=3
)
docket_number = fields.Integer()
bank_account_number = fields.Char()
bank_branch = fields.Integer(
size=2
)
admission_date = fields.Date()
email = fields.Char()
active = fields.Boolean(
default=True
)
employee_title_ids = fields.Many2many(
comodel_name='tmc.hr.employee_title'
)
employee_job_id = fields.Many2one(
comodel_name='tmc.hr.employee_job'
)
office_id = fields.Many2one(
comodel_name='tmc.hr.office'
)
_sql_constraints = [
('number_uniq',
'unique(docket_number, bank_account_number)',
'Number must be unique!'),
]
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class Employee(models.Model):
_name = 'tmc.hr.employee'
_order = 'name'
name = fields.Char()
internal_number = fields.Char(
size=3,
required=True
)
docket_number = fields.Integer(
required=True
)
bank_account_number = fields.Char()
bank_branch = fields.Integer(
size=2
)
admission_date = fields.Date()
email = fields.Char()
active = fields.Boolean(
default=True
)
employee_title_ids = fields.Many2many(
comodel_name='tmc.hr.employee_title'
)
employee_job_id = fields.Many2one(
comodel_name='tmc.hr.employee_job'
)
office_id = fields.Many2one(
comodel_name='tmc.hr.office'
)
_sql_constraints = [
('number_uniq',
'unique(docket_number, bank_account_number)',
'Number must be unique!'),
]
|
Move skip link right after body tag
|
<?php
/**
* Template for header
*
* <head> section and everything up until <div id="content">
*
* @Author: Roni Laukkarinen
* @Date: 2020-05-11 13:17:32
* @Last Modified by: Roni Laukkarinen
* @Last Modified time: 2021-02-25 13:47:40
*
* @package air-light
*/
namespace Air_Light;
?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class( 'no-js' ); ?>>
<a class="skip-link screen-reader-text" href="#content"><?php echo esc_html( get_default_localization( 'Skip to content' ) ); ?></a>
<?php wp_body_open(); ?>
<div id="page" class="site">
<div class="nav-container">
<header class="site-header">
<?php get_template_part( 'template-parts/header/branding' ); ?>
<?php get_template_part( 'template-parts/header/navigation' ); ?>
</header>
</div><!-- .nav-container -->
<div class="site-content">
|
<?php
/**
* Template for header
*
* <head> section and everything up until <div id="content">
*
* @Author: Roni Laukkarinen
* @Date: 2020-05-11 13:17:32
* @Last Modified by: Timi Wahalahti
* @Last Modified time: 2020-11-19 11:24:53
*
* @package air-light
*/
namespace Air_Light;
?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class( 'no-js' ); ?>>
<?php wp_body_open(); ?>
<div id="page" class="site">
<a class="skip-link screen-reader-text" href="#content"><?php echo esc_html( get_default_localization( 'Skip to content' ) ); ?></a>
<div class="nav-container">
<header class="site-header">
<?php get_template_part( 'template-parts/header/branding' ); ?>
<?php get_template_part( 'template-parts/header/navigation' ); ?>
</header>
</div><!-- .nav-container -->
<div class="site-content">
|
Rewrite Disqus to use the new scope selection system
|
from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'read data on your behalf'),
('write', 'read and write data on your behalf'),
('admin', 'read and write data on your behalf and moderate your forums'),
]
permissions_widget = 'radio'
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
|
from oauthlib.oauth2.draft25 import utils
import foauth.providers
def token_uri(service, token, r):
params = [((u'access_token', token)), ((u'api_key', service.client_id))]
r.url = utils.add_params_to_uri(r.url, params)
return r
class Disqus(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://disqus.com/'
docs_url = 'http://disqus.com/api/docs/'
category = 'Social'
# URLs to interact with the API
authorize_url = 'https://disqus.com/api/oauth/2.0/authorize/'
access_token_url = 'https://disqus.com/api/oauth/2.0/access_token/'
api_domain = 'disqus.com'
available_permissions = [
(None, 'read data on your behalf'),
('write', 'write data on your behalf'),
('admin', 'moderate your forums'),
]
bearer_type = token_uri
def get_scope_string(self, scopes):
# Disqus doesn't follow the spec on this point
return ','.join(scopes)
def get_user_id(self, key):
r = self.api(key, self.api_domain, u'/api/3.0/users/details.json')
return r.json[u'response'][u'id']
|
Change example from Null Island to Santiago, Chile
|
var point = require('turf-point');
/**
* Takes a bounding box and a cell depth and outputs points in a grid.
*
* @module turf/grid
* @param {Array<number>} extent extent in [xmin, ymin, xmax, ymax] order
* @param {Number} depth how many cells to output
* @return {FeatureCollection} grid as FeatureCollection with {@link Point} features
* @example
* var extent = [-70.823364, -33.553984, -70.473175, -33.302986];
* var depth = 10;
*
* var grid = turf.grid(extent, depth);
*
* //=grid
*/
module.exports = function(extents, depth) {
var xmin = extents[0];
var ymin = extents[1];
var xmax = extents[2];
var ymax = extents[3];
var interval = (xmax - xmin) / depth;
var coords = [];
var fc = {
type: 'FeatureCollection',
features: []
};
for (var x=0; x<=depth; x++){
for (var y=0;y<=depth; y++){
fc.features.push(point((x * interval) + xmin, (y * interval) + ymin));
}
}
return fc;
}
|
var point = require('turf-point');
/**
* Takes a bounding box and a cell depth and outputs points in a grid.
*
* @module turf/grid
* @param {Array<number>} extent extent in [xmin, ymin, xmax, ymax] order
* @param {Number} depth how many cells to output
* @return {FeatureCollection} grid as FeatureCollection with {@link Point} features
* @example
* var grid = turf.grid([0,0,10,10], 10);
* //=grid
*/
module.exports = function(extents, depth) {
var xmin = extents[0];
var ymin = extents[1];
var xmax = extents[2];
var ymax = extents[3];
var interval = (xmax - xmin) / depth;
var coords = [];
var fc = {
type: 'FeatureCollection',
features: []
};
for (var x=0; x<=depth; x++){
for (var y=0;y<=depth; y++){
fc.features.push(point((x * interval) + xmin, (y * interval) + ymin));
}
}
return fc;
}
|
Add unit test for make_thumb_url()
|
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""Unit tests."""
import unittest
import commonsdownloader
class TestCommonsDownloader(unittest.TestCase):
"""Testing methods from commonsdownloader."""
def test_clean_up_filename(self):
"""Test clean_up_filename."""
values = [('Example.jpg', 'Example.jpg'),
('Example.jpg ', 'Example.jpg'),
(' Example.jpg', 'Example.jpg'),
('My Example.jpg', 'My_Example.jpg')]
for (input_value, expected_value) in values:
self.assertEqual(commonsdownloader.clean_up_filename(input_value),
expected_value)
def test_make_thumb_url(self):
"""Test make_thumb_url."""
input_value = ('My_Example.jpg', 100)
expected_value = "http://commons.wikimedia.org/w/thumb.php?f=My_Example.jpg&width=100"
output = commonsdownloader.make_thumb_url(*input_value)
self.assertEqual(output, expected_value)
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""Unit tests."""
import unittest
import commonsdownloader
class TestCommonsDownloader(unittest.TestCase):
"""Testing methods from commonsdownloader."""
def test_clean_up_filename(self):
"""Test clean_up_filename."""
values = [('Example.jpg', 'Example.jpg'),
('Example.jpg ', 'Example.jpg'),
(' Example.jpg', 'Example.jpg'),
('My Example.jpg', 'My_Example.jpg')]
for (input_value, expected_value) in values:
self.assertEqual(commonsdownloader.clean_up_filename(input_value),
expected_value)
if __name__ == "__main__":
unittest.main()
|
Clear all caches after refreshing records
|
package org.strangeforest.tcb.stats.jobs;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.*;
import org.strangeforest.tcb.stats.service.*;
@Component
@Profile("jobs")
public class RefreshRecordsJob {
@Autowired private DataLoadCommand dataLoadCommand;
@Autowired private DataService dataService;
private static final Logger LOGGER = LoggerFactory.getLogger(RefreshRecordsJob.class);
@Scheduled(cron = "${tennis-stats.jobs.refresh-records:0 5 6 * * MON}")
public void refreshRecords() {
if (dataLoadCommand.execute("RefreshRecords", "-rr", "-c 1", "-rp 100") == 0) {
try {
dataLoadCommand.execute("Vacuum", "-vc", "-c 1");
}
finally {
clearCaches();
}
}
}
private void clearCaches() {
int cacheCount = dataService.clearCaches(".*");
LOGGER.info("{} cache(s) cleared.", cacheCount);
}
}
|
package org.strangeforest.tcb.stats.jobs;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.*;
import org.strangeforest.tcb.stats.service.*;
@Component
@Profile("jobs")
public class RefreshRecordsJob {
@Autowired private DataLoadCommand dataLoadCommand;
@Autowired private DataService dataService;
private static final Logger LOGGER = LoggerFactory.getLogger(RefreshRecordsJob.class);
@Scheduled(cron = "${tennis-stats.jobs.refresh-records:0 5 6 * * MON}")
public void refreshRecords() {
if (dataLoadCommand.execute("RefreshRecords", "-rr", "-c 1", "-rp 100") == 0) {
try {
dataLoadCommand.execute("Vacuum", "-vc", "-c 1");
}
finally {
clearCaches();
}
}
}
private void clearCaches() {
int cacheCount = dataService.clearCaches("Records.*") + dataService.clearCaches("PlayerRecords.*");
LOGGER.info("{} cache(s) cleared.", cacheCount);
}
}
|
Add required newline at end of file
|
// file: example/approle.js
process.env.DEBUG = 'node-vault'; // switch on debug mode
const vault = require('./../src/index')();
const mountPoint = 'approle';
const roleName = 'test-role';
vault.auths()
.then((result) => {
if (result.hasOwnProperty('approle/')) return undefined;
return vault.enableAuth({
mount_point: mountPoint,
type: 'approle',
description: 'Approle auth',
});
})
.then(() => vault.addApproleRole({ role_name: roleName, policies: 'dev-policy, test-policy' }))
.then(() => Promise.all([vault.getApproleRoleId({ role_name: roleName }),
vault.getApproleRoleSecret({ role_name: roleName })])
)
.then((result) => {
const roleId = result[0].data.role_id;
const secretId = result[1].data.secret_id;
return vault.approleLogin({ role_id: roleId, secret_id: secretId });
})
.then((result) => {
console.log(result);
})
.catch((err) => console.error(err.message));
|
// file: example/approle.js
process.env.DEBUG = 'node-vault'; // switch on debug mode
const vault = require('./../src/index')();
const mountPoint = 'approle';
const roleName = 'test-role';
vault.auths()
.then((result) => {
if (result.hasOwnProperty('approle/')) return undefined;
return vault.enableAuth({
mount_point: mountPoint,
type: 'approle',
description: 'Approle auth',
});
})
.then(() => vault.addApproleRole({ role_name: roleName, policies: 'dev-policy, test-policy' }))
.then(() => Promise.all([vault.getApproleRoleId({ role_name: roleName }),
vault.getApproleRoleSecret({ role_name: roleName })])
)
.then((result) => {
const roleId = result[0].data.role_id;
const secretId = result[1].data.secret_id;
return vault.approleLogin({ role_id: roleId, secret_id: secretId });
})
.then((result) => {
console.log(result);
})
.catch((err) => console.error(err.message));
|
Add 'inversedBy' attribute on ManyToOne association with Tag entity
Without this attribute the entity mapping information won't be considered valid.
|
<?php
namespace Fogs\TaggingBundle\Entity;
use \FPN\TagBundle\Entity\Tagging as BaseTagging;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\UniqueConstraint;
/**
* Fogs\TaggingBundle\Entity\Tagging
*
* @ORM\Table(uniqueConstraints={@UniqueConstraint(name="tagging_idx", columns={"tag_id", "resource_type", "resource_id"})})
* @ORM\Entity
*/
class Tagging extends BaseTagging
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Tag", inversedBy="tagging")
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
**/
protected $tag;
}
|
<?php
namespace Fogs\TaggingBundle\Entity;
use \FPN\TagBundle\Entity\Tagging as BaseTagging;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\UniqueConstraint;
/**
* Fogs\TaggingBundle\Entity\Tagging
*
* @ORM\Table(uniqueConstraints={@UniqueConstraint(name="tagging_idx", columns={"tag_id", "resource_type", "resource_id"})})
* @ORM\Entity
*/
class Tagging extends BaseTagging
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Tag")
* @ORM\JoinColumn(name="tag_id", referencedColumnName="id")
**/
protected $tag;
}
|
Fix typeTest for deep attrs
|
'use strict';
const { mapValues, get } = require('../../utilities');
const isObject = function (value) {
return value.constructor === Object;
};
const isObjectArray = function (value) {
return Array.isArray(value) && value.every(isObject);
};
const typeTest = ({ test: testFunc, message }) => name => ({
test (value) {
const val = get(value, name.split('.'));
if (val == null) { return true; }
return testFunc(val);
},
message: `'${name}' must be ${message}`,
});
const typeCheckers = {
stringTest: {
test: value => typeof value === 'string',
message: 'a string',
},
booleanTest: {
test: value => typeof value === 'boolean',
message: 'true or false',
},
numberTest: {
test: value => Number.isFinite(value),
message: 'a number',
},
integerTest: {
test: value => Number.isInteger(value),
message: 'an integer',
},
objectTest: {
test: isObject,
message: 'an object',
},
objectArrayTest: {
test: isObjectArray,
message: 'an array of objects',
},
objectOrArrayTest: {
test: value => isObject(value) || isObjectArray(value),
message: 'an array of objects',
},
};
const typeTests = mapValues(typeCheckers, typeTest);
module.exports = {
...typeTests,
};
|
'use strict';
const { mapValues } = require('../../utilities');
const isObject = function (value) {
return value.constructor === Object;
};
const isObjectArray = function (value) {
return Array.isArray(value) && value.every(isObject);
};
const typeTest = ({ test: testFunc, message }) => name => ({
test ({ [name]: value }) {
if (value == null) { return true; }
return testFunc(value);
},
message: `'${name}' must be ${message}`,
});
const typeCheckers = {
stringTest: {
test: value => typeof value === 'string',
message: 'a string',
},
booleanTest: {
test: value => typeof value === 'boolean',
message: 'true or false',
},
numberTest: {
test: value => Number.isFinite(value),
message: 'a number',
},
integerTest: {
test: value => Number.isInteger(value),
message: 'an integer',
},
objectTest: {
test: isObject,
message: 'an object',
},
objectArrayTest: {
test: isObjectArray,
message: 'an array of objects',
},
objectOrArrayTest: {
test: value => isObject(value) || isObjectArray(value),
message: 'an array of objects',
},
};
const typeTests = mapValues(typeCheckers, typeTest);
module.exports = {
...typeTests,
};
|
Allow filtering by author name
|
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
from quotations.apps.quotations import models as quotations_models
from quotations.libs.auth import MethodAuthentication
from quotations.libs.serializers import Serializer
class BaseMeta(object):
serializer = Serializer()
authentication = MethodAuthentication()
authorization = DjangoAuthorization()
class AuthorResource(ModelResource):
class Meta(BaseMeta):
queryset = quotations_models.Author.objects.all()
resource_name = 'authors'
filtering = {
'name': ['exact', 'contains']
}
class QuotationResource(ModelResource):
author = fields.ForeignKey(AuthorResource, 'author', full=True)
class Meta(BaseMeta):
queryset = quotations_models.Quotation.objects.all()
resource_name = 'quotations'
filtering = {
'text': ['contains'],
'author': ALL_WITH_RELATIONS
}
|
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.resources import ModelResource, ALL_WITH_RELATIONS
from quotations.apps.quotations import models as quotations_models
from quotations.libs.auth import MethodAuthentication
from quotations.libs.serializers import Serializer
class BaseMeta(object):
serializer = Serializer()
authentication = MethodAuthentication()
authorization = DjangoAuthorization()
class AuthorResource(ModelResource):
class Meta(BaseMeta):
queryset = quotations_models.Author.objects.all()
resource_name = 'authors'
class QuotationResource(ModelResource):
author = fields.ForeignKey(AuthorResource, 'author', full=True)
class Meta(BaseMeta):
queryset = quotations_models.Quotation.objects.all()
resource_name = 'quotations'
filtering = {
'text': ['contains'],
'author': ALL_WITH_RELATIONS
}
|
Fix detection on Windows 10 Anniversary
|
const DRAW_SIZE = 32;
function newContext() {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = DRAW_SIZE * 2;
return canvas.getContext('2d');
}
export function prepareCanvasContext(context) {
if (!context) {
context = newContext();
context.fillStyle = "#000";
context.font = `${DRAW_SIZE}px "Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol",Arial`;
} else {
context.clearRect(0, 0, DRAW_SIZE * 2, DRAW_SIZE * 2);
}
return context;
}
export function canDrawCharacter(character, context) {
context = prepareCanvasContext(context);
context.fillText(character, 0, DRAW_SIZE);
return context.getImageData(DRAW_SIZE / 2 + 2, DRAW_SIZE / 2, 1, 1).data[0] !== 0;
}
export function getCharacterWidth(character, context) {
context = prepareCanvasContext(context);
return context.measureText(character).width;
}
|
const DRAW_SIZE = 32;
function newContext() {
const canvas = document.createElement('canvas');
canvas.width = canvas.height = DRAW_SIZE * 2;
return canvas.getContext('2d');
}
export function prepareCanvasContext(context) {
if (!context) {
context = newContext();
context.fillStyle = "#000";
context.font = `${DRAW_SIZE}px "Apple Color Emoji","Segoe UI","Segoe UI Emoji","Segoe UI Symbol",Arial`;
} else {
context.clearRect(0, 0, DRAW_SIZE * 2, DRAW_SIZE * 2);
}
return context;
}
export function canDrawCharacter(character, context) {
context = prepareCanvasContext(context);
context.fillText(character, 0, DRAW_SIZE);
return context.getImageData(DRAW_SIZE / 2, DRAW_SIZE / 2, 1, 1).data[0] !== 0;
}
export function getCharacterWidth(character, context) {
context = prepareCanvasContext(context);
return context.measureText(character).width;
}
|
Use config to load available id providers
|
"use strict";
var db = require('../../models');
var config = require('../../config');
var authHelper = require('../../lib/auth-helper');
module.exports = function(app) {
var logger = app.get('logger');
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('/protected', authHelper.ensureAuthenticated, function(req, res) {
res.send('protected');
});
app.get('/auth', function(req, res) {
res.render('./auth/provider_list.ejs');
});
for (var idp in config.identity_providers) {
if (config.identity_providers[idp].enabled) {
logger.info(idp + ' authentication enabled');
require('./'+idp)(app);
}
}
};
|
"use strict";
var db = require('../../models');
var config = require('../../config');
var authHelper = require('../../lib/auth-helper');
module.exports = function(app) {
var logger = app.get('logger');
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('/protected', authHelper.ensureAuthenticated, function(req, res) {
res.send('protected');
});
app.get('/auth', function(req, res) {
res.render('./auth/provider_list.ejs');
});
if (config.identity_providers.facebook.enabled) {
logger.info('Facebook authentication enabled');
require('./facebook')(app);
}
if (config.identity_providers.github.enabled) {
logger.info('Github authentication enabled');
require('./github')(app);
}
if (config.identity_providers.local.enabled) {
logger.info('Local authentication enabled');
require('./local')(app);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.