text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Watch e2e tests for changes and lint
|
(function(){
'use strict';
var gulp = require('gulp');
var paths = require('./_paths');
gulp.task('watch', function() {
var lr = require('gulp-livereload');
lr.listen();
gulp.watch(paths.fonts, ['copy-fonts']);
gulp.watch(paths.styles.concat(paths.icons), ['sass']);
gulp.watch(paths.images, ['images']);
gulp.watch(paths.vendor_static, ['copy-vendor-js']);
gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
gulp.watch('tests/**/*.js', ['lint']);
gulp.watch(paths.guidance, ['guidance-build']);
// watch built files and send reload event
gulp.watch(paths.dest + '**/*').on('change', lr.changed);
});
})();
|
(function(){
'use strict';
var gulp = require('gulp');
var paths = require('./_paths');
gulp.task('watch', function() {
var lr = require('gulp-livereload');
lr.listen();
gulp.watch(paths.fonts, ['copy-fonts']);
gulp.watch(paths.styles.concat(paths.icons), ['sass']);
gulp.watch(paths.images, ['images']);
gulp.watch(paths.vendor_static, ['copy-vendor-js']);
gulp.watch(paths.src + 'javascripts/**/*', ['lint', 'js-concat']);
gulp.watch(paths.guidance, ['guidance-build']);
// watch built files and send reload event
gulp.watch(paths.dest + '**/*').on('change', lr.changed);
});
})();
|
Set the hostname when it localhost
|
import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url) or 'localhost'
os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname
password = keyring.get_password(hostname, username)
if not password:
prompt_tmpl = "{username}@{hostname}'s password: "
prompt = prompt_tmpl.format(username=username, hostname=hostname)
password = getpass.getpass(prompt)
keyring.set_password(hostname, username, password)
def get_vr(username=None):
username = os.environ['VELOCIRAPTOR_USERNAME']
base = os.environ['VELOCIRAPTOR_URL']
set_password(base, username)
return Velociraptor(base=base, username=username)
|
import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url) or 'localhost'
password = keyring.get_password(hostname, username)
if not password:
prompt_tmpl = "{username}@{hostname}'s password: "
prompt = prompt_tmpl.format(username=username, hostname=hostname)
password = getpass.getpass(prompt)
keyring.set_password(hostname, username, password)
def get_vr(username=None):
username = os.environ['VELOCIRAPTOR_USERNAME']
base = os.environ['VELOCIRAPTOR_URL']
set_password(base, username)
return Velociraptor(base=base, username=username)
|
Disable test that is non-deterministically failing.
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# test helper.run_tests function
import warnings
from .. import helper
from ... import _get_test_runner
from .. helper import pytest
# run_tests should raise ValueError when asked to run on a module it can't find
def test_module_not_found():
with helper.pytest.raises(ValueError):
_get_test_runner().run_tests('fake.module')
# run_tests should raise ValueError when passed an invalid pastebin= option
def test_pastebin_keyword():
with helper.pytest.raises(ValueError):
_get_test_runner().run_tests(pastebin='not_an_option')
# tests that tests are only run in Python 3 out of the 2to3'd build (otherwise
# a syntax error would occur)
try:
from .run_after_2to3 import test_run_after_2to3
except SyntaxError:
def test_run_after_2to3():
helper.pytest.fail("Not running the 2to3'd tests!")
# TODO: Temporarily disabled, as this seems to non-deterministically fail
# def test_deprecation_warning():
# with pytest.raises(DeprecationWarning):
# warnings.warn('test warning', DeprecationWarning)
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# test helper.run_tests function
import warnings
from .. import helper
from ... import _get_test_runner
from .. helper import pytest
# run_tests should raise ValueError when asked to run on a module it can't find
def test_module_not_found():
with helper.pytest.raises(ValueError):
_get_test_runner().run_tests('fake.module')
# run_tests should raise ValueError when passed an invalid pastebin= option
def test_pastebin_keyword():
with helper.pytest.raises(ValueError):
_get_test_runner().run_tests(pastebin='not_an_option')
# tests that tests are only run in Python 3 out of the 2to3'd build (otherwise
# a syntax error would occur)
try:
from .run_after_2to3 import test_run_after_2to3
except SyntaxError:
def test_run_after_2to3():
helper.pytest.fail("Not running the 2to3'd tests!")
def test_deprecation_warning():
with pytest.raises(DeprecationWarning):
warnings.warn('test warning', DeprecationWarning)
|
WIP: Fix adaptive example with LivePlot
|
import matplotlib.pyplot as plt
from bluesky import RunEngine
from bluesky.scans import AdaptiveAscan
from bluesky.examples import Mover, SynGauss
from bluesky.callbacks import LivePlot, LiveTable
from bluesky.tests.utils import setup_test_run_engine
#plt.ion()
RE = setup_test_run_engine()
motor = Mover('motor', ['pos'])
det = SynGauss('det', motor, 'pos', center=0, Imax=1, sigma=1)
#fig, ax = plt.subplots()
#ax.set_xlim([-15, 5])
#ax.set_ylim([0, 2])
# Point the function to our axes above, and specify what to plot.
#my_plotter = LivePlot('det', 'pos')
table = LiveTable(['det', 'pos'])
ad_scan = AdaptiveAscan(motor, [det], 'det', -15, 5, .01, 1, .05, True)
RE(ad_scan, subscriptions={'all': [table]}) #, my_plotter})
|
import matplotlib.pyplot as plt
from bluesky import RunEngine, Mover, SynGauss
from bluesky.examples import adaptive_scan
RE = RunEngine()
RE.verbose = False
motor = Mover('motor', ['pos'])
det = SynGauss('det', motor, 'pos', center=0, Imax=1, sigma=1)
def live_scalar_plotter(ax, y, x):
x_data, y_data = [], []
line, = ax.plot([], [], 'ro', markersize=10)
def update_plot(doc):
# Update with the latest data.
x_data.append(doc['data'][x])
y_data.append(doc['data'][y])
line.set_data(x_data, y_data)
# Rescale and redraw.
ax.relim(visible_only=True)
ax.autoscale_view(tight=True)
ax.figure.canvas.draw()
ax.figure.canvas.flush_events()
return update_plot
fig, ax = plt.subplots()
plt.show()
ax.set_xlim([-15, 5])
ax.set_ylim([0, 2])
# Point the function to our axes above, and specify what to plot.
my_plotter = live_scalar_plotter(ax, 'det', 'pos')
ad_scan = adaptive_scan(motor, det, 'pos', 'det', -15, 5, .01, 1, .05)
RE.run(ad_scan, subscriptions={'event': my_plotter})
|
Fix receiving an error message for python2 & 3
|
# -*- coding: utf-8 -*-
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(str(type(e)) + str(e.args))
|
# -*- coding: utf-8 -*-
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(e.message)
|
[sil-bug-reducer] Refactor adding subparsers given that all subparsers have a common swift_build_dir arg.
|
#!/usr/bin/env python
import argparse
import opt_bug_reducer
import random_bug_finder
def add_subparser(subparsers, module, name):
sparser = subparsers.add_parser(name)
sparser.add_argument('swift_build_dir',
help='Path to the swift build directory '
'containing tools to use')
module.add_parser_arguments(sparser)
def main():
parser = argparse.ArgumentParser(description="""\
A program for reducing sib/sil crashers""")
subparsers = parser.add_subparsers()
add_subparser(subparsers, opt_bug_reducer, 'opt')
add_subparser(subparsers, random_bug_finder, 'random-search')
args = parser.parse_args()
args.func(args)
main()
|
#!/usr/bin/env python
import argparse
import opt_bug_reducer
import random_bug_finder
def main():
parser = argparse.ArgumentParser(description="""\
A program for reducing sib/sil crashers""")
subparsers = parser.add_subparsers()
opt_subparser = subparsers.add_parser("opt")
opt_subparser.add_argument('swift_build_dir',
help='Path to the swift build directory '
'containing tools to use')
opt_bug_reducer.add_parser_arguments(opt_subparser)
random_search_subparser = subparsers.add_parser("random-search")
random_search_subparser.add_argument('swift_build_dir',
help='Path to the swift build '
'directory containing tools to use')
random_bug_finder.add_parser_arguments(random_search_subparser)
args = parser.parse_args()
args.func(args)
main()
|
Remove references to src/images folder
|
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@gatsbyjs`,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
module.exports = {
siteMetadata: {
title: `Gatsby Default Starter`,
description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
author: `@gatsbyjs`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
Add an extra explenation on how to use curl on this view.
|
from djangorestframework.views import View
from djangorestframework.permissions import PerUserThrottling, IsAuthenticated
from django.core.urlresolvers import reverse
class PermissionsExampleView(View):
"""
A container view for permissions examples.
"""
def get(self, request):
return [{'name': 'Throttling Example', 'url': reverse('throttled-resource')},
{'name': 'Logged in example', 'url': reverse('loggedin-resource')},]
class ThrottlingExampleView(View):
"""
A basic read-only View that has a **per-user throttle** of 10 requests per minute.
If a user exceeds the 10 requests limit within a period of one minute, the
throttle will be applied until 60 seconds have passed since the first request.
"""
permissions = ( PerUserThrottling, )
throttle = '10/min'
def get(self, request):
"""
Handle GET requests.
"""
return "Successful response to GET request because throttle is not yet active."
class LoggedInExampleView(View):
"""
You can login with **'test', 'test'.** or use curl:
`curl -X GET -H 'Accept: application/json' -u test:test http://localhost:8000/permissions-example`
"""
permissions = (IsAuthenticated, )
def get(self, request):
return 'Logged in or not?'
|
from djangorestframework.views import View
from djangorestframework.permissions import PerUserThrottling, IsAuthenticated
from django.core.urlresolvers import reverse
class PermissionsExampleView(View):
"""
A container view for permissions examples.
"""
def get(self, request):
return [{'name': 'Throttling Example', 'url': reverse('throttled-resource')},
{'name': 'Logged in example', 'url': reverse('loggedin-resource')},]
class ThrottlingExampleView(View):
"""
A basic read-only View that has a **per-user throttle** of 10 requests per minute.
If a user exceeds the 10 requests limit within a period of one minute, the
throttle will be applied until 60 seconds have passed since the first request.
"""
permissions = ( PerUserThrottling, )
throttle = '10/min'
def get(self, request):
"""
Handle GET requests.
"""
return "Successful response to GET request because throttle is not yet active."
class LoggedInExampleView(View):
"""
You can login with **'test', 'test'.**
"""
permissions = (IsAuthenticated, )
def get(self, request):
return 'Logged in or not?'
|
Add call for widget tool tips
|
package info.u_team.u_team_test.screen;
import com.mojang.blaze3d.matrix.MatrixStack;
import info.u_team.u_team_core.gui.UContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
public class BasicFluidInventoryScreen extends UContainerScreen<BasicFluidInventoryContainer> {
public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
}
@Override
public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
func_230446_a_(matrixStack);
super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
func_230459_a_(matrixStack, mouseX, mouseY);
}
}
|
package info.u_team.u_team_test.screen;
import com.mojang.blaze3d.matrix.MatrixStack;
import info.u_team.u_team_core.gui.UContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
public class BasicFluidInventoryScreen extends UContainerScreen<BasicFluidInventoryContainer> {
public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
}
@Override
public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
func_230446_a_(matrixStack);
super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
// buttons.forEach(button -> button.renderToolTip(mouseX, mouseY)); TODO nessessary??
func_230459_a_(matrixStack, mouseX, mouseY);
}
}
|
Add custom message for invalid url
|
import Messages from 'ember-cp-validations/validators/messages';
export default Messages.extend({
blank: 'Поле не может быть пустым',
email: 'Значение должно быть адресом электронной почты',
emailNotFound: 'Адрес не найден',
notANumber: 'Значение должно быть числом',
notAnInteger: 'Значение должно быть целым числом',
positive: 'Значение должно быть положительным числом',
invalid: 'Поле заполнено неверно',
url: 'Значение не является ссылкой'
});
|
import Messages from 'ember-cp-validations/validators/messages';
export default Messages.extend({
blank: 'Поле не может быть пустым',
email: 'Значение должно быть адресом электронной почты',
emailNotFound: 'Адрес не найден',
notANumber: 'Значение должно быть числом',
notAnInteger: 'Значение должно быть целым числом',
positive: 'Значение должно быть положительным числом',
invalid: 'Поле заполнено неверно'
});
|
[New] Remove development mode warning log
|
import Vue from './lib/vue';
import VueWrapper from './VueWrapper';
import './lib/matchesPolyfill';
Vue.config.productionTip = false;
function createElem() {
const elem = document.createElement('div');
document.body.appendChild(elem);
return elem;
}
export default function mount(component, options = {}) {
let elem = null;
const attachToDocument = options.attachToDocument;
if (attachToDocument) {
elem = createElem();
delete options.attachToDocument; // eslint-disable-line no-param-reassign
}
const Constructor = Vue.extend(component);
const vm = new Constructor(options);
if (options.slots) {
Object.keys(options.slots).forEach((key) => {
vm.$slots[key] = vm.$createElement(options.slots[key]);
});
}
vm.$mount(elem);
return new VueWrapper(vm, attachToDocument);
}
|
import Vue from './lib/vue';
import VueWrapper from './VueWrapper';
import './lib/matchesPolyfill';
function createElem() {
const elem = document.createElement('div');
document.body.appendChild(elem);
return elem;
}
export default function mount(component, options = {}) {
let elem = null;
const attachToDocument = options.attachToDocument;
if (attachToDocument) {
elem = createElem();
delete options.attachToDocument; // eslint-disable-line no-param-reassign
}
const Constructor = Vue.extend(component);
const vm = new Constructor(options);
if (options.slots) {
Object.keys(options.slots).forEach((key) => {
vm.$slots[key] = vm.$createElement(options.slots[key]);
});
}
vm.$mount(elem);
return new VueWrapper(vm, attachToDocument);
}
|
Fix retrieval of artifact names
Signed-off-by: Aurélien Bompard <bceb368e7f2cb351af47298f32034f0587bbe4a6@bompard.org>
|
import logging
from fastapi import Depends
from httpx import AsyncClient
from ..core.config import Settings, get_settings
log = logging.getLogger(__name__)
class DistGitClient:
def __init__(self, settings):
self.client = AsyncClient(base_url=settings.services.distgit_url, timeout=None)
async def get_projects(self, pattern):
response = await self.client.get(
"/api/0/projects",
params={
"pattern": f"*{pattern}*",
"short": "true",
"fork": "false",
},
)
response.raise_for_status()
result = response.json()
return result["projects"]
def get_distgit_client(settings: Settings = Depends(get_settings)):
return DistGitClient(settings)
|
import logging
from fastapi import Depends
from httpx import AsyncClient
from ..core.config import Settings, get_settings
log = logging.getLogger(__name__)
class DistGitClient:
def __init__(self, settings):
self.client = AsyncClient(base_url=settings.services.distgit_url, timeout=None)
async def get_projects(self, pattern):
response = await self.client.get(
"/api/0/projects",
params={
"pattern": f"*{pattern}*",
"short": "true",
"fork": "false",
},
)
response.raise_for_status()
result = response.json()
return [project["name"] for project in result["projects"]]
def get_distgit_client(settings: Settings = Depends(get_settings)):
return DistGitClient(settings)
|
Install Blog when example data is wanted.
|
<?php
namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
/**
* Validates and saves the data from the modules form
*
* @author Wouter Sioen <wouter.sioen@wijs.be>
*/
class ModulesHandler
{
public function process(Form $form, Request $request)
{
if (!$request->isMethod('POST')) {
return false;
}
$form->handleRequest($request);
if ($form->isValid()) {
return $this->processValidForm($form, $request);
}
return false;
}
public function processValidForm(Form $form, $request)
{
$session = $request->getSession();
$data = $form->getData();
if ($data['example_data'] === true && !in_array('Blog', $data['modules'])) {
$data['modules'][] = 'Blog';
}
$session->set('modules', $data['modules']);
$session->set('example_data', $data['example_data']);
$session->set('different_debug_email', $data['different_debug_email']);
$session->set('debug_email', $data['debug_email']);
return true;
}
}
|
<?php
namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
/**
* Validates and saves the data from the modules form
*
* @author Wouter Sioen <wouter.sioen@wijs.be>
*/
class ModulesHandler
{
public function process(Form $form, Request $request)
{
if (!$request->isMethod('POST')) {
return false;
}
$form->handleRequest($request);
if ($form->isValid()) {
return $this->processValidForm($form, $request);
}
return false;
}
public function processValidForm(Form $form, $request)
{
$session = $request->getSession();
$data = $form->getData();
$session->set('modules', $data['modules']);
$session->set('example_data', $data['example_data']);
$session->set('different_debug_email', $data['different_debug_email']);
$session->set('debug_email', $data['debug_email']);
return true;
}
}
|
Add a default value to the constructor.
svn commit r3127
|
<?php
require_once 'Swat/SwatOption.php';
/**
* A class representing a divider in a flydown
*
* This class is for semantic purposed only. The flydown handles all the
* displaying of dividers and regular flydown options.
*
* @package Swat
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatFlydownDivider extends SwatOption
{
/**
* Creates a flydown option
*
* @param mixed $value value of the option. This defaults to null.
* @param string $title displayed title of the divider. This defaults to
* two em dashes.
*/
public function __construct($value = null, $title = null)
{
if ($title === null)
$title = str_repeat('—', 6);
$this->value = $value;
$this->title = $title;
}
}
?>
|
<?php
require_once 'Swat/SwatOption.php';
/**
* A class representing a divider in a flydown
*
* This class is for semantic purposed only. The flydown handles all the
* displaying of dividers and regular flydown options.
*
* @package Swat
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatFlydownDivider extends SwatOption
{
/**
* Creates a flydown option
*
* @param mixed $value value of the option.
* @param string $title displayed title of the divider. This defaults to
* two em dashes.
*/
public function __construct($value, $title = null)
{
if ($title === null)
$title = str_repeat('—', 6);
$this->value = $value;
$this->title = $title;
}
}
?>
|
Allow any newer pandas version
Co-authored-by: Sabine Haas <7a4a302f5a1f49bb6bebf9ec4d25cae6930e4972@rl-institut.de>
|
#! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7dev',
author='oemof developer group',
url='https://oemof.org/',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
long_description=read('README.rst'),
packages=find_packages(),
install_requires=['numpy >= 1.7.0, < 1.17',
'pandas >= 0.18.0'],
package_data={
'demandlib': [os.path.join('bdew_data', '*.csv')],
'demandlib.examples': ['*.csv']},
)
|
#! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7dev',
author='oemof developer group',
url='https://oemof.org/',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
long_description=read('README.rst'),
packages=find_packages(),
install_requires=['numpy >= 1.7.0, < 1.17',
'pandas >= 0.18.0, < 1.2'],
package_data={
'demandlib': [os.path.join('bdew_data', '*.csv')],
'demandlib.examples': ['*.csv']},
)
|
Update the send to slack listener to allow users to customise the message
|
<?php
namespace Michaeljennings\Snapshot\Listeners;
use League\Event\EventInterface;
use Maknz\Slack\Client;
use Michaeljennings\Snapshot\Exceptions\EndPointNotSetException;
class SendToSlack extends Listener
{
/**
* Check if slack is enabled, if so send the snapshot to the relevant
* channel.
*
* @param EventInterface $event
* @throws EndPointNotSetException
*/
public function handle(EventInterface $event)
{
if ($this->config['slack']['enabled']) {
if (empty($this->config['slack']['endpoint'])) {
throw new EndPointNotSetException("You must set the endpoint for your slack channel.");
}
$client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']);
$client->send($this->getMessage($event->getSnapshot()));
}
}
/**
* Get the slack message for the snapshot. If you wish to use markdown
* then set the allow_markdown config option to true.
*
* @param mixed $snapshot
* @return string
*/
protected function getMessage($snapshot)
{
return 'A new snapshot has been captured. #' . $snapshot->getId();
}
}
|
<?php
namespace Michaeljennings\Snapshot\Listeners;
use League\Event\EventInterface;
use Maknz\Slack\Client;
use Michaeljennings\Snapshot\Exceptions\EndPointNotSetException;
class SendToSlack extends Listener
{
/**
* Check if slack is enabled, if so send the snapshot to the relevant
* channel.
*
* @param EventInterface $event
* @throws EndPointNotSetException
*/
public function handle(EventInterface $event)
{
if ($this->config['slack']['enabled']) {
if (empty($this->config['slack']['endpoint'])) {
throw new EndPointNotSetException("You must set the endpoint for your slack channel.");
}
$client = new Client($this->config['slack']['endpoint'], $this->config['slack']['settings']);
$snapshot = $event->getSnapshot();
$client->send('A new snapshot has been captured. #' . $snapshot->getId());
}
}
}
|
Change callback into external function
|
const path = require('path')
const fs = require('fs')
const { readFile } = require('./fs.utils')
const { log } = require('./log.utils')
module.exports = exports = configFilename => {
return (modules, options) => {
readFile(configFilename)
.then(data => JSON.parse(data).folder_path)
.then(processModuleData(modules))
.then(data => console.log(JSON.stringify(data, null, 2)))
}
}
function processModuleData(moduleNames) {
return folderPath => {
return moduleNames
.map(name => {
const addr = path.join(folderPath, 'files', name)
const file = fs.readFileSync(path.join(addr, 'settings.json'))
let settings = []
try {
settings = JSON.parse(file)
} catch(e) {
log({ type: 'warn', message: `Not able to load settings file for "${name}" module.` })
}
return { name, folder: addr, settings }
})
.filter(moduleConf => moduleConf.settings.length > 0)
}
}
|
const path = require('path')
const fs = require('fs')
const { readFile } = require('./fs.utils')
const { log } = require('./log.utils')
module.exports = exports = configFilename => {
return (modules, options) => {
readFile(configFilename)
.then(data => JSON.parse(data).folder_path)
.then(folderPath => {
return modules
.map(name => {
const addr = path.join(folderPath, 'files', name)
const file = fs.readFileSync(path.join(addr, 'settings.json'))
let settings = []
try {
settings = JSON.parse(file)
} catch(e) {
log({ type: 'warn', message: `Not able to load settings file for "${name}" module.` })
}
return { name, folder: addr, settings }
})
.filter(moduleConf => moduleConf.settings.length > 0)
})
.then(data => console.log(JSON.stringify(data)))
}
}
|
Add missing commas in res.send() calls
|
/**
* Get documentation URL
*/
exports.getDocUrl = function (req, res) {
res.sendBody('Documentation for this API can be found at http://github.com/thebinarypenguin/tasty');
};
/**
* Get all bookmarks
*/
exports.getAllBookmarks = function (req, res, params) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Create new bookmark
*/
exports.createBookmark = function (req, res, body) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Get specified bookmark
*/
exports.getBookmark = function (req, res, id, params) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Update specified bookmark
*/
exports.updateBookmark = function (req, res, id, body) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Delete specified bookmark
*/
exports.deleteBookmark = function (req, res, id) {
res.send(501, {}, {message: "I'm just a stub."});
};
|
/**
* Get documentation URL
*/
exports.getDocUrl = function (req, res) {
res.sendBody('Documentation for this API can be found at http://github.com/thebinarypenguin/tasty');
};
/**
* Get all bookmarks
*/
exports.getAllBookmarks = function (req, res, params) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Create new bookmark
*/
exports.createBookmark = function (req, res, body) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Get specified bookmark
*/
exports.getBookmark = function (req, res, id, params) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Update specified bookmark
*/
exports.updateBookmark = function (req, res, id, body) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Delete specified bookmark
*/
exports.deleteBookmark = function (req, res, id) {
res.send(501, {} {message: "I'm just a stub."});
};
|
Break if the collection is sorted
|
"""
This is pure python implementation of bubble sort algorithm
For doctests run following command:
python -m doctest -v bubble_sort.py
or
python3 -m doctest -v bubble_sort.py
For manual testing run:
python bubble_sort.py
"""
from __future__ import print_function
def bubble_sort(collection):
"""Pure implementation of bubble sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bubble_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([])
[]
>>> bubble_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length):
swapped = False
for j in range(length-1):
if collection[j] > collection[j+1]:
swapped = True
collection[j], collection[j+1] = collection[j+1], collection[j]
if not swapped: break # Stop iteration if the collection is sorted.
return collection
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(bubble_sort(unsorted))
|
"""
This is pure python implementation of bubble sort algorithm
For doctests run following command:
python -m doctest -v bubble_sort.py
or
python3 -m doctest -v bubble_sort.py
For manual testing run:
python bubble_sort.py
"""
from __future__ import print_function
def bubble_sort(collection):
"""Pure implementation of bubble sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bubble_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([])
[]
>>> bubble_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length):
for j in range(length-1):
if collection[j] > collection[j+1]:
collection[j], collection[j+1] = collection[j+1], collection[j]
return collection
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(bubble_sort(unsorted))
|
Add dependency on parse, be more explicit in supported Python versions.
|
import os
import os.path
import sys
from setuptools import find_packages, setup
requirements = ['parse>=1.1.5', 'PyYAML']
major, minor = sys.version_info[:2]
if major == 2 and minor < 7:
requirements.append('argparse')
setup(
name='behave',
version='1.0',
description='A Cucumber-like BDD tool',
author='Benno Rice',
author_email='benno@jeamland.net',
url='http://github.com/jeamland/behave',
packages=find_packages(),
package_data={'behave': ['languages.yml']},
scripts=['bin/behave'],
install_requires=requirements,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Testing",
"License :: OSI Approved :: BSD License",
],
)
|
import os
import os.path
import sys
from setuptools import find_packages, setup
requirements = ['PyYAML']
major, minor = sys.version_info[:2]
if major == 2 and minor < 7:
requirements.append('argparse')
setup(
name='behave',
version='1.0',
description='A Cucumber-like BDD tool',
author='Benno Rice',
author_email='benno@jeamland.net',
url='http://github.com/jeamland/behave',
packages=find_packages(),
package_data={'behave': ['languages.yml']},
scripts=['bin/behave'],
install_requires=requirements,
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Testing",
"License :: OSI Approved :: BSD License",
],
)
|
Adjust bigInputCard to receive a cardStyle and cardClass args
|
import m from 'mithril';
const bigInputCard = {
view(ctrl, args) {
const cardClass = args.cardClass || '.w-row.u-marginbottom-30.card.card-terciary.padding-redactor-description.text.optional.project_about_html.field_with_hint';
return m(cardClass, {style: (args.cardStyle||{})}, [
m('div', [
m('label.field-label.fontweight-semibold.fontsize-base', args.label),
(args.label_hint ? m('label.hint.fontsize-smallest.fontcolor-secondary', args.label_hint) : '')
]),
m('div', args.children)
]);
}
}
export default bigInputCard;
|
import m from 'mithril';
const bigInputCard = {
view(ctrl, args) {
const cardClass = '.w-row.u-marginbottom-30.card.card-terciary.padding-redactor-description.text.optional.project_about_html.field_with_hint';
return m(cardClass, [
m('div', [
m('label.field-label.fontweight-semibold.fontsize-base', args.label),
(args.label_hint ? m('label.hint.fontsize-smallest.fontcolor-secondary', args.label_hint) : '')
]),
m('div', args.children)
]);
}
}
export default bigInputCard;
|
Remove app from registry on uninstall
|
import filePaths from '../utils/file-paths';
import cp from 'child_process';
import path from 'path';
import app from 'app';
import AutoLauncher from './auto-launcher';
class SquirrelEvents {
check(options) {
if (options.squirrelInstall) {
this.spawnSquirrel(['--createShortcut', app.getPath('exe')], app.exit);
return true;
}
if (options.squirrelUpdated || options.squirrelObsolete) {
app.exit(0);
return true;
}
if (options.squirrelUninstall) {
AutoLauncher.disable(function(err) {
if (err) {
logError(err);
}
this.spawnSquirrel(['--removeShortcut', app.getPath('exe')], app.exit);
});
return true;
}
return false;
}
spawnSquirrel(args, callback) {
const squirrelExec = path.join(filePaths.getAppDir(), 'Update.exe');
log('spawning', squirrelExec, args);
const child = cp.spawn(squirrelExec, args, { detached: true });
child.on('close', function(code) {
if (code) {
logError(squirrelExec, 'exited with code', code);
}
callback(code || 0);
});
}
}
export default new SquirrelEvents();
|
import filePaths from '../utils/file-paths';
import cp from 'child_process';
import path from 'path';
import app from 'app';
class SquirrelEvents {
check(options) {
if (options.squirrelInstall) {
this.spawnSquirrel(['--createShortcut', app.getPath('exe')], app.exit);
return true;
}
if (options.squirrelUpdated || options.squirrelObsolete) {
app.exit(0);
return true;
}
if (options.squirrelUninstall) {
this.spawnSquirrel(['--removeShortcut', app.getPath('exe')], app.exit);
return true;
}
return false;
}
spawnSquirrel(args, callback) {
const squirrelExec = path.join(filePaths.getAppDir(), 'Update.exe');
log('spawning', squirrelExec, args);
const child = cp.spawn(squirrelExec, args, { detached: true });
child.on('close', function(code) {
if (code) {
logError(squirrelExec, 'exited with code', code);
}
callback(code || 0);
});
}
}
export default new SquirrelEvents();
|
Disable apc cache for building
|
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
//if (isset($_SERVER['HTTP_CLIENT_IP'])
// || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
// || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
//) {
// header('HTTP/1.0 403 Forbidden');
// exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
//}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('test', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
//if (isset($_SERVER['HTTP_CLIENT_IP'])
// || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
// || !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'))
//) {
// header('HTTP/1.0 403 Forbidden');
// exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
//}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
$loader = new \Symfony\Component\ClassLoader\ApcClassLoader('sf2', $loader);
$loader->register(true);
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('test', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Use system import for code splitting
|
import {subscribe, getTodo} from '../todo'
let graphArea
const unsubscribe = {
store: null,
todo: null,
}
export default toggleGraph
function toggleGraph() {
if (graphArea) {
graphArea.remove()
graphArea = null
unsubscribe.store()
unsubscribe.todo()
return false
} else {
graphArea = document.createElement('div')
document.body.querySelector('.graph-area-container').appendChild(graphArea)
const {storage} = getTodo()
loadAndRenderGraph(graphArea, storage)
updateTodoSubscription()
updateStoreSubscription(storage)
return true
}
}
function updateTodoSubscription() {
if (unsubscribe.todo) {
unsubscribe.todo()
}
unsubscribe.todo = subscribe(function onTodoUpdate() {
const {storage} = getTodo()
updateStoreSubscription(storage)
loadAndRenderGraph(graphArea, storage)
})
}
function updateStoreSubscription(store) {
if (unsubscribe.store) {
unsubscribe.store()
}
unsubscribe.store = store.subscribe(function onStoreUpdate() {
loadAndRenderGraph(graphArea, store)
})
}
function loadAndRenderGraph (graphArea, store) {
System.import('./render').then(renderGraphComponent => {
const renderGraph = renderGraphComponent.default
renderGraph(graphArea, store)
})
}
|
import {subscribe, getTodo} from '../todo'
import renderGraph from './render'
let graphArea
const unsubscribe = {
store: null,
todo: null,
}
export default toggleGraph
function toggleGraph() {
if (graphArea) {
graphArea.remove()
graphArea = null
unsubscribe.store()
unsubscribe.todo()
return false
} else {
graphArea = document.createElement('div')
document.body.querySelector('.graph-area-container').appendChild(graphArea)
const {storage} = getTodo()
renderGraph(graphArea, storage)
updateTodoSubscription()
updateStoreSubscription(storage)
return true
}
}
function updateTodoSubscription() {
if (unsubscribe.todo) {
unsubscribe.todo()
}
unsubscribe.todo = subscribe(function onTodoUpdate() {
const {storage} = getTodo()
updateStoreSubscription(storage)
renderGraph(graphArea, storage)
})
}
function updateStoreSubscription(store) {
if (unsubscribe.store) {
unsubscribe.store()
}
unsubscribe.store = store.subscribe(function onStoreUpdate() {
renderGraph(graphArea, store)
})
}
|
Stop the search of '.editorconfig' files in the parent container
|
package org.eclipse.ec4e.internal.resource;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Path;
import org.eclipse.ec4j.core.ResourcePaths.ResourcePath;
import org.eclipse.ec4j.core.Resources.Resource;
/**
* A {@link ResourcePath} implementation based on {@link IContainer}.
*
* @author <a href="https://github.com/ppalaga">Peter Palaga</a>
*/
public class ContainerResourcePath implements ResourcePath {
private final IContainer container;
ContainerResourcePath(IContainer container) {
this.container = container;
}
@Override
public ResourcePath getParent() {
if (container.getType() == IResource.PROJECT) {
// Stop the search of '.editorconfig' files in the parent container
return null;
}
IContainer parent = container.getParent();
return parent == null ? null : new ContainerResourcePath(parent);
}
@Override
public String getPath() {
return container.getLocation().toString().replaceAll("[\\\\]", "/");
}
@Override
public boolean hasParent() {
IContainer parent = container.getParent();
return parent != null;
}
@Override
public Resource resolve(String name) {
IFile child = container.getFile(new Path(name));
return new FileResource(child);
}
}
|
package org.eclipse.ec4e.internal.resource;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Path;
import org.eclipse.ec4j.core.ResourcePaths.ResourcePath;
import org.eclipse.ec4j.core.Resources.Resource;
/**
* A {@link ResourcePath} implementation based on {@link IContainer}.
*
* @author <a href="https://github.com/ppalaga">Peter Palaga</a>
*/
public class ContainerResourcePath implements ResourcePath {
private final IContainer container;
ContainerResourcePath(IContainer container) {
this.container = container;
}
@Override
public ResourcePath getParent() {
IContainer parent = container.getParent();
if (parent == null || parent.getType() == IResource.ROOT) {
return null;
}
// Search '.editorconfig' files only in project and folders container.
return new ContainerResourcePath(parent);
}
@Override
public String getPath() {
return container.getLocation().toString().replaceAll("[\\\\]", "/");
}
@Override
public boolean hasParent() {
IContainer parent = container.getParent();
return parent != null;
}
@Override
public Resource resolve(String name) {
IFile child = container.getFile(new Path(name));
return new FileResource(child);
}
}
|
Fix RegExp pattern to match single quote imports
|
// Inspired from https://github.com/markokajzer/discord-soundbot
// MIT License - Copyright (c) 2020 Marko Kajzer
const path = require('path');
const replace = require('replace-in-file');
const tsconfig = require('../tsconfig.json');
const pathAliases = tsconfig.compilerOptions.paths;
const from = Object.keys(pathAliases)
.map(key => new RegExp(`${key.split('/*')[0]}/[^'"]*`, 'g'));
const to = {};
Object.entries(pathAliases).forEach(([key, value]) => {
const match = key.split('/*')[0];
to[match] = value[0].split('/*')[0];
});
const options = {
files: ['dist/**/*.@(j|t)s'],
from,
to: (...args) => {
const [match, , , filename] = args;
const [replacePattern, ...file] = match.split('/');
const normalizedRelativePath = path.relative(
path.join(process.cwd(), path.dirname(filename)),
path.join(process.cwd(), 'dist', to[replacePattern], ...file)
);
const relativePath = normalizedRelativePath.startsWith('.')
? normalizedRelativePath
: `./${normalizedRelativePath}`;
return relativePath.replace(/\\/g, '/');
}
};
replace.sync(options);
|
// Inspired from https://github.com/markokajzer/discord-soundbot
// MIT License - Copyright (c) 2020 Marko Kajzer
const path = require('path');
const replace = require('replace-in-file');
const tsconfig = require('../tsconfig.json');
const pathAliases = tsconfig.compilerOptions.paths;
const from = Object.keys(pathAliases)
.map(key => new RegExp(`${key.split('/*')[0]}/[^"]*`, 'g'));
const to = {};
Object.entries(pathAliases).forEach(([key, value]) => {
const match = key.split('/*')[0];
to[match] = value[0].split('/*')[0];
});
const options = {
files: ['dist/**/*.@(j|t)s'],
from,
to: (...args) => {
const [match, , , filename] = args;
const [replacePattern, ...file] = match.split('/');
const normalizedRelativePath = path.relative(
path.join(process.cwd(), path.dirname(filename)),
path.join(process.cwd(), 'dist', to[replacePattern], ...file)
);
const relativePath = normalizedRelativePath.startsWith('.')
? normalizedRelativePath
: `./${normalizedRelativePath}`;
return relativePath.replace(/\\/g, '/');
}
};
replace.sync(options);
|
Handle placeholder deletion before animation fallback
|
(function () {
var logoPath = '/customize/CryptPad_logo.svg';
if (location.pathname === '/' || location.pathname === '/index.html') {
logoPath = '/customize/CryptPad_logo_hero.svg';
}
var elem = document.createElement('div');
elem.setAttribute('id', 'placeholder');
elem.innerHTML = [
'<div class="placeholder-logo-container">',
'<img class="placeholder-logo" src="' + logoPath + '">',
'</div>',
'<div class="placeholder-message-container">',
'<p>Loading...</p>',
'</div>'
].join('');
document.addEventListener('DOMContentLoaded', function() {
document.body.appendChild(elem);
// fallback if CSS animations not available
setTimeout(() => {
try {
document.querySelector('.placeholder-logo-container').style.opacity = 100;
document.querySelector('.placeholder-message-container').style.opacity = 100;
} catch (e) {}
}, 3000);
});
}());
|
(function () {
var logoPath = '/customize/CryptPad_logo.svg';
if (location.pathname === '/' || location.pathname === '/index.html') {
logoPath = '/customize/CryptPad_logo_hero.svg';
}
var elem = document.createElement('div');
elem.setAttribute('id', 'placeholder');
elem.innerHTML = [
'<div class="placeholder-logo-container">',
'<img class="placeholder-logo" src="' + logoPath + '">',
'</div>',
'<div class="placeholder-message-container">',
'<p>Loading...</p>',
'</div>'
].join('');
document.addEventListener('DOMContentLoaded', function() {
document.body.appendChild(elem);
// fallback if CSS animations not available
setTimeout(() => {
document.querySelector('.placeholder-logo-container').style.opacity = 100;
document.querySelector('.placeholder-message-container').style.opacity = 100;
}, 3000);
});
}());
|
Add $ModuleManager to local space (CallModule)
|
<?php
require_once 'Utils.php';
class WhatsBotCaller
{
private $ModuleManager = null;
private $Whatsapp = null;
private $Utils = null;
public function __construct(&$MDLM, WhatsappBridge &$WPB)
{
if($MDLM != null && !($MDLM instanceof ModuleManager)) // Podríamos testear en cada método si $this->ModuleManager está o no instanciado correctamente
trigger_error('You must pass a ModuleManager to WhatsBotCaller', E_USER_ERROR);
$this->ModuleManager = &$MDLM;
$this->Whatsapp = &$WPB;
$this->Utils = new Utils();
}
public function CallModule($ModuleName, $Filename, $Params, $Me, $ID, $Time, $From, $Name, $Text)
{
$ModuleManager = &$this->ModuleManager; // add to !reload, !update, etc...
$Whatsapp = &$this->Whatsapp;
$Utils = &$this->Utils;
return include $Filename;
}
public function CallDomainModule($ModuleName, $Filename, $ParsedURL, $URL, $Me, $ID, $Time, $From, $Name, $Text)
{
$Whatsapp = &$this->Whatsapp;
$Utils = &$this->Utils;
return include $Filename;
}
}
|
<?php
require_once 'Utils.php';
class WhatsBotCaller
{
private $ModuleManager = null;
private $Whatsapp = null;
private $Utils = null;
public function __construct(&$MDLM, WhatsappBridge &$WPB)
{
if($MDLM != null && !($MDLM instanceof ModuleManager)) // Podríamos testear en cada método si $this->ModuleManager está o no instanciado correctamente
trigger_error('You must pass a ModuleManager to WhatsBotCaller', E_USER_ERROR);
$this->ModuleManager = &$MDLM;
$this->Whatsapp = &$WPB;
$this->Utils = new Utils();
}
public function CallModule($ModuleName, $Filename, $Params, $Me, $ID, $Time, $From, $Name, $Text)
{
//$ModuleManager = &$this->ModuleManager; // add to !reload, !update, etc...
$Whatsapp = &$this->Whatsapp;
$Utils = &$this->Utils;
return include $Filename;
}
public function CallDomainModule($ModuleName, $Filename, $ParsedURL, $URL, $Me, $ID, $Time, $From, $Name, $Text)
{
$Whatsapp = &$this->Whatsapp;
$Utils = &$this->Utils;
return include $Filename;
}
}
|
Fix ceilometerclient mocks for 2.8.0 release
The function name changed in Iae7d60e1cf139b79e74caf81ed7bdbd0bf2bc473.
Change-Id: I1bbe3f32090b9b1fd7508b1b26665bceeea21f49
|
#
# 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.
from ceilometerclient.v2 import client as cc
from heat.tests import common
from heat.tests import utils
class CeilometerClientPluginTest(common.HeatTestCase):
def test_create(self):
self.patchobject(cc.Client, '_get_redirect_client')
context = utils.dummy_context()
plugin = context.clients.client_plugin('ceilometer')
client = plugin.client()
self.assertIsNotNone(client.alarms)
|
#
# 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.
from ceilometerclient.v2 import client as cc
from heat.tests import common
from heat.tests import utils
class CeilometerClientPluginTest(common.HeatTestCase):
def test_create(self):
self.patchobject(cc.Client, '_get_alarm_client')
context = utils.dummy_context()
plugin = context.clients.client_plugin('ceilometer')
client = plugin.client()
self.assertIsNotNone(client.alarms)
|
Add generic Python 3 trove classifier
|
from setuptools import setup
setup(
name='tangled.auth',
version='0.1a4.dev0',
description='Tangled auth integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.auth/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.auth',
'tangled.auth.tests',
],
install_requires=[
'tangled.web>=0.1a5',
],
extras_require={
'dev': [
'tangled.web[dev]>=0.1a5',
],
},
entry_points="""
[tangled.scripts]
auth = tangled.auth.command:Command
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
from setuptools import setup
setup(
name='tangled.auth',
version='0.1a4.dev0',
description='Tangled auth integration',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.auth/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.auth',
'tangled.auth.tests',
],
install_requires=[
'tangled.web>=0.1a5',
],
extras_require={
'dev': [
'tangled.web[dev]>=0.1a5',
],
},
entry_points="""
[tangled.scripts]
auth = tangled.auth.command:Command
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Mark 'tvnamer-gui' as a GUI script
|
#!/usr/bin/env python3
from setuptools import setup
with open("README.rst") as fd:
long_description = fd.read()
setup(
name="tvnamer",
version="1.0.0-dev",
description="Utility to rename lots of TV video files using the TheTVDB.",
long_description=long_description,
author="Tom Leese",
author_email="tom@tomleese.me.uk",
url="https://github.com/tomleese/tvnamer",
packages=["tvnamer"],
test_suite="tests",
install_requires=[
"pytvdbapi",
"pyside"
],
entry_points={
"console_scripts": [
"tvnamer = tvnamer:main",
"tvnamer-cli = tvnamer.cli:main"
],
'gui_scripts': [
"tvnamer-gui = tvnamer.gui:main",
]
},
classifiers=[
"Topic :: Internet",
"Topic :: Multimedia :: Video",
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4"
]
)
|
#!/usr/bin/env python3
from setuptools import setup
with open("README.rst") as fd:
long_description = fd.read()
setup(
name="tvnamer",
version="1.0.0-dev",
description="Utility to rename lots of TV video files using the TheTVDB.",
long_description=long_description,
author="Tom Leese",
author_email="tom@tomleese.me.uk",
url="https://github.com/tomleese/tvnamer",
packages=["tvnamer"],
test_suite="tests",
install_requires=[
"pytvdbapi",
"pyside"
],
entry_points={
"console_scripts": [
"tvnamer = tvnamer:main",
"tvnamer-cli = tvnamer.cli:main",
"tvnamer-gui = tvnamer.gui:main",
]
},
classifiers=[
"Topic :: Internet",
"Topic :: Multimedia :: Video",
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4"
]
)
|
Add dry run argument to CLI (-n)
|
#! /usr/bin/env node
'use strict';
var inquirer = require('inquirer');
var list = require('cli-list');
var generator = Object.freeze(require('./generator'));
var questions = Object.freeze(require('./cli.config.json').questions);
var args = list(process.argv.slice(2));
var cliArguments = {};
if (args[0].indexOf('-n') !== -1)
cliArguments.dryRun = true;
/*
* - Removes trailing slash
* - Converts to lower case
* - Trims
*/
// TODO: Add test for this
var formatString = function (val) {
if (val.charAt(val.length - 1) === '/')
val = val.substring(0, val.length - 1);
return val.toLowerCase().trim();
};
var questionsWithFilter = questions.map(function(questionsObj) {
if (questionsObj.filter === 'formatDist') {
questionsObj.filter = formatString;
}
return questionsObj;
});
inquirer.prompt(questionsWithFilter).then(function(answers) {
if (!cliArguments.dryRun)
generator(answers);
});
|
#! /usr/bin/env node
'use strict';
var inquirer = require('inquirer');
var generator = Object.freeze(require('./generator'));
var questions = Object.freeze(require('./cli.config.json').questions);
/*
* - Removes trailing slash
* - Converts to lower case
* - Trims
*/
// TODO: Add test for this
var formatString = function (val) {
if (val.charAt(val.length - 1) === '/')
val = val.substring(0, val.length - 1);
return val.toLowerCase().trim();
};
var questionsWithFilter = questions.map(function(questionsObj) {
if (questionsObj.filter === 'formatDist') {
questionsObj.filter = formatString;
}
return questionsObj;
});
inquirer.prompt(questionsWithFilter).then(function(answers) {
generator(answers);
});
|
Check if a wallet is loaded before accessing private states
|
function AppRun(AppConstants, $rootScope, $timeout, Wallet, Alert, $transitions) {
'ngInject';
// Change page title based on state
$transitions.onSuccess({ to: true }, (transition) => {
$rootScope.setPageTitle(transition.router.globals.current.title);
// Enable tooltips globally
$timeout( function() {
$('[data-toggle="tooltip"]').tooltip()
});
});
// Check if a wallet is loaded before accessing private states
$transitions.onStart({
to: (state) => {
return (state.name !== 'app.home') && (state.name !== 'app.login') && (state.name !== 'app.signup');
}
}, (transition) => {
if (!Wallet.current) {
Alert.noWalletLoaded();
return transition.router.stateService.target('app.home');
}
});
// Helper method for setting the page's title
$rootScope.setPageTitle = (title) => {
$rootScope.pageTitle = '';
if (title) {
$rootScope.pageTitle += title;
$rootScope.pageTitle += ' \u2014 ';
}
$rootScope.pageTitle += AppConstants.appName;
};
}
export default AppRun;
|
function AppRun(AppConstants, $rootScope, $timeout, Wallet) {
'ngInject';
// change page title based on state
$rootScope.$on('$stateChangeSuccess', (event, toState) => {
$rootScope.setPageTitle(toState.title);
// enable tooltips globally
$timeout( function() {
$('[data-toggle="tooltip"]').tooltip()
});
});
// Helper method for setting the page's title
$rootScope.setPageTitle = (title) => {
$rootScope.pageTitle = '';
if (title) {
$rootScope.pageTitle += title;
$rootScope.pageTitle += ' \u2014 ';
}
$rootScope.pageTitle += AppConstants.appName;
};
}
export default AppRun;
|
Refactor strings to template literals in Presto UI
|
/* global __dirname */
module.exports = {
entry: {
'index': `${__dirname}/index.jsx`,
'query': `${__dirname}/query.jsx`,
'plan': `${__dirname}/plan.jsx`,
'embedded_plan': `${__dirname}/embedded_plan.jsx`,
'stage': `${__dirname}/stage.jsx`,
'worker': `${__dirname}/worker.jsx`,
},
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/../dist',
filename: '[name].js'
}
};
|
module.exports = {
entry: {
'index': __dirname +'/index.jsx',
'query': __dirname +'/query.jsx',
'plan': __dirname +'/plan.jsx',
'embedded_plan': __dirname +'/embedded_plan.jsx',
'stage': __dirname +'/stage.jsx',
'worker': __dirname +'/worker.jsx',
},
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/../dist',
filename: '[name].js'
}
};
|
Add inflection and toml as dependencies for the project
|
from setuptools import setup
setup(name='openarc',
version='0.5.0',
description='Functional reactive graph backed by PostgreSQL',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Topic :: Database',
],
keywords='graph orm frp finance trading',
url='http://github.com/kchoudhu/openarc',
author='Kamil Choudhury',
author_email='kamil.choudhury@anserinae.net',
license='BSD',
packages=['openarc'],
install_requires=[
'gevent',
'inflection',
'msgpack-python',
'psycopg2',
'toml',
'zmq'
],
include_package_data=True,
zip_safe=False)
|
from setuptools import setup
setup(name='openarc',
version='0.5.0',
description='Functional reactive graph backed by PostgreSQL',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Topic :: Database',
],
keywords='graph orm frp finance trading',
url='http://github.com/kchoudhu/openarc',
author='Kamil Choudhury',
author_email='kamil.choudhury@anserinae.net',
license='BSD',
packages=['openarc'],
install_requires=[
'gevent',
'msgpack-python',
'psycopg2',
'zmq'
],
include_package_data=True,
zip_safe=False)
|
Add title var for template
|
<?php
/**
* # Page View Model
*
* Automaticly load page based on slug, throw 404 if page doesn't exist.
*
* @package Flatfile
* @category View Model
* @author Ziopod <ziopod@gmail.com>
* @copyright (c) 2013-2014 Ziopod
* @license http://opensource.org/licenses/MIT
**/
class Flatfile_View_Page extends View_App{
/**
* @var object Flafile page object
**/
public $page;
public function __construct()
{
// Try to load Flatfile
try
{
$this->page = new Model_Page(Request::initial()->param('slug'));
}
catch (Kohana_Exception $e)
{
throw HTTP_Exception::factory(404, __("Unable to find URI :uri"), array(':uri' => Request::initial()->uri() ));
}
$this->title = $this->page->title;
$this->author = $this->page->author;
$this->license = $this->page->license;
$this->description = $this->page->description;
}
}
|
<?php
/**
* # Page View Model
*
* Automaticly load page based on slug, throw 404 if page doesn't exist.
*
* @package Flatfile
* @category View Model
* @author Ziopod <ziopod@gmail.com>
* @copyright (c) 2013-2014 Ziopod
* @license http://opensource.org/licenses/MIT
**/
class Flatfile_View_Page extends View_App{
/**
* @var object Flafile page object
**/
public $page;
public function __construct()
{
// Try to load Flatfile
try
{
$this->page = new Model_Page(Request::initial()->param('slug'));
}
catch (Kohana_Exception $e)
{
throw HTTP_Exception::factory(404, __("Unable to find URI :uri"), array(':uri' => Request::initial()->uri() ));
}
$this->author = $this->page->author;
$this->license = $this->page->license;
$this->description = $this->page->description;
}
}
|
Increase splash screen time to 2 seconds.
|
package in.testpress.testpress.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import in.testpress.testpress.R;
public class SplashScreenActivity extends Activity {
// Splash screen timer
private static final int SPLASH_TIME_OUT = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// This method will be executed once the timer is over
// Start app main activity
Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
|
package in.testpress.testpress.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import in.testpress.testpress.R;
public class SplashScreenActivity extends Activity {
// Splash screen timer
private static final int SPLASH_TIME_OUT = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// This method will be executed once the timer is over
// Start app main activity
Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
|
Add locust testing box to allowed IPs, and get the SSL redirect from the environment so that it can be turned off for load testing
pep8
|
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.environ.get('SENTRY_DSN'),
}
ip_check = os.environ.get('RESTRICT_IPS', False)
RESTRICT_IPS = ip_check == 'True' or ip_check == '1'
ALLOWED_IPS = ['54.229.170.70']
ALLOWED_IP_RANGES = ['165.225.80.0/22', '193.240.203.32/29', '94.119.64.0/24', '178.208.163.0/24']
ssl_check = os.environ.get('SSL_REDIRECT', False)
SECURE_SSL_REDIRECT = ssl_check == 'True' or ssl_check == '1'
|
from .base import *
DEBUG = False
ALLOWED_HOSTS = ['selling-online-overseas.export.great.gov.uk']
ADMINS = (('David Downes', 'david@downes.co.uk'),)
MIDDLEWARE_CLASSES += [
'core.middleware.IpRestrictionMiddleware',
]
INSTALLED_APPS += [
'raven.contrib.django.raven_compat'
]
RAVEN_CONFIG = {
'dsn': os.environ.get('SENTRY_DSN'),
}
ip_check = os.environ.get('RESTRICT_IPS', False)
RESTRICT_IPS = ip_check == 'True' or ip_check == '1'
ALLOWED_IPS = []
ALLOWED_IP_RANGES = ['165.225.80.0/22', '193.240.203.32/29', '94.119.64.0/24', '178.208.163.0/24']
SECURE_SSL_REDIRECT = True
|
Mark instance list as staff-only, and give it a view name
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^instances/$", staff_member_required(views.InstanceListView.as_view()),
name="badge_instance_list"),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
)
|
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from . import views
from django.contrib.admin.views.decorators import staff_member_required
urlpatterns = patterns(
"",
url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"),
url(r"^issued/$", "badgekit_webhooks.views.badge_issued_hook",
name="badge_issued_hook"),
url(r"^instances/$", views.InstanceListView.as_view()),
url(r"^claim/([-A-Za-z0-9_]+)/$", 'badgekit_webhooks.views.claim_page'),
url(r"^claim/([-A-Za-z0-9_]+)/email/(html|text)$", 'badgekit_webhooks.views.show_claim_email',
name="show_claim_email"),
url(r"^issue/$", staff_member_required(views.SendClaimCodeView.as_view()),
name="badge_issue_form"),
url(r"^claimcode/([-A-Za-z.0-9_]+)/$",
views.ClaimCodeClaimView.as_view(), name='claimcode_claim'),
url(r"^badges/$", "badgekit_webhooks.views.list_badges_view", name="badges_list"),
)
|
Use flask's redirect() method to go to result link
|
from flask import Flask, render_template, redirect
from setup_cardsets import CardOperations
co = CardOperations()
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/rules')
def rules():
return render_template('rules.html')
@app.route('/setup')
def setup():
return render_template('setup.html')
@app.route('/toss/<int:cardcount>')
def toss(cardcount):
co.cardset(cardcount)
return render_template('toss.html')
@app.route('/begin')
def begin():
try:
co.toss_result()
return render_template('pages/begin.html')
except Exception as detail:
print detail
@app.route('/game')
def game():
co.update_page()
co.page_no = 1
return render_template('pages/game.html')
@app.route('/game/<statval>')
def game_move(statval):
try:
completed = co.compare(int(statval))
if not completed:
co.update_page()
return render_template('pages/game.html')
else:
return redirect('/result')
except Exception as detail:
print detail
@app.route('/result')
def result():
co.update_completion()
return render_template('pages/result.html')
if __name__ == '__main__':
app.run()
|
from flask import Flask, render_template
from setup_cardsets import CardOperations
co = CardOperations()
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/rules')
def rules():
return render_template('rules.html')
@app.route('/setup')
def setup():
return render_template('setup.html')
@app.route('/toss/<int:cardcount>')
def toss(cardcount):
co.cardset(cardcount)
return render_template('toss.html')
@app.route('/begin')
def begin():
try:
co.toss_result()
return render_template('pages/begin.html')
except Exception as detail:
print detail
@app.route('/game')
def game():
co.update_page()
co.page_no = 1
return render_template('pages/game.html')
@app.route('/game/<statval>')
def game_move(statval):
try:
completed = co.compare(int(statval))
if not completed:
co.update_page()
return render_template('pages/game.html')
else:
co.update_completion()
return render_template('pages/result.html')
except Exception as detail:
print detail
if __name__ == '__main__':
app.run()
|
Improve error message when reloadBaj is undefined.
|
$(document).ready(() => {
if (typeof window.reloadBaj === 'undefined') {
console.error('Alchemists Notifier: reloadBaj is undefined, unable to continue');
return;
}
var gameId = '0';
var interval;
var reload = window.reloadBaj;
var self = document.getElementById('alc-notifier');
for (var part of window.location.search.slice(1).split('&')) {
if (part.startsWith('id=')) {
gameId = part.slice(3);
break;
}
}
self.addEventListener('alc-interval', event => {
clearInterval(interval);
if (event.detail.action == 'start') {
interval = setInterval(reload, event.detail.delayMS);
}
});
self.dispatchEvent(new CustomEvent('alc-notifier-ready', {
detail: {
'game-id': gameId,
'waiting-text': window.TXT_ALC_ACTION_ATTENDRE
}
}));
});
|
$(document).ready(() => {
if (typeof window.reloadBaj === 'undefined') {
console.error('alchemists-boiteajeux: reloadBaj is undefined');
return;
}
var gameId = '0';
var interval;
var reload = window.reloadBaj;
var self = document.getElementById('alc-notifier');
for (var part of window.location.search.slice(1).split('&')) {
if (part.startsWith('id=')) {
gameId = part.slice(3);
break;
}
}
self.addEventListener('alc-interval', event => {
clearInterval(interval);
if (event.detail.action == 'start') {
interval = setInterval(reload, event.detail.delayMS);
}
});
self.dispatchEvent(new CustomEvent('alc-notifier-ready', {
detail: {
'game-id': gameId,
'waiting-text': window.TXT_ALC_ACTION_ATTENDRE
}
}));
});
|
Fix critical stupid copypaste error
|
from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order() + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return cls.objects.order_by('-order')[0].order
|
from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try:
self.order = self.max_order + 1
except:
self.order = 1 # 0 is a special index used in swap
if self.order == 0 and not swapping:
raise ValidationError("Can't set 'order' to 0")
super(OrderedModel, self).save(*args, **kwargs)
@classmethod
def swap(cls, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
@classmethod
def max_order(cls):
return self.__class__.objects.order_by('-order')[0].order
|
Clean up of test case
|
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\ORM\Event\OnClearEventArgs;
use Doctrine\ORM\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* ClearEventTest
*
* @author Michael Ridgway <mcridgway@gmail.com>
*/
class ClearEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
}
public function testEventIsCalledOnClear()
{
$listener = new OnClearListener;
$this->_em->getEventManager()->addEventListener(Events::onClear, $listener);
$this->_em->clear();
$this->assertTrue($listener->called);
}
}
class OnClearListener
{
public $called = false;
public function onClear(OnClearEventArgs $args)
{
$this->called = true;
}
}
|
<?php
namespace Doctrine\Tests\ORM\Functional;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\CMS\CmsPhonenumber;
use Doctrine\ORM\Event\OnClearEventArgs;
use Doctrine\ORM\Events;
require_once __DIR__ . '/../../TestInit.php';
/**
* ClearEventTest
*
* @author Michael Ridgway
*/
class ClearEventTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
protected function setUp() {
parent::setUp();
}
public function testEventIsCalledOnClear()
{
$listener = new OnClearListener;
$this->_em->getEventManager()->addEventListener(Events::onClear, $listener);
$this->_em->clear();
$this->assertTrue($listener->called);
}
}
class OnClearListener
{
public $called = false;
public function onClear(OnClearEventArgs $args)
{
$this->called = true;
}
}
|
Check the parameters for the Join command correctly
|
from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class JoinCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "Join"
def triggers(self):
return ["join"]
def execute(self, server, source, command, params, data):
if len(params) < 1:
self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Join what?")
return
if len(params) > 1:
self.bot.servers[server].outputHandler.cmdJOIN(params[0], params[1])
else:
self.bot.servers[server].outputHandler.cmdJOIN(params[0])
joinCommand = JoinCommand()
|
from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class JoinCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "Join"
def triggers(self):
return ["join"]
def execute(self, server, source, command, params, data):
if len(params) < 1:
self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Join what?")
return
if len(params) > 2:
self.bot.servers[server].outputHandler.cmdJOIN(params[0], params[1])
else:
self.bot.servers[server].outputHandler.cmdJOIN(params[0])
joinCommand = JoinCommand()
|
Use request helper function in LayersScraper
|
import requests
import json
from . import Scraper
class LayersScraper:
"""A superclass for scraping Layers of the UofT Map.
Map is located at http://map.utoronto.ca
"""
host = 'http://map.utoronto.ca/'
@staticmethod
def get_layers_json(campus):
"""Retrieve the JSON structure from host."""
Scraper.logger.info('Retrieving map layers for %s.' % campus.upper())
headers = {'Referer': LayersScraper.host}
data = Scraper.get('%s%s%s' % (
LayersScraper.host,
'data/map/',
campus
), headers=headers, json=True)
return data['layers']
@staticmethod
def get_value(entry, val, number=False):
"""Retrieve the desired value from the parsed response dictionary."""
if val in entry.keys():
return entry[val]
else:
return 0 if number else ''
|
import requests
import json
from . import Scraper
class LayersScraper:
"""A superclass for scraping Layers of the UofT Map.
Map is located at http://map.utoronto.ca
"""
host = 'http://map.utoronto.ca/'
s = requests.Session()
@staticmethod
def get_layers_json(campus):
"""Retrieve the JSON structure from host."""
Scraper.logger.info('Retrieving map layers for %s.' % campus.upper())
headers = {
'Referer': LayersScraper.host
}
html = LayersScraper.s.get('%s%s%s' % (
LayersScraper.host,
'data/map/',
campus
), headers=headers).text
data = json.loads(html)
return data['layers']
@staticmethod
def get_value(entry, val, number=False):
"""Retrieve the desired value from the parsed response dictionary."""
if val in entry.keys():
return entry[val]
else:
return 0 if number else ''
|
[ReactNative] Remove padding restriction on images
Summary:
@public
Padding actually works fine on images.
Test Plan: Nested text inside an image is properly positioned with padding on the image.
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ImageStylePropTypes
* @flow
*/
'use strict';
var ImageResizeMode = require('ImageResizeMode');
var LayoutPropTypes = require('LayoutPropTypes');
var ReactPropTypes = require('ReactPropTypes');
var ImageStylePropTypes = {
...LayoutPropTypes,
resizeMode: ReactPropTypes.oneOf(Object.keys(ImageResizeMode)),
backgroundColor: ReactPropTypes.string,
borderColor: ReactPropTypes.string,
borderWidth: ReactPropTypes.number,
borderRadius: ReactPropTypes.number,
// iOS-Specific style to "tint" an image.
// It changes the color of all the non-transparent pixels to the tintColor
tintColor: ReactPropTypes.string,
opacity: ReactPropTypes.number,
};
module.exports = ImageStylePropTypes;
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ImageStylePropTypes
* @flow
*/
'use strict';
var ImageResizeMode = require('ImageResizeMode');
var LayoutPropTypes = require('LayoutPropTypes');
var ReactPropTypes = require('ReactPropTypes');
var ImageStylePropTypes = {
...LayoutPropTypes,
resizeMode: ReactPropTypes.oneOf(Object.keys(ImageResizeMode)),
backgroundColor: ReactPropTypes.string,
borderColor: ReactPropTypes.string,
borderWidth: ReactPropTypes.number,
borderRadius: ReactPropTypes.number,
// iOS-Specific style to "tint" an image.
// It changes the color of all the non-transparent pixels to the tintColor
tintColor: ReactPropTypes.string,
opacity: ReactPropTypes.number,
};
// Image doesn't support padding correctly (#4841912)
var unsupportedProps = Object.keys({
padding: null,
paddingTop: null,
paddingLeft: null,
paddingRight: null,
paddingBottom: null,
paddingVertical: null,
paddingHorizontal: null,
});
for (var i = 0; i < unsupportedProps.length; i++) {
delete ImageStylePropTypes[unsupportedProps[i]];
}
module.exports = ImageStylePropTypes;
|
Change solr host to internal ip.
|
<?php
// Setup DB
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'uclalib',
'username' => 'uclalib',
'password' => 'uclalib',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
// Tell Drupal that we are behind a reverse proxy server
$conf['reverse_proxy'] = TRUE;
// List of trusted IPs (IP numbers of our reverse proxies)
$conf['reverse_proxy_addresses'] = array(
'127.0.0.1',
);
// Solr settings
$conf['search_api_solr_overrides'] = array(
'uclalib_solr_server' => array(
'name' => t('Solr Server (Staging)'),
'options' => array(
'host' => '192.168.129.217',
'port' => '8080',
'path' => '/solr/uclalibdev',
),
),
);
|
<?php
// Setup DB
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => 'uclalib',
'username' => 'uclalib',
'password' => 'uclalib',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
// Tell Drupal that we are behind a reverse proxy server
$conf['reverse_proxy'] = TRUE;
// List of trusted IPs (IP numbers of our reverse proxies)
$conf['reverse_proxy_addresses'] = array(
'127.0.0.1',
);
// Solr settings
$conf['search_api_solr_overrides'] = array(
'uclalib_solr_server' => array(
'name' => t('Solr Server (Staging)'),
'options' => array(
'host' => 'sky.bluespark.com',
'port' => '8080',
'path' => '/solr/uclalibdev',
),
),
);
|
Make wrapper returned by `returns_blocks` decorator, understand additional `args` and `kwargs` arguments.
|
# -*- coding: utf-8 -*-
import os.path
from django.http import HttpResponse
from django.conf import settings
from functools import wraps
from bempy import ImmediateResponse
def returns_blocks(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
page = func(request, *args, **kwargs)
try:
if isinstance(page, HttpResponse):
return page
else:
response = HttpResponse(page('render',
request=request,
js_filename='bempy.js',
css_filename='bempy.css'))
return response
except ImmediateResponse as e:
return e.response
wrapper.block = func
return wrapper
|
# -*- coding: utf-8 -*-
import os.path
from django.http import HttpResponse
from django.conf import settings
from functools import wraps
from bempy import ImmediateResponse
def returns_blocks(func):
@wraps(func)
def wrapper(request):
page = func(request)
try:
if isinstance(page, HttpResponse):
return page
else:
response = HttpResponse(page('render',
request=request,
js_filename='bempy.js',
css_filename='bempy.css'))
return response
except ImmediateResponse as e:
return e.response
wrapper.block = func
return wrapper
|
Add rsync to appCmd taskcat
|
'use strict';
var path = require('path');
var _ = require('lodash');
var PLUGIN_NAME = 'kalabox-plugin-rsync';
module.exports = function(kbox) {
var events = kbox.core.events;
var engine = kbox.engine;
var globalConfig = kbox.core.deps.lookup('globalConfig');
kbox.ifApp(function(app) {
// Grab the clients
var Rsync = require('./lib/rsync.js');
var rsync = new Rsync(kbox, app);
// Events
// Install the util container for our things
events.on('post-install', function(app, done) {
// If profile is set to dev build from source
var opts = {
name: 'rsync',
srcRoot: path.resolve(__dirname)
};
engine.build(opts, done);
});
// Tasks
// git wrapper: kbox git COMMAND
kbox.tasks.add(function(task) {
task.path = [app.name, 'rsync'];
task.category = 'appCmd';
task.description = 'Run rsync commands.';
task.kind = 'delegate';
task.func = function(done) {
rsync.cmd(this.payload, false, done);
};
});
});
};
|
'use strict';
var path = require('path');
var _ = require('lodash');
var PLUGIN_NAME = 'kalabox-plugin-rsync';
module.exports = function(kbox) {
var events = kbox.core.events;
var engine = kbox.engine;
var globalConfig = kbox.core.deps.lookup('globalConfig');
kbox.ifApp(function(app) {
// Grab the clients
var Rsync = require('./lib/rsync.js');
var rsync = new Rsync(kbox, app);
// Events
// Install the util container for our things
events.on('post-install', function(app, done) {
// If profile is set to dev build from source
var opts = {
name: 'rsync',
srcRoot: path.resolve(__dirname)
};
engine.build(opts, done);
});
// Tasks
// git wrapper: kbox git COMMAND
kbox.tasks.add(function(task) {
task.path = [app.name, 'rsync'];
task.description = 'Run rsync commands.';
task.kind = 'delegate';
task.func = function(done) {
rsync.cmd(this.payload, false, done);
};
});
});
};
|
Add return value to removeLecturerFromSubject
|
package at.ac.tuwien.inso.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import at.ac.tuwien.inso.entity.*;
import java.util.*;
public interface SubjectService {
@PreAuthorize("isAuthenticated()")
Page<Subject> findAll(Pageable pageable);
@PreAuthorize("isAuthenticated()")
Subject findOne(long id);
@PreAuthorize("isAuthenticated()")
List<Subject> searchForSubjects(String word);
@PreAuthorize("hasRole('ADMIN')")
Subject create(Subject subject);
@PreAuthorize("hasRole('ADMIN')")
Subject addLecturerToSubject(Long subjectId, Long lecturerUisUserId);
@PreAuthorize("hasRole('ADMIN')")
List<Lecturer> getAvailableLecturersForSubject(Long subjectId);
@PreAuthorize("hasRole('ADMIN')")
Lecturer removeLecturerFromSubject(Long subjectId, Long lecturerUisUserId);
}
|
package at.ac.tuwien.inso.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import at.ac.tuwien.inso.entity.*;
import java.util.*;
public interface SubjectService {
@PreAuthorize("isAuthenticated()")
Page<Subject> findAll(Pageable pageable);
@PreAuthorize("isAuthenticated()")
Subject findOne(long id);
@PreAuthorize("isAuthenticated()")
List<Subject> searchForSubjects(String word);
@PreAuthorize("hasRole('ADMIN')")
Subject create(Subject subject);
@PreAuthorize("hasRole('ADMIN')")
Subject addLecturerToSubject(Long subjectId, Long lecturerUisUserId);
@PreAuthorize("hasRole('ADMIN')")
List<Lecturer> getAvailableLecturersForSubject(Long subjectId);
@PreAuthorize("hasRole('ADMIN')")
void removeLecturerFromSubject(Long subjectId, Long lecturerId);
}
|
Add size loging for vendor.js file
|
module.exports = function(gulp, speck) {
return gulp.task('js:vendor', function() {
var uglify = require('gulp-uglify'),
gulpif = require('gulp-if'),
insert = require('gulp-insert'),
size = require('gulp-size'),
concat = require('gulp-concat');
return gulp.src(speck.config.vendorJS)
.pipe(gulpif(speck.build.env.optimise, uglify()))
.pipe(concat('vendor.js'))
.pipe(gulpif(speck.build.env.optimise, insert.prepend(
'/*\n' +
'* ' + speck.config.name + ', ' + speck.config.version + ' (' + speck.config.currentRevision + ')\n' +
'* ' + 'vendor.js built ' + new Date().toISOString().substring(0, 10) + '\n' +
'* Don\'t edit this file directly.\n' +
'*/\n'
)))
.pipe(size({gzip: true, title: 'vendor.js'}))
.pipe(gulp.dest(speck.assets.build.js));
});
};
|
module.exports = function(gulp, speck) {
return gulp.task('js:vendor', function() {
var uglify = require('gulp-uglify'),
gulpif = require('gulp-if'),
insert = require('gulp-insert'),
concat = require('gulp-concat');
return gulp.src(speck.config.vendorJS)
.pipe(gulpif(speck.build.env.optimise, uglify()))
.pipe(concat('vendor.js'))
.pipe(gulpif(speck.build.env.optimise, insert.prepend(
'/*\n' +
'* ' + speck.config.name + ', ' + speck.config.version + ' (' + speck.config.currentRevision + ')\n' +
'* ' + 'vendor.js built ' + new Date().toISOString().substring(0, 10) + '\n' +
'* Don\'t edit this file directly.\n' +
'*/\n'
)))
.pipe(gulp.dest(speck.assets.build.js));
});
};
|
Update ajax to remove overflow scrolling for embedded resume
|
$(document).on('ready', function() {
$.ajax({
cache: false,
url: "/partial-index.html"
}).done(function(response) {
$('.main-container').html(response);
});
// Use navigator to detect Safari and render old resume partial instead
$('nav a').on('click', function(event) {
event.preventDefault();
var targetURI = event.currentTarget.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
if(targetURI == "./resume/embedded-resume.html") {
$('.main-container').css("overflow-y", "visible");
}
else {
$('.main-container').css("overflow-y", "scroll");
}
});
});
$('.main-container').on('click', 'a.blog-link, a.home-link', function(event) {
event.preventDefault();
var targetURI = event.target.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
});
|
$(document).on('ready', function() {
$.ajax({
cache: false,
url: "/partial-index.html"
}).done(function(response) {
$('.main-container').html(response);
});
// Use navigator to detect Safari and render old resume partial instead
$('nav a').on('click', function(event) {
event.preventDefault();
var targetURI = event.currentTarget.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
$('.main-container').on('click', 'a.blog-link, a.home-link', function(event) {
event.preventDefault();
var targetURI = event.target.dataset.pagePartial;
$.ajax({
cache: false,
url: targetURI
}).done(function(response) {
$('.main-container').html(response);
});
});
});
|
Fix remove-before-visit for Windows, too
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gps
import (
"os"
"path/filepath"
)
func stripVendor(path string, info os.FileInfo, err error) error {
if err != nil && err != filepath.SkipDir {
return err
}
if info.Name() == "vendor" {
if _, err := os.Lstat(path); err == nil {
symlink := (info.Mode() & os.ModeSymlink) != 0
dir := info.IsDir()
switch {
case symlink && dir:
// This could be a windows junction directory. Support for these in the
// standard library is spotty, and we could easily delete an important
// folder if we called os.Remove or os.RemoveAll. Just skip these.
//
// TODO: If we could distinguish between junctions and Windows symlinks,
// we might be able to safely delete symlinks, even though junctions are
// dangerous.
return filepath.SkipDir
case symlink:
realInfo, err := os.Stat(path)
if err != nil {
return err
}
if realInfo.IsDir() {
return os.Remove(path)
}
case dir:
if err := removeAll(path); err != nil {
return err
}
return filepath.SkipDir
}
}
}
return nil
}
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gps
import (
"os"
"path/filepath"
)
func stripVendor(path string, info os.FileInfo, err error) error {
if err != nil && err != filepath.SkipDir {
return err
}
if info.Name() == "vendor" {
if _, err := os.Lstat(path); err == nil {
symlink := (info.Mode() & os.ModeSymlink) != 0
dir := info.IsDir()
switch {
case symlink && dir:
// This could be a windows junction directory. Support for these in the
// standard library is spotty, and we could easily delete an important
// folder if we called os.Remove or os.RemoveAll. Just skip these.
//
// TODO: If we could distinguish between junctions and Windows symlinks,
// we might be able to safely delete symlinks, even though junctions are
// dangerous.
return filepath.SkipDir
case symlink:
realInfo, err := os.Stat(path)
if err != nil {
return err
}
if realInfo.IsDir() {
return os.Remove(path)
}
case dir:
return removeAll(path)
}
}
}
return nil
}
|
Mark method arguments as final.
This used to be revision r2235.
|
package imagej.plugin.gui.swing;
import imagej.plugin.Plugin;
import imagej.plugin.PluginModule;
import imagej.plugin.gui.AbstractInputHarvester;
import imagej.plugin.gui.InputPanel;
import imagej.plugin.process.PluginPreprocessor;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* SwingInputHarvester is a plugin preprocessor that collects input parameter
* values from the user using a {@link SwingInputPanel} dialog box.
*/
@Plugin(type = PluginPreprocessor.class)
public class SwingInputHarvester extends AbstractInputHarvester {
@Override
public InputPanel createInputPanel() {
return new SwingInputPanel();
}
@Override
public boolean showDialog(final InputPanel inputPanel,
final PluginModule<?> module)
{
final JOptionPane optionPane = new JOptionPane(null);
optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
final JDialog dialog = optionPane.createDialog(module.getInfo().getLabel());
final JPanel mainPane = (JPanel) optionPane.getComponent(0);
final JPanel widgetPane = (JPanel) mainPane.getComponent(0);
widgetPane.add((SwingInputPanel) inputPanel);
dialog.setModal(true);
dialog.pack();
dialog.setVisible(true);
final Integer rval = (Integer) optionPane.getValue();
return rval != null && rval == JOptionPane.OK_OPTION;
}
}
|
package imagej.plugin.gui.swing;
import imagej.plugin.Plugin;
import imagej.plugin.PluginModule;
import imagej.plugin.gui.AbstractInputHarvester;
import imagej.plugin.gui.InputPanel;
import imagej.plugin.process.PluginPreprocessor;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* SwingInputHarvester is a plugin preprocessor that collects input parameter
* values from the user using a {@link SwingInputPanel} dialog box.
*/
@Plugin(type = PluginPreprocessor.class)
public class SwingInputHarvester extends AbstractInputHarvester {
@Override
public InputPanel createInputPanel() {
return new SwingInputPanel();
}
@Override
public boolean showDialog(InputPanel inputPanel, PluginModule<?> module) {
final JOptionPane optionPane = new JOptionPane(null);
optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
final JDialog dialog = optionPane.createDialog(module.getInfo().getLabel());
final JPanel mainPane = (JPanel) optionPane.getComponent(0);
final JPanel widgetPane = (JPanel) mainPane.getComponent(0);
widgetPane.add((SwingInputPanel) inputPanel);
dialog.setModal(true);
dialog.pack();
dialog.setVisible(true);
final Integer rval = (Integer) optionPane.getValue();
return rval != null && rval == JOptionPane.OK_OPTION;
}
}
|
Return new instance of filter state.
|
import Ember from 'ember'
import layout from '../templates/components/filter-facet'
import _ from 'lodash'
function callIfDefined (context, functionName, ...args) {
let func = context.get(functionName)
if (_.isFunction(func)) {
func(...args)
}
}
export default Ember.Component.extend({
layout,
classNames: ['facets'],
actions: {
'filter-change' (filterName, value) {
let filterState = this.get('activeFilters')
// Create a new filter state object, this helps with observers
filterState = _.extend({}, filterState)
filterState[filterName] = value
this.set('activeFilters', filterState)
callIfDefined(this, 'on-filter', filterState)
}
},
init () {
this._super(...arguments)
let filters = this.get('activeFilters')
if (filters === undefined || filters === null) {
this.set('activeFilters', {})
}
}
})
|
import Ember from 'ember'
import layout from '../templates/components/filter-facet'
import _ from 'lodash'
function callIfDefined (context, functionName, ...args) {
let func = context.get(functionName)
if (_.isFunction(func)) {
func(...args)
}
}
export default Ember.Component.extend({
layout,
classNames: ['facets'],
actions: {
'filter-change' (filterName, value) {
console.log(filterName)
let filterState = this.get('activeFilters')
filterState[filterName] = value
callIfDefined(this, 'on-filter', filterState)
}
},
init () {
this._super(...arguments)
let filters = this.get('activeFilters')
if (filters === undefined || filters === null) {
this.set('activeFilters', {})
}
}
})
|
Fix checks in session test
|
const graphqlTester = require('graphql-tester')
const expressGraphql = require('express-graphql')
const {expect} = require('chai')
const cookieSession = require('cookie-session')
const express = require('express')
const shortid = require('shortid')
const createExpressWrapper = require('graphql-tester/lib/main/servers/express.js').create
const app = require('../lib/app')
describe('api' , () => {
const test = graphqlTester.tester({
server: createExpressWrapper(app),
url: '/graphql'
})
it('responds with session id', done => {
test('{sessionId}').then(response => {
expect(response.success).to.be.ok
expect(response.status).to.equal(200)
expect(response.data.sessionId).to.not.equal('')
return done()
})
})
it('gives out unique session ids', done => {
test('{sessionId}').then(response1 => {
expect(response1.success).to.be.ok
expect(response1.status).to.equal(200)
test('{sessionId}').then(response2 => {
expect(response2.success).to.be.ok
expect(response2.status).to.equal(200)
expect(response2.data.sessionId).to.not.equal(response1.data.sessionId)
return done()
})
})
})
})
|
const graphqlTester = require('graphql-tester')
const expressGraphql = require('express-graphql')
const {expect} = require('chai')
const cookieSession = require('cookie-session')
const express = require('express')
const shortid = require('shortid')
const createExpressWrapper = require('graphql-tester/lib/main/servers/express.js').create
const app = require('../lib/app')
describe('api' , () => {
const test = graphqlTester.tester({
server: createExpressWrapper(app),
url: '/graphql'
})
it('responds with session id', done => {
test('{sessionId}').then(response => {
expect(response.success).to.be.ok
expect(response.status).to.equal(200)
expect(response.data.sessionId).to.not.equal('')
return done()
})
})
it('gives out unique session ids', done => {
test('{sessionId}').then(response1 => {
expect(response1.success).to.be.ok
expect(response1.status).to.equal(200)
test('{sessionId}').then(response2 => {
expect(response1.success).to.be.ok
expect(response1.status).to.equal(200)
expect(response1.data.sessionId).to.not.equal(response2.data.sessionId)
return done()
})
})
})
})
|
Fix not working language switch in production environment
Fixes #64
|
import Ember from "ember";
import translations from "croodle/lang/translations";
/* global Croodle */
export default Ember.View.extend({
templateName: 'language-switch',
languages: function() {
var languages = [];
for(var lang in translations) {
languages.push(lang);
}
return languages;
}.property(),
languageChanged: function() {
// change language
var language = this.get('controller.language.selected');
// save language in cookie
document.cookie="language=" + language + ";" +
// give it an lifetime of one year
"max-age=" + 60*60*24*356 + ";";
// rerender page
window.location.reload();
}.observes('controller.language.selected')
});
|
import Ember from "ember";
import translations from "croodle/lang/translations";
/* global Croodle */
export default Ember.View.extend({
templateName: 'language-switch',
languages: function() {
var languages = [];
for(var lang in translations) {
languages.push(lang);
}
return languages;
}.property(),
languageChanged: function() {
// change language
var language = this.get('controller.language.selected');
// save language in cookie
document.cookie="language=" + language + ";" +
// give it an lifetime of one year
"max-age=" + 60*60*24*356 + ";";
// rerender page
Croodle.reset();
}.observes('controller.language.selected')
});
|
Disable automatic setting of created and modified by columns
|
<?php
/**
* This model contains all methods for interacting with user emails.
*
* @package Nails
* @subpackage module-auth
* @category Model
* @author Nails Dev Team
*/
namespace Nails\Auth\Model\User;
use Nails\Auth\Constants;
use Nails\Common\Model\Base;
/**
* Class Email
*
* @package Nails\Auth\Model\User
*/
class Email extends Base
{
/**
* The table this model represents
*
* @var string
*/
const TABLE = NAILS_DB_PREFIX . 'user_email';
/**
* The name of the resource to use (as passed to \Nails\Factory::resource())
*
* @var string
*/
const RESOURCE_NAME = 'UserEmail';
/**
* The provider of the resource to use (as passed to \Nails\Factory::resource())
*
* @var string
*/
const RESOURCE_PROVIDER = Constants::MODULE_SLUG;
/**
* Disable setting of created_by and modified_by columns
*
* @var bool
*/
const AUTO_SET_USER = false;
}
|
<?php
/**
* This model contains all methods for interacting with user emails.
*
* @package Nails
* @subpackage module-auth
* @category Model
* @author Nails Dev Team
*/
namespace Nails\Auth\Model\User;
use Nails\Auth\Constants;
use Nails\Common\Model\Base;
/**
* Class Email
*
* @package Nails\Auth\Model\User
*/
class Email extends Base
{
/**
* The table this model represents
*
* @var string
*/
const TABLE = NAILS_DB_PREFIX . 'user_email';
/**
* The name of the resource to use (as passed to \Nails\Factory::resource())
*
* @var string
*/
const RESOURCE_NAME = 'UserEmail';
/**
* The provider of the resource to use (as passed to \Nails\Factory::resource())
*
* @var string
*/
const RESOURCE_PROVIDER = Constants::MODULE_SLUG;
}
|
Add native return type declaration (array) to Twig functions extension
|
<?php
/**
* User: Simon Libaud
* Date: 19/03/2017
* Email: simonlibaud@gmail.com.
*/
namespace Sil\RouteSecurityBundle\Twig;
use Sil\RouteSecurityBundle\Security\AccessControl;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Class RouteSecurityExtension.
*/
class RouteSecurityExtension extends AbstractExtension
{
private $accessControl;
public function __construct(AccessControl $accessControl)
{
$this->accessControl = $accessControl;
}
public function getFunctions(): array
{
return [
new TwigFunction('hasUserAccessToRoute', [$this->accessControl, 'hasUserAccessToRoute']),
new TwigFunction('hasUserAccessToRoutes', [$this->accessControl, 'hasUserAccessToRoutes']),
new TwigFunction('hasUserAccessAtLeastOneRoute', [$this->accessControl, 'hasUserAccessAtLeastOneRoute']),
];
}
}
|
<?php
/**
* User: Simon Libaud
* Date: 19/03/2017
* Email: simonlibaud@gmail.com.
*/
namespace Sil\RouteSecurityBundle\Twig;
use Sil\RouteSecurityBundle\Security\AccessControl;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Class RouteSecurityExtension.
*/
class RouteSecurityExtension extends AbstractExtension
{
private $accessControl;
public function __construct(AccessControl $accessControl)
{
$this->accessControl = $accessControl;
}
public function getFunctions()
{
return [
new TwigFunction('hasUserAccessToRoute', [$this->accessControl, 'hasUserAccessToRoute']),
new TwigFunction('hasUserAccessToRoutes', [$this->accessControl, 'hasUserAccessToRoutes']),
new TwigFunction('hasUserAccessAtLeastOneRoute', [$this->accessControl, 'hasUserAccessAtLeastOneRoute']),
];
}
}
|
Reduce speed of ZigBrain accelleration & test github web interface
|
class WanderBrain(CritterBrain):
def on_collision(self,dir,other,senses):
pass
def on_attack(self,dir,attacker,senses):
pass
def on_tick(self,senses):
self.body.turn(uniform(-0.1,+0.1)*randrange(1,4))
Brains.register(WanderBrain)
class ZigBrain(CritterBrain):
def on_collision(self,dir,other,senses):
pass
def on_attack(self,dir,attacker,senses):
pass
def on_tick(self,senses):
if randrange(1,10) == 1:
self.body.turn(uniform(-1,1))
else:
self.body.heading *= 1.01
Brains.register(ZigBrain)
|
class WanderBrain(CritterBrain):
def on_collision(self,dir,other,senses):
pass
def on_attack(self,dir,attacker,senses):
pass
def on_tick(self,senses):
self.body.turn(uniform(-0.1,+0.1)*randrange(1,4))
Brains.register(WanderBrain)
class ZigBrain(CritterBrain):
def on_collision(self,dir,other,senses):
pass
def on_attack(self,dir,attacker,senses):
pass
def on_tick(self,senses):
if randrange(1,10) == 1:
self.body.turn(uniform(-1,1))
else:
self.body.heading *= 1.1
Brains.register(ZigBrain)
|
Fix the documentation and codacy objection.
|
/*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.validate;
/**
* Thrown to indicate that a method has been passed an illegal or
* inappropriate argument during conversion from one type to another.
*
* @author Illia Shepilov
* @see ConversionError
*/
public class IllegalConversionArgumentException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
private final ConversionError conversionError;
public IllegalConversionArgumentException(ConversionError conversionError) {
super();
this.conversionError = conversionError;
}
public ConversionError getConversionError() {
return conversionError;
}
}
|
/*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.validate;
/**
* Thrown to indicate that a method has been passed
* an illegal or inappropriate argument during conversion.
*
* @author Illia Shepilov
* @see ConversionError
*/
public class IllegalConversionArgumentException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;
private final ConversionError conversionError;
public IllegalConversionArgumentException(ConversionError conversionError) {
this.conversionError = conversionError;
}
public ConversionError getConversionError() {
return conversionError;
}
}
|
Set version number to 0.9.15
|
from setuptools import setup
setup(
name='slacker',
version='0.9.15',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
|
from setuptools import setup
setup(
name='slacker',
version='0.9.10',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
|
Use double quote for error wraping
|
package vegeta
import (
"bytes"
"encoding/json"
"fmt"
)
// Dumper is an interface defining Results dumping.
type Dumper interface {
Dump(*Result) ([]byte, error)
}
// DumperFunc is an adapter to allow the use of ordinary functions as
// Dumpers. If f is a function with the appropriate signature, DumperFunc(f)
// is a Dumper object that calls f.
type DumperFunc func(*Result) ([]byte, error)
func (f DumperFunc) Dump(r *Result) ([]byte, error) { return f(r) }
// DumpCSV dumps a Result as a CSV record with six columns.
// The columns are: unix timestamp in ns since epoch, http status code,
// request latency in ns, bytes out, bytes in, and lastly the error.
var DumpCSV DumperFunc = func(r *Result) ([]byte, error) {
var buf bytes.Buffer
_, err := fmt.Fprintf(&buf, "%d,%d,%d,%d,%d,\"%s\"\n",
r.Timestamp.UnixNano(),
r.Code,
r.Latency.Nanoseconds(),
r.BytesOut,
r.BytesIn,
r.Error,
)
return buf.Bytes(), err
}
// DumpJSON dumps a Result as a JSON object.
var DumpJSON DumperFunc = func(r *Result) ([]byte, error) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(r)
return buf.Bytes(), err
}
|
package vegeta
import (
"bytes"
"encoding/json"
"fmt"
)
// Dumper is an interface defining Results dumping.
type Dumper interface {
Dump(*Result) ([]byte, error)
}
// DumperFunc is an adapter to allow the use of ordinary functions as
// Dumpers. If f is a function with the appropriate signature, DumperFunc(f)
// is a Dumper object that calls f.
type DumperFunc func(*Result) ([]byte, error)
func (f DumperFunc) Dump(r *Result) ([]byte, error) { return f(r) }
// DumpCSV dumps a Result as a CSV record with six columns.
// The columns are: unix timestamp in ns since epoch, http status code,
// request latency in ns, bytes out, bytes in, and lastly the error.
var DumpCSV DumperFunc = func(r *Result) ([]byte, error) {
var buf bytes.Buffer
_, err := fmt.Fprintf(&buf, "%d,%d,%d,%d,%d,'%s'\n",
r.Timestamp.UnixNano(),
r.Code,
r.Latency.Nanoseconds(),
r.BytesOut,
r.BytesIn,
r.Error,
)
return buf.Bytes(), err
}
// DumpJSON dumps a Result as a JSON object.
var DumpJSON DumperFunc = func(r *Result) ([]byte, error) {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(r)
return buf.Bytes(), err
}
|
Clear input after submit now functinal
|
//placing both controllers her b/c short program, otherwise would make partial
Todos.TodosController = Ember.ArrayController.extend ({
actions: {
createNewTodo: function() {
var newVal = this.get('newTodo'); // gets new todo Val
var todo = this.store.createRecord('todo' , { //Creates a new todo type
val: newVal , // gets new val
completed: false // sets to false completed
});
this.set('newTodo', ''); // set new todo to blank and save prev value to list
todo.save();
} ,
clearCompleted: function() {
var completed = this.filterBy('completed', true);//find all TRUE completed items
completed.invoke('deleteRecord'); //invoke this deletedRecord on all TRUE completed
completed.invoke('save'); // Save the view with after deleted TRUE completed items
}
}
});
Todos.TodoController = Ember.ObjectController.extend({
//Will define actions that can happen to the object
actions: {
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
}
}
});
|
//placing both controllers her b/c short program, otherwise would make partial
Todos.TodosController = Ember.ArrayController.extend ({
actions: {
createNewTodo: function() {
var newVal = this.get('newTodo'); // gets new todo Val
var todo = this.store.createRecord('todo' , { //Creates a new todo type
val: newVal , // gets new val
completed: false // sets to false completed
});
this.set('newtodo', ''); // set new todo to blank and save prev value to list
todo.save();
} ,
clearCompleted: function() {
var completed = this.filterBy('completed', true);//find all TRUE completed items
completed.invoke('deleteRecord'); //invoke this deletedRecord on all TRUE completed
completed.invoke('save'); // Save the view with after deleted TRUE completed items
}
}
});
Todos.TodoController = Ember.ObjectController.extend({
//Will define actions that can happen to the object
actions: {
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
}
}
});
|
Convert message check to regex
|
<?php
declare(strict_types=1);
namespace WRS\Tests\Storage;
use PHPUnit\Framework\TestCase;
use WRS\Storage\NullStorage;
class NullStorageTest extends TestCase
{
const KEY = "test";
const VALUE = "value";
public function testSave()
{
$ns = new NullStorage();
$ns->save(self::KEY, self::VALUE);
$this->assertTrue(true);
}
public function testExists()
{
$ns = new NullStorage();
$ns->save(self::KEY, self::VALUE);
$this->assertSame(false, $ns->exists(self::KEY));
}
/**
* @expectedException Exception
* @expectedExceptionMessageRegExp #^Cannot load key .*$#
*/
public function testLoad()
{
$ns = new NullStorage();
$result = $ns->load(self::KEY);
}
}
|
<?php
declare(strict_types=1);
namespace WRS\Tests\Storage;
use PHPUnit\Framework\TestCase;
use WRS\Storage\NullStorage;
class NullStorageTest extends TestCase
{
const KEY = "test";
const VALUE = "value";
public function testSave()
{
$ns = new NullStorage();
$ns->save(self::KEY, self::VALUE);
$this->assertTrue(true);
}
public function testExists()
{
$ns = new NullStorage();
$ns->save(self::KEY, self::VALUE);
$this->assertSame(false, $ns->exists(self::KEY));
}
/**
* @expectedException Exception
* @expectedExceptionMessage Cannot load key test
*/
public function testLoad()
{
$ns = new NullStorage();
$result = $ns->load(self::KEY);
}
}
|
Use a Not Found exception
|
<?php
namespace Church\Controller;
use Church\Entity\User\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* @Route(
* service="church.controller_user",
* defaults = {
* "version" = "1.0",
* "_format" = "json"
* }
* )
*/
class UserController extends Controller
{
/**
* @Route("/user/{user}.{_format}")
* @Method("GET")
*
* @param User $user
* @param Request $request
*/
public function showAction(User $user, Request $request) : Response
{
if (!$user->isEnabled()) {
throw new NotFoundHttpException("User account is disabled");
}
$roles = [];
if ($this->isLoggedIn() && $this->getUser()->isNeighbor($user)) {
$roles[] = 'neighbor';
}
return $this->serializer->serialize($user, $request->getRequestFormat(), $roles);
}
}
|
<?php
namespace Church\Controller;
use Church\Entity\User\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
/**
* @Route(
* service="church.controller_user",
* defaults = {
* "version" = "1.0",
* "_format" = "json"
* }
* )
*/
class UserController extends Controller
{
/**
* @Route("/user/{user}.{_format}")
* @Method("GET")
*
* @param User $user
* @param Request $request
*/
public function showAction(User $user, Request $request) : Response
{
if (!$user->isEnabled()) {
throw new GoneHttpException("User account is disabled");
}
$roles = [];
if ($this->isLoggedIn() && $this->getUser()->isNeighbor($user)) {
$roles[] = 'neighbor';
}
return $this->serializer->serialize($user, $request->getRequestFormat(), $roles);
}
}
|
Clarify error message when item is already locked.
|
/**
* Copyright (C) 2009-2013 Simonsoft Nordic AB
*
* 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 se.simonsoft.cms.item.commit;
import se.simonsoft.cms.item.CmsItemLock;
import se.simonsoft.cms.item.CmsItemPath;
import se.simonsoft.cms.item.CmsRepository;
public class CmsItemLockedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CmsItemLockedException(CmsRepository repository, CmsItemPath path) {
super("Item is already locked at path " + path);
}
public CmsItemLockedException(CmsRepository repository, CmsItemPath path, CmsItemLock lock) {
super("Item is already locked by user " + lock.getOwner() + " at path " + path);
}
}
|
/**
* Copyright (C) 2009-2013 Simonsoft Nordic AB
*
* 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 se.simonsoft.cms.item.commit;
import se.simonsoft.cms.item.CmsItemLock;
import se.simonsoft.cms.item.CmsItemPath;
import se.simonsoft.cms.item.CmsRepository;
public class CmsItemLockedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CmsItemLockedException(CmsRepository repository, CmsItemPath path) {
super("Item is locked at path " + path);
}
public CmsItemLockedException(CmsRepository repository, CmsItemPath path, CmsItemLock lock) {
super("Item is locked by user " + lock.getOwner() + " at path " + path);
}
}
|
Remove replace urlpatterns with simple array, make compatible with Django 1.9
|
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.4
from django.conf.urls.defaults import url
from avatar import views
urlpatterns = [
url(r'^add/$', views.add, name='avatar_add'),
url(r'^change/$', views.change, name='avatar_change'),
url(r'^delete/$', views.delete, name='avatar_delete'),
url(r'^render_primary/(?P<user>[\w\d\@\.\-_]{3,30})/(?P<size>[\d]+)/$',
views.render_primary,
name='avatar_render_primary'),
url(r'^list/(?P<username>[\+\w\@\.]+)/$',
views.avatar_gallery,
name='avatar_gallery'),
url(r'^list/(?P<username>[\+\w\@\.]+)/(?P<id>[\d]+)/$',
views.avatar,
name='avatar'),
]
|
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.4
from django.conf.urls.defaults import patterns, url
from avatar import views
urlpatterns = patterns('',
url(r'^add/$', views.add, name='avatar_add'),
url(r'^change/$', views.change, name='avatar_change'),
url(r'^delete/$', views.delete, name='avatar_delete'),
url(r'^render_primary/(?P<user>[\w\d\@\.\-_]{3,30})/(?P<size>[\d]+)/$',
views.render_primary,
name='avatar_render_primary'),
url(r'^list/(?P<username>[\+\w\@\.]+)/$',
views.avatar_gallery,
name='avatar_gallery'),
url(r'^list/(?P<username>[\+\w\@\.]+)/(?P<id>[\d]+)/$',
views.avatar,
name='avatar'),
)
|
Exclude test data utilities from lit.
|
import os
import sys
import lit.formats
import lit.util
import lit.llvm
# Configuration file for the 'lit' test runner.
lit.llvm.initialize(lit_config, config)
# name: The name of this test suite.
config.name = 'TFLITEHUB'
config.test_format = lit.formats.ShTest()
# suffixes: A list of file extensions to treat as test files.
config.suffixes = ['.py']
# test_source_root: The root path where tests are located.
config.test_source_root = os.path.dirname(__file__)
#config.use_default_substitutions()
config.excludes = [
'imagenet_test_data.py',
'lit.cfg.py',
'lit.site.cfg.py',
'manual_test.py',
'squad_test_data.py',
'test_util.py',
]
config.substitutions.extend([
('%PYTHON', sys.executable),
])
config.environment['PYTHONPATH'] = ":".join(sys.path)
project_root = os.path.dirname(os.path.dirname(__file__))
# Enable features based on -D FEATURES=hugetest,vulkan
# syntax.
features_param = lit_config.params.get('FEATURES')
if features_param:
config.available_features.update(features_param.split(','))
|
import os
import sys
import lit.formats
import lit.util
import lit.llvm
# Configuration file for the 'lit' test runner.
lit.llvm.initialize(lit_config, config)
# name: The name of this test suite.
config.name = 'TFLITEHUB'
config.test_format = lit.formats.ShTest()
# suffixes: A list of file extensions to treat as test files.
config.suffixes = ['.py']
# test_source_root: The root path where tests are located.
config.test_source_root = os.path.dirname(__file__)
#config.use_default_substitutions()
config.excludes = [
'lit.cfg.py',
'lit.site.cfg.py',
'test_util.py',
'manual_test.py',
]
config.substitutions.extend([
('%PYTHON', sys.executable),
])
config.environment['PYTHONPATH'] = ":".join(sys.path)
project_root = os.path.dirname(os.path.dirname(__file__))
# Enable features based on -D FEATURES=hugetest,vulkan
# syntax.
features_param = lit_config.params.get('FEATURES')
if features_param:
config.available_features.update(features_param.split(','))
|
Remove unused imports and variables.
|
package org.scribe.model;
import org.scribe.utils.OAuthEncoder;
/**
* @author: Pablo Fernandez
*/
public class Parameter implements Comparable<Parameter>
{
private final String key;
private final String value;
public Parameter(String key, String value)
{
this.key = key;
this.value = value;
}
public String asUrlEncodedPair()
{
return OAuthEncoder.encode(key).concat("=").concat(OAuthEncoder.encode(value));
}
public boolean equals(Object other)
{
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof Parameter)) return false;
Parameter otherParam = (Parameter) other;
return otherParam.key.equals(key) && otherParam.value.equals(value);
}
public int hashCode()
{
return key.hashCode() + value.hashCode();
}
public int compareTo(Parameter parameter)
{
int keyDiff = key.compareTo(parameter.key);
return keyDiff != 0 ? keyDiff : value.compareTo(parameter.value);
}
}
|
package org.scribe.model;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.scribe.exceptions.OAuthException;
import org.scribe.utils.OAuthEncoder;
/**
* @author: Pablo Fernandez
*/
public class Parameter implements Comparable<Parameter>
{
private static final String UTF = "UTF8";
private final String key;
private final String value;
public Parameter(String key, String value)
{
this.key = key;
this.value = value;
}
public String asUrlEncodedPair()
{
return OAuthEncoder.encode(key).concat("=").concat(OAuthEncoder.encode(value));
}
public boolean equals(Object other)
{
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof Parameter)) return false;
Parameter otherParam = (Parameter) other;
return otherParam.key.equals(key) && otherParam.value.equals(value);
}
public int hashCode()
{
return key.hashCode() + value.hashCode();
}
public int compareTo(Parameter parameter)
{
int keyDiff = key.compareTo(parameter.key);
return keyDiff != 0 ? keyDiff : value.compareTo(parameter.value);
}
}
|
Make config file optional by default.
|
// Adapted from https://github.com/tsantef/commander-starter
var fs = require('fs');
var path = require('path');
require('json5/lib/register')
module.exports = function commandLoader(program) {
'use strict';
var commands = {};
var loadPath = path.dirname(__filename);
// Loop though command files
fs.readdirSync(loadPath).filter(function (filename) {
return (/\.js$/.test(filename) && filename !== 'index.js');
}).forEach(function (filename) {
var name = filename.substr(0, filename.lastIndexOf('.'));
// Require command
var command = require(path.join(loadPath, filename));
var configFile = path.join(process.cwd(), 'lazuli.config');
if(program.config) {
configFile = program.config;
}
try {
program.conf = require(configFile);
}
catch(e) {}
// Initialize command
commands[name] = command(program);
});
return commands;
};
|
// Adapted from https://github.com/tsantef/commander-starter
var fs = require('fs');
var path = require('path');
require('json5/lib/register')
module.exports = function commandLoader(program) {
'use strict';
var commands = {};
var loadPath = path.dirname(__filename);
// Loop though command files
fs.readdirSync(loadPath).filter(function (filename) {
return (/\.js$/.test(filename) && filename !== 'index.js');
}).forEach(function (filename) {
var name = filename.substr(0, filename.lastIndexOf('.'));
// Require command
var command = require(path.join(loadPath, filename));
var configFile = path.join(process.cwd(), 'lazuli.config');
if(program.config) {
configFile = program.config;
}
program.conf = require(configFile);
// Initialize command
commands[name] = command(program);
});
return commands;
};
|
Change not to be reduced to localhost access
|
var ws = new WebSocket("ws://"+window.location.host+":8000/websocket");
ws.onmessage = function(evt){
myOutput.value = evt.data;
}
function sendRain(){
var msg = {
type: "message",
value: document.getElementById("RainNumber").value,
id: "Rain",
date: Date.now()
};
// Send the msg object as a JSON-formatted string.
ws.send(JSON.stringify(msg));
}
function updateRainRange(){
//get elements
var myRange = document.getElementById("RainRange");
var myNumber = document.getElementById("RainNumber");
//copy the value over
myNumber.value = myRange.value;
sendRain();
} // end function
function updateRainNumber(){
//get elements
var myRange = document.getElementById("RainRange");
var myNumber = document.getElementById("RainNumber");
//copy the value over
myRange.value = myNumber.value;
sendRain();
} // end function
ws.onmessage = function(evt){
var myOutput = document.getElementById("serverFeedback");
myOutput.value = evt.data;
}
|
var ws = new WebSocket("ws://localhost:8000/websocket");
ws.onmessage = function(evt){
myOutput.value = evt.data;
}
function sendRain(){
var msg = {
type: "message",
value: document.getElementById("RainNumber").value,
id: "Rain",
date: Date.now()
};
// Send the msg object as a JSON-formatted string.
ws.send(JSON.stringify(msg));
}
function updateRainRange(){
//get elements
var myRange = document.getElementById("RainRange");
var myNumber = document.getElementById("RainNumber");
//copy the value over
myNumber.value = myRange.value;
sendRain();
} // end function
function updateRainNumber(){
//get elements
var myRange = document.getElementById("RainRange");
var myNumber = document.getElementById("RainNumber");
//copy the value over
myRange.value = myNumber.value;
sendRain();
} // end function
ws.onmessage = function(evt){
var myOutput = document.getElementById("serverFeedback");
myOutput.value = evt.data;
}
|
Fix test error (still failing)
|
var chai = require('chai');
var expect = chai.expect;
/* fake api server */
var server = require('./server');
var api = server.createServer();
var clubs = [
{
id: '205',
name: 'SURTEX',
logo: 'http://121.199.38.39/hphoto/logoclub/NewClub.jpgw76_h76.jpg'
}
];
var responses = {
'clubs/': server.createGetResponse(JSON.stringify(clubs), 'application/json')
};
var bot = require('..')({url: api.url});
before(function (done) {
api.listen(api.port, function () {
for (var route in responses) {
api.on('/' + route, responses[route]);
}
done();
});
});
/* test cases */
describe('letsface api', function () {
it('should reply club list', function (done) {
var req = {
weixin: {
MsgType: 'text',
Content: 'clubs'
}
};
var res = {
reply: function (result) {
expect(result).to.equal('1 clubs');
done();
}
};
bot(req, res);
});
});
|
var chai = require('chai');
var expect = chai.expect;
/* fake api server */
var server = require('./server');
var api = server.createServer();
var clubs = [
{
id: '205',
name: 'SURTEX',
logo: 'http://121.199.38.39/hphoto/logoclub/NewClub.jpgw76_h76.jpg'
}
];
var responses = {
'clubs/': server.createGetResponse(JSON.stringify(clubs), 'application/json')
};
var bot = require('..')({url: api.url});
before(function (done) {
api.listen(api.port, function () {
for (var route in responses) {
api.on('/' + route, responses[route]);
}
done();
});
});
/* test cases */
describe('letsface api', function (done) {
var req = {
weixin: {
MsgType: 'text',
Content: 'clubs'
}
};
var res = {
reply: function (result) {
expect(result).to.equal('1 clubs');
done();
}
};
it('should reply club list', function () {
bot(req, res);
});
});
|
Add test for find string
|
var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
it('should add string to trie', function() {
expect(trie.add('test')).to.be.undefined;
});
it('should correctly find an added string', function() {
trie.add('test');
expect(trie.find('test')).to.be.true;
});
});
|
var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should add string to trie', function() {
expect(trie.add('test')).to.be.undefined;
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
});
|
Make sure to return the favorites count
|
<?php namespace App\Data;
use Eloquent;
use DiscussionPresenter;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
class Discussion extends Eloquent
{
use SoftDeletes, PresentableTrait;
protected $fillable = ['title', 'body', 'user_id', 'topic_id'];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $presenter = DiscussionPresenter::class;
protected static function boot()
{
parent::boot();
static::addGlobalScope('replyCount', function ($builder) {
$builder->withCount('replies');
});
}
//--------------------------------------------------------------------------
// Relationships
//--------------------------------------------------------------------------
public function answer()
{
return $this->hasOne(Reply::class, 'id', 'answer_id')->withCount('favorites');
}
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
public function replies()
{
return $this->hasMany(Reply::class)->withCount('favorites');
}
public function topic()
{
return $this->belongsTo(Topic::class);
}
//--------------------------------------------------------------------------
// Model Methods
//--------------------------------------------------------------------------
public function addReply(array $data)
{
$this->replies()->create($data);
}
public function scopeFilter($query, $filters)
{
return $filters->apply($query);
}
}
|
<?php namespace App\Data;
use Eloquent;
use DiscussionPresenter;
use Laracasts\Presenter\PresentableTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
class Discussion extends Eloquent
{
use SoftDeletes, PresentableTrait;
protected $fillable = ['title', 'body', 'user_id', 'topic_id'];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $presenter = DiscussionPresenter::class;
protected static function boot()
{
parent::boot();
static::addGlobalScope('replyCount', function ($builder) {
$builder->withCount('replies');
});
}
//--------------------------------------------------------------------------
// Relationships
//--------------------------------------------------------------------------
public function answer()
{
return $this->hasOne(Reply::class, 'id', 'answer_id');
}
public function author()
{
return $this->belongsTo(User::class, 'user_id');
}
public function replies()
{
return $this->hasMany(Reply::class)->withCount('favorites');
}
public function topic()
{
return $this->belongsTo(Topic::class);
}
//--------------------------------------------------------------------------
// Model Methods
//--------------------------------------------------------------------------
public function addReply(array $data)
{
$this->replies()->create($data);
}
public function scopeFilter($query, $filters)
{
return $filters->apply($query);
}
}
|
Remove unused json import in api wrapper
|
import os
import requests
class APIWrapper(object):
def __init__(self, base_url=None, auth_token=None):
if base_url:
self.base_url = base_url
else:
self.base_url = "http://api.football-data.org/v1"
if auth_token:
self.headers = {
'X-Auth-Token': auth_token
}
else:
self.headers = {}
def do_request(self, url, filters=None):
params = filters if filters else {}
r = requests.get(url=url, params=params, headers=self.headers)
if r.status_code == requests.codes.ok:
return r.json()
return None
def all_competitions(self):
url = "%s/competitions" % self.base_url
response = self.do_request(url=url)
return response
def main():
api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"])
res = api.do_request("http://api.football-data.org/v1/competitions")
print(res)
if __name__ == "__main__":
main()
|
import json
import os
import requests
class APIWrapper(object):
def __init__(self, base_url=None, auth_token=None):
if base_url:
self.base_url = base_url
else:
self.base_url = "http://api.football-data.org/v1"
if auth_token:
self.headers = {
'X-Auth-Token': auth_token
}
else:
self.headers = {}
def do_request(self, url, filters=None):
params = filters if filters else {}
r = requests.get(url=url, params=params, headers=self.headers)
if r.status_code == requests.codes.ok:
return r.json()
return None
def all_competitions(self):
url = "%s/competitions" % self.base_url
response = self.do_request(url=url)
return response
def main():
api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"])
res = api.do_request("http://api.football-data.org/v1/competitions")
print(res)
if __name__ == "__main__":
main()
|
Add a test for the get_thumb function.
|
# -*- coding:utf-8 -*-
import os
try:
import unittest2 as unittest
except ImportError:
import unittest # NOQA
from sigal.settings import read_settings, get_thumb
class TestSettings(unittest.TestCase):
"Read a settings file and check that the configuration is well done."
def setUp(self):
"Read the sample config file"
self.path = os.path.abspath(os.path.dirname(__file__))
default_conf = os.path.join(self.path, 'sample', 'sigal.conf.py')
self.settings = read_settings(default_conf)
def test_sizes(self):
"Test that image sizes are correctly read"
self.assertTupleEqual(self.settings['img_size'], (640, 480))
self.assertTupleEqual(self.settings['thumb_size'], (200, 150))
def test_settings(self):
self.assertEqual(self.settings['thumb_suffix'], '.tn')
def test_thumb(self):
self.assertEqual(get_thumb(self.settings, 'example.jpg'),
'thumbnails/example.tn.jpg')
self.assertEqual(get_thumb(self.settings, 'test/example.jpg'),
'test/thumbnails/example.tn.jpg')
|
# -*- coding:utf-8 -*-
import os
try:
import unittest2 as unittest
except ImportError:
import unittest # NOQA
from sigal.settings import read_settings
class TestSettings(unittest.TestCase):
"Read a settings file and check that the configuration is well done."
def setUp(self):
"Read the sample config file"
self.path = os.path.abspath(os.path.dirname(__file__))
default_conf = os.path.join(self.path, 'sample', 'sigal.conf.py')
self.settings = read_settings(default_conf)
def test_sizes(self):
"Test that image sizes are correctly read"
self.assertTupleEqual(self.settings['img_size'], (640, 480))
self.assertTupleEqual(self.settings['thumb_size'], (200, 150))
def test_settings(self):
self.assertEqual(self.settings['thumb_suffix'], '.tn')
|
Migrate to new plugin api
|
export default function ({ Plugin, types: t }) {
const visitor = {
Property: {
exit(node) {
if (node.computed || node.key.name !== 'propTypes') {
return;
}
const parent = this.findParent((parent) => {
return parent.type === 'CallExpression';
});
if (parent && parent.get('callee').matchesPattern('React.createClass')) {
this.dangerouslyRemove();
}
}
}
};
return new Plugin('react-remove-prop-types', {
visitor,
metadata: {
group: 'builtin-pre'
}
});
};
|
module.exports = function ({Transformer}) {
return new Transformer('minification.removeReactPropTypes', {
Property: {
exit(node) {
if (node.computed || node.key.name !== 'propTypes') {
return;
}
const parent = this.findParent((parent) => {
return parent.type === 'CallExpression';
});
if (parent && parent.get('callee').matchesPattern('React.createClass')) {
if (this.dangerouslyRemove) {
this.dangerouslyRemove();
} else {
this.remove();
}
}
}
}
});
};
|
Declare add() method in log class as package private
|
package org.tinylog.core.test;
import java.util.ArrayList;
import java.util.List;
import org.tinylog.core.Level;
/**
* Storage for {@link LogEntry LogEntries}.
*/
public class Log {
private Level minLevel;
private List<LogEntry> entries;
/** */
public Log() {
minLevel = Level.INFO;
entries = new ArrayList<>();
}
/**
* Gets the new minimum severity level. All log entries with a severity level less severe than the minimum level are
* ignored.
*
* @return The actual configured minimum severity level
*/
public Level getMinLevel() {
return minLevel;
}
/**
* Sets a new minimum severity level. All log entries with a severity level less severe than the minimum level are
* ignored.
*
* @param level New minimum severity level
*/
public void setMinLevel(Level level) {
this.minLevel = level;
}
/**
* Retrieves all stored log entries and clears the entire log afterwards.
*
* @return All store log entries
*/
public Iterable<LogEntry> consume() {
try {
return entries;
} finally {
entries = new ArrayList<>();
}
}
/**
* Appends a new log entry to the end of this log.
*
* @param entry Log entry to append to this log
*/
void add(LogEntry entry) {
if (entry.getLevel().ordinal() <= minLevel.ordinal()) {
entries.add(entry);
}
}
}
|
package org.tinylog.core.test;
import java.util.ArrayList;
import java.util.List;
import org.tinylog.core.Level;
/**
* Storage for {@link LogEntry LogEntries}.
*/
public class Log {
private Level minLevel;
private List<LogEntry> entries;
/** */
public Log() {
minLevel = Level.INFO;
entries = new ArrayList<>();
}
/**
* Gets the new minimum severity level. All log entries with a severity level less severe than the minimum level are
* ignored.
*
* @return The actual configured minimum severity level
*/
public Level getMinLevel() {
return minLevel;
}
/**
* Sets a new minimum severity level. All log entries with a severity level less severe than the minimum level are
* ignored.
*
* @param level New minimum severity level
*/
public void setMinLevel(Level level) {
this.minLevel = level;
}
/**
* Appends a new log entry to the end of this log.
*
* @param entry Log entry to append to this log
*/
public void add(LogEntry entry) {
if (entry.getLevel().ordinal() <= minLevel.ordinal()) {
entries.add(entry);
}
}
/**
* Retrieves all stored log entries and clears the entire log afterwards.
*
* @return All store log entries
*/
public Iterable<LogEntry> consume() {
try {
return entries;
} finally {
entries = new ArrayList<>();
}
}
}
|
Use Notifiable trait on user model
|
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the item's queue entry if it has one.
*/
public function items()
{
return $this->hasMany(Item::class);
}
}
|
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
// use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the item's queue entry if it has one.
*/
public function items()
{
return $this->hasMany(Item::class);
}
}
|
Use xmlrpclib.escape for escaping in PangoMarkupRenderer
|
# vim:fileencoding=utf-8:noet
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
from xmlrpclib import escape as _escape
class PangoMarkupRenderer(Renderer):
'''Powerline Pango markup segment renderer.'''
@staticmethod
def hlstyle(*args, **kwargs):
# We don't need to explicitly reset attributes, so skip those calls
return ''
def hl(self, contents, fg=None, bg=None, attr=None):
'''Highlight a segment.'''
awesome_attr = []
if fg is not None:
if fg is not False and fg[1] is not False:
awesome_attr += ['foreground="#{0:06x}"'.format(fg[1])]
if bg is not None:
if bg is not False and bg[1] is not False:
awesome_attr += ['background="#{0:06x}"'.format(bg[1])]
if attr is not None and attr is not False:
if attr & ATTR_BOLD:
awesome_attr += ['font_weight="bold"']
if attr & ATTR_ITALIC:
awesome_attr += ['font_style="italic"']
if attr & ATTR_UNDERLINE:
awesome_attr += ['underline="single"']
return '<span ' + ' '.join(awesome_attr) + '>' + contents + '</span>'
escape = staticmethod(_escape)
renderer = PangoMarkupRenderer
|
# vim:fileencoding=utf-8:noet
from powerline.renderer import Renderer
from powerline.colorscheme import ATTR_BOLD, ATTR_ITALIC, ATTR_UNDERLINE
class PangoMarkupRenderer(Renderer):
'''Powerline Pango markup segment renderer.'''
@staticmethod
def hlstyle(*args, **kwargs):
# We don't need to explicitly reset attributes, so skip those calls
return ''
def hl(self, contents, fg=None, bg=None, attr=None):
'''Highlight a segment.'''
awesome_attr = []
if fg is not None:
if fg is not False and fg[1] is not False:
awesome_attr += ['foreground="#{0:06x}"'.format(fg[1])]
if bg is not None:
if bg is not False and bg[1] is not False:
awesome_attr += ['background="#{0:06x}"'.format(bg[1])]
if attr is not None and attr is not False:
if attr & ATTR_BOLD:
awesome_attr += ['font_weight="bold"']
if attr & ATTR_ITALIC:
awesome_attr += ['font_style="italic"']
if attr & ATTR_UNDERLINE:
awesome_attr += ['underline="single"']
return '<span ' + ' '.join(awesome_attr) + '>' + contents + '</span>'
renderer = PangoMarkupRenderer
|
Clear the message box once it's done.
|
// Defines the top-level angular functionality. This will likely be refactored
// as I go.
var pyrcApp = angular.module("pyrcApp", []);
pyrcApp.controller("ircCtrl", function($scope) {
$scope.messages = [];
$scope.msg = "";
// Define the controller method for sending an IRC message.
$scope.sendIrcMessage = function() {
message = irc.privmsg("#python-requests", $scope.msg);
window.conn.send(message);
// Clear the message box.
$scope.msg = "";
};
ircLoop(function(message) {
$scope.$apply(function() {
if (message.command == "PRIVMSG") {
$scope.messages.push({
from: message.prefix.split('!', 2)[0],
text: message.trailing
});
}
});
});
});
|
// Defines the top-level angular functionality. This will likely be refactored
// as I go.
var pyrcApp = angular.module("pyrcApp", []);
pyrcApp.controller("ircCtrl", function($scope) {
$scope.messages = [];
$scope.msg = "";
// Define the controller method for sending an IRC message.
$scope.sendIrcMessage = function() {
message = irc.privmsg("#python-requests", $scope.msg);
window.conn.send(message);
};
ircLoop(function(message) {
$scope.$apply(function() {
if (message.command == "PRIVMSG") {
$scope.messages.push({
from: message.prefix.split('!', 2)[0],
text: message.trailing
});
}
});
});
});
|
Fix empty properties error in misspelled properties
|
'use strict';
var helpers = require('../helpers'),
yaml = require('js-yaml'),
fs = require('fs'),
path = require('path');
var properties = yaml.safeLoad(fs.readFileSync(path.join(__dirname, '../../data', 'properties.yml'), 'utf8')).split(' ');
module.exports = {
'name': 'no-misspelled-properties',
'defaults': {
'extra-properties': []
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('property', function (node) {
if (node.first().is('ident')) {
var curProperty = node.first().content;
if (curProperty.charAt(0) === '-') {
curProperty = helpers.stripPrefix(curProperty);
}
if (curProperty.length > 0 && properties.indexOf(curProperty) === -1 && parser.options['extra-properties'].indexOf(curProperty) === -1) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': node.start.line,
'column': node.start.column,
'message': 'Property `' + curProperty + '` appears to be spelled incorrectly',
'severity': parser.severity
});
}
}
});
return result;
}
};
|
'use strict';
var helpers = require('../helpers'),
yaml = require('js-yaml'),
fs = require('fs'),
path = require('path');
var properties = yaml.safeLoad(fs.readFileSync(path.join(__dirname, '../../data', 'properties.yml'), 'utf8')).split(' ');
module.exports = {
'name': 'no-misspelled-properties',
'defaults': {
'extra-properties': []
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('property', function (node) {
if (node.first().is('ident')) {
var curProperty = node.first().content;
if (curProperty.charAt(0) === '-') {
curProperty = helpers.stripPrefix(curProperty);
}
if (properties.indexOf(curProperty) === -1 && parser.options['extra-properties'].indexOf(curProperty) === -1) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': node.start.line,
'column': node.start.column,
'message': 'Property `' + curProperty + '` appears to be spelled incorrectly',
'severity': parser.severity
});
}
}
});
return result;
}
};
|
Add for loop in order to get correct structure of data
|
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* TaxonomyNodeRepository
*
* This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
* repository methods below.
*/
class TaxonomyNodeRepository extends EntityRepository
{
public function getDatabases($fennec_id){
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('t.taxonomyNodeId', 'db.name')
->from('AppBundle\Entity\TaxonomyNode', 't')
->innerJoin('AppBundle\Entity\Db','db','WITH', 't.db = db.dbId')
->where('t.fennec = :fennec_id')
->setParameter('fennec_id', $fennec_id);
$query = $qb->getQuery();
$data = $query->getArrayResult();
$result = array();
for($i=0;$i<sizeof($data);$i++){
$result[$data[$i]['name']] = $data[$i]['taxonomyNodeId'];
}
return $result;
}
public function getLineage(){
}
}
|
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* TaxonomyNodeRepository
*
* This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
* repository methods below.
*/
class TaxonomyNodeRepository extends EntityRepository
{
public function getDatabases($fennec_id){
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('t.taxonomyNodeId', 'db.name')
->from('AppBundle\Entity\TaxonomyNode', 't')
->innerJoin('AppBundle\Entity\Db','db','WITH', 't.db = db.dbId')
->where('t.fennec = :fennec_id')
->setParameter('fennec_id', $fennec_id);
$query = $qb->getQuery();
$result = $query->getArrayResult();
// $result = array();
// while($row = $stm_get_taxonomy_databases->fetch(PDO::FETCH_ASSOC)){
// $result[$row['name']] = $row['taxonomy_node_id'];
// }
// return $result;
}
public function getLineage(){
}
}
|
Remove captured output last line from the API
no longer needed
|
{
"draw": {{draw}},
"recordsTotal": {{recordsTotal}},
"recordsFiltered": {{recordsFiltered}},
"data": [
{% autoescape false %}
{%- for run in runs -%}
{
"id": {{run._id | tostr | default | tojson}},
"experiment_name": {{run.experiment.name | default | tojson}},
"status": {{run.status | default | tojson | safe}},
"is_alive": {{run.heartbeat | default | timediff | detect_alive_experiment | tojson }},
"start_time": {{run.start_time | default | format_datetime | tojson}},
"heartbeat": {{run.heartbeat | default | format_datetime | tojson}},
"heartbeat_diff": {{run.heartbeat | default | timediff | tojson}},
"hostname": {{run.host.hostname | default | tojson}},
{# commented out: "captured_out_last_line": {{run.captured_out | default | last_line | tojson}}, #}
"result":{{run.result | default | tojson}}
{%- if full_object -%},
"object": {{run | dump_json}}
{% endif %}
}
{%- if not loop.last -%}
,
{% endif %}
{% endfor %}
{% endautoescape %}
]
}
|
{
"draw": {{draw}},
"recordsTotal": {{recordsTotal}},
"recordsFiltered": {{recordsFiltered}},
"data": [
{% autoescape false %}
{%- for run in runs -%}
{
"id": {{run._id | tostr | default | tojson}},
"experiment_name": {{run.experiment.name | default | tojson}},
"status": {{run.status | default | tojson | safe}},
"is_alive": {{run.heartbeat | default | timediff | detect_alive_experiment | tojson }},
"start_time": {{run.start_time | default | format_datetime | tojson}},
"heartbeat": {{run.heartbeat | default | format_datetime | tojson}},
"heartbeat_diff": {{run.heartbeat | default | timediff | tojson}},
"hostname": {{run.host.hostname | default | tojson}},
"captured_out_last_line": {{run.captured_out | default | last_line | tojson}},
"result":{{run.result | default | tojson}}
{%- if full_object -%},
"object": {{run | dump_json}}
{% endif %}
}
{%- if not loop.last -%}
,
{% endif %}
{% endfor %}
{% endautoescape %}
]
}
|
Add type-hints to Controller-related classes
|
<?php
declare(strict_types=1);
namespace AlgoWeb\PODataLaravel\Controllers;
class MetadataControllerContainer
{
/** @var array[] */
private $metadata;
/**
* @param array[] $meta
*/
public function setMetadata(array $meta): void
{
$this->metadata = $meta;
}
/**
* @return array[]
*/
public function getMetadata()
{
return $this->metadata;
}
/**
* @param string $modelName
* @param string $verb
* @return mixed
*/
public function getMapping($modelName, $verb)
{
return $this->metadata[$modelName][$verb];
}
}
|
<?php
declare(strict_types=1);
namespace AlgoWeb\PODataLaravel\Controllers;
class MetadataControllerContainer
{
private $metadata;
/**
* @param array $meta
*/
public function setMetadata(array $meta)
{
$this->metadata = $meta;
}
/**
* @return array
*/
public function getMetadata()
{
return $this->metadata;
}
/**
* @param string $modelName
* @param string $verb
* @return array
*/
public function getMapping($modelName, $verb)
{
return $this->metadata[$modelName][$verb];
}
}
|
Remove requirement on presence of config file
The NipapConfig object required the presence of a configuration file. As
it is benficial to be able to load the NipapConfig without a
configuration file (for example when building docs using Sphinx), this
requirement has been removed.
|
import ConfigParser
class NipapConfig(ConfigParser.SafeConfigParser):
""" Makes configuration data available.
Implemented as a class with a shared state; once an instance has been
created, new instances with the same state can be obtained by calling
the custructor again.
"""
__shared_state = {}
_config = None
_cfg_path = None
def __init__(self, cfg_path=None, default={}):
""" Takes config file path and command line arguments.
"""
self.__dict__ = self.__shared_state
if len(self.__shared_state) == 0:
# First time - create new instance!
self._cfg_path = cfg_path
ConfigParser.ConfigParser.__init__(self, default)
self.read_file()
def read_file(self):
""" Read the configuration file
"""
try:
cfg_fp = open(self._cfg_path, 'r')
self.readfp(cfg_fp)
except IOError, e:
raise NipapConfigError(str(e))
class NipapConfigError(Exception):
pass
|
import ConfigParser
class NipapConfig(ConfigParser.SafeConfigParser):
""" Makes configuration data available.
Implemented as a class with a shared state; once an instance has been
created, new instances with the same state can be obtained by calling
the custructor again.
"""
__shared_state = {}
_config = None
_cfg_path = None
def __init__(self, cfg_path=None, default={}):
""" Takes config file path and command line arguments.
"""
self.__dict__ = self.__shared_state
if len(self.__shared_state) == 0:
# First time - create new instance!
if cfg_path is None:
raise NipapConfigError("missing configuration file")
self._cfg_path = cfg_path
ConfigParser.ConfigParser.__init__(self, default)
self.read_file()
def read_file(self):
""" Read the configuration file
"""
try:
cfg_fp = open(self._cfg_path, 'r')
self.readfp(cfg_fp)
except IOError, e:
raise NipapConfigError(str(e))
class NipapConfigError(Exception):
pass
|
FindUsedBlobs: Check for seen blobs before loading trees
The only effective change in behavior is that that toplevel nodes can
also be skipped.
|
package restic
import "context"
// FindUsedBlobs traverses the tree ID and adds all seen blobs (trees and data
// blobs) to the set blobs. Already seen tree blobs will not be visited again.
func FindUsedBlobs(ctx context.Context, repo Repository, treeID ID, blobs BlobSet) error {
h := BlobHandle{ID: treeID, Type: TreeBlob}
if blobs.Has(h) {
return nil
}
blobs.Insert(h)
tree, err := repo.LoadTree(ctx, treeID)
if err != nil {
return err
}
for _, node := range tree.Nodes {
switch node.Type {
case "file":
for _, blob := range node.Content {
blobs.Insert(BlobHandle{ID: blob, Type: DataBlob})
}
case "dir":
err := FindUsedBlobs(ctx, repo, *node.Subtree, blobs)
if err != nil {
return err
}
}
}
return nil
}
|
package restic
import "context"
// FindUsedBlobs traverses the tree ID and adds all seen blobs (trees and data
// blobs) to the set blobs. Already seen tree blobs will not be visited again.
func FindUsedBlobs(ctx context.Context, repo Repository, treeID ID, blobs BlobSet) error {
blobs.Insert(BlobHandle{ID: treeID, Type: TreeBlob})
tree, err := repo.LoadTree(ctx, treeID)
if err != nil {
return err
}
for _, node := range tree.Nodes {
switch node.Type {
case "file":
for _, blob := range node.Content {
blobs.Insert(BlobHandle{ID: blob, Type: DataBlob})
}
case "dir":
subtreeID := *node.Subtree
h := BlobHandle{ID: subtreeID, Type: TreeBlob}
if blobs.Has(h) {
continue
}
err := FindUsedBlobs(ctx, repo, subtreeID, blobs)
if err != nil {
return err
}
}
}
return nil
}
|
Remove unneeded reference to my-component.js from main.js.
|
/* 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.
*/
/**
* @fileoverview All js files needed for site included here.
<% if (isVendor) { %> * @author <%= agencyPOC %> (<%= agencyName %>)<% } %>
*/
// Services.
{% include "<%= projectDomain %><%= projectPath %>js/my-service.js" %}
// Components.
{% include "<%= projectDomain %><%= projectPath %>js/components/my-component/my-component-controller.js" %}
{% include "<%= projectDomain %><%= projectPath %>js/components/my-component/my-component-directive.js" %}
// Controllers.
{% include "<%= projectDomain %><%= projectPath %>js/sections/home-controller.js" %}
// Application module.
{% include "<%= projectDomain %><%= projectPath %>js/app.js" %}
goog.require('boilerplateNg.app');
|
/* 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.
*/
/**
* @fileoverview All js files needed for site included here.
<% if (isVendor) { %> * @author <%= agencyPOC %> (<%= agencyName %>)<% } %>
*/
// Services.
{% include "<%= projectDomain %><%= projectPath %>js/my-service.js" %}
// Components.
{% include "<%= projectDomain %><%= projectPath %>js/components/my-component/my-component-controller.js" %}
{% include "<%= projectDomain %><%= projectPath %>js/components/my-component/my-component-directive.js" %}
{% include "<%= projectDomain %><%= projectPath %>js/components/my-component/my-component.js" %}
// Controllers.
{% include "<%= projectDomain %><%= projectPath %>js/sections/home-controller.js" %}
// Application module.
{% include "<%= projectDomain %><%= projectPath %>js/app.js" %}
goog.require('boilerplateNg.app');
|
Add javadoc to batch builder.
|
package com.novoda.downloadmanager;
/**
* Builds instances of {@link Batch} using a fluent API.
*/
public interface BatchBuilder {
/**
* Sets {@link BatchFileBuilder} to build a {@link Batch} that will download a {@link BatchFile}
* from a given networkAddress.
*
* @param networkAddress to download file from.
* @return {@link BatchFileBuilder}.
*/
BatchFileBuilder downloadFrom(String networkAddress);
/**
* Build a new {@link Batch} instance.
*
* @return an instance of {@link Batch}.
*/
Batch build();
/**
* Creates a {@link BatchBuilder} from a {@link Batch}.
*
* @param batch to create the {@link BatchBuilder} from.
* @return {@link BatchBuilder}.
*/
static BatchBuilder from(Batch batch) {
InternalBatchBuilder builder = (InternalBatchBuilder) Batch.with(batch.storageRoot(), batch.downloadBatchId(), batch.title());
for (BatchFile batchFile : batch.batchFiles()) {
builder.withFile(batchFile);
}
return builder;
}
}
|
package com.novoda.downloadmanager;
/**
* Builds instances of {@link Batch} using a fluent API.
*/
public interface BatchBuilder {
/**
* Sets {@link BatchFileBuilder} to build a {@link Batch} that will download a {@link BatchFile}
* from a given networkAddress.
*
* @param networkAddress to download file from.
* @return {@link BatchFileBuilder}.
*/
BatchFileBuilder downloadFrom(String networkAddress);
/**
* Build a new {@link Batch} instance.
*
* @return an instance of {@link Batch}.
*/
Batch build();
static BatchBuilder from(Batch batch) {
InternalBatchBuilder builder = (InternalBatchBuilder) Batch.with(batch.storageRoot(), batch.downloadBatchId(), batch.title());
for (BatchFile batchFile : batch.batchFiles()) {
builder.withFile(batchFile);
}
return builder;
}
}
|
Fix missing renaming of logout => logoutLink
During development, this was previously named `logout`. This cleans up a
remaining instance of `logout`, renaming it to the preferred
`logoutLink` to remain consistent with the rest of the codebase.
|
import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logoutLink: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
|
import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
logout: links.logout,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}, logout: links.logout} // eslint-disable-line no-throw-literal
}
}
|
Add extra check for environment variables
isWebAppBuild will not return true if either the environment variables
are set to production or WEBAPP is set.
|
import { REGTEST_CORE_API_ENDPOINT } from '../account/store/settings/default'
export function openInNewTab(url) {
const win = window.open(url, '_blank')
win.focus()
}
export function isWindowsBuild() {
const isWindowsBuildCompileFlag = false
return isWindowsBuildCompileFlag === true
}
export function isWebAppBuild() {
const URL = document.createElement('a')
URL.href = window.location.href
const hostname = URL.hostname
const isWebAppHostnameFlag = hostname === 'browser.blockstack.org'
const isWebAppCompileFlag = process.env.NODE_ENV === 'production' || process.env.WEBAPP
return isWebAppHostnameFlag || isWebAppCompileFlag
}
/**
* Will determine whether or not we should try to
* perform "private" core endpoint functions --
* basically, attempts to read/write the core wallet.
* Tests using the compile flags determining if its
* a Windows / WebApp build and using the URL --
* if it's the standard regtest URL, then, yes, try
* to do the private operations, otherwise, no.
* @private
*/
export function isCoreEndpointDisabled(testUrl) {
return (isWindowsBuild() || isWebAppBuild() ||
!testUrl.startsWith(REGTEST_CORE_API_ENDPOINT))
}
const mobileWindowWidth = 768
export function isMobile() {
if (window.innerWidth <= mobileWindowWidth) {
return true
} else {
return false
}
}
|
import { REGTEST_CORE_API_ENDPOINT } from '../account/store/settings/default'
export function openInNewTab(url) {
const win = window.open(url, '_blank')
win.focus()
}
export function isWindowsBuild() {
const isWindowsBuildCompileFlag = false
return isWindowsBuildCompileFlag === true
}
export function isWebAppBuild() {
const URL = document.createElement('a')
URL.href = window.location.href
const hostname = URL.hostname
return hostname === 'browser.blockstack.org'
//let isWebAppBuildCompileFlag = false
//return isWebAppBuildCompileFlag === true
}
/**
* Will determine whether or not we should try to
* perform "private" core endpoint functions --
* basically, attempts to read/write the core wallet.
* Tests using the compile flags determining if its
* a Windows / WebApp build and using the URL --
* if it's the standard regtest URL, then, yes, try
* to do the private operations, otherwise, no.
* @private
*/
export function isCoreEndpointDisabled(testUrl) {
return (isWindowsBuild() || isWebAppBuild() ||
!testUrl.startsWith(REGTEST_CORE_API_ENDPOINT))
}
const mobileWindowWidth = 768
export function isMobile() {
if (window.innerWidth <= mobileWindowWidth) {
return true
} else {
return false
}
}
|
Make mdb2 reference actually read-only.
svn commit r5671
|
<?php
require_once 'Site/SiteApplicationModule.php';
require_once 'SwatDB/exceptions/SwatDBException.php';
require_once 'MDB2.php';
/**
* Application module for database connectivity
*
* @package Site
* @copyright 2004-2006 silverorange
*/
class SiteDatabaseModule extends SiteApplicationModule
{
// {{{ public properties
/**
* Name of the database
*
* This is the name of the database to connect to. Set this before calling
* {@link SiteApplication::init()}, afterwords consider it readonly.
*
* @var string
*/
public $name;
// }}}
// {{{ protected properties
/**
* The database object
*
* @var MDB2_Connection database connection object. This property is
* readonly publically accessible as 'mdb2'.
*/
protected $connection = null;
// }}}
// {{{ public function init()
public function init()
{
// TODO: change to array /form of DSN and move parts to a secure include file.
$dsn = 'pgsql://php:test@zest/'.$this->name;
$this->connection = MDB2::connect($dsn);
$this->connection->options['debug'] = true;
if (MDB2::isError($this->connection))
throw new SwatDBException($this->connection);
}
// }}}
// {{{ private function __get()
/**
* Allows readonly access to the database connection object
*/
private function __get($name)
{
if (strcmp($name, 'mdb2') == 0)
return $this->connection;
throw new SiteException("No property with the name '{$name}' exists.");
}
// }}}
}
?>
|
<?php
require_once 'Site/SiteApplicationModule.php';
require_once 'SwatDB/exceptions/SwatDBException.php';
require_once 'MDB2.php';
/**
* Application module for database connectivity
*
* @package Site
* @copyright 2004-2006 silverorange
*/
class SiteDatabaseModule extends SiteApplicationModule
{
// {{{ public properties
/**
* Name of the database
*
* This is the name of the database to connect to. Set this before calling
* {@link SiteApplication::init()}, afterwords consider it readonly.
*
* @var string
*/
public $name;
/**
* The database object
*
* @var MDB2_Connection Database connection object (readonly)
*/
public $mdb2 = null;
// }}}
// {{{ public function init()
public function init()
{
// TODO: change to array /form of DSN and move parts to a secure include file.
$dsn = 'pgsql://php:test@zest/'.$this->name;
$this->mdb2 = MDB2::connect($dsn);
$this->mdb2->options['debug'] = true;
if (MDB2::isError($this->mdb2))
throw new SwatDBException($this->mdb2);
}
// }}}
}
?>
|
[Minor] Clean up use of deprecated method
Signed-off-by: Gregor Zurowski <5fdc67d2166bcdd1d3aa4ed45ea5a25e9b21bc20@zurowski.org>
|
/**
* 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.camel.spring.boot;
import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
@Configuration
public class RouteConfigWithCamelContextInjected {
@Autowired
private CamelContext camelContext;
@Bean
public RoutesBuilder routeCreatedWithInjectedCamelContext() {
Assert.notNull(camelContext, "camelContext must not be null");
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("seda:test").to("seda:test");
}
};
}
}
|
/**
* 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.camel.spring.boot;
import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
@Configuration
public class RouteConfigWithCamelContextInjected {
@Autowired
private CamelContext camelContext;
@Bean
public RoutesBuilder routeCreatedWithInjectedCamelContext() {
Assert.notNull(camelContext);
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("seda:test").to("seda:test");
}
};
}
}
|
Check out the HAR log
|
<?php
set_error_handler(
function ($errno, $errstr, $errfile, $errline )
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
);
require __DIR__ . '/../vendor/autoload.php';
$driver = RemoteWebDriver::create('127.0.0.1:4444/wd/hub', DesiredCapabilities::phantomjs());
$driver->manage()->window()->setSize(new WebDriverDimension(1024, 1024));
$driver->manage()->timeouts()->implicitlyWait(8);
$driver->get('http://www.sbb.ch/geschaeftsreisen.html');
$driver->findElement(WebDriverBy::id('btUser'))->sendKeys('stc-cpedersoli');
$driver->executeScript('console.log(1611);');
echo json_encode(
array_map(
function ($logEntry)
{
return json_decode($logEntry['message'], true);
},
$driver->manage()->getLog('har')
)
);
|
<?php
set_error_handler(
function ($errno, $errstr, $errfile, $errline )
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
);
require __DIR__ . '/../vendor/autoload.php';
$driver = RemoteWebDriver::create('127.0.0.1:4444/wd/hub', DesiredCapabilities::phantomjs());
$driver->manage()->window()->setSize(new WebDriverDimension(1024, 1024));
$driver->manage()->timeouts()->implicitlyWait(16);
$driver->get('http://www.sbb.ch/geschaeftsreisen.html');
$driver->takeScreenshot(__DIR__ . '/s1.png');
$driver->findElement(WebDriverBy::id('btUser'))->sendKeys('stc-cpedersoli');
$driver->takeScreenshot(__DIR__ . '/s2.png');
|
Update to image src selector
|
/*
for each li
color = find span color --- this.text
url = find main prod image -- this.url
category Swatch Color Button = matching color.url
end
on click
*/
var colorBtnSrc = {};
$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').each( function getColorPhotosSrcs(){
var listings = $(this);
prodColor = $(this).find('.name').text();
console.log(prodColor);
$(this).find('label').click();
// find url of img when this li is checked and store it
// for (i = 0; i < listings.length; i++) {
// var colorImgSrc += $(document).find('.MagicZoomPlus img').attr('src');
// console.log(colorImgSrc);
// }
colorBtnSrc[prodColor] = $(document).find('.MagicZoomPlus').attr('src');
})
console.log(colorBtnSrc);
//$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').removeClass('selectedValue').find('.radio span').removeClass('checked');
//$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).addClass('selectedValue').find('.radio span').addClass('checked');
//$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).find('label').click();
|
/*
for each li
color = find span color --- this.text
url = find main prod image -- this.url
category Swatch Color Button = matching color.url
end
on click
*/
var colorBtnSrc = {};
$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').each( function getColorPhotosSrcs(){
var listings = $(this);
prodColor = $(this).find('.name').text();
console.log(prodColor);
$(this).find('label').click();
// find url of img when this li is checked and store it
// for (i = 0; i < listings.length; i++) {
// var colorImgSrc += $(document).find('.MagicZoomPlus img').attr('src');
// console.log(colorImgSrc);
// }
colorBtnSrc[prodColor] = $(document).find('.MagicZoomPlus img').attr('src');
})
console.log(colorBtnSrc);
//$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').removeClass('selectedValue').find('.radio span').removeClass('checked');
//$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).addClass('selectedValue').find('.radio span').addClass('checked');
//$("span:contains('Color')").parents().eq(2).find('.productAttributeValue li').eq(2).find('label').click();
|
Fix sorting of the imports.
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from PyFVCOM import ctd_tools
from PyFVCOM import current_tools
from PyFVCOM import grid_tools
from PyFVCOM import ll2utm
from PyFVCOM import ll2utm as coordinate_tools
from PyFVCOM import ocean_tools
from PyFVCOM import stats_tools
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide_tools
from PyFVCOM import plot
from PyFVCOM import process_results
from PyFVCOM import read_results
from PyFVCOM import utilities
|
"""
The FVCOM Python toolbox (PyFVCOM)
"""
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from PyFVCOM import ctd_tools
from PyFVCOM import current_tools
from PyFVCOM import grid_tools
from PyFVCOM import ll2utm
from PyFVCOM import ll2utm as coordinate_tools
from PyFVCOM import ocean_tools
from PyFVCOM import stats_tools
from PyFVCOM import tidal_ellipse
from PyFVCOM import tide_tools
from PyFVCOM import process_results
from PyFVCOM import read_results
from PyFVCOM import plot
from PyFVCOM import utilities
|
Remove required community.image in list
|
import React, { PropTypes } from 'react'
const ListItem = ({ onClick, community: { id, name, image } }) => (
<div className='ListItem' onClick={() => onClick(id)} style={{ cursor: 'pointer' }}>
<u
className='logo-icon nossas left'
style={{
backgroundImage: image ? `url(${image})` : undefined,
boxShadow: 'none'
}}
/>
<p>
<span>{name}</span>
<i className='fa fa-arrow-right gray right' aria-hidden='true' />
</p>
</div>
)
ListItem.propTypes = {
onClick: PropTypes.func.isRequired,
community: PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
image: PropTypes.string
})
}
export default ListItem
|
import React, { PropTypes } from 'react'
const ListItem = ({ onClick, community: { id, name, image } }) => (
<div className='ListItem' onClick={() => onClick(id)} style={{ cursor: 'pointer' }}>
<u
className='logo-icon nossas left'
style={{
backgroundImage: image ? `url(${image})` : undefined,
boxShadow: 'none'
}}
/>
<p>
<span>{name}</span>
<i className='fa fa-arrow-right gray right' aria-hidden='true' />
</p>
</div>
)
ListItem.propTypes = {
onClick: PropTypes.func.isRequired,
community: PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
image: PropTypes.string.isRequired
})
}
export default ListItem
|
Remove alias from service provider.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Support;
use Illuminate\Support\ServiceProvider;
class MessagesServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.messages'] = $this->app->share(function () {
return new Messages;
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$app = $this->app;
$app->after(function () use ($app) {
$app['orchestra.messages']->save();
});
}
}
|
<?php namespace Orchestra\Support;
use Illuminate\Support\ServiceProvider;
class MessagesServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.messages'] = $this->app->share(function () {
return new Messages;
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$app = $this->app;
$app->after(function () use ($app) {
$app['orchestra.messages']->save();
});
}
}
|
Fix an issue with Fiber (User.avatar)
|
import { RocketChat } from 'meteor/rocketchat:lib';
import property from 'lodash.property';
import schema from '../../schemas/users/User-type.graphqls';
const resolver = {
User: {
id: property('_id'),
status: ({status}) => status.toUpperCase(),
avatar: async({ _id }) => {
// XXX js-accounts/graphql#16
const avatar = await RocketChat.models.Avatars.model.rawCollection().findOne({
userId: _id
}, { fields: { url: 1 }});
if (avatar) {
return avatar.url;
}
},
channels: ({ _id }) => {
return RocketChat.models.Rooms.findBySubscriptionUserId(_id).fetch();
},
directMessages: ({ username }) => {
return RocketChat.models.Rooms.findByTypeContainingUsername('d', username).fetch();
}
}
};
export {
schema,
resolver
};
|
import { RocketChat } from 'meteor/rocketchat:lib';
import property from 'lodash.property';
import schema from '../../schemas/users/User-type.graphqls';
const resolver = {
User: {
id: property('_id'),
status: ({status}) => status.toUpperCase(),
avatar: async({ _id }) => {
const avatar = RocketChat.models.Avatars.findOne({
userId: _id
}, { fields: { url: 1 }});
if (avatar) {
return avatar.url;
}
},
channels: ({ _id }) => {
return RocketChat.models.Rooms.findBySubscriptionUserId(_id).fetch();
},
directMessages: ({ username }) => {
return RocketChat.models.Rooms.findByTypeContainingUsername('d', username).fetch();
}
}
};
export {
schema,
resolver
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.