text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Migrate "Jenkins API Token" config setting from masked to hidden
Related to "T6518-harbormaster-notify-jenkins-step" branch, but can't put it in there because "setHidden" method was added only to master recently (see ebebeb8f7cb7f1691fd65d3a5579efd26376afe4). | <?php
final class PhabricatorHarbormasterConfigOptions
extends PhabricatorApplicationConfigOptions {
public function getName() {
return pht('Harbormaster');
}
public function getDescription() {
return pht('Configure Harbormaster build engine.');
}
public function getFontIcon() {
return 'fa-ship';
}
public function getGroup() {
return 'apps';
}
public function getOptions() {
return array(
$this->newOption('jenkins.host', 'string', null)
->setDescription(pht('Jenkins installation hostname.')),
$this->newOption('jenkins.user-id', 'string', null)
->setDescription(pht('Username for accessing Jenkins.')),
$this->newOption('jenkins.api-token', 'string', null)
->setHidden(true)
->setDescription(pht('API token for accessing Jenkins.')),
);
}
}
| <?php
final class PhabricatorHarbormasterConfigOptions
extends PhabricatorApplicationConfigOptions {
public function getName() {
return pht('Harbormaster');
}
public function getDescription() {
return pht('Configure Harbormaster build engine.');
}
public function getFontIcon() {
return 'fa-ship';
}
public function getGroup() {
return 'apps';
}
public function getOptions() {
return array(
$this->newOption('jenkins.host', 'string', null)
->setDescription(pht('Jenkins installation hostname.')),
$this->newOption('jenkins.user-id', 'string', null)
->setDescription(pht('Username for accessing Jenkins.')),
$this->newOption('jenkins.api-token', 'string', null)
->setMasked(true)
->setDescription(pht('API token for accessing Jenkins.')),
);
}
}
|
Update instead of save when normalizing bug fields. | from django.contrib import admin
from django.utils.encoding import smart_text
from import_export.admin import ExportMixin
from remo.remozilla.models import Bug, Status
def encode_bugzilla_strings(modeladmin, request, queryset):
for obj in queryset:
kwargs = {}
fields = ['component', 'summary', 'whiteboard', 'status', 'resolution', 'first_comment']
for field in fields:
kwargs[field] = smart_text(getattr(obj, field))
Bug.objects.filter(pk=obj.id).update(**kwargs)
encode_bugzilla_strings.short_description = 'Encode bugzilla strings'
class BugAdmin(ExportMixin, admin.ModelAdmin):
"""Bug Admin."""
list_display = ('__unicode__', 'summary', 'status', 'resolution',
'bug_last_change_time',)
list_filter = ('status', 'resolution', 'council_vote_requested',)
search_fields = ('bug_id', 'summary', 'id',)
actions = [encode_bugzilla_strings]
admin.site.register(Bug, BugAdmin)
admin.site.register(Status)
| from django.contrib import admin
from django.utils.encoding import smart_text
from import_export.admin import ExportMixin
from remo.remozilla.models import Bug, Status
def encode_bugzilla_strings(modeladmin, request, queryset):
for obj in queryset:
fields = ['component', 'summary', 'whiteboard', 'status', 'resolution', 'first_comment']
for field in fields:
value = smart_text(getattr(obj, field))
setattr(obj, field, value)
obj.save()
encode_bugzilla_strings.short_description = 'Encode bugzilla strings'
class BugAdmin(ExportMixin, admin.ModelAdmin):
"""Bug Admin."""
list_display = ('__unicode__', 'summary', 'status', 'resolution',
'bug_last_change_time',)
list_filter = ('status', 'resolution', 'council_vote_requested',)
search_fields = ('bug_id', 'summary', 'id',)
actions = [encode_bugzilla_strings]
admin.site.register(Bug, BugAdmin)
admin.site.register(Status)
|
Use a metaclass instead of dirty dict()-mangling. | import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
def fn(self):
self.assertValidURLs(template)
return fn
for x in get_template_dirs():
for root, _, templates in os.walk(x):
for y in templates:
template = os.path.join(root, y)
attrs['test_%s' % slugify(template)] = generate(template)
return super(TestTemplatesMeta, cls).__new__(cls, name, bases, attrs)
class TestTemplates(TestCase):
__metaclass__ = TestTemplatesMeta
def assertValidURLs(self, template):
with open(template) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
template,
urls,
))
| import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
filename,
urls,
))
idx = 0
for x in get_template_dirs():
for root, _, filenames in os.walk(x):
for y in filenames:
def wrapper(self, filename=os.path.join(root, y)):
self.assertValidURLs(filename)
idx += 1
locals()['test_template_idx_%04d' % idx] = wrapper
|
Format how time from now is displayed | import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['arrival'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow('mm');
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
| import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['arrival'],
classNameBindings: ['isPast:arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow();
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 100%);
background-color: hsl(${hue}, 50%, 55%);
border-color: hsl(${hue}, 50%, 55%);`;
})
});
|
Add one more test for the Batch Extension. | <?php
namespace League\Plates\Extension;
class BatchTest extends \PHPUnit_Framework_TestCase
{
private $extension;
public function setUp()
{
$this->extension = new Batch;
$this->extension->engine = new \League\Plates\Engine();
$this->extension->template = new \League\Plates\Template($this->extension->engine);
}
public function testCanCreateExtension()
{
$this->assertInstanceOf('League\Plates\Extension\Batch', $this->extension);
}
public function testGetFunctionsReturnsAnArray()
{
$this->assertInternalType('array', $this->extension->getFunctions());
}
public function testGetFunctionsReturnsAtLeastOneRecord()
{
$this->assertTrue(count($this->extension->getFunctions()) > 0);
}
public function testRunBatch()
{
$this->assertTrue($this->extension->runBatch('Sweet ', 'trim') === 'Sweet');
$this->assertTrue($this->extension->runBatch('Jonathan', 'strtoupper|strtolower') === 'jonathan');
$this->assertTrue($this->extension->runBatch('Jonathan', 'e|strtolower') === 'jonathan');
}
public function testRunBatchException()
{
$this->setExpectedException('LogicException');
$this->assertTrue($this->extension->runBatch('Jonathan', 'somefunctionthatwillneverexist'));
}
}
| <?php
namespace League\Plates\Extension;
class BatchTest extends \PHPUnit_Framework_TestCase
{
private $extension;
public function setUp()
{
$this->extension = new Batch;
$this->extension->engine = new \League\Plates\Engine();
$this->extension->template = new \League\Plates\Template($this->extension->engine);
}
public function testCanCreateExtension()
{
$this->assertInstanceOf('League\Plates\Extension\Batch', $this->extension);
}
public function testGetFunctionsReturnsAnArray()
{
$this->assertInternalType('array', $this->extension->getFunctions());
}
public function testGetFunctionsReturnsAtLeastOneRecord()
{
$this->assertTrue(count($this->extension->getFunctions()) > 0);
}
public function testRunBatch()
{
$this->assertTrue($this->extension->runBatch('Sweet ', 'trim') === 'Sweet');
$this->assertTrue($this->extension->runBatch('Jonathan', 'strtoupper|strtolower') === 'jonathan');
$this->assertTrue($this->extension->runBatch('Jonathan', 'e|strtolower') === 'jonathan');
}
}
|
Switch doc to closure compiler templating | /**
* Takes a bounding box and returns a new bounding box with a size expanded or contracted
* by a factor of X.
*
* @module turf/size
* @category measurement
* @param {Array<number>} bbox a bounding box
* @param {Number} factor the ratio of the new bbox to the input bbox
* @return {Array<number>} the resized bbox
* @example
* var bbox = [0, 0, 10, 10]
*
* var resized = turf.size(bbox, 2);
*
* var features = {
* "type": "FeatureCollection",
* "features": [
* turf.bboxPolygon(bbox),
* turf.bboxPolygon(resized)
* ]
* };
*
* //=features
*/
module.exports = function(bbox, factor){
var currentXDistance = (bbox[2] - bbox[0]);
var currentYDistance = (bbox[3] - bbox[1]);
var newXDistance = currentXDistance * factor;
var newYDistance = currentYDistance * factor;
var xChange = newXDistance - currentXDistance;
var yChange = newYDistance - currentYDistance;
var lowX = bbox[0] - (xChange / 2);
var lowY = bbox[1] - (yChange / 2);
var highX = (xChange / 2) + bbox[2];
var highY = (yChange / 2) + bbox[3];
var sized = [lowX, lowY, highX, highY];
return sized;
}
| /**
* Takes a bounding box and returns a new bounding box with a size expanded or contracted
* by a factor of X.
*
* @module turf/size
* @category measurement
* @param {Array<number>} bbox a bounding box
* @param {number} factor the ratio of the new bbox to the input bbox
* @return {Array<number>} the resized bbox
* @example
* var bbox = [0, 0, 10, 10]
*
* var resized = turf.size(bbox, 2);
*
* var features = {
* "type": "FeatureCollection",
* "features": [
* turf.bboxPolygon(bbox),
* turf.bboxPolygon(resized)
* ]
* };
*
* //=features
*/
module.exports = function(bbox, factor){
var currentXDistance = (bbox[2] - bbox[0]);
var currentYDistance = (bbox[3] - bbox[1]);
var newXDistance = currentXDistance * factor;
var newYDistance = currentYDistance * factor;
var xChange = newXDistance - currentXDistance;
var yChange = newYDistance - currentYDistance;
var lowX = bbox[0] - (xChange / 2);
var lowY = bbox[1] - (yChange / 2);
var highX = (xChange / 2) + bbox[2];
var highY = (yChange / 2) + bbox[3];
var sized = [lowX, lowY, highX, highY];
return sized;
}
|
Add BareMiddleware to test helpers | import asyncio
import inspect
import sys
import rollbar
def run(coro):
if sys.version_info >= (3, 7):
return asyncio.run(coro)
assert inspect.iscoroutine(coro)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
asyncio.set_event_loop(None)
def async_receive(message):
async def receive():
return message
assert message['type'] == 'http.request'
return receive
class FailingTestASGIApp:
def __call__(self, scope, receive, send):
try:
run(self.app(scope, receive, send))
except Exception:
if scope['type'] == 'http':
rollbar.report_exc_info()
raise
async def app(self, scope, receive, send):
raise RuntimeError('Invoked only for testing')
class BareMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
await self.app(scope, receive, send)
| import asyncio
import inspect
import sys
import rollbar
def run(coro):
if sys.version_info >= (3, 7):
return asyncio.run(coro)
assert inspect.iscoroutine(coro)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
asyncio.set_event_loop(None)
def async_receive(message):
async def receive():
return message
assert message['type'] == 'http.request'
return receive
class FailingTestASGIApp:
def __call__(self, scope, receive, send):
try:
run(self.app(scope, receive, send))
except Exception:
if scope['type'] == 'http':
rollbar.report_exc_info()
raise
async def app(self, scope, receive, send):
raise RuntimeError('Invoked only for testing')
|
Allow opening a file by id and name | var GridStore = require('mongodb').GridStore;
/**
* @param filename: filename or ObjectId
*/
var SkinGridStore = exports.SkinGridStore = function(skinDb) {
this.skinDb = skinDb;
}
/**
* @param filename: filename or ObjectId
* callback(err, gridStoreObject)
*/
SkinGridStore.prototype.open = function(id, filename, mode, options, callback){
if(!callback){
callback = options;
options = undefined;
}
this.skinDb.open(function(err, db) {
new GridStore(db, id, filename, mode, options).open(callback);
});
}
/**
* @param filename: filename or ObjectId
*/
SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){
this.skinDb.open(function(err, db) {
GridStore.unlink(db, filename, callback);
});
}
SkinGridStore.prototype.exist = function(filename, rootCollection, callback){
this.skinDb.open(function(err, db) {
GridStore.exist(db, filename, rootCollection, callback);
});
}
exports.SkinGridStore = SkinGridStore;
| var GridStore = require('mongodb').GridStore;
/**
* @param filename: filename or ObjectId
*/
var SkinGridStore = exports.SkinGridStore = function(skinDb) {
this.skinDb = skinDb;
}
/**
* @param filename: filename or ObjectId
* callback(err, gridStoreObject)
*/
SkinGridStore.prototype.open = function(filename, mode, options, callback){
if(!callback){
callback = options;
options = undefined;
}
this.skinDb.open(function(err, db) {
new GridStore(db, filename, mode, options).open(callback);
});
}
/**
* @param filename: filename or ObjectId
*/
SkinGridStore.prototype.unlink = SkinGridStore.prototype.remove = function(filename, callback){
this.skinDb.open(function(err, db) {
GridStore.unlink(db, filename, callback);
});
}
SkinGridStore.prototype.exist = function(filename, rootCollection, callback){
this.skinDb.open(function(err, db) {
GridStore.exist(db, filename, rootCollection, callback);
});
}
exports.SkinGridStore = SkinGridStore;
|
:new: Add key to Message type | 'use babel'
/* @flow */
import type { Range, Point, TextEditor } from 'atom'
export type Message = {
key: string, // <-- Automatically added
location: {
file: string,
position: Range,
},
source: ?{
file: string,
position?: Point,
},
excerpt: string,
severity: 'error' | 'warning' | 'info',
reference: ?string,
solutions: ?Array<{
title: string,
position: Range,
currentText: ?string,
replaceWith: string,
}>,
description: ?Array<string>,
}
export type Linter = {
name: string,
scope: 'file' | 'project',
grammarScopes: Array<string>,
lint: ((textEditor: TextEditor) => ?Array<Message> | Promise<?Array<Message>>),
}
export type IndieConfig = {
name: string
}
export type MessagesPatch = {
added: Array<Message>,
removed: Array<Message>,
messages: Array<Message>,
}
export type UI = {
name: string,
activate(): void,
didBeginLinting(linter: Linter, filePath: ?string): void,
didFinishLinting(linter: Linter, filePath: ?string): void,
render(patch: MessagesPatch): void,
dispose(): void
}
export type State = { }
| 'use babel'
/* @flow */
import type { Range, Point, TextEditor } from 'atom'
export type Message = {
location: {
file: string,
position: Range,
},
source: ?{
file: string,
position?: Point,
},
excerpt: string,
severity: 'error' | 'warning' | 'info',
reference: ?string,
solutions: ?Array<{
title: string,
position: Range,
currentText: ?string,
replaceWith: string,
}>,
description: ?Array<string>,
}
export type Linter = {
name: string,
scope: 'file' | 'project',
grammarScopes: Array<string>,
lint: ((textEditor: TextEditor) => ?Array<Message> | Promise<?Array<Message>>),
}
export type IndieConfig = {
name: string
}
export type MessagesPatch = {
added: Array<Message>,
removed: Array<Message>,
messages: Array<Message>,
}
export type UI = {
name: string,
activate(): void,
didBeginLinting(linter: Linter, filePath: ?string): void,
didFinishLinting(linter: Linter, filePath: ?string): void,
render(patch: MessagesPatch): void,
dispose(): void
}
export type State = { }
|
Move tooltip story back to popover-tooltip | import '@salesforce-ux/design-system/assets/styles/salesforce-lightning-design-system.css';
export AppLauncher from './app-launcher/stories';
export BreadCrumb from './bread-crumb/stories';
export Button from './button/stories';
export ButtonStateful from './button-stateful/stories';
export Card from './card/stories';
export Checkbox from './forms/checkbox/stories';
export GlobalNavigationBar from './global-navigation-bar/stories';
export DataTable from './data-table/stories';
export DatePicker from './date-picker/stories';
export Dropdown from './menu-dropdown/stories';
export Input from './forms/input/stories';
export InlineInput from './forms/input/inline/stories';
export Search from './forms/input/search/stories';
export GlobalHeader from './global-header/stories';
export Icon from './icon/stories';
export Lookup from './lookup/stories';
export MediaObject from './media-object/stories';
export Modal from './modal/stories';
export Notification from './notification/stories';
export PageHeader from './page-header/stories';
export Popover from './popover/stories';
export Picklist from './menu-picklist/stories';
export Spinner from './spinner/stories';
export Tabs from './tabs/stories';
export TimePicker from './time-picker/stories';
export Tooltip from './popover-tooltip/stories';
export Tree from './tree/stories';
| import '@salesforce-ux/design-system/assets/styles/salesforce-lightning-design-system.css';
export AppLauncher from './app-launcher/stories';
export BreadCrumb from './bread-crumb/stories';
export Button from './button/stories';
export ButtonStateful from './button-stateful/stories';
export Card from './card/stories';
export Checkbox from './forms/checkbox/stories';
export GlobalNavigationBar from './global-navigation-bar/stories';
export DataTable from './data-table/stories';
export DatePicker from './date-picker/stories';
export Dropdown from './menu-dropdown/stories';
export Input from './forms/input/stories';
export InlineInput from './forms/input/inline/stories';
export Search from './forms/input/search/stories';
export GlobalHeader from './global-header/stories';
export Icon from './icon/stories';
export Lookup from './lookup/stories';
export MediaObject from './media-object/stories';
export Modal from './modal/stories';
export Notification from './notification/stories';
export PageHeader from './page-header/stories';
export Popover from './popover/stories';
export Picklist from './menu-picklist/stories';
export Spinner from './spinner/stories';
export Tabs from './tabs/stories';
export TimePicker from './time-picker/stories';
export Tooltip from './tooltip/stories';
export Tree from './tree/stories';
|
Add tests for the 404 and 500 error handlers. | from django.core.urlresolvers import reverse
from django.test import Client
from django.test.client import RequestFactory
from projects.models import Project
from innovate import urls
from innovate.views import handle404, handle500
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert response.has_header('location')
location = response.get('location', None)
assert location is not None
response = c.get(location)
assert response.status_code == 200
def test_featured():
project = Project.objects.create(
name=u'Test Project',
slug=u'test-project',
description=u'Blah',
featured=True
)
c = Client()
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
def test_404_handler():
"""Test that the 404 error handler renders and gives the correct code."""
response = handle404(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 404
def test_500_handler():
"""Test that the 500 error handler renders and gives the correct code."""
response = handle500(RequestFactory().get('/not/a/real/path/'))
assert response.status_code == 500
| from django.core.urlresolvers import reverse
from django.test import Client
from projects.models import Project
from innovate import urls
def test_routes():
c = Client()
for pattern in urls.urlpatterns:
response = c.get(reverse(pattern.name))
assert response.status_code == 301
assert response.has_header('location')
location = response.get('location', None)
assert location is not None
response = c.get(location)
assert response.status_code == 200
def test_featured():
project = Project.objects.create(
name=u'Test Project',
slug=u'test-project',
description=u'Blah',
featured=True
)
c = Client()
response = c.get('/en-US/')
assert response.status_code == 200
assert project.name in response.content
|
Change ObjectMap to new class name | <?php
use Allsop\App;
/**
* Theme initialization.
*/
/**
* Hide the 'Custom Fields' menu in production mode.
*/
if (defined('USE_PRODUCTION_ACF'))
{
define('ACF_LITE', true);
}
/**
* Load the classmap.
*/
require_once(FULL_PATH . 'vendor/autoload.php');
/**
* Load helper functions.
*/
foreach (glob(FULL_PATH . 'app/helpers/*.php') as $filename)
{
include $filename;
}
/**
* Configure the site.
*/
require_once(FULL_PATH . 'config/init.php');
/**
* Bind instances of each post type to the app so we can call them easily.
* Simply add more by creating a new custom post-type class and
* adding the full class path to the array below.
*/
App::bind([
'pages' => new Allsop\PostTypes\Page()),
'posts' => new Allsop\PostTypes\Post())
]);
| <?php
use Allsop\ObjectMap;
/**
* Theme initialization.
*/
/**
* Hide the 'Custom Fields' menu in production mode.
*/
if (defined('USE_PRODUCTION_ACF'))
{
define('ACF_LITE', true);
}
/**
* Load the classmap.
*/
require_once(FULL_PATH . 'vendor/autoload.php');
/**
* Load helper functions.
*/
foreach (glob(FULL_PATH . 'app/helpers/*.php') as $filename)
{
include $filename;
}
/**
* Configure the site.
*/
require_once(FULL_PATH . 'config/init.php');
/**
* Bind instances of each post type to the app so we can call them easily.
* Simply add more by creating a new custom post-type class and
* adding the full class path to the array below.
*/
ObjectMap::bind([
'pages' => new Allsop\PostTypes\Page()),
'posts' => new Allsop\PostTypes\Post())
]);
|
[AvoidMagicNumber] Store "sleep" delay into constant | <?php
/**
* @title Login Form Process
*
* @author Pierre-Henry Soria <hi@ph7.me>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License <http://www.gnu.org/licenses/gpl.html>
* @package PH7 / App / Module / Fake Admin Panel / Form / Processing
*/
namespace PH7;
class LoginFormProcess extends Form
{
const BRUTE_FORCE_SLEEP_DELAY = 6;
public function __construct()
{
parent::__construct();
(new Logger)->init($_POST);
sleep(self::BRUTE_FORCE_SLEEP_DELAY); // Security against brute-force attack and this will irritate hackers
$this->session->set('captcha_admin_enabled', 1); // Enable Captcha
\PFBC\Form::setError('form_login', t('"Email", "Username" or "Password" is Incorrect'));
}
}
| <?php
/**
* @title Login Form Process
*
* @author Pierre-Henry Soria <hi@ph7.me>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License <http://www.gnu.org/licenses/gpl.html>
* @package PH7 / App / Module / Fake Admin Panel / Form / Processing
*/
namespace PH7;
class LoginFormProcess extends Form
{
public function __construct()
{
parent::__construct();
(new Logger)->init($_POST);
sleep(6); // Security against brute-force attack and this will irritate the hacker
$this->session->set('captcha_admin_enabled', 1); // Enable Captcha
\PFBC\Form::setError('form_login', t('"Email", "Username" or "Password" is Incorrect'));
}
}
|
Use lodash method instead of vanilla js | import React, {PropTypes} from 'react'
import classnames from 'classnames'
import _ from 'lodash'
const VisHeader = ({views, view, onToggleView, name}) => (
<div className="graph-heading">
{views.length
? <ul className="nav nav-tablist nav-tablist-sm">
{views.map(v => (
<li
key={v}
onClick={() => onToggleView(v)}
className={classnames({active: view === v})}
>
{_.upperFirst(v)}
</li>
))}
</ul>
: null}
<div className="graph-title">{name}</div>
</div>
)
const {arrayOf, func, string} = PropTypes
VisHeader.propTypes = {
views: arrayOf(string).isRequired,
view: string.isRequired,
onToggleView: func.isRequired,
name: string.isRequired,
}
export default VisHeader
| import React, {PropTypes} from 'react'
import classnames from 'classnames'
const VisHeader = ({views, view, onToggleView, name}) => (
<div className="graph-heading">
{views.length
? <ul className="nav nav-tablist nav-tablist-sm">
{views.map(v => (
<li
key={v}
onClick={() => onToggleView(v)}
className={classnames({active: view === v})}
>
{v.charAt(0).toUpperCase() + v.slice(1)}
</li>
))}
</ul>
: null}
<div className="graph-title">{name}</div>
</div>
)
const {arrayOf, func, string} = PropTypes
VisHeader.propTypes = {
views: arrayOf(string).isRequired,
view: string.isRequired,
onToggleView: func.isRequired,
name: string.isRequired,
}
export default VisHeader
|
Test read from stdin and write to stdout | from io import StringIO
import sys
from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
FORMATTED_MARKDOWN = "# A header\n"
def test_no_files_passed():
assert run(()) == 0
def test_format(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path),)) == 0
assert file_path.read_text() == FORMATTED_MARKDOWN
def test_invalid_file():
assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1
def test_check(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(FORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 0
def test_check__fail(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
def test_dash_stdin(capsys, monkeypatch):
monkeypatch.setattr(sys, "stdin", StringIO(UNFORMATTED_MARKDOWN))
run(("-",))
captured = capsys.readouterr()
assert captured.out == FORMATTED_MARKDOWN
| from mdformat._cli import run
UNFORMATTED_MARKDOWN = "\n\n# A header\n\n"
FORMATTED_MARKDOWN = "# A header\n"
def test_no_files_passed():
assert run(()) == 0
def test_format(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path),)) == 0
assert file_path.read_text() == FORMATTED_MARKDOWN
def test_invalid_file():
assert run(("this is not a valid filepath?`=|><@{[]\\/,.%¤#'",)) == 1
def test_check(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(FORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 0
def test_check__fail(tmp_path):
file_path = tmp_path / "test_markdown.md"
file_path.write_text(UNFORMATTED_MARKDOWN)
assert run((str(file_path), "--check")) == 1
|
Include fetch polyfill by default
Currently, fetch will be polyfilled for older browsers
using the polyfill.io service. | export default ({title="", meta="", links="", content="", initialState={}, env={}, base_path="" }) => `
<html>
<head>
<meta charset="utf-8">
${title}
<meta name="viewport" content="width=device-width, initial-scale=1">
${meta}
${links}
<link href="${base_path}/static/app.css" rel=stylesheet>
</head>
<body>
<div id=app>${content}</div>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch&unknown=polyfill"></script>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
window.__APP_ENV_VARS__ = ${JSON.stringify(env)};
</script>
<script type=text/javascript src="${base_path}/static/app.js" charset=utf-8 async></script>
</body>
</html>
`;
| export default ({title="", meta="", links="", content="", initialState={}, env={}, base_path="" }) => `
<html>
<head>
<meta charset="utf-8">
${title}
<meta name="viewport" content="width=device-width, initial-scale=1">
${meta}
${links}
<link href="${base_path}/static/app.css" rel=stylesheet>
</head>
<body>
<div id=app>${content}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
window.__APP_ENV_VARS__ = ${JSON.stringify(env)};
</script>
<script type=text/javascript src="${base_path}/static/app.js" charset=utf-8 async></script>
</body>
</html>
`;
|
Change NavTab pager back to FragmentPagerAdapter.
When using a FragmentStatePagerAdapter, the action of swiping between our
Tabs feels noticeably less snappy, since the fragment gets recreated every
time the user swipes to it.
In this particular case, I think that proper memory management must give
way to snappiness.
Change-Id: Ifbce0e7231071d22718d1a2f6071fbe08569efdc | package org.wikipedia.navtab;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
public class NavTabFragmentPagerAdapter extends FragmentPagerAdapter {
private Fragment currentFragment;
public NavTabFragmentPagerAdapter(FragmentManager mgr) {
super(mgr);
}
@Nullable
public Fragment getCurrentFragment() {
return currentFragment;
}
@Override public Fragment getItem(int pos) {
return NavTab.of(pos).newInstance();
}
@Override public int getCount() {
return NavTab.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
currentFragment = ((Fragment) object);
super.setPrimaryItem(container, position, object);
}
} | package org.wikipedia.navtab;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
public class NavTabFragmentPagerAdapter extends FragmentStatePagerAdapter {
private Fragment currentFragment;
public NavTabFragmentPagerAdapter(FragmentManager mgr) {
super(mgr);
}
@Nullable
public Fragment getCurrentFragment() {
return currentFragment;
}
@Override public Fragment getItem(int pos) {
return NavTab.of(pos).newInstance();
}
@Override public int getCount() {
return NavTab.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
currentFragment = ((Fragment) object);
super.setPrimaryItem(container, position, object);
}
} |
Add correct name of constant variables | <?php
namespace fennecweb\ajax\details;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'detailsProjectsTestUser';
const USERID = 'detailsProjectsTestUser';
const PROVIDER = 'detailsProjectsTestUser';
public function testExecute()
{
//Test if the selected project contains the correct information
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'listingProjectsTestUserToken'
);
list($service) = WebService::factory('details/Project');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
'table_1'
);
$this->assertArraySubset($expected, $results);
}
}
| <?php
namespace fennecweb\ajax\details;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'listingProjectsTestUser';
const USERID = 'listingProjectsTestUser';
const PROVIDER = 'listingProjectsTestUser';
public function testExecute()
{
//Test if the selected project contains the correct information
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'listingProjectsTestUserToken'
);
list($service) = WebService::factory('details/Project');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
'table_1'
);
$this->assertArraySubset($expected, $results);
}
}
|
Use DocumentManager::merge instead of find | <?php
/**
* (c) Matthieu Bontemps <matthieu@knplabs.com>
* (c) Thibault Duplessis <thibault.duplessis@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Bundle\DoctrineUserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;
use Symfony\Component\EventDispatcher\Event;
class DoctrineUserBundle extends BaseBundle
{
public function boot()
{
$this->container->get('event_dispatcher')->connect('security.token.unserialize', array($this, 'listenToSecurityTokenUnserialize'));
}
public function listenToSecurityTokenUnserialize(Event $event)
{
if($user = $event->getSubject()->getUser()) {
$this->container->get('doctrine_user.object_manager')->merge($user);
}
}
}
| <?php
/**
* (c) Matthieu Bontemps <matthieu@knplabs.com>
* (c) Thibault Duplessis <thibault.duplessis@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Bundle\DoctrineUserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;
use Symfony\Component\EventDispatcher\Event;
class DoctrineUserBundle extends BaseBundle
{
public function boot()
{
$this->container->get('event_dispatcher')->connect('security.token.unserialize', array($this, 'listenToSecurityTokenUnserialize'));
}
public function listenToSecurityTokenUnserialize(Event $event)
{
if($user = $event->getSubject()->getUser()) {
$user = $this->container->get('doctrine_user.repository.user')->find($user->getId());
}
}
}
|
Fix task to create build.properties | <?php
namespace Task;
use Mage\Task\AbstractTask;
class CreateBuildProperties extends AbstractTask {
public function getName() {
return 'Creating build.properties file...';
}
public function run() {
$commandForBranch = "git status | grep -o \"origin/.*'\"";
$output = "";
$this->runCommandLocal($commandForBranch, $output);
$branch = str_replace("'", "", $output);
$date = new \DateTime();
$commandForCommit = "git rev-parse HEAD";
$result = $this->runCommandLocal($commandForCommit, $output);
$commit = $output;
$fileContent = "branch=$branch\n" . "commit=$commit\n" . "date=" . $date->format("d/m/Y H:i") ."\n";
file_put_contents(getcwd().'/build.properties', $fileContent);
return $result;
}
}
| <?php
namespace Task;
use Mage\Task\AbstractTask;
class CreateBuildProperties extends AbstractTask {
public function getName() {
return 'Creating build.properties file...';
}
public function run() {
$commandForBranch = "git status | grep -o \"origin/.*'\"";
$output = $this->runCommandLocal($commandForBranch);
$branch = str_replace("'", "", $output);
$date = new \DateTime();
$commandForCommit = 'git rev-parse HEAD';
$output = $this->runCommandLocal($commandForCommit);
$commit = $output;
$fileContent = "branch=$branch\n" . "commit=$commit\n" . "date=" . $date->format("d/m/Y H:i") ."\n";
file_put_contents(getcwd().'/build.properties', $fileContent);
return $result;
}
}
|
Add items in phishing REGEX list | (function() {
'use strict';
var phishingExpressions = [
/\.beget\.tech/,
/acusticanapoli\.com/,
/archer\.fr/,
/assurance-ameli-recouvrement\.com/,
/assurance\.remboursement-amelifr/,
/assure-ameli-portail-remboursement\.info/,
/assurance-ameli-recouvrement\.net/,
/assurance\.remboursement-amelifr\.kostidis\.gr/,
/intercoined\.com/,
/liveone\.com\.br/,
/mannishtalk\.com/,
/remboursement\.ameliassurance\.contempora\.ro/,
/remboursement\.ameliassurance-fr36932693693269\.irds\.ro/,
/remboursement\.caisse-assurance\.irds\.ro/,
/remboursement\.ameliassurance\.marikala\.gr/,
/sendibm/,
/yzfg\.r\.bh\.d\.sendibt3\.com/,
/www\.crplindia\.com/,
/www\.imakecollege\.com/
];
/* Export either through Angular loader or CommonJS */
if (typeof module != 'undefined') { // we're in Node
module.exports = phishingExpressions;
} else { // we're in the browser
angular.module('ddsCommon').constant('phishingExpressions', phishingExpressions);
}
/* End of export */
})();
| (function() {
'use strict';
var phishingExpressions = [
/acusticanapoli\.com/,
/archer\.fr/,
/assurance-ameli-recouvrement\.com/,
/assurance-ameli-recouvrement\.net/,
/assurance\.remboursement-amelifr\.kostidis\.gr/,
/depor420\.beget\.tech/,
/intercoined\.com/,
/liveone\.com\.br/,
/mannishtalk\.com/,
/remboursement\.ameliassurance\.contempora\.ro/,
/remboursement\.ameliassurance-fr36932693693269\.irds\.ro/,
/remboursement\.caisse-assurance\.irds\.ro/,
/remboursement\.ameliassurance\.marikala\.gr/,
/yzfg\.r\.bh\.d\.sendibt3\.com/
];
/* Export either through Angular loader or CommonJS */
if (typeof module != 'undefined') { // we're in Node
module.exports = phishingExpressions;
} else { // we're in the browser
angular.module('ddsCommon').constant('phishingExpressions', phishingExpressions);
}
/* End of export */
})();
|
Support to use "data-*" attributes to set options | // Save the other cropper
Cropper.other = $.fn.cropper;
// Register as jQuery plugin
$.fn.cropper = function (option) {
var args = toArray(arguments, 1);
var result;
this.each(function () {
var $this = $(this);
var data = $this.data(NAMESPACE);
var options;
var fn;
if (!data) {
if (/destroy/.test(option)) {
return;
}
options = $.extend({}, $this.data(), $.isPlainObject(option) && option);
$this.data(NAMESPACE, (data = new Cropper(this, options)));
}
if (typeof option === 'string' && $.isFunction(fn = data[option])) {
result = fn.apply(data, args);
}
});
return isUndefined(result) ? this : result;
};
$.fn.cropper.Constructor = Cropper;
$.fn.cropper.setDefaults = Cropper.setDefaults;
// No conflict
$.fn.cropper.noConflict = function () {
$.fn.cropper = Cropper.other;
return this;
};
| // Save the other cropper
Cropper.other = $.fn.cropper;
// Register as jQuery plugin
$.fn.cropper = function (options) {
var args = toArray(arguments, 1);
var result;
this.each(function () {
var $this = $(this);
var data = $this.data(NAMESPACE);
var fn;
if (!data) {
if (/destroy/.test(options)) {
return;
}
$this.data(NAMESPACE, (data = new Cropper(this, options)));
}
if (typeof options === 'string' && $.isFunction(fn = data[options])) {
result = fn.apply(data, args);
}
});
return isUndefined(result) ? this : result;
};
$.fn.cropper.Constructor = Cropper;
$.fn.cropper.setDefaults = Cropper.setDefaults;
// No conflict
$.fn.cropper.noConflict = function () {
$.fn.cropper = Cropper.other;
return this;
};
|
Add warning if large_description is not generated | from setuptools import setup, find_packages
import os
from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
try:
import pypandoc
with open('README.md') as readme_md:
readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown')
except:
print("WARNING: Did not create pypi readme")
readme = None
setup(
name=name,
version=version,
author=author,
url="https://github.com/khazhyk/osuapi",
license="MIT",
long_description=readme,
keywords="osu",
packages=find_packages(),
description="osu! api wrapper.",
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Utilities"
]
)
| from setuptools import setup, find_packages
import os
from osuapi import __version__ as version, __title__ as name, __author__ as author, __license__ as license
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
try:
import pypandoc
with open('README.md') as readme_md:
readme = pypandoc.convert_text(readme_md.read(), 'rst', 'markdown')
except:
readme = None
setup(
name=name,
version=version,
author=author,
url="https://github.com/khazhyk/osuapi",
license="MIT",
long_description=readme,
keywords="osu",
packages=find_packages(),
description="osu! api wrapper.",
classifiers=[
"Development Status :: 1 - Planning",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Utilities"
]
)
|
Change dataSample to generate indices of random pair using list of values | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
| #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
random_pairs = dedupe.core.randomPairs(len(data), sample_size)
return tuple((data[k1], data[k2]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
Remove IP address from feed description | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from .models import LoggedAction
class RecentChangesFeed(Feed):
title = "YourNextMP recent changes"
description = "Changes to YNMP candidates"
link = "/feeds/changes.xml"
feed_type = Atom1Feed
def items(self):
return LoggedAction.objects.order_by('-updated')[:50]
def item_title(self, item):
return "{0} - {1}".format(
item.popit_person_id,
item.action_type
)
def item_description(self, item):
description = """
{0}
Updated at {1}
""".format(
item.source,
str(item.updated),
)
return description
def item_link(self, item):
return reverse('person-view', args=[item.popit_person_id])
| from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerator import Atom1Feed
from .models import LoggedAction
class RecentChangesFeed(Feed):
title = "YourNextMP recent changes"
description = "Changes to YNMP candidates"
link = "/feeds/changes.xml"
feed_type = Atom1Feed
def items(self):
return LoggedAction.objects.order_by('-updated')[:50]
def item_title(self, item):
return "{0} - {1}".format(
item.popit_person_id,
item.action_type
)
def item_description(self, item):
description = """
{0}
Updated by {1} at {2}
""".format(
item.source,
item.ip_address,
str(item.updated),
)
return description
def item_link(self, item):
return reverse('person-view', args=[item.popit_person_id])
|
Remove previous functionality for hiding data in the path URL | (function(){
'use strict';
angular.module('cla.controllers')
.controller('SearchCtrl',
['$scope', '$state', '$location',
function($scope, $state, $location) {
$scope.$on('$locationChangeSuccess', function(){
var searchList = ($state.current.name.indexOf('complaint') !== -1)? 'complaints' : 'cases';
var $searchElement = angular.element(document.getElementById('case-search'));
$searchElement.attr('placeholder', 'Search ' + searchList);
$scope.search = $location.search().search || '';
});
$scope.submit = function() {
var action = ($state.current.name.indexOf('complaint') !== -1)? 'complaints_list' : 'case_list';
$state.go(action, {search: $scope.search}, {inherit: false});
};
}
]
);
})();
| (function(){
'use strict';
angular.module('cla.controllers')
.controller('SearchCtrl',
['$scope', '$state', '$location',
function($scope, $state, $location) {
$scope.$on('$locationChangeSuccess', function(){
var searchList = ($state.current.name.indexOf('complaint') !== -1)? 'complaints' : 'cases';
var $searchElement = angular.element(document.getElementById('case-search'));
$searchElement.attr('placeholder', 'Search ' + searchList);
$scope.search = $location.search().search || '';
});
$scope.submit = function() {
var action = ($state.current.name.indexOf('complaint') !== -1)? 'complaints_list' : 'case_list';
$state.go(action, {search: $scope.search}, {inherit: false, location: false});
};
}
]
);
})();
|
Fix module require chicken-egg problem | //Get required modules
var Connection = require( 'ssh2' );
var domain = require( 'domain' );
//Auxiliary function to initialize/re-initialize ssh connection
function initializeConnection() {
//Add my libs
var handlers = require( './handlers.js' );
//Initialize the ssh connection
connection = new Connection(),
handler = domain.create();
//Handling "error" event inside domain handler.
handler.add(connection);
//Add global connection handlers
handlers.setGlobalConnectionHandlers();
//Start connection
connection.connect(OptionsForSFTP);
}
function resetConnection() {
//Mark inactive connection
active_connection = false;
//Start connection
connection.connect(OptionsForSFTP);
}
//Expose handlers public API
module.exports = {
resetConnection: resetConnection,
initializeConnection: initializeConnection
};
| //Get required modules
var Connection = require( 'ssh2' );
var domain = require( 'domain' );
//Add my libs
var handlers = require( './handlers.js' );
//Auxiliary function to initialize/re-initialize ssh connection
function initializeConnection() {
//Initialize the ssh connection
connection = new Connection(),
handler = domain.create();
//Handling "error" event inside domain handler.
handler.add(connection);
//Add global connection handlers
handlers.setGlobalConnectionHandlers();
//Start connection
connection.connect(OptionsForSFTP);
}
function resetConnection() {
//Mark inactive connection
active_connection = false;
//Start connection
connection.connect(OptionsForSFTP);
}
//Expose handlers public API
module.exports = {
initializeConnection: initializeConnection,
resetConnection: resetConnection
};
|
Revert "Schema.define could return associated instance" | export default class EntitySchema {
constructor(key, options = {}) {
if (!key || typeof key !== 'string') {
throw new Error('A string non-empty key is required');
}
this._key = key;
const idAttribute = options.idAttribute || 'id';
this._getId = typeof idAttribute === 'function' ? idAttribute : x => x[idAttribute];
this._idAttribute = idAttribute;
}
getKey() {
return this._key;
}
getId(entity) {
return this._getId(entity);
}
getIdAttribute() {
return this._idAttribute;
}
define(nestedSchema) {
for (let key in nestedSchema) {
if (nestedSchema.hasOwnProperty(key)) {
this[key] = nestedSchema[key];
}
}
}
}
| export default class EntitySchema {
constructor(key, options = {}) {
if (!key || typeof key !== 'string') {
throw new Error('A string non-empty key is required');
}
this._key = key;
const idAttribute = options.idAttribute || 'id';
this._getId = typeof idAttribute === 'function' ? idAttribute : x => x[idAttribute];
this._idAttribute = idAttribute;
}
getKey() {
return this._key;
}
getId(entity) {
return this._getId(entity);
}
getIdAttribute() {
return this._idAttribute;
}
define(nestedSchema) {
for (let key in nestedSchema) {
if (nestedSchema.hasOwnProperty(key)) {
this[key] = nestedSchema[key];
}
}
return this;
}
}
|
Fix error when the mail engine is not set | <?php
namespace MailMotor\Bundle\MailMotorBundle\Factory;
use MailMotor\Bundle\MailMotorBundle\Gateway\SubscriberGateway;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
/**
* This is the class that loads and manages your bundle configuration
*
* @author Jeroen Desloovere <info@jeroendesloovere.be>
*/
class MailMotorFactory
{
/** @var Container */
protected $container;
/** @var string|null */
protected $mailEngine;
public function __construct(
Container $container,
?string $mailEngine
) {
$this->container = $container;
$this->setMailEngine($mailEngine);
}
public function getSubscriberGateway(): SubscriberGateway
{
return $this->container->get('mailmotor.' . $this->mailEngine . '.subscriber.gateway');
}
protected function setMailEngine(?string $mailEngine): void
{
if ($mailEngine == null) {
$mailEngine = 'not_implemented';
}
$this->mailEngine = strtolower($mailEngine);
}
}
| <?php
namespace MailMotor\Bundle\MailMotorBundle\Factory;
use MailMotor\Bundle\MailMotorBundle\Gateway\SubscriberGateway;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
/**
* This is the class that loads and manages your bundle configuration
*
* @author Jeroen Desloovere <info@jeroendesloovere.be>
*/
class MailMotorFactory
{
/** @var Container */
protected $container;
/** @var string */
protected $mailEngine;
public function __construct(
Container $container,
string $mailEngine
) {
$this->container = $container;
$this->setMailEngine($mailEngine);
}
public function getSubscriberGateway(): SubscriberGateway
{
return $this->container->get('mailmotor.' . $this->mailEngine . '.subscriber.gateway');
}
protected function setMailEngine(string $mailEngine): void
{
if ($mailEngine == null) {
$mailEngine = 'not_implemented';
}
$this->mailEngine = strtolower($mailEngine);
}
}
|
Fix unicode error in new test | '''Test Span.as_doc() doesn't segfault'''
from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy
def test_issue1537():
string = 'The sky is blue . The man is pink . The dog is purple .'
doc = Doc(Vocab(), words=string.split())
doc[0].sent_start = True
for word in doc[1:]:
if word.nbor(-1).text == '.':
word.sent_start = True
else:
word.sent_start = False
sents = list(doc.sents)
sent0 = sents[0].as_doc()
sent1 = sents[1].as_doc()
assert isinstance(sent0, Doc)
assert isinstance(sent1, Doc)
# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
# nlp = load_spacy('en')
# doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
# sents = [s.as_doc() for s in doc.sents]
# print(list(sents[0].noun_chunks))
# print(list(sents[1].noun_chunks))
| '''Test Span.as_doc() doesn't segfault'''
from ...tokens import Doc
from ...vocab import Vocab
from ... import load as load_spacy
def test_issue1537():
string = 'The sky is blue . The man is pink . The dog is purple .'
doc = Doc(Vocab(), words=string.split())
doc[0].sent_start = True
for word in doc[1:]:
if word.nbor(-1).text == '.':
word.sent_start = True
else:
word.sent_start = False
sents = list(doc.sents)
sent0 = sents[0].as_doc()
sent1 = sents[1].as_doc()
assert isinstance(sent0, Doc)
assert isinstance(sent1, Doc)
# Currently segfaulting, due to l_edge and r_edge misalignment
#def test_issue1537_model():
# nlp = load_spacy('en')
# doc = nlp(u'The sky is blue. The man is pink. The dog is purple.')
# sents = [s.as_doc() for s in doc.sents]
# print(list(sents[0].noun_chunks))
# print(list(sents[1].noun_chunks))
|
[FIX] account_analytic_invoice_line_menu: Put dependency to "account_analytic_analysis" module. | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Analytic Invoice Line Menu",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributors": [
"Ana Juaristi <anajuaristi@avanzosc.es>",
"Alfredo de la Fuente <alfredodelafuente@avanzosc.es>",
],
"category": "Sales Management",
"depends": [
"account_analytic_analysis"
],
"data": [
"views/account_analytic_invoice_line_view.xml",
],
"installable": True,
}
| # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Account Analytic Invoice Line Menu",
"version": "8.0.1.0.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"contributors": [
"Ana Juaristi <anajuaristi@avanzosc.es>",
"Alfredo de la Fuente <alfredodelafuente@avanzosc.es>",
],
"category": "Sales Management",
"depends": [
],
"data": [
"views/account_analytic_invoice_line_view.xml",
],
"installable": True,
}
|
Check date of scan is not in future | from radar.validation.data_sources import DataSourceValidationMixin
from radar.validation.core import Field, Validation
from radar.validation.meta import MetaValidationMixin
from radar.validation.patients import PatientValidationMixin
from radar.validation.validators import required, optional, min_, max_, none_if_blank, max_length, not_in_future
class FetalAnomalyScanValidation(PatientValidationMixin, DataSourceValidationMixin, MetaValidationMixin, Validation):
date_of_scan = Field([required(), not_in_future()])
gestational_age = Field([required(), min_(8 * 7, 'days'), max_(45 * 7, 'days')])
oligohydramnios = Field([optional()])
right_anomaly_details = Field([none_if_blank(), optional(), max_length(1000)])
right_ultrasound_details = Field([none_if_blank(), optional(), max_length(1000)])
left_anomaly_details = Field([none_if_blank(), optional(), max_length(1000)])
left_ultrasound_details = Field([none_if_blank(), optional(), max_length(1000)])
| from radar.validation.data_sources import DataSourceValidationMixin
from radar.validation.core import Field, Validation
from radar.validation.meta import MetaValidationMixin
from radar.validation.patients import PatientValidationMixin
from radar.validation.validators import required, optional, min_, max_, none_if_blank, max_length
class FetalAnomalyScanValidation(PatientValidationMixin, DataSourceValidationMixin, MetaValidationMixin, Validation):
date_of_scan = Field([required()])
gestational_age = Field([required(), min_(8 * 7, 'days'), max_(45 * 7, 'days')])
oligohydramnios = Field([optional()])
right_anomaly_details = Field([none_if_blank(), optional(), max_length(1000)])
right_ultrasound_details = Field([none_if_blank(), optional(), max_length(1000)])
left_anomaly_details = Field([none_if_blank(), optional(), max_length(1000)])
left_ultrasound_details = Field([none_if_blank(), optional(), max_length(1000)])
|
Load plugin from entry point in electron | require('babel-register')({ extensions: ['.jsx'] });
const app = require('hadron-app');
const React = require('react');
const ReactDOM = require('react-dom');
const AppRegistry = require('hadron-app-registry');
const DataService = require('mongodb-data-service');
const Connection = require('mongodb-connection-model');
const {{pascalcase name}}Component = require('../../lib/components');
// const CONNECTION = new Connection({
// hostname: '127.0.0.1',
// port: 27018,
// ns: '{{slugcase name}}',
// mongodb_database_name: 'admin'
// });
const entryPoint = require('../../');
const appRegistry = new AppRegistry();
global.hadronApp = app;
global.hadronApp.appRegistry = appRegistry;
entryPoint.activate(appRegistry);
// const dataService = new DataService(CONNECTION);
// dataService.onDataServiceInitialized(dataService);
// global.hadronApp.appRegistry.onActivated();
// dataService.connect((error, ds) => {
// global.hadronApp.dataService = ds;
// global.hadronApp.appRegistry.onConnected(error, ds);
// });
ReactDOM.render(
React.createElement({{pascalcase name}}Component),
document.getElementById('container')
);
| require('babel-register')({ extensions: ['.jsx'] });
const app = require('hadron-app');
const React = require('react');
const ReactDOM = require('react-dom');
const AppRegistry = require('hadron-app-registry');
const DataService = require('mongodb-data-service');
const Connection = require('mongodb-connection-model');
const {{pascalcase name}}Component = require('../../lib/components');
const {{pascalcase name}}Store = require('../../lib/stores');
const {{pascalcase name}}Actions = require('../../lib/actions');
// const CONNECTION = new Connection({
// hostname: '127.0.0.1',
// port: 27018,
// ns: '{{slugcase name}}',
// mongodb_database_name: 'admin'
// });
global.hadronApp = app;
global.hadronApp.appRegistry = new AppRegistry();
global.hadronApp.appRegistry.registerStore('{{pascalcase name}}.Store', {{pascalcase name}}Store);
global.hadronApp.appRegistry.registerAction('{{pascalcase name}}.Actions', {{pascalcase name}}Actions);
// const dataService = new DataService(CONNECTION);
// dataService.onDataServiceInitialized(dataService);
// global.hadronApp.appRegistry.onActivated();
// dataService.connect((error, ds) => {
// global.hadronApp.dataService = ds;
// global.hadronApp.appRegistry.onConnected(error, ds);
// });
ReactDOM.render(
React.createElement({{pascalcase name}}Component),
document.getElementById('container')
);
|
Fix patch 131 for db with lots of revisions
Summary:
The old version of this loads all differential revisions at once, but that much
can't all be loaded into memory when there are close to 500,000 revisions. This
diff splits up loading the revisions.
Test Plan: Ran this to run the migration in our install
Reviewers: jungejason, epriestley
Reviewed By: epriestley
CC: aran
Differential Revision: https://secure.phabricator.com/D2243 | <?php
/*
* Copyright 2012 Facebook, 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.
*/
$table = new DifferentialRevision();
$conn_w = $table->establishConnection('w');
echo "Migrating revisions";
do {
$revisions = id(new DifferentialRevision())
->loadAllWhere('branchName IS NULL LIMIT 1000');
foreach ($revisions as $revision) {
echo ".";
$diff = $revision->loadActiveDiff();
if (!$diff) {
continue;
}
$branch_name = $diff->getBranch();
$arc_project_phid = $diff->getArcanistProjectPHID();
queryfx(
$conn_w,
'UPDATE %T SET branchName = %s, arcanistProjectPHID = %s WHERE id = %d',
$table->getTableName(),
$branch_name,
$arc_project_phid,
$revision->getID());
}
} while (count($revisions) == 1000);
echo "\nDone.\n";
| <?php
/*
* Copyright 2012 Facebook, 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.
*/
$table = new DifferentialRevision();
$conn_w = $table->establishConnection('w');
$revisions = id(new DifferentialRevision())->loadAll();
echo "Migrating ".count($revisions)." revisions";
foreach ($revisions as $revision) {
echo ".";
$diff = $revision->loadActiveDiff();
if (!$diff) {
continue;
}
$branch_name = $diff->getBranch();
$arc_project_phid = $diff->getArcanistProjectPHID();
queryfx(
$conn_w,
'UPDATE %T SET branchName = %s, arcanistProjectPHID = %s WHERE id = %d',
$table->getTableName(),
$branch_name,
$arc_project_phid,
$revision->getID());
}
echo "\nDone.\n";
|
Allow hooks to return values (and simplify the code) | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Université Catholique de Louvain.
#
# This file is part of INGInious.
#
# INGInious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# INGInious is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with INGInious. If not, see <http://www.gnu.org/licenses/>.
""" Hook Manager """
class HookManager(object):
""" Registers an manages hooks. Hooks are callback functions called when the backend does a specific action. """
def __init__(self):
self.hooks = {}
def add_hook(self, name, callback):
""" Add a new hook that can be called with the call_hook function """
hook_list = self.hooks.get(name, [])
hook_list.append(callback)
self.hooks[name] = hook_list
def call_hook(self, name, **kwargs):
""" Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)"""
return map(lambda x: x(**kwargs), self.hooks.get(name, []))
| # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Université Catholique de Louvain.
#
# This file is part of INGInious.
#
# INGInious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# INGInious is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with INGInious. If not, see <http://www.gnu.org/licenses/>.
""" Hook Manager """
class HookManager(object):
""" Registers an manages hooks. Hooks are callback functions called when the backend does a specific action. """
def __init__(self):
self.hooks = {}
def add_hook(self, name, callback):
""" Add a new hook that can be called with the call_hook function """
hook_list = self.hooks.get(name, [])
hook_list.append(callback)
self.hooks[name] = hook_list
def call_hook(self, name, **kwargs):
""" Call all hooks registered with this name """
for func in self.hooks.get(name, []):
func(**kwargs)
|
Change params to suit and rank | """
Created on Dec 24, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
from .card import Card
class BjCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
""" Returns the value of the card used for scoring the game """
if self._value:
return self._value
elif self.rank not in list('JQKA'):
self._value = int(self.rank)
elif self.rank in list('JQK'):
self._value = 10
else:
self._value = 11
return self._value
| """
Created on Dec 24, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
from .card import Card
class BjCard(Card):
def __init__(self, *args, **kwarg):
super().__init__(*args, **kwarg)
@property
def value(self):
""" Returns the value of the card used for scoring the game """
if self._value:
return self._value
elif self.rank not in list('JQKA'):
self._value = int(self.rank)
elif self.rank in list('JQK'):
self._value = 10
else:
self._value = 11
return self._value
|
Convert exception creation to leaveNode() | <?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2015 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\CodeCleaner;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Exit_;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Throw_;
class ExitPass extends CodeCleanerPass
{
/**
* Converts exit calls to BreakExceptions.
*
* @param \PhpParser\Node $node
*/
public function leaveNode(Node $node)
{
if ($node instanceof Exit_) {
$args = array(new Arg(new String_('Goodbye.')));
return new Throw_(new New_(new Name('Psy\Exception\BreakException'), $args));
}
}
}
| <?php
/*
* This file is part of Psy Shell.
*
* (c) 2012-2015 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\CodeCleaner;
use PhpParser\Node;
use PhpParser\Node\Expr\Exit_;
use Psy\Exception\BreakException;
class ExitPass extends CodeCleanerPass
{
/**
* Throws a PsySH BreakException instead on exit().
*
* @throws \Psy\Exception\BreakException if the node is an exit node.
*
* @param \PhpParser\Node $node
*/
public function enterNode(Node $node)
{
if ($node instanceof Exit_) {
throw new BreakException('Goodbye.');
}
}
}
|
Make work with modern markdown2
Within a pre block, links don't link, which is good. | from tiddlywebplugins.markdown import render
from tiddlyweb.model.tiddler import Tiddler
def test_urlification():
tiddler = Tiddler('blah')
tiddler.text = """
lorem ipsum http://example.org dolor sit amet
... http://www.example.com/foo/bar ...
"""
environ = {'tiddlyweb.config': {'markdown.wiki_link_base': ''}}
output = render(tiddler, environ)
for url in ["http://example.org", "http://www.example.com/foo/bar"]:
assert '<a href="%(url)s">%(url)s</a>' % { "url": url } in output
def test_precedence():
tiddler = Tiddler('cow')
tiddler.text = """
* [Pry](http://www.philaquilina.com/2012/05/17/tossing-out-irb-for-pry/)
* [Rails console](http://37signals.com/svn/posts/3176-three-quick-rails-console-tips)
"""
environ = {'tiddlyweb.config': {'markdown.wiki_link_base': ''}}
output = render(tiddler, environ)
assert "http://<a href" not in output
| from tiddlywebplugins.markdown import render
from tiddlyweb.model.tiddler import Tiddler
def test_urlification():
tiddler = Tiddler('blah')
tiddler.text = """
lorem ipsum http://example.org dolor sit amet
... http://www.example.com/foo/bar ...
"""
environ = {'tiddlyweb.config': {'markdown.wiki_link_base': ''}}
output = render(tiddler, environ)
for url in ["http://example.org", "http://www.example.com/foo/bar"]:
assert '<a href="%(url)s">%(url)s</a>' % { "url": url } in output
def test_precedence():
tiddler = Tiddler('cow')
tiddler.text = """
* [Pry](http://www.philaquilina.com/2012/05/17/tossing-out-irb-for-pry/)
* [Rails console](http://37signals.com/svn/posts/3176-three-quick-rails-console-tips)
"""
environ = {'tiddlyweb.config': {'markdown.wiki_link_base': ''}}
output = render(tiddler, environ)
assert "http://<a href" not in output
|
Use standard 3-part version number. |
import os
from setuptools import setup, find_packages
setup(
name = 'projd',
version = '0.1.0',
license = 'MIT',
description = 'Utilities for working with projects and applications '
'organized within a root directory.',
long_description = open(os.path.join(os.path.dirname(__file__),
'README.md')).read(),
keywords = 'python project directory application',
url = 'https://github.com/todddeluca/projd',
author = 'Todd Francis DeLuca',
author_email = 'todddeluca@yahoo.com',
classifiers = ['License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
py_modules = ['projd'],
)
|
import os
from setuptools import setup, find_packages
setup(
name = 'projd',
version = '0.1',
license = 'MIT',
description = 'Utilities for working with projects and applications '
'organized within a root directory.',
long_description = open(os.path.join(os.path.dirname(__file__),
'README.md')).read(),
keywords = 'python project directory application',
url = 'https://github.com/todddeluca/projd',
author = 'Todd Francis DeLuca',
author_email = 'todddeluca@yahoo.com',
classifiers = ['License :: OSI Approved :: MIT License',
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
py_modules = ['projd'],
)
|
Fix missing import for sys | import os
import sys
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
| import os
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
|
Revert "Replace TRAVIS_BUILD_NUMBER with TRAVIS_BUILD_ID"
This reverts commit 6e63853bd31eb8db95d33bf9fd7d5841f93085f1. | var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
| var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_ID;
browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
|
Check if Bluetooth is enabled | var log = function(message) {
console.log(message);
logDiv.innerHTML = logDiv.innerHTML + message + "<br>";
};
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event.
onDeviceReady: function() {
StatusBar.overlaysWebView( false );
StatusBar.backgroundColorByHexString('#ffffff');
StatusBar.styleDefault();
log("DeviceReady");
// Check Bluetooth is Enabled
bluetoothSerial.isEnabled(
function() {
log("Bluetooth is enabled");
}, function() {
log("Bluetooth is *not* enabled");
});
},
};
app.initialize(); | var log = function(message) {
console.log(message);
logDiv.innerHTML = logDiv.innerHTML + message + "<br>";
};
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event.
onDeviceReady: function() {
StatusBar.overlaysWebView( false );
StatusBar.backgroundColorByHexString('#ffffff');
StatusBar.styleDefault();
log("DeviceReady");
},
};
app.initialize(); |
Substitute merge() with assign() - Ember deprecation | import { get } from '@ember/object';
import { assign } from '@ember/polyfills';
import computeFn from '../utils/helper-compute';
import BaseHelper from './-base';
export default BaseHelper.extend({
compute: computeFn(function (params, formatHash = {}) {
this._super(...arguments);
if (!params || params && params.length > 3) {
throw new TypeError('ember-moment: Invalid Number of arguments, at most 3');
}
const moment = get(this, 'moment');
const { locale, timeZone } = formatHash;
const [date, referenceTime, formats] = params;
const clone = Object.create(formatHash);
delete clone.locale;
delete clone.timeZone;
const mergedFormats = assign(clone, formats);
return this.morphMoment(moment.moment(date), { locale, timeZone }).calendar(referenceTime, mergedFormats);
})
});
| import { get } from '@ember/object';
import { merge } from '@ember/polyfills';
import computeFn from '../utils/helper-compute';
import BaseHelper from './-base';
export default BaseHelper.extend({
compute: computeFn(function (params, formatHash = {}) {
this._super(...arguments);
if (!params || params && params.length > 3) {
throw new TypeError('ember-moment: Invalid Number of arguments, at most 3');
}
const moment = get(this, 'moment');
const { locale, timeZone } = formatHash;
const [date, referenceTime, formats] = params;
const clone = Object.create(formatHash);
delete clone.locale;
delete clone.timeZone;
const mergedFormats = merge(clone, formats);
return this.morphMoment(moment.moment(date), { locale, timeZone }).calendar(referenceTime, mergedFormats);
})
});
|
Update dict instead of doc | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.util.log import with_progress_bar
from corehq.util.couch import iter_update, DocUpdate
from django.core.management.base import BaseCommand
from auditcare.utils.export import navigation_event_ids_by_user
import logging
from auditcare.models import NavigationEventAudit
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = """Scrub a username from auditcare for GDPR compliance"""
def add_arguments(self, parser):
parser.add_argument('username', help="Username to scrub")
def handle(self, username, **options):
def update_username(event_dict):
event_dict['user'] = new_username
return DocUpdate(doc=event_dict)
new_username = "Redacted User (GDPR)"
event_ids = navigation_event_ids_by_user(username)
iter_update(NavigationEventAudit.get_db(), update_username, with_progress_bar(event_ids, len(event_ids)))
| from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.util.log import with_progress_bar
from corehq.util.couch import iter_update, DocUpdate
from django.core.management.base import BaseCommand
from auditcare.utils.export import navigation_event_ids_by_user
import logging
from auditcare.models import NavigationEventAudit
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = """Scrub a username from auditcare for GDPR compliance"""
def add_arguments(self, parser):
parser.add_argument('username', help="Username to scrub")
def handle(self, username, **options):
def update_username(event_dict):
audit_doc = NavigationEventAudit.wrap(event_dict)
audit_doc.user = new_username
event_dict['user'] = new_username
return DocUpdate(doc=audit_doc)
new_username = "Redacted User (GDPR)"
event_ids = navigation_event_ids_by_user(username)
iter_update(NavigationEventAudit.get_db(), update_username, with_progress_bar(event_ids, len(event_ids)))
|
Stop excluding bower because it is gone | 'use strict';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: path.join(__dirname, 'public'),
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.s?css$/,
loader: ExtractTextPlugin.extract('style', 'css', 'autoprefixer', 'sass')
},
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
},
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false}
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.ProvidePlugin({
fetch: 'whatwg-fetch'
})
]
};
| 'use strict';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: path.join(__dirname, 'public'),
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.s?css$/,
loader: ExtractTextPlugin.extract('style', 'css', 'autoprefixer', 'sass')
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
},
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false}
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.ProvidePlugin({
fetch: 'whatwg-fetch'
})
]
};
|
Remove unused php open and close tags | <?php
error_reporting(E_ALL & ~E_NOTICE);
foreach (glob("functions/*.php") as $filename) {
include $filename;
}
if ( isset($_GET['host']) && !empty($_GET['host'])) {
$data = [];
$hostname = mb_strtolower(get($_GET['host']));
$host = parse_hostname($hostname);
if ($host['port']) {
$port = $host['port'];
} else {
$port = get($_GET['port'], '443');
}
$host = $host['hostname'];
if ( !is_numeric($port) ) {
$port = 443;
}
$data["data"] = check_json($host,$port);
} elseif(isset($_GET['csr']) && !empty($_GET['csr'])) {
$data["data"]["chain"]["1"] = csr_parse_json($_GET['csr']);
} else {
$data["error"] = ["Host is required"];
}
$data = utf8encodeNestedArray($data);
if(isset($data["data"]["error"])) {
$data["error"] = $data["data"]["error"];
unset($data["data"]);
}
if ($_GET["type"] == "pretty") {
header('Content-Type: text/html');
echo "<pre>";
echo htmlspecialchars(json_encode($data,JSON_PRETTY_PRINT));
echo "</pre>";
} else {
header('Content-Type: application/json');
echo json_encode($data);
}
?>
| <?php
error_reporting(E_ALL & ~E_NOTICE);
foreach (glob("functions/*.php") as $filename) {
include $filename;
}
if ( isset($_GET['host']) && !empty($_GET['host'])) {
$data = [];
$hostname = mb_strtolower(get($_GET['host']));
$host = parse_hostname($hostname);
if ($host['port']) {
$port = $host['port'];
} else {
$port = get($_GET['port'], '443');
}
$host = $host['hostname'];
if ( !is_numeric($port) ) {
$port = 443;
}
$data["data"] = check_json($host,$port);
} elseif(isset($_GET['csr']) && !empty($_GET['csr'])) {
$data["data"]["chain"]["1"] = csr_parse_json($_GET['csr']);
} else {
$data["error"] = ["Host is required"];
}
$data = utf8encodeNestedArray($data);
if(isset($data["data"]["error"])) {
$data["error"] = $data["data"]["error"];
unset($data["data"]);
}
if ($_GET["type"] == "pretty") {
header('Content-Type: text/html');
echo "<pre>";
echo htmlspecialchars(json_encode($data,JSON_PRETTY_PRINT));
echo "</pre>";
?>
<?
} else {
header('Content-Type: application/json');
echo json_encode($data);
}
?>
|
Revert "Allow only one listener to be subscribed to the background store"
This reverts commit 598c160833271897c9f564b0bad7f71d2f8e39f3. | export default function createDevToolsStore(onDispatch) {
let currentState = {
committedState: {},
stagedActions: [],
computedStates: [],
skippedActions: {},
currentStateIndex: 0
};
let listeners = [];
let initiated = false;
function dispatch(action) {
if (action.type[0] !== '@') onDispatch(action);
return action;
}
function getState() {
return currentState;
}
function isSet() {
return initiated;
}
function setState(state) {
currentState = state;
listeners.forEach(listener => listener());
initiated = true;
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
return {
dispatch,
getState,
subscribe,
liftedStore: {
dispatch,
getState,
setState,
subscribe,
isSet
}
};
}
| export default function createDevToolsStore(onDispatch) {
let currentState = {
committedState: {},
stagedActions: [],
computedStates: [],
skippedActions: {},
currentStateIndex: 0
};
let handleChangeState = null;
let initiated = false;
function dispatch(action) {
if (action.type[0] !== '@') onDispatch(action);
return action;
}
function getState() {
return currentState;
}
function isSet() {
return initiated;
}
function setState(state) {
currentState = state;
if (handleChangeState) handleChangeState();
if (!initiated) initiated = true;
}
function subscribe(listener) {
handleChangeState = listener;
return function unsubscribe() {
handleChangeState = null;
};
}
return {
dispatch,
getState,
liftedStore: {
dispatch,
getState,
setState,
subscribe,
isSet
}
};
}
|
Store Alchemy emotion on MongoDB | import http from 'http';
import express from 'express';
import io from 'socket.io';
import bodyparser from 'body-parser';
import chatbot from './chatterbot/chatbotController.js';
import analyzerController from './controllers/analyzerController.js';
const routes = require('./config/routes.js');
const app = express();
const theServer = http.Server(app);
const ioServer = io(theServer);
const port = process.env.PORT || 1337;
app.use(express.static(`${__dirname}/../client`));
app.use(bodyparser);
routes(app);
ioServer.on('connection', (socket) => {
console.log('a user connected: ', socket.conn.id);
socket.on('message', (msg) => {
analyzerController.setAnalysis(msg);
chatbot.response(socket.conn.id, msg, (err, response) => {
if (err) { console.log(err); }
socket.emit('message', response);
});
});
socket.on('disconnect', () => { console.log('user disconnected'); });
});
theServer.listen(port, () => {
console.log('listening on localhost:', port);
});
| import http from 'http';
import express from 'express';
import io from 'socket.io';
import bodyparser from 'body-parser';
import chatbot from './chatterbot/chatbotController.js';
import analyzerController from './controllers/analyzerController.js';
const routes = require('./config/routes.js');
const app = express();
const theServer = http.Server(app);
const ioServer = io(theServer);
const port = process.env.PORT || 1337;
app.use(express.static(__dirname + '/../client'));
app.use(bodyparser);
routes(app);
ioServer.on('connection', (socket) => {
console.log('a user connected: ', socket);
let msgCount = 0;
socket.on('message', (msg) => {
analyzerController.setAnalysis(msg);
chatbot.response(socket.conn.id + msgCount.toString(), msg, (response) => {
socket.emit(response);
});
msgCount++;
});
});
theServer.listen(port, () => {
console.log('listening on localhost:', port);
});
|
Reformat bandwidth data return section | const chart = require('ascii-chart');
function pointsFromBandwidthData(values, numPoints) {
// Define vars
const len = values.length;
const points = [];
let i = 0;
let size;
// Split values into n points
if(numPoints < 2) {
points.push(values);
} else {
if(len % numPoints === 0) {
size = Math.floor(len / numPoints);
while (i < len) {
points.push(values.slice(i, i += size));
}
}
while (i < len) {
size = Math.ceil((len - i) / numPoints--);
points.push(values.slice(i, i += size));
}
}
// Return points
return points
// Calculate average value of each point
.map(point => Math.round(point.reduce((a,b) => a + b) / point.length))
// Convert bytes to megabytes
.map(bytes => Number((bytes / 1000000).toPrecision(3)));
}
module.exports = values => {
if(values && values.length) {
const points = pointsFromBandwidthData(values, 56);
return chart(points, {
width: 125,
height: 20,
padding: 0,
pointChar: '*',
negativePointChar: '.'
});
} else {
return '';
}
}
| const chart = require('ascii-chart');
function pointsFromBandwidthData(values, numPoints) {
// Define vars
const len = values.length;
const points = [];
let i = 0;
let size;
// Split values into n points
if(numPoints < 2) {
points.push(values);
} else {
if(len % numPoints === 0) {
size = Math.floor(len / numPoints);
while (i < len) {
points.push(values.slice(i, i += size));
}
}
while (i < len) {
size = Math.ceil((len - i) / numPoints--);
points.push(values.slice(i, i += size));
}
}
// Return points
const result = points
// Calculate average value of each point
.map(point => Math.round(point.reduce((a,b) => a + b) / point.length))
// Convert bytes to megabytes
.map(bytes => Number((bytes / 1000000).toPrecision(3)));
return result;
}
module.exports = values => {
if(values && values.length) {
const points = pointsFromBandwidthData(values, 56);
return chart(points, {
width: 125,
height: 20,
padding: 0,
pointChar: '*',
negativePointChar: '.'
});
} else {
return '';
}
}
|
Add event_type to the event constructor | from simple_es.identifier.identifies import Identifies
class DomainEvent():
"""
Base class for all domain driven events
TODO: Split logic around saving to a data store into a separate class
TODO: Restrict the ability to toggle recorded
"""
event_type = None
_identifier = None
_recorded = False
def __init__(self, identifier=None, event_type=None):
# Validate that identifier is an instance of an event Identifier
if not isinstance(identifier, Identifies):
raise TypeError('Event identifier must be an instance of the Identifies class',
identifier,
type(identifier))
# Validate that event type was set in a child
if event_type is None:
raise TypeError('Event type must be a string', event_type, type(event_type))
# Assign the identifier to the event
self._identifier = identifier
# Assign the type to the event
self.event_type = event_type
@property
def attributes(self):
"""
Filter out private member variables (names prefixed with an underscore)
"""
return {key: value for key, value
in self.__dict__.items()
if key.startswith('_') is False}
| from simple_es.identifier.identifies import Identifies
class DomainEvent():
"""
Base class for all domain driven events
TODO: Split logic around saving to a data store into a separate class
TODO: Restrict the ability to toggle recorded
"""
event_type = None
_identifier = None
_recorded = False
def __init__(self, identifier=None):
if not isinstance(identifier, Identifies):
raise TypeError('Event identifier must be an instance of the Identifies class', identifier)
self._identifier = identifier
@property
def attributes(self):
"""
Filter out private member variables (names prefixed with an underscore)
"""
return {key: value for key, value
in self.__dict__.items()
if key.startswith('_') is False}
|
Send email notification of important changes | 'use strict';
const schedule = require('node-schedule');
const jenkins = require('./lib/jenkins');
const redis = require('./lib/redis');
const gitter = require('./lib/gitter');
const sendgrid = require('./lib/sendgrid');
const pkg = require('./package.json');
console.log(`Staring ${pkg.name} v${pkg.version}`);
schedule.scheduleJob(process.env.CRON_INTERVAL, function() {
console.log('Running Cron Job...');
console.log('Fetching Jenkins nodes...');
jenkins.getComputers(function(err, nodes) {
if (err) { throw err; }
console.log(`Found ${nodes.length} Jenkins nodes.`);
console.log('Checking changed Jenkins nodes...');
redis.jenkinsChanged(nodes, function(err, changed) {
if (err) { throw err; }
console.log(`${changed.length} node(s) changed.`);
if (changed.length > 0) {
console.log('Posting to Gitter...');
gitter.post(changed, function(err) {
if (err) { throw err; }
console.log('Gitter: Ok!');
});
console.log('Notifying via Sendgrid...');
sendgrid.notify(changed, function(err) {
if (err) { throw err; }
console.log('Sendgrid: Ok!');
});
}
});
});
});
| 'use strict';
const redis = require('./lib/redis');
const jenkins = require('./lib/jenkins');
const gitter = require('./lib/gitter');
const schedule = require('node-schedule');
const pkg = require('./package.json');
console.log(`Staring ${pkg.name} v${pkg.version}`);
schedule.scheduleJob(process.env.CRON_INTERVAL, function() {
console.log('Running Cron Job...');
console.log('Fetching Jenkins nodes...');
jenkins.getComputers(function(err, nodes) {
if (err) { throw err; }
console.log(`Found ${nodes.length} Jenkins nodes.`);
console.log('Checking changed Jenkins nodes...');
redis.jenkinsChanged(nodes, function(err, changed) {
if (err) { throw err; }
console.log(`${changed.length} node(s) changed.`);
console.log('Posting to Gitter...');
gitter.post(changed, function(err) {
if (err) { throw err; }
console.log('Gitter: Ok!');
});
});
});
});
|
Add messageType to message factory | # coding: utf-8
import string
import factory
import random
from django.contrib.auth.models import User
from message.models import Message, MessageType
from test.utils import generate_string, lorem_ipsum
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = "Boy"
last_name = "Factory"
email = factory.LazyAttribute(
lambda a:
"{0}_{1}@example.com".format(a.first_name, a.last_name).lower())
username = factory.Sequence(lambda n: "username_%s" % n)
class MessageFactory(factory.Factory):
'''
Factory for messages
'''
FACTORY_FOR = Message
message = lorem_ipsum()
contact_first_name = factory.Sequence(lambda n: "user_%s" % n)
contact_last_name = factory.Sequence(lambda n: "name_%s" % n)
contact_mail = factory.LazyAttribute(
lambda a:
"{0}_{1}@example.com".format(
a.contact_first_name,
a.contact_last_name
).lower())
contact_phone = generate_string(str_len=10, src=string.digits)
user = factory.SubFactory(UserFactory)
messageType = random.randint(
MessageType.TYPE_REQUEST, MessageType.TYPE_INFO)
| # coding: utf-8
import string
import factory
from django.contrib.auth.models import User
from message.models import Message
from test.utils import generate_string, lorem_ipsum
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = "Boy"
last_name = "Factory"
email = factory.LazyAttribute(
lambda a:
"{0}_{1}@example.com".format(a.first_name, a.last_name).lower())
username = factory.Sequence(lambda n: "username_%s" % n)
class MessageFactory(factory.Factory):
'''
Factory for messages
'''
FACTORY_FOR = Message
message = lorem_ipsum()
contact_first_name = factory.Sequence(lambda n: "user_%s" % n)
contact_last_name = factory.Sequence(lambda n: "name_%s" % n)
contact_mail = factory.LazyAttribute(
lambda a:
"{0}_{1}@example.com".format(
a.contact_first_name,
a.contact_last_name
).lower())
contact_phone = generate_string(str_len=10, src=string.digits)
user = factory.SubFactory(UserFactory)
|
Add version constraint to collection-instances | Package.describe({
documentation: 'README.md',
git: 'https://github.com/hansoft/meteor-logger-mongo.git',
name: 'hansoft:logger-mongo',
summary: 'Store console.<log/warn/error> in mongodb.',
version: '1.0.0',
});
Package.onUse(function(api) {
api.versionsFrom('1.2');
api.use([
'check',
'ecmascript',
'mongo',
'underscore',
]);
api.use('insecure', ['client', 'server'], { weak: true });
api.use([
'dburles:mongo-collection-instances@0.3.4',
]);
api.addFiles('lib/logger-mongo.js');
api.addFiles('server/logger-mongo.js', 'server');
api.addFiles('client/logger-mongo.js', 'client');
api.export('Logger');
});
| Package.describe({
documentation: 'README.md',
git: 'https://github.com/hansoft/meteor-logger-mongo.git',
name: 'hansoft:logger-mongo',
summary: 'Store console.<log/warn/error> in mongodb.',
version: '1.0.0',
});
Package.onUse(function(api) {
api.versionsFrom('1.2');
api.use([
'check',
'ecmascript',
'mongo',
'underscore',
]);
api.use('insecure', ['client', 'server'], { weak: true });
api.use([
'dburles:mongo-collection-instances',
]);
api.addFiles('lib/logger-mongo.js');
api.addFiles('server/logger-mongo.js', 'server');
api.addFiles('client/logger-mongo.js', 'client');
api.export('Logger');
});
|
Fix no data error on cde dashboard
Possible related to http://jira.meteorite.bi/browse/SKU-1258. | var saikuWidgetComponent = BaseComponent.extend({
update : function() {
var myself=this;
var htmlId = "#" + myself.htmlObject;
if (myself.saikuFilePath.substr(0,1) == "/") {
myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 );
}
var parameters = {};
if (myself.parameters) {
_.each(myself.parameters, function(parameter) {
var k = parameter[0];
var v = parameter[1];
if (window.hasOwnProperty(v)) {
v = window[v];
}
parameters[k] = v;
});
}
if (myself.width) {
$(htmlId).width(myself.width);
}
if (myself.width) {
$(htmlId).height(myself.height);
}
if ("table" == myself.renderMode) {
$(htmlId).addClass('workspace_results');
var t = $("<div></div>");
$(htmlId).html(t);
htmlId = t;
}
var myClient = new SaikuClient({
server: "../../../../plugin/saiku/api",
path: "/cde-component"
});
myClient.execute({
file: myself.saikuFilePath,
htmlObject: htmlId,
render: myself.renderMode,
mode: myself.renderType,
zoom: true,
params: parameters
});
}
});
| var saikuWidgetComponent = BaseComponent.extend({
update : function() {
var myself=this;
var htmlId = "#" + myself.htmlObject;
if (myself.saikuFilePath.substr(0,1) == "/") {
myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 );
}
var parameters = {};
if (myself.parameters) {
_.each(myself.parameters, function(parameter) {
var k = parameter[0];
var v = parameter[1];
if (window.hasOwnProperty(v)) {
v = window[v];
}
parameters[k] = v;
});
}
if (myself.width) {
$(htmlId).width(myself.width);
}
if (myself.width) {
$(htmlId).height(myself.height);
}
if ("table" == myself.renderMode) {
$(htmlId).addClass('workspace_results');
var t = $("<div></div>");
$(htmlId).html(t);
htmlId = t;
}
var myClient = new SaikuClient({
server: "../../../plugin/saiku/api",
path: "/cde-component"
});
myClient.execute({
file: myself.saikuFilePath,
htmlObject: htmlId,
render: myself.renderMode,
mode: myself.renderType,
zoom: true,
params: parameters
});
}
});
|
Add comment to fix a bug | import React from 'react';
import isEmpty from 'lodash/isEmpty';
import SingleUnitOnMap from './SingleUnitOnMap';
import {sortByCondition} from '../helpers';
export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => {
let unitsInOrder = units.slice();
// Draw things in condition order
unitsInOrder = sortByCondition(unitsInOrder).reverse();
if(!isEmpty(unitsInOrder) && selectedUnitId) {
const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId);
const selectedUnit = unitsInOrder[index]; //FIXME: This fails if url parameter unitId does not exist
unitsInOrder.push(selectedUnit);
}
return(
<div className="units-on-map">
{
!isEmpty(unitsInOrder) && unitsInOrder.map(
(unit, index) =>
<SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={`${index}:${unit.id}`} openUnit={openUnit} />
)
}
</div>
);
};
export default UnitsOnMap;
| import React from 'react';
import isEmpty from 'lodash/isEmpty';
import SingleUnitOnMap from './SingleUnitOnMap';
import {sortByCondition} from '../helpers';
export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => {
let unitsInOrder = units.slice();
// Draw things in condition order
unitsInOrder = sortByCondition(unitsInOrder).reverse();
if(!isEmpty(unitsInOrder) && selectedUnitId) {
const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId);
const selectedUnit = unitsInOrder[index];
unitsInOrder.push(selectedUnit);
}
return(
<div className="units-on-map">
{
!isEmpty(unitsInOrder) && unitsInOrder.map(
(unit, index) =>
<SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={`${index}:${unit.id}`} openUnit={openUnit} />
)
}
</div>
);
};
export default UnitsOnMap;
|
Set html of the message displayed to user, instead of text. | $('form#submit-repo').submit(
function(evt){
evt.preventDefault();
var status = $('#status');
var repo = $('label[for="repo_name"]').text() + $('input[name="repo_name"]').val();
var text = 'Processing to create ' + repo + ' ...';
$('#status').children().remove();
var processing = $('<span id="processing">').text(text)
status.append(processing);
var xhr = $.post(
'/manage',
$(this).serialize(),
function(data, status_code, jqxhr) {
$('#status').children().remove()
status.append($('<p>').html(data.message));
}
);
$('input[name="repo_name"]').val('');
}
);
| $('form#submit-repo').submit(
function(evt){
evt.preventDefault();
var status = $('#status');
var repo = $('label[for="repo_name"]').text() + $('input[name="repo_name"]').val();
var text = 'Processing to create ' + repo + ' ...';
$('#status').children().remove();
var processing = $('<span id="processing">').text(text)
status.append(processing);
var xhr = $.post(
'/manage',
$(this).serialize(),
function(data, status_code, jqxhr) {
$('#status').children().remove()
status.append($('<p>').text(data.message));
}
);
$('input[name="repo_name"]').val('');
}
);
|
Add callback schema for Foursquare authentication | const Joi = require('joi')
exports.create = Joi.object({
location: Joi.object({
latitude: Joi.number().required(),
longitude: Joi.number().required()
}),
place: {
id: Joi.string(),
name: Joi.string()
},
visitor: {
message: Joi.string().required(),
name: Joi.string().allow('', null)
}
}).options({ stripUnknown: true })
exports.getAllQuery = Joi.object({
visitors: Joi.boolean()
}).options({ stripUnknown: true })
exports.callbackQuery = Joi.object({
code: Joi.string()
}).options({ stripUnknown: true })
exports.response = Joi.array().items(Joi.object({
location: Joi.object({
latitude: Joi.number().required(),
longitude: Joi.number().required()
}).rename('lat', 'latitude')
.rename('lng', 'longitude'),
name: Joi.string().required(),
placeId: Joi.string().required()
}).rename('place_id', 'placeId')
.options({ stripUnknown: true }))
exports.searchQuery = Joi.object({
location: Joi.string().required(),
keyword: Joi.string()
})
| const Joi = require('joi')
exports.create = Joi.object({
location: Joi.object({
latitude: Joi.number().required(),
longitude: Joi.number().required()
}),
place: {
id: Joi.string(),
name: Joi.string()
},
visitor: {
message: Joi.string().required(),
name: Joi.string().allow('', null)
}
}).options({ stripUnknown: true })
exports.getAllQuery = Joi.object({
visitors: Joi.boolean()
}).options({ stripUnknown: true })
exports.response = Joi.array().items(Joi.object({
location: Joi.object({
latitude: Joi.number().required(),
longitude: Joi.number().required()
}).rename('lat', 'latitude')
.rename('lng', 'longitude'),
name: Joi.string().required(),
placeId: Joi.string().required()
}).rename('place_id', 'placeId')
.options({ stripUnknown: true }))
exports.searchQuery = Joi.object({
location: Joi.string().required(),
keyword: Joi.string()
})
|
Replace util.inherits with class extends | 'use strict';
const { EventEmitter } = require('events');
const sinon = require('sinon');
class ReadlineStub extends EventEmitter {
constructor() {
super();
this.line = '';
this.input = new EventEmitter();
}
}
const stub = {};
Object.assign(stub, {
write: sinon.stub().returns(stub),
moveCursor: sinon.stub().returns(stub),
setPrompt: sinon.stub().returns(stub),
close: sinon.stub().returns(stub),
pause: sinon.stub().returns(stub),
resume: sinon.stub().returns(stub),
_getCursorPos: sinon.stub().returns({
cols: 0,
rows: 0,
}),
output: {
end: sinon.stub(),
mute: sinon.stub(),
unmute: sinon.stub(),
__raw__: '',
write(str) {
this.__raw__ += str;
},
},
});
Object.assign(ReadlineStub.prototype, stub);
module.exports = ReadlineStub;
| 'use strict';
const { EventEmitter } = require('events');
const util = require('util');
const sinon = require('sinon');
const stub = {};
Object.assign(stub, {
write: sinon.stub().returns(stub),
moveCursor: sinon.stub().returns(stub),
setPrompt: sinon.stub().returns(stub),
close: sinon.stub().returns(stub),
pause: sinon.stub().returns(stub),
resume: sinon.stub().returns(stub),
_getCursorPos: sinon.stub().returns({
cols: 0,
rows: 0,
}),
output: {
end: sinon.stub(),
mute: sinon.stub(),
unmute: sinon.stub(),
__raw__: '',
write(str) {
this.__raw__ += str;
},
},
});
const ReadlineStub = function () {
this.line = '';
this.input = new EventEmitter();
EventEmitter.apply(this, arguments);
};
util.inherits(ReadlineStub, EventEmitter);
Object.assign(ReadlineStub.prototype, stub);
module.exports = ReadlineStub;
|
Add protocol to hosts for CORS | import boto3
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Set CORS rules on the Notice and Comment attachment bucket'
def handle(self, *args, **options):
hosts = settings.ALLOWED_HOSTS
origins = ['http://' + host for host in hosts]
origins = origins + ['https://' + host for host in hosts]
session = boto3.Session(
aws_access_key_id=settings.ATTACHMENT_ACCESS_KEY_ID,
aws_secret_access_key=settings.ATTACHMENT_SECRET_ACCESS_KEY,
)
s3 = session.client('s3')
s3.put_bucket_cors(
Bucket=settings.ATTACHMENT_BUCKET,
CORSConfiguration={
'CORSRules': [
{
'AllowedMethods': ['GET', 'PUT'],
'AllowedOrigins': origins or ['*'],
'AllowedHeaders': ['*'],
},
],
},
)
| import boto3
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Set CORS rules on the Notice and Comment attachment bucket'
def handle(self, *args, **options):
session = boto3.Session(
aws_access_key_id=settings.ATTACHMENT_ACCESS_KEY_ID,
aws_secret_access_key=settings.ATTACHMENT_SECRET_ACCESS_KEY,
)
s3 = session.client('s3')
s3.put_bucket_cors(
Bucket=settings.ATTACHMENT_BUCKET,
CORSConfiguration={
'CORSRules': [
{
'AllowedMethods': ['GET', 'PUT'],
'AllowedOrigins': settings.ALLOWED_HOSTS or ['*'],
'AllowedHeaders': ['*'],
},
],
},
)
|
Add missing phrases for datatables bulk actions | <?php
declare(strict_types=1);
return [
'already_authenticated' => 'You are already authenticated!',
'import_complete' => 'Congrats! Import process completed.',
'resource_saved' => 'Congrats! Requested :resource [:identifier] saved successfully.',
'resource_deleted' => 'Done! Requested :resource [:identifier] deleted successfully.',
'resource_not_found' => 'Sorry! Requested :resource [:identifier] not found!',
'delete_confirmation_title' => 'Delete Confirmation',
'delete_confirmation_body' => 'Are you sure you want to delete :resource [:identifier]?',
'session_required' => 'You must login first!',
'token_mismatch' => 'The page has expired due to inactivity. Please refresh and try again.',
'invalid_phone' => 'Invalid phone number!',
'invalid_indexing_rule' => 'An indexing rule needs to return a boolean or a string.',
'no_records_selected' => 'No selected records!',
'records_deleted' => 'Records deleted!',
'records_activated' => 'Records activated!',
'records_deactivated' => 'Records deactivated!',
];
| <?php
declare(strict_types=1);
return [
'already_authenticated' => 'You are already authenticated!',
'import_complete' => 'Congrats! Import process completed.',
'resource_saved' => 'Congrats! Requested :resource [:identifier] saved successfully.',
'resource_deleted' => 'Done! Requested :resource [:identifier] deleted successfully.',
'resource_not_found' => 'Sorry! Requested :resource [:identifier] not found!',
'delete_confirmation_title' => 'Delete Confirmation',
'delete_confirmation_body' => 'Are you sure you want to delete :resource [:identifier]?',
'session_required' => 'You must login first!',
'token_mismatch' => 'The page has expired due to inactivity. Please refresh and try again.',
'invalid_phone' => 'Invalid phone number!',
'invalid_indexing_rule' => 'An indexing rule needs to return a boolean or a string.',
'no_records_selected' => 'No selected records!',
'records_deleted' => 'Records deleted!',
];
|
Make it work in recursion too | 'use strict';
/**
* Require modules.
*/
var isObject = require('is-object');
var clone = require('clone');
/**
* Pick values from object except the given keys.
*
* @param {object} obj
* @param {array|string}
*
* @return {object}
*/
module.exports = function except(obj, keys) {
if (!isObject(obj)) {
throw new Error('`obj` should be object');
}
if (typeof keys === 'string') {
keys = [keys];
}
if (keys instanceof Array === false) {
throw new Error('`keys` should be array');
}
var result = clone(obj);
for (var i = 0, l = keys.length; i < l; i++) {
var parts = keys[i].split('.');
var first = parts.shift();
var value = result[first];
if (isObject(value) && parts.length > 0) {
result = except(result[first], parts);
if (isObject(result[first]) && !Object.keys(result[first]).length) {
delete result[first];
}
} else {
delete result[first];
}
}
return result;
};
| 'use strict';
/**
* Require modules.
*/
var isObject = require('is-object');
var clone = require('clone');
/**
* Pick values from object except the given keys.
*
* @param {object} obj
* @param {array|string}
*
* @return {object}
*/
module.exports = function except(obj, keys) {
if (!isObject(obj)) {
throw new Error('`obj` should be object');
}
if (typeof keys === 'string') {
keys = [keys];
}
if (keys instanceof Array === false) {
throw new Error('`keys` should be array');
}
var result = clone(obj);
for (var i = 0, l = keys.length; i < l; i++) {
var parts = keys[i].split('.');
var first = parts.shift();
var value = result[first];
if (isObject(value) && parts.length > 0) {
except(result[first], parts);
if (isObject(result[first]) && !Object.keys(result[first]).length) {
delete result[first];
}
} else {
delete result[first];
}
}
return result;
};
|
Add blank line between README and CHANGES in long_description | import codecs
from setuptools import setup
lines = codecs.open('README', 'r', 'utf-8').readlines()[3:]
lines.append('\n')
lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:])
desc = ''.join(lines).lstrip()
import translitcodec
version = translitcodec.__version__
setup(name='translitcodec',
version=version,
description='Unicode to 8-bit charset transliteration codec',
long_description=desc,
long_description_content_type='text/x-rst',
author='Jason Kirtland',
author_email='jek@discorporate.us',
url='https://github.com/claudep/translitcodec',
packages=['translitcodec'],
license='MIT License',
python_requires='>=3',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
],
)
| import codecs
from setuptools import setup
lines = codecs.open('README', 'r', 'utf-8').readlines()[3:]
lines.extend(codecs.open('CHANGES', 'r', 'utf-8').readlines()[1:])
desc = ''.join(lines).lstrip()
import translitcodec
version = translitcodec.__version__
setup(name='translitcodec',
version=version,
description='Unicode to 8-bit charset transliteration codec',
long_description=desc,
author='Jason Kirtland',
author_email='jek@discorporate.us',
url='https://github.com/claudep/translitcodec',
packages=['translitcodec'],
license='MIT License',
python_requires='>=3',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
],
)
|
Fix join on room with currently playing song bug | const initialState = {
time: 0,
songIndex: 0,
isPlaying: false,
isPaused: false
}
export default function player(state = initialState, action) {
switch (action.type) {
case 'UPDATE_CURRENT_PLAYER_TIME':
if (!state.isPaused) {
return Object.assign({}, state, {
time: action.time,
isPlaying: true
})
}
else {
return Object.assign({}, state, {
time: action.time,
isPlaying: false
})
}
case 'UPDATE_CURRENT_PLAYLIST_SONG':
return Object.assign({}, state, {
songIndex: action.songIndex
})
case 'SET_IS_PLAYING':
return Object.assign({}, state, {
isPlaying: true,
isPaused: false
})
case 'SET_NOT_PLAYING':
return Object.assign({}, state, {
isPlaying: false,
isPaused: true
})
default:
return state
}
}
| const initialState = {
time: 0,
songIndex: 0,
isPlaying: false
}
export default function player(state = initialState, action) {
switch (action.type) {
case 'UPDATE_CURRENT_PLAYER_TIME':
if (state.isPlaying) {
return Object.assign({}, state, {
time: action.time,
isPlaying: true
})
}
else {
return Object.assign({}, state, {
time: action.time,
isPlaying: false
})
}
case 'UPDATE_CURRENT_PLAYLIST_SONG':
return Object.assign({}, state, {
songIndex: action.songIndex
})
case 'SET_IS_PLAYING':
return Object.assign({}, state, {
isPlaying: true
})
case 'SET_NOT_PLAYING':
return Object.assign({}, state, {
isPlaying: false
})
default:
return state
}
}
|
Change is_luci default to True.
Most things should be on LUCI now, so this better reflects reality, and
might help shakeout any obsolete non-LUCI handling.
Bug: 993137
Recipe-Nontrivial-Roll: build
Recipe-Nontrivial-Roll: build_limited_scripts_slave
Recipe-Nontrivial-Roll: chromiumos
Recipe-Nontrivial-Roll: depot_tools
Recipe-Nontrivial-Roll: infra
Recipe-Nontrivial-Roll: release_scripts
Recipe-Nontrivial-Roll: skia
Change-Id: I5d43654d1f8ef2d980a3c8892e718b102e6cbbe1
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/recipes-py/+/1750109
Auto-Submit: Michael Moss <9cc3612fe50cad025435ae878219b6203d6b641d@chromium.org>
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Commit-Queue: Michael Moss <9cc3612fe50cad025435ae878219b6203d6b641d@chromium.org> | # Copyright 2017 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
from recipe_engine import recipe_api
class RuntimeApi(recipe_api.RecipeApi):
"""This module assists in experimenting with production recipes.
For example, when migrating builders from Buildbot to pure LUCI stack.
"""
def __init__(self, properties, **kwargs):
super(RuntimeApi, self).__init__(**kwargs)
self._properties = properties
@property
def is_luci(self):
"""True if this recipe is currently running on LUCI stack.
Should be used only during migration from Buildbot to LUCI stack.
"""
return bool(self._properties.get('is_luci', True))
@property
def is_experimental(self):
"""True if this recipe is currently running in experimental mode.
Typical usage is to modify steps which produce external side-effects so that
non-production runs of the recipe do not affect production data.
Examples:
* Uploading to an alternate google storage file name when in non-prod mode
* Appending a 'non-production' tag to external RPCs
"""
return bool(self._properties.get('is_experimental', False))
| # Copyright 2017 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
from recipe_engine import recipe_api
class RuntimeApi(recipe_api.RecipeApi):
"""This module assists in experimenting with production recipes.
For example, when migrating builders from Buildbot to pure LUCI stack.
"""
def __init__(self, properties, **kwargs):
super(RuntimeApi, self).__init__(**kwargs)
self._properties = properties
@property
def is_luci(self):
"""True if this recipe is currently running on LUCI stack.
Should be used only during migration from Buildbot to LUCI stack.
"""
return bool(self._properties.get('is_luci', False))
@property
def is_experimental(self):
"""True if this recipe is currently running in experimental mode.
Typical usage is to modify steps which produce external side-effects so that
non-production runs of the recipe do not affect production data.
Examples:
* Uploading to an alternate google storage file name when in non-prod mode
* Appending a 'non-production' tag to external RPCs
"""
return bool(self._properties.get('is_experimental', False))
|
Add --force option to module:publish command | <?php
declare(strict_types=1);
namespace Cortex\Fort\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:publish:fort {--force : Overwrite any existing files.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Cortex Fort Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->warn('Publish cortex/fort:');
$this->call('vendor:publish', ['--tag' => 'rinvex-fort-config', '--force' => $this->option('force')]);
$this->call('vendor:publish', ['--tag' => 'cortex-fort-views', '--force' => $this->option('force')]);
$this->call('vendor:publish', ['--tag' => 'cortex-fort-lang', '--force' => $this->option('force')]);
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Fort\Console\Commands;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:publish:fort';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish Cortex Fort Resources.';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->warn('Publish cortex/fort:');
$this->call('vendor:publish', ['--tag' => 'rinvex-fort-config']);
$this->call('vendor:publish', ['--tag' => 'cortex-fort-views']);
$this->call('vendor:publish', ['--tag' => 'cortex-fort-lang']);
}
}
|
Make subpage_urls a property on RoutablePageTest | from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
| from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
Comment the main compiler script | #!/usr/bin/env node
/*
* A PlainScript Compiler
*
* This is a command line application that compiles a PlainScript program from
* a file. There are three options:
*
* ./plainscript.js -a <filename>
* writes out the AST and stops
*
* ./plainscript.js -i <filename>
* writes the decorated AST then stops
*
* ./plainscript.js <filename>
* compiles the PlainScript program to JavaScript, writing the generated
* JavaScript code to standard output.
*
* ./plainscript.js -o <filename>
* optimizes the intermediate code before generating target JavaScript.
*
* Output of the AST and decorated AST uses the object inspection functionality
* built into Node.js.
*/
const argv = require('yargs')
.usage('$0 [-a] [-o] [-i] filename')
.boolean(['a', 'o', 'i'])
.describe('a', 'show abstract syntax tree after parsing then stop')
.describe('o', 'do optimizations')
.describe('i', 'generate and show the decorated abstract syntax tree then stop')
.demand(1)
.argv;
const fs = require('fs');
const util = require('util');
const parse = require('./syntax/parser');
const generate = require('./backend/javascript-generator');
fs.readFile(argv._[0], 'utf-8', (err, text) => {
let program = parse(text);
if (argv.a) {
console.log(util.inspect(program, { depth: null }));
return;
}
program.analyze();
if (argv.o) {
program = program.optimize();
}
if (argv.i) {
console.log(util.inspect(program, { depth: null }));
return;
}
generate(program);
});
| #!/usr/bin/env node
const argv = require('yargs')
.usage('$0 [-a] [-o] [-i] filename')
.boolean(['a', 'o', 'i'])
.describe('a', 'show abstract syntax tree after parsing then stop')
.describe('o', 'do optimizations')
.describe('i', 'generate and show the decorated abstract syntax tree then stop')
.demand(1)
.argv;
const fs = require('fs');
const util = require('util');
const parse = require('./syntax/parser');
const generate = require('./backend/javascript-generator');
fs.readFile(argv._[0], 'utf-8', (err, text) => {
let program = parse(text);
if (argv.a) {
console.log(util.inspect(program, { depth: null }));
return;
}
program.analyze();
if (argv.o) {
program = program.optimize();
}
if (argv.i) {
console.log(util.inspect(program, { depth: null }));
return;
}
generate(program);
});
|
Fix deprecated API warning in buffalo packr
Signed-off-by: Elliot Murphy <014ce8fab4ab9f8a957bfe9f974379093994de97@users.noreply.github.com> | package models
import (
"log"
"github.com/gobuffalo/envy"
"github.com/gobuffalo/packr/v2"
"github.com/gobuffalo/pop"
"github.com/nleof/goyesql"
)
// DB is a connection to your database to be used
// throughout your application.
var DB *pop.Connection
// Q is a map of SQL queries
var Q goyesql.Queries
func init() {
var err error
env := envy.Get("GO_ENV", "development")
DB, err = pop.Connect(env)
if err != nil {
log.Fatal(err)
}
pop.Debug = env == "development"
box := packr.New("./sql", "./sql")
sql, err := box.Find("queries.sql")
if err != nil {
log.Fatal(err)
}
Q = goyesql.MustParseBytes(sql)
}
| package models
import (
"log"
"github.com/gobuffalo/envy"
"github.com/gobuffalo/packr/v2"
"github.com/gobuffalo/pop"
"github.com/nleof/goyesql"
)
// DB is a connection to your database to be used
// throughout your application.
var DB *pop.Connection
// Q is a map of SQL queries
var Q goyesql.Queries
func init() {
var err error
env := envy.Get("GO_ENV", "development")
DB, err = pop.Connect(env)
if err != nil {
log.Fatal(err)
}
pop.Debug = env == "development"
box := packr.New("./sql", "./sql")
sql, err := box.MustBytes("queries.sql")
if err != nil {
log.Fatal(err)
}
Q = goyesql.MustParseBytes(sql)
}
|
Modify codes to avoid redundant function call | package com.example.andrewhanks.myapplication.chainofresponsibility;
abstract class Handler {
protected Handler next;
Handler(Handler next) {
this.next = next;
}
void doNext(char c) {
if (next != null) {
next.handle(c);
}
}
abstract void handle(char c);
}
class SymbolHandler extends Handler {
SymbolHandler(Handler next) {
super(next);
}
void handle(char c) {
System.out.println("Symbol has been handled");
doNext(c);
}
}
class CharacterHandler extends Handler {
CharacterHandler(Handler next) {
super(next);
}
void handle(char c) {
if (Character.isLetter(c)) {
System.out.println("Character has been handled");
} else {
doNext(c);
}
}
}
class DigitHandler extends Handler {
DigitHandler(Handler next) {
super(next);
}
void handle(char c) {
if (Character.isDigit(c)) {
System.out.println("Digit has been handled");
} else {
doNext(c);
}
}
} | package com.example.andrewhanks.myapplication.chainofresponsibility;
abstract class Handler {
protected Handler next;
Handler(Handler next) {
this.next = next;
}
void doNext(char c) {
if (next != null) {
next.handle(c);
}
}
abstract void handle(char c);
}
class SymbolHandler extends Handler {
SymbolHandler(Handler next) {
super(next);
}
void handle(char c) {
System.out.println("Symbol has been handled");
doNext(c);
}
}
class CharacterHandler extends Handler {
CharacterHandler(Handler next) {
super(next);
}
void handle(char c) {
if (Character.isLetter(c)) {
System.out.println("Character has been handled");
}
doNext(c);
}
}
class DigitHandler extends Handler {
DigitHandler(Handler next) {
super(next);
}
void handle(char c) {
if (Character.isDigit(c)) {
System.out.println("Digit has been handled");
}
doNext(c);
}
} |
Switch to Space.getenv for default envs | let env = Space.getenv.multi({
password: ['EXAMPLE_ORG_PASSWORD', '1234', 'string'],
email: ['EXAMPLE_ORG_EMAIL', 'example@email.com', 'string']
});
let createExampleOrg = function() {
let byEmail = { 'emails.address': env.email };
if (Meteor.users.find(byEmail).count() === 0) {
Donations.app.send(new Donations.RegisterOrganization({
targetId: new Guid(),
name: 'My Example Organization',
password: new Password(SHA256(env.password)),
country: new Country('AT'),
contact: new Donations.Contact({
email: new EmailAddress(env.email),
name: 'Dominik Guzei',
phone: '+43 676 9222862'
})
}));
}
};
Donations.setupDevData = function() {
createExampleOrg();
};
|
let createExampleOrg = function() {
let byEmail = { 'emails.address': process.env.EXAMPLE_ORG_EMAIL };
if (Meteor.users.find(byEmail).count() === 0) {
Donations.app.send(new Donations.RegisterOrganization({
targetId: new Guid(),
name: 'My Example Organization',
password: new Password(SHA256(process.env.EXAMPLE_ORG_PASSWORD)),
country: new Country('AT'),
contact: new Donations.Contact({
email: new EmailAddress(process.env.EXAMPLE_ORG_EMAIL),
name: 'Dominik Guzei',
phone: '+43 676 9222862'
})
}));
}
};
Donations.setupDevData = function() {
createExampleOrg();
};
|
Fix broken twitter avatars
- services.twitter.profile_image_url_https field wasn't being published | privacyOptions = { // true means exposed
_id: true,
commentCount: true,
createdAt: true,
email_hash: true,
isInvited: true,
karma: true,
postCount: true,
slug: true,
username: true,
'profile.name': true,
'profile.notifications': true,
'profile.bio': true,
'profile.github': true,
'profile.site': true,
'profile.twitter': true,
'services.twitter.profile_image_url': true,
'services.twitter.profile_image_url_https': true,
'services.facebook.id': true,
'services.twitter.screenName': true,
'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code
'votes.downvotedComments': true,
'votes.downvotedPosts': true,
'votes.upvotedComments': true,
'votes.upvotedPosts': true
};
// minimum required properties to display avatars
avatarOptions = {
_id: true,
email_hash: true,
slug: true,
username: true,
'profile.name': true,
'profile.github': true,
'profile.twitter': true,
'services.twitter.profile_image_url': true,
'services.facebook.id': true,
'services.twitter.screenName': true,
'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code
}
| privacyOptions = { // true means exposed
_id: true,
commentCount: true,
createdAt: true,
email_hash: true,
isInvited: true,
karma: true,
postCount: true,
slug: true,
username: true,
'profile.name': true,
'profile.notifications': true,
'profile.bio': true,
'profile.github': true,
'profile.site': true,
'profile.twitter': true,
'services.twitter.profile_image_url': true,
'services.facebook.id': true,
'services.twitter.screenName': true,
'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code
'votes.downvotedComments': true,
'votes.downvotedPosts': true,
'votes.upvotedComments': true,
'votes.upvotedPosts': true
};
// minimum required properties to display avatars
avatarOptions = {
_id: true,
email_hash: true,
slug: true,
username: true,
'profile.name': true,
'profile.github': true,
'profile.twitter': true,
'services.twitter.profile_image_url': true,
'services.facebook.id': true,
'services.twitter.screenName': true,
'services.github.screenName': true, // Github is not really used, but there are some mentions to it in the code
}
|
Add leading to zeros to single digit | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
var tw = 1500000;
function getTimeRemaining(consumed = 0) {
var t = tw - consumed;
tw = t;
var minute = Math.floor((t/1000/60) % 60);
var seconds = Math.floor((t/1000) % 60);
return {
minute, seconds
};
}
function initializedClock() {
var timeInterval = setInterval(() => {
var timex = getTimeRemaining(1000);
console.log(timex.minute,' : ',('0' + timex.seconds).slice(-2));
if (timex.t <= 0) {
clearInterval(timeInterval);
}
}, 1000);
}
initializedClock();
export default App;
| import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
var tw = 1500000;
function getTimeRemaining(consumed = 0) {
var t = tw - consumed;
tw = t;
var minute = Math.floor((t/1000/60) % 60);
var seconds = Math.floor((t/1000) % 60);
return {
minute, seconds
};
}
function initializedClock() {
var timeInterval = setInterval(() => {
var timex = getTimeRemaining(1000);
console.log(timex.minute,' : ',timex.seconds);
if (timex.t <= 0) {
clearInterval(timeInterval);
}
}, 1000);
}
initializedClock();
export default App;
|
Correct comments around license header | /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
// === Files in this section do not contain FOAM models
IGNORE('lib/dao_test.js');
// TODO: when genJava allows: IGNORE('com/google/foam/demos');
IGNORE('com/google/net/proto_gen.js');
IGNORE('com/google/foam/demos/tabata/main.js');
IGNORE('com/google/foam/experimental/Promise_test.js');
// these files depend on global objects and should not be loaded by foamlink
IGNORE('com/google/foam/demos/u2');
// === Files in this section should be processed by foamlink
// but cannot be due to code invoked during loading
// depends on instance variable 'this.SomeSpecialType'
MANUAL('test/Foo.js', [
'test.Foo', 'test.Person',
'test.Bar', 'test.Address',
'test.DayOfWeek', 'test.User',
'test.SomeSpecialType',
'test.SpecialProperty',
'test.me.AnEnum',
'test.FooRefinement'
]);
// foamlink proxy value can't be used as primitive
MANUAL('foam/swift/dao/CachingDAO.js', [
'foam.swift.dao.CachingDAO'
]);
MANUAL('foam/swift/ui/DAOTableViewSource.js', [
'foam.swift.ui.DAOTableViewSource.js'
]);
| // /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
// === Files in this section do not contain FOAM models
IGNORE('lib/dao_test.js');
// TODO: when genJava allows: IGNORE('com/google/foam/demos');
IGNORE('com/google/net/proto_gen.js');
IGNORE('com/google/foam/demos/tabata/main.js');
IGNORE('com/google/foam/experimental/Promise_test.js');
// these files depend on global objects and should not be loaded by foamlink
IGNORE('com/google/foam/demos/u2');
// === Files in this section should be processed by foamlink
// but cannot be due to code invoked during loading
// depends on instance variable 'this.SomeSpecialType'
MANUAL('test/Foo.js', [
'test.Foo', 'test.Person',
'test.Bar', 'test.Address',
'test.DayOfWeek', 'test.User',
'test.SomeSpecialType',
'test.SpecialProperty',
'test.me.AnEnum',
'test.FooRefinement'
]);
// foamlink proxy value can't be used as primitive
MANUAL('foam/swift/dao/CachingDAO.js', [
'foam.swift.dao.CachingDAO'
]);
MANUAL('foam/swift/ui/DAOTableViewSource.js', [
'foam.swift.ui.DAOTableViewSource.js'
]);
|
Remove call to `withFactories` method
See #66
I have kept the `setupUp` method in place for convenience. | <?php
namespace Spatie\Skeleton\Tests;
use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\Skeleton\SkeletonServiceProvider;
class TestCase extends Orchestra
{
public function setUp(): void
{
parent::setUp();
//
}
protected function getPackageProviders($app)
{
return [
SkeletonServiceProvider::class,
];
}
public function getEnvironmentSetUp($app)
{
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
/*
include_once __DIR__.'/../database/migrations/create_skeleton_table.php.stub';
(new \CreatePackageTable())->up();
*/
}
}
| <?php
namespace Spatie\Skeleton\Tests;
use Orchestra\Testbench\TestCase as Orchestra;
use Spatie\Skeleton\SkeletonServiceProvider;
class TestCase extends Orchestra
{
public function setUp(): void
{
parent::setUp();
$this->withFactories(__DIR__.'/database/factories');
}
protected function getPackageProviders($app)
{
return [
SkeletonServiceProvider::class,
];
}
public function getEnvironmentSetUp($app)
{
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
/*
include_once __DIR__.'/../database/migrations/create_skeleton_table.php.stub';
(new \CreatePackageTable())->up();
*/
}
}
|
Update to new Armourer's Workshop API | package net.mcft.copy.betterstorage.addon.armourersworkshop;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderHandler;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderManager;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentPart;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentType;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataHandler;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataManager;
import com.mojang.authlib.GameProfile;
public class AWDataManager implements IEquipmentDataManager, IEquipmentRenderManager {
@Override
public void onLoad(IEquipmentDataHandler dataHandler) {
AWAddon.dataHandler = dataHandler;
}
@Override
public void onLoad(IEquipmentRenderHandler renderHandler) {
AWAddon.renderHandler = renderHandler;
}
@Override
public void onRenderEquipment(Entity entity, EnumEquipmentType armourType) { }
@Override
public void onRenderEquipmentPart(Entity entity, EnumEquipmentPart armourPart) { }
@Override
public void onRenderMannequin(TileEntity TileEntity, GameProfile gameProfile) { }
}
| package net.mcft.copy.betterstorage.addon.armourersworkshop;
import net.minecraft.entity.Entity;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderHandler;
import riskyken.armourersWorkshop.api.client.render.IEquipmentRenderManager;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentPart;
import riskyken.armourersWorkshop.api.common.equipment.EnumEquipmentType;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataHandler;
import riskyken.armourersWorkshop.api.common.equipment.IEquipmentDataManager;
public class AWDataManager implements IEquipmentDataManager, IEquipmentRenderManager {
@Override
public void onLoad(IEquipmentDataHandler dataHandler) {
AWAddon.dataHandler = dataHandler;
}
@Override
public void onLoad(IEquipmentRenderHandler renderHandler) {
AWAddon.renderHandler = renderHandler;
}
@Override
public void onRenderEquipment(Entity entity, EnumEquipmentType armourType) {
}
@Override
public void onRenderEquipmentPart(Entity entity, EnumEquipmentPart armourPart) {
}
} |
Update start process to reflect new path for /cmd | import subprocess
import sys
import os
import setup_util
import time
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
subprocess.call("go get -u github.com/robfig/revel/revel", shell=True, cwd="revel")
subprocess.call("go build -o bin/revel github.com/robfig/revel/revel", shell=True, cwd="revel")
subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'revel' in line and 'run-tests' not in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
return 0
| import subprocess
import sys
import os
import setup_util
import time
def start(args):
setup_util.replace_text("revel/src/benchmark/conf/app.conf", "tcp\(.*:3306\)", "tcp(" + args.database_host + ":3306)")
subprocess.call("go get github.com/robfig/revel/cmd", shell=True, cwd="revel")
subprocess.call("go build -o bin/revel github.com/robfig/revel/cmd", shell=True, cwd="revel")
subprocess.Popen("bin/revel run benchmark prod".rsplit(" "), cwd="revel")
return 0
def stop():
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'revel' in line and 'run-tests' not in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
return 0
|
Use campaign topic for prompt | 'use strict';
const mongoose = require('mongoose');
const helpers = require('../lib/helpers');
/**
* Schema.
*/
const userSchema = new mongoose.Schema({
_id: String,
topic: String,
campaignId: Number,
signupStatus: String,
});
/**
* Prompt user to signup for given campaign ID.
*/
userSchema.methods.promptSignupForCampaignId = function (campaignId) {
this.topic = `campaign_${this.campaignId}`;
this.campaignId = campaignId;
this.signupStatus = 'prompt';
return this.save();
};
/**
* Post signup for current campaign and set it as the topic.
*/
userSchema.methods.postSignup = function () {
// TODO: Post to DS API
this.signupStatus = 'doing';
return this.save();
};
/**
* Unset current campaign and reset topic to random.
*/
userSchema.methods.declineSignup = function () {
this.campaignId = null;
this.signupStatus = null;
this.topic = 'random';
return this.save();
};
module.exports = mongoose.model('users', userSchema);
| 'use strict';
const mongoose = require('mongoose');
const helpers = require('../lib/helpers');
/**
* Schema.
*/
const userSchema = new mongoose.Schema({
_id: String,
topic: String,
campaignId: Number,
});
/**
* Prompt user to signup for given campaign ID.
*/
userSchema.methods.promptSignupForCampaignId = function (campaignId) {
this.topic = 'campaign_select';
this.campaignId = campaignId;
return this.save();
};
/**
* Post signup for current campaign and set it as the topic.
*/
userSchema.methods.postSignup = function () {
// TODO: Post to DS API
this.topic = `campaign_${this.campaignId}`;
return this.save();
};
/**
* Unset current campaign and reset topic to random.
*/
userSchema.methods.declineSignup = function () {
this.campaignId = null;
this.topic = 'random';
return this.save();
};
module.exports = mongoose.model('users', userSchema);
|
Check notification setting before displaying notification. | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import net.simonvt.cathode.common.util.WakeLock;
import net.simonvt.cathode.settings.Settings;
public class NotificationReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if (Settings.get(context).getBoolean(Settings.NOTIFICACTIONS_ENABLED, false)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PendingResult pendingResult = goAsync();
NotificationHelper.displayNotifications(context);
NotificationHelper.scheduleNextNotification(context);
pendingResult.finish();
} else {
WakeLock.acquire(context, NotificationService.LOCK_TAG);
NotificationService.start(context);
}
}
}
}
| /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import net.simonvt.cathode.common.util.WakeLock;
public class NotificationReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PendingResult pendingResult = goAsync();
NotificationHelper.displayNotifications(context);
NotificationHelper.scheduleNextNotification(context);
pendingResult.finish();
} else {
WakeLock.acquire(context, NotificationService.LOCK_TAG);
NotificationService.start(context);
}
}
}
|
Create json object rather than forming the strings ourselves | // Decodes data received
function decode(content){
var lsRegExp = /\%20/g;
var lsRegExp2 = /\%2B/g;
content = String(unescape(content)).replace(lsRegExp, " ");
content = content.replace(lsRegExp2, "+")
return content;
}
// Encodes data to be sent
function encode(content) {
var lsRegExp = new RegExp(" ","gim");
var lsRegExp2 = /\+/g;
content = String(escape(content)).replace(lsRegExp, "%20");
content = content.replace(lsRegExp2, "%2B");
return content;
}
// Formats the data into a basic json format
function toJSON(content) {
var jsonObj = new Object();
jsonObj.name = "BeginToReason";
jsonObj.pkg = "User";
jsonObj.project = "Teaching_Project";
jsonObj.content = content;
jsonObj.parent = "undefined";
jsonObj.type = "f";
return JSON.stringify(jsonObj);
// return '{"name":"' + "BeginToReason" + '","pkg":"User","project":"Teaching_Project","content":"' + content + '","parent":"undefined","type":"f"}';
} | // Decodes data received
function decode(content){
var lsRegExp = /\%20/g;
var lsRegExp2 = /\%2B/g;
content = String(unescape(content)).replace(lsRegExp, " ");
content = content.replace(lsRegExp2, "+")
return content;
}
// Encodes data to be sent
function encode(content) {
var lsRegExp = new RegExp(" ","gim");
var lsRegExp2 = /\+/g;
content = String(escape(content)).replace(lsRegExp, "%20");
content = content.replace(lsRegExp2, "%2B");
return content;
}
// Formats the data into a basic json format
function toJSON(content) {
return'{"name":"' + "BeginToReason" + '","pkg":"User","project":"Teaching_Project","content":"' + content + '","parent":"undefined","type":"f"}';
} |
Update crel to latest version from github.com/KoryNunn/crel | (e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],l=a.attrMap[l]||l,o(l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(e):this.crel=e}); | (e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],o(l=a.attrMap[l]||l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(()=>e):this.crel=e}); |
Fix the incorrect URL being generated | <?php
class Email {
public $db = null;
public $email = '';
public $from = 'luke@lcahill.co.uk';
public $subject = 'Note Keeper - please confirm your email.';
public $message = '';
public $userId = '';
function __construct($email, $userId) {
$this->email = $email;
$this->userId = $userId;
require_once '../db-connect.inc.php';
$this->db = Database::ConnectDb();
}
function constructConfirmLink() {
$date = new DateTime();
$timestamp = $date->getTimestamp();
$confirm = md5($timestamp);
$stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId");
$stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId));
$url = $_SERVER['SERVER_NAME'];
$link = 'http://' . $url . '/notes/confirm.php?hash=' . $confirm . '&user=' . $this->userId;
$this->message = 'Please follow this link to confirm your account <a href="' . $link . '">' . $link . '</a>';
$this->sendEmail();
}
function sendEmail() {
mail($this->email, $this->subject, $this->message);
}
}
?> | <?php
class Email {
public $db = null;
public $email = '';
public $from = 'luke@lcahill.co.uk';
public $subject = 'Note Keeper - please confirm your email.';
public $message = '';
public $userId = '';
function __construct($email, $userId) {
$this->email = $email;
$this->userId = $userId;
require_once '../db-connect.inc.php';
$this->db = Database::ConnectDb();
}
function constructConfirmLink() {
$date = new DateTime();
$timestamp = $date->getTimestamp();
$confirm = md5($timestamp);
$stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId");
$stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId));
$url = $_SERVER['SERVER_NAME'];
$link = 'http://' . $url . '/notes/includes/email-confirmation/confirm.php?hash=' . $this->userId . '&user=' . $this->userId;
$this->message = 'Please follow this link to confirm your account <a href="' . $link . '">' . $link . '</a>';
$this->sendEmail();
}
function sendEmail() {
mail($this->email, $this->subject, $this->message);
}
}
?> |
Fix storage_access in the test config | from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this as an example, make sure to either
# 1) create a local `user_opts.py`, or
# 2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value
# (i.e., user_opts['swan']['username'] -> 'your_username')
from .user_opts import user_opts
config = Config(
executors=[
ThreadPoolExecutor(
label='local_threads_globus',
storage_access=[GlobusScheme(
endpoint_uuid=user_opts['globus']['endpoint'],
endpoint_path=user_opts['globus']['path']
)],
working_dir=user_opts['globus']['path']
)
],
run_dir=get_rundir()
)
| from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this as an example, make sure to either
# 1) create a local `user_opts.py`, or
# 2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value
# (i.e., user_opts['swan']['username'] -> 'your_username')
from .user_opts import user_opts
config = Config(
executors=[
ThreadPoolExecutor(
label='local_threads_globus',
storage_access=[GlobusScheme(
endpoint_uuid=user_opts['globus']['endpoint'],
endpoint_path=user_opts['globus']['path']
)[,
working_dir=user_opts['globus']['path']
)
],
run_dir=get_rundir()
)
|
Remove leftover logging in test | var Enum = require('../../core/Enum');
describe('Enum', function () {
it('should create an enum and provide a lookup function', function () {
var myEnum = Enum(['a', 'b', 'c']);
expect(myEnum).to.have.ownProperty('a');
expect(myEnum).to.have.ownProperty('b')
expect(myEnum).to.have.ownProperty('c');
expect(myEnum.__lookup(myEnum.a)).to.equal('a');
expect(myEnum.__lookup(myEnum.b)).to.equal('b');
expect(myEnum.__lookup(myEnum.c)).to.equal('c');
});
it('should not be writable', function () {
var myEnum = Enum(['a']);
var prevValue = myEnum.a;
myEnum.a = -1;
expect(myEnum.a).to.equal(prevValue);
var prevLookupFunction = myEnum.__lookup;
myEnum.__lookup = 100;
expect(myEnum.__lookup).to.equal(prevLookupFunction);
});
});
| var Enum = require('../../core/Enum');
describe('Enum', function () {
it('should create an enum and provide a lookup function', function () {
var myEnum = Enum(['a', 'b', 'c']);
console.log(myEnum);
expect(myEnum).to.have.ownProperty('a');
expect(myEnum).to.have.ownProperty('b')
expect(myEnum).to.have.ownProperty('c');
expect(myEnum.__lookup(myEnum.a)).to.equal('a');
expect(myEnum.__lookup(myEnum.b)).to.equal('b');
expect(myEnum.__lookup(myEnum.c)).to.equal('c');
});
it('should not be writable', function () {
var myEnum = Enum(['a']);
var prevValue = myEnum.a;
myEnum.a = -1;
expect(myEnum.a).to.equal(prevValue);
var prevLookupFunction = myEnum.__lookup;
myEnum.__lookup = 100;
expect(myEnum.__lookup).to.equal(prevLookupFunction);
});
});
|
Save ontology map in script | import sys
import os
from os.path import join, dirname, abspath
from indra import preassembler
from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file as mht
from indra.sources.sofia.make_sofia_tsv import make_file as mst
from indra.java_vm import autoclass
eidos_package = 'org.clulab.wm.eidos'
if __name__ == '__main__':
sofia_ont_path = sys.argv[1]
hume_path = 'hume_ontology_examples.tsv'
mht(hume_path)
sofia_path = 'sofia_ontology_examples.tsv'
mst(sofia_ont_path, sofia_path)
om = autoclass(eidos_package + '.apps.OntologyMapper')
eidos = autoclass(eidos_package + '.EidosSystem')
es = eidos(autoclass('java.lang.Object')())
example_weight = 0.8
parent_weight = 0.1
topn = 10
table_str = om.mapOntologies(es, hume_path, sofia_path, example_weight,
parent_weight, topn)
with open(join(dirname(abspath(__file__)), os.pardir, 'resources',
'wm_ontomap.tsv'), 'w') as fh:
fh.write(table_str)
| import sys
from indra.sources import eidos
from indra.sources.hume.make_hume_tsv import make_file as mht
from indra.sources.sofia.make_sofia_tsv import make_file as mst
from indra.java_vm import autoclass
eidos_package = 'org.clulab.wm.eidos'
if __name__ == '__main__':
sofia_ont_path = sys.argv[1]
hume_path = 'hume_ontology_examaples.tsv'
mht(hume_path)
sofia_path = 'sofia_ontology_examples.tsv'
mst(sofia_ont_path, sofia_path)
om = autoclass(eidos_package + '.apps.OntologyMapper')
eidos = autoclass(eidos_package + '.EidosSystem')
es = eidos(autoclass('java.lang.Object')())
example_weight = 0.8
parent_weight = 0.1
topn = 10
table_str = om.mapOntologies(es, hume_path, sofia_path, example_weight,
parent_weight, topn)
|
Stop the server when done. | """Test wsgi."""
import threading
import pytest
import portend
from cheroot import wsgi
@pytest.fixture
def simple_wsgi_server():
"""Fucking simple wsgi server fixture (duh)."""
port = portend.find_available_local_port()
def app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [b'Hello world!']
host = '::'
addr = host, port
server = wsgi.Server(addr, app)
thread = threading.Thread(target=server.start)
thread.setDaemon(True)
thread.start()
yield locals()
server.stop()
def test_connection_keepalive(simple_wsgi_server):
"""Test the connection keepalive works (duh)."""
pass
| """Test wsgi."""
import threading
import pytest
import portend
from cheroot import wsgi
@pytest.fixture
def simple_wsgi_server():
"""Fucking simple wsgi server fixture (duh)."""
port = portend.find_available_local_port()
def app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return [b'Hello world!']
host = '::'
addr = host, port
server = wsgi.Server(addr, app)
thread = threading.Thread(target=server.start)
thread.setDaemon(True)
thread.start()
yield locals()
# would prefer to stop server, but has errors
# server.stop()
def test_connection_keepalive(simple_wsgi_server):
"""Test the connection keepalive works (duh)."""
pass
|
Complete string tests to pass |
module("About Strings (topics/about_strings.js)");
test("delimiters", function() {
var singleQuotedString = 'apple';
var doubleQuotedString = "apple";
equal(true, singleQuotedString === doubleQuotedString, 'are the two strings equal?');
});
test("concatenation", function() {
var fruit = "apple";
var dish = "pie";
equal("apple pie", fruit + " " + dish, 'what is the value of fruit + " " + dish?');
});
test("character Type", function() {
var characterType = typeof("Amory".charAt(1)); // typeof will be explained in about reflection
equal('string', characterType, 'Javascript has no character type');
});
test("escape character", function() {
var stringWithAnEscapedCharacter = "\u0041pple";
equal("Apple", stringWithAnEscapedCharacter, 'what is the value of stringWithAnEscapedCharacter?');
});
test("string.length", function() {
var fruit = "apple";
equal(5, fruit.length, 'what is the value of fruit.length?');
});
test("slice", function() {
var fruit = "apple pie";
equal("apple", fruit.slice(0,5), 'what is the value of fruit.slice(0,5)?');
});
|
module("About Strings (topics/about_strings.js)");
test("delimiters", function() {
var singleQuotedString = 'apple';
var doubleQuotedString = "apple";
equal(__, singleQuotedString === doubleQuotedString, 'are the two strings equal?');
});
test("concatenation", function() {
var fruit = "apple";
var dish = "pie";
equal(__, fruit + " " + dish, 'what is the value of fruit + " " + dish?');
});
test("character Type", function() {
var characterType = typeof("Amory".charAt(1)); // typeof will be explained in about reflection
equal(__, characterType, 'Javascript has no character type');
});
test("escape character", function() {
var stringWithAnEscapedCharacter = "\u0041pple";
equal(__, stringWithAnEscapedCharacter, 'what is the value of stringWithAnEscapedCharacter?');
});
test("string.length", function() {
var fruit = "apple";
equal(__, fruit.length, 'what is the value of fruit.length?');
});
test("slice", function() {
var fruit = "apple pie";
equal(__, fruit.slice(0,5), 'what is the value of fruit.slice(0,5)?');
});
|
Exit process if clearing process does not finish within 3 seconds
App would previously refuse to exit if it could not send a successful
clear message to each player. | var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() { return gracefulExit(radiodan); }
};
function gracefulExit(radiodan) {
// if promise does not resolve quickly enough, exit anyway
setTimeout(exitWithCode(2), 3000);
return clearPlayers(radiodan.cache.players)
.then(exitWithCode(0), exitWithCode(1));
};
function clearPlayers(players) {
var resolved = utils.promise.resolve(),
playerIds = Object.keys(players || {});
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
function exitWithCode(exitCode) {
return function() {
process.exit(exitCode);
return utils.promise.resolve();
}
}
| var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
function() {
process.exit(0);
},
function() {
process.exit(1);
}
);
function clearPlayers(players) {
var playerIds = Object.keys(players),
resolved = utils.promise.resolve();
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
};
};
|
Disable default registerCommands method as all commands are registered as tagged services | <?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014 Elcodi.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Bundle\CoreBundle;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Elcodi\Bundle\CoreBundle\DependencyInjection\ElcodiCoreExtension;
/**
* ElcodiCoreBundle Bundle
*
* This is the core of the suite.
* All available bundles in this suite could have this bundle as a main
* dependency.
*/
class ElcodiCoreBundle extends Bundle
{
/**
* Returns the bundle's container extension.
*
* @return ExtensionInterface The container extension
*/
public function getContainerExtension()
{
return new ElcodiCoreExtension();
}
/**
* Register Commands.
*
* Disabled as commands are registered as services
*
* @param Application $application An Application instance
*/
public function registerCommands(Application $application)
{
return;
}
}
| <?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014 Elcodi.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <yuhu@mmoreram.com>
* @author Aldo Chiecchia <zimage@tiscali.it>
* @author Elcodi Team <tech@elcodi.com>
*/
namespace Elcodi\Bundle\CoreBundle;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Elcodi\Bundle\CoreBundle\DependencyInjection\ElcodiCoreExtension;
/**
* ElcodiCoreBundle Bundle
*
* This is the core of the suite.
* All available bundles in this suite could have this bundle as a main
* dependency.
*/
class ElcodiCoreBundle extends Bundle
{
/**
* Returns the bundle's container extension.
*
* @return ExtensionInterface The container extension
*/
public function getContainerExtension()
{
return new ElcodiCoreExtension();
}
}
|
Add long description to the package. | from distutils.core import setup
from setuptools import find_packages
with open('README.rst') as file:
long_description = file.read()
setup(name='geventconnpool',
version = "0.1a",
description = 'TCP connection pool for gevent',
long_description = long_description,
url="https://github.com/rasky/geventconnpool",
author="Giovanni Bajo",
author_email="rasky@develer.com",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
install_requires=[
'gevent >= 0.13'
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: No Input/Output (Daemon)",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Topic :: Software Development",
])
| from distutils.core import setup
from setuptools import find_packages
setup(name='geventconnpool',
version = "0.1",
description = 'TCP connection pool for gevent',
url="https://github.com/rasky/geventconnpool",
author="Giovanni Bajo",
author_email="rasky@develer.com",
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
install_requires=[
'gevent >= 0.13'
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: No Input/Output (Daemon)",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Topic :: Software Development",
])
|
Fix deprecation warnings for Ember 1.10.0. | import Ember from 'ember';
export default Ember.Mixin.create({
hasPaginationSupport: true,
total: 0,
page: 0,
pageSize: 10,
didRequestPage: Ember.K,
first: function () {
return this.get('page') * this.get('pageSize') + 1;
}.property('page', 'pageSize'),
last: function () {
return Math.min((this.get('page') + 1) * this.get('pageSize'), this.get('total'));
}.property('page', 'pageSize', 'total'),
hasPrevious: function () {
return this.get('page') > 0;
}.property('page'),
hasNext: function () {
return this.get('last') < this.get('total');
}.property('last', 'total'),
nextPage: function () {
if (this.get('hasNext')) {
this.incrementProperty('page');
}
},
previousPage: function () {
if (this.get('hasPrevious')) {
this.decrementProperty('page');
}
},
totalPages: function () {
return Math.ceil(this.get('total') / this.get('pageSize'));
}.property('total', 'pageSize'),
pageDidChange: function () {
this.didRequestPage(this.get('page'));
}.observes('page')
});
| import Ember from 'ember';
export default Ember.Mixin.create({
hasPaginationSupport: true,
total: 0,
page: 0,
pageSize: 10,
didRequestPage: Ember.K,
first: function () {
return this.get('page') * this.get('pageSize') + 1;
}.property('page', 'pageSize').cacheable(),
last: function () {
return Math.min((this.get('page') + 1) * this.get('pageSize'), this.get('total'));
}.property('page', 'pageSize', 'total').cacheable(),
hasPrevious: function () {
return this.get('page') > 0;
}.property('page').cacheable(),
hasNext: function () {
return this.get('last') < this.get('total');
}.property('last', 'total').cacheable(),
nextPage: function () {
if (this.get('hasNext')) {
this.incrementProperty('page');
}
},
previousPage: function () {
if (this.get('hasPrevious')) {
this.decrementProperty('page');
}
},
totalPages: function () {
return Math.ceil(this.get('total') / this.get('pageSize'));
}.property('total', 'pageSize').cacheable(),
pageDidChange: function () {
this.didRequestPage(this.get('page'));
}.observes('page')
});
|
Remove Python 3 incompatible print statement | #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from networkx import *
z=[5,3,3,3,3,2,2,2,1,1,1]
print(is_valid_degree_sequence(z))
print("Configuration model")
G=configuration_model(z) # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
if d in hist:
hist[d]+=1
else:
hist[d]=1
print("degree #nodes")
for d in hist:
print('%d %d' % (d,hist[d]))
| #!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from networkx import *
z=[5,3,3,3,3,2,2,2,1,1,1]
print is_valid_degree_sequence(z)
print("Configuration model")
G=configuration_model(z) # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
if d in hist:
hist[d]+=1
else:
hist[d]=1
print("degree #nodes")
for d in hist:
print('%d %d' % (d,hist[d]))
|
Fix minor mismatched class usage | /*-
* -\-\-
* docker-client
* --
* Copyright (C) 2016 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.docker.client.messages;
import static com.spotify.docker.FixtureUtil.fixture;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spotify.docker.client.ObjectMapperProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ImageInfoTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private ObjectMapper objectMapper;
@Before
public void setUp() throws Exception {
objectMapper = new ObjectMapperProvider().getContext(ImageInfoTest.class);
}
@Test
public void test1_24() throws Exception {
objectMapper.readValue(fixture("fixtures/1.24/imageInfo.json"), ImageInfo.class);
}
} | /*-
* -\-\-
* docker-client
* --
* Copyright (C) 2016 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.docker.client.messages;
import static com.spotify.docker.FixtureUtil.fixture;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spotify.docker.client.ObjectMapperProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ImageInfoTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private ObjectMapper objectMapper;
@Before
public void setUp() throws Exception {
objectMapper = new ObjectMapperProvider().getContext(ContainerInfo.class);
}
@Test
public void test1_24() throws Exception {
objectMapper.readValue(fixture("fixtures/1.24/imageInfo.json"), ImageInfo.class);
}
} |
Add an expectedFailure decorator to the test_connect_remote() test case.
It fails when running within the context of the test suite, but succeeds
when running alone.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@127290 91177308-0d34-0410-b5e6-96231b3b80d8 | """
Test lldb 'process connect' command.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = "connect_remote"
@unittest2.expectedFailure
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
# First, we'll start a fake debugserver (a simple echo server).
import subprocess
fakeserver = subprocess.Popen('./EchoServer.py')
# This does the cleanup afterwards.
def cleanup_fakeserver():
fakeserver.kill()
fakeserver.wait()
self.addTearDownHook(cleanup_fakeserver)
self.runCmd("process connect connect://localhost:12345")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
Test lldb 'process connect' command.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = "connect_remote"
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
# First, we'll start a fake debugserver (a simple echo server).
import subprocess
fakeserver = subprocess.Popen('./EchoServer.py')
# This does the cleanup afterwards.
def cleanup_fakeserver():
fakeserver.kill()
fakeserver.wait()
self.addTearDownHook(cleanup_fakeserver)
self.runCmd("process connect connect://localhost:12345")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
|
Enforce flake8 and NOQA cases | from ctypes import * # NOQA
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
# Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
| from ctypes import *
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
# Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
|
Remove some definitions and methods from the public space (lowercase
their name) | package wsmaterials
import (
"fmt"
"github.com/emicklei/go-restful"
"net/http"
)
type jsonpResponseWriter struct {
writer http.ResponseWriter
callback string
}
func (j *jsonpResponseWriter) Header() http.Header {
return j.writer.Header()
}
func (j *jsonpResponseWriter) WriteHeader(status int) {
j.writer.WriteHeader(status)
}
func (j *jsonpResponseWriter) Write(bytes []byte) (int, error) {
if j.callback != "" {
bytes = []byte(fmt.Sprintf("%s(%s)", j.callback, bytes))
}
return j.writer.Write(bytes)
}
func newJsonpResponseWriter(httpWriter http.ResponseWriter, callback string) *jsonpResponseWriter {
jsonpResponseWriter := new(jsonpResponseWriter)
jsonpResponseWriter.writer = httpWriter
jsonpResponseWriter.callback = callback
return jsonpResponseWriter
}
func JsonpFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
callback := req.Request.FormValue("callback")
jsonpResponseWriter := newJsonpResponseWriter(resp.ResponseWriter, callback)
resp.ResponseWriter = jsonpResponseWriter
chain.ProcessFilter(req, resp)
}
| package wsmaterials
import (
"fmt"
"github.com/emicklei/go-restful"
"net/http"
)
type JsonpResponseWriter struct {
writer http.ResponseWriter
callback string
}
func (j *JsonpResponseWriter) Header() http.Header {
return j.writer.Header()
}
func (j *JsonpResponseWriter) WriteHeader(status int) {
j.writer.WriteHeader(status)
}
func (j *JsonpResponseWriter) Write(bytes []byte) (int, error) {
if j.callback != "" {
bytes = []byte(fmt.Sprintf("%s(%s)", j.callback, bytes))
}
return j.writer.Write(bytes)
}
func NewJsonpResponseWriter(httpWriter http.ResponseWriter, callback string) *JsonpResponseWriter {
jsonpResponseWriter := new(JsonpResponseWriter)
jsonpResponseWriter.writer = httpWriter
jsonpResponseWriter.callback = callback
return jsonpResponseWriter
}
func JsonpFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
callback := req.Request.FormValue("callback")
jsonpResponseWriter := NewJsonpResponseWriter(resp.ResponseWriter, callback)
resp.ResponseWriter = jsonpResponseWriter
chain.ProcessFilter(req, resp)
}
|
Set default scopes to read | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from operator import or_
from sentry.models import ApiKey, OrganizationMemberType
from sentry.web.frontend.base import OrganizationView
DEFAULT_SCOPES = [
'project:read',
'event:read',
'team:read',
'org:read',
]
class OrganizationApiKeysView(OrganizationView):
required_access = OrganizationMemberType.ADMIN
def handle(self, request, organization):
if request.POST.get('op') == 'newkey':
key = ApiKey.objects.create(
organization=organization,
scopes=reduce(or_, [getattr(ApiKey.scopes, s) for s in DEFAULT_SCOPES])
)
redirect_uri = reverse('sentry-organization-api-key-settings', args=[
organization.slug, key.id,
])
return HttpResponseRedirect(redirect_uri)
key_list = sorted(ApiKey.objects.filter(
organization=organization,
), key=lambda x: x.label)
context = {
'key_list': key_list,
}
return self.respond('sentry/organization-api-keys.html', context)
| from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from sentry.models import ApiKey, OrganizationMemberType
from sentry.web.frontend.base import OrganizationView
class OrganizationApiKeysView(OrganizationView):
required_access = OrganizationMemberType.ADMIN
def handle(self, request, organization):
if request.POST.get('op') == 'newkey':
key = ApiKey.objects.create(organization=organization)
redirect_uri = reverse('sentry-organization-api-key-settings', args=[
organization.slug, key.id,
])
return HttpResponseRedirect(redirect_uri)
key_list = sorted(ApiKey.objects.filter(
organization=organization,
), key=lambda x: x.label)
context = {
'key_list': key_list,
}
return self.respond('sentry/organization-api-keys.html', context)
|
Change DB to ip loopback from 'localhost' which doesn't work for some reason on halstead. | from base_settings import *
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu']
with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f:
SECRET_KEY = f.read().strip()
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
# it would be nice to enable this, but we go w/o SSL from the WashU load
# balancer, meaning infinite redirects if we enable this :(
# SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'
DEFAULT_FROM_EMAIL = "webmaster@pttrack.snhc.wustl.edu"
SERVER_EMAIL = "admin@pttrack.snhc.wustl.edu"
with open(os.path.join(BASE_DIR, 'secrets/database_password.txt')) as f:
DB_PASSWORD = f.read().strip()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'osler',
'USER': 'django',
'PASSWORD': DB_PASSWORD,
# 'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
| from base_settings import *
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['pttrack.snhc.wustl.edu']
with open(os.path.join(BASE_DIR, 'secrets/secret_key.txt')) as f:
SECRET_KEY = f.read().strip()
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
# it would be nice to enable this, but we go w/o SSL from the WashU load
# balancer, meaning infinite redirects if we enable this :(
# SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'
DEFAULT_FROM_EMAIL = "webmaster@pttrack.snhc.wustl.edu"
SERVER_EMAIL = "admin@pttrack.snhc.wustl.edu"
with open(os.path.join(BASE_DIR, 'secrets/database_password.txt')) as f:
DB_PASSWORD = f.read().strip()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'osler',
'USER': 'django',
'PASSWORD': DB_PASSWORD,
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
} |
Add 'distribute' to the node services | #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)
SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']
class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):
PUBLISH='publish'
ACCESS = 'access'
BROKER = 'broker'
DISTRIBUTE = 'distribute'
ADMINISTRATIVE='administrative'
def __init__(self, data=None):
super(NodeServiceModel,self).__init__(data)
| #!/usr/bin/pyton
# Copyright 2011 Lockheed Martin
'''
Created on Mar 17, 2011
Base model class for learning registry data model
@author: jpoyau
'''
from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig
from pylons import *
import datetime, logging
log = logging.getLogger(__name__)
SPEC_SERVICE_DESCRIPTION= appConfig['spec.models.node_service_description']
DB_NODE = appConfig['couchdb.db.node']
class NodeServiceModel(createBaseModel(SPEC_SERVICE_DESCRIPTION, DB_NODE)):
PUBLISH='publish'
ACCESS = 'access'
BROKER = 'broker'
ADMINISTRATIVE='administrative'
def __init__(self, data=None):
super(NodeServiceModel,self).__init__(data)
|
Use rimraf instead of spawning rm -rf
Thus, it works on Windows! | var test = require("tap").test
, fs = require("fs")
, path = require("path")
, existsSync = fs.existsSync || path.existsSync
, spawn = require("child_process").spawn
, npm = require("../../")
, rimraf = require("rimraf")
test("not every pkg.name can be required", function (t) {
t.plan(1)
setup(function () {
npm.install(".", function (err) {
if (err) return t.fail(err)
t.ok(existsSync(__dirname +
"/false_name/node_modules/tap/node_modules/buffer-equal"))
})
})
})
function setup (cb) {
process.chdir(__dirname + "/false_name")
npm.load(function () {
rimraf.sync(__dirname + "/false_name/node_modules")
fs.mkdirSync(__dirname + "/false_name/node_modules")
cb()
})
}
| var test = require("tap").test
, fs = require("fs")
, path = require("path")
, existsSync = fs.existsSync || path.existsSync
, spawn = require("child_process").spawn
, npm = require("../../")
test("not every pkg.name can be required", function (t) {
t.plan(1)
setup(function () {
npm.install(".", function (err) {
if (err) return t.fail(err)
t.ok(existsSync(__dirname +
"/false_name/node_modules/tap/node_modules/buffer-equal"))
})
})
})
function setup (cb) {
process.chdir(__dirname + "/false_name")
npm.load(function () {
spawn("rm", [ "-rf", __dirname + "/false_name/node_modules" ])
.on("exit", function () {
fs.mkdirSync(__dirname + "/false_name/node_modules")
cb()
})
})
}
|
Handle doc without domain or domains | from couchdbkit import ResourceNotFound
from django.http import Http404
from jsonobject.exceptions import WrappingAttributeError
def get_document_or_404(cls, domain, doc_id, additional_doc_types=None):
"""
Gets a document and enforces its domain and doc type.
Raises Http404 if the doc isn't found or domain/doc_type don't match.
"""
allowed_doc_types = (additional_doc_types or []) + [cls.__name__]
try:
unwrapped = cls.get_db().get(doc_id)
except ResourceNotFound:
raise Http404()
if ((unwrapped.get('domain', None) != domain and
domain not in unwrapped.get('domains', [])) or
unwrapped['doc_type'] not in allowed_doc_types):
raise Http404()
try:
return cls.wrap(unwrapped)
except WrappingAttributeError:
raise Http404()
| from couchdbkit import ResourceNotFound
from django.http import Http404
from jsonobject.exceptions import WrappingAttributeError
def get_document_or_404(cls, domain, doc_id, additional_doc_types=None):
"""
Gets a document and enforces its domain and doc type.
Raises Http404 if the doc isn't found or domain/doc_type don't match.
"""
allowed_doc_types = (additional_doc_types or []) + [cls.__name__]
try:
unwrapped = cls.get_db().get(doc_id)
except ResourceNotFound:
raise Http404()
if (unwrapped.get('domain', domain) != domain or
domain not in unwrapped.get('domains', [domain]) or
unwrapped['doc_type'] not in allowed_doc_types):
raise Http404()
try:
return cls.wrap(unwrapped)
except WrappingAttributeError:
raise Http404()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.