text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Exclude entries that don't have their own URLs | <?php namespace Craft;
class SimpleSitemapController extends BaseController
{
protected $allowAnonymous = true;
public function actionIndex()
{
$xml = new \SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>' .
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>'
);
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->limit = null;
foreach ($criteria as $entry) {
if($entry->url) {
$url = $xml->addChild('url');
$url->addChild('loc', $entry->url);
$url->addChild('lastmod', $entry->dateUpdated->format(\DateTime::W3C));
$url->addChild('priority', $entry->uri == '__home__' ? 0.75 : 0.5);
}
}
HeaderHelper::setContentTypeByExtension('xml');
ob_start();
echo $xml->asXML();
craft()->end();
}
}
| <?php namespace Craft;
class SimpleSitemapController extends BaseController
{
protected $allowAnonymous = true;
public function actionIndex()
{
$xml = new \SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>' .
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>'
);
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->limit = null;
foreach ($criteria as $entry)
{
$url = $xml->addChild('url');
$url->addChild('loc', $entry->url);
$url->addChild('lastmod', $entry->dateUpdated->format(\DateTime::W3C));
$url->addChild('priority', $entry->uri == '__home__' ? 0.75 : 0.5);
}
HeaderHelper::setContentTypeByExtension('xml');
ob_start();
echo $xml->asXML();
craft()->end();
}
}
|
Put terminal handlers under base_url | import os
from terminado import NamedTermManager
from IPython.html.utils import url_path_join as ujoin
from .handlers import TerminalHandler, NewTerminalHandler, TermSocket
from . import api_handlers
def initialize(webapp):
shell = os.environ.get('SHELL', 'sh')
webapp.terminal_manager = NamedTermManager(shell_command=[shell])
base_url = webapp.settings['base_url']
handlers = [
(ujoin(base_url, "/terminals/new"), NewTerminalHandler),
(ujoin(base_url, r"/terminals/(\w+)"), TerminalHandler),
(ujoin(base_url, r"/terminals/websocket/(\w+)"), TermSocket,
{'term_manager': webapp.terminal_manager}),
(ujoin(base_url, r"/api/terminals"), api_handlers.TerminalRootHandler),
(ujoin(base_url, r"/api/terminals/(\w+)"), api_handlers.TerminalHandler),
]
webapp.add_handlers(".*$", handlers) | import os
from terminado import NamedTermManager
from .handlers import TerminalHandler, NewTerminalHandler, TermSocket
from . import api_handlers
def initialize(webapp):
shell = os.environ.get('SHELL', 'sh')
webapp.terminal_manager = NamedTermManager(shell_command=[shell])
handlers = [
(r"/terminals/new", NewTerminalHandler),
(r"/terminals/(\w+)", TerminalHandler),
(r"/terminals/websocket/(\w+)", TermSocket,
{'term_manager': webapp.terminal_manager}),
(r"/api/terminals", api_handlers.TerminalRootHandler),
(r"/api/terminals/(\w+)", api_handlers.TerminalHandler),
]
webapp.add_handlers(".*$", handlers) |
Disable reactivity of item sets publications. | Meteor.publish('ItemSets.id', function (id) {
check(id, String);
this.unblock();
return ItemSets.find(new Meteor.Collection.ObjectID(id), { reactive: false });
});
Meteor.publish('ItemSets.last', function () {
this.unblock();
return ItemSets.find({}, { sort: { patchVersion : -1, generationDate: -1 }, limit: 1 }, { reactive: false });
});
Meteor.publish('Downloads', function () {
this.unblock();
return Downloads.find();
});
Meteor.publish('Versions', function () {
this.unblock();
return Versions.find();
});
Meteor.publish('GuestbookEntries', function () {
this.unblock();
return GuestbookEntries.find({ approved: true });
});
Meteor.publish('TwitterAnnouncements.last', function () {
this.unblock();
return TwitterAnnouncements.find({}, { sort: { creationDate: -1 }, limit: 1 });
});
| Meteor.publish('ItemSets.id', function (id) {
check(id, String);
this.unblock();
return ItemSets.find(new Meteor.Collection.ObjectID(id));
});
Meteor.publish('ItemSets.last', function () {
this.unblock();
return ItemSets.find({}, { sort: { patchVersion : -1, generationDate: -1 }, limit: 1 });
});
Meteor.publish('Downloads', function () {
this.unblock();
return Downloads.find();
});
Meteor.publish('Versions', function () {
this.unblock();
return Versions.find();
});
Meteor.publish('GuestbookEntries', function () {
this.unblock();
return GuestbookEntries.find({ approved: true });
});
Meteor.publish('TwitterAnnouncements.last', function () {
this.unblock();
return TwitterAnnouncements.find({}, { sort: { creationDate: -1 }, limit: 1 });
});
|
Make data construction a bit simpler to understand. | import assert from 'assert';
import RawMetadata from '../rawmetadata.js';
const fromMetadataJsonToKataGroups = (metadataJson) => {
return RawMetadata.toKataGroups(metadataJson);
};
class Kata {
static withId(id) {
return {id};
}
}
describe('create KataGroups from the raw metadata', function() {
const group = {items: [Kata.withId(1)]};
const anotherGroup = {items: [Kata.withId(2)]};
it('for one group only one KataGroup is created', function() {
const groupedMetadataJson = {
groups: {'group name': group}
};
var kataGroups = fromMetadataJsonToKataGroups(groupedMetadataJson);
assert.equal(kataGroups.length, 1);
});
it('two groups two KataGroups are created', function() {
const groupedMetadataJson = {
groups: {
'group name': group,
'group name1': anotherGroup
}
};
var kataGroups = fromMetadataJsonToKataGroups(groupedMetadataJson);
assert.equal(kataGroups.length, 2);
});
});
| import assert from 'assert';
import RawMetadata from '../rawmetadata.js';
const fromMetadataJsonToKataGroups = (metadataJson) => {
return RawMetadata.toKataGroups(metadataJson);
};
describe('create KataGroups from the raw metadata', function() {
const group = {items: [{id: 1}]};
const anotherGroup = {items: [{id: 2}]};
it('for one group only one KataGroup is created', function() {
const groupedMetadataJson = {
groups: {'group name': group}
};
var kataGroups = fromMetadataJsonToKataGroups(groupedMetadataJson);
assert.equal(kataGroups.length, 1);
});
it('two groups two KataGroups are created', function() {
const groupedMetadataJson = {
groups: {
'group name': group,
'group name1': anotherGroup
}
};
var kataGroups = fromMetadataJsonToKataGroups(groupedMetadataJson);
assert.equal(kataGroups.length, 2);
});
});
|
Change test, so that view has a request object | from unittest import TestCase
from mock import Mock, patch
from django.test import RequestFactory
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
ParagraphLayersApplier(), SearchReplaceLayersApplier())
generator.get_tree_paragraph.return_value = {
'text': 'Some Text',
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
paragraph_id = '103-3-a'
reg_version = '2013-10607'
request = RequestFactory().get('/fake-path')
view = PartialParagraphView.as_view(template_name='tree.html')
response = view(request, paragraph_id=paragraph_id, reg_version=reg_version)
self.assertEqual(response.context_data['node'],
generator.get_tree_paragraph.return_value)
| from unittest import TestCase
from mock import Mock, patch
from regulations.generator.layers.layers_applier import *
from regulations.views.partial import *
class PartialParagraphViewTests(TestCase):
@patch('regulations.views.partial.generator')
def test_get_context_data(self, generator):
generator.get_all_section_layers.return_value = (InlineLayersApplier(),
ParagraphLayersApplier(), SearchReplaceLayersApplier())
generator.get_tree_paragraph.return_value = {
'text': 'Some Text',
'children': [],
'label': {'text': '867-53-q', 'parts': ['867', '53', 'q']}
}
rpv = PartialParagraphView()
context = rpv.get_context_data(paragraph_id = '867-53-q',
reg_version = 'verver')
self.assertEqual(context['node'],
generator.get_tree_paragraph.return_value)
|
Add explicit usage of backend | from .page import Page
import six
from bs4 import UnicodeDammit, BeautifulSoup
# from lxml.etree import fromstring
def parse(source):
"""Parse a HOCR stream into page elements.
@param[in] source
Either a file-like object or a filename of the HOCR text.
"""
# Corece the source into content.
if isinstance(source, six.string_types):
with open(source, 'rb') as stream:
content = stream.read()
else:
content = source.read()
# Parse the HOCR xml stream.
ud = UnicodeDammit(content, is_html=True)
soup = BeautifulSoup(ud.unicode_markup, 'lxml')
# Get all the pages and parse them into page elements.
return [Page(x) for x in soup.find_all(class_='ocr_page')]
| from .page import Page
import six
from bs4 import UnicodeDammit, BeautifulSoup
# from lxml.etree import fromstring
def parse(source):
"""Parse a HOCR stream into page elements.
@param[in] source
Either a file-like object or a filename of the HOCR text.
"""
# Corece the source into content.
if isinstance(source, six.string_types):
with open(source, 'rb') as stream:
content = stream.read()
else:
content = source.read()
# Parse the HOCR xml stream.
ud = UnicodeDammit(content, is_html=True)
soup = BeautifulSoup(ud.unicode_markup)
# Get all the pages and parse them into page elements.
return [Page(x) for x in soup.find_all(class_='ocr_page')]
|
Test non-1D array error in utils
Adds a test for `_bool_cmp_mtx_cnt` to make sure that both arrays are 1D
only. Will raise a `ValueError` if this is not the case. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
import numpy as np
import dask_distance._utils
@pytest.mark.parametrize("et, u, v", [
(ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)),
(ValueError, np.zeros((1, 2,), dtype=bool), np.zeros((2,), dtype=bool)),
(ValueError, np.zeros((2,), dtype=bool), np.zeros((1, 2,), dtype=bool)),
])
def test__bool_cmp_mtx_cnt_err(et, u, v):
with pytest.raises(et):
dask_distance._utils._bool_cmp_mtx_cnt(u, v)
def test__bool_cmp_mtx_cnt():
u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool)
v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool)
uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v)
uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float)
assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pytest
import numpy as np
import dask_distance._utils
@pytest.mark.parametrize("et, u, v", [
(ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)),
])
def test__bool_cmp_mtx_cnt_err(et, u, v):
with pytest.raises(et):
dask_distance._utils._bool_cmp_mtx_cnt(u, v)
def test__bool_cmp_mtx_cnt():
u = np.array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool)
v = np.array([0, 1, 1, 0, 0, 0, 1, 1, 1, 1], dtype=bool)
uv_cmp_mtx = dask_distance._utils._bool_cmp_mtx_cnt(u, v)
uv_cmp_mtx_exp = np.array([[1, 2], [3, 4]], dtype=float)
assert (np.array(uv_cmp_mtx) == uv_cmp_mtx_exp).all()
|
Attach sender field to PendingInvoice | 'use strict';
module.exports = function(sequelize, DataTypes) {
var PendingInvoice = sequelize.define('PendingInvoice', {
invoiceId: DataTypes.INTEGER,
due: DataTypes.STRING,
paymentDays: DataTypes.INTEGER
// TODO: status enum
// TODO: items (InvoiceItem)
},
{
classMethods: {
associate: function(models) {
PendingInvoice.belongsTo(models.Client, {
foreignKey: 'receiver',
});
PendingInvoice.belongsTo(models.User, {
foreignKey: 'sender',
});
}
}
}
);
return PendingInvoice;
};
| 'use strict';
module.exports = function(sequelize, DataTypes) {
var PendingInvoice = sequelize.define('PendingInvoice', {
invoiceId: DataTypes.INTEGER,
due: DataTypes.STRING,
paymentDays: DataTypes.INTEGER
// TODO: status enum
// TODO: sender (User)
// TODO: items (InvoiceItem)
},
{
classMethods: {
associate: function(models) {
PendingInvoice.belongsTo(models.Client, {
foreignKey: 'receiver',
});
}
}
}
);
return PendingInvoice;
};
|
Fix the version dependency on ruffus to 2.2, rather than >= 2.0.0 | #!/usr/bin/env python
from setuptools import setup
setup(
name='Rubra',
version='0.1.5',
author='Bernie Pope',
author_email='bjpope@unimelb.edu.au',
packages=['rubra'],
package_data={'rubra': ['examples/*.py']},
entry_points={
'console_scripts': ['rubra = rubra.rubra:main']
},
url='https://github.com/bjpop/rubra',
license='LICENSE.txt',
description='Rubra is a pipeline system for bioinformatics workflows\
with support for running pipeline stages on a distributed compute cluster.',
long_description=open('README.txt').read(),
install_requires=[
"ruffus==2.2",
],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT',
'Operating System :: POSIX',
'Programming Language :: Python',
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='Rubra',
version='0.1.5',
author='Bernie Pope',
author_email='bjpope@unimelb.edu.au',
packages=['rubra'],
package_data={'rubra': ['examples/*.py']},
entry_points={
'console_scripts': ['rubra = rubra.rubra:main']
},
url='https://github.com/bjpop/rubra',
license='LICENSE.txt',
description='Rubra is a pipeline system for bioinformatics workflows\
with support for running pipeline stages on a distributed compute cluster.',
long_description=open('README.txt').read(),
install_requires=[
"ruffus >= 2.0.0",
],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT',
'Operating System :: POSIX',
'Programming Language :: Python',
],
)
|
Fix Django 1.9 import error | """
An url to AutocompleteView.
autocomplete_light_autocomplete
Given a 'autocomplete' argument with the name of the autocomplete, this url
routes to AutocompleteView.
autocomplete_light_registry
Renders the autocomplete registry, good for debugging, requires being
authenticated as superuser.
"""
from django import VERSION
from .views import AutocompleteView, RegistryView
if VERSION > (1, 9):
from django.conf.urls import url
else:
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.5
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^(?P<autocomplete>[-\w]+)/$',
AutocompleteView.as_view(),
name='autocomplete_light_autocomplete'
),
url(r'^$',
RegistryView.as_view(),
name='autocomplete_light_registry'
),
]
if VERSION < (1, 9):
urlpatterns = patterns('', *urlpatterns)
| """
An url to AutocompleteView.
autocomplete_light_autocomplete
Given a 'autocomplete' argument with the name of the autocomplete, this url
routes to AutocompleteView.
autocomplete_light_registry
Renders the autocomplete registry, good for debugging, requires being
authenticated as superuser.
"""
from django import VERSION
from .views import AutocompleteView, RegistryView
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.5
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^(?P<autocomplete>[-\w]+)/$',
AutocompleteView.as_view(),
name='autocomplete_light_autocomplete'
),
url(r'^$',
RegistryView.as_view(),
name='autocomplete_light_registry'
),
]
if VERSION < (1, 9):
urlpatterns = patterns('', *urlpatterns)
|
Make the guzzle client an instance variable during instantiation | <?php
namespace duncan3dc\Proxy;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
class App
{
private $client;
public function __construct()
{
$this->client = new Client([
"http_errors" => false,
]);
}
public function run(): void
{
$url = $this->generateUrl();
$response = $this->client->request($_SERVER["REQUEST_METHOD"], $url, [
"headers" => [
"User-Agent" => $_SERVER["HTTP_USER_AGENT"],
],
"form_params" => $_POST,
]);
$this->respond($response);
}
private function generateUrl(): string
{
return "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
}
private function respond(ResponseInterface $response): void
{
http_response_code($response->getStatusCode());
header("Content-Type: " . $response->getHeader("content-type")[0]);
echo $response->getBody();
}
}
| <?php
namespace duncan3dc\Proxy;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
class App
{
public function run(): void
{
$client = new Client([
"http_errors" => false,
]);
$url = $this->generateUrl();
$response = $client->request($_SERVER["REQUEST_METHOD"], $url, [
"headers" => [
"User-Agent" => $_SERVER["HTTP_USER_AGENT"],
],
"form_params" => $_POST,
]);
$this->respond($response);
}
private function generateUrl(): string
{
return "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
}
private function respond(ResponseInterface $response): void
{
http_response_code($response->getStatusCode());
header("Content-Type: " . $response->getHeader("content-type")[0]);
echo $response->getBody();
}
}
|
Include babel poylfills in dummy app build | /*jshint node:true*/
/* global require, module */
var path = require('path');
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
sassOptions: {
includePaths: [
'tests/dummy/app/components',
'addon/styles'
]
},
babel: {
includePolyfill: true
}
});
app.import(path.join(app.bowerDirectory, 'osf-style/css/base.css'));
app.import(path.join(app.bowerDirectory, 'dropzone/dist/basic.css'));
app.import(path.join(app.bowerDirectory, 'dropzone/dist/dropzone.css'));
app.import(path.join(app.bowerDirectory, 'dropzone/dist/dropzone.js'));
return app.toTree();
};
| /*jshint node:true*/
/* global require, module */
var path = require('path');
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
sassOptions: {
includePaths: [
'tests/dummy/app/components',
'addon/styles'
]
}
});
app.import(path.join(app.bowerDirectory, 'osf-style/css/base.css'));
app.import(path.join(app.bowerDirectory, 'dropzone/dist/basic.css'));
app.import(path.join(app.bowerDirectory, 'dropzone/dist/dropzone.css'));
app.import(path.join(app.bowerDirectory, 'dropzone/dist/dropzone.js'));
return app.toTree();
};
|
internal/uidriver/mobile: Fix the package name in a panic message | // Copyright 2019 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build ((ios && arm) || (ios && arm64)) && !ebitengl
// +build ios,arm ios,arm64
// +build !ebitengl
package mobile
import (
"fmt"
"github.com/hajimehoshi/ebiten/v2/internal/driver"
"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal"
"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal/mtl"
)
func (*UserInterface) Graphics() driver.Graphics {
if _, err := mtl.CreateSystemDefaultDevice(); err != nil {
panic(fmt.Sprintf("mobile: mtl.CreateSystemDefaultDevice failed on iOS: %v", err))
}
return metal.Get()
}
| // Copyright 2019 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build ((ios && arm) || (ios && arm64)) && !ebitengl
// +build ios,arm ios,arm64
// +build !ebitengl
package mobile
import (
"fmt"
"github.com/hajimehoshi/ebiten/v2/internal/driver"
"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal"
"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal/mtl"
)
func (*UserInterface) Graphics() driver.Graphics {
if _, err := mtl.CreateSystemDefaultDevice(); err != nil {
panic(fmt.Sprintf("ebiten: mtl.CreateSystemDefaultDevice failed on iOS: %v", err))
}
return metal.Get()
}
|
Revert "Send changes in react-counter-messaging"
This reverts commit ff9167ce9607408eaadc188435dca89192933915. | import React, { Component, PropTypes } from 'react';
class Counter extends Component {
constructor() {
super();
this.state = { counter: 0 };
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment() {
const state = { counter: this.state.counter + 1 };
this.setState(state);
}
decrement() {
const state = { counter: this.state.counter - 1 };
this.setState(state);
}
render() {
const { counter } = this.state;
return (
<p>
Clicked: {counter} times
{' '}
<button onClick={this.increment}>+</button>
{' '}
<button onClick={this.decrement}>-</button>
</p>
);
}
}
export default Counter;
| import React, { Component, PropTypes } from 'react';
class Counter extends Component {
constructor() {
super();
this.state = { counter: 0 };
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
increment() {
const state = { counter: this.state.counter + 1 };
window.devToolsExtension && window.devToolsExtension.send('increment', state);
this.setState(state);
}
decrement() {
const state = { counter: this.state.counter - 1 };
window.devToolsExtension && window.devToolsExtension.send('decrement', state);
this.setState(state);
}
render() {
const { counter } = this.state;
return (
<p>
Clicked: {counter} times
{' '}
<button onClick={this.increment}>+</button>
{' '}
<button onClick={this.decrement}>-</button>
</p>
);
}
}
export default Counter;
|
Remove bold from table and add nbsp for table spacing | <fieldset class="personalblock">
<legend><?php p($l->t('Mozilla Sync')); ?></legend>
<table class="nostyle">
<tr>
<td><?php p($l->t('Email'));?> </td>
<td><code><?php p($_['email']);?></code></td>
</tr>
<tr>
<td><?php p($l->t('Password'));?> </td>
<td><?php p($l->t('Use your ownCloud account password'));?></td>
</tr>
<tr>
<td><?php p($l->t('Server address'));?> </td>
<td><code><?php p($_['syncaddress']);?></code></td>
</tr>
</table>
<?php p($l->t("Once set up, additional devices can be added via Mozilla's device pairing service or manually."));?>
</fieldset>
| <fieldset class="personalblock">
<legend><?php p($l->t('Mozilla Sync')); ?></legend>
<table class="nostyle">
<tr>
<td><label class="bold"><?php p($l->t('Email'));?></label></td>
<td><code><?php p($_['email']);?></code></td>
</tr>
<tr>
<td><label class="bold"><?php p($l->t('Password'));?></label></td>
<td><?php p($l->t('Use your ownCloud account password'));?></td>
</tr>
<tr>
<td><label class="bold"><?php p($l->t('Server address'));?></label></td>
<td><code><?php p($_['syncaddress']);?></code></td>
</tr>
</table>
<?php p($l->t("Once set up, additional devices can be added via Mozilla's device pairing service or manually."));?>
</fieldset>
|
Add option to set PORT via env variable | #!/usr/bin/env node
process.title = 'timeline_serve';
var _ = require('underscore')._;
var express = require('express');
var socket = require('socket.io');
var fs = require('fs');
var port = process.env.PORT;
var app = express();
app.configure(function () {
app.use(express.static(__dirname + '/../public'));
});
var server = app.listen(port);
function readData () {
var fileNames = fs.readdirSync('./');
return _.reduce(fileNames, function (memo, filename) {
var stat = fs.statSync(filename);
if (stat.isFile()) {
memo[filename] = fs.readFileSync(filename, 'utf8');
}
return memo;
}, {});
}
var io = socket.listen(server);
io.configure(function () {
io.set("log level", 1);
});
io.sockets.on('connection', function (socket) {
socket.emit('data', readData());
});
var watch = require('node-watch');
watch(__dirname + '/../public', function () {
io.sockets.emit('reload');
});
watch('./', function () {
io.sockets.emit('data', readData());
});
console.log('Timeline server started.');
console.log('Reading timeline files from ' + fs.realpathSync('./'));
console.log('Point your browser to http://localhost:' + port + '/');
| #!/usr/bin/env node
process.title = 'timeline_serve';
var _ = require('underscore')._;
var express = require('express');
var socket = require('socket.io');
var fs = require('fs');
var app = express();
app.configure(function () {
app.use(express.static(__dirname + '/../public'));
});
var server = app.listen(8888);
function readData () {
var fileNames = fs.readdirSync('./');
return _.reduce(fileNames, function (memo, filename) {
var stat = fs.statSync(filename);
if (stat.isFile()) {
memo[filename] = fs.readFileSync(filename, 'utf8');
}
return memo;
}, {});
}
var io = socket.listen(server);
io.configure(function () {
io.set("log level", 1);
});
io.sockets.on('connection', function (socket) {
socket.emit('data', readData());
});
var watch = require('node-watch');
watch(__dirname + '/../public', function () {
io.sockets.emit('reload');
});
watch('./', function () {
io.sockets.emit('data', readData());
});
console.log('Timeline server started.');
console.log('Reading timeline files from ' + fs.realpathSync('./'));
console.log('Point your browser to http://localhost:8888/');
|
Throw an error instead of returning null | import gravity from '../../lib/loaders/gravity';
import { GraphQLString, GraphQLBoolean } from 'graphql';
import { mutationWithClientMutationId } from 'graphql-relay';
import { artworkFields } from '../artwork/index';
export default mutationWithClientMutationId({
name: 'SaveArtwork',
decription: 'Save (or remove) an artwork to (from) a users default collection.',
inputFields: {
artwork_id: {
type: GraphQLString,
},
remove: {
type: GraphQLBoolean,
},
},
outputFields: artworkFields(),
mutateAndGetPayload: ({
artwork_id,
remove,
}, request, { rootValue: { accessToken, userID } }) => {
if (!accessToken) return new Error('You need to be signed in to perform this action');
const saveMethod = remove ? 'DELETE' : 'POST';
return gravity.with(accessToken, {
method: saveMethod,
})(`/collection/saved-artwork/artwork/${artwork_id}`, {
user_id: userID,
}).then(() => gravity(`artwork/${artwork_id}`));
},
});
| import gravity from '../../lib/loaders/gravity';
import { GraphQLString, GraphQLBoolean } from 'graphql';
import { mutationWithClientMutationId } from 'graphql-relay';
import { artworkFields } from '../artwork/index';
export default mutationWithClientMutationId({
name: 'SaveArtwork',
decription: 'Save (or remove) an artwork to (from) a users default collection.',
inputFields: {
artwork_id: {
type: GraphQLString,
},
remove: {
type: GraphQLBoolean,
},
},
outputFields: artworkFields(),
mutateAndGetPayload: ({
artwork_id,
remove,
}, request, { rootValue: { accessToken, userID } }) => {
if (!accessToken) return null;
const saveMethod = remove ? 'DELETE' : 'POST';
return gravity.with(accessToken, {
method: saveMethod,
})(`/collection/saved-artwork/artwork/${artwork_id}`, {
user_id: userID,
}).then(() => gravity(`artwork/${artwork_id}`));
},
});
|
Add redis config path format | # -*- coding: utf-8 -*-
import ConfigParser
import os
DEBUG = True
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
if DEBUG:
config.read("{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT))
else:
config.read('/etc/autocloud/autocloud.cfg')
KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url')
BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url')
if DEBUG:
REDIS_CONFIG_FILEPATH = "{PROJECT_ROOT}/config/redis_server.json".format(
PROJECT_ROOT=PROJECT_ROOT)
else:
REDIS_CONFIG_FILEPATH = config.get('autocloud', 'redis_config_filepath')
JENKINS_BASE_URL = config.get('jenkins', 'baseurl')
JENKINS_USERNAME = config.get('jenkins', 'username')
JENKINS_TOKEN = config.get('jenkins', 'token')
JENKINS_JOB_NAME = config.get('jenkins', 'job_name')
HOST = config.get('autocloud', 'host') or '127.0.0.1'
PORT = int(config.get('autocloud', 'port')) or 5000
DEBUG = config.get('autocloud', 'debug')
SQLALCHEMY_URI = config.get('sqlalchemy', 'uri')
| # -*- coding: utf-8 -*-
import ConfigParser
import os
DEBUG = True
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
config = ConfigParser.RawConfigParser()
if DEBUG:
config.read("{PROJECT_ROOT}/config/autocloud.cfg".format(
PROJECT_ROOT=PROJECT_ROOT))
else:
config.read('/etc/autocloud/autocloud.cfg')
KOJI_SERVER_URL = config.get('autocloud', 'koji_server_url')
BASE_KOJI_TASK_URL = config.get('autocloud', 'base_koji_task_url')
if DEBUG:
REDIS_CONFIG_FILEPATH = "{PROJECT_ROOT}/config/redis_server.json"
else:
REDIS_CONFIG_FILEPATH = config.get('autocloud', 'redis_config_filepath')
JENKINS_BASE_URL = config.get('jenkins', 'baseurl')
JENKINS_USERNAME = config.get('jenkins', 'username')
JENKINS_TOKEN = config.get('jenkins', 'token')
JENKINS_JOB_NAME = config.get('jenkins', 'job_name')
HOST = config.get('autocloud', 'host') or '127.0.0.1'
PORT = int(config.get('autocloud', 'port')) or 5000
DEBUG = config.get('autocloud', 'debug')
SQLALCHEMY_URI = config.get('sqlalchemy', 'uri')
|
Simplify getter using php 8 syntax | <?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="entityType", type="string")
*/
abstract class AbstractContentNodeOwner extends BaseEntity {
/**
* @ORM\OneToOne(targetEntity="ContentNode", inversedBy="owner")
* @ORM\JoinColumn(nullable=true)
*/
public ?ContentNode $rootContentNode = null;
public function setRootContentNode(?ContentNode $rootContentNode) {
// unset the owning side of the relation if necessary
if (null === $rootContentNode && null !== $this->rootContentNode) {
$this->rootContentNode->owner = null;
}
// set the owning side of the relation if necessary
if (null !== $rootContentNode && $rootContentNode->owner !== $this) {
$rootContentNode->owner = $this;
}
$this->rootContentNode = $rootContentNode;
}
/**
* @return ContentNode[]
*/
#[ApiProperty(writable: false)]
public function getContentNodes(): array {
return $this->rootContentNode?->getRootDescendants() ?? [];
}
}
| <?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiProperty;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="entityType", type="string")
*/
abstract class AbstractContentNodeOwner extends BaseEntity {
/**
* @ORM\OneToOne(targetEntity="ContentNode", inversedBy="owner")
* @ORM\JoinColumn(nullable=true)
*/
public ?ContentNode $rootContentNode = null;
public function setRootContentNode(?ContentNode $rootContentNode) {
// unset the owning side of the relation if necessary
if (null === $rootContentNode && null !== $this->rootContentNode) {
$this->rootContentNode->owner = null;
}
// set the owning side of the relation if necessary
if (null !== $rootContentNode && $rootContentNode->owner !== $this) {
$rootContentNode->owner = $this;
}
$this->rootContentNode = $rootContentNode;
}
/**
* @return ContentNode[]
*/
#[ApiProperty(writable: false)]
public function getContentNodes(): array {
if (null != $this->rootContentNode) {
return $this->rootContentNode->getRootDescendants();
}
return [];
}
}
|
Fix snippet parser for Italian.
Former-commit-id: bb8d10f5f8301fbcd4f4232612bf722d380a3d10 | #-*- encoding: utf-8 -*-
from __future__ import unicode_literals
from core import *
class SnippetParser(SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('bandiera'):
return self.handle_bandiera(template)
elif template.name.matches('citazione'):
return self.handle_citazione(template)
return super(SnippetParser, self).strip_template(
template, normalize, collapse)
def handle_bandiera(template):
return template.get(1)
def handle_citazione(template):
if template.params:
return '« ' + self.sp(template.params[0]) + ' »'
| #-*- encoding: utf-8 -*-
from __future__ import unicode_literals
from core import *
def handle_bandiera(template):
return template.get(1)
def handle_citazione(template):
if template.params:
return '« ' + sp(template.params[0]) + ' »'
class SnippetParser(SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('bandiera'):
return handle_bandiera(template)
elif template.name.matches('citazione'):
return handle_citazione(template)
return super(SnippetParser, self).strip_template(
template, normalize, collapse)
|
Fix bug with remoteScrollTime docs changer. | define([
'underscore',
'text!templates/grid-docs.html',
'text!pages/grid-options-remoteScrollTime.html',
'dobygrid',
'js/sample-fetcher'
], function (_, template, page, DobyGrid, remotedata) {
"use strict";
return Backbone.DobyView.extend({
events: function () {
return _.extend({}, Backbone.DobyView.prototype.events, {
"change #option-value": "changeOption"
});
},
initialize: function () {
var html = _.template(template, {
page: page
});
this.$el.append(html);
},
render: function () {
this.grid = new DobyGrid({
columns: [{
id: "id",
name: "ID",
field: "id"
}, {
id: "name",
name: "Name",
field: "name"
}, {
id: "age",
name: "Age",
field: "age"
}],
data: remotedata,
rowHeight: 35
}).appendTo('#demo-grid');
},
changeOption: function (event) {
// Get value
var value = $(event.currentTarget).val();
// Set value
this.grid.setOptions({remoteScrollTime: value});
}
});
}); | define([
'underscore',
'text!templates/grid-docs.html',
'text!pages/grid-options-remoteScrollTime.html',
'dobygrid',
'js/sample-fetcher'
], function (_, template, page, DobyGrid, remotedata) {
"use strict";
return Backbone.DobyView.extend({
events: function () {
return _.extend({}, Backbone.DobyView.prototype.events, {
"change #option-value": "changeOption"
});
},
initialize: function () {
var html = _.template(template, {
page: page
});
this.$el.append(html);
},
render: function () {
new DobyGrid({
columns: [{
id: "id",
name: "ID",
field: "id"
}, {
id: "name",
name: "Name",
field: "name"
}, {
id: "age",
name: "Age",
field: "age"
}],
data: remotedata,
rowHeight: 35
}).appendTo('#demo-grid');
},
changeOption: function (event) {
// Get value
var value = $(event.currentTarget).val();
// Set value
this.grid.setOptions({remoteScrollTime: value});
}
});
}); |
Fix Twitter share test not deterministic | "use strict";
var shared = require("./shared.js");
var EmbeddedSharePage = function() {
this.url = "/embed/social-share";
this.dummyTweetButton = element(by.css(".tweet.dummy_btn"));
this.dummyFacebookLikeButton = element(by.css(".fb_like.dummy_btn"));
this.get = function() {
browser.get(this.url);
return this;
}
this.clickDummyTweetButton = function() {
this.dummyTweetButton.click();
browser.waitForAngular();
};
this.getTwitterIframe = function() {
return this.dummyTweetButton.element(by.css("iframe"));
};
this.clickDummyFacebookLikeButton = function() {
this.dummyFacebookLikeButton.click();
};
this.getFacebookIframe = function() {
return this.dummyFacebookLikeButton.element(by.css("iframe"));
};
};
module.exports = EmbeddedSharePage;
| "use strict";
var shared = require("./shared.js");
var EmbeddedSharePage = function() {
this.url = "/embed/social-share";
this.dummyTweetButton = element(by.css(".tweet.dummy_btn"));
this.dummyFacebookLikeButton = element(by.css(".fb_like.dummy_btn"));
this.get = function() {
browser.get(this.url);
return this;
}
this.clickDummyTweetButton = function() {
this.dummyTweetButton.click();
};
this.getTwitterIframe = function() {
return this.dummyTweetButton.element(by.css("iframe"));
};
this.clickDummyFacebookLikeButton = function() {
this.dummyFacebookLikeButton.click();
};
this.getFacebookIframe = function() {
return this.dummyFacebookLikeButton.element(by.css("iframe"));
};
};
module.exports = EmbeddedSharePage;
|
Add heroku url to axios request | import axios from 'axios';
export const FETCH_SEARCH_RESULTS = 'fetch_search_results';
const ROOT_URL = 'https://earlybirdsearch.herokuapp.com/?';
export function fetchSearchResults(term, location) {
const request = axios.get(`${ROOT_URL}business=${term}&location=${location}`);
console.log(request);
// const testJSON = {
// data: [
// { name: 'Michael Mina', url: 'yelp.com/michaelminna' },
// { name: 'Sushi', url: 'yelp.com/sushi' },
// { name: 'Thai', url: 'yelp.com/thai' },
// { name: 'Chinese', url: 'yelp.com/chinese' }
// ]
// };
return {
type: FETCH_SEARCH_RESULTS,
payload: request
}
}
| // import axios from 'axios';
export const FETCH_SEARCH_RESULTS = 'fetch_search_results';
// const ROOT_URL = 'http://herokuapp.com/';
export function fetchSearchResults(term, location) {
// const request = axios.get(`${ROOT_URL}/${term}/${location}`);
const testJSON = {
data: [
{ name: 'Michael Mina', url: 'yelp.com/michaelminna' },
{ name: 'Sushi', url: 'yelp.com/sushi' },
{ name: 'Thai', url: 'yelp.com/thai' },
{ name: 'Chinese', url: 'yelp.com/chinese' }
]
};
return {
type: FETCH_SEARCH_RESULTS,
payload: testJSON
}
}
|
Refactor selection sort w/ comments | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last position reversely: len(ls) - 1, ..., 0.
for i in reversed(range(len(ls))):
# Select next max element, and swap it and element at position i.
s = 0
for j in range(1, i + 1):
if ls[j] > ls[s]:
s = j
ls[s], ls[i] = ls[i], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
|
Update the path to Amanda in the ‘amanda.js’ file | // Load dependencies
var amanda = require('../../../dist/latest.js');
/**
* Test #1
*/
exports['Test #1'] = function(test) {
var count = 0;
var schema = {
required: true,
format: 'alpha'
};
[
'abc',
'ABC',
'Abc',
'aBc'
].forEach(function(data) {
amanda.validate(data, schema, function(error) {
count += 1;
test.equal(error, undefined);
});
});
[
'123',
'+@#$~^*{}',
'lorem ipsum',
' ',
123,
null,
[],
{},
function() {},
null,
undefined
].forEach(function(data) {
amanda.validate(data, schema, function(error) {
count += 1;
test.ok(error);
});
});
test.equal(count, 15);
test.done();
}; | // Load dependencies
var amanda = require('../../../src/amanda.js');
/**
* Test #1
*/
exports['Test #1'] = function(test) {
var count = 0;
var schema = {
required: true,
format: 'alpha'
};
[
'abc',
'ABC',
'Abc',
'aBc'
].forEach(function(data) {
amanda.validate(data, schema, function(error) {
count += 1;
test.equal(error, undefined);
});
});
[
'123',
'+@#$~^*{}',
'lorem ipsum',
' ',
123,
null,
[],
{},
function() {},
null,
undefined
].forEach(function(data) {
amanda.validate(data, schema, function(error) {
count += 1;
test.ok(error);
});
});
test.equal(count, 15);
test.done();
}; |
Remove line added by mistake | #!/usr/bin/env python
import re
from setuptools import setup, find_packages
with open('rhino/__init__.py') as f:
version = re.findall(r"^__version__ = '(.*)'", f.read(), re.M)[0]
with open('README.rst') as f:
README = f.read()
setup(
name='Rhino',
version=version,
author='Stanis Trendelenburg',
author_email='stanis.trendelenburg@gmail.com',
packages=find_packages(exclude=['test*', 'example*']),
url='https://github.com/trendels/rhino',
license='MIT',
description='A microframework for building RESTful web services',
long_description=README,
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| #!/usr/bin/env python
import re
from setuptools import setup, find_packages
with open('rhino/__init__.py') as f:
version = re.findall(r"^__version__ = '(.*)'", f.read(), re.M)[0]
with open('README.rst') as f:
README = f.read()
setup(
name='Rhino',
version=version,
author='Stanis Trendelenburg',
author_email='stanis.trendelenburg@gmail.com',
packages=find_packages(exclude=['test*', 'example*']),
url='https://github.com/trendels/rhino',
license='MIT',
description='A microframework for building RESTful web services',
long_description=README,
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
install_requires=['uritemplate'],
)
|
Fix African Storybook loading by ensuring Hashi runs body.onload handlers. | import replaceScript from './replaceScript';
/*
* runs an array of async functions in sequential order
*/
export function seq(arr, index) {
// first call, without an index
if (typeof index === 'undefined') {
index = 0;
}
function callback() {
index++;
if (index < arr.length) {
seq(arr, index);
} else {
// If finished trigger all the DOM Content Loaded event
const DOMContentLoadedEvent = document.createEvent('Event');
DOMContentLoadedEvent.initEvent('DOMContentLoaded', true, true);
document.dispatchEvent(DOMContentLoadedEvent);
const $body = document.querySelector('body');
if ($body && $body.onload) {
$body.onload();
}
}
}
if (arr.length) {
const fn = arr[index];
fn(callback);
}
}
export function setContent(contents) {
document.documentElement.innerHTML = contents;
// First generate the callbacks for all script tags.
// This will create insertion operations for all script tags
const $scripts = document.querySelectorAll('script');
const runList = [].map.call($scripts, function($script) {
return function(callback) {
replaceScript($script, callback);
};
});
// insert the script tags sequentially
// to preserve execution order
seq(runList);
}
export default function loadCurrentPage() {
const req = new XMLHttpRequest();
req.addEventListener('load', () => {
setContent(req.responseText);
});
req.open('GET', window.location.href);
req.send();
}
| import replaceScript from './replaceScript';
/*
* runs an array of async functions in sequential order
*/
export function seq(arr, index) {
// first call, without an index
if (typeof index === 'undefined') {
index = 0;
}
function callback() {
index++;
if (index < arr.length) {
seq(arr, index);
} else {
// If finished trigger all the DOM Content Loaded event
const DOMContentLoadedEvent = document.createEvent('Event');
DOMContentLoadedEvent.initEvent('DOMContentLoaded', true, true);
document.dispatchEvent(DOMContentLoadedEvent);
}
}
if (arr.length) {
const fn = arr[index];
fn(callback);
}
}
export function setContent(contents) {
document.documentElement.innerHTML = contents;
// First generate the callbacks for all script tags.
// This will create insertion operations for all script tags
const $scripts = document.querySelectorAll('script');
const runList = [].map.call($scripts, function($script) {
return function(callback) {
replaceScript($script, callback);
};
});
// insert the script tags sequentially
// to preserve execution order
seq(runList);
}
export default function loadCurrentPage() {
const req = new XMLHttpRequest();
req.addEventListener('load', () => {
setContent(req.responseText);
});
req.open('GET', window.location.href);
req.send();
}
|
Change lab assistant constant to one word | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab_assistant'
VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]
GRADE_TAGS = ['composition', 'total', 'partner a', 'partner b', 'regrade',
'revision']
API_PREFIX = '/api'
GRADES_BUCKET = 'ok_grades_bucket'
TIMEZONE = 'America/Los_Angeles'
AUTOGRADER_URL = 'https://autograder.cs61a.org'
FORBIDDEN_ROUTE_NAMES = [
'about',
'admin',
'api',
'comments',
'login',
'logout',
'testing-login',
]
FORBIDDEN_ASSIGNMENT_NAMES = []
| """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab assistant'
VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]
GRADE_TAGS = ['composition', 'total', 'partner a', 'partner b', 'regrade',
'revision']
API_PREFIX = '/api'
GRADES_BUCKET = 'ok_grades_bucket'
TIMEZONE = 'America/Los_Angeles'
AUTOGRADER_URL = 'https://autograder.cs61a.org'
FORBIDDEN_ROUTE_NAMES = [
'about',
'admin',
'api',
'comments',
'login',
'logout',
'testing-login',
]
FORBIDDEN_ASSIGNMENT_NAMES = []
|
Use output_dir, not hard-coded dir name | from __future__ import print_function
import os
import sys
from django.core.management.base import BaseCommand
from emailfwd.models import ForwardedEmailAddress
class Command(BaseCommand):
args = '<output_dir>'
help = 'Export the email forwarding data directory'
def handle(self, *args, **options):
output_dir = args[0]
if not os.path.isdir(output_dir) or os.listdir(output_dir):
print('Provide an empty directory that exists', file=sys.stderr)
return 1
for fwd in ForwardedEmailAddress.objects.all():
outname = os.path.join(output_dir, '{0.name}@{0.domain}'.format(fwd))
with open(outname, 'wb') as out:
for dest in fwd.emaildestination_set.all():
print(dest.email, file=out)
| from __future__ import print_function
import os
import sys
from django.core.management.base import BaseCommand
from emailfwd.models import ForwardedEmailAddress
class Command(BaseCommand):
args = '<output_dir>'
help = 'Export the email forwarding data directory'
def handle(self, *args, **options):
output_dir = args[0]
if not os.path.isdir(output_dir) or os.listdir('data'):
print('Provide an empty directory that exists', file=sys.stderr)
return 1
for fwd in ForwardedEmailAddress.objects.all():
outname = os.path.join(output_dir, '{0.name}@{0.domain}'.format(fwd))
with open(outname, 'wb') as out:
for dest in fwd.emaildestination_set.all():
print(dest.email, file=out)
|
Add an `error` listener to the Redis client.
This is probably the cause of `ETIMEDOUT` errors crashing cb_server. When the Redis connection fails for any reason (Redis being restarted, etc.), the node_redis client throws an exception instead of reconnecting unless there is an `error` handler registered on the client object.
Relevant code in node_redis: https://github.com/mranney/node_redis/blob/master/index.js#L196-200 | //
// redis_store.js
//
// Redis data store backend for cb_server
//
var redis = require("redis");
var redisClient = redis.createClient(
process.env.REDIS_PORT || 6379,
process.env.REDIS_HOST || '127.0.0.1',
{}
);
redisClient.on("error", function (err) {
console.log("Redis error: " + err);
});
function redisUserKey(username) {
return "SkynetUser:"+username;
}
module.exports = {
getUser: function (username, callback) {
redisClient.hgetall(redisUserKey(username), callback);
},
isExistingUser: function (username, callback) {
redisClient.exists(redisUserKey(username), callback);
},
createUser: function (user, callback) {
redisClient.hmset(redisUserKey(user.username), user, function (err) {
callback(err, err != null ? null : user);
});
},
updateUser: function (user, callback) {
redisClient.hmset(redisUserKey(user.username), user, function (err) {
callback(err, err != null ? null : user);
});
}
}
| //
// redis_store.js
//
// Redis data store backend for cb_server
//
var redis = require("redis");
var redisClient = redis.createClient(
process.env.REDIS_PORT || 6379,
process.env.REDIS_HOST || '127.0.0.1',
{}
);
function redisUserKey(username) {
return "SkynetUser:"+username;
}
module.exports = {
getUser: function (username, callback) {
redisClient.hgetall(redisUserKey(username), callback);
},
isExistingUser: function (username, callback) {
redisClient.exists(redisUserKey(username), callback);
},
createUser: function (user, callback) {
redisClient.hmset(redisUserKey(user.username), user, function (err) {
callback(err, err != null ? null : user);
});
},
updateUser: function (user, callback) {
redisClient.hmset(redisUserKey(user.username), user, function (err) {
callback(err, err != null ? null : user);
});
}
}
|
Fix to take an optional target | // reduce and expand
export const reduce = (x, start, end) => (x - start) / (end - start);
export const expand = (x, start, end) => (x * (end - start)) + start;
export const chainFns = fns => value => {
fns.forEach(fn => (value = fn(value)));
return value;
};
export const noOp = () => {};
export const on = (...args) => {
let target = global.window;
if(args.length > 2)
target = args.shift();
const [event, fn] = args;
const listener = (...args) => fn(...args);
target.addEventListener(event, listener);
return () => target.removeEventListener(event, listener);
};
export const Range = initial => {
const range = initial ? [initial, initial] : [];
let empty = initial === undefined;
range.extend = value => {
if(empty) {
range.push(value, value);
empty = false;
return;
}
if(value < range[0])
range[0] = value;
if(value > range[1])
range[1] = value;
};
range.min = () => range[0];
range.max = () => range[1];
range.width = () => range[1] - range[0];
return range;
};
| // reduce and expand
export const reduce = (x, start, end) => (x - start) / (end - start);
export const expand = (x, start, end) => (x * (end - start)) + start;
export const chainFns = fns => value => {
fns.forEach(fn => (value = fn(value)));
return value;
};
export const noOp = () => {};
export const on = (event, fn) => {
const listener = (...args) => fn(...args);
global.window.addEventListener(event, listener);
return () => global.window.removeEventListener(event, listener);
};
export const Range = initial => {
const range = initial ? [initial, initial] : [];
let empty = initial === undefined;
range.extend = value => {
if(empty) {
range.push(value, value);
empty = false;
return;
}
if(value < range[0])
range[0] = value;
if(value > range[1])
range[1] = value;
};
range.min = () => range[0];
range.max = () => range[1];
range.width = () => range[1] - range[0];
return range;
};
|
Add dummy collection resolving on database initialization | package lt.itdbaltics.camel.component.existdb;
import org.exist.xmldb.DatabaseImpl;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
public class DatabaseFactory {
private static DatabaseImpl database;
public DatabaseFactory() throws Exception {
if (database == null) {
database = new DatabaseImpl();
database.setProperty("create-database", "true");
database.setProperty("configuration", "conf.xml");
DatabaseManager.registerDatabase(database);
//FIXME: Externalize database URL
DatabaseManager.getCollection("xmldb:exist:///db");
}
}
public void destroy() {
if (database != null) {
try {
DatabaseManager.deregisterDatabase(database);
database = null;
} catch (Exception ex) {
}
}
}
}
| package lt.itdbaltics.camel.component.existdb;
import org.exist.xmldb.DatabaseImpl;
import org.xmldb.api.DatabaseManager;
public class DatabaseFactory {
private static DatabaseImpl database;
public DatabaseFactory() throws Exception {
if (database == null) {
database = new DatabaseImpl();
database.setProperty("create-database", "true");
database.setProperty("configuration", "conf.xml");
DatabaseManager.registerDatabase(database);
}
}
public void destroy() {
if (database != null) {
try {
DatabaseManager.deregisterDatabase(database);
database = null;
} catch (Exception ex) {
}
}
}
}
|
Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning | var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("hello");
// startTime = Date.now();
//}
if (y > screen.height){
console.log("hello");
startTime = Date.now();
vy = 0;
ay = 0;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("second if");
// vy = 0;
// ay = 0;
//}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
| var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
|
Add cwd to docker-compose to make it actually work | var spawn = require('child_process').spawn;
function Runner() {
}
Runner.prototype.init = function(bosco, next) {
this.bosco = bosco;
next();
};
Runner.prototype.list = function(options, next) {
var installed = true;
spawn('docker-compose', ['--version'], { cwd: options.cwd, stdio: 'ignore' })
.on('error', function() {
installed = false;
return next(null, []);
}).on('exit', function() {
if (installed) { return next(null, ['docker-compose']); }
});
};
Runner.prototype.stop = function(options, next) {
spawn('docker-compose', ['stop'], { cwd: options.cwd, stdio: 'inherit' }).on('exit', next);
};
Runner.prototype.start = function(options, next) {
spawn('docker-compose', ['up', '-d'], { cwd: options.cwd, stdio: 'inherit' }).on('exit', next);
};
module.exports = new Runner();
| var spawn = require('child_process').spawn;
function Runner() {
}
Runner.prototype.init = function(bosco, next) {
this.bosco = bosco;
next();
};
Runner.prototype.list = function(options, next) {
var installed = true;
spawn('docker-compose', ['--version'], { stdio: 'ignore' })
.on('error', function() {
installed = false;
return next(null, []);
}).on('exit', function() {
if (installed) { return next(null, ['docker-compose']); }
});
};
Runner.prototype.stop = function(options, next) {
spawn('docker-compose', ['stop'], { cwd: options.cwd, stdio: 'inherit' }).on('exit', next);
};
Runner.prototype.start = function(options, next) {
spawn('docker-compose', ['up', '-d'], { cwd: options.cwd, stdio: 'inherit' }).on('exit', next);
};
module.exports = new Runner();
|
Fix execution context in replaceMap | module.exports.rewire = function(module, autoReset, afterEachHook) {
var rewiredNames = [];
if (typeof autoReset === 'undefined') {
autoReset = true;
}
if (typeof afterEachHook === 'undefined') {
afterEachHook = afterEach;
}
function reset() {
rewiredNames.forEach(function(name) {
module.__ResetDependency__(name);
});
rewiredNames.length = 0;
}
if (autoReset) {
afterEachHook(reset);
}
return {
replace: function(name, replacement) {
module.__Rewire__(name, replacement);
rewiredNames.push(name);
return this;
},
replaceMap: function(replacementMap) {
var that = this;
Object.keys(replacementMap).forEach(function(name) {
that.replace(name, replacementMap[name]);
});
return this;
},
reset: function() {
reset();
return this;
}
};
};
| module.exports.rewire = function(module, autoReset, afterEachHook) {
var rewiredNames = [];
if (typeof autoReset === 'undefined') {
autoReset = true;
}
if (typeof afterEachHook === 'undefined') {
afterEachHook = afterEach;
}
function reset() {
rewiredNames.forEach(function(name) {
module.__ResetDependency__(name);
});
rewiredNames.length = 0;
}
if (autoReset) {
afterEachHook(reset);
}
return {
replace: function(name, replacement) {
module.__Rewire__(name, replacement);
rewiredNames.push(name);
return this;
},
replaceMap: function(replacementMap) {
Object.keys(replacementMap).forEach(function(name) {
this.replace(name, replacementMap[name]);
});
return this;
},
reset: function() {
reset();
return this;
}
};
};
|
Fix a stupid typo in the Google Closure Compiler processor that prevented it from working properly. | __author__ = "Wim Leers (work@wimleers.com)"
__version__ = "$Rev$"
__date__ = "$Date$"
__license__ = "GPL"
from processor import *
import os
import os.path
class GoogleClosureCompiler(Processor):
"""compresses .js files with Google Closure Compiler"""
valid_extensions = (".js")
def run(self):
# We don't rename the file, so we can use the default output file.
# Run Google Closure Compiler on the file.
compiler_path = os.path.join(self.processors_path, "compiler.jar")
(stdout, stderr) = self.run_command("java -jar %s --js %s --js_output_file %s" % (compiler_path, self.input_file, self.output_file))
# Raise an exception if an error occurred.
if not stderr == "":
raise ProcessorError(stderr)
return self.output_file
| __author__ = "Wim Leers (work@wimleers.com)"
__version__ = "$Rev$"
__date__ = "$Date$"
__license__ = "GPL"
from processor import *
import os
import os.path
class GoogleClosureCompiler(Processor):
"""compresses .js files with Google Closure Compiler"""
valid_extensions = (".js")
def run(self):
# We don't rename the file, so we can use the default output file.
# Run Google Closure Compiler on the file.
compiler_path = os.path.join(self.processors_path, "compiler.jar")
(stdout, stderr) = self.run_command("java -jar %s --js %s --js_output_file %s" % (compiler_path, self.input_file, self.input_file))
# Raise an exception if an error occurred.
if not stderr == "":
raise ProcessorError(stderr)
return self.output_file
|
Change reminder interval to 2 hours | <?php
use \Moat\Models;
/**
*
*
* @author Tyler Menezes <tylermenezes@gmail.com>
* @copyright Copyright (c) Tyler Menezes. Released under the BSD license.
*
*/
class cron {
use \ThinTasks\Task;
public function main()
{
// Event reminders
$upcoming_unnotified_hours = Models\OfficeHours\Slot::find()
->where('NOW() < starts_at')
->where('NOW() > DATE_SUB(starts_at, INTERVAL 2 HOUR)')
->where('sent_reminder = 0')
->where('userID IS NOT NULL')
->order_by('starts_at ASC')
->all();
foreach ($upcoming_unnotified_hours as $slot) {
mail($slot->user->email, 'Hours on '.date('M j', $slot->starts_at).' at '.date('g:i a', $slot->starts_at),
\Moat::$twig->render('emails/hours_reminder.txt.twig', ['slot' => $slot]),
'From: "Moat" <moat@studentrnd.org>');
$slot->sent_reminder = true;
}
}
}
| <?php
use \Moat\Models;
/**
*
*
* @author Tyler Menezes <tylermenezes@gmail.com>
* @copyright Copyright (c) Tyler Menezes. Released under the BSD license.
*
*/
class cron {
use \ThinTasks\Task;
public function main()
{
// Event reminders
$upcoming_unnotified_hours = Models\OfficeHours\Slot::find()
->where('NOW() < starts_at')
->where('NOW() > DATE_SUB(starts_at, INTERVAL 1 HOUR)')
->where('sent_reminder = 0')
->where('userID IS NOT NULL')
->order_by('starts_at ASC')
->all();
foreach ($upcoming_unnotified_hours as $slot) {
mail($slot->user->email, 'Hours on '.date('M j', $slot->starts_at).' at '.date('g:i a', $slot->starts_at),
\Moat::$twig->render('emails/hours_reminder.txt.twig', ['slot' => $slot]),
'From: "Moat" <moat@studentrnd.org>');
$slot->sent_reminder = true;
}
}
}
|
Revert "add all feature flag env variables during deployment"
This reverts commit 30054de694abf26b8871ff06421a930012019390.
This is unnecessary because we’re not setting feature flag env
variables on the client side using envify (see previous commit). | import { herokuConfig } from './util'
import { extend, pick } from 'lodash'
const keys = [
'ASSET_HOST',
'ASSET_PATH',
'AWS_ACCESS_KEY_ID',
'AWS_S3_BUCKET',
'AWS_S3_HOST',
'AWS_SECRET_ACCESS_KEY',
'FACEBOOK_APP_ID',
'FILEPICKER_API_KEY',
'GOOGLE_BROWSER_KEY',
'GOOGLE_CLIENT_ID',
'HOST',
'LOG_LEVEL',
'NODE_ENV',
'SEGMENT_KEY',
'SLACK_APP_CLIENT_ID',
'SOCKET_HOST',
'UPSTREAM_HOST'
]
export default function (done) {
herokuConfig().info((err, vars) => {
if (err) done(err)
extend(process.env, pick(vars, keys))
done()
})
}
| import { herokuConfig } from './util'
import { each, includes } from 'lodash'
const keys = [
'ASSET_HOST',
'ASSET_PATH',
'AWS_ACCESS_KEY_ID',
'AWS_S3_BUCKET',
'AWS_S3_HOST',
'AWS_SECRET_ACCESS_KEY',
'FACEBOOK_APP_ID',
'FILEPICKER_API_KEY',
'GOOGLE_BROWSER_KEY',
'GOOGLE_CLIENT_ID',
'HOST',
'LOG_LEVEL',
'NODE_ENV',
'SEGMENT_KEY',
'SLACK_APP_CLIENT_ID',
'SOCKET_HOST',
'UPSTREAM_HOST'
]
export default function (done) {
herokuConfig().info((err, vars) => {
if (err) done(err)
each(vars, (v, k) => {
if (includes(keys, k) || k.startsWith('FEATURE_FLAG_')) {
process.env[k] = v
}
})
done()
})
}
|
Change name of database for test | from endpoints import Controller, CorsMixin
import sqlite3
from datetime import datetime
conn = sqlite3.connect('databaseForTest.db')
cur = conn.cursor()
class Default(Controller, CorsMixin):
def GET(self):
return "CIUK"
def POST(self, **kwargs):
return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price'])
class Products(Controller, CorsMixin):
def GET(self):
cur.execute("select * from products")
return cur.fetchall()
class Product(Controller, CorsMixin):
def GET(self, id):
cur.execute("select * from products where id=?", (id,))
return cur.fetchone()
def POST(self, **kwargs):
row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()]
cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row))
conn.commit()
return "New product added!"
def PUT(self, id, **kwargs):
row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id]
cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row))
conn.commit()
return "Product updated!"
def DELETE(self, id):
cur.execute("delete from products where id=?", (id,))
conn.commit()
return "Product deleted!"
| from endpoints import Controller, CorsMixin
import sqlite3
from datetime import datetime
conn = sqlite3.connect('CIUK.db')
cur = conn.cursor()
class Default(Controller, CorsMixin):
def GET(self):
return "CIUK"
def POST(self, **kwargs):
return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price'])
class Products(Controller, CorsMixin):
def GET(self):
cur.execute("select * from products")
return cur.fetchall()
class Product(Controller, CorsMixin):
def GET(self, id):
cur.execute("select * from products where id=?", (id,))
return cur.fetchone()
def POST(self, **kwargs):
row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()]
cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row))
conn.commit()
return "New product added!"
def PUT(self, id, **kwargs):
row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id]
cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row))
conn.commit()
return "Product updated!"
def DELETE(self, id):
cur.execute("delete from products where id=?", (id,))
conn.commit()
return "Product deleted!"
|
[FIX] account_fiscal_year: Use AGPL license, as it depends on `date_range` that uses that | # Copyright 2016 Camptocamp SA
# Copyright 2018 Lorenzo Battistini <https://github.com/eLBati>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Account Fiscal Year",
"summary": "Create a menu for Account Fiscal Year",
"version": "13.0.1.0.0",
"development_status": "Beta",
"category": "Accounting",
"website": "https://github.com/OCA/account-financial-tools",
"author": "Agile Business Group, Camptocamp SA, "
"Odoo Community Association (OCA)",
"maintainers": ["eLBati"],
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["account", "date_range"],
"data": ["data/date_range_type.xml", "views/account_views.xml"],
}
| # Copyright 2016 Camptocamp SA
# Copyright 2018 Lorenzo Battistini <https://github.com/eLBati>
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Account Fiscal Year",
"summary": "Create a menu for Account Fiscal Year",
"version": "13.0.1.0.0",
"development_status": "Beta",
"category": "Accounting",
"website": "https://github.com/OCA/account-financial-tools",
"author": "Agile Business Group, Camptocamp SA, "
"Odoo Community Association (OCA)",
"maintainers": ["eLBati"],
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": ["account", "date_range"],
"data": ["data/date_range_type.xml", "views/account_views.xml"],
}
|
Add route to handle a borrow request | // import necessary modules
import express from 'express';
import users from '../controllers/users';
import verifyToken from '../controllers/auth/verifyToken';
const router = express.Router();
// Endpoint for user to signup
router.post('/signup', users.createUser);
// Endpoint for user to signin
router.post('/login', users.authenticateUser);
// Endpoint for user to upvote a book
router.post('/:userId/book/:bookId/upvote', verifyToken, users.upVote);
// Endpoint for user to downvote a book
router.post('/:userId/book/:bookId/downvote', verifyToken, users.downVote);
// Endpoint to update a book
router.post('/:userId/fav/:bookId', verifyToken, users.favoriteBook);
// Endpoint for user to review a book
router.post('/:userId/review/:bookId', verifyToken, users.reviewBook);
// Endpoint for user to get favorite books
router.get('/:userId/favbooks', verifyToken, users.getFavoriteBooks);
// Endpoint for user to borrow a book
router.post('/:userId/borrow/:bookId', verifyToken, users.sendBorrowRequest);
// Endpoint for Admin to handle borrow requests
router.put('/:userId/borrow/:bookId', verifyToken, users.handleBorrowRequest);
export default router;
| // import necessary modules
import express from 'express';
import users from '../controllers/users';
import verifyToken from '../controllers/auth/verifyToken';
const router = express.Router();
router.post('/signup', users.createUser);
router.post('/login', users.authenticateUser);
// Endpoint for user to upvote a book
router.post('/:userId/book/:bookId/upvote', verifyToken, users.upVote);
// Endpoint for user to downvote a book
router.post('/:userId/book/:bookId/downvote', verifyToken, users.downVote);
// Endpoint to update a book
router.post('/:userId/fav/:bookId', verifyToken, users.favoriteBook);
// Endpoint for user to review a book
router.post('/:userId/review/:bookId', verifyToken, users.reviewBook);
router.get('/:userId/favbooks', verifyToken, users.getFavoriteBooks);
router.post('/:userId/borrow/:bookId', verifyToken, users.sendBorrowRequest);
export default router;
|
Revert "use strict dependency injection" | 'use strict';
/**
* angular-select-text directive
*/
angular.module('angular-select-text', []).
directive('selectText', function ($window) {
var selectElement;
if ($window.document.selection) {
selectElement = function(element) {
var range = $window.document.body.createTextRange();
range.moveToElementText(element[0]);
range.select();
};
} else if ($window.getSelection) {
selectElement = function(element) {
var range = $window.document.createRange();
range.selectNode(element[0]);
$window.getSelection().addRange(range);
};
}
return {
restrict: 'A',
link: function(scope, element, attrs){
element.bind('click', function(){
selectElement(element);
});
}
};
}); | 'use strict';
/**
* angular-select-text directive
*/
angular.module('angular-select-text', []).
directive('selectText', ['$window', function ($window) {
var selectElement;
if ($window.document.selection) {
selectElement = function(element) {
var range = $window.document.body.createTextRange();
range.moveToElementText(element[0]);
range.select();
};
} else if ($window.getSelection) {
selectElement = function(element) {
var range = $window.document.createRange();
range.selectNode(element[0]);
$window.getSelection().addRange(range);
};
}
return {
restrict: 'A',
link: function(scope, element, attrs){
element.bind('click', function(){
selectElement(element);
});
}
};
}]);
|
Use the correct classifier for production | import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [req.strip() for req in open('requirements.pip')]
setup(
name = 'leaderboard',
version = "2.0.0",
author = 'David Czarnecki',
author_email = "dczarnecki@agoragames.com",
packages = ['leaderboard'],
install_requires = requirements,
url = 'https://github.com/agoragames/leaderboard-python',
license = "LICENSE.txt",
description = 'Leaderboards backed by Redis in Python',
long_description = open('README.md').read(),
keywords = ['python', 'redis', 'leaderboard'],
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: System :: Distributed Computing",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries'
]
)
| import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
requirements = [req.strip() for req in open('requirements.pip')]
setup(
name = 'leaderboard',
version = "2.0.0",
author = 'David Czarnecki',
author_email = "dczarnecki@agoragames.com",
packages = ['leaderboard'],
install_requires = requirements,
url = 'https://github.com/agoragames/leaderboard-python',
license = "LICENSE.txt",
description = 'Leaderboards backed by Redis in Python',
long_description = open('README.md').read(),
keywords = ['python', 'redis', 'leaderboard'],
classifiers = [
'Development Status :: 1 - Production',
'License :: OSI Approved :: MIT License',
"Intended Audience :: Developers",
"Operating System :: POSIX",
"Topic :: Communications",
"Topic :: System :: Distributed Computing",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries'
]
)
|
Add window.onload for style adjust | function adjustStyle() {
var width = 0;
// get the width.. more cross-browser issues
if (window.innerHeight) {
width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
width = document.documentElement.clientWidth;
} else if (document.body) {
width = document.body.clientWidth;
}
// now we should have it
if (width < 600) {
document.getElementById("myCSS").setAttribute("href", "_css/narrow.css");
} else {
document.getElementById("myCSS").setAttribute("href", "_css/main.css");
}
}
// now call it when the window is resized.
window.onresize = function () {
adjustStyle();
};
window.onload = function () {
adjustStyle();
}; | function adjustStyle() {
var width = 0;
// get the width.. more cross-browser issues
if (window.innerHeight) {
width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
width = document.documentElement.clientWidth;
} else if (document.body) {
width = document.body.clientWidth;
}
// now we should have it
if (width < 600) {
document.getElementById("myCSS").setAttribute("href", "_css/narrow.css");
} else {
document.getElementById("myCSS").setAttribute("href", "_css/main.css");
}
}
// now call it when the window is resized.
window.onresize = function () {
adjustStyle();
};
|
Reset the num threads to the env variable, not the default | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_NUM_THREADS))
threads = "3154"
env[key] = threads
config.reload_config()
try:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
| from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test_ = False
def test_num_threads_variable(self):
"""
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
"""
key = 'NUMBA_NUM_THREADS'
current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS))
threads = "3154"
env[key] = threads
config.reload_config()
try:
self.assertEqual(threads, str(get_thread_count()))
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
finally:
# reset the env variable/set to default
env[key] = current
config.reload_config()
if __name__ == '__main__':
unittest.main()
|
Rename ResCountry class to CompassionCountry | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import fields, models
class CompassionCountry(models.Model):
""" This class upgrade the countries to add spoken languages
to match Compassion needs.
"""
_inherit = 'compassion.country'
##########################################################################
# FIELDS #
##########################################################################
spoken_langs_ids = fields.Many2many('res.lang.compassion')
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emmanuel Mathier <emmanuel.mathier@gmail.com>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import fields, models
class ResCountry(models.Model):
""" This class upgrade the countries to add spoken languages
to match Compassion needs.
"""
_inherit = 'compassion.country'
##########################################################################
# FIELDS #
##########################################################################
spoken_langs_ids = fields.Many2many('res.lang.compassion')
|
Make the JS file more readable by moving the comments. | // jQuery.instance
// ---------------
;(function($) {
$.fn.instance = function (type) {
var $this = this.first();
var $this = $this.data('instance') || ($this.data('instance', $this) && $this);
// Tip: Implement a 'klass' property to make sure extending doesn't happen twice.
if ((type) && ((!$this.klass) || (!type.klass) || ($this.klass != type.klass))) {
$this.extend(type);
}
return $this;
};
})(jQuery);
/* Quick usage guide:
*
* var $one = $("#sidebar").instance();
* var $two = $("#sidebar").instance();
* $one.abc = 42;
* $two.abc; //=> 42
*
* var Rule = {
* expand: function () { ... }
* };
*
* var $one = $("#sidebar").instance(Rule);
* $one.expand();
*/
| /* jQuery.instance
* ---------------
*
* Quick guide:
*
* var $one = $("#sidebar").instance();
* var $two = $("#sidebar").instance();
* $one.abc = 42;
* $two.abc; //=> 42
*
* var Rule = {
* expand: function () { ... }
* };
*
* var $one = $("#sidebar").instance(Rule);
* $one.expand();
*/
;(function($) {
$.fn.instance = function (type) {
var $this = this.first();
var $this = $this.data('instance') || ($this.data('instance', $this) && $this);
// Tip: Implement a 'klass' property to make sure extending doesn't happen twice.
if ((type) && ((!$this.klass) || (!type.klass) || ($this.klass != type.klass))) {
$this.extend(type);
}
return $this;
};
})(jQuery);
|
Set thread local the entity manager in validatorfactory also in
doTransaction with already created EntityManagers | package persistence.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
public class TransactionUtil {
public static void doTransaction(EntityManagerFactory emf, Transaction t) {
EntityManager em = emf.createEntityManager();
EMInjectorConstraintValidatorFactory.setThreadLocalEntityManager(em);
try{
doTransaction(em, t);
}finally {
em.close();
}
}
public static void doTransaction(EntityManager em, Transaction t) {
EntityTransaction tx = null;
EMInjectorConstraintValidatorFactory.setThreadLocalEntityManager(em);
try{
tx = em.getTransaction();
tx.begin();
t.doTransation(em);
tx.commit();
} finally {
if (tx != null && tx.isActive()) {
tx.rollback();
}
}
}
}
| package persistence.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
public class TransactionUtil {
public static void doTransaction(EntityManagerFactory emf, Transaction t) {
EntityManager em = emf.createEntityManager();
EMInjectorConstraintValidatorFactory.setThreadLocalEntityManager(em);
try{
doTransaction(em, t);
}finally {
em.close();
}
}
public static void doTransaction(EntityManager em, Transaction t) {
EntityTransaction tx = null;
try{
tx = em.getTransaction();
tx.begin();
t.doTransation(em);
tx.commit();
} finally {
if (tx != null && tx.isActive()) {
tx.rollback();
}
}
}
}
|
Check Python version at startup | from distutils.version import StrictVersion
from platform import python_version
min_supported_python_version = '3.6'
if StrictVersion(python_version()) < StrictVersion(min_supported_python_version):
error_msg = (
"Tohu requires Python {min_supported_python_version} or greater to run "
"(currently running under Python {python_version()})"
)
raise RuntimeError(error_msg)
from .v4.base import *
from .v4.primitive_generators import *
from .v4.derived_generators import *
from .v4.dispatch_generators import *
from .v4.custom_generator import CustomGenerator
from .v4.logging import logger
from .v4.utils import print_generated_sequence
from .v4 import base
from .v4 import primitive_generators
from .v4 import derived_generators
from .v4 import dispatch_generators
from .v4 import custom_generator
from .v4 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ dispatch_generators.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias | from .v4.base import *
from .v4.primitive_generators import *
from .v4.derived_generators import *
from .v4.dispatch_generators import *
from .v4.custom_generator import CustomGenerator
from .v4.logging import logger
from .v4.utils import print_generated_sequence
from .v4 import base
from .v4 import primitive_generators
from .v4 import derived_generators
from .v4 import dispatch_generators
from .v4 import custom_generator
from .v4 import set_special_methods
__all__ = base.__all__ \
+ primitive_generators.__all__ \
+ derived_generators.__all__ \
+ dispatch_generators.__all__ \
+ custom_generator.__all__ \
+ ['tohu_logger', 'print_generated_sequence']
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
tohu_logger = logger # alias |
Use environment variable to fetch map information | const mapBaseLayers = require('../../../public/static/map/map-base-layers.config.json')
async function fetchMap(resolver, query) {
const result = await fetch(process.env.GRAPHQL_ENDPOINT, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
}),
})
const json = await result.json()
return json.data[resolver]
}
export function getMapBaseLayers() {
return mapBaseLayers
}
export async function getMapLayers() {
const query = `{ mapLayerSearch { results { id title url params layers external detailUrl detailItem detailIsShape noDetail authScope } } }`
const { results: mapLayerResults } = await fetchMap('mapLayerSearch', query)
return mapLayerResults
}
export async function getPanelLayers() {
const query = `{ mapCollectionSearch { results { id title mapLayers { id title legendItems { id title url params layers iconUrl imageRule notSelectable noDetail } authScope imageRule iconUrl url params layers detailUrl detailItem detailIsShape noDetail minZoom maxZoom } } } }`
const { results: mapPanelLayerResults } = await fetchMap('mapCollectionSearch', query)
return mapPanelLayerResults
}
| const mapBaseLayers = require('../../../public/static/map/map-base-layers.config.json')
async function fetchMap(resolver, query) {
const result = await fetch('http://localhost:8080/cms_search/graphql', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
}),
})
const json = await result.json()
return json.data[resolver]
}
export function getMapBaseLayers() {
return mapBaseLayers
}
export async function getMapLayers() {
const query = `{ mapLayerSearch { results { id title url params layers external detailUrl detailItem detailIsShape noDetail authScope } } }`
const { results: mapLayerResults } = await fetchMap('mapLayerSearch', query)
return mapLayerResults
}
export async function getPanelLayers() {
const query = `{ mapCollectionSearch { results { id title mapLayers { id title legendItems { id title url params layers iconUrl imageRule notSelectable noDetail } authScope imageRule iconUrl url params layers detailUrl detailItem detailIsShape noDetail minZoom maxZoom } } } }`
const { results: mapPanelLayerResults } = await fetchMap('mapCollectionSearch', query)
return mapPanelLayerResults
}
|
Use useCallback so that `increment` is memoized | import React, {useState} from 'react';
import PropTypes from 'prop-types';
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
const increment = useCallback(() => setCount(count + 1), [count]);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={increment}
>
Increment
</button>
</div>
);
};
Counter.propTypes = {
initialCount: PropTypes.number,
};
Counter.defaultProps = {
initialCount: 0,
};
export default Counter;
| import React, {useState} from 'react';
import PropTypes from 'prop-types';
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
const increment = () => setCount(count + 1);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={increment}
>
Increment
</button>
</div>
);
};
Counter.propTypes = {
initialCount: PropTypes.number,
};
Counter.defaultProps = {
initialCount: 0,
};
export default Counter;
|
Add note and fatal to Log | import sys
from colors import Colors
class Log:
@classmethod
def print_msg(cls, title, msg, color, new_line = True):
Log.raw("{0}{1}{2}: {3}".format(color, title, Colors.NORMAL, msg), new_line)
@classmethod
def msg(cls, msg, new_line = True):
Log.print_msg("Message", msg, Colors.MAGENTA_FG, new_line)
@classmethod
def info(cls, msg, new_line = True):
Log.print_msg("Info", msg, Colors.CYAN_FG, new_line)
@classmethod
def warn(cls, msg, new_line = True):
Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)
@classmethod
def note(cls, msg, new_line = True):
Log.print_msg("Note", msg, Colors.YELLOW_FG, new_line)
@classmethod
def err(cls, msg, new_line = True):
Log.print_msg("Error", msg, Colors.RED_FG, new_line)
@classmethod
def fatal(cls, msg, new_line = True):
Log.print_msg("Fatal", msg, Colors.RED_FG, new_line)
exit(1)
@classmethod
def raw(cls, msg, new_line = True):
if new_line and msg[-1:] != "\n":
msg += "\n"
sys.stdout.write("{0}".format(msg))
| import sys
from colors import Colors
class Log:
@classmethod
def print_msg(cls, title, msg, color, new_line = True):
Log.raw("{0}{1}{2}: {3}".format(color, title, Colors.NORMAL, msg), new_line)
@classmethod
def msg(cls, msg, new_line = True):
Log.print_msg("Message", msg, Colors.MAGENTA_FG, new_line)
@classmethod
def info(cls, msg, new_line = True):
Log.print_msg("Info", msg, Colors.CYAN_FG, new_line)
@classmethod
def warn(cls, msg, new_line = True):
Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)
@classmethod
def err(cls, msg, new_line = True):
Log.print_msg("Error", msg, Colors.RED_FG, new_line)
@classmethod
def raw(cls, msg, new_line = True):
if new_line and msg[-1:] != "\n":
msg += "\n"
sys.stdout.write("{0}".format(msg))
|
Use the VERSION constant if available | <?php
use League\CommonMark\CommonMarkConverter;
require_once __DIR__.'/../vendor/autoload.php';
function getVersion() {
if (defined('League\CommonMark\CommonMarkConverter::VERSION')) {
$version = CommonMarkConverter::VERSION;
if (preg_match('/^[\d\.]+/$', $version) === 1) {
return $version;
}
}
$lock = json_decode(file_get_contents(__DIR__.'/../composer.lock'), true);
foreach ($lock['packages'] as $package) {
if ($package['name'] === 'league/commonmark') {
return $package['version'];
}
}
if (isset($version)) {
return $version;
}
return 'latest';
}
if (!isset($_GET['text'])) {
$markdown = '';
} else {
$markdown = $_GET['text'];
if (mb_strlen($markdown) > 1000) {
http_response_code(413); // Request Entity Too Large
$markdown = "Input must be less than 1,000 characters";
}
}
$converter = new CommonMarkConverter();
$html = $converter->convertToHtml($markdown);
header('Content-Type: application/json');
echo json_encode([
'name' => 'league/commonmark',
'version' => getVersion(),
'html' => $html,
]);
| <?php
use League\CommonMark\CommonMarkConverter;
require_once __DIR__.'/../vendor/autoload.php';
function getVersion() {
$lock = json_decode(file_get_contents(__DIR__.'/../composer.lock'), true);
foreach ($lock['packages'] as $package) {
if ($package['name'] === 'league/commonmark') {
return $package['version'];
}
}
return 'latest';
}
if (!isset($_GET['text'])) {
$markdown = '';
} else {
$markdown = $_GET['text'];
if (mb_strlen($markdown) > 1000) {
http_response_code(413); // Request Entity Too Large
$markdown = "Input must be less than 1,000 characters";
}
}
$converter = new CommonMarkConverter();
$html = $converter->convertToHtml($markdown);
header('Content-Type: application/json');
echo json_encode([
'name' => 'league/commonmark',
'version' => getVersion(),
'html' => $html,
]);
|
[Registry] Initialize shared registry with empty array | <?php
/*
* This file is part of the Panda Registry Package.
*
* (c) Ioannis Papikas <papikas.ioan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Panda\Registry;
/**
* Class SharedRegistry
* @package Panda\Registry
*/
class SharedRegistry extends AbstractRegistry
{
/**
* @var array
*/
protected static $registry = [];
/**
* @return array
*/
public function getRegistry(): array
{
return self::$registry;
}
/**
* @param array $registry
*/
public function setRegistry(array $registry)
{
self::$registry = $registry;
}
}
| <?php
/*
* This file is part of the Panda Registry Package.
*
* (c) Ioannis Papikas <papikas.ioan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Panda\Registry;
/**
* Class SharedRegistry
* @package Panda\Registry
*/
class SharedRegistry extends AbstractRegistry
{
/**
* @var array
*/
protected static $registry;
/**
* @return array
*/
public function getRegistry(): array
{
return self::$registry;
}
/**
* @param array $registry
*/
public function setRegistry(array $registry)
{
self::$registry = $registry;
}
}
|
Fix lolex integration test on old nodes | require('../common');
var util = require('util');
var assert = require('assert');
var lolex = require('lolex');
var stream = require('../../');
var Transform = stream.Transform;
function MyTransform() {
Transform.call(this);
}
util.inherits(MyTransform, Transform);
var clock = lolex.install({toFake: [ 'setImmediate', 'nextTick' ]});
var stream2DataCalled = false;
var stream = new MyTransform();
stream.on('data', function() {
stream.on('end', function() {
var stream2 = new MyTransform();
stream2.on('data', function() {
stream2.on('end', function() {
stream2DataCalled = true
});
setImmediate(function() {
stream2.end()
});
});
stream2.emit('data')
});
stream.end();
});
stream.emit('data');
clock.runAll()
clock.uninstall();
assert(stream2DataCalled);
| require('../common');
var util = require('util');
var assert = require('assert');
var lolex = require('lolex');
var stream = require('../../');
var Transform = stream.Transform;
function MyTransform() {
Transform.call(this);
}
util.inherits(MyTransform, Transform);
const clock = lolex.install({toFake: [ 'setImmediate', 'nextTick' ]});
let stream2DataCalled = false;
var stream = new MyTransform();
stream.on('data', function() {
stream.on('end', function() {
var stream2 = new MyTransform();
stream2.on('data', function() {
stream2.on('end', function() {
stream2DataCalled = true
});
setImmediate(function() {
stream2.end()
});
});
stream2.emit('data')
});
stream.end();
});
stream.emit('data');
clock.runAll()
clock.uninstall();
assert(stream2DataCalled);
|
Disable test until bug fixed. | package org.jctools.queues;
import org.jctools.queues.spec.ConcurrentQueueSpec;
import org.jctools.queues.spec.Ordering;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Collection;
import static org.jctools.util.PortableJvmInfo.CPUs;
@RunWith(Parameterized.class)
@Ignore
public class MpqSanityTestMpscCompound extends MpqSanityTest
{
public MpqSanityTestMpscCompound(ConcurrentQueueSpec spec, MessagePassingQueue<Integer> queue)
{
super(spec, queue);
}
@Parameterized.Parameters
public static Collection<Object[]> parameters()
{
ArrayList<Object[]> list = new ArrayList<Object[]>();
list.add(makeMpq(0, 1, CPUs, Ordering.NONE, null));// MPSC size 1
list.add(makeMpq(0, 1, SIZE, Ordering.NONE, null));// MPSC size SIZE
return list;
}
}
| package org.jctools.queues;
import org.jctools.queues.spec.ConcurrentQueueSpec;
import org.jctools.queues.spec.Ordering;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Collection;
import static org.jctools.util.PortableJvmInfo.CPUs;
@RunWith(Parameterized.class)
public class MpqSanityTestMpscCompound extends MpqSanityTest
{
public MpqSanityTestMpscCompound(ConcurrentQueueSpec spec, MessagePassingQueue<Integer> queue)
{
super(spec, queue);
}
@Parameterized.Parameters
public static Collection<Object[]> parameters()
{
ArrayList<Object[]> list = new ArrayList<Object[]>();
list.add(makeMpq(0, 1, CPUs, Ordering.NONE, null));// MPSC size 1
list.add(makeMpq(0, 1, SIZE, Ordering.NONE, null));// MPSC size SIZE
return list;
}
}
|
Change help text for MFMT | 'use strict';
// Third party dependencies
var moment = require('moment');
// Local dependencies
var command = require('../lib/command');
var fs = require('../lib/fs');
/**
* Returns the last modified timestamp of the remote file as a decimal number.
* @param {!string} pathname
* @param {!object} commandChannel
* @param {!object} session
*/
command.add('MFMT', 'MFMT <sp> time-val <sp> pathname', function (args, commandChannel, session) {
// Right number of arguments?
if (args.split(' ').length < 2) {
commandChannel.write(501, 'Invalid number of arguments');
return;
}
// Parse the arguments
var modificationTime = moment(args.split(' ', 2)[0], 'YYYYMMDDHHmmss');
var pathname = args.split(' ', 2)[1];
var absolutePath = fs.toAbsolute(pathname, session.cwd);
// Valid modification time?
if (!modificationTime.isValid()) {
commandChannel.write(501, modificationTime + ': Invalid argument');
return;
}
fs.utimes(absolutePath, modificationTime.unix(), modificationTime.unix(), function (err) {
if (err) {
commandChannel.write(550, fs.errorMessage(err, pathname));
} else {
commandChannel.write(213, 'Modify=' + modificationTime.format('YYYYMMDDHHmmss') + '; ' + pathname);
}
});
});
| 'use strict';
// Third party dependencies
var moment = require('moment');
// Local dependencies
var command = require('../lib/command');
var fs = require('../lib/fs');
/**
* Returns the last modified timestamp of the remote file as a decimal number.
* @param {!string} pathname
* @param {!object} commandChannel
* @param {!object} session
*/
command.add('MFMT', 'MFMT <sp> time <sp> pathname', function (args, commandChannel, session) {
// Right number of arguments?
if (args.split(' ').length < 2) {
commandChannel.write(501, 'Invalid number of arguments');
return;
}
// Parse the arguments
var modificationTime = moment(args.split(' ', 2)[0], 'YYYYMMDDHHmmss');
var pathname = args.split(' ', 2)[1];
var absolutePath = fs.toAbsolute(pathname, session.cwd);
// Valid modification time?
if (!modificationTime.isValid()) {
commandChannel.write(501, modificationTime + ': Invalid argument');
return;
}
fs.utimes(absolutePath, modificationTime.unix(), modificationTime.unix(), function (err) {
if (err) {
commandChannel.write(550, fs.errorMessage(err, pathname));
} else {
commandChannel.write(213, 'Modify=' + modificationTime.format('YYYYMMDDHHmmss') + '; ' + pathname);
}
});
});
|
Add comments for dev and clear codes. | function r() {
var strings = arguments[0]; // template strings
var values = Array.prototype.slice.call(arguments, 1); // interpolation values
// concentrate strings and interpolations
var str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
})
.replace(/\r\n/g, '\n'); // replace for window newline \r\n
// check top-tagged applied
var newlineAndTabs = str.match(/^\n[\t]*/);
if( newlineAndTabs != null ) {
var matched = newlineAndTabs[0];
str = str.replace(new RegExp(matched, 'g'), '\n')
.substr(1);
}
else {
var matched = str.match(/^[\t]*/)[0];
str = str.substr(matched.length)
.replace(new RegExp('\n'+matched, 'g'), '\n');
}
return str;
}
module.exports = r; | function r() {
var strings = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
// concentrate strings and interpolations
var str = strings.raw.reduce(function(prev, cur, idx) {
return prev + values[idx-1] + cur;
})
.replace(/\r\n/g, '\n');
var newlineAndTabs = str.match(/^\n[\t]*/);
if( newlineAndTabs != null ) {
var matched = newlineAndTabs[0];
str = str.replace(new RegExp(matched, 'g'), '\n').substr(1);
}
else {
var matched = str.match(/^[\t]*/)[0];
str = str.substr(matched.length).replace(new RegExp('\n'+matched, 'g'), '\n');
}
return str;
}
module.exports = r; |
Make autoupdate depend on reload, which makes sense
Since it actually calls reload | Package.describe({
summary: "Update the client when new client code is available",
version: '1.2.2-plugins.0'
});
Cordova.depends({
'cordova-plugin-file': '2.0.0',
'cordova-plugin-file-transfer': '1.0.0'
});
Package.onUse(function (api) {
api.use([
'webapp',
'check'
], 'server');
api.use([
'tracker',
'retry'
], 'client');
api.use([
'ddp',
'mongo',
'underscore'
], ['client', 'server']);
api.use('reload', 'client');
api.use(['http', 'random'], 'web.cordova');
api.addFiles('autoupdate_server.js', 'server');
api.addFiles('autoupdate_client.js', 'web.browser');
api.addFiles('autoupdate_cordova.js', 'web.cordova');
api.export('Autoupdate');
});
| Package.describe({
summary: "Update the client when new client code is available",
version: '1.2.2-plugins.0'
});
Cordova.depends({
'cordova-plugin-file': '2.0.0',
'cordova-plugin-file-transfer': '1.0.0'
});
Package.onUse(function (api) {
api.use([
'webapp',
'check'
], 'server');
api.use([
'tracker',
'retry'
], 'client');
api.use([
'ddp',
'mongo',
'underscore'
], ['client', 'server']);
api.use('reload', 'client', {weak: true});
api.use(['http', 'random'], 'web.cordova');
api.addFiles('autoupdate_server.js', 'server');
api.addFiles('autoupdate_client.js', 'web.browser');
api.addFiles('autoupdate_cordova.js', 'web.cordova');
api.export('Autoupdate');
});
|
Add missing binding for Logging | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.log;
import com.google.common.annotations.Beta;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import javax.inject.Singleton;
import static org.weakref.jmx.guice.ExportBinder.newExporter;
@Beta
public class LogJmxModule
implements Module
{
@Override
public void configure(Binder binder)
{
binder.disableCircularProxies();
binder.bind(LoggingMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(LoggingMBean.class).as("io.airlift.log:name=Logging");
}
@Provides
@Singleton
public Logging getLogging()
{
return Logging.initialize();
}
}
| /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.log;
import com.google.common.annotations.Beta;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import static org.weakref.jmx.guice.ExportBinder.newExporter;
@Beta
public class LogJmxModule
implements Module
{
@Override
public void configure(Binder binder)
{
binder.disableCircularProxies();
binder.bind(LoggingMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(LoggingMBean.class).as("io.airlift.log:name=Logging");
}
}
|
Fix notification counter when there's more than 100 notifications
Turns out Movim 0.14 can call this function with a string "+100". | const {ipcRenderer} = require('electron');
window.electron = {
openExternal: function(url) {
ipcRenderer.send('open-external', url);
},
notification: function(counter) {
ipcRenderer.send('notification', ~~counter);
}
};
// shim for old Movim pods
window.require = function(str) {
return {
shell: {
openExternal: function(url) {
window.electron.openExternal(url);
}
},
remote: {
getCurrentWindow: function() {
return {
notification: function(counter) {
window.electron.notification(counter);
}
}
}
}
};
};
| const {ipcRenderer} = require('electron');
window.electron = {
openExternal: function(url) {
ipcRenderer.send('open-external', url);
},
notification: function(counter) {
ipcRenderer.send('notification', 0 + counter);
}
};
// shim for old Movim pods
window.require = function(str) {
return {
shell: {
openExternal: function(url) {
window.electron.openExternal(url);
}
},
remote: {
getCurrentWindow: function() {
return {
notification: function(counter) {
window.electron.notification(counter);
}
}
}
}
};
};
|
Disable admin panel element translations, if appropriate options is activated | <?php
namespace TMCms\Admin;
use TMCms\Config\Settings;
use TMCms\Files\Finder;
use TMCms\Traits\singletonOnlyInstanceTrait;
defined ('INC') or exit;
class AdminTranslations {
use singletonOnlyInstanceTrait;
private static $init_data = [];
public function getActualValueByKey($key) {
if (!self::$init_data) {
$this->init_data();
}
return is_string($key) && isset(self::$init_data[$key]) ? self::$init_data[$key] : $key;
}
private function init_data()
{
if (Settings::getInstance()->get('disable_cms_translations')) {
return; // No translations
}
$data = [];
foreach (Finder::getInstance()->getPathFolders(Finder::TYPE_TRANSLATIONS) as $file) {
$file_path = $file . Users::getInstance()->getUserLng() . '.php';
if (stripos($file_path, DIR_BASE) === false) {
$file_path = DIR_BASE . $file_path;
}
if (file_exists($file_path)) {
$data += require_once $file_path;
}
}
self::$init_data = $data;
}
} | <?php
namespace TMCms\Admin;
use TMCms\Files\Finder;
use TMCms\Traits\singletonOnlyInstanceTrait;
defined ('INC') or exit;
class AdminTranslations {
use singletonOnlyInstanceTrait;
private static $init_data;
public function getActualValueByKey($key) {
if (!self::$init_data) {
$this->init_data();
}
return is_string($key) && isset(self::$init_data[$key]) ? self::$init_data[$key] : $key;
}
private function init_data()
{
$data = [];
foreach (Finder::getInstance()->getPathFolders(Finder::TYPE_TRANSLATIONS) as $file) {
$file_path = $file . Users::getInstance()->getUserLng() . '.php';
if (stripos($file_path, DIR_BASE) === false) {
$file_path = DIR_BASE . $file_path;
}
if (file_exists($file_path)) {
$data += require_once $file_path;
}
}
self::$init_data = $data;
}
} |
Allow new GitHub token format
GitHub rolled out a new OAuth token format, see
https://github.blog/2021-04-05-behind-githubs-new-authentication-token-formats/
This commit updates the configuration properties validation to allow it. | package sagan.renderer;
import javax.validation.constraints.Pattern;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* Configuration properties for the Sagan Renderer application
*/
@ConfigurationProperties("sagan.renderer")
@Validated
public class RendererProperties {
private final Github github = new Github();
private final Guides guides = new Guides();
public Github getGithub() {
return this.github;
}
public Guides getGuides() {
return this.guides;
}
public static class Github {
/**
* Access token to query public github endpoints.
* https://developer.github.com/v3/auth/#authenticating-for-saml-sso
*/
@Pattern(regexp = "([0-9a-zA-Z_]*)?")
private String token;
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
}
public static class Guides {
/**
* Name of the Github organization to fetch guides from.
*/
private String organization = "spring-guides";
public String getOrganization() {
return this.organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
}
}
| package sagan.renderer;
import javax.validation.constraints.Pattern;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* Configuration properties for the Sagan Renderer application
*/
@ConfigurationProperties("sagan.renderer")
@Validated
public class RendererProperties {
private final Github github = new Github();
private final Guides guides = new Guides();
public Github getGithub() {
return this.github;
}
public Guides getGuides() {
return this.guides;
}
public static class Github {
/**
* Access token to query public github endpoints.
* https://developer.github.com/v3/auth/#authenticating-for-saml-sso
*/
@Pattern(regexp = "([0-9a-z]*)?")
private String token;
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
}
public static class Guides {
/**
* Name of the Github organization to fetch guides from.
*/
private String organization = "spring-guides";
public String getOrganization() {
return this.organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
}
}
|
Add non-working test for X-Forwarded-For | import requests
def register_asheesh():
return requests.post(
'http://localhost:3000/register',
{'rawHostname': 'asheesh',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()},
)
def register_asheesh2_bad_key_type():
return requests.post(
'http://localhost:3000/register',
{'rawHostname': 'asheesh2',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pem').read()},
)
def register_asheesh3_x_forwarded_for():
# Provide the HTTP_FORWARDED_COUNT=1 environment variable to
# Meteor before running this test.
#
# FIXME: This doesn't pass, but for now, I'm not *that* worried.
return requests.post(
'http://localhost:3000/register',
data={'rawHostname': 'asheesh3',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()},
headers={'X-Forwarded-For': '128.151.2.1'},
)
| import requests
def register_asheesh():
return requests.post(
'http://localhost:3000/register',
{'rawHostname': 'asheesh',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()},
)
def register_asheesh2_bad_key_type():
return requests.post(
'http://localhost:3000/register',
{'rawHostname': 'asheesh2',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pem').read()},
)
|
Fix misleading test method name to avoid confusion.
svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=380843 | /* Copyright 2006 The Apache Software Foundation or its licensors, as applicable
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import junit.framework.TestCase;
public class FileChannelTest extends TestCase {
/**
* @tests java.nio.channels.FileChannel#isOpen()
*/
public void test_isOpen() throws Exception {
// Regression for HARMONY-40
File logFile = File.createTempFile("out", "tmp");
logFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(logFile, true);
FileChannel channel = out.getChannel();
out.write(1);
out.close();
assertFalse("Assert 0: Channel is still open", channel.isOpen());
}
}
| /* Copyright 2006 The Apache Software Foundation or its licensors, as applicable
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import junit.framework.TestCase;
public class FileChannelTest extends TestCase {
/**
* @tests java.nio.channels.FileChannel#isOpen()
*/
public void test_close() throws Exception {
// Regression for HARMONY-40
File logFile = File.createTempFile("out", "tmp");
logFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(logFile, true);
FileChannel channel = out.getChannel();
out.write(1);
out.close();
assertFalse("Assert 0: Channel is still open", channel.isOpen());
}
}
|
Use new urlResource options from CM | /**
* @class Denkmal_App
* @extends CM_App
*/
var Denkmal_App = CM_App.extend({
ready: function() {
CM_App.prototype.ready.call(this);
this._registerServiceWorker();
},
_registerServiceWorker: function() {
if ('serviceWorker' in navigator) {
var path = cm.getUrlResource('layout', 'js/service-worker.js', {sameOrigin: true, root: true});
navigator.serviceWorker.register(path).then(function(registration) {
cm.debug.log('ServiceWorker registration succeeded.');
}).catch(function(error) {
cm.debug.log('ServiceWorker registration failed.', error);
});
} else {
cm.debug.log('ServiceWorker not supported.');
}
}
});
| /**
* @class Denkmal_App
* @extends CM_App
*/
var Denkmal_App = CM_App.extend({
ready: function() {
CM_App.prototype.ready.call(this);
this._registerServiceWorker();
},
_registerServiceWorker: function() {
if ('serviceWorker' in navigator) {
var path = cm.getUrlResource('layout', 'js/service-worker.js');
/**
* Same-origin workaround
* @todo replace with https://github.com/cargomedia/CM/pull/1715
*/
path = path.replace(cm.getUrlResource(), cm.getUrl());
navigator.serviceWorker.register(path).then(function(registration) {
cm.debug.log('ServiceWorker registration succeeded.');
}).catch(function(error) {
cm.debug.log('ServiceWorker registration failed.', error);
});
} else {
cm.debug.log('ServiceWorker not supported.');
}
}
});
|
Move "Upgrade complete." to the end of the output, not the beginning. | try {
// XXX can't get this from updater.js because in 0.3.7 and before the
// updater didn't have the right NODE_PATH set. At some point we can
// remove this and just use updater.CURRENT_VERSION.
var VERSION = "0.3.8";
var fs = require('fs');
var path = require('path');
var files = require("../lib/files.js");
var _ = require("../lib/third/underscore.js");
var topDir = files.get_dev_bundle();
var changelogPath = path.join(topDir, 'History.md');
if (path.existsSync(changelogPath)) {
var changelogData = fs.readFileSync(changelogPath, 'utf8');
var changelogSections = changelogData.split(/\n\#\#/);
_.each(changelogSections, function (section) {
var m = /^\s*v([^\s]+)/.exec(section);
if (m && m[1] === VERSION) {
section = section.replace(/^\s+/, '').replace(/\s+$/, '');
console.log();
console.log(section);
console.log();
}
});
}
} catch (err) {
// don't print a weird error message if something goes wrong.
}
console.log("Upgrade complete.");
| console.log("Upgrade complete.");
try {
// XXX can't get this from updater.js because in 0.3.7 and before the
// updater didn't have the right NODE_PATH set. At some point we can
// remove this and just use updater.CURRENT_VERSION.
var VERSION = "0.3.8";
var fs = require('fs');
var path = require('path');
var files = require("../lib/files.js");
var _ = require("../lib/third/underscore.js");
var topDir = files.get_dev_bundle();
var changelogPath = path.join(topDir, 'History.md');
if (path.existsSync(changelogPath)) {
var changelogData = fs.readFileSync(changelogPath, 'utf8');
var changelogSections = changelogData.split(/\n\#\#/);
_.each(changelogSections, function (section) {
var m = /^\s*v([^\s]+)/.exec(section);
if (m && m[1] === VERSION) {
section = section.replace(/^\s+/, '').replace(/\s+$/, '');
console.log();
console.log(section);
console.log();
}
});
}
} catch (err) {
// don't print a weird error message if something goes wrong.
}
|
Add `null` in typehint where needed. | <?php
/**
* Bright Nucleus View Component.
*
* @package BrightNucleus\View
* @author Alain Schlesser <alain.schlesser@gmail.com>
* @license MIT
* @link http://www.brightnucleus.com/
* @copyright 2016 Alain Schlesser, Bright Nucleus
*/
namespace BrightNucleus\View\Engine;
use BrightNucleus\View\Support\FinderInterface;
use BrightNucleus\View\View\ViewInterface;
/**
* Interface ViewFinderInterface.
*
* @since 0.1.0
*
* @package BrightNucleus\View\View
* @author Alain Schlesser <alain.schlesser@gmail.com>
*/
interface ViewFinderInterface extends FinderInterface
{
/**
* Find a result based on a specific criteria.
*
* @since 0.1.0
*
* @param array $criteria Criteria to search for.
* @param EngineInterface|null $engine Optional. Engine to use with the view.
*
* @return ViewInterface View that was found.
*/
public function find(array $criteria, EngineInterface $engine = null);
}
| <?php
/**
* Bright Nucleus View Component.
*
* @package BrightNucleus\View
* @author Alain Schlesser <alain.schlesser@gmail.com>
* @license MIT
* @link http://www.brightnucleus.com/
* @copyright 2016 Alain Schlesser, Bright Nucleus
*/
namespace BrightNucleus\View\Engine;
use BrightNucleus\View\Support\FinderInterface;
use BrightNucleus\View\View\ViewInterface;
/**
* Interface ViewFinderInterface.
*
* @since 0.1.0
*
* @package BrightNucleus\View\View
* @author Alain Schlesser <alain.schlesser@gmail.com>
*/
interface ViewFinderInterface extends FinderInterface
{
/**
* Find a result based on a specific criteria.
*
* @since 0.1.0
*
* @param array $criteria Criteria to search for.
* @param EngineInterface $engine Optional. Engine to use with the view.
*
* @return ViewInterface View that was found.
*/
public function find(array $criteria, EngineInterface $engine = null);
}
|
Allow @ and - in usernames also in umessages. | from django.conf.urls import *
from userena.contrib.umessages import views as messages_views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^compose/$',
messages_views.message_compose,
name='userena_umessages_compose'),
url(r'^compose/(?P<recipients>[\@\+\.\w-]+)/$',
messages_views.message_compose,
name='userena_umessages_compose_to'),
url(r'^reply/(?P<parent_id>[\d]+)/$',
messages_views.message_compose,
name='userena_umessages_reply'),
url(r'^view/(?P<username>[\@\.\w-]+)/$',
login_required(messages_views.MessageDetailListView.as_view()),
name='userena_umessages_detail'),
url(r'^remove/$',
messages_views.message_remove,
name='userena_umessages_remove'),
url(r'^unremove/$',
messages_views.message_remove,
{'undo': True},
name='userena_umessages_unremove'),
url(r'^$',
login_required(messages_views.MessageListView.as_view()),
name='userena_umessages_list'),
)
| from django.conf.urls import *
from userena.contrib.umessages import views as messages_views
from django.contrib.auth.decorators import login_required
urlpatterns = patterns('',
url(r'^compose/$',
messages_views.message_compose,
name='userena_umessages_compose'),
url(r'^compose/(?P<recipients>[\+\.\w]+)/$',
messages_views.message_compose,
name='userena_umessages_compose_to'),
url(r'^reply/(?P<parent_id>[\d]+)/$',
messages_views.message_compose,
name='userena_umessages_reply'),
url(r'^view/(?P<username>[\.\w]+)/$',
login_required(messages_views.MessageDetailListView.as_view()),
name='userena_umessages_detail'),
url(r'^remove/$',
messages_views.message_remove,
name='userena_umessages_remove'),
url(r'^unremove/$',
messages_views.message_remove,
{'undo': True},
name='userena_umessages_unremove'),
url(r'^$',
login_required(messages_views.MessageListView.as_view()),
name='userena_umessages_list'),
)
|
Add environment to app contract. | <?php namespace Illuminate\Contracts\Foundation;
use Illuminate\Contracts\Container\Container;
interface Application extends Container {
/**
* Get or check the current application environment.
*
* @param mixed
* @return string
*/
public function environment();
/**
* Register a service provider with the application.
*
* @param \Illuminate\Support\ServiceProvider|string $provider
* @param array $options
* @param bool $force
* @return \Illuminate\Support\ServiceProvider
*/
public function register($provider, $options = array(), $force = false);
/**
* Register a deferred provider and service.
*
* @param string $provider
* @param string $service
* @return void
*/
public function registerDeferredProvider($provider, $service = null);
/**
* Boot the application's service providers.
*
* @return void
*/
public function boot();
/**
* Register a new boot listener.
*
* @param mixed $callback
* @return void
*/
public function booting($callback);
/**
* Register a new "booted" listener.
*
* @param mixed $callback
* @return void
*/
public function booted($callback);
}
| <?php namespace Illuminate\Contracts\Foundation;
use Illuminate\Contracts\Container\Container;
interface Application extends Container {
/**
* Register a service provider with the application.
*
* @param \Illuminate\Support\ServiceProvider|string $provider
* @param array $options
* @param bool $force
* @return \Illuminate\Support\ServiceProvider
*/
public function register($provider, $options = array(), $force = false);
/**
* Register a deferred provider and service.
*
* @param string $provider
* @param string $service
* @return void
*/
public function registerDeferredProvider($provider, $service = null);
/**
* Boot the application's service providers.
*
* @return void
*/
public function boot();
/**
* Register a new boot listener.
*
* @param mixed $callback
* @return void
*/
public function booting($callback);
/**
* Register a new "booted" listener.
*
* @param mixed $callback
* @return void
*/
public function booted($callback);
}
|
Remove unnecessary method (there is a magic method already) | <?php
namespace MenaraSolutions\Geographer;
/**
* Class State
* @package MenaraSolutions\FluentGeonames
*/
class State extends Divisible
{
/**
* @var string
*/
protected $memberClass = City::class;
/**
* @var string
*/
protected static $parentClass = Country::class;
/**
* @var string
*/
protected $standard = 'geonames';
/**
* @var array
*/
protected $exposed = [
'code' => 'ids.geonames',
'fipsCode' => 'ids.fips',
'isoCode' => 'ids.iso_3166_2',
'geonamesCode' => 'ids.geonames',
'postCodes' => 'postcodes',
'name'
];
/**
* @return Collections\MemberCollection
*/
public function getCities()
{
return $this->getMembers();
}
}
| <?php
namespace MenaraSolutions\Geographer;
/**
* Class State
* @package MenaraSolutions\FluentGeonames
*/
class State extends Divisible
{
/**
* @var string
*/
protected $memberClass = City::class;
/**
* @var string
*/
protected static $parentClass = Country::class;
/**
* @var string
*/
protected $standard = 'geonames';
/**
* @var array
*/
protected $exposed = [
'code' => 'ids.geonames',
'fipsCode' => 'ids.fips',
'isoCode' => 'ids.iso_3166_2',
'geonamesCode' => 'ids.geonames',
'zipRanges' => 'zip_ranges',
'name'
];
/**
* @return Collections\MemberCollection
*/
public function getCities()
{
return $this->getMembers();
}
/**
* @return array
*/
public function getZipRanges()
{
$ranges = $this->meta['zip_ranges'];
if ($zip_ranges === null) {
return [];
}
return $ranges;
}
}
|
JENA-865: Include prefixes in example query | /** Standalone configuration for qonsole on index page */
define( [], function() {
return {
prefixes: {
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"owl": "http://www.w3.org/2002/07/owl#",
"xsd": "http://www.w3.org/2001/XMLSchema#"
},
queries: [
{ "name": "Selection of triples",
"query": "SELECT ?subject ?predicate ?object\nWHERE {\n" +
" ?subject ?predicate ?object\n}\n" +
"LIMIT 25"
},
{ "name": "Selection of classes",
"query": "SELECT DISTINCT ?class ?label ?description\nWHERE {\n" +
" ?class a owl:Class.\n" +
" OPTIONAL { ?class rdfs:label ?label}\n" +
" OPTIONAL { ?class rdfs:comment ?description}\n}\n" +
"LIMIT 25",
"prefixes": ["owl", "rdfs"]
}
]
};
} );
| /** Standalone configuration for qonsole on index page */
define( [], function() {
return {
prefixes: {
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"owl": "http://www.w3.org/2002/07/owl#",
"xsd": "http://www.w3.org/2001/XMLSchema#"
},
queries: [
{ "name": "Selection of triples",
"query": "SELECT ?subject ?predicate ?object\nwhere {\n" +
" ?subject ?predicate ?object\n}\n" +
"LIMIT 25"
},
{ "name": "Selection of classes",
"query": "SELECT distinct ?class ?label ?description\nwhere {\n" +
" ?class a owl:Class.\n" +
" OPTIONAL { ?class rdfs:label ?label}\n" +
" OPTIONAL { ?class rdfs:comment ?description}\n}\n" +
"LIMIT 25"
}
]
};
} ); |
Revert "GCW-1826 Disable off canvas scroll" | import Ember from 'ember';
export default Ember.Component.extend({
foundation: null,
currentClassName: Ember.computed("className", function(){
return this.get("className") ? `.${this.get('className')}` : document;
}),
didInsertElement() {
var className = this.get("currentClassName");
var _this = this;
this._super();
Ember.run.debounce(this, function(){
var clientHeight = $( window ).height();
$('.inner-wrap').css('min-height', clientHeight);
}, 1000);
Ember.run.scheduleOnce('afterRender', this, function(){
var initFoundation = Ember.$(className).foundation({
offcanvas: { close_on_click: true }
});
_this.set("foundation", initFoundation);
});
}
// TODO: Breaks sometime on menu-bar
// willDestroyElement() {
// this.get("foundation").foundation("destroy");
// }
});
| import Ember from 'ember';
export default Ember.Component.extend({
foundation: null,
currentClassName: Ember.computed("className", function(){
return this.get("className") ? `.${this.get('className')}` : document;
}),
click() {
if($('.off-canvas-wrap.move-right')[0]) {
$('html').css('overflow', 'auto');
} else {
$('html').css('overflow', 'hidden');
}
},
didInsertElement() {
var className = this.get("currentClassName");
var _this = this;
this._super();
Ember.run.debounce(this, function(){
var clientHeight = $( window ).height();
$('.inner-wrap').css('min-height', clientHeight);
}, 1000);
Ember.run.scheduleOnce('afterRender', this, function(){
var initFoundation = Ember.$(className).foundation({
offcanvas: { close_on_click: true }
});
_this.set("foundation", initFoundation);
});
}
// TODO: Breaks sometime on menu-bar
// willDestroyElement() {
// this.get("foundation").foundation("destroy");
// }
});
|
Include request and nonce test | <?php
/**
* Plugin Name: Example Success
* Plugin URI:
* Description: An example with wordpress-validator
* Version: 1.0.0
* Author: labodudev
* Author URI: http://labodudev.fr
* Requires at least: 4.1
* Tested up to: 4.4
*/
if ( !defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
include_once( 'test/nonce.test.php');
include_once( 'test/request.test.php');
add_action( 'wp_ajax_add_github', 'ajax_add_github' );
function ajax_add_github() {
// Check nonce
$_wpnonce = sanitize_key( $_POST['_wpnonce'] );
if ( wp_verify_nonce( $_wpnonce, 'ajax_add_github' ) )
wp_send_json_error();
// Securize email
$email = sanitize_email( $_POST['email'] );
wp_send_json_success( array( 'All data is securized!' ) );
}
?>
| <?php
/**
* Plugin Name: Example Success
* Plugin URI:
* Description: An example with wordpress-validator
* Version: 1.0.0
* Author: labodudev
* Author URI: http://labodudev.fr
* Requires at least: 4.1
* Tested up to: 4.4
*/
if ( !defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
add_action( 'wp_ajax_add_github', 'ajax_add_github' );
function ajax_add_github() {
// Check nonce
$_wpnonce = sanitize_key( $_POST['_wpnonce'] );
if ( wp_verify_nonce( $_wpnonce, 'ajax_add_github' ) )
wp_send_json_error();
// Securize email
$email = sanitize_email( $_POST['email'] );
wp_send_json_success( array( 'All data is securized!' ) );
}
?>
|
Fix spoofed data parser init | package protocolsupport.protocol.utils.spoofedata;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;
public class SpoofedDataParser {
private static final List<Function<String, SpoofedData>> parsers = new ArrayList<>();
static {
if (isPaperHandshakeEvent()) {
parsers.add(new PaperSpoofedDataParser());
}
parsers.add(new BungeeCordSpoofedDataParser());
}
public static SpoofedData tryParse(String data) {
for (Function<String, SpoofedData> parser : parsers) {
try {
SpoofedData result = parser.apply(data);
if (result != null) {
return result;
}
} catch (Exception e) {
}
}
return null;
}
private static boolean isPaperHandshakeEvent() {
try {
Class.forName(PlayerHandshakeEvent.class.getName());
return true;
} catch (Throwable e) {
return false;
}
}
}
| package protocolsupport.protocol.utils.spoofedata;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;
public class SpoofedDataParser {
private static final List<Function<String, SpoofedData>> parsers = new ArrayList<>();
static {
if (isPaperHandshakeEvent()) {
parsers.add(new PaperSpoofedDataParser());
}
parsers.add(new BungeeCordSpoofedDataParser());
}
public static SpoofedData tryParse(String data) {
for (Function<String, SpoofedData> parser : parsers) {
try {
SpoofedData result = parser.apply(data);
if (result != null) {
return result;
}
} catch (Exception e) {
}
}
return null;
}
private static boolean isPaperHandshakeEvent() {
try {
Class.forName(PlayerHandshakeEvent.class.getName());
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
|
Remove integration tests that throws lots of false positives.
Signed-off-by: Xabier Larrakoetxea <30fb0ea44f2104eb1a81e793d922a064c3916c2f@gmail.com> | // +build integration
package memory
import (
"context"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// TODO: Research how to integrate this test correctly so if doesn't fail the 50% of the times.
func _TestMemoryAllocationAttack(t *testing.T) {
assert := assert.New(t)
var size uint64 = 200 * MiB
ma, err := NewMemAllocation(size)
assert.NoError(err, "Creation of memory allocator shouldn't error")
// Get current memory
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
startMem := mem.Alloc
// Allocate memory and test if increased.
ma.Apply(context.TODO())
time.Sleep(1 * time.Millisecond)
runtime.ReadMemStats(&mem)
endMem := mem.Alloc
// Let 10% margin delta from the wanted size
assert.InDelta((endMem - startMem), size, float64(size)*0.35, "current memory allocation should be wanted allocation (35% deviation)")
// Free memory and test if released.
ma.Revert()
time.Sleep(1 * time.Millisecond)
runtime.ReadMemStats(&mem)
// Let 10% margin delta from the wanted size
assert.InDelta(startMem, mem.Alloc, float64(size)*0.35, "current memory and initial memory should be equal (35% deviation)")
}
| // +build integration
package memory
import (
"context"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestMemoryAllocationAttack(t *testing.T) {
assert := assert.New(t)
var size uint64 = 200 * MiB
ma, err := NewMemAllocation(size)
assert.NoError(err, "Creation of memory allocator shouldn't error")
// Get current memory
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
startMem := mem.Alloc
// Allocate memory and test if increased.
ma.Apply(context.TODO())
time.Sleep(1 * time.Millisecond)
runtime.ReadMemStats(&mem)
endMem := mem.Alloc
// Let 10% margin delta from the wanted size
assert.InDelta((endMem - startMem), size, float64(size)*0.35, "current memory allocation should be wanted allocation (35% deviation)")
// Free memory and test if released.
ma.Revert()
time.Sleep(1 * time.Millisecond)
runtime.ReadMemStats(&mem)
// Let 10% margin delta from the wanted size
assert.InDelta(startMem, mem.Alloc, float64(size)*0.35, "current memory and initial memory should be equal (35% deviation)")
}
|
Define Buffer globally if buffer built-in module installed. | var map = require("./map.json");
var meteorAliases = {};
Object.keys(map).forEach(function (id) {
if (typeof map[id] === "string") {
var aliasParts = module.id.split("/");
aliasParts.pop();
aliasParts.push("node_modules", map[id]);
exports[id] = meteorAliases[id + ".js"] =
aliasParts.join("/");
} else {
exports[id] = map[id];
meteorAliases[id + ".js"] = function(){};
}
});
if (typeof meteorInstall === "function") {
meteorInstall({
// Install the aliases into a node_modules directory one level up from
// the root directory, so that they do not clutter the namespace
// available to apps and packages.
"..": {
node_modules: meteorAliases
}
});
}
// If Buffer is not defined globally, but the "buffer" built-in stub is
// installed and can be imported, use it to define global.Buffer so that
// modules like core-util-is/lib/util.js can refer to Buffer without
// crashing application startup.
if (typeof global.Buffer !== "function") {
try {
// Use (0, require)(...) to avoid registering a dependency on the
// "buffer" stub, in case it is not otherwise bundled.
global.Buffer = (0, require)("buffer");
} catch (ok) {
// Failure to import "buffer" is fine as long as the Buffer global
// variable is not used.
}
}
| var map = require("./map.json");
var meteorAliases = {};
Object.keys(map).forEach(function (id) {
if (typeof map[id] === "string") {
var aliasParts = module.id.split("/");
aliasParts.pop();
aliasParts.push("node_modules", map[id]);
exports[id] = meteorAliases[id + ".js"] =
aliasParts.join("/");
} else {
exports[id] = map[id];
meteorAliases[id + ".js"] = function(){};
}
});
if (typeof meteorInstall === "function") {
meteorInstall({
// Install the aliases into a node_modules directory one level up from
// the root directory, so that they do not clutter the namespace
// available to apps and packages.
"..": {
node_modules: meteorAliases
}
});
}
|
Allow opening projects with no config file | import fs from "fs-extra"
import path from "path"
import _ from "underscore"
export default class ProjectStore {
static displayName = "ProjectStore"
constructor() {
this.state = {
rootPath: "",
contentPath: "",
mediaPath: "",
shortcuts: {}
}
const ProjectActions = this.alt.actions.ProjectActions
this.bindListeners({
setRoot: ProjectActions.OPEN
})
}
setRoot(rootPath) {
this.setState({
rootPath : rootPath,
contentPath : rootPath,
mediaPath : rootPath,
shortcuts : {}
})
this.loadConfig()
}
loadConfig() {
let configFile = path.join(this.state.rootPath, "downquark_config.json")
if (!fs.existsSync(configFile)) return
let config = fs.readJSONSync(configFile, { throws: false })
if (config) {
this.setState({
contentPath: path.join(this.state.rootPath, config.contentPath || ""),
mediaPath: path.join(this.state.rootPath, config.mediaPath || ""),
shortcuts: _.mapObject(config.shortcuts || {}, (p, alias) => {
return path.join(this.state.rootPath, p)
})
})
}
}
}
| import fs from "fs-extra"
import path from "path"
import _ from "underscore"
export default class ProjectStore {
static displayName = "ProjectStore"
constructor() {
this.state = {
rootPath: "",
contentPath: "",
mediaPath: "",
shortcuts: {}
}
const ProjectActions = this.alt.actions.ProjectActions
this.bindListeners({
setRoot: ProjectActions.OPEN
})
}
setRoot(rootPath) {
this.state.rootPath = rootPath
this.state.contentPath = rootPath
this.state.mediaPath = rootPath
this.loadConfig()
}
loadConfig() {
let configFile = path.join(this.state.rootPath, "downquark_config.json")
let config = fs.readJSONSync(configFile, { throws: false })
if (config) {
this.setState({
contentPath: path.join(this.state.rootPath, config.contentPath || ""),
mediaPath: path.join(this.state.rootPath, config.mediaPath || ""),
shortcuts: _.mapObject(config.shortcuts || {}, (p, alias) => {
return path.join(this.state.rootPath, p)
})
})
}
}
}
|
Move test to test src | package org.jboss.loom.migrators._ext;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.jboss.loom.utils.ClassUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class to prepare external migrators test environment (copies files etc.).
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class ExternalMigratorsTestEnv {
private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class );
protected static File workDir;
@BeforeClass
public static void copyTestExtMigratorFiles() throws IOException {
workDir = new File("target/extMigrators/");
FileUtils.forceMkdir( workDir );
ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestMigrator.mig.xml", workDir );
ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestJaxbBean.groovy", workDir );
}
@AfterClass
public static void deleteTestExtMigratorFiles() throws IOException {
FileUtils.forceDelete( workDir );
}
}// class
| package org.jboss.loom.migrators._ext;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.jboss.loom.utils.ClassUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class to prepare external migrators test environment (copies files etc.).
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class ExternalMigratorsTestEnv {
private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class );
protected static File workDir;
@BeforeClass
public static void copyTestExtMigratorFiles() throws IOException {
workDir = new File("target/extMigrators/");
FileUtils.forceMkdir( workDir );
ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestMigrator.mig.xml", workDir );
ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestJaxbBean.groovy", workDir );
}
@AfterClass
public static void deleteTestExtMigratorFiles() throws IOException {
FileUtils.forceDelete( workDir );
}
}// class
|
Fix faulty URL reference in the package metadata. | from setuptools import setup, find_packages
setup(name='addressable',
description='Use lists like you would dictionaries.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='stijn@debrouwere.org',
url='https://github.com/debrouwere/python-addressable/',
download_url='http://www.github.com/debrouwere/python-addressable/tarball/master',
version='1.1.1',
license='ISC',
packages=find_packages(),
keywords='utility',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
],
) | from setuptools import setup, find_packages
setup(name='addressable',
description='Use lists like you would dictionaries.',
long_description=open('README.rst').read(),
author='Stijn Debrouwere',
author_email='stijn@stdout.be',
url='http://stdbrouw.github.com/python-addressable/',
download_url='http://www.github.com/stdbrouw/python-addressable/tarball/master',
version='1.1.0',
license='ISC',
packages=find_packages(),
keywords='utility',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
],
) |
Remove all deprecated lists, not just 'yunohost' | from moulinette.utils.log import getActionLogger
from yunohost.app import app_fetchlist, app_removelist, _read_appslist_list
from yunohost.tools import Migration
logger = getActionLogger('yunohost.migration')
class MyMigration(Migration):
"Migrate from official.json to apps.json"
def migrate(self):
# Remove all the deprecated lists
lists_to_remove = [
"https://app.yunohost.org/official.json",
"https://app.yunohost.org/community.json",
"https://labriqueinter.net/apps/labriqueinternet.json"
]
appslists = _read_appslist_list()
for appslist, infos in appslists.items():
if infos["url"] in lists_to_remove:
app_removelist(name=appslist)
# Replace by apps.json list
app_fetchlist(name="yunohost",
url="https://app.yunohost.org/apps.json")
def backward(self):
# Remove apps.json list
app_removelist(name="yunohost")
# Replace by official.json list
app_fetchlist(name="yunohost",
url="https://app.yunohost.org/official.json")
| from moulinette.utils.log import getActionLogger
from yunohost.app import app_fetchlist, app_removelist
from yunohost.tools import Migration
logger = getActionLogger('yunohost.migration')
class MyMigration(Migration):
"Migrate from official.json to apps.json"
def migrate(self):
# Remove official.json list
app_removelist(name="yunohost")
# Replace by apps.json list
app_fetchlist(name="yunohost",
url="https://app.yunohost.org/apps.json")
def backward(self):
# Remove apps.json list
app_removelist(name="yunohost")
# Replace by official.json list
app_fetchlist(name="yunohost",
url="https://app.yunohost.org/official.json")
|
Remove oauth from api routing for testing | var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var sockets = require('./routes/sockets.js');
var auth = require('./auth/auth.js');
require('./db/index.js')(launchServer);
function launchServer() {
var app = express();
// ZACH: have a routes file
app.use(session({
secret: 'victoriousresistance',
resave: true,
saveUninitialized: false,
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
//router and sockets
require('./routes/webRoutes.js')(app, express);
app.use('/api',
// auth.checkAuth,
require('./routes/apiRoutes.js'));
// ZACH: sockets in a different file
var server = require('http').Server(app);
sockets(server);
//twilio
require('./routes/twilio.js')(app);
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log('iDioma listening on port: ' + port);
});
}
| var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var sockets = require('./routes/sockets.js');
var auth = require('./auth/auth.js');
require('./db/index.js')(launchServer);
function launchServer() {
var app = express();
// ZACH: have a routes file
app.use(session({
secret: 'victoriousresistance',
resave: true,
saveUninitialized: false,
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
//router and sockets
require('./routes/webRoutes.js')(app, express);
app.use('/api', auth.checkAuth, require('./routes/apiRoutes.js'));
// ZACH: sockets in a different file
var server = require('http').Server(app);
sockets(server);
//twilio
require('./routes/twilio.js')(app);
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log('iDioma listening on port: ' + port);
});
}
|
Make code for options.escape cleaner | /*!
* word-wrap <https://github.com/jonschlinkert/word-wrap>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*
* Adapted from http://james.padolsey.com/javascript/wordwrap-for-javascript/
* @attribution
*/
module.exports = function(str, options) {
options = options || {};
if (str == null) {
return str;
}
var width = options.width || 50;
var indent = (typeof options.indent === 'string')
? options.indent
: ' ';
var newline = options.newline || '\n' + indent;
function identity(str) {
return str;
};
var escape = typeof options.escape === 'function'
? options.escape
: identity;
var re = new RegExp('.{1,' + width + '}(\\s+|$)|\\S+?(\\s+|$)', 'g');
if (options.cut) {
re = new RegExp('.{1,' + width + '}', 'g');
}
var lines = str.match(re) || [];
var res = indent + lines.map(escape).join(newline);
if (options.trim === true) {
res = res.replace(/[ \t]*$/gm, '');
}
return res;
};
| /*!
* word-wrap <https://github.com/jonschlinkert/word-wrap>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*
* Adapted from http://james.padolsey.com/javascript/wordwrap-for-javascript/
* @attribution
*/
module.exports = function(str, options) {
options = options || {};
if (str == null) {
return str;
}
var width = options.width || 50;
var indent = (typeof options.indent === 'string')
? options.indent
: ' ';
var newline = options.newline || '\n' + indent;
var escape = options.escape || function(str){return str;};
var re = new RegExp('.{1,' + width + '}(\\s+|$)|\\S+?(\\s+|$)', 'g');
if (options.cut) {
re = new RegExp('.{1,' + width + '}', 'g');
}
var lines = str.match(re) || [];
var res = indent + lines.map(function(str){return escape(str)}).join(newline);
if (options.trim === true) {
res = res.replace(/[ \t]*$/gm, '');
}
return res;
};
|
Change the format into json because Swagger UI requires strict JSON | package org.wildfly.swarm.examples.jaxrs.swagger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import io.swagger.annotations.*;
import javax.ws.rs.core.MediaType;
import org.joda.time.DateTime;
@Path("/time")
@Api(value = "/time", description = "Get the time", tags = "time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {
@GET
@Path("/now")
@ApiOperation(value = "Get the current time",
notes = "Returns the time as a string",
response = String.class
)
@Produces(MediaType.APPLICATION_JSON)
public String get() {
return String.format("{\"value\" : \"The time is %s\"}", new DateTime());
}
}
| package org.wildfly.swarm.examples.jaxrs.swagger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import io.swagger.annotations.*;
import javax.ws.rs.core.MediaType;
import org.joda.time.DateTime;
@Path("/time")
@Api(value = "/time", description = "Get the time", tags = "time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {
@GET
@Path("/now")
@ApiOperation(value = "Get the current time",
notes = "Returns the time as a string",
response = String.class
)
@Produces(MediaType.APPLICATION_JSON)
public String get() {
return "The time is " + new DateTime();
}
}
|
Update fjord l10n_completion file location | import os
def truthy(item):
return item.lower().startswith('t')
DEBUG = truthy(os.environ.get('DEBUG', 'True'))
PROJECTS = {
'SUMO': {
'name': 'SUMO',
'url': 'https://support.mozilla.org/',
'postatus_url': 'https://support.mozilla.org/media/postatus.txt',
'verbatim_url': 'https://localize.mozilla.org/projects/sumo/',
'verbatim_locale_url': 'https://localize.mozilla.org/%s/sumo/',
'l10n_completion_url': 'https://support.mozilla.org/media/uploads/l10n_history.json',
},
'Input': {
'name': 'Input',
'url': 'https://input.mozilla.org/',
'postatus_url': 'https://input.mozilla.org/media/postatus.txt',
'verbatim_url': 'https://localize.mozilla.org/projects/input/',
'verbatim_locale_url': 'https://localize.mozilla.org/%s/input/',
'l10n_completion_url': 'https://people.mozilla.org/~wkahngreene/l10n/fjord_completion.json',
},
}
| import os
def truthy(item):
return item.lower().startswith('t')
DEBUG = truthy(os.environ.get('DEBUG', 'True'))
PROJECTS = {
'SUMO': {
'name': 'SUMO',
'url': 'https://support.mozilla.org/',
'postatus_url': 'https://support.mozilla.org/media/postatus.txt',
'verbatim_url': 'https://localize.mozilla.org/projects/sumo/',
'verbatim_locale_url': 'https://localize.mozilla.org/%s/sumo/',
'l10n_completion_url': 'https://support.mozilla.org/media/uploads/l10n_history.json',
},
'Input': {
'name': 'Input',
'url': 'https://input.mozilla.org/',
'postatus_url': 'https://input.mozilla.org/media/postatus.txt',
'verbatim_url': 'https://localize.mozilla.org/projects/input/',
'verbatim_locale_url': 'https://localize.mozilla.org/%s/input/',
'l10n_completion_url': 'https://input.mozilla.org/static/l10n_completion.json',
},
}
|
Enable canvas rendering by default (SVG is broken for now after this commit!) | import qs from 'qs';
// TODO: if we're in a test mode it'd be nice not to have to set document.location.search... pull
// from global or something instead?
const qsObj = qs.parse(document.location.search.slice(1)); // lop off leading question mark
const types = {
bool(value, name) {
// this is a bool
if (value === '') {
return true;
} else if (value === '0' || value === 'false') {
return false;
} else if (value === '1' || value === 'true') {
return true;
} else {
throw new Error(`could not parse boolean flag ${name}`);
}
}
};
function getFlag(name, type, defaultValue) {
if (qsObj[name] !== undefined) {
return type(qsObj[name], name);
} else {
return defaultValue;
}
}
export const ENABLE_YT_PLAYBACK = getFlag('enableyt', types.bool, false);
export const ENABLE_CANVAS_PLAYBACK = getFlag('canvas', types.bool, true);
// TODO: remove once SVG Chart is removed
export const ENABLE_3D_ACCEL = getFlag('enable3daccel', types.bool, false);
export const MUTE = getFlag('mute', types.bool, false);
export const SHOW_FPS = getFlag('fps', types.bool, false);
| import qs from 'qs';
// TODO: if we're in a test mode it'd be nice not to have to set document.location.search... pull
// from global or something instead?
const qsObj = qs.parse(document.location.search.slice(1)); // lop off leading question mark
const types = {
bool(value, name) {
// this is a bool
if (value === '') {
return true;
} else if (value === '0' || value === 'false') {
return false;
} else if (value === '1' || value === 'true') {
return true;
} else {
throw new Error(`could not parse boolean flag ${name}`);
}
}
};
function getFlag(name, type, defaultValue) {
if (qsObj[name] !== undefined) {
return type(qsObj[name], name);
} else {
return defaultValue;
}
}
export const ENABLE_YT_PLAYBACK = getFlag('enableyt', types.bool, false);
export const ENABLE_CANVAS_PLAYBACK = getFlag('canvas', types.bool, false);
// TODO: remove once SVG Chart is removed
export const ENABLE_3D_ACCEL = getFlag('enable3daccel', types.bool, false);
export const MUTE = getFlag('mute', types.bool, false);
export const SHOW_FPS = getFlag('fps', types.bool, false);
|
Change @include settings so that the script is not run on all pages | // ==UserScript==
// @name Turn off age gate on Amazon.co.jp
// @namespace curipha
// @description Click "I'm over 18" automatically
// @include https://www.amazon.co.jp/gp/product/*
// @include https://www.amazon.co.jp/gp/browse.html*
// @include https://www.amazon.co.jp/dp/*
// @include https://www.amazon.co.jp/*/dp/*
// @exclude https://www.amazon.co.jp/ap/*
// @exclude https://www.amazon.co.jp/mn/*
// @exclude https://www.amazon.co.jp/clouddrive*
// @version 0.5.2
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
if (document.title === '警告:アダルトコンテンツ') {
const a = document.body.querySelector('center a[href*="black-curtain-redirect.html"]');
if (a) {
location.href = a.href;
}
}
})();
| // ==UserScript==
// @name Turn off age gate on Amazon.co.jp
// @namespace curipha
// @description Click "I'm over 18" automatically
// @include https://www.amazon.co.jp/gp/product/*
// @include https://www.amazon.co.jp/dp/*
// @include https://www.amazon.co.jp/*/dp/*
// @exclude https://www.amazon.co.jp/ap/*
// @exclude https://www.amazon.co.jp/mn/*
// @exclude https://www.amazon.co.jp/clouddrive*
// @version 0.5.2
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
if (document.title === '警告:アダルトコンテンツ') {
const a = document.body.querySelector('center a[href*="black-curtain-redirect.html"]');
if (a) {
location.href = a.href;
}
}
})();
|
Validate resource schema are valid on startup | 'use strict'
const schemaValidator = module.exports = { }
schemaValidator.validate = function (resources) {
Object.keys(resources).forEach(resource => {
Object.keys(resources[resource].attributes).forEach(attribute => {
const joiSchema = resources[resource].attributes[attribute]
if (!joiSchema._settings) return
const types = joiSchema._settings.__one || joiSchema._settings.__many
types.forEach(type => {
if (!resources[type]) {
throw new Error(`'${resource}'.'${attribute}' is defined to hold a relation with '${type}', but '${type}' is not a valid resource name!`)
}
})
const foreignRelation = joiSchema._settings.__as
if (!foreignRelation) return
const backReference = resources[types[0]].attributes[foreignRelation]
if (!backReference) {
throw new Error(`'${resource}'.'${attribute}' is defined as being a foreign relation to the primary '${types[0]}'.'${foreignRelation}', but that primary relationship does not exist!`)
}
})
})
}
| 'use strict'
const schemaValidator = module.exports = { }
schemaValidator.validate = function (resources) {
Object.keys(resources).forEach(resource => {
Object.keys(resources[resource].attributes).forEach(attribute => {
let joiSchema = resources[resource].attributes[attribute]
if (!joiSchema._settings) return
let types = joiSchema._settings.__one || joiSchema._settings.__many
types.forEach(type => {
if (!resources[type]) {
throw new Error(`'${resource}'.'${attribute}' is defined to hold a relation with '${type}', but '${type}' is not a valid resource name!`)
}
})
let foreignRelation = joiSchema._settings.__as
if (!foreignRelation) return
let backReference = resources[types[0]].attributes[foreignRelation]
if (!backReference) {
throw new Error(`'${resource}'.'${attribute}' is defined as being a foreign relation to the primary '${types[0]}'.'${foreignRelation}', but that primary relationship does not exist!`)
}
})
})
}
|
[Φ] Add Tensor to standard imports | # pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import Tensor, DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
| # pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
Change interpolation sentinels to prevent collissions with pillar data | #
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–14 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
import os, sys
from version import RECLASS_NAME
# defaults for the command-line options
OPT_STORAGE_TYPE = 'yaml_fs'
OPT_INVENTORY_BASE_URI = os.path.join('/etc', RECLASS_NAME)
OPT_NODES_URI = 'nodes'
OPT_CLASSES_URI = 'classes'
OPT_PRETTY_PRINT = True
OPT_OUTPUT = 'yaml'
CONFIG_FILE_SEARCH_PATH = [os.getcwd(),
os.path.expanduser('~'),
OPT_INVENTORY_BASE_URI,
os.path.dirname(sys.argv[0])
]
CONFIG_FILE_NAME = RECLASS_NAME + '-config.yml'
PARAMETER_INTERPOLATION_SENTINELS = ('{{', '}}')
PARAMETER_INTERPOLATION_DELIMITER = ':'
| #
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–14 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
import os, sys
from version import RECLASS_NAME
# defaults for the command-line options
OPT_STORAGE_TYPE = 'yaml_fs'
OPT_INVENTORY_BASE_URI = os.path.join('/etc', RECLASS_NAME)
OPT_NODES_URI = 'nodes'
OPT_CLASSES_URI = 'classes'
OPT_PRETTY_PRINT = True
OPT_OUTPUT = 'yaml'
CONFIG_FILE_SEARCH_PATH = [os.getcwd(),
os.path.expanduser('~'),
OPT_INVENTORY_BASE_URI,
os.path.dirname(sys.argv[0])
]
CONFIG_FILE_NAME = RECLASS_NAME + '-config.yml'
PARAMETER_INTERPOLATION_SENTINELS = ('${', '}')
PARAMETER_INTERPOLATION_DELIMITER = ':'
|
Fix sqlite db filename generation | <?php
namespace Phive\Tests\Queue\Db\Pdo;
class SqliteQueueTest extends PdoQueueTest
{
public static function createHandler()
{
// Generate a new db file on every method call to prevent
// a "Database schema has changed" error which occurs if any
// other process (e.g. worker) is still using the old db file.
// We also can't use the shared cache mode due to
// @link http://stackoverflow.com/questions/9150319/enable-shared-pager-cache-in-sqlite-using-php-pdo
return new PdoHandler(array(
'dsn' => sprintf('sqlite:%s/%s.sq3', sys_get_temp_dir(), uniqid('phive_tests_')),
'username' => null,
'password' => null,
'table_name' => 'queue',
));
}
}
| <?php
namespace Phive\Tests\Queue\Db\Pdo;
class SqliteQueueTest extends PdoQueueTest
{
public static function createHandler()
{
// Generate a new db file on every method call to prevent
// a "Database schema has changed" error which occurs if any
// other process (e.g. worker) is still using the old db file.
// We also can't use the shared cache mode due to
// @link http://stackoverflow.com/questions/9150319/enable-shared-pager-cache-in-sqlite-using-php-pdo
return new PdoHandler(array(
'dsn' => 'sqlite:'.tempnam(sys_get_temp_dir(), 'q_').'.sq3',
'username' => null,
'password' => null,
'table_name' => 'queue',
));
}
}
|
Add proptype validation to StatusCounter component | import React from 'react';
import PropTypes from 'prop-types';
import './status-counter.scss';
const StatusCounter = props => (
<div className="status-counter">
<ul>
<li>
<span className="count">{props.postTotals.pending_count}</span>
<span className="status">Pending</span>
<div>
<a className="button -secondary" href={`/campaigns/${props.campaign.id}/inbox`}>Review</a>
</div>
</li>
{/* @TODO - add back in when we deal with pagination on the single campaign view
<li>
<span className="status">Accepted</span>
<span className="count">{props.postTotals.accepted_count}</span>
</li>
<li>
<span className="status">Rejected</span>
<span className="count">{props.postTotals.rejected_count}</span>
</li>
*/}
</ul>
</div>
);
StatusCounter.propTypes = {
postTotals: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
campaign: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};
| import React from 'react';
import './status-counter.scss';
export default (props) => (
<div className="status-counter">
<ul>
<li>
<span className="count">{props.postTotals.pending_count}</span>
<span className="status">Pending</span>
<div>
<a className="button -secondary" href={`/campaigns/${props.campaign.id}/inbox`}>Review</a>
</div>
</li>
{/* @TODO - add back in when we deal with pagination on the single campaign view
<li>
<span className="status">Accepted</span>
<span className="count">{props.postTotals.accepted_count}</span>
</li>
<li>
<span className="status">Rejected</span>
<span className="count">{props.postTotals.rejected_count}</span>
</li>*/}
</ul>
</div>
);
|
Use grunt log utility for errors logging | /**
* BBB `module` generator for Yeoman
* Initialize a single module file and related test.
*/
"use strict";
var util = require("util");
var _ = require("lodash");
var grunt = require("grunt");
var BBBGenerator = require("../base/bbb-generator");
/**
* Module exports
*/
module.exports = Generator;
Generator._name = "bbb:module";
/**
* BBB Generator constructor
* Extend Yeoman base generator
*/
function Generator(args, options, config) {
BBBGenerator.apply(this, arguments);
this.moduleName = args[0];
}
util.inherits(Generator, BBBGenerator);
/**
* Generate the module file
*/
Generator.prototype.module = function module() {
if (!this.bbb) {
grunt.log.error("You must init your project first");
return;
}
if (!this.moduleName) {
grunt.log.error("You must provide a name for your module");
return;
}
var output = this.normalizeJS(this.src.read("module.js"));
this.write("app/modules/" + this.moduleName + ".js", output);
};
/**
* Generate the module related base test
*/
Generator.prototype.moduleTest = function moduleTest() {
// TODO: Generate module test scaffhold
};
| /**
* BBB `module` generator for Yeoman
* Initialize a single module file and related test.
*/
"use strict";
var util = require("util");
var path = require("path");
var _ = require("lodash");
var BBBGenerator = require("../base/bbb-generator");
/**
* Module exports
*/
module.exports = Generator;
Generator._name = "bbb:module";
/**
* BBB Generator constructor
* Extend Yeoman base generator
*/
function Generator(args, options, config) {
BBBGenerator.apply(this, arguments);
this.moduleName = args[0];
}
util.inherits(Generator, BBBGenerator);
/**
* Generate the module file
*/
Generator.prototype.module = function module() {
if (!this.bbb) {
this.log.writeln("You must init your project first");
return;
}
if (!this.moduleName) {
this.log.writeln(">> You must provide a name for your module");
return;
}
var output = this.normalizeJS(this.src.read("module.js"));
this.write("app/modules/" + this.moduleName + ".js", output);
};
/**
* Generate the module related base test
*/
Generator.prototype.moduleTest = function moduleTest() {
// TODO: Generate module test scaffhold
};
|
Add test variant without parameters | /*
* Bach - Java Shell Builder
* Copyright (C) 2019 Christian Stein
*
* 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
*
* https://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 test.base;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
class SwallowSystemTests {
@Test
@SwallowSystem
void empty(SwallowSystem.Streams streams) {
assertTrue(streams.lines().isEmpty());
assertTrue(streams.errors().isEmpty());
}
@Test
@SwallowSystem
void normalAndErrorOutput() {
System.out.println("out");
System.err.println("err");
}
@Test
@SwallowSystem
void normalAndErrorOutput(SwallowSystem.Streams streams) {
System.out.println("out");
System.err.println("err");
assertLinesMatch(List.of("out"), streams.lines());
assertLinesMatch(List.of("err"), streams.errors());
}
}
| /*
* Bach - Java Shell Builder
* Copyright (C) 2019 Christian Stein
*
* 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
*
* https://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 test.base;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
class SwallowSystemTests {
@Test
@SwallowSystem
void empty(SwallowSystem.Streams streams) {
assertTrue(streams.lines().isEmpty());
assertTrue(streams.errors().isEmpty());
}
@Test
@SwallowSystem
void normalAndErrorOutput(SwallowSystem.Streams streams) {
System.out.println("out");
System.err.println("err");
assertLinesMatch(List.of("out"), streams.lines());
assertLinesMatch(List.of("err"), streams.errors());
}
}
|
Fix database migration script for UUID field in invoice item model. | import uuid
from django.db import migrations, models
import waldur_core.core.fields
def gen_uuid(apps, schema_editor):
InvoiceItem = apps.get_model('invoices', 'InvoiceItem')
for row in InvoiceItem.objects.all():
row.uuid = uuid.uuid4().hex
row.save(update_fields=['uuid'])
class Migration(migrations.Migration):
dependencies = [
('invoices', '0052_delete_servicedowntime'),
]
operations = [
migrations.AddField(
model_name='invoiceitem', name='uuid', field=models.UUIDField(null=True),
),
migrations.RunPython(gen_uuid, elidable=True),
migrations.AlterField(
model_name='invoiceitem',
name='uuid',
field=waldur_core.core.fields.UUIDField(),
),
]
| import uuid
from django.db import migrations
import waldur_core.core.fields
def gen_uuid(apps, schema_editor):
InvoiceItem = apps.get_model('invoices', 'InvoiceItem')
for row in InvoiceItem.objects.all():
row.uuid = uuid.uuid4().hex
row.save(update_fields=['uuid'])
class Migration(migrations.Migration):
dependencies = [
('invoices', '0052_delete_servicedowntime'),
]
operations = [
migrations.AddField(
model_name='invoiceitem',
name='uuid',
field=waldur_core.core.fields.UUIDField(null=True),
),
migrations.RunPython(gen_uuid, elidable=True),
migrations.AlterField(
model_name='invoiceitem',
name='uuid',
field=waldur_core.core.fields.UUIDField(),
),
]
|
Add new placeholders to Example.js | (function (env) {
"use strict";
env.ddg_spice_<: $lia_name :> = function(api_result){
// Validate the response (customize for your Spice)
if (api_result.error) {
return Spice.failed('<: $lia_name :>');
}
// Render the response
Spice.add({
id: "<: $lia_name :>",
// Customize these properties
name: "AnswerBar title",
data: api_result,
meta: {
sourceName: "Example.com",
sourceUrl: 'http://<: $ia_domain :>/details/' + api_result.name
},
templates: {
group: '<: $ia_group :>',
options: {
content: Spice.<: $lia_name :>.content,
moreAt: true
}
<: $ia_rel :>
});
};
}(this));
| (function (env) {
"use strict";
env.ddg_spice_<: $lia_name :> = function(api_result){
// Validate the response (customize for your Spice)
if (api_result.error) {
return Spice.failed('<: $lia_name :>');
}
// Render the response
Spice.add({
id: "<: $lia_name :>",
// Customize these properties
name: "AnswerBar title",
data: api_result,
meta: {
sourceName: "Example.com",
sourceUrl: 'http://example.com/url/to/details/' + api_result.name
},
templates: {
group: 'your-template-group',
options: {
content: Spice.<: $lia_name :>.content,
moreAt: true
}
}
});
};
}(this));
|
Add replication mode sys health information to Go API | package api
func (c *Sys) Health() (*HealthResponse, error) {
r := c.c.NewRequest("GET", "/v1/sys/health")
// If the code is 400 or above it will automatically turn into an error,
// but the sys/health API defaults to returning 5xx when not sealed or
// inited, so we force this code to be something else so we parse correctly
r.Params.Add("sealedcode", "299")
r.Params.Add("uninitcode", "299")
resp, err := c.c.RawRequest(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result HealthResponse
err = resp.DecodeJSON(&result)
return &result, err
}
type HealthResponse struct {
Initialized bool `json:"initialized"`
Sealed bool `json:"sealed"`
Standby bool `json:"standby"`
ReplicationPerfMode string `json:"replication_perf_mode"`
ReplicationDRMode string `json:"replication_dr_mode"`
ServerTimeUTC int64 `json:"server_time_utc"`
Version string `json:"version"`
ClusterName string `json:"cluster_name,omitempty"`
ClusterID string `json:"cluster_id,omitempty"`
}
| package api
func (c *Sys) Health() (*HealthResponse, error) {
r := c.c.NewRequest("GET", "/v1/sys/health")
// If the code is 400 or above it will automatically turn into an error,
// but the sys/health API defaults to returning 5xx when not sealed or
// inited, so we force this code to be something else so we parse correctly
r.Params.Add("sealedcode", "299")
r.Params.Add("uninitcode", "299")
resp, err := c.c.RawRequest(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result HealthResponse
err = resp.DecodeJSON(&result)
return &result, err
}
type HealthResponse struct {
Initialized bool `json:"initialized"`
Sealed bool `json:"sealed"`
Standby bool `json:"standby"`
ServerTimeUTC int64 `json:"server_time_utc"`
Version string `json:"version"`
ClusterName string `json:"cluster_name,omitempty"`
ClusterID string `json:"cluster_id,omitempty"`
}
|
Remove junk and add more logging | # -*- coding: utf-8 -*-
import sys
import logging
from website.app import setup_django
setup_django()
from website import mails
from osf.models import OSFUser
from addons.mendeley.models import UserSettings
import progressbar
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main(dry=True):
qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner').order_by('pk')
count = qs.count()
pbar = progressbar.ProgressBar(maxval=count).start()
logger.info('Sending email to {} users'.format(count))
for i, each in enumerate(qs):
user = each.owner
logger.info('Sending email to OSFUser {}'.format(user._id))
if not dry:
mails.send_mail(
mail=mails.MENDELEY_REAUTH,
to_addr=user.username,
can_change_preferences=False,
user=user
)
pbar.update(i + 1)
logger.info('Sent email to {} users'.format(count))
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
script_utils.add_file_logger(logger, __file__)
main(dry=dry)
| # -*- coding: utf-8 -*-
import sys
import logging
from website.app import setup_django
setup_django()
from website import mails
from osf.models import OSFUser
from addons.mendeley.models import UserSettings
import progressbar
from scripts import utils as script_utils
logger = logging.getLogger(__name__)
def main(dry=True):
user = OSFUser.load('qrgl2')
qs = UserSettings.objects.filter(owner__is_active=True).select_related('owner')
pbar = progressbar.ProgressBar(maxval=qs.count()).start()
for i, each in enumerate(qs):
user = each.owner
logger.info('Sending email to OSFUser {}'.format(user._id))
if not dry:
mails.send_mail(
mail=mails.MENDELEY_REAUTH,
to_addr=user.username,
can_change_preferences=False,
user=user
)
pbar.update(i + 1)
if __name__ == '__main__':
dry = '--dry' in sys.argv
if not dry:
script_utils.add_file_logger(logger, __file__)
main(dry=dry)
|
Change the help and assignments to match. | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from credentials.management.helpers import import_sshkeypair
class Command(BaseCommand):
help = "Import ssh keypair"
args = "[public key filename] [private key filename] [name]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if label already exists."),
)
def handle(self, *args, **options):
if len(args) != 3:
raise CommandError(
"must provide a public keyfile, private keyfile and label")
public_key, private_key, name = args
import_sshkeypair(
label, public_key, private_key,
update=options["update"], stdout=self.stdout)
transaction.commit_unless_managed()
| from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from credentials.management.helpers import import_sshkeypair
class Command(BaseCommand):
help = "Import ssh keypair"
args = "[public key filename] [private key filename] [name]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if label already exists."),
)
def handle(self, *args, **options):
if len(args) != 3:
raise CommandError(
"must provide a label, public keyfile and private keyfile")
label, public_key, private_key = args
import_sshkeypair(
label, public_key, private_key,
update=options["update"], stdout=self.stdout)
transaction.commit_unless_managed()
|
Fix saving icons input icon | <label class="col-sm-2 control-label">{{ $input['label'] }}</label>
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"><i id="icon_selector_view" style="font-size:18px" class="fa fa-{{ ($value)?$value:$input['options'][0] }}"></i></span>
<select name="{{ $name }}" class="form-control" id="icon_selector">
@foreach ($input['options'] as $icon)
<option value="{{ $icon }}" @if($value == $icon) selected @endif>{{ $icon }}</option>
@endforeach
</select>
</div>
</div>
@section('scripts')
@parent
<script>
$('#icon_selector').change(function(){
$('#icon_selector_view').attr('class', 'fa fa-'+$(this).val());
});
</script>
@endsection | <label class="col-sm-2 control-label">{{ $input['label'] }}</label>
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"><i id="icon_selector_view" style="font-size:18px" class="fa fa-{{ $input['options'][0] }}"></i></span>
<select name="{{ $name }}" class="form-control" id="icon_selector">
@foreach ($input['options'] as $icon)
<option value="{{ $icon }}" @if($value == $icon) selected @endif>{{ $icon }}</option>
@endforeach
</select>
</div>
</div>
@section('scripts')
@parent
<script>
$('#icon_selector').change(function(){
$('#icon_selector_view').attr('class', 'fa fa-'+$(this).val());
});
</script>
@endsection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.