executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
return () -> {
NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);
if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
downloadService.stackNotification(notificationInformation);
} else {
downloadService.updateNotification(notificationInformation);
}
return null;
};
}
void setDownloadService(DownloadService downloadService) {
this.downloadService = downloadService;
}
}
"
Send user information to the state,"middleware('auth');
$this->middleware('role:admin,staff');
$this->registrar = $registrar;
$this->campaignService = $campaignService;
}
/**
* Display the specified resource.
*
* @param string $id signup id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$signup = Signup::find($id);
$campaign = $this->campaignService->find($id);
$user = $this->registrar->find($signup->northstar_id);
return view('signups.show', compact('campaign'))
->with('state', [
'signup' => $signup,
'campaign' => $campaign,
'user' => $user->toArray(),
]);
}
}
","middleware('auth');
$this->middleware('role:admin,staff');
$this->registrar = $registrar;
$this->campaignService = $campaignService;
}
/**
* Display the specified resource.
*
* @param string $id signup id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$signup = Signup::find($id);
$campaign = $this->campaignService->find($id);
return view('signups.show')
->with('state', [
'signup' => $signup,
'campaign' => $campaign,
]);
}
}
"
Add ascii art to home page.,"@extends('laravelerator::layouts.master')
@section('content')
Home
-
alg:generate Database code generation
- Validate schema
-
template and path are required args.
table, namespace, schema & mock are options.
-
General
-
Explore the use of Facades
@stop
_ ___ ______ ___ _ _ _____ _ _____ ______ ___ _____ _____ ______
| | / _ \ | ___ \ / _ \ | | | || ___|| | | ___|| ___ \ / _ \|_ _|| _ || ___ \
| | / /_\ \| |_/ // /_\ \| | | || |__ | | | |__ | |_/ // /_\ \ | | | | | || |_/ /
| | | _ || / | _ || | | || __| | | | __| | / | _ | | | | | | || /
| |____| | | || |\ \ | | | |\ \_/ /| |___ | |____| |___ | |\ \ | | | | | | \ \_/ /| |\ \
\_____/\_| |_/\_| \_|\_| |_/ \___/ \____/ \_____/\____/ \_| \_|\_| |_/ \_/ \___/ \_| \_|
","@extends('laravelerator::layouts.master')
@section('content')
Home
-
alg:generate Database code generation
- Validate schema
-
template and path are required args.
table, namespace, schema & mock are options.
-
General
-
Explore the use of Facades
@stop
"
"Remove explicit assignment to undefined.
jshint complains about these.","var Timer = (function(Event, Util) {
'use strict';
// Internal constants for the various timer states.
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
var startTime, endTime, solveTime;
var intervalID;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; }
function isRunning() { return state === Running; }
function onWaiting() {
endTime = undefined;
}
function onRunning() {
startTime = Util.getMilli();
intervalID = Util.setInterval(runningEmitter, 100);
}
function onStopped() {
endTime = Util.getMilli();
Util.clearInterval(intervalID);
setState(Waiting);
}
function setState(new_state) {
state = new_state;
switch(state) {
case Waiting: onWaiting(); break;
case Running: onRunning(); break;
case Stopped: onStopped(); break;
}
}
function runningEmitter() {
Event.emit(""timer/running"");
}
function triggerDown() {
if (isWaiting()) {
setState(Ready);
} else if (isRunning()) {
setState(Stopped);
}
}
function triggerUp() {
if (isReady()) {
setState(Running);
}
}
function getCurrent() {
return (endTime || Util.getMilli()) - startTime;
}
return {
triggerDown: triggerDown,
triggerUp: triggerUp,
getCurrent: getCurrent
};
});
if (typeof module !== 'undefined')
module.exports = Timer;
","var Timer = (function(Event, Util) {
'use strict';
// Internal constants for the various timer states.
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
var startTime = undefined, endTime = undefined, solveTime = undefined;
var intervalID = undefined;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; }
function isRunning() { return state === Running; }
function onWaiting() {
endTime = undefined;
}
function onRunning() {
startTime = Util.getMilli();
intervalID = Util.setInterval(runningEmitter, 100);
}
function onStopped() {
endTime = Util.getMilli();
Util.clearInterval(intervalID);
setState(Waiting);
}
function setState(new_state) {
state = new_state;
switch(state) {
case Waiting: onWaiting(); break;
case Running: onRunning(); break;
case Stopped: onStopped(); break;
}
}
function runningEmitter() {
Event.emit(""timer/running"");
}
function triggerDown() {
if (isWaiting()) {
setState(Ready);
} else if (isRunning()) {
setState(Stopped);
}
}
function triggerUp() {
if (isReady()) {
setState(Running);
}
}
function getCurrent() {
return (endTime || Util.getMilli()) - startTime;
}
return {
triggerDown: triggerDown,
triggerUp: triggerUp,
getCurrent: getCurrent
};
});
if (typeof module !== 'undefined')
module.exports = Timer;
"
Tweak order of operations in populate migration,"# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations, models
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
broadcast_count = len(broadcast_ids)
if broadcast_count:
print('Starting to update %d broadcasts send all field...' % broadcast_count)
updated = 0
for chunk in chunk_list(broadcast_ids, 5000):
Broadcast.objects.filter(pk__in=chunk).update(send_all=False)
print(""Updated %d of %d broadcasts"" % (updated + len(chunk), broadcast_count))
def apply_as_migration(apps, schema_editor):
Broadcast = apps.get_model('msgs', 'Broadcast')
do_populate_send_all(Broadcast)
def apply_manual():
from temba.msgs.models import Broadcast
do_populate_send_all(Broadcast)
class Migration(migrations.Migration):
dependencies = [
('msgs', '0088_broadcast_send_all'),
]
operations = [
migrations.AlterField(
model_name='broadcast',
name='send_all',
field=models.NullBooleanField(default=False,
help_text='Whether this broadcast should send to all URNs for each contact'),
),
migrations.RunPython(apply_as_migration),
]
","# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations, models
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
broadcast_count = len(broadcast_ids)
if broadcast_count:
print('Starting to update %d broadcasts send all field...' % broadcast_count)
updated = 0
for chunk in chunk_list(broadcast_ids, 1000):
Broadcast.objects.filter(pk__in=chunk).update(send_all=False)
print(""Updated %d of %d broadcasts"" % (updated + len(chunk), broadcast_count))
def apply_as_migration(apps, schema_editor):
Broadcast = apps.get_model('msgs', 'Broadcast')
do_populate_send_all(Broadcast)
def apply_manual():
from temba.msgs.models import Broadcast
do_populate_send_all(Broadcast)
class Migration(migrations.Migration):
dependencies = [
('msgs', '0088_broadcast_send_all'),
]
operations = [
migrations.RunPython(apply_as_migration),
migrations.AlterField(
model_name='broadcast',
name='send_all',
field=models.NullBooleanField(default=False,
help_text='Whether this broadcast should send to all URNs for each contact'),
),
]
"
Fix caption of quick link in dashboard,"@extends( 'layouts.master' )
@section( 'title', 'Welcome' )
@section( 'heading', 'Welcome' )
@section( 'main' )
@row
@col( s12 )
You are logged in.
@endcol
@endrow
@row
@col( s12 )
@foreach ( $clients as $client )
@if ( $client->init_oauth_uri )
init_oauth_uri }}"">
https
Go to {{ $client->title ?: $client->client_id }}
@elseif ( $client->home_uri )
home_uri }}"">
submit
Go to {{ $client->title ?: $client->client_id }}
@endif
@endforeach
@endcol
@endrow
@endsection
","@extends( 'layouts.master' )
@section( 'title', 'Welcome' )
@section( 'heading', 'Welcome' )
@section( 'main' )
@row
@col( s12 )
You are logged in.
@endcol
@endrow
@row
@col( s12 )
@foreach ( $clients as $client )
@if ( $client->init_oauth_uri )
init_oauth_uri }}"">
https
Go to {{ $client->title ?: $client->id }}
@elseif ( $client->home_uri )
home_uri }}"">
submit
Go to {{ $client->title ?: $client->id }}
@endif
@endforeach
@endcol
@endrow
@endsection
"
Order displayed slides by weight,"from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
""""""
""""""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
""""""
""""""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
return Slide.objects.filter(tags__name__in=self.tags.names()).order_by('weight').distinct()
","from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from model_utils.models import TimeFramedModel
from taggit.managers import TaggableManager
@python_2_unicode_compatible
class Slide(TimeFramedModel):
""""""
""""""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
image = models.ImageField(
upload_to='slides/',
)
duration = models.PositiveIntegerField(
default=7,
)
weight = models.SmallIntegerField(
default=0,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:slide_update', args=[self.pk])
def get_displays(self):
return Display.objects.filter(tags__name__in=self.tags.names()).distinct()
@python_2_unicode_compatible
class Display(models.Model):
""""""
""""""
name = models.CharField(
max_length=255,
)
description = models.TextField(
blank=True,
)
tags = TaggableManager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('signage:display_update', args=[self.pk])
def get_slides(self):
return Slide.objects.filter(tags__name__in=self.tags.names()).distinct()
"
Update migration file to use the new config file,"""use strict"";
var config = require('../config/config');
var knex = require('knex')(config.database);
knex.schema.hasTable('users')
.then(function(exists) {
if (!exists) {
return knex.schema.createTable('users', function(t) {
t.bigIncrements('id').primary();
t.string('email', 100).index('users_email_idx');
t.string('password', 255);
t.dateTime('created_at').defaultTo(knex.raw('now()'));
t.dateTime('updated_at').defaultTo(knex.raw('now()'));
});
} else {
console.log('users table already exists.');
}
}).then(function() {
return knex.schema.hasTable('tokens').then(function (exists) {
if (!exists) {
return knex.schema.createTable('tokens', function (t) {
t.bigIncrements('id').primary();
t.biginteger('user_id').references('id').inTable('users');
t.string('token', 255).index('tokens_token_idx');
t.dateTime('expiry');
t.dateTime('created_at').defaultTo(knex.raw('now()'));
t.dateTime('updated_at').defaultTo(knex.raw('now()'));
});
} else {
console.log('tokens table already exists.');
}
});
}).then(function() {
process.exit(1);
});","""use strict"";
var path = require('path');
var HOME = process.env.HOME || process.env.HOMEPATH;
var APP_ENV = process.env.APP_ENV || 'dev';
var config = require('../config/config')[APP_ENV];
var knex = require('knex')(config.database);
knex.schema.hasTable('users')
.then(function(exists) {
if (!exists) {
return knex.schema.createTable('users', function(t) {
t.bigIncrements('id').primary();
t.string('email', 100).index('users_email_idx');
t.string('password', 255);
t.dateTime('created_at').defaultTo(knex.raw('now()'));
t.dateTime('updated_at').defaultTo(knex.raw('now()'));
});
} else {
console.log('users table already exists.');
}
}).then(function() {
return knex.schema.hasTable('tokens').then(function (exists) {
if (!exists) {
return knex.schema.createTable('tokens', function (t) {
t.bigIncrements('id').primary();
t.biginteger('user_id').references('id').inTable('users');
t.string('token', 255).index('tokens_token_idx');
t.dateTime('expiry');
t.dateTime('created_at').defaultTo(knex.raw('now()'));
t.dateTime('updated_at').defaultTo(knex.raw('now()'));
});
} else {
console.log('tokens table already exists.');
}
});
}).then(function() {
process.exit(1);
});"
Remove description and add updated_at so we can see when tickets were last updated,"@extends('layouts.default')
@section('content')
Support Tickets
Title |
Priority |
Status |
Replies |
Owner |
Updated At |
@foreach ($tickets as $ticket)
@if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id)
id)) }}"">
{{ $ticket->title }}
|
{{ $ticket->priority->title }}
|
{{ $ticket->status->title }}
|
{{ $ticket->replies }}
|
{{ $ticket->owner->username }}
|
{{ $ticket->updated_at }}
|
@endif
@endforeach
@stop","@extends('layouts.default')
@section('content')
Support Tickets
Title |
Description |
Priority |
Status |
Replies |
Owner |
@foreach ($tickets as $ticket)
@if (Sentry::inGroup(Sentry::findGroupByName('Admins')) || $ticket->owner_id == Sentry::getUser()->id)
id)) }}"">
{{ $ticket->title }}
|
{{ $ticket->description }}
|
{{ $ticket->priority->title }}
|
{{ $ticket->status->title }}
|
{{ $ticket->replies }}
|
{{ $ticket->owner->username }}
|
@endif
@endforeach
@stop"
Add tests for different types of phred offsets,"#!/usr/bin/env python
import numpy as np
from unittest import TestCase, main
from skbio.format.sequences.fastq import (format_fastq_record,
_phred_to_ascii33,
_phred_to_ascii64)
class FASTQFormatTests(TestCase):
def setUp(self):
self.qual_scores = np.array([38, 39, 40], dtype=np.int8)
self.args = (b'abc', b'def', self.qual_scores)
def test_format_fastq_record_phred_offset_33(self):
exp = b""@abc\ndef\n+\nGHI\n""
obs = format_fastq_record(*self.args, phred_offset=33)
self.assertEqual(obs, exp)
def test_format_fastq_record_phred_offset_64(self):
exp = b""@abc\ndef\n+\nfgh\n""
obs = format_fastq_record(*self.args, phred_offset=64)
self.assertEqual(obs, exp)
def test_format_fastq_record_invalid_phred_offset(self):
with self.assertRaises(ValueError):
format_fastq_record(*self.args, phred_offset=42)
def test_phred_to_ascii33(self):
obs = _phred_to_ascii33(self.qual_scores)
self.assertEqual(obs, b'GHI')
def test_phred_to_ascii64(self):
obs = _phred_to_ascii64(self.qual_scores)
self.assertEqual(obs, b'fgh')
if __name__ == '__main__':
main()
","#!/usr/bin/env python
import numpy as np
from unittest import TestCase, main
from skbio.format.sequences.fastq import (format_fastq_record,
_phred_to_ascii33,
_phred_to_ascii64)
class FASTQFormatTests(TestCase):
def test_format_fastq_record(self):
""""""Construt a FASTQ record""""""
exp = b""@abc\ndef\n+\nfgh\n""
obs = format_fastq_record(b'abc', b'def',
np.array([38, 39, 40], dtype=np.int8), 64)
self.assertEqual(obs, exp)
def test_phred_to_ascii33(self):
""""""Write out terrible FASTQ quality scores""""""
exp = b'GHI'
obs = _phred_to_ascii33(np.array([38, 39, 40], dtype=np.int8))
self.assertEqual(obs, exp)
def test_phred_to_ascii64(self):
""""""Write out terrible FASTQ quality scores""""""
exp = b'fgh'
obs = _phred_to_ascii64(np.array([38, 39, 40], dtype=np.int8))
self.assertEqual(obs, exp)
if __name__ == '__main__':
main()
"
Set starting view of map to USA,"var SkirmishMap = (function () {
var map;
function initialize() {
console.log(""SkirmishMap initializing"");
var mapOptions;
mapOptions = {
center: new google.maps.LatLng(39.8282, -98.5795),
zoom: 5
};
map = new google.maps.Map(document.getElementById(""map-canvas""), mapOptions);
};
var displayCity = function(city){
var iconBase = 'http://www.gravatar.com/avatar/';
new google.maps.Marker({
position: new google.maps.LatLng(city.latLng[0], city.latLng[1]),
map: map,
title: city.name + ' ' + city.playerId,
icon: iconBase + '205e460b479e2e5b48aec07710c08d50?s=50',
playerId: city.playerId
});
};
var displayCities = function(cities){
for(var i = 0; i < cities.length; i++){
var city = cities[i];
SkirmishMap.displayCity(city);
};
};
return {
displayCity: displayCity,
displayCities: displayCities,
initialize: initialize
};
})();","var SkirmishMap = (function () {
var map;
function initialize() {
console.log(""SkirmishMap initializing"");
var mapOptions;
mapOptions = {
center: new google.maps.LatLng(39.8282, 98.5795),
zoom: 10
};
map = new google.maps.Map(document.getElementById(""map-canvas""), mapOptions);
};
var displayCity = function(city){
var iconBase = 'http://www.gravatar.com/avatar/';
new google.maps.Marker({
position: new google.maps.LatLng(city.latLng[0], city.latLng[1]),
map: map,
title: city.name + ' ' + city.playerId,
icon: iconBase + '205e460b479e2e5b48aec07710c08d50?s=50',
playerId: city.playerId
});
};
var displayCities = function(cities){
for(var i = 0; i < cities.length; i++){
var city = cities[i];
SkirmishMap.displayCity(city);
};
};
return {
displayCity: displayCity,
displayCities: displayCities,
initialize: initialize
};
})();"
Add a new grunt task chaining build and headless testing,"module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> v<%= pkg.version %> */\n',
mangle: true
},
build: {
src: 'build/smallmouth.js',
dest: 'build/smallmouth.min.js'
}
},
typescript: {
base: {
src: ['src/**/*.ts'],
dest: 'build/smallmouth.js',
options: {
module: 'amd', //or commonjs
target: 'es5', //or es3
sourcemap: true,
declaration: true,
}
}
},
karma: {
unit: {
configFile: 'karma.conf.js',
browsers: ['Chrome']
},
headless: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS']
}
}
});
// Load the plugin that provides the ""uglify"" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-karma');
// Default task(s).
grunt.registerTask('default', ['typescript', 'uglify']);
grunt.registerTask('test', ['typescript', 'karma:headless']);
};
","module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> v<%= pkg.version %> */\n',
mangle: true
},
build: {
src: 'build/smallmouth.js',
dest: 'build/smallmouth.min.js'
}
},
typescript: {
base: {
src: ['src/**/*.ts'],
dest: 'build/smallmouth.js',
options: {
module: 'amd', //or commonjs
target: 'es5', //or es3
sourcemap: true,
declaration: true,
}
}
},
karma: {
unit: {
configFile: 'karma.conf.js',
browsers: ['Chrome']
},
headless: {
configFile: 'karma.conf.js',
browsers: ['PhantomJS']
}
}
});
// Load the plugin that provides the ""uglify"" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-karma');
// Default task(s).
grunt.registerTask('default', ['typescript', 'uglify']);
};
"
Correct migration in project template,"# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-19 11:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import modelcluster.fields
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('longclawproducts', '0002_auto_20170219_0804'),
]
operations = [
migrations.CreateModel(
name='ProductVariant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.DecimalField(decimal_places=2, max_digits=12)),
('ref', models.CharField(max_length=32)),
('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')),
('description', wagtail.wagtailcore.fields.RichTextField()),
('stock', models.IntegerField(default=0)),
('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='products.Product')),
],
options={
'abstract': False,
},
),
]
","# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-19 11:14
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
import modelcluster.fields
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('longclawproducts', '0002_auto_20170219_0804'),
]
operations = [
migrations.CreateModel(
name='ProductVariant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.DecimalField(decimal_places=2, max_digits=12)),
('ref', models.CharField(max_length=32)),
('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('product', 'ref'), separator='')),
('description', wagtail.wagtailcore.fields.RichTextField()),
('stock', models.IntegerField(default=0)),
('product', modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='variants', to='longclawproducts.Product')),
],
options={
'abstract': False,
},
),
]
"
Remove pc.DepthMaterial from API ref.,"pc.extend(pc, function () {
/**
* @private
* @name pc.DepthMaterial
* @class A Depth material is is for rendering linear depth values to a render target.
* @author Will Eastcott
*/
var DepthMaterial = function () {
};
DepthMaterial = pc.inherits(DepthMaterial, pc.Material);
pc.extend(DepthMaterial.prototype, {
/**
* @private
* @function
* @name pc.DepthMaterial#clone
* @description Duplicates a Depth material.
* @returns {pc.DepthMaterial} A cloned Depth material.
*/
clone: function () {
var clone = new pc.DepthMaterial();
Material.prototype._cloneInternal.call(this, clone);
clone.update();
return clone;
},
update: function () {
},
updateShader: function (device) {
var options = {
skin: !!this.meshInstances[0].skinInstance
};
var library = device.getProgramLibrary();
this.shader = library.getProgram('depth', options);
}
});
return {
DepthMaterial: DepthMaterial
};
}());","pc.extend(pc, function () {
/**
* @name pc.DepthMaterial
* @class A Depth material is is for rendering linear depth values to a render target.
* @author Will Eastcott
*/
var DepthMaterial = function () {
};
DepthMaterial = pc.inherits(DepthMaterial, pc.Material);
pc.extend(DepthMaterial.prototype, {
/**
* @function
* @name pc.DepthMaterial#clone
* @description Duplicates a Depth material.
* @returns {pc.DepthMaterial} A cloned Depth material.
*/
clone: function () {
var clone = new pc.DepthMaterial();
Material.prototype._cloneInternal.call(this, clone);
clone.update();
return clone;
},
update: function () {
},
updateShader: function (device) {
var options = {
skin: !!this.meshInstances[0].skinInstance
};
var library = device.getProgramLibrary();
this.shader = library.getProgram('depth', options);
}
});
return {
DepthMaterial: DepthMaterial
};
}());"
"Replace non-standard prependArg with bind
bind is not supported on IE8, but we have it in the Strophe.js polyfills.
More info here: https://groups.google.com/forum/#!topic/strophe/TkEpQQK37PM","Strophe.addConnectionPlugin('iexdomain', {
init: function(conn) {
// replace Strophe.Request._newXHR with new IE CrossDomain version
var nativeXHR = new XMLHttpRequest();
if (window.XDomainRequest && ! (""withCredentials"" in nativeXHR)) {
Strophe.Request.prototype._newXHR = function() {
var xhr = new XDomainRequest();
xhr.setRequestHeader = function () {} ;
xhr.readyState = 0;
xhr.onreadystatechange = this.func.bind(undefined, this);
xhr.onerror = function() {
xhr.readyState = 4;
xhr.status = 500;
xhr.onreadystatechange(xhr.responseText);
};
xhr.ontimeout = function() {
xhr.readyState = 4;
xhr.status = 0;
xhr.onreadystatechange(xhr.responseText);
};
xhr.onload = function() {
xhr.readyState = 4;
xhr.status = 200;
var _response = xhr.responseText;
var _xml = new ActiveXObject('Microsoft.XMLDOM');
_xml.async = 'false';
_xml.loadXML(_response);
xhr.responseXML = _xml;
xhr.onreadystatechange(_response);
};
return xhr;
};
} else {
console.info(""Browser doesnt support XDomainRequest."" + "" Falling back to native XHR implementation."");
}
}
});
","Strophe.addConnectionPlugin('iexdomain', {
init: function(conn) {
// replace Strophe.Request._newXHR with new IE CrossDomain version
var nativeXHR = new XMLHttpRequest();
if (window.XDomainRequest && ! (""withCredentials"" in nativeXHR)) {
Strophe.Request.prototype._newXHR = function() {
var xhr = new XDomainRequest();
xhr.setRequestHeader = function () {} ;
xhr.readyState = 0;
xhr.onreadystatechange = this.func.prependArg(this);
xhr.onerror = function() {
xhr.readyState = 4;
xhr.status = 500;
xhr.onreadystatechange(xhr.responseText);
};
xhr.ontimeout = function() {
xhr.readyState = 4;
xhr.status = 0;
xhr.onreadystatechange(xhr.responseText);
};
xhr.onload = function() {
xhr.readyState = 4;
xhr.status = 200;
var _response = xhr.responseText;
var _xml = new ActiveXObject('Microsoft.XMLDOM');
_xml.async = 'false';
_xml.loadXML(_response);
xhr.responseXML = _xml;
xhr.onreadystatechange(_response);
};
return xhr;
};
} else {
console.info(""Browser doesnt support XDomainRequest."" + "" Falling back to native XHR implementation."");
}
}
});
"
Allow multiple permissions for an endpoint,"from functools import wraps
from flask_jwt_extended import get_jwt_identity, jwt_required, current_user
from werkzeug.exceptions import Unauthorized
from scuevals_api.models import User
def optional_arg_decorator(fn):
def wrapped_decorator(*args):
if len(args) == 1 and callable(args[0]):
return fn(args[0])
else:
def real_decorator(decoratee):
return fn(decoratee, *args)
return real_decorator
return wrapped_decorator
@optional_arg_decorator
def auth_required(fn, *permissions):
""""""
Decorating a view with this ensures that the requester provided a JWT
and that the requester has any of the permissions needed to access the view.
""""""
@wraps(fn)
def wrapper(*args, **kwargs):
jwt_required(lambda: None)()
identity = get_jwt_identity()
if identity['type'] == User.Normal:
# fail if the user is still suspended
if current_user.suspended():
raise Unauthorized('user is suspended')
if identity['type'] == User.Student:
# make sure the read access is synced up
current_user.check_read_access()
# verify that the user has the correct permissions for this view
if permissions and len(set(permissions).intersection(current_user.permissions_list)) == 0:
raise Unauthorized()
return fn(*args, **kwargs)
return wrapper
","from functools import wraps
from flask_jwt_extended import get_jwt_identity, jwt_required, current_user
from werkzeug.exceptions import Unauthorized
from scuevals_api.models import User
def optional_arg_decorator(fn):
def wrapped_decorator(*args):
if len(args) == 1 and callable(args[0]):
return fn(args[0])
else:
def real_decorator(decoratee):
return fn(decoratee, *args)
return real_decorator
return wrapped_decorator
@optional_arg_decorator
def auth_required(fn, permission=None):
""""""
Decorating a view with this ensures that the requester provided a JWT
and that the requester has permission to access the view.
""""""
@wraps(fn)
def wrapper(*args, **kwargs):
jwt_required(lambda: None)()
identity = get_jwt_identity()
if identity['type'] == User.Normal:
# fail if the user is still suspended
if current_user.suspended():
raise Unauthorized('user is suspended')
if identity['type'] == User.Student:
# make sure the read access is synced up
current_user.check_read_access()
# verify that the user has the correct permissions for this view
if permission is not None and permission not in current_user.permissions_list:
raise Unauthorized()
return fn(*args, **kwargs)
return wrapper
"
Add list:site command enable option,"setName('list:site')
->setAliases(['sites'])
->setDescription('Lists all sites in a group')
->addOption(
'enable',
'e',
InputOption::VALUE_NONE,
'Show only enabled sites'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$sites = $this->manager->getSites();
if ($input->getOption('enable')) {
$sites = array_filter($sites, function($site) {
/** @var \Panlatent\SiteCli\Site $site */
return $site->isEnable();
});
}
sort($sites);
foreach ($sites as $site) {
$status = $site->isEnable() ? '√' : 'x';
$name = $site->isEnable() ? '%s/%s' : '%s/%s';
$count = $site->count();
$output->writeln(sprintf("" - %s $name [%d]"",
$status,
$site->getGroup()->getName(),
$site->getName(),
$count
));
}
}
}","setName('list:site')
->setAliases(['sites'])
->setDescription('Lists all sites in a group');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
$sites = $this->manager->getSites();
sort($sites);
foreach ($sites as $site) {
$status = $site->isEnable() ? '√' : 'x';
$name = $site->isEnable() ? '%s/%s' : '%s/%s';
$count = $site->count();
$output->writeln(sprintf("" - %s $name [%d]"",
$status,
$site->getGroup()->getName(),
$site->getName(),
$count
));
}
}
}"
Upgrade dependency requests to ==2.10.0,"import re
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
with open('abakus/__init__.py', 'r') as fd:
version = re.search(
r'^__version__\s*=\s*[\'""]([^\'""]*)[\'""]',
fd.read(),
re.MULTILINE
).group(1)
setup(
name=""django-auth-abakus"",
version='1.1.0',
url='http://github.com/webkom/django-auth-abakus',
author='Webkom, Abakus Linjeforening',
author_email='webkom@abakus.no',
description='A django auth module that can be used to to authenticate '
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
'requests==2.10.0',
],
tests_require=[
'django>=1.4',
'requests==2.7.0',
'responses'
],
license='MIT',
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
""Programming Language :: Python"",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
""Topic :: Software Development :: Libraries :: Python Modules"",
""Framework :: Django"",
""Environment :: Web Environment"",
""Operating System :: OS Independent"",
""Natural Language :: English"",
]
)
","import re
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
with open('abakus/__init__.py', 'r') as fd:
version = re.search(
r'^__version__\s*=\s*[\'""]([^\'""]*)[\'""]',
fd.read(),
re.MULTILINE
).group(1)
setup(
name=""django-auth-abakus"",
version='1.1.0',
url='http://github.com/webkom/django-auth-abakus',
author='Webkom, Abakus Linjeforening',
author_email='webkom@abakus.no',
description='A django auth module that can be used to to authenticate '
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
'requests==2.7.0',
],
tests_require=[
'django>=1.4',
'requests==2.7.0',
'responses'
],
license='MIT',
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
""Programming Language :: Python"",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
""Topic :: Software Development :: Libraries :: Python Modules"",
""Framework :: Django"",
""Environment :: Web Environment"",
""Operating System :: OS Independent"",
""Natural Language :: English"",
]
)
"
"Revert ""confirm query params never overwrite dynamic url components""
This reverts commit 9aa3a57a289985d24877515995b3f1d589624a8d.
Conflicts:
cherryontop/decorators/qp.py","import functools
from cherryontop.errors import InvalidParameter, UnexpectedParameter
def typecast_query_params(*a, **kw):
allowed, cast_funcs = _get_checks(*a, **kw)
def wrap(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
# all supplied parameters allowed?
for param in kwargs:
if param not in allowed:
raise UnexpectedParameter(param)
# typecast params
for param_name, cast in cast_funcs:
if param_name in kwargs:
try:
kwargs[param_name] = cast(kwargs[param_name])
except ValueError:
raise InvalidParameter(param_name)
return f(*args, **kwargs)
return wrapped
return wrap
def _get_checks(*args, **kwargs):
allowed = kwargs.pop('allow', [])
allowed = set(allowed)
to_cast = []
for caster in args:
param_name, func = caster
if not callable(func):
raise TypeError('cast func must be callable')
allowed.add(param_name)
to_cast.append(caster)
return allowed, to_cast
","import functools
import inspect
import cherrypy
from cherrypy.lib.httputil import parse_query_string
from cherryontop.errors import InvalidParameter, UnexpectedParameter
def typecast_query_params(*a, **kw):
allowed, cast_funcs = _get_checks(*a, **kw)
def wrap(f):
dynamic_url_args = _positional_arg_names(f)
if set(allowed) & set(dynamic_url_args): # disjoint?
msg = 'query param and dynamic url component names cannot match'
raise ValueError(msg)
@functools.wraps(f)
def wrapped(*args, **kwargs):
query_params = parse_query_string(cherrypy.request.query_string)
# no param names conflict with dynamic url component names
for param in query_params:
if param in dynamic_url_args:
raise UnexpectedParameter(param)
# all supplied parameters allowed?
for param in query_params:
if param not in allowed:
raise UnexpectedParameter(param)
# typecast params
for param, cast in cast_funcs:
if param in query_params:
try:
query_params[param] = cast(query_params[param])
except ValueError:
raise InvalidParameter(param)
kwargs.update(query_params)
return f(*args, **kwargs)
return wrapped
return wrap
def _get_checks(*args, **kwargs):
allowed = kwargs.pop('allow', [])
allowed = set(allowed)
to_cast = []
for caster in args:
param_name, func = caster
if not callable(func):
raise TypeError('cast func must be callable')
allowed.add(param_name)
to_cast.append(caster)
return allowed, to_cast
def _positional_arg_names(f):
spec = inspect.getargspec(f)
args = spec.args
num_positional = len(args) - len(spec.defaults)
return args[:num_positional]
"
Add useHistoryState-plugin to plugins. (not only create),"Ext.namespace('Kwc.List.Switch');
Kwc.List.Switch.Component = Ext.extend(Kwf.EyeCandy.List,
{
//transition: {},
showArrows: true,
defaultState: 'normal',
childSelector: '> div > .listSwitchItem',
_init: function() {
this.states = [
'normal'
];
if (!this.plugins) this.plugins = [];
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveListener.LargeContentAjax({
largeContainerSelector: '.listSwitchLargeContent',
transition: this.transition.type,
transitionConfig: this.transition
}));
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.Click({}));
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.DefaultActiveClass({}));
if (this.showArrows) {
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.NextPreviousLinks({
}));
}
if (this.showPlayPause) {
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.PlayPauseLink({
autoPlay: this.autoPlay
}));
}
if (this.useHistoryState) {
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.HistoryState({
}));
}
Kwc.List.Switch.Component.superclass._init.call(this);
}
});
","Ext.namespace('Kwc.List.Switch');
Kwc.List.Switch.Component = Ext.extend(Kwf.EyeCandy.List,
{
//transition: {},
showArrows: true,
defaultState: 'normal',
childSelector: '> div > .listSwitchItem',
_init: function() {
this.states = [
'normal'
];
if (!this.plugins) this.plugins = [];
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveListener.LargeContentAjax({
largeContainerSelector: '.listSwitchLargeContent',
transition: this.transition.type,
transitionConfig: this.transition
}));
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.Click({}));
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.DefaultActiveClass({}));
if (this.showArrows) {
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.NextPreviousLinks({
}));
}
if (this.showPlayPause) {
this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.PlayPauseLink({
autoPlay: this.autoPlay
}));
}
if (this.useHistoryState) {
new Kwf.EyeCandy.List.Plugins.ActiveChanger.HistoryState({
});
}
Kwc.List.Switch.Component.superclass._init.call(this);
}
});
"
"Change setData test
Let setData assert not equals to origin content.","response = new MessagePackResponse([
'hello' => 'lumtify'
]);
}
/**
* Test Extends Response
*
* @return void
*/
public function testExtendsResponse()
{
$this->assertTrue($this->response instanceof Response);
}
/**
* Test setData.
*
* @return void
*/
public function testSetData()
{
$origin = $this->response->getContent();
$data = $this->response->setData([
'a' => 'ha'
]);
$this->assertNotEquals($data->getContent(), $origin);
}
/**
* Test getData.
*
* @return void
*/
public function testGetData()
{
$data = $this->response->getData();
$this->assertEquals([
'hello' => 'lumtify'
], $data);
}
}
","response = new MessagePackResponse([
'hello' => 'lumtify'
]);
}
/**
* Test Extends Response
*
* @return void
*/
public function testExtendsResponse()
{
$this->assertTrue($this->response instanceof Response);
}
/**
* Test setData.
*
* @return void
*/
public function testSetData()
{
$data = $this->response->setData([
'a' => 'ha'
]);
$this->assertEquals($data, $this->response->getContent()->content);
}
/**
* Test getData.
*
* @return void
*/
public function testGetData()
{
$data = $this->response->getData();
$this->assertEquals([
'hello' => 'lumtify'
], $data);
}
}
"
Define options for API at near place,"'use strict';
const https = require('https');
const request = require('request');
console.log('Loading function');
exports.handler = (event, context, callback) => {
var token = event.token;
var body = """";
var githubOptions = {
url: ""https://api.github.com/notifications"",
headers: {
""Content-type"": ""application/json"",
""User-Agent"": ""Awesome-Octocat-App"",
""Authorization"": `token ${event.token}`
}
}
var slackOptions = {
url: `https://hooks.slack.com${event.path}`,
headers: {
""Content-type"": ""application/json""
}
};
request(githubOptions, (error, response, body) => {
JSON.parse(body).forEach((notification) => {
var data = JSON.stringify({
""attachments"": [
{
""title"": notification.subject.title,
""text"": notification.subject.url.replace(/api\./, '').replace(/repos\//, '')
}
]
});
request.post(slackOptions, (error, response, body) => {
console.log(body);
}).form(data);
});
});
callback(null, 'hoge'); // Echo back the first key value
};
","'use strict';
const https = require('https');
const request = require('request');
console.log('Loading function');
exports.handler = (event, context, callback) => {
var token = event.token;
var body = """";
var githubOptions = {
url: ""https://api.github.com/notifications"",
headers: {
""Content-type"": ""application/json"",
""User-Agent"": ""Awesome-Octocat-App"",
""Authorization"": `token ${event.token}`
}
}
request(githubOptions, (error, response, body) => {
JSON.parse(body).forEach((notification) => {
var data = JSON.stringify({
""attachments"": [
{
""title"": notification.subject.title,
""text"": notification.subject.url.replace(/api\./, '').replace(/repos\//, '')
}
]
});
var slackOptions = {
url: `https://hooks.slack.com${event.path}`,
headers: {
""Content-type"": ""application/json""
},
form: data
};
request.post(slackOptions, (error, response, body) => {
console.log(body);
});
});
});
callback(null, 'hoge'); // Echo back the first key value
};
"
Remove null checks for notification params,"package name.snavrotskiy.ant.listener;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
/**
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
*
* Notification parameters
*/
class NotificationParams {
/**
* Tray icon.
*/
private final URL icon;
/**
* Notification title.
*/
private final String title;
/**
* Notification message.
*/
private final String message;
/**
* Default constructor. All parameters have to be non-null
*
* @param trayIcon tray icon
* @param notificationTitle notification title
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
}
/**
* Get uri for tray icon.
*
* @return uri
*/
URL getIcon() {
return icon;
}
/**
* Get notification title.
*
* @return title
*/
String getTitle() {
return title;
}
/**
* Get notification message.
*
* @return message
*/
String getMessage() {
return message;
}
}
","package name.snavrotskiy.ant.listener;
import com.google.common.base.Preconditions;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
/**
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
*
* Notification parameters
*/
class NotificationParams {
/**
* Tray icon.
*/
private final URL icon;
/**
* Notification title.
*/
private final String title;
/**
* Notification message.
*/
private final String message;
/**
* Default constructor. All parameters have to be non-null
*
* @param trayIcon tray icon
* @param notificationTitle notification title
* @param notificationMessage notification message
*/
NotificationParams(@NotNull final URL trayIcon, @NotNull final String notificationTitle, @NotNull final String notificationMessage) {
Preconditions.checkNotNull(trayIcon);
Preconditions.checkNotNull(notificationTitle);
Preconditions.checkNotNull(notificationMessage);
icon = trayIcon;
title = notificationTitle;
message = notificationMessage;
}
/**
* Get uri for tray icon.
*
* @return uri
*/
URL getIcon() {
return icon;
}
/**
* Get notification title.
*
* @return title
*/
String getTitle() {
return title;
}
/**
* Get notification message.
*
* @return message
*/
String getMessage() {
return message;
}
@Override
public String toString() {
return ""NotificationParams{""
+ ""icon="" + icon
+ "", title='"" + title + '\''
+ "", message='"" + message + '\''
+ '}';
}
}
"
Add proper fields for the form.,"var _ = require('underscore');
var WidgetsFormBaseSchema = require('./widgets-form-base-schema-model');
module.exports = WidgetsFormBaseSchema.extend({
initialize: function (attrs, opts) {
if (!opts.columnOptionsFactory) throw new Error('columnOptionsFactory is required');
this._columnOptionsFactory = opts.columnOptionsFactory;
WidgetsFormBaseSchema.prototype.initialize.apply(this, arguments);
},
getFields: function () {
return {
data: 'column,bins',
style: 'sync_on_bbox_change'
};
},
updateSchema: function () {
var columnOptions = this._columnOptionsFactory.create(this.get('column'), this._isDateType);
var helpMsg = this._columnOptionsFactory.unavailableColumnsHelpMessage();
this.schema = _.extend(this.schema, {
column: {
title: _t('editor.widgets.widgets-form.data.column'),
type: 'Select',
help: helpMsg,
options: columnOptions,
editorAttrs: {
disabled: this._columnOptionsFactory.areColumnsUnavailable()
}
},
bins: {
title: _t('editor.widgets.widgets-form.data.bins'),
type: 'Number',
validators: ['required', {
type: 'interval',
min: 0,
max: 30
}]
}
});
},
canSave: function () {
return this.get('column');
},
_isDateType: function (m) {
return m.get('type') === 'date' || m.get('type') === 'number';
}
});
","var _ = require('underscore');
var WidgetsFormBaseSchema = require('./widgets-form-base-schema-model');
module.exports = WidgetsFormBaseSchema.extend({
initialize: function (attrs, opts) {
if (!opts.columnOptionsFactory) throw new Error('columnOptionsFactory is required');
this._columnOptionsFactory = opts.columnOptionsFactory;
WidgetsFormBaseSchema.prototype.initialize.apply(this, arguments);
},
updateSchema: function () {
var columnOptions = this._columnOptionsFactory.create(this.get('column'), this._isDateType);
var helpMsg = this._columnOptionsFactory.unavailableColumnsHelpMessage();
this.schema = _.extend(this.schema, {
column: {
title: _t('editor.widgets.widgets-form.data.column'),
type: 'Select',
help: helpMsg,
options: columnOptions,
editorAttrs: {
disabled: this._columnOptionsFactory.areColumnsUnavailable()
}
},
bins: {
title: _t('editor.widgets.widgets-form.data.bins'),
type: 'Number',
validators: ['required', {
type: 'interval',
min: 0,
max: 30
}]
}
});
},
canSave: function () {
return this.get('column');
},
_isDateType: function (m) {
return m.get('type') === 'date' || m.get('type') === 'number';
}
});
"
"Implement getArrayCopy method to solve error:
Zend\\Stdlib\\Hydrator\\ArraySerializable::extract expects the provided
object to implement getArrayCopy()","id;
}
/**
*
* @return the $name
*/
public function getName()
{
return $this->name;
}
/**
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
// @todo: Add phones support
// @todo: Add Gedmo Annotations support
/**
*
* @see Zend\\Stdlib\\Hydrator\\ArraySerializable::extract expects the provided object to implement getArrayCopy()
* @return multitype
*/
public function getArrayCopy()
{
return get_object_vars($this);
}
}","id;
}
/**
*
* @return the $name
*/
public function getName()
{
return $this->name;
}
/**
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
// @todo: Add phones support
// @todo: Add Gedmo Annotations support
// @todo: Check if getArrayCopy() function is required
}"
Fix settings for username and email,"// Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
forceEmailLowercase: true,
forceUsernameLowercase: true,
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username',
fieldLabel: 'Username',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction(""Please write your username"");
return false;
} else {
return true;
}
}
}, {
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction(""Please write your first name"");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions *',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
","// Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username',
fieldLabel: 'Username',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction(""Please write your username"");
return false;
} else {
return true;
}
}
}, {
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction(""Please write your first name"");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions *',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
"
Disable import of `content_modified_at` for assets [WEB-1870]," $datum->id,
];
}
// Unfortunately, NetX does not provide this data:
// protected function getDates(Datum $datum)
// {
// $dates = parent::getDates($datum);
// return array_merge($dates, [
// 'content_modified_at' => $datum->date('content_modified_at'),
// ]);
// }
protected function getSync(Datum $datum, $test = false)
{
return [
'imagedArtworks' => $this->getSyncAssetOf($datum, 'rep_of_artworks'),
'imagedExhibitions' => $this->getSyncAssetOf($datum, 'rep_of_exhibitions'),
'documentedArtworks' => $this->getSyncAssetOf($datum, 'doc_of_artworks'),
'documentedExhibitions' => $this->getSyncAssetOf($datum, 'doc_of_exhibitions'),
];
}
private function getSyncAssetOf(Datum $datum, string $pivot_field)
{
return $this->getSyncPivots($datum, $pivot_field, 'related_id', function ($pivot) {
return [
$pivot->related_id => [
'preferred' => $pivot->is_preferred,
'is_doc' => $pivot->is_doc,
],
];
});
}
}
"," $datum->id,
];
}
protected function getDates(Datum $datum)
{
$dates = parent::getDates($datum);
return array_merge($dates, [
'content_modified_at' => $datum->date('content_modified_at'),
]);
}
protected function getSync(Datum $datum, $test = false)
{
return [
'imagedArtworks' => $this->getSyncAssetOf($datum, 'rep_of_artworks'),
'imagedExhibitions' => $this->getSyncAssetOf($datum, 'rep_of_exhibitions'),
'documentedArtworks' => $this->getSyncAssetOf($datum, 'doc_of_artworks'),
'documentedExhibitions' => $this->getSyncAssetOf($datum, 'doc_of_exhibitions'),
];
}
private function getSyncAssetOf(Datum $datum, string $pivot_field)
{
return $this->getSyncPivots($datum, $pivot_field, 'related_id', function ($pivot) {
return [
$pivot->related_id => [
'preferred' => $pivot->is_preferred,
'is_doc' => $pivot->is_doc,
],
];
});
}
}
"
Handle exceptions when cropping images.,"argument('start');
Post::where('id', '>', $start)->chunk(100, function ($posts) use ($aws) {
foreach ($posts as $post) {
$image = $post->url;
try {
$editedImage = (string) Image::make($image)
->orientate()
->fit(400)
->encode('jpg', 75);
$aws->storeImageData($editedImage, 'edited_'.$post->id);
} catch (ImageException $e) {
$this->error('Failed to edit image for post '.$post->id);
}
$this->line('Saved edited image for post '.$post->id);
}
});
}
}
","argument('start');
Post::where('id', '>', $start)->chunk(100, function ($posts) use ($aws) {
foreach ($posts as $post) {
$image = $post->url;
$editedImage = (string) Image::make($image)
->orientate()
->fit(400)
->encode('jpg', 75);
$aws->storeImageData($editedImage, 'edited_'.$post->id);
$this->line('Saved edited image for post '.$post->id);
}
});
}
}
"
Set short timeout before reload following tab query as script content sometimes does not render without.,"const filesInDirectory = dir => new Promise (resolve =>
dir.createReader ().readEntries (entries =>
Promise.all (entries.filter (e => e.name[0] !== '.').map (e =>
e.isDirectory
? filesInDirectory (e)
: new Promise (resolve => e.file (resolve))
))
.then (files => [].concat (...files))
.then (resolve)
)
)
const timestampForFilesInDirectory = dir =>
filesInDirectory (dir).then (files =>
files.map (f => f.name + f.lastModifiedDate).join ())
const reload = () => {
chrome.tabs.query ({ active: true, currentWindow: true }, tabs => { // NB: see https://github.com/xpl/crx-hotreload/issues/5
if (tabs[0]) { chrome.tabs.reload (tabs[0].id) }
{
setTimeout(function () {
chrome.runtime.reload ()
}, 500)
}
})
}
const watchChanges = (dir, lastTimestamp) => {
timestampForFilesInDirectory (dir).then (timestamp => {
if (!lastTimestamp || (lastTimestamp === timestamp)) {
setTimeout (() => watchChanges (dir, timestamp), 1000) // retry after 1s
} else {
reload ()
}
})
}
chrome.management.getSelf (self => {
if (self.installType === 'development') {
chrome.runtime.getPackageDirectoryEntry (dir => watchChanges (dir))
}
})
","const filesInDirectory = dir => new Promise (resolve =>
dir.createReader ().readEntries (entries =>
Promise.all (entries.filter (e => e.name[0] !== '.').map (e =>
e.isDirectory
? filesInDirectory (e)
: new Promise (resolve => e.file (resolve))
))
.then (files => [].concat (...files))
.then (resolve)
)
)
const timestampForFilesInDirectory = dir =>
filesInDirectory (dir).then (files =>
files.map (f => f.name + f.lastModifiedDate).join ())
const reload = () => {
chrome.tabs.query ({ active: true, currentWindow: true }, tabs => { // NB: see https://github.com/xpl/crx-hotreload/issues/5
if (tabs[0]) { chrome.tabs.reload (tabs[0].id) }
chrome.runtime.reload ()
})
}
const watchChanges = (dir, lastTimestamp) => {
timestampForFilesInDirectory (dir).then (timestamp => {
if (!lastTimestamp || (lastTimestamp === timestamp)) {
setTimeout (() => watchChanges (dir, timestamp), 1000) // retry after 1s
} else {
reload ()
}
})
}
chrome.management.getSelf (self => {
if (self.installType === 'development') {
chrome.runtime.getPackageDirectoryEntry (dir => watchChanges (dir))
}
})
"
Copy reference handling methods to collection as well,"VIE.prototype.Collection = Backbone.Collection.extend({
model: VIE.prototype.Entity,
get: function(id) {
if (id == null) return null;
id = this.toReference(id);
return this._byId[id.id != null ? id.id : id];
},
addOrUpdate: function(model) {
var collection = this;
if (_.isArray(model)) {
var entities = [];
_.each(model, function(item) {
entities.push(collection.addOrUpdate(item));
});
return entities;
}
if (!model.isEntity) {
model = new this.model(model);
}
if (!model.id) {
this.add(model);
return model;
}
if (this.get(model.id)) {
var existing = this.get(model.id);
if (model.attributes) {
return existing.set(model.attributes);
}
return existing.set(model);
}
this.add(model);
return model;
},
isReference: function(uri){
var matcher = new RegExp(""^\\<([^\\>]*)\\>$"");
if (matcher.exec(uri)) {
return true;
}
return false;
},
toReference: function(uri){
if (this.isReference(uri)) {
return uri;
}
return '<' + uri + '>';
},
fromReference: function(uri){
if (!this.isReference(uri)) {
return uri;
}
return uri.substring(1, uri.length - 1);
}
});
","VIE.prototype.Collection = Backbone.Collection.extend({
model: VIE.prototype.Entity,
get: function(id) {
if (!this.models.length) {
return null;
}
if (!this.models[0].isReference(id)) {
id = this.models[0].toReference(id);
}
if (id == null) return null;
return this._byId[id.id != null ? id.id : id];
},
addOrUpdate: function(model) {
var collection = this;
if (_.isArray(model)) {
var entities = [];
_.each(model, function(item) {
entities.push(collection.addOrUpdate(item));
});
return entities;
}
if (!model.isEntity) {
model = new this.model(model);
}
if (!model.id) {
this.add(model);
return model;
}
if (this.get(model.id)) {
var existing = this.get(model.id);
if (model.attributes) {
return existing.set(model.attributes);
}
return existing.set(model);
}
this.add(model);
return model;
}
});
"
"OEE-54: Modify ACL. Refactor ACL Walker.
- Add set organization listener","getEntityManager()
->createQuery('SELECT org FROM OroOrganizationBundle:Organization org ORDER BY org.id')
->setMaxResults(1)
->getSingleResult();
}
/**
* Get organization by id
*
* @param $id
* @return Organization
*/
public function getOrganizationById($id)
{
return $this->getEntityManager()
->createQuery('SELECT org FROM OroOrganizationBundle:Organization org WHERE org.id = :id')
->setParameter('id', $id)
->getSingleResult();
}
/**
* Update all records in given table with organization id
*
* @param string $tableName table name to update, example: OroCRMAccountBundle:Account or OroUserBundle:Group
* @param integer $id Organization id
*
* @return integer Number of rows affected
*/
public function updateWithOrganization($tableName, $id)
{
return $this->getEntityManager()
->createQueryBuilder()
->update($tableName, 't')
->set('t.organization', ':id')
->setParameter('id', $id)
->getQuery()
->execute();
}
}
","getEntityManager()
->createQuery('SELECT org FROM OroOrganizationBundle:Organization org ORDER BY org.id')
->setMaxResults(1)
->getSingleResult();
}
public function getOrganizationById($id)
{
return $this->getEntityManager()
->createQuery('SELECT org FROM OroOrganizationBundle:Organization org WHERE org.id = :id')
->setParameter('id', $id)
->getSingleResult();
}
/**
* Update all records in given table with organization id
*
* @param string $tableName table name to update, example: OroCRMAccountBundle:Account or OroUserBundle:Group
* @param integer $id Organization id
*
* @return integer Number of rows affected
*/
public function updateWithOrganization($tableName, $id)
{
return $this->getEntityManager()
->createQueryBuilder()
->update($tableName, 't')
->set('t.organization', ':id')
->setParameter('id', $id)
->getQuery()
->execute();
}
}
"
Create a copy of node data for modal state.,"import { $$, Component } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'
export default class CitationModal extends Component {
getInitialState () {
const { mode, node } = this.props
const value = mode === 'edit' ? node.references.slice() : []
return { value }
}
render () {
const { document, mode } = this.props
const { value } = this.state
const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'
const root = document.root
const referencesList = root.resolve('references')
const disableConfirm = value.length === 0
const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' }
return $$(Modal, modalProps,
$$(Form, {},
$$(FormRow, {},
$$(MultiSelect, {
options: referencesList.map(ref => {
return { value: ref.id, label: ref.content }
}),
value,
label: 'Select Reference',
placeholder: 'Please select one or more references',
onchange: this._updateReferencess
}).ref('references')
)
)
)
}
_updateReferencess () {
const value = this.refs.references.val()
this.extendState({ value })
}
}
","import { $$, Component } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'
export default class CitationModal extends Component {
getInitialState () {
const { mode, node } = this.props
const value = mode === 'edit' ? node.references : []
return { value }
}
render () {
const { document, mode } = this.props
const { value } = this.state
const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'
const root = document.root
const referencesList = root.resolve('references')
const disableConfirm = value.length === 0
const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' }
return $$(Modal, modalProps,
$$(Form, {},
$$(FormRow, {},
$$(MultiSelect, {
options: referencesList.map(ref => {
return { value: ref.id, label: ref.content }
}),
value,
label: 'Select Reference',
placeholder: 'Please select one or more references',
onchange: this._updateReferencess
}).ref('references')
)
)
)
}
_updateReferencess () {
const value = this.refs.references.val()
this.extendState({ value })
}
}
"
"GUI: Make stop button from custom gui keep partial results
git-svn-id: c451f99c539e6b066ec18a47a9c67064d2e0d34d@8709 fc29be9c-2cb0-420d-b520-73dbd18add6e","/*
* IKToolExecutor.java
*
* Created on August 11, 2010, 12:38 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.opensim.tools.serializers;
import java.io.IOException;
import java.util.Observable;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolExecutor.Operation;
import org.opensim.tracking.ForwardToolModel;
import org.opensim.tracking.ResultDisplayerInterface;
/**
*
* @author ayman
*/
public class ForwardToolExecutor extends ToolExecutor {
ForwardToolModel toolModel;
/** Creates a new instance of IKToolExecutor */
public ForwardToolExecutor(Model model, String setupFile, ResultDisplayerInterface displayer) throws IOException {
super(model, setupFile);
toolModel = new ForwardToolModel(model);
toolModel.addResultDisplayer(displayer);
//toolModel.loadSettings(setupFile);
toolModel.addObserver(this);
}
public void execute() {
toolModel.loadSettings(setupFile);
toolModel.execute();
}
public void cancel() {
toolModel.interrupt(true);
}
public void update(Observable o, Object arg) {
if (arg==ForwardToolModel.Operation.ExecutionStateChanged && !toolModel.isExecuting()){
setChanged();
notifyObservers(Operation.ExecutionFinished);
}
}
}
","/*
* IKToolExecutor.java
*
* Created on August 11, 2010, 12:38 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.opensim.tools.serializers;
import java.io.IOException;
import java.util.Observable;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolExecutor.Operation;
import org.opensim.tracking.ForwardToolModel;
import org.opensim.tracking.ResultDisplayerInterface;
/**
*
* @author ayman
*/
public class ForwardToolExecutor extends ToolExecutor {
ForwardToolModel toolModel;
/** Creates a new instance of IKToolExecutor */
public ForwardToolExecutor(Model model, String setupFile, ResultDisplayerInterface displayer) throws IOException {
super(model, setupFile);
toolModel = new ForwardToolModel(model);
toolModel.addResultDisplayer(displayer);
//toolModel.loadSettings(setupFile);
toolModel.addObserver(this);
}
public void execute() {
toolModel.loadSettings(setupFile);
toolModel.execute();
}
public void cancel() {
toolModel.cancel();
}
public void update(Observable o, Object arg) {
if (arg==ForwardToolModel.Operation.ExecutionStateChanged && !toolModel.isExecuting()){
setChanged();
notifyObservers(Operation.ExecutionFinished);
}
}
}
"
Add code to handle a file which comes from a temporary directory.,"path = str_replace($config[""ROOT""], """", $path);
} else {
$this->path = substr($path, strpos($path, $this->module->name) + strlen($this->module->name) + 1);
}
$this->name = basename($path);
$this->startLine = $dict[""startLine""];
$this->startColumn = $dict[""startColumn""];
$this->endLine = $dict[""endLine""];
$this->endColumn = $dict[""endColumn""];
$this->rule = $dict[""rule""];
$this->priority = $dict[""priority""];
$this->message = $dict[""message""];
$path = $this->path;
$gitHubRoot = $config[""GITHUB_ROOT""];
if (array_key_exists($this->module->name, $config[""GITHUB_ROOTS""])) {
$gitHubRoot = $config[""GITHUB_ROOTS""][$this->module->name];
$pathPrefixToRemove = $config[""COCOAPODS_PREFIX""].$this->module->name;
$path = str_replace($pathPrefixToRemove, """", $path);
}
$this->link = $gitHubRoot . $path . ""#L"" . $this->startLine . ""-"" . $this->endLine;
}
};
?>","path = str_replace($config[""ROOT""], """", $path);
$this->name = basename($path);
$this->startLine = $dict[""startLine""];
$this->startColumn = $dict[""startColumn""];
$this->endLine = $dict[""endLine""];
$this->endColumn = $dict[""endColumn""];
$this->rule = $dict[""rule""];
$this->priority = $dict[""priority""];
$this->message = $dict[""message""];
$path = $this->path;
$gitHubRoot = $config[""GITHUB_ROOT""];
if (array_key_exists($this->module->name, $config[""GITHUB_ROOTS""])) {
$gitHubRoot = $config[""GITHUB_ROOTS""][$this->module->name];
$pathPrefixToRemove = $config[""COCOAPODS_PREFIX""].$this->module->name;
$path = str_replace($pathPrefixToRemove, """", $path);
}
$this->link = $gitHubRoot . $path . ""#L"" . $this->startLine . ""-"" . $this->endLine;
}
};
?>"
"Add serialization and deserlization for User
Serialization step: get the user.id as a cookie value and send it back to the client for later user.
Deserialization: client sends make a request with cookie value that can be turned into an actual user instance.","const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('../config/keys');
const mongoose = require('mongoose');
const User = mongoose.model('users'); // retrieve this collection
// Tell passport to use google oauth for authentication
passport.use(
new GoogleStrategy(
{
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback'
},
// Get executed when a user is actually executed. we can store this on the database
// to link this token to a user for later use.
(accessToken, refreshToken, profile, done) => {
User.findOne({googleId: profile.id})
.then( existingUser => {
if ( existingUser ) {
// first arg: no error, second arg: tell passport that this is the user that we just created
done(null, existingUser);
} else {
new User({ googleId: profile.id }) // create a user model instance
.save() //save it to db
.then(user => done(null, user)); // finish saving, so we need to call done to finish the OAuth process
}
});
} )
);
// Once we get the user instance from the db ( this happens after the authentication process above finishes )
// We ask passport to use user.id ( not googleId ), created by MongoDb, to send this info to the client
// by setting it in the cookie, so that future requests from the client will have this information in the cookie
// set automatically by the browser
passport.serializeUser( (user, done) => {
done(null, user.id);
});
// Client sends more requests to the server after all the auth process. Passport will use the cookie info
// in the request to create or query for the User instance associated with that info
passport.deserializeUser( (id, done) => {
User.findById(id)
.then(user => done( null, user));
});
// Tell passport that it needs to use cookie to keep track of the currently signed in user
","const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('../config/keys');
const mongoose = require('mongoose');
const User = mongoose.model('users'); // retrieve this collection
// Tell passport to use google oauth for authentication
passport.use(
new GoogleStrategy(
{
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback'
},
// Get executed when a user is actually executed. we can store this on the database
// to link this token to a user for later use.
(accessToken, refreshToken, profile, done) => {
User.findOne({googleId: profile.id})
.then( existingUser => {
if ( existingUser ) {
// first arg: no error, second arg: tell passport that this is the user that we just created
done(null, existingUser);
} else {
new User({ googleId: profile.id }) // create a user model instance
.save() //save it to db
.then(user => done(null, user)); // finish saving, so we need to call done to finish the OAuth process
}
});
} )
);"
Raise version and change keywords for upcoming release,"from setuptools import setup, find_packages
import os
version = '0.5'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description=""Admin Controller add-on for basic TG identity model."",
long_description=README + ""\n"" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
""Programming Language :: Python"",
""Topic :: Software Development :: Libraries :: Python Modules"",
],
keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin',
author='Christopher Perkins',
author_email='chris@percious.com',
url='tgtools.googlecode.com',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.4',
# -*- Extra requirements: -*-
],
entry_points=""""""
# -*- Entry points: -*-
"""""",
)
","from setuptools import setup, find_packages
import os
version = '0.4'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description=""Admin Controller add-on for basic TG identity model."",
long_description=README + ""\n"" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
""Programming Language :: Python"",
""Topic :: Software Development :: Libraries :: Python Modules"",
],
keywords='TG2, TG, sprox, Rest, internet, adminn',
author='Christopher Perkins',
author_email='chris@percious.com',
url='tgtools.googlecode.com',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.4',
# -*- Extra requirements: -*-
],
entry_points=""""""
# -*- Entry points: -*-
"""""",
)
"
Fix manageId typo causing error when creating on dashboard,"///
///
(function () {
angular
.module('GVA.Creation')
.controller('DashboardController', DashboardController);
DashboardController.$inject = ['$scope', 'AccountService', 'PollService'];
function DashboardController($scope, AccountService, PollService) {
$scope.account = AccountService.account;
$scope.createPoll = createNewPoll;
$scope.getUserPolls = getUserPolls;
$scope.navigateToManagePage = navigateToManagePage;
$scope.userPolls = {};
activate();
function activate() {
AccountService.registerAccountObserver(function () {
$scope.account = AccountService.account;
});
getUserPolls();
}
function createNewPoll(question) {
PollService.createPoll(question, createPollSuccessCallback);
}
function createPollSuccessCallback(data) {
navigateToManagePage(data.ManageId);
}
function getUserPolls() {
PollService.getUserPolls()
.success(function (data) {
$scope.userPolls = data;
});
}
function navigateToManagePage(manageId) {
window.location.href = '/#/Manage/' + manageId;
};
}
})();
","///
///
(function () {
angular
.module('GVA.Creation')
.controller('DashboardController', DashboardController);
DashboardController.$inject = ['$scope', 'AccountService', 'PollService'];
function DashboardController($scope, AccountService, PollService) {
$scope.account = AccountService.account;
$scope.createPoll = createNewPoll;
$scope.getUserPolls = getUserPolls;
$scope.navigateToManagePage = navigateToManagePage;
$scope.userPolls = {};
activate();
function activate() {
AccountService.registerAccountObserver(function () {
$scope.account = AccountService.account;
});
getUserPolls();
}
function createNewPoll(question) {
PollService.createPoll(question, createPollSuccessCallback);
}
function createPollSuccessCallback(data) {
navigateToManagePage(data.manageId);
}
function getUserPolls() {
PollService.getUserPolls()
.success(function (data) {
$scope.userPolls = data;
});
}
function navigateToManagePage(manageId) {
window.location.href = '/#/Manage/' + manageId;
};
}
})();
"
[DASH-2397] Refresh hostings after closing modal,"import Reflux from 'reflux';
import _ from 'lodash';
import { CheckListStoreMixin, HostingMixin, WaitForStoreMixin, StoreLoadingMixin } from '../../mixins';
import SessionActions from '../Session/SessionActions';
import Actions from './HostingActions';
export default Reflux.createStore({
listenables: Actions,
mixins: [
CheckListStoreMixin,
HostingMixin,
WaitForStoreMixin,
StoreLoadingMixin
],
getInitialState() {
return {
items: [],
isLoading: false
};
},
init() {
this.data = this.getInitialState();
this.waitFor(
SessionActions.setInstance,
this.refreshData
);
this.setLoadingStates();
},
sendHostingAnalytics(type, payload) {
window.analytics.track('Used Dashboard Sockets API', {
type,
instance: payload.instanceName,
socketId: payload.label,
socket: 'hosting'
});
},
setHosting(data) {
this.data.items = _.forEach(data, this.prepareHosting);
this.trigger(this.data);
},
refreshData() {
Actions.fetchHostings();
},
onFetchHostingsCompleted(data) {
Actions.setHosting(data);
},
onCreateHostingCompleted(payload) {
this.refreshData();
this.sendHostingAnalytics('add', payload);
},
onUpdateHostingCompleted(payload) {
this.refreshData();
this.sendHostingAnalytics('edit', payload);
},
onRemoveHostingsCompleted(payload) {
this.refreshData();
this.sendHostingAnalytics('delete', payload);
}
});
","import Reflux from 'reflux';
import _ from 'lodash';
import { CheckListStoreMixin, HostingMixin, WaitForStoreMixin, StoreLoadingMixin } from '../../mixins';
import SessionActions from '../Session/SessionActions';
import Actions from './HostingActions';
export default Reflux.createStore({
listenables: Actions,
mixins: [
CheckListStoreMixin,
HostingMixin,
WaitForStoreMixin,
StoreLoadingMixin
],
getInitialState() {
return {
items: [],
isLoading: false
};
},
init() {
this.data = this.getInitialState();
this.waitFor(
SessionActions.setInstance,
this.refreshData
);
this.setLoadingStates();
},
sendHostingAnalytics(type, payload) {
window.analytics.track('Used Dashboard Sockets API', {
type,
instance: payload.instanceName,
socketId: payload.label,
socket: 'hosting'
});
},
setHosting(data) {
this.data.items = _.forEach(data, this.prepareHosting);
this.trigger(this.data);
},
refreshData() {
Actions.fetchHostings();
},
onFetchHostingsCompleted(data) {
Actions.setHosting(data);
},
onCreateHostingCompleted(payload) {
this.sendHostingAnalytics('add', payload);
},
onUpdateHostingCompleted(payload) {
this.sendHostingAnalytics('edit', payload);
},
onRemoveHostingsCompleted(payload) {
this.refreshData();
this.sendHostingAnalytics('delete', payload);
}
});
"
"Return the SystemException's description in extra information only if not empty
see 72ae641557703c600de12c07a04346ba16001251","
* @package WoltLabSuite\Core\System\Exception
*/
class SystemException extends LoggedException implements IExtraInformationException
{
/**
* error description
* @var string
*/
protected $description;
/**
* additional information
* @var string
*/
protected $information = '';
/**
* additional information
* @var string
*/
protected $functions = '';
/**
* Creates a new SystemException.
*
* @param string $message error message
* @param int $code error code
* @param string $description description of the error
* @param \Exception $previous repacked Exception
*/
public function __construct($message = '', $code = 0, $description = '', ?\Exception $previous = null)
{
parent::__construct((string)$message, (int)$code, $previous);
$this->description = $description;
}
/**
* Returns the description of this exception.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @inheritDoc
*/
public function getExtraInformation()
{
if ($this->description) {
return [
['Description', $this->description],
];
}
return [];
}
/**
* @inheritDoc
*/
public function show()
{
}
}
","
* @package WoltLabSuite\Core\System\Exception
*/
class SystemException extends LoggedException implements IExtraInformationException
{
/**
* error description
* @var string
*/
protected $description;
/**
* additional information
* @var string
*/
protected $information = '';
/**
* additional information
* @var string
*/
protected $functions = '';
/**
* Creates a new SystemException.
*
* @param string $message error message
* @param int $code error code
* @param string $description description of the error
* @param \Exception $previous repacked Exception
*/
public function __construct($message = '', $code = 0, $description = '', ?\Exception $previous = null)
{
parent::__construct((string)$message, (int)$code, $previous);
$this->description = $description;
}
/**
* Returns the description of this exception.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @inheritDoc
*/
public function getExtraInformation()
{
return [
['Description', $this->description],
];
}
/**
* @inheritDoc
*/
public function show()
{
}
}
"
Reset to device connection usb communication,"package com.github.mjdev.libaums.usb;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.os.Build;
import android.util.Log;
/**
* Created by magnusja on 21/12/16.
*/
public class UsbCommunicationFactory {
enum UnderlyingUsbCommunication {
USB_REQUEST_ASYNC,
DEVICE_CONNECTION_SYNC
}
private static final String TAG = UsbCommunicationFactory.class.getSimpleName();
private static UnderlyingUsbCommunication underlyingUsbCommunication = UnderlyingUsbCommunication.DEVICE_CONNECTION_SYNC;
public static UsbCommunication createUsbCommunication(UsbDeviceConnection deviceConnection, UsbEndpoint outEndpoint, UsbEndpoint inEndpoint) {
UsbCommunication communication;
if (underlyingUsbCommunication == UnderlyingUsbCommunication.DEVICE_CONNECTION_SYNC) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
communication = new JellyBeanMr2Communication(deviceConnection, outEndpoint, inEndpoint);
} else {
Log.i(TAG, ""using workaround usb communication"");
communication = new HoneyCombMr1Communication(deviceConnection, outEndpoint, inEndpoint);
}
} else {
communication = new UsbRequestCommunication(deviceConnection, outEndpoint, inEndpoint);
}
return communication;
}
public static void setUnderlyingUsbCommunication(UnderlyingUsbCommunication underlyingUsbCommunication) {
UsbCommunicationFactory.underlyingUsbCommunication = underlyingUsbCommunication;
}
}
","package com.github.mjdev.libaums.usb;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.os.Build;
import android.util.Log;
/**
* Created by magnusja on 21/12/16.
*/
public class UsbCommunicationFactory {
enum UnderlyingUsbCommunication {
USB_REQUEST,
DEVICE_CONNECTION
}
private static final String TAG = UsbCommunicationFactory.class.getSimpleName();
private static UnderlyingUsbCommunication underlyingUsbCommunication = UnderlyingUsbCommunication.USB_REQUEST;
public static UsbCommunication createUsbCommunication(UsbDeviceConnection deviceConnection, UsbEndpoint outEndpoint, UsbEndpoint inEndpoint) {
UsbCommunication communication;
if (underlyingUsbCommunication == UnderlyingUsbCommunication.DEVICE_CONNECTION) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
communication = new JellyBeanMr2Communication(deviceConnection, outEndpoint, inEndpoint);
} else {
Log.i(TAG, ""using workaround usb communication"");
communication = new HoneyCombMr1Communication(deviceConnection, outEndpoint, inEndpoint);
}
} else {
communication = new UsbRequestCommunication(deviceConnection, outEndpoint, inEndpoint);
}
return communication;
}
public static void setUnderlyingUsbCommunication(UnderlyingUsbCommunication underlyingUsbCommunication) {
UsbCommunicationFactory.underlyingUsbCommunication = underlyingUsbCommunication;
}
}
"
Add missing global object to fix broken reference assignment,"var Namespace = (function (global) {
'use strict';
return {
/**
* Creates a global object in a single line.
* // example
* Namespace.create('foo.bar'); // -> foo.bar
*
* @param {string} namespace
*/
create: function (namespace) {
var parent = global,
parts = namespace.split('.'),
len = parts.length,
part,
i
;
for (i = 0; i < len; i++) {
part = parts[i];
parent = (parent[part] = parent[part] || {});
}
},
/**
* Check for global object.
* // example
* Namespace.is('foo.bar'); // -> false
* Namespace.create('foo.bar'); // -> foo.bar
* Namespace.is('foo.bar'); // -> true
*
* @param {string} namespace
*/
is: function (namespace) {
var parent = global,
result = false,
parts = namespace.split('.'),
len = parts.length,
part,
i
;
for (i = 0; i < len; i++) {
part = parts[i];
if (!parent[part]) {
result = false;
return false;
}
parent = parent[part];
result = true;
}
return result;
}
};
}(this));
","var Namespace = (function (global) {
'use strict';
return {
/**
* Creates a global object in a single line.
* // example
* Namespace.create('foo.bar'); // -> foo.bar
*
* @param {string} namespace
*/
create: function (namespace) {
var parent = global,
parts = namespace.split('.'),
len = parts.length,
part,
i
;
for (i = 0; i < len; i++) {
part = parts[i];
parent = (parent[part] = parent[part] || {});
}
},
/**
* Check for global object.
* // example
* Namespace.is('foo.bar'); // -> false
* Namespace.create('foo.bar'); // -> foo.bar
* Namespace.is('foo.bar'); // -> true
*
* @param {string} namespace
*/
is: function (namespace) {
var parent = global,
result = false,
parts = namespace.split('.'),
len = parts.length,
part,
i
;
for (i = 0; i < len; i++) {
part = parts[i];
if (!parent[part]) {
result = false;
return false;
}
parent = parent[part];
result = true;
}
return result;
}
};
}());
"
"Use full pathname to perf_expectations in test.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/266055
git-svn-id: http://src.chromium.org/svn/trunk/src@28770 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: f9d8e0a8dae19e482d3c435a76b4e38403e646b5","#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""""""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
""""""
UNIT_TESTS = [
'tests.perf_expectations_unittest',
]
PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
return output
def CheckChangeOnCommit(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api,
output_api))
return output
","#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""""""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
""""""
UNIT_TESTS = [
'tests.perf_expectations_unittest',
]
PERF_EXPECTATIONS = 'perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
return output
def CheckChangeOnCommit(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api,
output_api))
return output
"
Check database json data type compatibility,"increments('id');
$table->string('slug');
$table->{$this->jsonable()}('name');
$table->{$this->jsonable()}('description')->nullable();
$table->timestamps();
$table->softDeletes();
// Indexes
$table->unique('slug');
// Engine
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(config('rinvex.fort.tables.roles'));
}
/**
* Get jsonable column data type.
*
* @return string
*/
public function jsonable()
{
return DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql'
&& version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')
? 'json' : 'text';
}
}
","increments('id');
$table->json('name');
$table->string('slug');
$table->json('description')->nullable();
$table->timestamps();
$table->softDeletes();
// Indexes
$table->unique('slug');
// Engine
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(config('rinvex.fort.tables.roles'));
}
}
"
Use priority ordering low to high,"package biz.paluch.logcapture.common;
import java.util.Comparator;
import java.util.ServiceLoader;
import java.util.TreeSet;
/**
* @author Mark Paluch
*/
public class Service {
public static MessageCollectionFactory getFactory() {
ServiceLoader loader = ServiceLoader.load(MessageCollectionFactory.class);
TreeSet factories = new TreeSet(
new Comparator() {
@Override
public int compare(MessageCollectionFactory o1, MessageCollectionFactory o2) {
if (o1.priority() > o2.priority()) {
return -1;
}
if (o1.priority() < o2.priority()) {
return 1;
}
return 0;
}
});
for (MessageCollectionFactory messageCollectionFactory : loader) {
factories.add(messageCollectionFactory);
}
if (factories.isEmpty()) {
throw new IllegalStateException(""Cannot retrieve a "" + MessageCollectionFactory.class.getName()
+ "". Please add logcapture modules or create a service extension."");
}
return factories.first();
}
}
","package biz.paluch.logcapture.common;
import java.util.Comparator;
import java.util.ServiceLoader;
import java.util.TreeSet;
/**
* @author Mark Paluch
*/
public class Service {
public static MessageCollectionFactory getFactory() {
ServiceLoader loader = ServiceLoader.load(MessageCollectionFactory.class);
TreeSet factories = new TreeSet(
new Comparator() {
@Override
public int compare(MessageCollectionFactory o1, MessageCollectionFactory o2) {
if (o1.priority() > o2.priority()) {
return 1;
}
if (o1.priority() < o2.priority()) {
return -1;
}
return 0;
}
});
for (MessageCollectionFactory messageCollectionFactory : loader) {
factories.add(messageCollectionFactory);
}
if (factories.isEmpty()) {
throw new IllegalStateException(""Cannot retrieve a "" + MessageCollectionFactory.class.getName()
+ "". Please add logcapture modules or create a service extension."");
}
return factories.first();
}
}
"
Allow for customizing searchable chunk size,"get('scout.searchableChunkSize', 100);
$builder->macro('searchable', function (EloquentBuilder $builder) use ($chunkSize) {
$builder->chunk($chunkSize, function ($models) use ($builder) {
$models->searchable();
event(new ModelsImported($models));
});
});
$builder->macro('unsearchable', function (EloquentBuilder $builder) use ($chunkSize) {
$builder->chunk($chunkSize, function ($models) use ($builder) {
$models->unsearchable();
});
});
}
}
","macro('searchable', function (EloquentBuilder $builder) {
$builder->chunk(100, function ($models) use ($builder) {
$models->searchable();
event(new ModelsImported($models));
});
});
$builder->macro('unsearchable', function (EloquentBuilder $builder) {
$builder->chunk(100, function ($models) use ($builder) {
$models->unsearchable();
});
});
}
}
"
Update DAX per 2021-06-24 changes,"# Copyright (c) 2012-2017, Mark Peek
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import boolean
class SSESpecification(AWSProperty):
props = {
""SSEEnabled"": (boolean, False),
}
class Cluster(AWSObject):
resource_type = ""AWS::DAX::Cluster""
props = {
""AvailabilityZones"": (str, False),
""ClusterEndpointEncryptionType"": (str, False),
""ClusterName"": (str, False),
""Description"": (str, False),
""IAMRoleARN"": (str, True),
""NodeType"": (str, True),
""NotificationTopicARN"": (str, False),
""ParameterGroupName"": (str, False),
""PreferredMaintenanceWindow"": (str, False),
""ReplicationFactor"": (str, True),
""SSESpecification"": (SSESpecification, False),
""SecurityGroupIds"": ([str], False),
""SubnetGroupName"": (str, True),
""Tags"": (dict, False),
}
class ParameterGroup(AWSObject):
resource_type = ""AWS::DAX::ParameterGroup""
props = {
""Description"": (str, False),
""ParameterGroupName"": (str, False),
""ParameterNameValues"": (dict, False),
}
class SubnetGroup(AWSObject):
resource_type = ""AWS::DAX::SubnetGroup""
props = {
""Description"": (str, False),
""SubnetGroupName"": (str, False),
""SubnetIds"": ([str], False),
}
","# Copyright (c) 2012-2017, Mark Peek
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import boolean
class SSESpecification(AWSProperty):
props = {
""SSEEnabled"": (boolean, False),
}
class Cluster(AWSObject):
resource_type = ""AWS::DAX::Cluster""
props = {
""AvailabilityZones"": (str, False),
""ClusterName"": (str, False),
""Description"": (str, False),
""IAMRoleARN"": (str, True),
""NodeType"": (str, True),
""NotificationTopicARN"": (str, False),
""ParameterGroupName"": (str, False),
""PreferredMaintenanceWindow"": (str, False),
""ReplicationFactor"": (str, True),
""SSESpecification"": (SSESpecification, False),
""SecurityGroupIds"": ([str], False),
""SubnetGroupName"": (str, True),
""Tags"": (dict, False),
}
class ParameterGroup(AWSObject):
resource_type = ""AWS::DAX::ParameterGroup""
props = {
""Description"": (str, False),
""ParameterGroupName"": (str, False),
""ParameterNameValues"": (dict, False),
}
class SubnetGroup(AWSObject):
resource_type = ""AWS::DAX::SubnetGroup""
props = {
""Description"": (str, False),
""SubnetGroupName"": (str, False),
""SubnetIds"": ([str], False),
}
"
"Make sure to clear search filters before and after search
(clearing before is defensive, after is cleanup)"," 'json');
protected function cacheFolder()
{
return Kurogo::getSiteVar('ARCGIS_CACHE','maps');
}
public function search($searchText)
{
$this->parser->clearSearchFilters();
$this->parser->addSearchFilter('text', $searchText);
$items = $this->items();
$this->parser->clearSearchFilters();
return $items;
}
public function searchByProximity($center, $tolerance, $maxItems)
{
$this->parser->clearSearchFilters();
// TODO: these units are completely wrong (but work for harvard b/c
// their units are in feet); we should use MapProjector to get
// a decent range
$dLatDegrees = $tolerance;
$dLonDegrees = $tolerance;
$maxLat = $center['lat'] + $dLatDegrees;
$minLat = $center['lat'] - $dLatDegrees;
$maxLon = $center['lon'] + $dLonDegrees;
$minLon = $center['lon'] - $dLonDegrees;
$this->parser->addSearchFilter('geometry', ""$minLon,$minLat,$maxLon,$maxLat"");
$this->parser->addSearchFilter('geometryType', 'esriGeometryEnvelope');
$this->parser->addSearchFilter('spatialRel', 'esriSpatialRelIntersects');
$this->parser->addSearchFilter('returnGeometry', 'false');
$items = $this->items();
$this->parser->clearSearchFilters();
return $items;
}
}
"," 'json');
protected function cacheFolder()
{
return Kurogo::getSiteVar('ARCGIS_CACHE','maps');
}
public function search($searchText)
{
$this->parser->clearSearchFilters();
$this->parser->addSearchFilter('text', $searchText);
return $this->items();
}
public function searchByProximity($center, $tolerance, $maxItems)
{
// TODO: these units are completely wrong (but work for harvard b/c
// their units are in feet); we should use MapProjector to get
// a decent range
$dLatDegrees = $tolerance;
$dLonDegrees = $tolerance;
$maxLat = $center['lat'] + $dLatDegrees;
$minLat = $center['lat'] - $dLatDegrees;
$maxLon = $center['lon'] + $dLonDegrees;
$minLon = $center['lon'] - $dLonDegrees;
$this->parser->addSearchFilter('geometry', ""$minLon,$minLat,$maxLon,$maxLat"");
$this->parser->addSearchFilter('geometryType', 'esriGeometryEnvelope');
$this->parser->addSearchFilter('spatialRel', 'esriSpatialRelIntersects');
$this->parser->addSearchFilter('returnGeometry', 'false');
$items = $this->items();
$this->parser->clearSearchFilters();
return $items;
}
}
"
"Make MissingError translatable for auto install of postgis extension, plus fix some typos","# Copyright 2011-2012 Nicolas Bessi (Camptocamp SA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
""""""Helper to setup Postgis""""""
import logging
from odoo import _
from odoo.exceptions import MissingError
logger = logging.getLogger('geoengine.sql')
def init_postgis(cr):
"""""" Initialize postgis
Add PostGIS support to the database. PostGIS is a spatial database
extender for PostgreSQL object-relational database. It adds support for
geographic objects allowing location queries to be run in SQL.
""""""
cr.execute(""""""
SELECT
tablename
FROM
pg_tables
WHERE
tablename='spatial_ref_sys';
"""""")
check = cr.fetchone()
if check:
return {}
try:
cr.execute(""""""
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_topology;
"""""")
except Exception:
raise MissingError(
_(
""Error, can not automatically initialize spatial postgis""
"" support. Database user may have to be superuser and""
"" postgres/postgis extensions with their devel header have""
"" to be installed. If you do not want Odoo to connect with a""
"" super user you can manually prepare your database. To do""
"" this, open a client to your database using a super user and""
"" run:\n""
""CREATE EXTENSION postgis;\n""
""CREATE EXTENSION postgis_topology;\n""
)
)
","# Copyright 2011-2012 Nicolas Bessi (Camptocamp SA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
""""""Helper to setup Postgis""""""
import logging
from odoo.exceptions import MissingError
logger = logging.getLogger('geoengine.sql')
def init_postgis(cr):
"""""" Initialize postgis
Add PostGIS support to the database. PostGIS is a spatial database
extender for PostgreSQL object-relational database. It adds support for
geographic objects allowing location queries to be run in SQL.
""""""
cr.execute(""""""
SELECT
tablename
FROM
pg_tables
WHERE
tablename='spatial_ref_sys';
"""""")
check = cr.fetchone()
if check:
return {}
try:
cr.execute(""""""
CREATE EXTENSION postgis;
CREATE EXTENSION postgis_topology;
"""""")
except Exception:
raise MissingError(
""Error, can not automatically initialize spatial postgis support. ""
""Database user may have to be superuser and postgres/postgis ""
""extentions with their devel header have to be installed. ""
""If you do not want Odoo to connect with a super user ""
""you can manually prepare your database. To do this""
""open a client to your database using a super user and run: \n""
""CREATE EXTENSION postgis;\n""
""CREATE EXTENSION postgis_topology;\n""
)
"
Fix cprint with unicode characters,"from __future__ import print_function
import sys
import string
import json
from colors import *
def is_posix_filename(name, extra_chars=""""):
CHARS = string.letters + string.digits + ""._-"" + extra_chars
return all(c in CHARS for c in name)
def cprint(color, msg, file=sys.stdout, end='\n'):
if type(msg) is unicode:
data = msg
elif type(msg) is str:
data = msg.__str__()
print(color + data + RESET, file=file, end=end)
def _assert(condition, msg):
if condition:
return
cprint(LRED, msg)
sys.exit(1)
def to_unicode(obj, encoding='utf-8'):
assert isinstance(obj, basestring), type(obj)
if isinstance(obj, unicode):
return obj
for encoding in ['utf-8', 'latin1']:
try:
obj = unicode(obj, encoding)
return obj
except UnicodeDecodeError:
pass
assert False, ""tst: non-recognized encoding""
def data2json(data):
def date_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif hasattr(obj, 'email'):
return obj.email()
return obj
return json.dumps(
data,
default=date_handler,
indent=2,
separators=(',', ': '),
sort_keys=True,
ensure_ascii=False)
","from __future__ import print_function
import sys
import string
import json
from colors import *
def is_posix_filename(name, extra_chars=""""):
CHARS = string.letters + string.digits + ""._-"" + extra_chars
return all(c in CHARS for c in name)
def cprint(color, msg, file=sys.stdout, end='\n'):
data = msg.__str__() if hasattr(msg, '__str__') else msg
print(color + data + RESET, file=file, end=end)
def _assert(condition, msg):
if condition:
return
cprint(LRED, msg)
sys.exit(1)
def to_unicode(obj, encoding='utf-8'):
assert isinstance(obj, basestring), type(obj)
if isinstance(obj, unicode):
return obj
for encoding in ['utf-8', 'latin1']:
try:
obj = unicode(obj, encoding)
return obj
except UnicodeDecodeError:
pass
assert False, ""tst: non-recognized encoding""
def data2json(data):
def date_handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif hasattr(obj, 'email'):
return obj.email()
return obj
return json.dumps(
data,
default=date_handler,
indent=2,
separators=(',', ': '),
sort_keys=True,
ensure_ascii=False)
"
"Test added for the ticket tracker url.
The automatic test now checks also the ticket tracker url (just tests that
the javascript contains the word %TICKET%).","import contextlib
import mock
import testify as T
from pushmanager.handlers import CheckSitesBookmarkletHandler
from pushmanager.handlers import CreateRequestBookmarkletHandler
from pushmanager.testing.testservlet import AsyncTestCase
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self):
return [
(CreateRequestBookmarkletHandler.url, CreateRequestBookmarkletHandler),
(CheckSitesBookmarkletHandler.url, CheckSitesBookmarkletHandler),
]
@contextlib.contextmanager
def page(self, handler):
with mock.patch.object(handler, ""get_current_user""):
handler.get_current_user.return_value = ""testuser""
response = self.fetch(str(handler.url))
yield response
def test_create_request_bookmarklet(self):
with self.page(CreateRequestBookmarkletHandler) as response:
# We'll get a javascript as the body, just check some
# variable names/strings that we know is there in the
# script.
T.assert_equal(response.error, None)
T.assert_in(""ticketNumberToURL"", response.body)
T.assert_in(""codeReview"", response.body)
T.assert_in(""%TICKET%"", response.body)
def test_check_sites_bookmarklet(self):
with self.page(CheckSitesBookmarkletHandler) as response:
# See comment above in test_create_request_bookmarklet
T.assert_equal(response.error, None)
T.assert_in(""window.open"", response.body)
","import contextlib
import mock
import testify as T
from pushmanager.handlers import CheckSitesBookmarkletHandler
from pushmanager.handlers import CreateRequestBookmarkletHandler
from pushmanager.testing.testservlet import AsyncTestCase
class BookmarkletTest(T.TestCase, AsyncTestCase):
def get_handlers(self):
return [
(CreateRequestBookmarkletHandler.url, CreateRequestBookmarkletHandler),
(CheckSitesBookmarkletHandler.url, CheckSitesBookmarkletHandler),
]
@contextlib.contextmanager
def page(self, handler):
with mock.patch.object(handler, ""get_current_user""):
handler.get_current_user.return_value = ""testuser""
response = self.fetch(str(handler.url))
yield response
def test_create_request_bookmarklet(self):
with self.page(CreateRequestBookmarkletHandler) as response:
# We'll get a javascript as the body, just check some
# variable names/strings that we know is there in the
# script.
T.assert_equal(response.error, None)
T.assert_in(""ticketNumberToURL"", response.body)
T.assert_in(""codeReview"", response.body)
def test_check_sites_bookmarklet(self):
with self.page(CheckSitesBookmarkletHandler) as response:
# See comment above in test_create_request_bookmarklet
T.assert_equal(response.error, None)
T.assert_in(""window.open"", response.body)
"
"Use constant from interface, not from injector
I've notice issue with constant and Mockery.
If we use Mockery to mock class, than we can't access to the constants.
This change uses constants from another class, so we have access
on mocking ConfigAggregatorInjector.","projectDir);
$configProvider = sprintf('%s\ConfigProvider', $moduleName);
if (! $injector->isRegistered($configProvider)) {
$injector->inject(
$configProvider,
InjectorInterface::TYPE_CONFIG_PROVIDER
);
}
try {
$enable = new Enable($this->projectDir, $this->modulesPath, $this->composer);
$enable->setMoveModuleClass(false);
return $enable->process($moduleName);
} catch (RuntimeException $ex) {
throw new Exception\RuntimeException($ex->getMessage(), $ex->getCode(), $ex);
}
}
}
","projectDir);
$configProvider = sprintf('%s\ConfigProvider', $moduleName);
if (! $injector->isRegistered($configProvider)) {
$injector->inject(
$configProvider,
ConfigAggregatorInjector::TYPE_CONFIG_PROVIDER
);
}
try {
$enable = new Enable($this->projectDir, $this->modulesPath, $this->composer);
$enable->setMoveModuleClass(false);
return $enable->process($moduleName);
} catch (RuntimeException $ex) {
throw new Exception\RuntimeException($ex->getMessage(), $ex->getCode(), $ex);
}
}
}
"
Fix nav test utils export,"var fs = require('fs');
module.exports = (function() {
const PATH_COOKIES = '/tmp/cookies.txt';
function setUp() {
casper.options.viewportSize = {width: 1280, height: 768};
casper.options.waitTimeout = 10000;
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11');
casper.on('remote.message', function(msg) {
this.echo(""Error: "" + msg, ""ERROR"");
});
casper.on('page.error', function(msg, trace) {
this.echo(""Error: "" + msg, ""ERROR"");
for(var i=0; i
Email Recipients
{members.map((member, i) =>
-
{`${member.first_name || member.title} ${member.last_name}`}
)}
Subject: {preview[0]}
Freinds of Chichester Harbour
Dear Member,
{preview[1]
.split('\n')
.filter(el => el !== '')
.map((par, i) =>
)
}
","import React from 'react'
export default ({members, preview, props: { submit_custom_email, edit_custom }}) =>
Email Recipients
{members.map((member, i) =>
-
{`${member.first_name || member.title} ${member.last_name}`}
)}
Subject: {preview[0]}
Dear Member,
{preview[1]
.split('\n')
.filter(el => el !== '')
.map((par, i) =>
)
}
"
Use Laravel database configuration by default," [
'driver' => 'dbal',
'dbal' => [
'connection' => env('DB_CONNECTION', 'mysql'),
'table' => 'event_store',
],
],
/*
|--------------------------------------------------------------------------
| Read model storage configuration
|--------------------------------------------------------------------------
| You can choose a driver, possible options are:
|
| elasticsearch, inmemory
|
*/
'read-model' => [
'driver' => 'elasticsearch',
'elasticsearch' => [
'hosts' => ['localhost:9200']
]
],
/*
|--------------------------------------------------------------------------
| Saga configuration
|--------------------------------------------------------------------------
| You can choose a driver, possible options are:
|
| mongodb, inmemory
|
*/
'saga' => [
'driver' => 'inmemory',
'mongodb' => [
'collection' => 'sagas',
],
'sagas' => [],
],
/*
|--------------------------------------------------------------------------
| Generator configuration
|--------------------------------------------------------------------------
|
*/
'generators' => [
'paths' => [
'stubs' => resource_path('stubs/broadway'),
'tests' => base_path('tests'),
],
],
];
"," [
'driver' => 'dbal',
'dbal' => [
'connection' => 'mysql',
'table' => 'event_store',
],
],
/*
|--------------------------------------------------------------------------
| Read model storage configuration
|--------------------------------------------------------------------------
| You can choose a driver, possible options are:
|
| elasticsearch, inmemory
|
*/
'read-model' => [
'driver' => 'elasticsearch',
'elasticsearch' => [
'hosts' => ['localhost:9200']
]
],
/*
|--------------------------------------------------------------------------
| Saga configuration
|--------------------------------------------------------------------------
| You can choose a driver, possible options are:
|
| mongodb, inmemory
|
*/
'saga' => [
'driver' => 'inmemory',
'mongodb' => [
'collection' => 'sagas',
],
'sagas' => [],
],
/*
|--------------------------------------------------------------------------
| Generator configuration
|--------------------------------------------------------------------------
|
*/
'generators' => [
'paths' => [
'stubs' => resource_path('stubs/broadway'),
'tests' => base_path('tests'),
],
],
];
"
Add possibility to locally forward the mail server,"#!/usr/bin/env python
# -*- coding: utf-8 -*-
""""""
Utils for sending emails via SMTP on localhost.
""""""
from email.utils import formatdate
from email.mime.text import MIMEText
import smtplib
import textwrap
from config import MAILSERVER_HOST, MAILSERVER_PORT
def wrap_message(message, chars_in_line=80):
""""""Wraps an unformatted block of text to 80 characters
""""""
return_text = []
for paragraph in message.split('\n'):
lines = textwrap.wrap(paragraph, chars_in_line)
if not lines:
return_text.append('')
else:
return_text.extend(lines)
return '\n'.join(return_text)
def send_mail(sender, receipient, subject, message):
""""""Send a MIME text mail from sender to receipient with subject and message.
The message will be wrapped to 80 characters and encoded to UTF8.
Returns False, if sending from localhost:25 fails.
Else returns True.
""""""
message = wrap_message(message)
mail = MIMEText(message, _charset='utf-8')
mail['From'] = sender
mail['To'] = receipient
mail['Subject'] = subject
mail['Date'] = formatdate(localtime=True)
try:
smtp = smtplib.SMTP()
smtp.connect(host=MAILSERVER_HOST, port=MAILSERVER_PORT)
smtp.sendmail(sender, receipient, mail.as_string(0))
smtp.close()
return True
except IOError:
# smtp.connect failed to connect
return False","#!/usr/bin/env python
# -*- coding: utf-8 -*-
""""""
Utils for sending emails via SMTP on localhost.
""""""
from email.utils import formatdate
from email.mime.text import MIMEText
import smtplib
import textwrap
from config import MAILSERVER_HOST
def wrap_message(message, chars_in_line=80):
""""""Wraps an unformatted block of text to 80 characters
""""""
return_text = []
for paragraph in message.split('\n'):
lines = textwrap.wrap(paragraph, chars_in_line)
if not lines:
return_text.append('')
else:
return_text.extend(lines)
return '\n'.join(return_text)
def send_mail(sender, receipient, subject, message):
""""""Send a MIME text mail from sender to receipient with subject and message.
The message will be wrapped to 80 characters and encoded to UTF8.
Returns False, if sending from localhost:25 fails.
Else returns True.
""""""
message = wrap_message(message)
mail = MIMEText(message, _charset='utf-8')
mail['From'] = sender
mail['To'] = receipient
mail['Subject'] = subject
mail['Date'] = formatdate(localtime=True)
try:
smtp = smtplib.SMTP()
smtp.connect(host=MAILSERVER_HOST, port=25)
smtp.sendmail(sender, receipient, mail.as_string(0))
smtp.close()
return True
except IOError:
# smtp.connect failed to connect
return False"
Allow for empty tags and authors on `ContentSerializer`,"from django import forms
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Content, Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ('password',)
class SimpleAuthorSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name')
class ContentSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='content-detail',
lookup_field='pk'
)
tags = serializers.PrimaryKeyRelatedField(many=True, required=False)
authors = serializers.PrimaryKeyRelatedField(many=True, required=False)
class Meta:
model = Content
exclude = ('polymorphic_ctype',)
class ContentSerializerReadOnly(ContentSerializer):
tags = TagSerializer(many=True, required=False)
authors = SimpleAuthorSerializer(many=True, required=False)
class PolymorphicContentSerializerMixin(object):
def to_native(self, value):
if hasattr(value, 'get_serializer_class'):
ThisSerializer = value.get_serializer_class()
else:
class ThisSerializer(serializers.ModelSerializer):
class Meta:
model = value.__class__
serializer = ThisSerializer(context=self.context)
return serializer.to_native(value)
class PolymorphicContentSerializer(ContentSerializer, PolymorphicContentSerializerMixin):
pass
class PolymorphicContentSerializerReadOnly(ContentSerializerReadOnly, PolymorphicContentSerializerMixin):
pass
","from django import forms
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Content, Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ('password',)
class SimpleAuthorSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name')
class ContentSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='content-detail',
lookup_field='pk'
)
class Meta:
model = Content
exclude = ('polymorphic_ctype',)
class ContentSerializerReadOnly(ContentSerializer):
tags = TagSerializer(many=True, required=False)
authors = SimpleAuthorSerializer(many=True, required=False)
class PolymorphicContentSerializerMixin(object):
def to_native(self, value):
if hasattr(value, 'get_serializer_class'):
ThisSerializer = value.get_serializer_class()
else:
class ThisSerializer(serializers.ModelSerializer):
class Meta:
model = value.__class__
serializer = ThisSerializer(context=self.context)
return serializer.to_native(value)
class PolymorphicContentSerializer(ContentSerializer, PolymorphicContentSerializerMixin):
pass
class PolymorphicContentSerializerReadOnly(ContentSerializerReadOnly, PolymorphicContentSerializerMixin):
pass
"
Send to DQ not admin,"#!/usr/bin/env python3
from reporter.reports import Report, Schedule
from reporter import get_case_link, RECIPIENT_BRICCS_DQ
class BriccsCivcrmBlankStudyId(Report):
def __init__(self):
super().__init__(
introduction=(""The following participants have a blank ""
""study ID in the CiviCRM Study Enrolment""),
recipients=[RECIPIENT_BRICCS_DQ],
schedule=Schedule.daily,
sql='''
SELECT civicrm_case_id, civicrm_contact_id
FROM i2b2_app03_b1_Data.dbo.LOAD_Civicrm
WHERE blank_study_id = 1
AND (
is_recruited = 1
OR is_withdrawn = 1
OR is_duplicate = 1
)
'''
)
def get_report_line(self, row):
return '- {}\r\n\r\n'.format(
get_case_link(
'Click to View',
row[""civicrm_case_id""],
row[""civicrm_contact_id""]))
","#!/usr/bin/env python3
from reporter.reports import Report, Schedule
from reporter import get_case_link, RECIPIENT_BRICCS_ADMIN
class BriccsCivcrmBlankStudyId(Report):
def __init__(self):
super().__init__(
introduction=(""The following participants have a blank ""
""study ID in the CiviCRM Study Enrolment""),
recipients=[RECIPIENT_BRICCS_ADMIN],
schedule=Schedule.daily,
sql='''
SELECT civicrm_case_id, civicrm_contact_id
FROM i2b2_app03_b1_Data.dbo.LOAD_Civicrm
WHERE blank_study_id = 1
AND (
is_recruited = 1
OR is_withdrawn = 1
OR is_duplicate = 1
)
'''
)
def get_report_line(self, row):
return '- {}\r\n\r\n'.format(
get_case_link(
'Click to View',
row[""civicrm_case_id""],
row[""civicrm_contact_id""]))
"
Allow rdflib 6.0.0 to be used now that it should work,"#!/usr/bin/env python
# encoding=utf-8
from __future__ import print_function
import os
import sys
try:
from setuptools import setup
except ImportError:
print(""This package requires 'setuptools' to be installed."")
sys.exit(1)
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
setup(name='skosify',
version='2.2.1', # Use bumpversion to update
description='SKOS converter for RDFS/OWL/SKOS vocabularies.',
long_description=README,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
keywords='rdf skos',
author='Osma Suominen',
author_email='osma.suominen@helsinki.fi',
url='https://github.com/NatLibFi/Skosify',
license='MIT',
install_requires=['rdflib'],
setup_requires=['rdflib>=3.0.0', 'pytest-runner>=2.9'],
tests_require=['pytest<6.0.0', 'pytest-pep8', 'pytest-cov', 'pytest-catchlog'],
packages=['skosify', 'skosify.rdftools'],
entry_points={'console_scripts': ['skosify=skosify.cli:main']}
)
","#!/usr/bin/env python
# encoding=utf-8
from __future__ import print_function
import os
import sys
try:
from setuptools import setup
except ImportError:
print(""This package requires 'setuptools' to be installed."")
sys.exit(1)
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
setup(name='skosify',
version='2.2.1', # Use bumpversion to update
description='SKOS converter for RDFS/OWL/SKOS vocabularies.',
long_description=README,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
],
keywords='rdf skos',
author='Osma Suominen',
author_email='osma.suominen@helsinki.fi',
url='https://github.com/NatLibFi/Skosify',
license='MIT',
install_requires=['rdflib'],
setup_requires=['rdflib>=3.0.0,<6.0.0', 'pytest-runner>=2.9'],
tests_require=['pytest<6.0.0', 'pytest-pep8', 'pytest-cov', 'pytest-catchlog'],
packages=['skosify', 'skosify.rdftools'],
entry_points={'console_scripts': ['skosify=skosify.cli:main']}
)
"
Allow passing in data to a query action,"/**
* Model which handles ""special"" actions against the query
* Ex.: selections, swap axis, mdx
*/
var QueryAction = Backbone.Model.extend({
initialize: function(args, options) {
// Keep track of query
this.query = options.query;
// Set default url
this.url = this.query.url;
},
get: function(action, options) {
this.handle(""fetch"", action, options);
},
post: function(action, options) {
this.handle(""save"", action, options);
},
put: function(action, options) {
this.id = _.uniqueId('queryaction_');
this.handle(""save"", action, options);
delete this.id;
},
del: function(action, options) {
this.id = _.uniqueId('queryaction_');
this.handle(""delete"", action, options);
delete this.id;
},
// Call arbitrary actions against the query
handle: function(method, action, options) {
// Set query action
this.url = this.query.url() + escape(action);
// Clear out old attributes
this.attributes = options.data? options.data : {};
// Initiate action
if (method == ""save"") {
// Handle response from server
this.parse = options.success;
this.save();
} else if (method == ""delete"") {
this.destroy(options);
} else if (method == ""fetch"") {
this.parse = function() {};
this.fetch(options);
}
}
});","/**
* Model which handles ""special"" actions against the query
* Ex.: selections, swap axis, mdx
*/
var QueryAction = Backbone.Model.extend({
initialize: function(args, options) {
// Keep track of query
this.query = options.query;
// Set default url
this.url = this.query.url;
},
get: function(action, options) {
this.handle(""fetch"", action, options);
},
post: function(action, options) {
this.handle(""save"", action, options);
},
put: function(action, options) {
this.id = _.uniqueId('queryaction_');
this.handle(""save"", action, options);
delete this.id;
},
del: function(action, options) {
this.id = _.uniqueId('queryaction_');
this.handle(""delete"", action, options);
delete this.id;
},
// Call arbitrary actions against the query
handle: function(method, action, options) {
// Set query action
this.url = this.query.url() + escape(action);
// Clear out old attributes
this.attributes = {};
// Initiate action
if (method == ""save"") {
// Handle response from server
this.parse = options.success;
this.save();
} else if (method == ""delete"") {
this.destroy(options);
} else if (method == ""fetch"") {
this.parse = function() {};
this.fetch(options);
}
}
});"
"Adjust code to restore generality.
Discussions suggest runtime is not catestrophically slow, so return
generality to the code for sake of my sanity.","# Python Packages
import random
# External Packages
import numpy as np
def sin_theta_sum(variables):
theta = 0
for var in variables:
theta += var
return np.sin(theta)
def gen_random_variables(count, rmin, rmax):
variables = []
for i in range(count):
variables.append(np.random.uniform(rmin, rmax))
# test_range(rmin, rmax, value)
return variables
def run_monte_carlo(samples, function, func_coeff, func_vars):
value = 0
for i in range(samples):
if i % 10000 == 0:
print(i)
value += function(func_vars)
value = value*func_coeff/samples
return value
def sin_monte_element(rmax):
value = gen_random_variables(8, 0, rmax)
result = sin_theta_sum(value)
return result
def main():
rmax = np.pi/8
samples = 10000000
coefficient = 1000000
volume = np.power(rmax, 8)
func_coeff = coefficient*volume
func_vars = rmax
result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars)
print(result)
def test_range(rmin, rmax, value):
if (value <= rmin or value >= rmax):
print(False)
main()
","# Python Packages
import random
# External Packages
import numpy as np
def sin_theta_sum(theta):
return np.sin(theta)
def gen_random_value(count, rmin, rmax):
value = 0
for i in range(count):
value += np.random.uniform(rmin, rmax)
# test_range(rmin, rmax, value)
return value
def run_monte_carlo(samples, function, func_coeff, func_vars):
value = 0
for i in range(samples):
if i % 10000 == 0:
print(i)
value += function(func_vars)
value = value*func_coeff/samples
return value
def sin_monte_element(rmax):
value = gen_random_value(8, 0, rmax)
result = sin_theta_sum(value)
return result
def main():
rmax = np.pi/8
samples = 10000000
coefficient = 1000000
volume = np.power(np.pi/8, 8)
func_coeff = coefficient*volume
func_vars = rmax
result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars)
print(result)
def test_range(rmin, rmax, value):
if (value <= rmin or value >= rmax):
print(False)
main()
"
Load size on right click,"$(document).ready(function() {
// Allow all sortable rows to be sortable
$("".sortable"").sortable();
// Disallow selection
$("".sortable"").disableSelection();
$(document).bind(""contextmenu"", function (e) {
// Don't allow the browsers to handle the right-click
e.preventDefault();
// Get the block
var block = $(e.target);
// Load the properties of the block
// Get classes of the block
var classList = block.attr(""class"").split("" "");
// Prepare Regex (gets size of block)
var classRegex = /col-..-(\d+)/g;
// Search for first class that has the size
$.each(classList, function(index, item) {
var match = classRegex.exec(item);
if (match != null) {
// Set the dropdown menu to that size
$(""#size"").val(match[1]);
// Don't continue checking other classes
return false;
}
});
// Make the right-click-menu appear iff a block was clicked
if ($(e.target).parents("".row"").length > 0) {
$("".custom-menu"").finish().toggle(100).css({
left: e.pageX + ""px"",
top: e.pageY + ""px""
});
}
});
// Function to hide the menu
$(document).bind(""mousedown"", function (e) {
// If the menu itself was clicked
if (!$(e.target).parents("".custom-menu"").length > 0) {
// Hide it
$("".custom-menu"").hide();
}
});
// If the apply button is clicked
$("".custom-menu input.hide-menu"").click(function(){
if($(this).attr(""data-action"") == ""apply"") {
alert($(""#size"").val());
}
// Hide it AFTER the action was triggered
$("".custom-menu"").hide(100);
});
});
","$(document).ready(function() {
// Allow all sortable rows to be sortable
$("".sortable"").sortable();
// Disallow selection
$("".sortable"").disableSelection();
$(document).bind(""contextmenu"", function (e) {
// Don't allow the browsers to handle the right-click
e.preventDefault();
// Make the right-click-menu appear iff a block was clicked
if ($(e.target).parents("".row"").length > 0) {
$("".custom-menu"").finish().toggle(100).css({
left: e.pageX + ""px"",
top: e.pageY + ""px""
});
}
});
// Function to hide the menu
$(document).bind(""mousedown"", function (e) {
// If the menu itself was clicked
if (!$(e.target).parents("".custom-menu"").length > 0) {
// Hide it
$("".custom-menu"").hide();
}
});
// If the apply button is clicked
$("".custom-menu input.hide-menu"").click(function(){
if($(this).attr(""data-action"") == ""apply"") {
alert($(""#size"").val());
}
// Hide it AFTER the action was triggered
$("".custom-menu"").hide(100);
});
});
"
Set content type for long_description,"#!/usr/bin/env python
from setuptools import setup
try:
with open('README.rst', 'r', encoding='utf-8') as f:
readme = f.read()
except IOError:
readme = ''
setup(
name='cr8',
author='Mathias Fußenegger',
author_email='pip@zignar.net',
url='https://github.com/mfussenegger/cr8',
description='A collection of command line tools for crate devs',
long_description=readme,
long_description_content_type='text/x-rst',
entry_points={
'console_scripts': [
'cr8 = cr8.__main__:main',
]
},
packages=['cr8'],
install_requires=[
'crate>=0.16',
'argh',
'tqdm',
'Faker==0.9.1',
'aiohttp>=3.3,<4',
'toml'
],
extras_require={
'uvloop': ['uvloop'],
'asyncpg': ['asyncpg']
},
python_requires='>=3.6',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
use_scm_version=True,
setup_requires=['setuptools_scm']
)
","#!/usr/bin/env python
from setuptools import setup
try:
with open('README.rst', 'r', encoding='utf-8') as f:
readme = f.read()
except IOError:
readme = ''
setup(
name='cr8',
author='Mathias Fußenegger',
author_email='pip@zignar.net',
url='https://github.com/mfussenegger/cr8',
description='A collection of command line tools for crate devs',
long_description=readme,
entry_points={
'console_scripts': [
'cr8 = cr8.__main__:main',
]
},
packages=['cr8'],
install_requires=[
'crate>=0.16',
'argh',
'tqdm',
'Faker==0.9.1',
'aiohttp>=3.3,<4',
'toml'
],
extras_require={
'uvloop': ['uvloop'],
'asyncpg': ['asyncpg']
},
python_requires='>=3.6',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
use_scm_version=True,
setup_requires=['setuptools_scm']
)
"
Return chained iterators instead of only first of multiple iterators,"from lxml import etree
import itertools
from app import formatting
def get_namespace_from_top(fn, key='xmlns'):
ac, el = next(etree.iterparse(fn))
return {'xmlns': el.nsmap[key]}
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
""""""
Calls xmltag generator for multiple files.
""""""
return itertools.chain.from_iterable([generate_xmltags(
fn, tag, ignore_tags, ns) for fn in input_files])
def generate_tags_multiple_files_strings(input_files, ns, tag, ignore_tags):
""""""
Creates stringified xml output of elements with certain tag.
""""""
for el in generate_tags_multiple_files(input_files, tag, ignore_tags, ns):
yield formatting.string_and_clear(el, ns)
def generate_xmltags(fn, tag, ignore_tags, ns=None):
""""""
Base generator for percolator xml psm, peptide, protein output,
as well as for mzML, mzIdentML.
ignore_tags are the ones that are not cleared when met by parser.
""""""
if ns is None:
xmlns = ''
else:
xmlns = '{%s}' % ns['xmlns']
for ac, el in etree.iterparse(fn):
if el.tag == '{0}{1}'.format(xmlns, tag):
yield el
elif el.tag in ['{0}{1}'.format(xmlns, x) for x in
ignore_tags]:
formatting.clear_el(el)
","from lxml import etree
from app import formatting
def get_namespace_from_top(fn, key='xmlns'):
ac, el = next(etree.iterparse(fn))
return {'xmlns': el.nsmap[key]}
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
""""""
Calls xmltag generator for multiple files.
""""""
# Deprecate?
for fn in input_files:
return generate_xmltags(fn, tag, ignore_tags, ns)
def generate_tags_multiple_files_strings(input_files, ns, tag, ignore_tags):
""""""
Creates stringified xml output of elements with certain tag.
""""""
for el in generate_tags_multiple_files(input_files, tag, ignore_tags, ns):
yield formatting.string_and_clear(el, ns)
def generate_xmltags(fn, tag, ignore_tags, ns=None):
""""""
Base generator for percolator xml psm, peptide, protein output,
as well as for mzML, mzIdentML.
ignore_tags are the ones that are not cleared when met by parser.
""""""
if ns is None:
xmlns = ''
else:
xmlns = '{%s}' % ns['xmlns']
for ac, el in etree.iterparse(fn):
if el.tag == '{0}{1}'.format(xmlns, tag):
yield el
elif el.tag in ['{0}{1}'.format(xmlns, x) for x in
ignore_tags]:
formatting.clear_el(el)
"
Add daystate_dict function to serialize daystates to dictionaries,"# Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
def daystate_dict(daystate):
return {
'id': daystate.id,
'org_id': daystate.org_id,
'identifier': daystate.identifer,
'greeting': daystate.greeting
}
","# Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from functools import wraps
from flask_jwt_extended import utils
from flask_jwt_extended.utils import ctx_stack
from flask_jwt_extended.exceptions import NoAuthorizationError
from datetime import timedelta
def jwt_optional(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# Decode token in header
try:
jwt_data = utils._decode_jwt_from_request(type='access')
# Verify this is an access token
if jwt_data['type'] != 'access':
raise WrongTokenError('Only access tokens can access this endpoint')
# Check if this is a revoked token
if utils.get_blacklist_enabled():
utils.check_if_token_revoked(jwt_data)
# Add the data to the context
ctx_stack.top.jwt_identity = jwt_data['identity']
ctx_stack.top.jwt_user_claims = jwt_data['user_claims']
except NoAuthorizationError:
# Ignore a missing header
pass
finally:
return fn(*args, **kwargs)
return wrapper
def range_inclusive_dates(start, end):
date_range = end - start
for day_i in range(date_range.days + 1):
yield start + timedelta(days=day_i)
"
Add missing test Mako test dependency.,"import os
import sys
import re
from setuptools import setup, find_packages
v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py'))
VERSION = re.compile(r"".*__version__ = '(.*?)'"", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(name='dogpile.cache',
version=VERSION,
description=""A caching front-end based on the Dogpile lock."",
long_description=open(readme).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
keywords='caching',
author='Mike Bayer',
author_email='mike_mp@zzzcomputing.com',
url='http://bitbucket.org/zzzeek/dogpile.cache',
license='BSD',
packages=find_packages('.', exclude=['ez_setup', 'tests*']),
namespace_packages=['dogpile'],
entry_points=""""""
[mako.cache]
dogpile.cache = dogpile.cache.plugins.mako_cache:MakoPlugin
"""""",
zip_safe=False,
install_requires=['dogpile.core>=0.4.1'],
test_suite='nose.collector',
tests_require=['nose', 'mock', 'Mako'],
)
","import os
import sys
import re
from setuptools import setup, find_packages
v = open(os.path.join(os.path.dirname(__file__), 'dogpile', 'cache', '__init__.py'))
VERSION = re.compile(r"".*__version__ = '(.*?)'"", re.S).match(v.read()).group(1)
v.close()
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
setup(name='dogpile.cache',
version=VERSION,
description=""A caching front-end based on the Dogpile lock."",
long_description=open(readme).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
],
keywords='caching',
author='Mike Bayer',
author_email='mike_mp@zzzcomputing.com',
url='http://bitbucket.org/zzzeek/dogpile.cache',
license='BSD',
packages=find_packages('.', exclude=['ez_setup', 'tests*']),
namespace_packages=['dogpile'],
entry_points=""""""
[mako.cache]
dogpile.cache = dogpile.cache.plugins.mako_cache:MakoPlugin
"""""",
zip_safe=False,
install_requires=['dogpile.core>=0.4.1'],
test_suite='nose.collector',
tests_require=['nose', 'mock'],
)
"
fix(bulk-mailer): Remove the locale prefix on filenames w/ --write,"/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var fs = require('fs')
var path = require('path')
module.exports = function (config) {
var messageId = 0;
if (config.outputDir) {
ensureOutputDirExists(config.outputDir)
}
return {
sendMail: function (emailConfig, callback) {
if (config.outputDir) {
var language = emailConfig.headers['Content-Language']
var outputPath = path.join(config.outputDir, emailConfig.to)
var textPath = outputPath + '.txt'
fs.writeFileSync(textPath, emailConfig.text)
var htmlPath = outputPath + '.html'
fs.writeFileSync(htmlPath, emailConfig.html)
}
if (Math.random() > config.failureRate) {
messageId++
callback(null, {
message: 'good',
messageId: messageId
})
} else {
callback(new Error('uh oh'))
}
},
close: function () {}
};
};
function ensureOutputDirExists(outputDir) {
var dirStats
try {
dirStats = fs.statSync(outputDir)
} catch (e) {
fs.mkdirSync(outputDir);
return;
}
if (! dirStats.isDirectory()) {
console.error(outputDir + ' is not a directory');
process.exit(1)
}
}
","/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var fs = require('fs')
var path = require('path')
module.exports = function (config) {
var messageId = 0;
if (config.outputDir) {
ensureOutputDirExists(config.outputDir)
}
return {
sendMail: function (emailConfig, callback) {
if (config.outputDir) {
var language = emailConfig.headers['Content-Language']
var outputPath = path.join(config.outputDir, language + '.' + emailConfig.to)
var textPath = outputPath + '.txt'
fs.writeFileSync(textPath, emailConfig.text)
var htmlPath = outputPath + '.html'
fs.writeFileSync(htmlPath, emailConfig.html)
}
if (Math.random() > config.failureRate) {
messageId++
callback(null, {
message: 'good',
messageId: messageId
})
} else {
callback(new Error('uh oh'))
}
},
close: function () {}
};
};
function ensureOutputDirExists(outputDir) {
var dirStats
try {
dirStats = fs.statSync(outputDir)
} catch (e) {
fs.mkdirSync(outputDir);
return;
}
if (! dirStats.isDirectory()) {
console.error(outputDir + ' is not a directory');
process.exit(1)
}
}
"
Improve adding ‘botamp_entity_id’ attribute script,"eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'botamp_entity_id',
[
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Botamp Entity ID',
'input' => '',
'class' => '',
'source' => '',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => false,
'required' => false,
'user_defined' => false,
'default' => 0,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => false,
'unique' => true,
'apply_to' => ''
]
);
}
}
","eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'botamp_entity_id',
[
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Botamp Entity ID',
'input' => '',
'class' => '',
'source' => '',
'global' => \Magento\Catalog\Model\Resource\Eav\Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => false,
'default' => 0,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => true,
'apply_to' => ''
]
);
}
}
"
Mark index migration as non atomic,"# Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
atomic = False
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql=""""""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
"""""",
reverse_sql=""""""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
"""""",
),
migrations.RunSQL(
sql=""""""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
"""""",
reverse_sql=""""""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
""""""
),
]
","# Generated by Django 2.1.7 on 2019-05-12 16:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publishers', '0007_publisher_romeo_parent_id'),
]
operations = [
migrations.AlterField(
model_name='journal',
name='title',
field=models.CharField(max_length=256),
),
migrations.AlterField(
model_name='publisher',
name='name',
field=models.CharField(max_length=256),
),
migrations.RunSQL(
sql=""""""
CREATE INDEX CONCURRENTLY papers_journal_title_upper ON public.papers_journal USING btree (UPPER(title));
"""""",
reverse_sql=""""""
DROP INDEX CONCURRENTLY papers_journal_title_upper;
""""""
),
migrations.RunSQL(
sql=""""""
CREATE INDEX CONCURRENTLY papers_publisher_name_upper ON public.papers_publisher USING btree (UPPER(name));
"""""",
reverse_sql=""""""
DROP INDEX CONCURRENTLY papers_publisher_name_upper;
""""""
),
]
"
Add description of Parameters section in docstring,"import csv
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
class AnomalyScore(object):
""""""A class to calculate anomaly score in a cluster.
""""""
def __init__(self, graph, clusters, filename):
""""""The constructor of class AnomalyScore.
Parameters
----------
graph : graph
A graph to be analyzed for its anomaly.
clusters : dict[list]
Dictionary of list containing node identifier for each clusters.
filename : str
Filename for anomaly detection result.
""""""
self.graph = graph
self.clusters = clusters
self.filename = filename
self.property = {}
self.abstraction = {}
def write_property(self):
""""""Write cluster property to a file.
""""""
# get cluster abstraction and its properties
self.abstraction = ClusterAbstraction.dp_lcs(self.graph, self.clusters)
self.property = ClusterUtility.get_cluster_property(self.graph, self.clusters)
# write to csv
f = open(self.filename + '_anomaly.csv', 'wt')
writer = csv.writer(f)
# set header
header = ('cluster_id', 'cluster_abstraction') + tuple(self.property[0].keys())
writer.writerow(header)
# write data
for cluster_id, abstract in self.abstraction.iteritems():
row = (cluster_id, abstract) + tuple(self.property[cluster_id].values())
writer.writerow(row)
","import csv
from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction
from pygraphc.clustering.ClusterUtility import ClusterUtility
class AnomalyScore(object):
""""""A class to calculate anomaly score in a cluster.
""""""
def __init__(self, graph, clusters, filename):
""""""The constructor of class AnomalyScore.
Parameters
----------
graph : graph
clusters : dict[list]
filename : str
""""""
self.graph = graph
self.clusters = clusters
self.filename = filename
self.property = {}
self.abstraction = {}
def write_property(self):
""""""Write cluster property to a file.
""""""
# get cluster abstraction and its properties
self.abstraction = ClusterAbstraction.dp_lcs(self.graph, self.clusters)
self.property = ClusterUtility.get_cluster_property(self.graph, self.clusters)
# write to csv
f = open(self.filename + '_anomaly.csv', 'wt')
writer = csv.writer(f)
# set header
header = ('cluster_id', 'cluster_abstraction') + tuple(self.property[0].keys())
writer.writerow(header)
# write data
for cluster_id, abstract in self.abstraction.iteritems():
row = (cluster_id, abstract) + tuple(self.property[cluster_id].values())
writer.writerow(row)
"
Remove (Participant) relationship displayed after the last non PI researcher CC2608,"@if (isset($related['researchers']) && sizeof($related['researchers']['docs']) > 0)
Researchers:
@foreach($researchers_array as $relation=>$researchers)
@foreach($researchers as $key=>$col)
{{$col['to_title']}}
@if($relation!=""Participant"")
({{ $relation }})
@endif
@if($displayNum<$related['researchers']['count'])
,
@endif
@endforeach
@endforeach
@if($related['researchers']['count'] > 5)
View all {{ $related['researchers']['count'] }} related researchers
@endif
@endif","@if (isset($related['researchers']) && sizeof($related['researchers']['docs']) > 0)
Researchers:
@foreach($researchers_array as $relation=>$researchers)
@foreach($researchers as $key=>$col)
{{$col['to_title']}}
@if($key!=sizeof($researchers)-1)
,
@endif
@endforeach
({{ $relation }})
@endforeach
@if($related['researchers']['count'] > 5)
View all {{ $related['researchers']['count'] }} related researchers
@endif
@endif"
Stop looking up inherited box when box doesn't exist anymore,"getData()->chained->componentClass);
$ret['child'] = $this->_getContentChild();
return $ret;
}
private function _getContentChild()
{
$masterChild = $this->getData()->chained->getComponent()->getContentChild();
$c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
$page = $this->getData();
while($c && !$c->hasContent()) {
while ($page && !$page->inherits) {
$page = $page->parent;
if ($page instanceof Kwf_Component_Data_Root) break;
}
if (!isset($page->chained)) {
$c = null;
break;
}
$masterBox = $page->chained->getChildComponent('-'.$this->getData()->id);
if (!$masterBox) {
$c = null;
break;
}
$masterChild = $masterBox->getChildComponent(array('generator' => 'child'));
$c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
if ($page instanceof Kwf_Component_Data_Root) break;
$page = $page->parent;
}
return $c;
}
}
","getData()->chained->componentClass);
$ret['child'] = $this->_getContentChild();
return $ret;
}
private function _getContentChild()
{
$masterChild = $this->getData()->chained->getComponent()->getContentChild();
$c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
$page = $this->getData();
while($c && !$c->hasContent()) {
while ($page && !$page->inherits) {
$page = $page->parent;
if ($page instanceof Kwf_Component_Data_Root) break;
}
if (!isset($page->chained)) {
$c = null;
break;
}
$masterChild = $page->chained->getChildComponent('-'.$this->getData()->id)
->getChildComponent(array('generator' => 'child'));
$c = Kwc_Chained_Cc_Component::getChainedByMaster($masterChild, $this->getData());
if ($page instanceof Kwf_Component_Data_Root) break;
$page = $page->parent;
}
return $c;
}
}
"
Fix space bug for reflect and refract brdf,"(function (ns) {
var Shade = require(""../../interfaces.js""),
SpaceVectorType = Shade.SpaceVectorType;
ns.emissive = {
inputSpaces: [
SpaceVectorType.OBJECT
]
}
ns.diffuse = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.phong = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.cookTorrance = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT,
SpaceVectorType.OBJECT
]
}
ns.ward = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT,
SpaceVectorType.OBJECT
]
}
ns.scatter = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.reflect = {
inputSpaces: [
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.refract = {
inputSpaces: [
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT,
SpaceVectorType.OBJECT
]
}
}(exports));
","(function (ns) {
var Shade = require(""../../interfaces.js""),
SpaceVectorType = Shade.SpaceVectorType;
ns.emissive = {
inputSpaces: [
SpaceVectorType.OBJECT
]
}
ns.diffuse = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.phong = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.cookTorrance = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT,
SpaceVectorType.OBJECT
]
}
ns.ward = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT,
SpaceVectorType.OBJECT
]
}
ns.scatter = {
inputSpaces: [
SpaceVectorType.OBJECT,
SpaceVectorType.VIEW_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.reflect = {
inputSpaces: [
SpaceVectorType.WORLD_NORMAL,
SpaceVectorType.OBJECT
]
}
ns.refract = {
inputSpaces: [
SpaceVectorType.WORLD_NORMAL,
SpaceVectorType.OBJECT,
SpaceVectorType.OBJECT
]
}
}(exports));
"
Remove secret key from the gondor settings file,"import os
import urlparse
from .settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
if ""GONDOR_DATABASE_URL"" in os.environ:
urlparse.uses_netloc.append(""postgres"")
url = urlparse.urlparse(os.environ[""GONDOR_DATABASE_URL""])
DATABASES = {
""default"": {
""ENGINE"": {
""postgres"": ""django.db.backends.postgresql_psycopg2""
}[url.scheme],
""NAME"": url.path[1:],
""USER"": url.username,
""PASSWORD"": url.password,
""HOST"": url.hostname,
""PORT"": url.port
}
}
MEDIA_ROOT = os.path.join(os.environ[""GONDOR_DATA_DIR""], ""site_media"", ""media"")
STATIC_ROOT = os.path.join(os.environ[""GONDOR_DATA_DIR""], ""site_media"", ""static"")
MEDIA_URL = ""/site_media/media/"" # make sure this maps inside of site_media_url
STATIC_URL = ""/site_media/static/"" # make sure this maps inside of site_media_url
ADMIN_MEDIA_PREFIX = STATIC_URL + ""admin/""
FILE_UPLOAD_PERMISSIONS = 0640
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')","import os
import urlparse
from .settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
if ""GONDOR_DATABASE_URL"" in os.environ:
urlparse.uses_netloc.append(""postgres"")
url = urlparse.urlparse(os.environ[""GONDOR_DATABASE_URL""])
DATABASES = {
""default"": {
""ENGINE"": {
""postgres"": ""django.db.backends.postgresql_psycopg2""
}[url.scheme],
""NAME"": url.path[1:],
""USER"": url.username,
""PASSWORD"": url.password,
""HOST"": url.hostname,
""PORT"": url.port
}
}
MEDIA_ROOT = os.path.join(os.environ[""GONDOR_DATA_DIR""], ""site_media"", ""media"")
STATIC_ROOT = os.path.join(os.environ[""GONDOR_DATA_DIR""], ""site_media"", ""static"")
MEDIA_URL = ""/site_media/media/"" # make sure this maps inside of site_media_url
STATIC_URL = ""/site_media/static/"" # make sure this maps inside of site_media_url
ADMIN_MEDIA_PREFIX = STATIC_URL + ""admin/""
FILE_UPLOAD_PERMISSIONS = 0640
SECRET_KEY = '8f89aej9fa89898__fd9er38948934fjsfoijdaf.'"
Exit the loop early when experimenting.,"#!/usr/bin/python3
import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
if index > 1:
break
","#!/usr/bin/python3
import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
"
"Change Rfree and wRte in SmallOpenEconomy test
Interest factor was set to 20%; changing it to a more reasonable 1.03 fixed the weird interaction with the new nan_bool functionality.","import copy
from HARK import distributeParams
from HARK.ConsumptionSaving.ConsAggShockModel import AggShockConsumerType, SmallOpenEconomy, init_cobb_douglas
from HARK.distribution import Uniform
import numpy as np
import unittest
class testSmallOpenEconomy(unittest.TestCase):
def test_small_open(self):
agent = AggShockConsumerType()
agent.AgentCount = 100 # Very low number of agents for the sake of speed
agent.cycles = 0
# Make agents heterogeneous in their discount factor
agents = distributeParams(agent,
'DiscFac',
3,
Uniform(bot=.90, top=.94) # Impatient agents
)
# Make an economy with those agents living in it
small_economy = SmallOpenEconomy(
agents=agents,
Rfree = 1.03,
wRte = 1.0,
KtoLnow = 1.0,
**copy.copy(init_cobb_douglas)
)
small_economy.act_T = 400 # Short simulation history
small_economy.max_loops = 3 # Give up quickly for the sake of time
small_economy.makeAggShkHist() # Simulate a history of aggregate shocks
small_economy.verbose = False # Turn off printed messages
# Give data about the economy to all the agents in it
for this_type in small_economy.agents:
this_type.getEconomyData(small_economy)
small_economy.solve()
","import copy
from HARK import distributeParams
from HARK.ConsumptionSaving.ConsAggShockModel import AggShockConsumerType, SmallOpenEconomy, init_cobb_douglas
from HARK.distribution import Uniform
import numpy as np
import unittest
class testSmallOpenEconomy(unittest.TestCase):
def test_small_open(self):
agent = AggShockConsumerType()
agent.AgentCount = 100 # Very low number of agents for the sake of speed
agent.cycles = 0
# Make agents heterogeneous in their discount factor
agents = distributeParams(agent,
'DiscFac',
3,
Uniform(bot=.90, top=.94) # Impatient agents
)
# Make an economy with those agents living in it
small_economy = SmallOpenEconomy(
agents=agents,
Rfree = 0.2,
wRte = 0.2,
KtoLnow = 1,
**copy.copy(init_cobb_douglas)
)
small_economy.act_T = 400 # Short simulation history
small_economy.max_loops = 3 # Give up quickly for the sake of time
small_economy.makeAggShkHist() # Simulate a history of aggregate shocks
small_economy.verbose = False # Turn off printed messages
# Give data about the economy to all the agents in it
for this_type in small_economy.agents:
this_type.getEconomyData(small_economy)
small_economy.solve()
"
Fix checkbox agree in install welcome to be checked,"
Welcome
Before you can use the website, you need to configure the website.
Mostly, it takes less than 5 minutes to complete.
First, read the agreement bellow and accept the agreement if you want to use
this website.
THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
","
Welcome
Before you can use the website, you need to configure the website.
Mostly, it takes less than 5 minutes to complete.
First, read the agreement bellow and accept the agreement if you want to use
this website.
THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"
Fix input appearance in the 'All' view,"import React from 'react';
import { Redirect } from 'react-router-dom';
import TodoItem from './TodoItem';
import TodoTextInput from './TodoTextInput';
import './TaskList.css';
export default function (props) {
if (!props.doesExist) {
return ;
}
return (
{props.title}
{props.cardId &&
props.onTodoItemCreate(name, props.cardId)}
placeholder=""What needs to be done?""
/>}
{Object.keys(props.tasks).map(key => (
props.onTodoItemToggleCheck(key)}
onRemove={() => props.onTodoItemRemove(key)}
/>
))}
);
}
","import React from 'react';
import { Redirect } from 'react-router-dom';
import TodoItem from './TodoItem';
import TodoTextInput from './TodoTextInput';
import './TaskList.css';
export default function (props) {
if (!props.doesExist) {
return ;
}
return (
{props.title}
props.onTodoItemCreate(name, props.cardId)}
placeholder=""What needs to be done?""
/>
{Object.keys(props.tasks).map(key => (
props.onTodoItemToggleCheck(key)}
onRemove={() => props.onTodoItemRemove(key)}
/>
))}
);
}
"
"Remove id,subscription key for LUIS","var service=require('./services/service.js');
var Client = require('node-rest-client').Client;
module.exports= {
getResponse :function(message,callback){
processMessage(message,function(processed){
if(processed){
if(processed.intent!='none'){
service[processed.intent](processed.entities,function(message){
callback(message);
});
}
}
else { callback(""Sorry.I don't know."")}
});
//if(processed.
}
}
processMessage= function(message,callback){
var client = new Client();
var args={
parameters : {id: ""Application.ID"",'subscription-key': ""Application.KEY"",q:message}
}
var req=client.get(""https://api.projectoxford.ai/luis/v1/application"",args,
function(data,response){
callback({intent:data.intents[0].intent,entities:data.entities});
});
req.on('error', function (err) {
console.log('request error', err);
callback({intent:'error'});
});
}
//console.log(processMessage(""send me ppmc url""));
","var service=require('./services/service.js');
var Client = require('node-rest-client').Client;
module.exports= {
getResponse :function(message,callback){
processMessage(message,function(processed){
if(processed){
if(processed.intent!='none'){
service[processed.intent](processed.entities,function(message){
callback(message);
});
}
}
else { callback(""Sorry.I don't know."")}
});
//if(processed.
}
}
processMessage= function(message,callback){
var client = new Client();
var args={
parameters : {id: ""104ea5b9-50ad-4b90-8c54-6bd8c27a391f"",'subscription-key': ""cd3ab42d747b45cb9ecf0c1796ed32ef"",q:message}
}
var req=client.get(""https://api.projectoxford.ai/luis/v1/application"",args,
function(data,response){
callback({intent:data.intents[0].intent,entities:data.entities});
});
req.on('error', function (err) {
console.log('request error', err);
callback({intent:'error'});
});
}
//console.log(processMessage(""send me ppmc url""));"
FIX price sec. related field as readonly,"# -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
class account_invoice_line(models.Model):
_inherit = 'account.invoice.line'
# we add this fields instead of making original readonly because we need
# on change to change values, we make readonly in view because sometimes
# we want them to be writeable
invoice_line_tax_id_readonly = fields.Many2many(
related='invoice_line_tax_id',
)
price_unit_readonly = fields.Float(
related='price_unit',
)
product_can_modify_prices = fields.Boolean(
related='product_id.can_modify_prices',
readonly=True,
string='Product Can modify prices')
@api.one
@api.constrains(
'discount', 'product_can_modify_prices')
def check_discount(self):
if (
self.user_has_groups(
'price_security.group_restrict_prices') and
not self.product_can_modify_prices and self.invoice_id
):
self.env.user.check_discount(
self.discount,
self.invoice_id.partner_id.property_product_pricelist.id)
","# -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
class account_invoice_line(models.Model):
_inherit = 'account.invoice.line'
# we add this fields instead of making original readonly because we need
# on change to change values, we make readonly in view because sometimes
# we want them to be writeable
invoice_line_tax_id_readonly = fields.Many2many(
related='invoice_line_tax_id',
)
price_unit_readonly = fields.Float(
related='price_unit',
)
product_can_modify_prices = fields.Boolean(
related='product_id.can_modify_prices',
string='Product Can modify prices')
@api.one
@api.constrains(
'discount', 'product_can_modify_prices')
def check_discount(self):
if (
self.user_has_groups(
'price_security.group_restrict_prices') and
not self.product_can_modify_prices and self.invoice_id
):
self.env.user.check_discount(
self.discount,
self.invoice_id.partner_id.property_product_pricelist.id)
"
Print args when generating stats,"import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description=""Generates stats for a group"")
parser.add_argument(""-g"", ""--group"", dest=""group_name"", required=True,
help=""Group to generate stats for."")
parser.add_argument(""-s"", ""--stat"", dest=""stats"", default=[],
action=""append"",
help=(""Name of stat to generate. This may be specified""
"" more than once. Choices: %s ""
% "", "".join(all_statistics.keys())))
parser.add_argument(""--all-stats"", action=""store_true"", default=False,
help=""Generate all possible stats."")
parser.add_argument(""--ignore-user"", dest=""ignore_users"", default=[],
action=""append"",
help=""User to ignore. May be specified more than once."")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
print(""args: %s"" % str(args))
if not stats:
parser.print_help()
raise RuntimeError(""Must specify a valid --stat or use --all-stats"")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
","import argparse
import webbrowser
from .groupserializer import GroupSerializer
from .statistic import all_statistics
from .statistics import *
def gstat_stats():
parser = argparse.ArgumentParser(description=""Generates stats for a group"")
parser.add_argument(""-g"", ""--group"", dest=""group_name"", required=True,
help=""Group to generate stats for."")
parser.add_argument(""-s"", ""--stat"", dest=""stats"", default=[],
action=""append"",
help=(""Name of stat to generate. This may be specified""
"" more than once. Choices: %s ""
% "", "".join(all_statistics.keys())))
parser.add_argument(""--all-stats"", action=""store_true"", default=False,
help=""Generate all possible stats."")
parser.add_argument(""--ignore-user"", dest=""ignore_users"", default=[],
action=""append"",
help=""User to ignore. May be specified more than once."")
args = parser.parse_args()
stats = [stat_class() for name, stat_class in all_statistics.items()
if args.all_stats or name in args.stats]
if not stats:
parser.print_help()
raise RuntimeError(""Must specify a valid --stat or use --all-stats"")
(group, messages) = GroupSerializer.load(args.group_name)
for stat in stats:
stat.calculate(group, messages, ignore_users=args.ignore_users)
for stat in stats:
output_html_filename = stat.show()
try:
# webbrowser.open_new_tab(output_html_filename)
pass
except:
pass
"
Use sentinel value for ctx,"# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
""""""Template based messages.""""""
from __future__ import absolute_import, print_function
from flask import render_template
from flask_mail import Message
class TemplatedMessage(Message):
""""""Siplify creation of templated messages.""""""
def __init__(self, template_body=None, template_html=None, ctx=None,
**kwargs):
r""""""Build message body and HTML based on provided templates.
Provided templates can use keyword arguments ``body`` and ``html``
respectively.
:param template_body: Path to the text template.
:param template_html: Path to the html template.
:param ctx: A mapping containing additional information passed to the
template.
:param \*\*kwargs: Keyword arguments as defined in
:class:`flask_mail.Message`.
""""""
ctx = ctx if ctx else {}
if template_body:
kwargs['body'] = render_template(
template_body, body=kwargs.get('body'), **ctx
)
if template_html:
kwargs['html'] = render_template(
template_html, html=kwargs.get('html'), **ctx
)
super(TemplatedMessage, self).__init__(**kwargs)
","# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
""""""Template based messages.""""""
from __future__ import absolute_import, print_function
from flask import render_template
from flask_mail import Message
class TemplatedMessage(Message):
""""""Siplify creation of templated messages.""""""
def __init__(self, template_body=None, template_html=None, ctx={},
**kwargs):
r""""""Build message body and HTML based on provided templates.
Provided templates can use keyword arguments ``body`` and ``html``
respectively.
:param template_body: Path to the text template.
:param template_html: Path to the html template.
:param ctx: A mapping containing additional information passed to the
template.
:param \*\*kwargs: Keyword arguments as defined in
:class:`flask_mail.Message`.
""""""
if template_body:
kwargs['body'] = render_template(
template_body, body=kwargs.get('body'), **ctx
)
if template_html:
kwargs['html'] = render_template(
template_html, html=kwargs.get('html'), **ctx
)
super(TemplatedMessage, self).__init__(**kwargs)
"
"Fix anchor of the ""Add it to the directory"" link","import React from 'react';
import Link from '../components/Link';
import { StyleSheet, css } from 'glamor/aphrodite';
export default () => {
return (
);
};
let styles = StyleSheet.create({
footer: {
borderTop: '1px solid #ECECEC',
width: '100%',
},
container: {
width: '100%',
maxWidth: '1319px',
padding: '24px 24px 24px 24px',
margin: '0 auto 0 auto',
},
});
","import React from 'react';
import Link from '../components/Link';
import { StyleSheet, css } from 'glamor/aphrodite';
export default () => {
return (
);
};
let styles = StyleSheet.create({
footer: {
borderTop: '1px solid #ECECEC',
width: '100%',
},
container: {
width: '100%',
maxWidth: '1319px',
padding: '24px 24px 24px 24px',
margin: '0 auto 0 auto',
},
});
"
Change few occurences of a public setUp() method to protected,"controllerNameParser = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')
->disableOriginalConstructor()
->getMock();
}
/**
* @group legacy
*/
public function testLegacyConstructorApi()
{
new DelegatingLoader($this->controllerNameParser, new NullLogger(), new LoaderResolver());
$this->assertTrue(true, '__construct() accepts a LoggerInterface instance as its second argument');
}
/**
* @group legacy
*/
public function testLegacyConstructorApiAcceptsNullAsSecondArgument()
{
new DelegatingLoader($this->controllerNameParser, null, new LoaderResolver());
$this->assertTrue(true, '__construct() accepts null as its second argument');
}
public function testConstructorApi()
{
new DelegatingLoader($this->controllerNameParser, new LoaderResolver());
$this->assertTrue(true, '__construct() takes a ControllerNameParser and LoaderResolverInterface respectively as its first and second argument.');
}
}
","controllerNameParser = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser')
->disableOriginalConstructor()
->getMock();
}
/**
* @group legacy
*/
public function testLegacyConstructorApi()
{
new DelegatingLoader($this->controllerNameParser, new NullLogger(), new LoaderResolver());
$this->assertTrue(true, '__construct() accepts a LoggerInterface instance as its second argument');
}
/**
* @group legacy
*/
public function testLegacyConstructorApiAcceptsNullAsSecondArgument()
{
new DelegatingLoader($this->controllerNameParser, null, new LoaderResolver());
$this->assertTrue(true, '__construct() accepts null as its second argument');
}
public function testConstructorApi()
{
new DelegatingLoader($this->controllerNameParser, new LoaderResolver());
$this->assertTrue(true, '__construct() takes a ControllerNameParser and LoaderResolverInterface respectively as its first and second argument.');
}
}
"
Fix position calculation of second character when first character is a newline,"package org.spoofax.jsglr2.inputstack;
import org.metaborg.parsetable.characterclasses.CharacterClassFactory;
import org.spoofax.jsglr2.parser.Position;
public class LayoutSensitiveInputStack extends InputStack {
private static final int TAB_SIZE = 8;
private int currentLine;
private int currentColumn;
public Position previousPosition;
public LayoutSensitiveInputStack(String inputString) {
super(inputString);
this.currentLine = 1;
this.currentColumn = CharacterClassFactory.isNewLine(currentChar) ? 0 : 1;
this.previousPosition = new Position(-1, currentLine, currentColumn - 1);
}
public Position currentPosition() {
return new Position(currentOffset, currentLine, currentColumn);
}
@Override public void next() {
super.next();
previousPosition = currentPosition();
if(currentOffset < inputLength) {
if(CharacterClassFactory.isNewLine(currentChar)) {
currentLine++;
currentColumn = 0;
} else if(CharacterClassFactory.isCarriageReturn(currentChar)) {
} else if(CharacterClassFactory.isTab(currentChar)) {
currentColumn = (currentColumn / TAB_SIZE + 1) * TAB_SIZE;
} else {
currentColumn++;
}
}
if(currentOffset == inputLength)
currentColumn++;
}
}
","package org.spoofax.jsglr2.inputstack;
import org.metaborg.parsetable.characterclasses.CharacterClassFactory;
import org.spoofax.jsglr2.parser.Position;
public class LayoutSensitiveInputStack extends InputStack {
private static final int TAB_SIZE = 8;
private int currentLine = 1;
private int currentColumn = 1;
public Position previousPosition = new Position(-1, 1, 0);
public LayoutSensitiveInputStack(String inputString) {
super(inputString);
}
public Position currentPosition() {
return new Position(currentOffset, currentLine, currentColumn);
}
@Override public void next() {
super.next();
previousPosition = currentPosition();
if(currentOffset < inputLength) {
if(CharacterClassFactory.isNewLine(currentChar)) {
currentLine++;
currentColumn = 0;
} else if(CharacterClassFactory.isCarriageReturn(currentChar)) {
} else if(CharacterClassFactory.isTab(currentChar)) {
currentColumn = (currentColumn / TAB_SIZE + 1) * TAB_SIZE;
} else {
currentColumn++;
}
}
if(currentOffset == inputLength)
currentColumn++;
}
}
"
Remove cytoolz usage in CLI,"# coding: utf8
from __future__ import unicode_literals
from ...gold import iob_to_biluo
from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
""""""
Convert IOB files into JSON format for use with train cli.
""""""
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first[""paragraphs""][0][""sentences""]
for sent in group[1:]:
to_extend.extend(sent[""paragraphs""][0][""sentences""])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split(""|"") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = [""-""] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{""orth"": w, ""tag"": p, ""ner"": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{""tokens"": sent} for sent in sentences]
paragraphs = [{""sentences"": [sent]} for sent in sentences]
docs = [{""id"": 0, ""paragraphs"": [para]} for para in paragraphs]
return docs
","# coding: utf8
from __future__ import unicode_literals
import cytoolz
from ...gold import iob_to_biluo
def iob2json(input_data, n_sents=10, *args, **kwargs):
""""""
Convert IOB files into JSON format for use with train cli.
""""""
docs = []
for group in cytoolz.partition_all(n_sents, docs):
group = list(group)
first = group.pop(0)
to_extend = first[""paragraphs""][0][""sentences""]
for sent in group[1:]:
to_extend.extend(sent[""paragraphs""][0][""sentences""])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split(""|"") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = [""-""] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{""orth"": w, ""tag"": p, ""ner"": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{""tokens"": sent} for sent in sentences]
paragraphs = [{""sentences"": [sent]} for sent in sentences]
docs = [{""id"": 0, ""paragraphs"": [para]} for para in paragraphs]
return docs
"
Include csrf-token into JWT on every web request," \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
/** include laravel csrf-token on jwt token **/
'web' => \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
];
}
"," \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
"
Correct spelling of $driver variable,"
* (c) Graham Campbell
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NotifyMeHQ\NotifyMe;
use InvalidArgumentException;
class NotifyMeFactory implements FactoryInterface
{
/**
* Create a new gateway instance.
*
* @param string[] $config
*
* @return \NotifyMeHQ\NotifyMe\GatewayInterface
*/
public function make(array $config)
{
return $this->createFactory($config)->make($config);
}
/**
* Create a connector instance based on the configuration.
*
* @param string[] $config
*
* @throws \InvalidArgumentException
*
* @return \NotifyMeHQ\NotifyMe\FactoryInterface
*/
public function createFactory(array $config)
{
if (!isset($config['driver'])) {
throw new InvalidArgumentException(""A driver must be specified."");
}
$driver = ucfirst($config['driver']);
$class = ""NotifyMeHQ\\{$driver}\\{$driver}Factory"";
if (class_exists($class)) {
return new $class();
}
throw new InvalidArgumentException(""Unsupported driver [{$config['driver']}]."");
}
}
","
* (c) Graham Campbell
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace NotifyMeHQ\NotifyMe;
use InvalidArgumentException;
class NotifyMeFactory implements FactoryInterface
{
/**
* Create a new gateway instance.
*
* @param string[] $config
*
* @return \NotifyMeHQ\NotifyMe\GatewayInterface
*/
public function make(array $config)
{
return $this->createFactory($config)->make($config);
}
/**
* Create a connector instance based on the configuration.
*
* @param string[] $config
*
* @throws \InvalidArgumentException
*
* @return \NotifyMeHQ\NotifyMe\FactoryInterface
*/
public function createFactory(array $config)
{
if (!isset($config['driver'])) {
throw new InvalidArgumentException(""A driver must be specified."");
}
$dirver = ucfirst($config['driver']);
$class = ""NotifyMeHQ\\{$dirver}\\{$dirver}Factory"";
if (class_exists($class)) {
return new $class();
}
throw new InvalidArgumentException(""Unsupported driver [{$config['driver']}]."");
}
}
"
Use Locale.UK while parsing dates.,"/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
package it.inaf.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatter {
public static String format(String date)
{
SimpleDateFormat format = new SimpleDateFormat(""EEE, dd MMM yyyy HH:mm:ss Z"", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
format = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"", Locale.UK);
try {
tmpDate = format.parse(date);
} catch (ParseException e1) {
format = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"", Locale.UK);
try {
tmpDate = format.parse(date);
} catch (ParseException e2) {
e2.printStackTrace();
}
}
}
SimpleDateFormat postFormater = new SimpleDateFormat(""dd.MM.yyyy"", Locale.ITALY);
return postFormater.format(tmpDate);
}
}","/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
package it.inaf.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatter {
public static String format(String date)
{
SimpleDateFormat format = new SimpleDateFormat(""EEE, dd MMM yyyy HH:mm:ss Z"");
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
format = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"");
try {
tmpDate = format.parse(date);
} catch (ParseException e1) {
format = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"");
try {
tmpDate = format.parse(date);
} catch (ParseException e2) {
e2.printStackTrace();
}
}
}
SimpleDateFormat postFormater = new SimpleDateFormat(""dd.MM.yyyy"", Locale.ITALY);
return postFormater.format(tmpDate);
}
}"
Add `{'ignoreSearch': true}` to cache.match(),"/* https://developers.google.com/web/ilt/pwa/offline-quickstart */
var CACHE = 'evilnickname-soundboard-cache';
var urlsToCache = [
'.',
'index.html',
'megaphone.svg',
'android-chrome-512x512.png'
]
self.addEventListener('install', function (e) {
console.log('The service worker is being installed.');
e.waitUntil(caches.open(CACHE)
.then(function (cache) {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request, {'ignoreSearch': true})
.then(function (response) {
return response || fetchAndCache(event.request);
})
);
});
function fetchAndCache(url) {
return fetch(url)
.then(function (response) {
// Check if we received a valid response
if (!response.ok) {
throw Error(response.statusText);
}
return caches.open(CACHE)
.then(function (cache) {
cache.put(url, response.clone());
return response;
});
})
.catch(function (error) {
console.log('Request failed:', error);
// You could return a custom offline 404 page here
});
}","/* https://developers.google.com/web/ilt/pwa/offline-quickstart */
var CACHE = 'evilnickname-soundboard-cache';
var urlsToCache = [
'.',
'index.html',
'megaphone.svg',
'android-chrome-512x512.png'
]
self.addEventListener('install', function (e) {
console.log('The service worker is being installed.');
e.waitUntil(caches.open(CACHE)
.then(function (cache) {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request)
.then(function (response) {
return response || fetchAndCache(event.request);
})
);
});
function fetchAndCache(url) {
return fetch(url)
.then(function (response) {
// Check if we received a valid response
if (!response.ok) {
throw Error(response.statusText);
}
return caches.open(CACHE)
.then(function (cache) {
cache.put(url, response.clone());
return response;
});
})
.catch(function (error) {
console.log('Request failed:', error);
// You could return a custom offline 404 page here
});
}"
"Disable RefreshDatabase & set default user.
The RefreshDatabase trait doesn't seem to work with Dusk, probably because the transaction isn't committed when request is made?","create();
}
/**
* Setup the test environment.
*
* @return void
*/
public function setUp()
{
parent::setUp();
$this->configureMocks();
}
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
static::startChromeDriver();
}
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
'--disable-gpu',
'--headless',
'no-sandbox',
]);
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
}
","configureMocks();
}
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
static::startChromeDriver();
}
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions)->addArguments([
'--disable-gpu',
'--headless',
'no-sandbox',
]);
return RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
}
"
"Fix the but There is an error (cannot concatenate str and int objects)
when the user does not specify the inputs.","""""""
DummyProcess to check the WPS structure
Author: Jorge de Jesus (jorge.jesus@gmail.com) as suggested by Kor de Jong
""""""
from pywps.Process import WPSProcess
import types
class Process(WPSProcess):
def __init__(self):
# init process
WPSProcess.__init__(self,
identifier = ""dummyprocess"", # must be same, as filename
title=""Dummy Process"",
version = ""0.1"",
storeSupported = ""true"",
statusSupported = ""true"",
abstract=""The Dummy process is used for testing the WPS structure. The process will accept 2 input numbers and will return the XML result with an add one and subtract one operation"",
grassLocation =False)
self.Input1 = self.addLiteralInput(identifier = ""input1"",
title = ""Input1 number"",
type=types.IntType,
default=""100"")
self.Input2= self.addLiteralInput(identifier=""input2"",
title=""Input2 number"",
type=types.IntType,
default=""200"")
self.Output1=self.addLiteralOutput(identifier=""output1"",
title=""Output1 add 1 result"")
self.Output2=self.addLiteralOutput(identifier=""output2"",title=""Output2 subtract 1 result"" )
def execute(self):
self.Output1.setValue(int(self.Input1.getValue())+1)
self.Output2.setValue(int(self.Input1.getValue())-1)
return
","""""""
DummyProcess to check the WPS structure
Author: Jorge de Jesus (jorge.de-jesus@jrc.it) as suggested by Kor de Jong
""""""
from pywps.Process import WPSProcess
class Process(WPSProcess):
def __init__(self):
# init process
WPSProcess.__init__(self,
identifier = ""dummyprocess"", # must be same, as filename
title=""Dummy Process"",
version = ""0.1"",
storeSupported = ""true"",
statusSupported = ""true"",
abstract=""The Dummy process is used for testing the WPS structure. The process will accept 2 input numbers and will return the XML result with an add one and subtract one operation"",
grassLocation =False)
self.Input1 = self.addLiteralInput(identifier = ""input1"",
title = ""Input1 number"",
default=""100"")
self.Input2= self.addLiteralInput(identifier=""input2"",
title=""Input2 number"",
default=""200"")
self.Output1=self.addLiteralOutput(identifier=""output1"",
title=""Output1 add 1 result"")
self.Output2=self.addLiteralOutput(identifier=""output2"",title=""Output2 subtract 1 result"" )
def execute(self):
self.Output1.setValue(self.Input1.getValue()+1)
self.Output2.setValue(self.Input1.getValue()-1)
return
"
Fix NPE on retry rule.,"package pt.fccn.saw.selenium;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by mehmetgerceker on 12/7/15.
*/
public class RetryRule implements TestRule {
private AtomicInteger retryCount;
public RetryRule(int retries){
super();
this.retryCount = new AtomicInteger(retries);
}
@Override
public Statement apply(final Statement base, final Description description) {
//statement is a private method which will return a new statement
//here Statement is taken as abstract for your test which includes test method and before/after methods )
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.out.println(""Evaluating retry ..."");
Throwable firstCaughtThrowable = null;
// implement retry logic here
while (retryCount.getAndDecrement() > 0) {
try {
base.evaluate();
return;
} catch (Throwable t) {
t.printStackTrace();
if (firstCaughtThrowable == null) {
firstCaughtThrowable = t;
}
if (retryCount.get() > 0 && description.getAnnotation(Retry.class)!= null) {
System.err.println(description.getDisplayName() +
"": Failed, "" +
retryCount.toString() +
"" retries remain"");
} else {
throw firstCaughtThrowable;
}
}
}
}
};
}
}
","package pt.fccn.saw.selenium;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by mehmetgerceker on 12/7/15.
*/
public class RetryRule implements TestRule {
private AtomicInteger retryCount;
public RetryRule(int retries){
super();
this.retryCount = new AtomicInteger(retries);
}
@Override
public Statement apply(final Statement base, final Description description) {
//statement is a private method which will return a new statement
//here Statement is taken as abstract for your test which includes test method and before/after methods )
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.out.println(""Evaluating retry ..."");
Throwable caughtThrowable = null;
// implement retry logic here
while (retryCount.getAndDecrement() > 0) {
try {
base.evaluate();
return;
} catch (Throwable t) {
t.printStackTrace();
if (retryCount.get() > 0 && description.getAnnotation(Retry.class)!= null) {
caughtThrowable = t;
System.err.println(description.getDisplayName() +
"": Failed, "" +
retryCount.toString() +
"" retries remain"");
} else {
throw caughtThrowable;
}
}
}
}
};
}
}
"
Remove a couple unused variables.,"assign('currentTime', date('Y-m-d H:i:s'));
$file_log = CRM_Core_Error::createDebugLogger();
$logFileName = $file_log->_filename;
$file_log->close();
$this->assign('fileName', $logFileName);
$entries = array();
if ($handle = @fopen($logFileName,'r')) {
$line = 0;
while (!feof($handle)) {
$line++;
$dd = fgets($handle);
if (strlen($dd) >= 15 && (' ' != $dd[0])) {
$date = substr($dd,0,15);
if (preg_match(""/^[A-Z][a-z]{2} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/"",$date)) {
$entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
$entries[$line] = array('lineNumber' => ''.$line.'', 'dateTime' => $date, 'message' => substr($dd,16));
}
}
}
fclose($handle);
krsort($entries);
$this->assign('logEntries', $entries);
}
parent::run();
}
}
","assign('currentTime', date('Y-m-d H:i:s'));
$config = CRM_Core_Config::singleton();
$file_log = CRM_Core_Error::createDebugLogger();
$logFileName = $file_log->_filename;
$logFileFormat = $file_log->_lineFormat;
$file_log->close();
$this->assign('fileName', $logFileName);
$entries = array();
if ($handle = @fopen($logFileName,'r')) {
$line = 0;
while (!feof($handle)) {
$line++;
$dd = fgets($handle);
if (strlen($dd) >= 15 && (' ' != $dd[0])) {
$date = substr($dd,0,15);
if (preg_match(""/^[A-Z][a-z]{2} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/"",$date)) {
$entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
$entries[$line] = array('lineNumber' => ''.$line.'', 'dateTime' => $date, 'message' => substr($dd,16));
}
}
}
fclose($handle);
krsort($entries);
$this->assign('logEntries', $entries);
}
parent::run();
}
}
"
Include author in progress notes,"/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/
Ext.define('SlateAdmin.model.person.progress.ProgressNote', {
extend: 'Ext.data.Model',
idProperty: 'ID',
fields: [
'Subject',
{
name: 'ID',
type: 'integer',
useNull: true,
defaultValue: null
}, {
name: 'Class',
defaultValue: 'Slate\\Progress\\Note'
}, {
name: 'ContextClass',
defaultValue: 'Emergence\\People\\Person'
}, {
name: 'ContextID',
type: 'integer'
}, {
name: 'AuthorID',
type: 'integer',
useNull: true,
defaultValue: null,
persist: false
}, {
name: 'Author',
useNull: true,
defaultValue: null,
persist: false
}, {
name: 'Message',
type: 'string',
allowBlank: false
}, {
name: 'MessageFormat',
defaultValue: 'html'
}, {
name: 'Status',
useNull: true,
defaultValue: null
}, {
name: 'Source',
useNull: true,
defaultValue: null
}, {
name: 'ParentMessageID',
type: 'integer',
useNull: true,
defaultValue: null
}, {
name: 'Sent',
type: 'date',
dateFormat: 'timestamp'
}
],
proxy: {
type: 'slaterecords',
url: '/notes',
include: ['Author']
}
});
","/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/
Ext.define('SlateAdmin.model.person.progress.ProgressNote', {
extend: 'Ext.data.Model',
idProperty: 'ID',
fields: [
'Subject',
{
name: 'ID',
type: 'integer',
useNull: true,
defaultValue: null
}, {
name: 'Class',
defaultValue: 'Slate\\Progress\\Note'
}, {
name: 'ContextClass',
defaultValue: 'Emergence\\People\\Person'
}, {
name: 'ContextID',
type: 'integer'
}, {
name: 'AuthorID',
type: 'integer',
useNull: true,
defaultValue: null,
persist: false
}, {
name: 'Author',
useNull: true,
defaultValue: null,
persist: false
}, {
name: 'Message',
type: 'string',
allowBlank: false
}, {
name: 'MessageFormat',
defaultValue: 'html'
}, {
name: 'Status',
useNull: true,
defaultValue: null
}, {
name: 'Source',
useNull: true,
defaultValue: null
}, {
name: 'ParentMessageID',
type: 'integer',
useNull: true,
defaultValue: null
}, {
name: 'Sent',
type: 'date',
dateFormat: 'timestamp'
}
],
proxy: {
type: 'slaterecords',
writer: {
type: 'json',
rootProperty: 'data',
writeAllFields: false,
allowSingle: false
},
url: '/notes'
}
});
"
Update to the latest version of wptrunner.,"# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKAGE_VERSION = '0.1'
deps = ['fxos-appgen>=0.2.7',
'marionette_client>=0.7.1.1',
'marionette_extension >= 0.1',
'mozdevice >= 0.33',
'mozlog >= 1.8',
'moznetwork >= 0.24',
'mozprocess >= 0.18',
'wptserve >= 1.0.1',
'wptrunner >= 0.3']
setup(name='fxos-certsuite',
version=PACKAGE_VERSION,
description='Certification suite for FirefoxOS',
classifiers=[],
keywords='mozilla',
author='Mozilla Automation and Testing Team',
author_email='tools@lists.mozilla.org',
url='https://github.com/mozilla-b2g/fxos-certsuite',
license='MPL',
packages=['certsuite'],
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points=""""""
# -*- Entry points: -*-
[console_scripts]
runcertsuite = certsuite:harness_main
cert = certsuite:certcli
"""""")
","# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup
PACKAGE_VERSION = '0.1'
deps = ['fxos-appgen>=0.2.7',
'marionette_client>=0.7.1.1',
'marionette_extension >= 0.1',
'mozdevice >= 0.33',
'mozlog >= 1.8',
'moznetwork >= 0.24',
'mozprocess >= 0.18',
'wptserve >= 1.0.1',
'wptrunner >= 0.2.8, < 0.3']
setup(name='fxos-certsuite',
version=PACKAGE_VERSION,
description='Certification suite for FirefoxOS',
classifiers=[],
keywords='mozilla',
author='Mozilla Automation and Testing Team',
author_email='tools@lists.mozilla.org',
url='https://github.com/mozilla-b2g/fxos-certsuite',
license='MPL',
packages=['certsuite'],
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points=""""""
# -*- Entry points: -*-
[console_scripts]
runcertsuite = certsuite:harness_main
cert = certsuite:certcli
"""""")
"
Fix exception when saving dashboards,"'use strict';
var codex = require('../codex');
var Boom = require('boom');
var Dashboard = require('../models/Dashboard');
module.exports = codex.controller(Dashboard, {
get: true,
search: true,
insert: true,
replace: true,
preInsert: function (req, esRequest, callback) {
if (!req.user || !req.user.isAdmin()) {
return callback(Boom.forbidden());
}
// enforce unique constraint on name TODO this should be done in model
Dashboard.search({
body: {
query: {
'constant_score': {
filter: {
term: {
// use un-analyzed version of the field for case-sensitive matching
'name': esRequest.body.name
}
}
}
}
}
}, function (err, results) {
if (err) {
return callback(err);
}
if (results.length > 0 && results[0].id !== esRequest.id) {
return callback(Boom.create(400, 'There\'s already a dashboard with the name ' + esRequest.body.name, {
error: 'UniqueConstraintViolation',
field: 'name',
value: esRequest.body.name
}));
}
callback(null, esRequest);
});
},
delete: true,
preDelete: function (req, esRequest, callback) {
if (!req.user || !req.user.isAdmin()) {
return callback(Boom.forbidden());
}
callback(null, esRequest);
}
}).with(require('../caper-trail').controller);
","'use strict';
var codex = require('../codex');
var Boom = require('boom');
var Dashboard = require('../models/Dashboard');
module.exports = codex.controller(Dashboard, {
get: true,
search: true,
insert: true,
replace: true,
preInsert: function (req, esRequest, callback) {
if (!req.user || !req.user.isAdmin()) {
return callback(Boom.forbidden());
}
// enforce unique constraint on name
Dashboard.search({
body: {
query: {
'constant_score': {
filter: {
term: {
// use un-analyzed version of the field for case-sensitive matching
'name': esRequest.body.name
}
}
}
}
}
}, function (err, results) {
if (err) {
return callback(err);
}
if (results.length > 0 && results[0]._.id !== esRequest.id) {
return callback(Boom.create(400, 'There\'s already a dashboard with the name ' + esRequest.body.name, {
error: 'UniqueConstraintViolation',
field: 'name',
value: esRequest.body.name
}));
}
callback(null, esRequest);
});
},
delete: true,
preDelete: function (req, esRequest, callback) {
if (!req.user || !req.user.isAdmin()) {
return callback(Boom.forbidden());
}
callback(null, esRequest);
}
}).with(require('../caper-trail').controller);
"
Update copy of unserialization error message,"
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CacheTool\Adapter;
use CacheTool\Code;
abstract class AbstractAdapter
{
/**
* @param Code $code
* @return string
*/
abstract protected function doRun(Code $code);
/**
* @param Code $code
* @throws \RuntimeException
* @return mixed
*/
public function run(Code $code)
{
$result = @unserialize($this->doRun($code));
if (!is_array($result)) {
throw new \RuntimeException('Could not unserialize data from adapter.');
}
if (empty($result['errors'])) {
return $result['result'];
}
$msgs = array();
foreach ($result['errors'] as $error) {
$msgs[] = ""{$error['str']} (error code: {$error['no']})"";
}
throw new \RuntimeException(implode(PHP_EOL, $msgs));
}
/**
* @return string
*/
protected function createTemporaryFile()
{
$file = sprintf(""%s/cachetool-%s.php"", sys_get_temp_dir(), uniqid());
touch($file);
chmod($file, 0666);
return $file;
}
}
","
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CacheTool\Adapter;
use CacheTool\Code;
abstract class AbstractAdapter
{
/**
* @param Code $code
* @return string
*/
abstract protected function doRun(Code $code);
/**
* @param Code $code
* @throws \RuntimeException
* @return mixed
*/
public function run(Code $code)
{
$result = @unserialize($this->doRun($code));
if (!is_array($result)) {
throw new \RuntimeException('Could not unserialize output');
}
if (empty($result['errors'])) {
return $result['result'];
}
$msgs = array();
foreach ($result['errors'] as $error) {
$msgs[] = ""{$error['str']} (error code: {$error['no']})"";
}
throw new \RuntimeException(implode(PHP_EOL, $msgs));
}
/**
* @return string
*/
protected function createTemporaryFile()
{
$file = sprintf(""%s/cachetool-%s.php"", sys_get_temp_dir(), uniqid());
touch($file);
chmod($file, 0666);
return $file;
}
}
"
Complete cyclic rotation on a given array.,"array = $array;
$this->rotation = $rotation;
}
/**
* @param mixed $rotation
*/
public function setRotation($rotation) {
$this->rotation = $rotation;
}
/**
* @param mixed $array
*/
public function setArray($array) {
$this->array = $array;
}
/**
* @return mixed
*/
public function getArray() {
return $this->array;
}
/**
* @return mixed
*/
public function getRotation() {
return $this->rotation;
}
public function rotateArray() {
$arrayToRotate = $this->getArray();
$rotation = $this->getRotation();
$arrayCount = count($arrayToRotate);
//var_dump($arrayCount);exit;
$outputArray = array();
foreach($arrayToRotate as $key => $value) {
$rotationTimes = $key + $rotation + 1;
if($rotationTimes > $arrayCount) {
$modulusKey = $rotationTimes % $rotation;
$outputArray[$modulusKey] = $value;
}
else {
$outputArray[$rotationTimes - 1] = $value;
}
}
return $outputArray;
}
}
$cyclicRotation = new CyclicRotation([3, 8, 9, 7, 6], 3);
var_dump($cyclicRotation->rotateArray());","array = $array;
$this->rotation = $rotation;
}
/**
* @param mixed $rotation
*/
public function setRotation($rotation) {
$this->rotation = $rotation;
}
/**
* @param mixed $array
*/
public function setArray($array) {
$this->array = $array;
}
/**
* @return mixed
*/
public function getArray() {
return $this->array;
}
/**
* @return mixed
*/
public function getRotation() {
return $this->rotation;
}
public function rotateArray() {
$arrayToRotate = $this->getArray();
$rotation = $this->getRotation();
$arrayCount = count($arrayToRotate);
//var_dump($arrayCount);exit;
$outputArray = array();
foreach($arrayToRotate as $key => $value) {
$rotationTimes = $key + $rotation;
if($rotationTimes >= $arrayCount) {
$modulusKey = $rotationTimes % $rotation;
$outputArray[$modulusKey] = $value;
}
else {
$outputArray[$rotationTimes] = $value;
}
}
}
}
$cyclicRotation = new CyclicRotation([3, 8, 9, 7, 6], 3);
$cyclicRotation->rotateArray();"
Fix Firefox: no more sending a post when submitting.,"$(window).load(function () {
var Ector = require('ector');
ector = new Ector();
var previousResponseNodes = null;
var user = { username: ""Guy""};
var msgtpl = $('#msgtpl').html();
var lastmsg = false;
$('#msgtpl').remove();
var message;
$('#send').on('click', function () {
var d = new Date();
var entry = $('#message').val();
message = {
user: user,
message: entry,
h: d.getHours(),
m: d.getMinutes()
};
$('#message').attr('value',''); // FIXME
$('#messages').append('' + Mustache.render(msgtpl, message) + '
');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
ector.addEntry(entry);
ector.linkNodesToLastSentence(previousResponseNodes);
var response = ector.generateResponse();
// console.log('%s: %s', ector.name, response.sentence);
previousResponseNodes = response.nodes;
d = new Date();
message = {
user: {username: ector.name},
message: response.sentence,
h: d.getHours(),
m: d.getMinutes()
};
$('#messages').append('' + Mustache.render(msgtpl, message) + '
');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
return false;
});
});","$(window).load(function () {
var Ector = require('ector');
ector = new Ector();
var previousResponseNodes = null;
var user = { username: ""Guy""};
var msgtpl = $('#msgtpl').html();
var lastmsg = false;
$('#msgtpl').remove();
var message;
$('#send').on('click', function () {
var d = new Date();
var entry = $('#message').val();
message = {
user: user,
message: entry,
h: d.getHours(),
m: d.getMinutes()
};
$('#message').attr('value',''); // FIXME
$('#messages').append('' + Mustache.render(msgtpl, message) + '
');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
ector.addEntry(entry);
ector.linkNodesToLastSentence(previousResponseNodes);
var response = ector.generateResponse();
// console.log('%s: %s', ector.name, response.sentence);
previousResponseNodes = response.nodes;
d = new Date();
message = {
user: {username: ector.name},
message: response.sentence,
h: d.getHours(),
m: d.getMinutes()
};
$('#messages').append('' + Mustache.render(msgtpl, message) + '
');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
});
});"
Fix error in pomm service provider,"
*/
class Pomm implements ServiceProvider
{
/**
* Returns a list of all container entries registered by this service provider.
*
* - the key is the entry name
* - the value is a callable that will return the entry, aka the **factory**
*
* Factories have the following signature:
* function(ContainerInterface $container, callable $getPrevious = null)
*
* About factories parameters:
*
* - the container (instance of `Interop\Container\ContainerInterface`)
* - a callable that returns the previous entry if overriding a previous entry, or `null` if not
*
* @return callable[]
*/
public function getServices()
{
return [
\PommProject\Foundation\Pomm::class => function () {
return new \PommProject\Foundation\Pomm(['db' => [
'dsn' => getenv('DATABASE_DSN'),
'class:session_builder' => SessionBuilder::class
]]);
}
];
}
}
","
*/
class Pomm implements ServiceProvider
{
/**
* Returns a list of all container entries registered by this service provider.
*
* - the key is the entry name
* - the value is a callable that will return the entry, aka the **factory**
*
* Factories have the following signature:
* function(ContainerInterface $container, callable $getPrevious = null)
*
* About factories parameters:
*
* - the container (instance of `Interop\Container\ContainerInterface`)
* - a callable that returns the previous entry if overriding a previous entry, or `null` if not
*
* @return callable[]
*/
public function getServices()
{
return [
\PommProject\Foundation\Pomm::class => function () {
return new Pomm(['db' => [
'dsn' => getenv('DATABASE_DSN'),
'class:session_builder' => SessionBuilder::class
]]);
}
];
}
}
"
Add operation to update campaign.,"""""""
API MAPPING FOR Eloqua API V2
""""""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'update_campaign': {
'method': 'PUT',
'path': '/assets/campaign/{{campaign_id}}'
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId'],
'status': 201
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
","""""""
API MAPPING FOR Eloqua API V2
""""""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'update_campaign': {
'method': 'PUT',
'path': '/assets/campaign/{{campaign_id}}'
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId']
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
"
Handle case when RenderContext is not an array but ArrayObject,"templating = $templating;
}
/**
* @param GetResponseForControllerResultEvent $event
*/
public function onKernelView(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
$nodeTranslation = $request->attributes->get('_nodeTranslation');
if ($nodeTranslation) {
$entity = $request->attributes->get('_entity');
$url = $request->attributes->get('url');
$nodeMenu = $request->attributes->get('_nodeMenu');
$parameters = $request->attributes->get('_renderContext');
$renderContext = array(
'_nodeTranslation' => $nodeTranslation,
'slug' => $url,
'page' => $entity,
'resource' => $entity,
'nodemenu' => $nodeMenu,
);
if (is_array($parameters) || $parameters instanceof \ArrayObject) {
$parameters = array_merge($renderContext, (array)$parameters);
} else {
$parameters = $renderContext;
}
// Sent the response here, another option is to let the symfony kernel.view listener handle it
$event->setResponse($this->templating->renderResponse($entity->getDefaultView(), $parameters));
}
}
}
","templating = $templating;
}
/**
* @param GetResponseForControllerResultEvent $event
*/
public function onKernelView(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
$nodeTranslation = $request->attributes->get('_nodeTranslation');
if ($nodeTranslation) {
$entity = $request->attributes->get('_entity');
$url = $request->attributes->get('url');
$nodeMenu = $request->attributes->get('_nodeMenu');
$parameters = $request->attributes->get('_renderContext');
$renderContext = array(
'_nodeTranslation' => $nodeTranslation,
'slug' => $url,
'page' => $entity,
'resource' => $entity,
'nodemenu' => $nodeMenu,
);
if (is_array($parameters)) {
$parameters = array_merge($renderContext, $parameters);
} else {
$parameters = $renderContext;
}
// Sent the response here, another option is to let the symfony kernel.view listener handle it
$event->setResponse($this->templating->renderResponse($entity->getDefaultView(), $parameters));
}
}
}
"
Update tests for new API.,"# -*- coding: utf-8 -*-
import hummus
from tempfile import NamedTemporaryFile
import os
def assert_pdf(filename):
with open(filename, 'rb') as stream:
assert stream.read(4) == b'%PDF'
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(stream.name)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_document_stream():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(stream)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_page_size():
page = hummus.Page()
assert page.media_box.left == 0
page.media_box = hummus.Rectangle(0, 0, 800, 1000)
assert page.media_box.bottom == 1000
def test_basic_text():
with NamedTemporaryFile(delete=False) as stream:
with hummus.Document(stream) as document:
with document.Page() as page:
pass
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
","# -*- coding: utf-8 -*-
import hummus
from tempfile import NamedTemporaryFile
import os
def assert_pdf(filename):
with open(filename, 'rb') as stream:
assert stream.read(4) == b'%PDF'
def test_document_file():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(filename=stream.name)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_document_stream():
with NamedTemporaryFile(delete=False) as stream:
# Run through a normal cycle.
document = hummus.Document(stream)
document.begin()
document.end()
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
def test_page_size():
page = hummus.Page()
assert page.media_box.left == 0
page.media_box = hummus.Rectangle(0, 0, 800, 1000)
assert page.media_box.bottom == 1000
def test_basic_text():
with NamedTemporaryFile(delete=False) as stream:
with hummus.Document(stream) as document:
with document.Page() as page:
pass
# Open and test the file.
assert_pdf(stream.name)
# Remove the file.
os.remove(stream.name)
"
"Remove version range for py-sonic
py-sonic stopped supporting python2 > 0.6.2
Using pip to install results in an error if this is not set","from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall(""__([a-z]+)__ = '([^']+)'"", content))
return metadata['version']
setup(
name='Mopidy-Subidy',
version=get_version('mopidy_subidy/__init__.py'),
url='http://github.com/prior99/mopidy-subidy/',
license='BSD-3-Clause',
author='prior99',
author_email='fgnodtke@cronosx.de',
description='Improved Subsonic extension for Mopidy',
long_description=open('README.md').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'Mopidy >= 2.0',
'py-sonic == 0.6.2',
'Pykka >= 1.1'
],
entry_points={
b'mopidy.ext': [
'subidy = mopidy_subidy:SubidyExtension',
],
},
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD 3-Clause',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Multimedia :: Sound/Audio :: Players'
]
)
","from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall(""__([a-z]+)__ = '([^']+)'"", content))
return metadata['version']
setup(
name='Mopidy-Subidy',
version=get_version('mopidy_subidy/__init__.py'),
url='http://github.com/prior99/mopidy-subidy/',
license='BSD-3-Clause',
author='prior99',
author_email='fgnodtke@cronosx.de',
description='Improved Subsonic extension for Mopidy',
long_description=open('README.md').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'Mopidy >= 2.0',
'py-sonic >= 0.6.1',
'Pykka >= 1.1'
],
entry_points={
b'mopidy.ext': [
'subidy = mopidy_subidy:SubidyExtension',
],
},
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD 3-Clause',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Multimedia :: Sound/Audio :: Players'
]
)
"
"Use 127.0.0.1 instead of localhost in test DB connection
Using localhost prevents from running tests in WSL"," 'travis',
'connections' => [
'travis' => [
'driver' => 'c5_pdo_mysql',
'server' => '127.0.0.1',
'database' => 'concrete5_tests',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
'driverOptions' => [
PDO::MYSQL_ATTR_INIT_COMMAND => ""SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"",
],
],
'travisWithoutDB' => [
'driver' => 'c5_pdo_mysql',
'server' => '127.0.0.1',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
'driverOptions' => [
PDO::MYSQL_ATTR_INIT_COMMAND => ""SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"",
],
],
],
];
"," 'travis',
'connections' => [
'travis' => [
'driver' => 'c5_pdo_mysql',
'server' => 'localhost',
'database' => 'concrete5_tests',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
'driverOptions' => [
PDO::MYSQL_ATTR_INIT_COMMAND => ""SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"",
],
],
'travisWithoutDB' => [
'driver' => 'c5_pdo_mysql',
'server' => 'localhost',
'username' => 'travis',
'password' => '',
'charset' => 'utf8',
'driverOptions' => [
PDO::MYSQL_ATTR_INIT_COMMAND => ""SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"",
],
],
],
];
"
Replace R.pickBy() with complemented predicate with R.reject(),"/*jslint node, es6, maxlen: 80 */
/*eslint indent: ""off"" */
""use strict"";
const R = require(""ramda"");
module.exports = function groupByFiles(config) {
return Object
.keys(config)
.reduce(
(acc, linterName) => R.evolve(
{
fileLinters: (fileLinters) => config[linterName]
.files
.reduce(
function addLinterNameToFile(filesAcc, fileName) {
const linters = R.propOr(
[],
fileName,
filesAcc
);
return R.assoc(
fileName,
linters.concat(linterName),
filesAcc
);
},
fileLinters
)
},
acc
),
{
fileLinters: {},
linterConfigs: R.pipe(
R.reject(
R.propSatisfies(R.isEmpty, ""files"")
),
R.map(
R.omit([""files"", ""ignore""])
)
)(config)
}
);
};
","/*jslint node, es6, maxlen: 80 */
/*eslint indent: ""off"" */
""use strict"";
const R = require(""ramda"");
module.exports = function groupByFiles(config) {
return Object
.keys(config)
.reduce(
(acc, linterName) => R.evolve(
{
fileLinters: (fileLinters) => config[linterName]
.files
.reduce(
function addLinterNameToFile(filesAcc, fileName) {
const linters = R.propOr(
[],
fileName,
filesAcc
);
return R.assoc(
fileName,
linters.concat(linterName),
filesAcc
);
},
fileLinters
)
},
acc
),
{
fileLinters: {},
linterConfigs: R.pipe(
R.pickBy(
R.propSatisfies(
R.complement(R.isEmpty),
""files""
)
),
R.map(
R.omit([""files"", ""ignore""])
)
)(config)
}
);
};
"
"Add the possiblity to pass a conf file to Publisher and Subscriber class
Closes #20","from gevent import monkey
monkey.patch_all()
import uuid
from kombu.mixins import ConsumerMixin
from pubsub.backend.base import BaseSubscriber, BasePublisher
from pubsub.helpers import get_config
from pubsub.backend.handlers import RabbitMQHandler
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._producer = self._create_producer()
def publish(self, message):
message_id = str(uuid.uuid4())
message = {'payload': message,
'message_id': message_id,
'reply_to': None}
self._producer.publish(
message, exchange=self._exchange, **self.config.get('publish'))
return message_id
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self, config=None):
self.config = config or get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._queue = self._create_queue()
def run_forever(self):
self.run()
def get_consumers(self, consumer, channel):
return [consumer(
queues=[self._queue],
callbacks=[self.on_message],
**self.config.get('consumer'))]
def on_message(self, body, message):
message.ack()
","from gevent import monkey
monkey.patch_all()
import uuid
from kombu.mixins import ConsumerMixin
from pubsub.backend.base import BaseSubscriber, BasePublisher
from pubsub.helpers import get_config
from pubsub.backend.handlers import RabbitMQHandler
class RabbitMQPublisher(BasePublisher, RabbitMQHandler):
def __init__(self):
self.config = get_config('rabbitmq').get('publisher', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._producer = self._create_producer()
def publish(self, message):
message_id = str(uuid.uuid4())
message = {'payload': message,
'message_id': message_id,
'reply_to': None}
self._producer.publish(
message, exchange=self._exchange, **self.config.get('publish'))
return message_id
class RabbitMQSubscriber(ConsumerMixin, BaseSubscriber, RabbitMQHandler):
def __init__(self):
self.config = get_config('rabbitmq').get('subscriber', None)
self.connection = self._connect()
def start(self):
self._exchange = self._create_exchange()
self._queue = self._create_queue()
def run_forever(self):
self.run()
def get_consumers(self, consumer, channel):
return [consumer(
queues=[self._queue],
callbacks=[self.on_message],
**self.config.get('consumer'))]
def on_message(self, body, message):
message.ack()
"
Test that factories can be added manually,"package net.kencochrane.raven;
import com.google.common.collect.Iterators;
import mockit.Injectable;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Tested;
import net.kencochrane.raven.dsn.Dsn;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ServiceLoader;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class RavenFactoryTest {
@Tested
private RavenFactory ravenFactory;
@Mocked
private ServiceLoader mockServiceLoader;
@BeforeMethod
public void setUp() throws Exception {
new NonStrictExpectations() {{
ServiceLoader.load(RavenFactory.class);
result = mockServiceLoader;
}};
}
@Test
public void testGetFactoriesFromServiceLoader(@Injectable final Raven mockRaven,
@Injectable final Dsn mockDsn) throws Exception {
new NonStrictExpectations() {{
mockServiceLoader.iterator();
result = Iterators.singletonIterator(ravenFactory);
ravenFactory.createRavenInstance(mockDsn);
result = mockRaven;
}};
Raven raven = RavenFactory.ravenInstance(mockDsn);
assertThat(raven, is(mockRaven));
}
@Test
public void testGetFactoriesManuallyAdded(@Injectable final Raven mockRaven,
@Injectable final Dsn mockDsn) throws Exception {
new NonStrictExpectations() {{
RavenFactory.registerFactory(ravenFactory);
ravenFactory.createRavenInstance(mockDsn);
result = mockRaven;
}};
Raven raven = RavenFactory.ravenInstance(mockDsn);
assertThat(raven, is(mockRaven));
}
}
","package net.kencochrane.raven;
import com.google.common.collect.Iterators;
import mockit.Injectable;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Tested;
import net.kencochrane.raven.dsn.Dsn;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ServiceLoader;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class RavenFactoryTest {
@Tested
private RavenFactory ravenFactory;
@Mocked
private ServiceLoader mockServiceLoader;
@BeforeMethod
public void setUp() throws Exception {
new NonStrictExpectations() {{
ServiceLoader.load(RavenFactory.class);
result = mockServiceLoader;
}};
}
@Test
public void testGetFactoriesFromServiceLoader(@Injectable final Raven mockRaven,
@Injectable final Dsn mockDsn) throws Exception {
new NonStrictExpectations() {{
mockServiceLoader.iterator();
result = Iterators.singletonIterator(ravenFactory);
ravenFactory.createRavenInstance(mockDsn);
result = mockRaven;
}};
Raven raven = RavenFactory.ravenInstance(mockDsn);
assertThat(raven, is(mockRaven));
}
}
"
Add horizontal rule to footer,"
","
"
Update max length for x-ray tube housing/insert model validation," 'required|exists:machines,id|integer',
'hsgManufID' => 'integer|exists:manufacturers,id',
'hsgModel' => 'string|nullable|max:50',
'hsgSN' => 'string|nullable|max:20',
'insertManufID' => 'integer|exists:manufacturers,id',
'insertModel' => 'string|nullable|max:50',
'insertSN' => 'string|nullable|max:20',
'manufDate' => 'date_format:Y-m-d|nullable',
'installDate' => 'date_format:Y-m-d|nullable',
'lfs' => 'numeric',
'mfs' => 'numeric',
'sfs' => 'numeric',
'tube_status' => 'required|in:Active,Removed|max:20',
'notes' => 'string|nullable|max:65535',
];
}
}
"," 'required|exists:machines,id|integer',
'hsgManufID' => 'integer|exists:manufacturers,id',
'hsgModel' => 'string|nullable|max:30',
'hsgSN' => 'string|nullable|max:20',
'insertManufID' => 'integer|exists:manufacturers,id',
'insertModel' => 'string|nullable|max:30',
'insertSN' => 'string|nullable|max:20',
'manufDate' => 'date_format:Y-m-d|nullable',
'installDate' => 'date_format:Y-m-d|nullable',
'lfs' => 'numeric',
'mfs' => 'numeric',
'sfs' => 'numeric',
'tube_status' => 'required|in:Active,Removed|max:20',
'notes' => 'string|nullable|max:65535',
];
}
}
"
Enable SQL logging only in debug mode,"getStatementHandler()
->withLogging()
->withStopWatch();
}
if ($db->schema('\Miniflux\Schema')->check(Schema\VERSION)) {
return $db;
} else {
$errors = $db->getLogMessages();
$nb_errors = count($errors);
$last_error = isset($errors[$nb_errors - 1]) ? $errors[$nb_errors - 1] : 'Enable debug mode to have more information';
throw new RuntimeException('Unable to migrate the database schema: '.$last_error);
}
}
function get_connection_parameters()
{
if (DB_DRIVER === 'postgres') {
require_once __DIR__.'/../schemas/postgres.php';
$params = array(
'driver' => 'postgres',
'hostname' => DB_HOSTNAME,
'username' => DB_USERNAME,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'port' => DB_PORT,
);
} else {
require_once __DIR__.'/../schemas/sqlite.php';
$params = array(
'driver' => 'sqlite',
'filename' => DB_FILENAME,
);
}
return $params;
}
","getStatementHandler()->withLogging();
if (DEBUG_MODE) {
$db->getStatementHandler()->withStopWatch();
}
if ($db->schema('\Miniflux\Schema')->check(Schema\VERSION)) {
return $db;
} else {
$errors = $db->getLogMessages();
$nb_errors = count($errors);
$last_error = isset($errors[$nb_errors - 1]) ? $errors[$nb_errors - 1] : 'Unknown SQL error';
throw new RuntimeException('Unable to migrate the database schema: '.$last_error);
}
}
function get_connection_parameters()
{
if (DB_DRIVER === 'postgres') {
require_once __DIR__.'/../schemas/postgres.php';
$params = array(
'driver' => 'postgres',
'hostname' => DB_HOSTNAME,
'username' => DB_USERNAME,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'port' => DB_PORT,
);
} else {
require_once __DIR__.'/../schemas/sqlite.php';
$params = array(
'driver' => 'sqlite',
'filename' => DB_FILENAME,
);
}
return $params;
}
"
Add stub to search for players remotely,"#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from db import commit_db_item
from db.player import Player
from db.team import Team
from utils.player_finder import PlayerFinder
def migrate_players(plr_src_file=None):
if not plr_src_file:
plr_src_file = os.path.join(
os.path.dirname(__file__), 'nhl_players.json')
migration_data = json.load(open(plr_src_file))
for player_id in sorted(migration_data.keys())[:]:
last_name = migration_data[player_id]['last_name']
first_name = migration_data[player_id]['first_name']
position = migration_data[player_id]['position']
alternate_last_names = migration_data[player_id].get(
'alternate_last_names', None)
alternate_first_names = migration_data[player_id].get(
'alternate_first_names', None)
alternate_positions = migration_data[player_id].get(
'alternate_positions', None)
plr = Player(
player_id, last_name, first_name, position,
alternate_last_names=alternate_last_names,
alternate_first_names=alternate_first_names,
alternate_positions=alternate_positions
)
print(""Working on %s"" % plr)
commit_db_item(plr)
def search_players(src_type):
plr_f = PlayerFinder()
current_teams = Team.find_teams_for_season()
for team in sorted(current_teams)[:]:
team_players = plr_f.find_players_for_team(team, src_type)
print(sorted(team_players))
","#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from db import commit_db_item
from db.player import Player
def migrate_players(plr_src_file=None):
if not plr_src_file:
plr_src_file = os.path.join(
os.path.dirname(__file__), 'nhl_players.json')
migration_data = json.load(open(plr_src_file))
for player_id in sorted(migration_data.keys())[:]:
last_name = migration_data[player_id]['last_name']
first_name = migration_data[player_id]['first_name']
position = migration_data[player_id]['position']
alternate_last_names = migration_data[player_id].get(
'alternate_last_names', None)
alternate_first_names = migration_data[player_id].get(
'alternate_first_names', None)
alternate_positions = migration_data[player_id].get(
'alternate_positions', None)
plr = Player(
player_id, last_name, first_name, position,
alternate_last_names=alternate_last_names,
alternate_first_names=alternate_first_names,
alternate_positions=alternate_positions
)
print(""Working on %s"" % plr)
commit_db_item(plr)
"
Add ability to create question from toolbar,"# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _, get_language
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('add', 'question'):
params = ('?_popup&category=%s&language=%s' %
(category.pk, self.request.LANGUAGE_CODE))
menu.add_modal_item(_('Add question'), reverse('admin:aldryn_faq_question_add') + params)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)
","# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from aldryn_blog import request_post_identifier
from aldryn_faq import request_faq_category_identifier
@toolbar_pool.register
class FaqToolbar(CMSToolbar):
def populate(self):
def can(action, model):
perm = 'aldryn_faq.%(action)s_%(model)s' % {'action': action,
'model': model}
return self.request.user.has_perm(perm)
if self.is_current_app and (can('add', 'category')
or can('change', 'category')):
menu = self.toolbar.get_or_create_menu('faq-app', _('FAQ'))
if can('add', 'category'):
menu.add_modal_item(_('Add category'), reverse('admin:aldryn_faq_category_add') + '?_popup')
category = getattr(self.request, request_faq_category_identifier, None)
if category and can('change', 'category'):
url = reverse('admin:aldryn_faq_category_change', args=(category.pk,)) + '?_popup'
menu.add_modal_item(_('Edit category'), url, active=True)"
Print message when the bitbucket action is invalid,"notification = $notification;
$this->run();
}
public function run()
{
$action = $this->notification->header(""X-Event-Key"");
$validActions = [""pullrequest:created""];
// Only 'pullrequest:created' action is supported at this moment
if (!in_array($action, $validActions)) {
echo ""The action '{$action}' is not valid. Only 'pullrequest:created' action is supported at this moment.\n"";
return;
}
$reviewers = $this->notification[""pullrequest""][""reviewers""];
foreach ($reviewers as $reviewer) {
$this->notify($reviewer[""username""]);
}
}
/**
* Trigger the notification
*
* @param string $username
*/
public function notify($username)
{
$slackToken = SlackToken::where(""bitbucket_username"", $username)->first();
if ($slackToken) {
$user = User::where(""id"", $slackToken->user_id)->first();
$user->notify(new RequestReview($this->requestReviewData()));
}
}
public function requestReviewData()
{
return [
""username"" => $this->notification[""pullrequest""][""author""][""username""],
""title"" => $this->notification[""pullrequest""][""title""],
""url"" => $this->notification[""pullrequest""][""links""][""html""][""href""],
""repository"" => $this->notification[""pullrequest""][""destination""][""repository""][""name""],
""from"" => ""Bitbucket""
];
}
}","notification = $notification;
$this->run();
}
public function run()
{
$reviewers = $this->notification[""pullrequest""][""reviewers""];
foreach ($reviewers as $reviewer) {
$this->notify($reviewer[""username""]);
}
}
/**
* Trigger the notification
*
* @param string $username
*/
public function notify($username)
{
$slackToken = SlackToken::where(""bitbucket_username"", $username)->first();
if ($slackToken) {
$user = User::where(""id"", $slackToken->user_id)->first();
$user->notify(new RequestReview($this->requestReviewData()));
}
}
public function requestReviewData()
{
return [
""username"" => $this->notification[""pullrequest""][""author""][""username""],
""title"" => $this->notification[""pullrequest""][""title""],
""url"" => $this->notification[""pullrequest""][""links""][""html""][""href""],
""repository"" => $this->notification[""pullrequest""][""destination""][""repository""][""name""],
""from"" => ""Bitbucket""
];
}
}"
Add some slashes and other things.,"from django import http
from django.conf import settings
from django.views.generic import RedirectView, View
from requests_oauthlib import OAuth2Session
CLIENT_ID = settings.HELLO_BASE_CLIENT_ID
CLIENT_SECRET = settings.HELLO_BASE_CLIENT_SECRET
AUTHORIZATION_URL = 'https://localhost:8443/authorize/'
TOKEN_URL = 'https://localhost:8443/token/'
class PreAuthorizationView(RedirectView):
def get(self, request, *args, **kwargs):
# Redirect the user to Hello! Base ID using the appropriate
# URL with a few key OAuth paramters built in.
base = OAuth2Session(CLIENT_ID)
authorization_url, state = base.authorization_url(AUTHORIZATION_URL)
# State is used to prevent CSRF, so let's keep this for later.
request.session['oauth_state'] = state
request.session.modified = True
return http.HttpResponseRedirect(authorization_url)
class PostAuthorizationView(View):
def get(self, request, *args, **kwargs):
# We SHOULD be grabbing state from the session, maybe this'll
# work in production, but in development it's not. So... we're
# doing this. :(
base = OAuth2Session(CLIENT_ID, state=request.GET['state'])
token = base.fetch_token(
TOKEN_URL,
auth=(CLIENT_ID, CLIENT_SECRET),
authorization_response=request.build_absolute_uri()
)
","from django import http
from django.conf import settings
from django.views.generic import RedirectView, View
from requests_oauthlib import OAuth2Session
CLIENT_ID = settings.HELLO_BASE_CLIENT_ID
CLIENT_SECRET = settings.HELLO_BASE_CLIENT_SECRET
AUTHORIZATION_URL = 'https://localhost:8443/authorize'
TOKEN_URL = 'https://localhost:8443/token'
class PreAuthorizationView(RedirectView):
def get(self, request, *args, **kwargs):
# Redirect the user to Hello! Base ID using the appropriate
# URL with a few key OAuth paramters built in.
base = OAuth2Session(CLIENT_ID)
authorization_url, state = base.authorization_url(AUTHORIZATION_URL)
print(state)
# State is used to prevent CSRF, so let's keep this for later.
request.session['oauth_state'] = state
print(request.session['oauth_state'])
request.session.modified = True
return http.HttpResponseRedirect(authorization_url)
class PostAuthorizationView(View):
def get(self, request, *args, **kwargs):
# We SHOULD be grabbing state from the session, maybe this'll
# work in production, but in development it's not. So... we're
# doing this. :(
base = OAuth2Session(CLIENT_ID, state=request.GET['state'])
token = base.fetch_token(TOKEN_URL, client_secret=CLIENT_SECRET, authorization_response=self.request.build_absolute_uri())
print(token)
"
Fix url redirection to relative,"angular
.module('search', ['angucomplete-alt'])
.controller('SearchController', ['SEARCH_DATA', '$window', function (searchData, $window) {
var me = this;
me.docs = searchData.data;
me.src = searchData.src;
me.search = function (selected) {
var doc,
path,
url;
if (selected) {
doc = selected.originalObject;
me.src.forEach(function (src) {
if (src[src.length-1] === '/') {
src = src.slice(0, src.length-1);
}
if (doc.meta.path.indexOf(src) === 0) {
path = doc.meta.path.slice(src.length);
}
});
if (path !== undefined) {
url = path.split('/')
.concat([doc.meta.filename])
.filter(function (p) { return p; })
.join('_') + '.html#line' + doc.meta.lineno;
$window.location = url;
}
}
};
}]);
","angular
.module('search', ['angucomplete-alt'])
.controller('SearchController', ['SEARCH_DATA', '$window', function (searchData, $window) {
var me = this;
me.docs = searchData.data;
me.src = searchData.src;
me.search = function (selected) {
var doc,
path,
url;
if (selected) {
doc = selected.originalObject;
me.src.forEach(function (src) {
if (src[src.length-1] === '/') {
src = src.slice(0, src.length-1);
}
if (doc.meta.path.indexOf(src) === 0) {
path = doc.meta.path.slice(src.length);
}
});
if (path !== undefined) {
url = '/' + path.split('/')
.concat([doc.meta.filename])
.filter(function (p) { return p; })
.join('_') + '.html#line' + doc.meta.lineno;
$window.location = url;
}
}
};
}]);
"
Add io to message event definition,"'use strict';
const Debug = require('debug');
module.exports = function MessageEventDefinition(eventDefinition) {
const {id, type, cancelActivity} = eventDefinition;
const debug = Debug(`bpmn-engine:${type.toLowerCase()}`);
const io = eventDefinition.getIO();
const eventState = {};
const definitionApi = {
id,
type,
cancelActivity,
activate
};
return definitionApi;
function activate(parentApi, parentExecutionContext, emit) {
let deactivated;
debug(`<${id}> listen for messages`);
const activityApi = {
type,
cancelActivity,
deactivate,
getState,
execute,
stop
};
parentExecutionContext.addStateSource(getState);
parentExecutionContext.addIoSource(io);
parentExecutionContext.addStopFn(stop);
emit('enter', activityApi, parentExecutionContext);
return activityApi;
function execute() {
if (deactivated) return;
eventState.waiting = true;
parentExecutionContext.postpone((err, ...args) => {
eventState.waiting = undefined;
if (err) return emit('error', err);
io.setResult(...args);
debug(`<${id}> message received`);
emit('end', activityApi, parentExecutionContext);
emit('leave', activityApi, parentExecutionContext);
});
emit('wait', activityApi, parentExecutionContext);
}
function getState() {
return Object.assign({}, eventState);
}
function stop() {
deactivate();
}
function deactivate() {
deactivated = true;
}
}
};
","'use strict';
const Debug = require('debug');
module.exports = function MessageEventDefinition(eventDefinition) {
const id = eventDefinition.id;
const type = eventDefinition.type;
const debug = Debug(`bpmn-engine:${type.toLowerCase()}`);
const cancelActivity = eventDefinition.cancelActivity;
const eventState = {};
const definitionApi = {
id,
type,
cancelActivity,
activate
};
return definitionApi;
function activate(parentApi, parentExecutionContext, emit) {
let deactivated;
debug(`<${id}> listen for messages`);
const activityApi = {
type,
cancelActivity,
deactivate,
getState,
execute,
stop
};
parentExecutionContext.addStateSource(getState);
parentExecutionContext.addStopFn(stop);
emit('enter', activityApi, parentExecutionContext);
return activityApi;
function execute() {
if (deactivated) return;
eventState.waiting = true;
parentExecutionContext.postpone((err, ...args) => {
eventState.waiting = undefined;
if (err) return emit('error', err);
parentExecutionContext.assignResult(...args);
debug(`<${id}> message received`);
emit('end', activityApi, parentExecutionContext);
emit('leave', activityApi, parentExecutionContext);
});
emit('wait', activityApi, parentExecutionContext);
}
function getState() {
return Object.assign({}, eventState);
}
function stop() {
deactivate();
}
function deactivate() {
deactivated = true;
}
}
};
"
Fix api demo link to link to html version," 'developers',
'title' => 'Entwickler',
],
[
'routeKey' => 'specification',
'title' => 'Spezifikation',
],
[
'routeKey' => 'api.v1.system.show',
'params' => [1, 'format' => 'html'],
'title' => 'Demo',
],
[
'title' => 'Kontakt',
'url' => 'https://oparl.org/kontakt/',
],
];
public function compose(View $view)
{
return $view->with('sections', $this->getSections());
}
protected function getSections()
{
$sections = $this->sections;
$currentRouteName = \Route::currentRouteName();
foreach ($sections as $key => $section) {
if (isset($section['routeKey']) && starts_with($currentRouteName, $section['routeKey'])) {
$sections[$key]['current'] = true;
break;
}
}
if (\Auth::check()) {
array_unshift($sections, [
'routeKey' => 'admin.dashboard',
'title' => '',
]);
}
return $sections;
}
}
"," 'developers',
'title' => 'Entwickler',
],
[
'routeKey' => 'specification',
'title' => 'Spezifikation',
],
[
'routeKey' => 'api.v1.system.show',
'params' => [1],
'title' => 'Demo',
],
[
'title' => 'Kontakt',
'url' => 'https://oparl.org/kontakt/',
],
];
public function compose(View $view)
{
return $view->with('sections', $this->getSections());
}
protected function getSections()
{
$sections = $this->sections;
$currentRouteName = \Route::currentRouteName();
foreach ($sections as $key => $section) {
if (isset($section['routeKey']) && starts_with($currentRouteName, $section['routeKey'])) {
$sections[$key]['current'] = true;
break;
}
}
if (\Auth::check()) {
array_unshift($sections, [
'routeKey' => 'admin.dashboard',
'title' => '',
]);
}
return $sections;
}
}
"
Fix all courses being displayed for all lecturers,"(function() {
'use strict';
angular
.module('lecturer')
.factory('coursesFactory', coursesFactory);
/* @ngInject */
function coursesFactory(coursesService, lecturerFactory) {
var selectedCourse = {};
var Course = false;
var service = {
getCourses: getCourses,
addCourse: addCourse,
setCourse: setCourse,
getCourse: getCourse
};
return service;
function getCourses(onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.query({lecturer: lecturerFactory.getLecturerId()}, onSuccess);
}
function addCourse(course, onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.save(course, onSuccess);
}
function setCourse(course) {
selectedCourse = course;
}
function getCourse() {
return selectedCourse;
}
}
})();
","(function() {
'use strict';
angular
.module('lecturer')
.factory('coursesFactory', coursesFactory);
/* @ngInject */
function coursesFactory(coursesService) {
var selectedCourse = {};
var Course = false;
var service = {
getCourses: getCourses,
addCourse: addCourse,
setCourse: setCourse,
getCourse: getCourse
};
return service;
function getCourses(onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.query({lecturer: 1}, onSuccess);
}
function addCourse(course, onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.save(course, onSuccess);
}
function setCourse(course) {
selectedCourse = course;
}
function getCourse() {
return selectedCourse;
}
}
})();"
Change of plans: let's have a separate method,"kernel->shutdown();
$this->kernel->boot();
}
/**
* This method checks that the EM is still valid and avoids rebooting the kernel.
* The EM is cleared every time to avoid inconsistencies.
* If something broke the EntityManager, the connection is closed, to avoid further usage.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function doRequest($request)
{
/** @var AbstractManagerRegistry $doctrine */
$doctrine = $this->getContainer()->get('doctrine');
/** @var EntityManagerInterface $manager */
foreach ($doctrine->getManagers() as $manager) {
$this->handleManager($manager);
}
return $this->kernel->handle($request);
}
/**
* @param EntityManagerInterface $manager
*/
private function handleManager(EntityManagerInterface $manager)
{
$manager->clear();
if ( ! $manager->isOpen()) {
$manager->getConnection()->close();
}
}
}
","getContainer()->get('doctrine');
/** @var EntityManagerInterface $manager */
foreach ($doctrine->getManagers() as $manager) {
$this->handleManager($manager);
}
return $this->kernel->handle($request);
}
/**
* @param EntityManagerInterface $manager
*/
private function handleManager(EntityManagerInterface $manager)
{
$manager->clear();
if ( ! $manager->isOpen()) {
$manager->getConnection()->close();
}
}
}
"
Fix errors related to Immutable.js,"var ActionTypes = require('../constants').ActionTypes
var Dispatcher = require('../dispatcher');
var Immutable = require('immutable');
var Store = require('./es6_store');
var _dispatchToken
var _product = Immutable.Map({});
class ProductStore extends Store {
constructor() {
super()
_dispatchToken = Dispatcher.register((action) => {
switch (action.type) {
case ActionTypes.INTRODUCTION_RECEIVE:
_product.set('is_member', true);
this.emitChange()
break
case ActionTypes.PRODUCT_RECEIVE:
_product = Immutable.Map(action.product);
this.emitChange()
break
}
})
}
getName() {
return _product.get('name');
}
getProduct() {
// return the raw JS object for now
return (_product && _product.toJS()) || {};
}
getSlug() {
return _product.get('slug');
}
getCoreTeamIds() {
var coreTeam = _product.get('core_team');
return (coreTeam && coreTeam.toJS()) || []
}
isCoreTeam(currentUser) {
if (currentUser) {
return this.getCoreTeamIds().indexOf(currentUser.id) > -1 ||
currentUser.is_staff ||
currentUser.staff ||
currentUser.is_core;
}
return false;
}
}
var store = new ProductStore()
var dataTag = document.getElementById('ProductStore')
if (dataTag) {
Dispatcher.dispatch({
type: ActionTypes.PRODUCT_RECEIVE,
product: JSON.parse(dataTag.innerHTML)
})
}
module.exports = store
","var ActionTypes = require('../constants').ActionTypes
var Dispatcher = require('../dispatcher');
var Immutable = require('immutable');
var Store = require('./es6_store');
var _dispatchToken
var _product = Immutable.Map({});
class ProductStore extends Store {
constructor() {
super()
_dispatchToken = Dispatcher.register((action) => {
switch (action.type) {
case ActionTypes.INTRODUCTION_RECEIVE:
_product.set('is_member', true);
this.emitChange()
break
case ActionTypes.PRODUCT_RECEIVE:
_product = Immutable.Map(action.product);
this.emitChange()
break
}
})
}
getName() {
return _product.get('name');
}
getProduct() {
// return the raw JS object for now
return _product.toJS();
}
getSlug() {
return _product.get('slug');
}
getCoreTeamIds() {
return _product.get('core_team').toJS() || []
}
isCoreTeam(currentUser) {
if (currentUser) {
return this.getCoreTeamIds().indexOf(currentUser.id) > -1 ||
currentUser.is_staff ||
currentUser.staff ||
currentUser.is_core;
}
return false;
}
}
var store = new ProductStore()
var dataTag = document.getElementById('ProductStore')
if (dataTag) {
Dispatcher.dispatch({
type: ActionTypes.PRODUCT_RECEIVE,
product: JSON.parse(dataTag.innerHTML)
})
}
module.exports = store
"
Use correct driver class as the old one is being deprecated.,"package net.sourceforge.javydreamercsw.mysql.driver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import org.netbeans.api.db.explorer.DatabaseException;
import org.netbeans.api.db.explorer.JDBCDriver;
import org.netbeans.api.db.explorer.JDBCDriverManager;
import org.openide.modules.ModuleInstall;
import org.openide.util.Exceptions;
import org.openide.windows.WindowManager;
public class Installer extends ModuleInstall {
public static final String DRIVER = ""com.mysql.cj.jdbc.Driver"";
private static final Logger LOG
= Logger.getLogger(Installer.class.getCanonicalName());
@Override
public void restored() {
WindowManager.getDefault().invokeWhenUIReady(() -> {
//Check drivers
if (JDBCDriverManager.getDefault().getDrivers(DRIVER).length == 0) {
try {
LOG.fine(""Registering MySQL driver!"");
JDBCDriverManager.getDefault().addDriver(
JDBCDriver.create(""mysql"", ""MySQL"",
DRIVER,
new URL[]{new URL(
""nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar"")}));
} catch (DatabaseException | MalformedURLException ex) {
Exceptions.printStackTrace(ex);
}
}
});
}
}
","package net.sourceforge.javydreamercsw.mysql.driver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import org.netbeans.api.db.explorer.DatabaseException;
import org.netbeans.api.db.explorer.JDBCDriver;
import org.netbeans.api.db.explorer.JDBCDriverManager;
import org.openide.modules.ModuleInstall;
import org.openide.util.Exceptions;
import org.openide.windows.WindowManager;
public class Installer extends ModuleInstall {
public static final String mysqlDriverClass = ""com.mysql.jdbc.Driver"";
private static final Logger LOG =
Logger.getLogger(Installer.class.getCanonicalName());
@Override
public void restored() {
WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
@Override
public void run() {
//Check drivers
if (JDBCDriverManager.getDefault().getDrivers(mysqlDriverClass).length == 0) {
try {
LOG.fine(""Registering MySQL driver!"");
JDBCDriverManager.getDefault().addDriver(
JDBCDriver.create(""mysql"", ""MySQL"",
mysqlDriverClass,
new URL[]{new URL(
""nbinst:/modules/ext/com.validation.manager.mysql/1/mysql/mysql-connector-java.jar"")}));
} catch (DatabaseException ex) {
Exceptions.printStackTrace(ex);
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
}
}
}
});
}
}
"
Add language code in the command,"from optparse import make_option
from datetime import datetime as dt
from django.core.management.base import BaseCommand
from django.utils import translation
from django.conf import settings
from dateutil.relativedelta import *
from silver.documents_generator import DocumentsGenerator
from silver.models import Subscription
class Command(BaseCommand):
help = 'Generates the billing documents (Invoices, Proformas).'
option_list = BaseCommand.option_list + (
make_option('--subscription',
action='store',
dest='subscription_id',
type=""int""),
make_option('--date',
action='store',
dest='billing_date',
type=""string""),
)
def handle(self, *args, **options):
translation.activate('en-us')
date = None
if options['billing_date']:
billing_date = dt.strptime(options['billing_date'], '%Y-%m-%d').date()
docs_generator = DocumentsGenerator()
if options['subscription_id']:
try:
subscription = Subscription.objects.get(id=options['subscription_id'])
docs_generator.generate(subscription=subscription)
self.stdout.write('Done. You can have a Club-Mate now. :)')
except Subscription.DoesNotExist:
msg = 'The subscription with the provided id does not exist.'
self.stdout.write(msg)
else:
docs_generator.generate(billing_date=billing_date)
self.stdout.write('Done. You can have a Club-Mate now. :)')
","from optparse import make_option
from datetime import datetime as dt
from django.core.management.base import BaseCommand
from django.utils import translation
from django.conf import settings
from dateutil.relativedelta import *
from silver.documents_generator import DocumentsGenerator
from silver.models import Subscription
class Command(BaseCommand):
help = 'Generates the billing documents (Invoices, Proformas).'
option_list = BaseCommand.option_list + (
make_option('--subscription',
action='store',
dest='subscription_id',
type=""int""),
make_option('--date',
action='store',
dest='billing_date',
type=""string""),
)
def handle(self, *args, **options):
translation.activate(settings.LANGUAGE_CODE)
date = None
if options['billing_date']:
billing_date = dt.strptime(options['billing_date'], '%Y-%m-%d').date()
docs_generator = DocumentsGenerator()
if options['subscription_id']:
try:
subscription = Subscription.objects.get(id=options['subscription_id'])
docs_generator.generate(subscription=subscription)
self.stdout.write('Done. You can have a Club-Mate now. :)')
except Subscription.DoesNotExist:
msg = 'The subscription with the provided id does not exist.'
self.stdout.write(msg)
else:
docs_generator.generate(billing_date=billing_date)
self.stdout.write('Done. You can have a Club-Mate now. :)')
"
"Move the logic for ""for"" to the end of the constructor so that
everything else is set first.","message = $_GET['message'];
}
if (isset($options['continueURL'])) {
$this->continueURL = $options['continueURL'];
}
if (isset($options['saveType'])) {
$this->saveType = $options['saveType'];
}
if (isset($options['ajaxredirect'])) {
$this->ajaxRedirect = $options['ajaxredirect'];
}
if (isset($_GET['for'])) {
switch ($_GET['for']) {
case ""login"":
$this->message = ""You have been logged in! Please click continue if you are not redirected."";
$options['continueURL'] = Wub_Controller::$url . ""home"";
break;
case ""accounts"":
if ($this->saveType == 'create') {
$this->message = ""Thank you for registering. You will now need to log in."";
$this->continueURL = Wub_Controller::$url . ""login"";
} else {
$this->message = ""You account has been saved!"";
}
break;
default:
break;
}
}
}
}","message = ""You have been logged in! Please click continue if you are not redirected."";
$options['continueURL'] = Wub_Controller::$url . ""home"";
break;
case ""accounts"":
if ($this->saveType == 'create') {
$this->message = ""Thank you for registering. You will now need to log in."";
$this->continueURL = Wub_Controller::$url . ""login"";
} else {
$this->message = ""You account has been saved!"";
}
break;
default:
break;
}
}
if (isset($_GET['message'])) {
$this->message = $_GET['message'];
}
if (isset($options['continueURL'])) {
$this->continueURL = $options['continueURL'];
}
if (isset($options['saveType'])) {
$this->saveType = $options['saveType'];
}
if (isset($options['ajaxredirect'])) {
$this->ajaxRedirect = $options['ajaxredirect'];
}
}
}"
Use ChromeHeadless for karma tests,"'use strict';
const os = require('os');
module.exports = (config) => {
config.set({
basePath: '',
frameworks: [
'jasmine-jquery',
'jasmine'
],
files: [
// fixtures
{
pattern: './fixture/**/*',
included: false
},
// testHelper
'../../test/client/initHelper.js',
// specs
'../../test/client/specsContext.js'
],
exclude: [],
preprocessors: {
'../../test/client/specsContext.js': ['webpack']
},
reporters: [
'kjhtml',
'mocha',
'coverage'
],
coverageReporter: {
type: 'lcov',
dir: '../../target/coverage/client'
},
webpack: {
module: {
rules: [
{
test: /\.js$/,
use: 'isparta-loader',
exclude: /(test|node_modules)\//
},
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules\//
},
{
test: /\.scss$/,
use: [
'css-loader',
{
loader: 'sass-loader',
options: {outputStyle: 'compressed'}
}
]
}
]
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
browserConsoleLogOptions: {
level: 'log',
terminal: true
},
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: false,
concurrency: os.cpus().length
});
};
","'use strict';
const os = require('os');
module.exports = (config) => {
config.set({
basePath: '',
frameworks: [
'jasmine-jquery',
'jasmine'
],
files: [
// fixtures
{
pattern: './fixture/**/*',
included: false
},
// testHelper
'../../test/client/initHelper.js',
// specs
'../../test/client/specsContext.js'
],
exclude: [],
preprocessors: {
'../../test/client/specsContext.js': ['webpack']
},
reporters: [
'kjhtml',
'mocha',
'coverage'
],
coverageReporter: {
type: 'lcov',
dir: '../../target/coverage/client'
},
webpack: {
module: {
rules: [
{
test: /\.js$/,
use: 'isparta-loader',
exclude: /(test|node_modules)\//
},
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules\//
},
{
test: /\.scss$/,
use: [
'css-loader',
{
loader: 'sass-loader',
options: {outputStyle: 'compressed'}
}
]
}
]
}
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
browserConsoleLogOptions: {
level: 'log',
terminal: true
},
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: os.cpus().length
});
};
"
"Remove version when client is used
Upon further reading of the Google Maps docs when using a client ID and not specifying a version it will by default supply the Release version. Since its not necessary to provide a version number I removed that bit of code.","/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-g-map',
included: function(app, parentAddon) {
var target = (parentAddon || app);
target.import('vendor/addons.css');
},
contentFor: function(type, config) {
var content = '';
if (type === 'head') {
var src = '//maps.googleapis.com/maps/api/js';
var gMapConfig = config['g-map'] || {};
var params = [];
var key = gMapConfig.key;
if (key) {
params.push('key=' + encodeURIComponent(key));
}
var version = gMapConfig.version;
if (version) {
params.push('v=' + encodeURIComponent(version));
}
var client = gMapConfig.client;
if (client) {
params.push('client=' + encodeURIComponent(client));
}
var libraries = gMapConfig.libraries;
if (libraries && libraries.length) {
params.push('libraries=' + encodeURIComponent(libraries.join(',')));
}
var language = gMapConfig.language;
if (language) {
params.push('language=' + encodeURIComponent(language));
}
var protocol = gMapConfig.protocol;
if (protocol) {
src = protocol + ':' + src;
}
src += '?' + params.join('&');
content = '';
var exclude = gMapConfig.exclude;
if (exclude) {
content = ''
}
}
return content;
}
};
","/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-g-map',
included: function(app, parentAddon) {
var target = (parentAddon || app);
target.import('vendor/addons.css');
},
contentFor: function(type, config) {
var content = '';
if (type === 'head') {
var src = '//maps.googleapis.com/maps/api/js';
var gMapConfig = config['g-map'] || {};
var params = [];
var key = gMapConfig.key;
if (key) {
params.push('key=' + encodeURIComponent(key));
}
var version = gMapConfig.version;
if (version) {
params.push('v=' + encodeURIComponent(version));
}
var client = gMapConfig.client;
if (client) {
params.push('client=' + encodeURIComponent(client));
if (!version) {
params.push('v=3');
}
}
var libraries = gMapConfig.libraries;
if (libraries && libraries.length) {
params.push('libraries=' + encodeURIComponent(libraries.join(',')));
}
var language = gMapConfig.language;
if (language) {
params.push('language=' + encodeURIComponent(language));
}
var protocol = gMapConfig.protocol;
if (protocol) {
src = protocol + ':' + src;
}
src += '?' + params.join('&');
content = '';
var exclude = gMapConfig.exclude;
if (exclude) {
content = ''
}
}
return content;
}
};
"
"Move socket creation to method
Signed-off-by: Bram Devries ","
import merge from 'deepmerge';
import {SOCKET_DISPATCH, SOCKET_RECEIVE_ACTION, SOCKET_CONNECT, SOCKET_DISCONNECT} from './constants';
const defaultOptions = {
actions: [],
};
export default function socketMiddleware(options = defaultOptions) {
let socket;
options = merge(defaultOptions, options);
// Determines wether or not an action should be emitted to the socket server.
const shouldEmit = action => {
return socket // We need a socket server
&& !action.emitted // If the action was emitted before, we will not emit it again.
&& options.actions.includes(action.type); // The action type needs to be included
};
const setupSocket = (url) => {
socket = options.resolveSocket(url);
socket.on(SOCKET_RECEIVE_ACTION, action => {
store.dispatch({...action, emitted: true});
});
socket.on('disconnect', () => {
store.dispatch({
type: SOCKET_DISCONNECT,
});
});
socket.on('reconnect', () => {
store.dispatch({
type: SOCKET_CONNECT,
});
});
return socket;
}
return store => next => action => {
// We first execute the action locally
const result = next(action);
// We want to intercept a couple of actions related to sockets.
switch (action.type) {
case SOCKET_CONNECT:
if (!socket) {
socket = setupSocket(action.url);
}
break;
}
// If the action should be emitted we do so.
if (shouldEmit(action)) {
socket.emit(SOCKET_DISPATCH, action);
}
// Return the result to the next middleware.
return result;
};
}
","
import merge from 'deepmerge';
import {SOCKET_DISPATCH, SOCKET_RECEIVE_ACTION, SOCKET_CONNECT, SOCKET_DISCONNECT} from './constants';
const defaultOptions = {
actions: [],
};
export default function socketMiddleware(options = defaultOptions) {
let socket;
options = merge(defaultOptions, options);
// Determines wether or not an action should be emitted to the socket server.
const shouldEmit = action => {
return socket // We need a socket server
&& !action.emitted // If the action was emitted before, we will not emit it again.
&& options.actions.includes(action.type); // The action type needs to be included
};
return store => next => action => {
// We first execute the action locally
const result = next(action);
// We want to intercept a couple of actions related to sockets.
switch (action.type) {
case SOCKET_CONNECT:
if (!socket) {
socket = options.resolveSocket(action.url);
socket.on(SOCKET_RECEIVE_ACTION, action => {
store.dispatch({...action, emitted: true});
});
socket.on('disconnect', () => {
store.dispatch({
type: SOCKET_DISCONNECT,
});
});
socket.on('reconnect', () => {
store.dispatch({
type: SOCKET_CONNECT,
});
});
}
break;
}
// If the action should be emitted we do so.
if (shouldEmit(action)) {
socket.emit(SOCKET_DISPATCH, action);
}
// Return the result to the next middleware.
return result;
};
}
"
"Fix another fatal error from SimpleTest refactoring.
git-svn-id: 25f448894bd6eb0cddf10ded73b4f5a7ea3203f3@1696 48356398-32a2-884e-a903-53898d9a118a","_context =& $context;
}
public function expectContext($key, $value) {
$this->_expected_context[$key] = $value;
}
public function expectContextAt($step, $key, $value) {
$this->_expected_context_at[$step][$key] = $value;
}
public function send($v1, $v2) {
// test for context
$context = SimpleTest::getContext();
$test = $context->getTest();
// compat
if (empty($this->_mock)) {
$mock = $this;
} else {
$mock = $this->_mock;
}
foreach ($this->_expected_context as $key => $value) {
$test->assertEqual($value, $this->_context->get($key));
}
$step = $mock->getCallCount('send');
if (isset($this->_expected_context_at[$step])) {
foreach ($this->_expected_context_at[$step] as $key => $value) {
$test->assertEqual($value, $this->_context->get($key));
}
}
// boilerplate mock code, does not have return value or references
$args = func_get_args();
$mock->invoke('send', $args);
}
}
","_context =& $context;
}
public function expectContext($key, $value) {
$this->_expected_context[$key] = $value;
}
public function expectContextAt($step, $key, $value) {
$this->_expected_context_at[$step][$key] = $value;
}
public function send($v1, $v2) {
// test for context
$context = SimpleTest::getContext();
$test = $context->getTest();
// compat
if (empty($this->_mock)) {
$mock = $this;
} else {
$mock = $this->_mock;
}
foreach ($this->_expected_context as $key => $value) {
$test->assertEqual($value, $this->_context->get($key));
}
$step = $mock->getCallCount('send');
if (isset($this->_expected_context_at[$step])) {
foreach ($this->_expected_context_at[$step] as $key => $value) {
$test->assertEqual($value, $this->_context->get($key));
}
}
// boilerplate mock code, does not have return value or references
$args = func_get_args();
$mock->_invoke('send', $args);
}
}
"
[FIX] Fix wrong member in getter.,"package de.apileipzig.mediahandbook.entity;
/**
* Default implementation of a Branch.
*
* @author cpieloth
*/
public class DefaultBranch implements Branch {
private int id;
private int parentId;
private String internalType;
private String internalKey;
private String name;
private String description;
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
@Override
public int getParentId() {
return parentId;
}
@Override
public void setParentId(int id) {
this.parentId = id;
}
@Override
public String getInternalType() {
return internalType;
}
@Override
public void setInternalType(String internalType) {
this.internalType = internalType;
}
@Override
public String getInternalKey() {
return internalKey;
}
@Override
public void setInternalKey(String internalKey) {
this.internalKey = internalKey;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String street) {
this.description = street;
}
@Override
public String toString() {
return """" + this.getClass().getSimpleName() + ""[id="" + id + "",name="" + name + "",...]"";
}
}
","package de.apileipzig.mediahandbook.entity;
/**
* Default implementation of a Branch.
*
* @author cpieloth
*/
public class DefaultBranch implements Branch {
private int id;
private int parentId;
private String internalType;
private String internalKey;
private String name;
private String description;
@Override
public int getId() {
return id;
}
@Override
public void setId(int id) {
this.id = id;
}
@Override
public int getParentId() {
return parentId;
}
@Override
public void setParentId(int id) {
this.parentId = id;
}
@Override
public String getInternalType() {
return name;
}
@Override
public void setInternalType(String internalType) {
this.internalType = internalType;
}
@Override
public String getInternalKey() {
return internalKey;
}
@Override
public void setInternalKey(String internalKey) {
this.internalKey = internalKey;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String street) {
this.description = street;
}
@Override
public String toString() {
return """" + this.getClass().getSimpleName() + ""[id="" + id + "",name="" + name + "",...]"";
}
}
"
Increase and fuzz sleep time,"from listing import Listing, session
from scraper import Scraper
from slack import Slack
from random import randint
import sys
import traceback
import time
slack = Slack()
def scrape():
results = 0
duplicates = 0
for result in Scraper().results():
results += 1
listing = Listing(result).process()
if listing is None:
duplicates += 1
continue
session.add(listing)
session.commit()
if listing.transit_stop is None:
continue
post = (
':house: {0} :moneybag: ${1} :round_pushpin: {2} :station: {3} '
':link: <{4}>'
.format(listing.name, listing.price, listing.area,
listing.transit_stop, listing.link)
)
slack.post(post)
print(""%s: processed %s listings, %s were duplicates."" %
(time.ctime(), results, duplicates)
)
if __name__ == '__main__':
while True:
try:
scrape()
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
print(""Error:"", sys.exc_info()[0])
traceback.print_exc()
time.sleep(14400 + randint(-600, 600))
","from listing import Listing, session
from scraper import Scraper
from slack import Slack
import sys
import traceback
import time
slack = Slack()
def scrape():
results = 0
duplicates = 0
for result in Scraper().results():
results += 1
listing = Listing(result).process()
if listing is None:
duplicates += 1
continue
session.add(listing)
session.commit()
if listing.transit_stop is None:
continue
post = (
':house: {0} :moneybag: ${1} :round_pushpin: {2} :station: {3} '
':link: <{4}>'
.format(listing.name, listing.price, listing.area,
listing.transit_stop, listing.link)
)
slack.post(post)
print(""%s: processed %s listings, %s were duplicates."" %
(time.ctime(), results, duplicates)
)
if __name__ == '__main__':
while True:
try:
scrape()
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
print(""Error:"", sys.exc_info()[0])
traceback.print_exc()
time.sleep(3600)
"
Fix date format: should be 24-hour.,"#!/usr/bin/env node
// Dependencies
var moment = require(""moment"");
var sugar = require(""sugar"");
var colors = require(""colors"");
var exec = require(""child_process"").exec;
// Check for CLI argument
process.argv.splice(0, 2);
if (process.argv.length > 0) {
// Attempt to parse the date
var date = process.argv.join("" "");
var parsedDate = Date.create(date);
if (parsedDate != ""Invalid Date""){
// Date could be parsed, parse the date to git date format
var dateString = moment(parsedDate).format(""ddd MMM DD HH:mm:ss YYYY ZZ"");
// Actually modify the dates
var command = ""GIT_COMMITTER_DATE=\"""" + dateString + ""\"" git commit --amend --date=\"""" + dateString + ""\"" --no-edit"";
exec(command, function(err, stdout, stderr){
if (err){
console.log(""fatal: Could not change the previous commit"");
} else {
// Dates modified, notify the user
console.log(""\nModified previous commit:\n\tAUTHOR_DATE "" + colors.grey(dateString) + ""\n\tCOMMITTER_DATE "" + colors.grey(dateString) + ""\n\nCommand executed:\n\t"" + colors.bgWhite.black(command) + ""\n"");
}
});
} else {
console.log(""fatal: Could not parse \"""" + date + ""\"" into a valid date"");
}
} else {
// Show notice
console.log(""fatal: No date string given"");
}
","#!/usr/bin/env node
// Dependencies
var moment = require(""moment"");
var sugar = require(""sugar"");
var colors = require(""colors"");
var exec = require(""child_process"").exec;
// Check for CLI argument
process.argv.splice(0, 2);
if (process.argv.length > 0) {
// Attempt to parse the date
var date = process.argv.join("" "");
var parsedDate = Date.create(date);
if (parsedDate != ""Invalid Date""){
// Date could be parsed, parse the date to git date format
var dateString = moment(parsedDate).format(""ddd MMM DD hh:mm:ss YYYY ZZ"");
// Actually modify the dates
var command = ""GIT_COMMITTER_DATE=\"""" + dateString + ""\"" git commit --amend --date=\"""" + dateString + ""\"" --no-edit"";
exec(command, function(err, stdout, stderr){
if (err){
console.log(""fatal: Could not change the previous commit"");
} else {
// Dates modified, notify the user
console.log(""\nModified previous commit:\n\tAUTHOR_DATE "" + colors.grey(dateString) + ""\n\tCOMMITTER_DATE "" + colors.grey(dateString) + ""\n\nCommand executed:\n\t"" + colors.bgWhite.black(command) + ""\n"");
}
});
} else {
console.log(""fatal: Could not parse \"""" + date + ""\"" into a valid date"");
}
} else {
// Show notice
console.log(""fatal: No date string given"");
}
"
Replace array by counter value in throttler,"'use strict';
const { Transform } = require('stream');
module.exports = class Throttler extends Transform {
constructor (pgstream, ...args) {
super(...args);
this.pgstream = pgstream;
this.sampleLength = global.settings.copy_from_maximum_slow_input_speed_interval || 15;
this.minimunBytesPerSecondThershold = global.settings.copy_from_minimum_input_speed || 0;
this.byteCount = 0;
this.bytesPerSecondHistory = [];
this._interval = setInterval(this._updateMetrics.bind(this), 1000);
}
_updateMetrics () {
this.bytesPerSecondHistory.push(this.byteCount);
this.byteCount = 0;
if (this.bytesPerSecondHistory.length > this.sampleLength) {
this.bytesPerSecondHistory.shift();
}
let doesNotReachThreshold = 0;
for (const bytesPerSecond of this.bytesPerSecondHistory) {
if (bytesPerSecond <= this.minimunBytesPerSecondThershold) {
doesNotReachThreshold += 1;
}
}
if (doesNotReachThreshold >= this.sampleLength) {
clearInterval(this._interval);
this.pgstream.emit('error', new Error('Connection closed by server: input data too slow'));
}
}
_transform (chunk, encoding, callback) {
this.byteCount += chunk.length;
callback(null, chunk);
}
_flush (callback) {
clearInterval(this._interval);
callback();
}
};
","'use strict';
const { Transform } = require('stream');
module.exports = class Throttler extends Transform {
constructor (pgstream, ...args) {
super(...args);
this.pgstream = pgstream;
this.sampleLength = global.settings.copy_from_maximum_slow_input_speed_interval || 15;
this.minimunBytesPerSecondThershold = global.settings.copy_from_minimum_input_speed || 0;
this.byteCount = 0;
this.bytesPerSecondHistory = [];
this._interval = setInterval(this._updateMetrics.bind(this), 1000);
}
_updateMetrics () {
this.bytesPerSecondHistory.push(this.byteCount);
this.byteCount = 0;
if (this.bytesPerSecondHistory.length > this.sampleLength) {
this.bytesPerSecondHistory.shift();
}
const doesNotReachThreshold = [];
for (const bytesPerSecond of this.bytesPerSecondHistory) {
if (bytesPerSecond <= this.minimunBytesPerSecondThershold) {
doesNotReachThreshold.push(true);
}
}
if (doesNotReachThreshold.length >= this.sampleLength) {
clearInterval(this._interval);
this.pgstream.emit('error', new Error('Connection closed by server: input data too slow'));
}
}
_transform (chunk, encoding, callback) {
this.byteCount += chunk.length;
callback(null, chunk);
}
_flush (callback) {
clearInterval(this._interval);
callback();
}
};
"
Fix permission problems for running scripts via sh binary,"package x1125io.initdlight;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
final String TAG = ""initdlight"";
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
for (String file: context.getFilesDir().list()) {
ProcessRunner pr = new ProcessRunner();
String fullFilePath = context.getFilesDir().toString() + ""/"" + file;
int exitCode = pr.Run(new String[] { ""su"", ""-c"", ""sh "" + fullFilePath });
if (exitCode == 0) {
Log.d(TAG, ""started "" + file);
} else {
Log.d(TAG, String.format(
""error starting %s; exit code: %d; stdout: %s; stderr: %s"",
file,
exitCode,
pr.getStdout(),
pr.getStderr()
));
}
}
}
}
}","package x1125io.initdlight;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BootReceiver extends BroadcastReceiver {
final String TAG = ""initdlight"";
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
for (String file: context.getFilesDir().list()) {
ProcessRunner pr = new ProcessRunner();
String fullFilePath = context.getFilesDir().toString() + ""/"" + file;
int exitCode = pr.Run(new String[] { ""su"", ""-c"", ""sh"", fullFilePath });
if (exitCode == 0) {
Log.d(TAG, ""started "" + file);
} else {
Log.d(TAG, String.format(
""error starting %s; exit code: %d; stdout: %s; stderr: %s"",
file,
exitCode,
pr.getStdout(),
pr.getStderr()
));
}
}
}
}
}"
"Disable NPM publish, do it manually to cope with failures.","module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.loadNpmTasks('grunt-release');
grunt.initConfig({
jshint: {
all: [""lib/*.js"", ""test/*.js"", ""Gruntfile.js""],
options: {
jshintrc: "".jshintrc""
}
},
watch: {
all: {
files: ['lib/**.js', 'test/**'],
tasks: ['test']
}
},
mochacli: {
options: {
files: ['test/*_test.js'],
},
spec: {
options: {
reporter: 'spec',
slow: 2000,
timeout: 10000
}
}
},
release: {
options: {
npm: false
}
}
});
grunt.registerTask('default', ['test']);
grunt.registerTask('build', ['jshint']);
grunt.registerTask('package', ['build', 'release']);
grunt.registerTask('test', ['build', 'mochacli']);
};
","module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.loadNpmTasks('grunt-release');
grunt.initConfig({
jshint: {
all: [""lib/*.js"", ""test/*.js"", ""Gruntfile.js""],
options: {
jshintrc: "".jshintrc""
}
},
watch: {
all: {
files: ['lib/**.js', 'test/**'],
tasks: ['test']
}
},
mochacli: {
options: {
files: ['test/*_test.js'],
},
spec: {
options: {
reporter: 'spec',
slow: 2000,
timeout: 10000
}
}
}
});
grunt.registerTask('default', ['test']);
grunt.registerTask('build', ['jshint']);
grunt.registerTask('package', ['build', 'release']);
grunt.registerTask('test', ['build', 'mochacli']);
};
"
Fix Netflix in light of the new scope selection system,"import urlparse
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
request_token_url = 'http://api.netflix.com/oauth/request_token'
authorize_url = 'https://api-user.netflix.com/oauth/login'
access_token_url = 'http://api.netflix.com/oauth/access_token'
api_domains = ['api-public.netflix.com', 'api.netflix.com']
available_permissions = [
(None, 'read and manage your queue'),
]
https = False
signature_type = SIGNATURE_TYPE_QUERY
def get_authorize_params(self, *args, **kwargs):
params = super(Netflix, self).get_authorize_params(*args, **kwargs)
params['oauth_consumer_key'] = self.client_id
return params
def get_user_id(self, key):
r = self.api(key, self.api_domains[0], u'/users/current',
params={'output': 'json'})
redirect = r.json[u'resource'][u'link'][u'href']
parts = urlparse.urlparse(redirect)
r = self.api(key, parts.netloc, parts.path,
params={'output': 'json'})
return r.json[u'user'][u'user_id']
","import urlparse
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
request_token_url = 'http://api.netflix.com/oauth/request_token'
authorize_url = 'https://api-user.netflix.com/oauth/login'
access_token_url = 'http://api.netflix.com/oauth/access_token'
api_domains = ['api-public.netflix.com', 'api.netflix.com']
available_permissions = [
(None, 'read and manage your queue'),
]
https = False
signature_type = SIGNATURE_TYPE_QUERY
def get_authorize_params(self, redirect_uri):
params = super(Netflix, self).get_authorize_params(redirect_uri)
params['oauth_consumer_key'] = self.client_id
return params
def get_user_id(self, key):
r = self.api(key, self.api_domains[0], u'/users/current',
params={'output': 'json'})
redirect = r.json[u'resource'][u'link'][u'href']
parts = urlparse.urlparse(redirect)
r = self.api(key, parts.netloc, parts.path,
params={'output': 'json'})
return r.json[u'user'][u'user_id']
"
"Reset email form value on success
closes #3663
- Set value of email input as nil string","/* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
actions: {
submit: function () {
var self = this,
data = self.getProperties('email');
this.toggleProperty('submitting');
this.validate({ format: false }).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'POST',
data: {
passwordreset: [{
email: data.email
}]
}
}).then(function (resp) {
self.toggleProperty('submitting');
self.notifications.showSuccess('Please check your email for instructions.', {delayed: true});
self.set('email', '');
self.transitionToRoute('signin');
}).catch(function (resp) {
self.toggleProperty('submitting');
self.notifications.showAPIError(resp, { defaultErrorText: 'There was a problem logging in, please try again.' });
});
}).catch(function (errors) {
self.toggleProperty('submitting');
self.notifications.showErrors(errors);
});
}
}
});
export default ForgottenController;
","/* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
actions: {
submit: function () {
var self = this,
data = self.getProperties('email');
this.toggleProperty('submitting');
this.validate({ format: false }).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'POST',
data: {
passwordreset: [{
email: data.email
}]
}
}).then(function (resp) {
self.toggleProperty('submitting');
self.notifications.showSuccess('Please check your email for instructions.', {delayed: true});
self.transitionToRoute('signin');
}).catch(function (resp) {
self.toggleProperty('submitting');
self.notifications.showAPIError(resp, { defaultErrorText: 'There was a problem logging in, please try again.' });
});
}).catch(function (errors) {
self.toggleProperty('submitting');
self.notifications.showErrors(errors);
});
}
}
});
export default ForgottenController;
"
Move cache key out of base class,"import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs[""match_key""]
@property
def _validators(self):
return [(""match_id_validator"", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({""404"": ""%s match not found"" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
CACHE_KEY_FORMAT = ""apiv2_match_controller_{}"" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchController, self).__init__(*args, **kw)
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
","import json
import webapp2
from controllers.api.api_base_controller import ApiBaseController
from helpers.model_to_dict import ModelToDict
from models.match import Match
class ApiMatchControllerBase(ApiBaseController):
CACHE_KEY_FORMAT = ""apiv2_match_controller_{}"" # (match_key)
CACHE_VERSION = 2
CACHE_HEADER_LENGTH = 60 * 60
def __init__(self, *args, **kw):
super(ApiMatchControllerBase, self).__init__(*args, **kw)
self.match_key = self.request.route_kwargs[""match_key""]
self._partial_cache_key = self.CACHE_KEY_FORMAT.format(self.match_key)
@property
def _validators(self):
return [(""match_id_validator"", self.match_key)]
def _set_match(self, match_key):
self.match = Match.get_by_id(match_key)
if self.match is None:
self._errors = json.dumps({""404"": ""%s match not found"" % self.match_key})
self.abort(404)
class ApiMatchController(ApiMatchControllerBase):
def _track_call(self, match_key):
self._track_call_defer('match', match_key)
def _render(self, match_key):
self._set_match(match_key)
match_dict = ModelToDict.matchConverter(self.match)
return json.dumps(match_dict, ensure_ascii=True)
"
"CA-40618: Change path to the supplemental pack
Signed-off-by: Javier Alvarez-Valle ","import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
""""""Base Exception class for all transfer plugin errors.""""""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
""""""Base Exception class for all transfer plugin errors.""""""
def __init__(self, *args):
Exception.__init__(self, *args)
def run2(command):
run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait for the process to return
out, err = [ e.splitlines() for e in run.communicate() ]
return run.returncode, out, err
drac_path='/opt/dell/srvadmin/sbin/racadm'
def DRAC( power_on_ip, user, password):
if( not os.path.exists(drac_path)):
raise DRAC_NO_SUPP_PACK()
cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password)
retcode,out,err=run2(cmd)
if(len(err)==0):
return str(True)
else:
raise DRAC_POWERON_FAILED()
def main():
if len(sys.argv)<3:
exit(0)
ip=sys.argv[1]
user=sys.argv[2]
password=sys.argv[3]
print DRAC(ip,user,password)
if __name__ == ""__main__"":
main()","import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
""""""Base Exception class for all transfer plugin errors.""""""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
""""""Base Exception class for all transfer plugin errors.""""""
def __init__(self, *args):
Exception.__init__(self, *args)
def run2(command):
run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait for the process to return
out, err = [ e.splitlines() for e in run.communicate() ]
return run.returncode, out, err
drac_path='/usr/sbin/racadm'
def DRAC( power_on_ip, user, password):
if( not os.path.exists(drac_path)):
raise DRAC_NO_SUPP_PACK()
cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password)
retcode,out,err=run2(cmd)
if(len(err)==0):
return str(True)
else:
raise DRAC_POWERON_FAILED()
def main():
if len(sys.argv)<3:
exit(0)
ip=sys.argv[1]
user=sys.argv[2]
password=sys.argv[3]
print DRAC(ip,user,password)
if __name__ == ""__main__"":
main()"
Throw an exception if registerRepositoryMappings() returns bad arrays,"
*/
trait StorageTrait
{
/**
* Return a list of entities to map to repositories.
*
*
* return [
* 'alias' => [\Entity\Class::class => \Repository\Class::class],
* ];
*
*
* @return array
*/
protected function registerRepositoryMappings()
{
return [];
}
/**
* Call this in register method.
*
* @internal
*/
final protected function extendRepositoryMapping()
{
$app = $this->getContainer();
$app['storage'] = $app->share(
$app->extend(
'storage',
function ($entityManager) use ($app) {
foreach ($this->registerRepositoryMappings() as $alias => $map) {
if (Arr::isIndexedArray($map)) {
// Usually caused by [entity, repo] instead of [entity => repo]
throw new \RuntimeException(sprintf('Repository mapping for %s `%s` is not an associative array.', __CLASS__, $alias));
}
$app['storage.repositories'] += $map;
$app['storage.metadata']->setDefaultAlias($app['schema.prefix'] . $alias, key($map));
$entityManager->setRepository(key($map), current($map));
}
return $entityManager;
}
)
);
}
/** @return Container */
abstract protected function getContainer();
}
","
*/
trait StorageTrait
{
/**
* Return a list of entities to map to repositories.
*
*
* return [
* 'alias' => [\Entity\Class\Name => \Repository\Class\Name],
* ];
*
*
* @return array
*/
protected function registerRepositoryMappings()
{
return [];
}
/**
* Call this in register method.
*
* @internal
*/
final protected function extendRepositoryMapping()
{
$app = $this->getContainer();
$app['storage'] = $app->share(
$app->extend(
'storage',
function ($entityManager) use ($app) {
foreach ($this->registerRepositoryMappings() as $alias => $map) {
$app['storage.repositories'] += $map;
$app['storage.metadata']->setDefaultAlias($app['schema.prefix'] . $alias, key($map));
$entityManager->setRepository(key($map), current($map));
}
return $entityManager;
}
)
);
}
/** @return Container */
abstract protected function getContainer();
}
"
:checkered_flag: Fix version parsing of file(1),"
let spawn = require('./spawn')
let self = {
platform: function () {
return process.platform
},
arch: function () {
return process.arch
},
process_type: function () {
return process.type || 'browser'
},
get_version: function (key) {
return process.versions[key]
},
/**
* Get platform in the format used by the itch.io API
*/
itch_platform: function () {
switch (self.platform()) {
case 'darwin':
return 'osx'
case 'win32':
return 'windows'
case 'linux':
return 'linux'
}
},
cli_args: function () {
return process.argv
},
check_presence: async function (command, args, parser) {
if (typeof args === 'undefined') {
args = []
}
let stdout = ''
let stderr = ''
let spawn_opts = {
command,
args,
ontoken: (tok) => stdout += '\n' + tok,
onerrtoken: (tok) => stderr += '\n' + tok
}
let code = await spawn(spawn_opts)
if (code !== 0) {
throw new Error(`${command} exited with code ${code}\n${stdout}\n${stderr}`)
}
let parsed = null
if (parser) {
let matches = parser.exec(stdout + '\n' + stderr)
if (matches) {
parsed = matches[1]
}
}
return {code, stdout, stderr, parsed}
}
}
module.exports = self
","
let spawn = require('./spawn')
let self = {
platform: function () {
return process.platform
},
arch: function () {
return process.arch
},
process_type: function () {
return process.type || 'browser'
},
get_version: function (key) {
return process.versions[key]
},
/**
* Get platform in the format used by the itch.io API
*/
itch_platform: function () {
switch (self.platform()) {
case 'darwin':
return 'osx'
case 'win32':
return 'windows'
case 'linux':
return 'linux'
}
},
cli_args: function () {
return process.argv
},
check_presence: async function (command, args, parser) {
if (typeof args === 'undefined') {
args = []
}
let stdout = ''
let stderr = ''
let spawn_opts = {
command,
args,
ontoken: (tok) => stdout += tok,
onerrtoken: (tok) => stderr += tok
}
let code = await spawn(spawn_opts)
if (code !== 0) {
throw new Error(`${command} exited with code ${code}\n${stdout}\n${stderr}`)
}
let parsed = null
if (parser) {
let matches = parser.exec(stdout + '\n' + stderr)
if (matches) {
parsed = matches[1]
}
}
return {code, stdout, stderr, parsed}
}
}
module.exports = self
"
Fix main menu url reversing in admin,"from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import Library, Variable, Node
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(Node):
def __init__(self, content_type):
self.content_type = Variable(content_type)
def render(self, context):
try:
content_type = self.content_type.resolve(context)
except VariableDoesNotExist:
return ''
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
try:
return reverse(view_name)
except NoReverseMatch:
return ''
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requires a single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
","from django.template import Library, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist
from django.template.defaulttags import URLNode
from ..models import MenuItem
from ..settings import CONFIG
register = Library()
class MainMenuItemURLNode(URLNode):
def __init__(self, content_type):
self.content_type = Variable(content_type)
self.args = ()
self.kwargs = {}
self.asvar = False
self.legacy_view_name = True
def render(self, context):
try:
content_type = self.content_type.resolve(context)
opts = content_type.model_class()._meta
app_label = opts.app_label
module_name = opts.module_name
self.view_name = 'admin:%s_%s_changelist' % \
(app_label, module_name)
except VariableDoesNotExist:
return ''
return super(MainMenuItemURLNode, self).render(context)
@register.inclusion_tag('lemon/main_menu.html')
def main_menu():
queryset = MenuItem.objects.select_related('section', 'content_type')
queryset = queryset.order_by('section__position', 'position')
return {'menu_items': queryset, 'menu_links': CONFIG['MENU_LINKS']}
@register.tag
def main_menu_item_url(parser, token):
try:
tag_name, content_type = token.split_contents()
except ValueError:
raise TemplateSyntaxError(
'%r tag requiresa single argument' % token.contents.split()[0]
)
return MainMenuItemURLNode(content_type)
"
RPB: Fix errors with placeholder columns,"(function () {
var Ext = window.Ext4 || window.Ext;
Ext.define('Rally.apps.roadmapplanningboard.PlaceholderColumn', {
extend: 'Ext.Component',
alias: 'widget.cardboardplaceholdercolumn',
requires: [
'Rally.ui.cardboard.ColumnHeader'
],
afterRender: function () {
this.drawHeader();
this.fireEvent('ready', this);
},
drawHeader: function () {
var config = {
renderTo: Ext.get(this.headerCell)
};
Ext.fly(this.headerCell).addCls('planning-column');
this.columnHeader = Ext.widget(Ext.merge(config, this.columnHeaderConfig));
// Add a couple of containers to match the structure of the timeframe planning column header
this.columnHeader.add({
xtype: 'container',
tpl: [
''
],
data: {}
});
this.columnHeader.add({
xtype: 'container',
tpl: [
''
],
data: {}
});
},
getColumnHeader: function() {
return this.columnHeader;
},
getColumnHeaderCell: function () {
return Ext.get(this.headerCell);
},
getContentCell: function () {
return Ext.get(this.contentCell);
},
getCards: function () {
return [];
},
findCardInfo: function () {
return null;
},
isMatchingRecord: function () {
return false;
},
refresh: function () {
return null;
},
getHeaderTitle: function () {
return this.columnHeader.down('#headerTitle');
}
});
})();
","(function () {
var Ext = window.Ext4 || window.Ext;
Ext.define('Rally.apps.roadmapplanningboard.PlaceholderColumn', {
extend: 'Ext.Component',
alias: 'widget.cardboardplaceholdercolumn',
requires: [
'Rally.ui.cardboard.ColumnHeader'
],
afterRender: function () {
this.drawHeader();
this.fireEvent('ready', this);
},
drawHeader: function () {
var config = {
renderTo: Ext.get(this.headerCell)
};
Ext.fly(this.headerCell).addCls('planning-column');
this.columnHeader = Ext.widget(Ext.merge(config, this.columnHeaderConfig));
// Add a couple of containers to match the structure of the timeframe planning column header
this.columnHeader.add({
xtype: 'container',
tpl: [
''
],
data: {}
});
this.columnHeader.add({
xtype: 'container',
tpl: [
''
],
data: {}
});
},
getColumnHeader: function() {
return this.columnHeader;
},
getColumnHeaderCell: function () {
return Ext.get(this.headerCell);
},
getContentCell: function () {
return Ext.get(this.contentCell);
},
getCards: function () {
return [];
},
getHeaderTitle: function () {
return this.columnHeader.down('#headerTitle');
}
});
})();
"
Clear date range picker if no start and end date given,"$(function () {
'use strict';
$.fn.getDateRangeSeparator = function () {
return ' to ';
};
$.fn.createBootstrap3DateRangePicker = function(
range_labels, separator, startdate, enddate
) {
var now = moment();
var ranges = {};
ranges[range_labels.last_7_days] = [
moment().subtract('7', 'days').startOf('days')
];
ranges[range_labels.last_month] = [
moment().subtract('1', 'months').startOf('month'),
moment().subtract('1', 'months').endOf('month')
];
ranges[range_labels.last_30_days] = [
moment().subtract('30', 'days').startOf('days')
];
var config = {
showDropdowns: true,
ranges: ranges,
locale: {
format: 'YYYY-MM-DD',
separator: separator
}
};
var hasStartAndEndDate = !_.isEmpty(startdate) && !_.isEmpty(enddate);
if (hasStartAndEndDate) {
config.startDate = new Date(startdate);
config.endDate = new Date(enddate);
}
$(this).daterangepicker(config);
if (! hasStartAndEndDate){
$(this).val("""");
}
};
$.fn.createBootstrap3DefaultDateRangePicker = function () {
this.createBootstrap3DateRangePicker(
{
last_7_days: 'Last 7 Days',
last_month: 'Last Month',
last_30_days: 'Last 30 Days'
},
this.getDateRangeSeparator()
);
};
});
","$(function () {
'use strict';
$.fn.getDateRangeSeparator = function () {
return ' to ';
};
$.fn.createBootstrap3DateRangePicker = function(
range_labels, separator, startdate, enddate
) {
var now = moment();
var ranges = {};
ranges[range_labels.last_7_days] = [
moment().subtract('7', 'days').startOf('days')
];
ranges[range_labels.last_month] = [
moment().subtract('1', 'months').startOf('month'),
moment().subtract('1', 'months').endOf('month')
];
ranges[range_labels.last_30_days] = [
moment().subtract('30', 'days').startOf('days')
];
var config = {
showDropdowns: true,
ranges: ranges,
locale: {
format: 'YYYY-MM-DD',
separator: separator
}
};
if (!_.isEmpty(startdate) && !_.isEmpty(enddate)) {
config.startDate = new Date(startdate);
config.endDate = new Date(enddate);
}
$(this).daterangepicker(config);
};
$.fn.createBootstrap3DefaultDateRangePicker = function () {
this.createBootstrap3DateRangePicker(
{
last_7_days: 'Last 7 Days',
last_month: 'Last Month',
last_30_days: 'Last 30 Days'
},
this.getDateRangeSeparator()
);
};
});
"
Add additional log statements when running cronjob,"command('gw2heroes:update')
->everyFiveMinutes()
->withoutOverlapping()
->sendOutputTo(storage_path('logs/last-update.log'));
$schedule->call(function() {
\Log::info('Start update...');
$updater = new Updater();
$updater->scheduleUpdate(ItemUpdater::class);
$updater->scheduleUpdate(SpecializationUpdater::class);
$updater->scheduleUpdate(TraitUpdater::class);
$updater->queueScheduledUpdates();
\Log::info('finished update...');
})->everyMinute();
}
}
","command('gw2heroes:update')
->everyFiveMinutes()
->withoutOverlapping()
->sendOutputTo(storage_path('logs/last-update.log'));
$schedule->call(function() {
$updater = new Updater();
$updater->scheduleUpdate(ItemUpdater::class);
$updater->scheduleUpdate(SpecializationUpdater::class);
$updater->scheduleUpdate(TraitUpdater::class);
$updater->queueScheduledUpdates();
})->everyMinute();
}
}
"
Add visual editor template to Peer Review on Provide Feedback step,"export default assignment => ([
{
title: 'Read the article',
content: 'Read the article and complete the Peer Review Exercise. This will help prepare you for providing feedback.',
status: 'not_yet_started',
trainings: [
{
title: 'Peer Review Exercise',
path: '../../../training/students/peer-review',
external: true
}
]
},
{
title: 'Provide feedback',
content: 'Assess your classmate\'s proposed contributions.',
status: 'peer_review_started',
trainings: [
{
title: 'Bibliography',
path: `${assignment.sandboxUrl}/Bibliograpy`,
external: true
},
{
title: 'Sandbox',
path: assignment.sandboxUrl,
external: true
},
{
title: 'Peer Review',
path: `${assignment.sandboxUrl}/${assignment.username}_Peer_Review?veaction=edit&preload=Template:Dashboard.wikiedu.org_peer_review`,
external: true
}
]
},
{
title: 'Mark as complete',
content: 'Let your classmate know that you\'ve reviewed their work by posting on their talk page so they can begin to incorporate your feedback into their draft.',
status: 'peer_review_completed',
trainings: [
{
title: 'Sandbox',
path: assignment.sandboxUrl,
external: true
}
]
}
]);
","export default assignment => ([
{
title: 'Read the article',
content: 'Read the article and complete the Peer Review Exercise. This will help prepare you for providing feedback.',
status: 'not_yet_started',
trainings: [
{
title: 'Peer Review Exercise',
path: '../../../training/students/peer-review',
external: true
}
]
},
{
title: 'Provide feedback',
content: 'Assess your classmate\'s proposed contributions.',
status: 'peer_review_started',
trainings: [
{
title: 'Bibliography',
path: `${assignment.sandboxUrl}/Bibliograpy`,
external: true
},
{
title: 'Sandbox',
path: assignment.sandboxUrl,
external: true
},
{
title: 'Peer Review',
path: `${assignment.sandboxUrl}/${assignment.username}_Peer_Review`,
external: true
}
]
},
{
title: 'Mark as complete',
content: 'Let your classmate know that you\'ve reviewed their work by posting on their talk page so they can begin to incorporate your feedback into their draft.',
status: 'peer_review_completed',
trainings: [
{
title: 'Sandbox',
path: assignment.sandboxUrl,
external: true
}
]
}
]);
"
Fix hometask disabled for admin,"angular
.module('app')
.controller('LessonModalController', LessonModalController);
function LessonModalController(self, $mdDialog, lesson, AuthService) {
if (lesson && lesson.startTime) {
lesson.startTime = new Date(lesson.startTime);
}
self.lesson = lesson;
self.cancel = cancel;
self.now = now;
self.isAdminLesson = isAdminLesson;
self.isTeacherLesson = isTeacherLesson;
self.isStudentLesson = isStudentLesson;
self.isPastLesson = isPastLesson;
self.canSave = canSave;
self.canEditHometask = canEditHometask;
AuthService.prepareAuthInfo().then(function () {
self.userRole = AuthService.role;
});
function isAdminLesson() {
return self.userRole === 'ADMIN';
}
function isTeacherLesson() {
return self.userRole === 'TEACHER';
}
function isStudentLesson() {
return self.userRole === 'STUDENT';
}
function isPastLesson() {
return self.lesson.startTime < now();
}
function canSave() {
return self.isAdminLesson() || (self.isTeacherLesson() && !self.isPastLesson());
}
function canEditHometask() {
return (!self.isPastLesson() && self.isTeacherLesson()) || self.isAdminLesson();
}
function now() {
return +new Date();
}
function cancel() {
$mdDialog.cancel();
}
}","angular
.module('app')
.controller('LessonModalController', LessonModalController);
function LessonModalController(self, $mdDialog, lesson, AuthService) {
if (lesson && lesson.startTime) {
lesson.startTime = new Date(lesson.startTime);
}
self.lesson = lesson;
self.cancel = cancel;
self.now = now;
self.isAdminLesson = isAdminLesson;
self.isTeacherLesson = isTeacherLesson;
self.isStudentLesson = isStudentLesson;
self.isPastLesson = isPastLesson;
self.canSave = canSave;
self.canEditHometask = canEditHometask;
AuthService.prepareAuthInfo().then(function () {
self.userRole = AuthService.role;
});
function isAdminLesson() {
return self.userRole === 'ADMIN';
}
function isTeacherLesson() {
return self.userRole === 'TEACHER';
}
function isStudentLesson() {
return self.userRole === 'STUDENT';
}
function isPastLesson() {
return self.lesson.startTime < now();
}
function canSave() {
return self.isAdminLesson() || (self.isTeacherLesson() && !self.isPastLesson());
}
function canEditHometask() {
return !self.isPastLesson() && (self.isTeacherLesson() || self.isAdminLesson());
}
function now() {
return +new Date();
}
function cancel() {
$mdDialog.cancel();
}
}"
Fix default render file page,"render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
public function dashboardAction() {
return $this->render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
public function uiGeneralAction() {
return $this->render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
public function uiIconsAction() {
return $this->render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
public function formAction() {
$form = $this->createForm(FormDemoModelType::class);
return $this->render('AvanzuAdminThemeBundle:Default:form.html.twig', [
'form' => $form->createView(),
]);
}
public function loginAction() {
return $this->render('AvanzuAdminThemeBundle:Default:login.html.twig');
}
}
","render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
public function uiGeneralAction() {
return $this->render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
public function uiIconsAction() {
return $this->render('AvanzuAdminThemeBundle:Default:index.html.twig');
}
public function formAction() {
$form = $this->createForm(FormDemoModelType::class);
return $this->render('AvanzuAdminThemeBundle:Default:form.html.twig', [
'form' => $form->createView(),
]);
}
public function loginAction() {
return $this->render('AvanzuAdminThemeBundle:Default:login.html.twig');
}
}
"
Fix bug to avoid duplicating topics,"from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
from redis import StrictRedis
import rq
def extract_topic_items(topic):
r = StrictRedis()
def topic_in_queue(topic):
q = rq.Queue('topics', connection=StrictRedis())
if any(job.kwargs.get('topic') for job in q.get_jobs()):
return True
else:
return False
db = MongoClient(MONGO_URI).get_default_database()
resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))
data = resp.json()
related_topics = data.get('related_topics')
items = data.get('items')
if resp.ok:
print('Inserting {} items for topic {}'.format(len(items)), topic)
res = db['items'].insert(items)
r.sadd('scraped_topics', topic)
for related_topic in related_topics:
if not topic_in_queue(related_topic) and not r.sismember('scraped_topics', related_topic):
print('Enqueuing related topic'.format(related_topic))
req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json()
print(""Rate limit! Going to sleep for 2 mins!"")
sleep(2 * 60)
print(""Wakey wakey eggs and bakey!"")
return res
else:
raise Exception('Something went wrong with topic {}. /api/explore/{} returned {}'.format(topic, topic, resp))
if __name__ == '__main__':
extract_topic_items('finance')
","from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
def extract_topic_items(topic):
db = MongoClient(MONGO_URI).get_default_database()
resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))
data = resp.json()
related_topics = data.get('related_topics')
items = data.get('items')
if items:
res = db['items'].insert(items)
db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic,
'is_scraped': True,
'datetime_scraped': datetime.utcnow(),
'queued': True}},
upsert=True)
for related_topic in related_topics:
req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json()
print(""Rate limit! Going to sleep for 2 mins!"")
sleep(2 * 60)
print(""Wakey wakey eggs and bakey!"")
return res
elif resp.ok and not items:
return
else:
raise Exception
if __name__ == '__main__':
extract_topic_items('finance')
"
"[WIP] BB-4325: Refactor block types, move expressions in vars from buildView to finishView
- added test for Options:setMultiple","options = new Options(['value' => 'test']);
}
public function testGet()
{
$this->assertEquals('test', $this->options->get('value'));
$this->setExpectedException('OutOfBoundsException');
$this->assertFalse($this->options->get('nameNotExist'));
}
public function testOffsetGet()
{
$this->assertEquals('test', $this->options->offsetGet('value'));
}
public function testOffsetSet()
{
$this->options->offsetSet('attribute', 'bar');
$this->assertSame(['value' => 'test', 'attribute' => 'bar'], $this->options->toArray());
}
public function testOffsetUnset()
{
$this->options->offsetUnset('value');
$this->assertSame([], $this->options->toArray());
}
public function testOffsetExists()
{
$this->assertTrue($this->options->offsetExists('value'));
$this->assertFalse($this->options->offsetExists('attr'));
}
public function testGetAll()
{
$this->assertSame(['value' => 'test'], $this->options->toArray());
}
public function testSetMultiple()
{
$values = ['value'=> 'test1', 'value2'=> 'test2', 'value3'=> 'test3'];
$this->options->setMultiple($values);
$this->assertEquals($values, $this->options->toArray());
}
}
","options = new Options(['value' => 'test']);
}
public function testGet()
{
$this->assertEquals('test', $this->options->get('value'));
$this->setExpectedException('OutOfBoundsException');
$this->assertFalse($this->options->get('nameNotExist'));
}
public function testOffsetGet()
{
$this->assertEquals('test', $this->options->offsetGet('value'));
}
public function testOffsetSet()
{
$this->options->offsetSet('attribute', 'bar');
$this->assertSame(['value' => 'test', 'attribute' => 'bar'], $this->options->toArray());
}
public function testOffsetUnset()
{
$this->options->offsetUnset('value');
$this->assertSame([], $this->options->toArray());
}
public function testOffsetExists()
{
$this->assertTrue($this->options->offsetExists('value'));
$this->assertFalse($this->options->offsetExists('attr'));
}
public function testGetAll()
{
$this->assertSame(['value' => 'test'], $this->options->toArray());
}
}
"
Add Salmon Run (S3) tab to schedule,"import React, { useState } from 'react';
import ScheduleContents from './ScheduleContents';
import ScheduleTabs from './ScheduleTabs';
const data = [
{
id: 'regular3',
ref: 'splatoon3/regular'.split('/'),
label: 'Regular'
},
{
id: 'challenge3',
ref: 'splatoon3/bankara_challenge'.split('/'),
label: 'Anarchy (Series)'
},
{
id: 'open3',
ref: 'splatoon3/bankara_open'.split('/'),
label: 'Anarchy (Open)'
},
{
id: 'salmon3',
ref: 'splatoon3/salmon'.split('/'),
label: 'Salmon Run'
},
{
id: 'regular2',
ref: 'splatoon2/regular'.split('/'),
label: 'Regular'
},
{
id: 'gachi2',
ref: 'splatoon2/gachi'.split('/'),
label: 'Ranked'
},
{
id: 'league2',
ref: 'splatoon2/league'.split('/'),
label: 'League'
},
{
id: 'salmon2',
ref: 'splatoon2/salmon'.split('/'),
label: 'Salmon Run'
}
];
export default function ScheduleDisplay () {
const [selected, setSelected] = useState('challenge3');
return (
<>
setSelected(id)}
selected={selected}
/>
>
);
}
ScheduleDisplay.propTypes = {
};
","import React, { useState } from 'react';
import ScheduleContents from './ScheduleContents';
import ScheduleTabs from './ScheduleTabs';
const data = [
{
id: 'regular3',
ref: 'splatoon3/regular'.split('/'),
label: 'Regular'
},
{
id: 'challenge3',
ref: 'splatoon3/bankara_challenge'.split('/'),
label: 'Anarchy (Series)'
},
{
id: 'open3',
ref: 'splatoon3/bankara_open'.split('/'),
label: 'Anarchy (Open)'
},
{
id: 'regular2',
ref: 'splatoon2/regular'.split('/'),
label: 'Regular'
},
{
id: 'gachi2',
ref: 'splatoon2/gachi'.split('/'),
label: 'Ranked'
},
{
id: 'league2',
ref: 'splatoon2/league'.split('/'),
label: 'League'
},
{
id: 'salmon2',
ref: 'splatoon2/salmon'.split('/'),
label: 'Salmon Run'
}
];
export default function ScheduleDisplay () {
const [selected, setSelected] = useState('challenge3');
return (
<>
setSelected(id)}
selected={selected}
/>
>
);
}
ScheduleDisplay.propTypes = {
};
"
Handle sensors / types that aren't in config file,"#!/usr/bin/env python
import mosquitto
import os
import time
import json
import random
import yaml
# Load config
stream = open(""config.yml"", 'r')
config = yaml.load(stream)
endpoint = os.environ['MQTT_ENDPOINT']
mypid = os.getpid()
client_uniq = ""sensor_mqtt_""+str(mypid)
mqttc = mosquitto.Mosquitto(client_uniq)
mqttc.username_pw_set(config['mqtt']['username'])
mqttc.connect(config['mqtt']['broker'], config['mqtt']['port'], 60, True)
def publish(sensor, reading_type, reading):
try:
sensor_config = config['sensors'][sensor][reading_type]
except KeyError:
print ""unknown sensor or reading type: "" + sensor + "" "" + reading_type
else:
if sensor_config:
data = {
'version':'1.0.0',
'datastreams': [
{
""id"" : sensor_config['publish_id'],
""datapoints"": [
{
""at"": time.ctime(),
""value"": reading
}
]
}
]
}
mqttc.publish(sensor_config['mqtt_endpoint'], json.dumps(data))
print ""message published: "" + sensor + "" "" + reading_type
while mqttc.loop() == 0:
publish(""R1"", ""RIVR"", random.randrange(0,255))
time.sleep(1)
pass
def cleanup():
print ""Ending and cleaning up""
mqttc.disconnect()","#!/usr/bin/env python
import mosquitto
import os
import time
import json
import random
import yaml
# Load config
stream = open(""config.yml"", 'r')
config = yaml.load(stream)
endpoint = os.environ['MQTT_ENDPOINT']
mypid = os.getpid()
client_uniq = ""sensor_mqtt_""+str(mypid)
mqttc = mosquitto.Mosquitto(client_uniq)
mqttc.username_pw_set(config['mqtt']['username'])
mqttc.connect(config['mqtt']['broker'], config['mqtt']['port'], 60, True)
def publish(sensor, reading_type, reading):
sensor_config = config['sensors'][sensor][reading_type]
if sensor_config:
data = {
'version':'1.0.0',
'datastreams': [
{
""id"" : sensor_config['publish_id'],
""datapoints"": [
{
""at"": time.ctime(),
""value"": reading
}
]
}
]
}
mqttc.publish(sensor_config['mqtt_endpoint'], json.dumps(data))
while mqttc.loop() == 0:
publish(""R1"", ""RIVR"", random.randrange(0,255))
print ""message published""
time.sleep(1)
pass
def cleanup():
print ""Ending and cleaning up""
mqttc.disconnect()"
Store inputted text in the local state,"'use strict';
import PfText from './PfText'
import PfTextInput from './PfTextInput'
import PfButton from './PfButton'
import Constants from './Constants'
import React, { Component } from 'react'
import {
StyleSheet,
Text,
TextInput,
View,
TouchableHighlight,
ActivityIndicator,
ScrollView
} from 'react-native';
export default class RequestCollectionScreen extends Component {
constructor(props) {
super(props);
this.state = {
name: ""Pfandgeber"",
address: """",
numBottles: """",
isAdding: false
}
}
render() {
const buttonOrSpinner = this.state.isAdding ?
( ) :
( );
return (
Find someone to collect your bottles and cans.
this.setState({name: text})} />
this.setState({address: text})} />
this.setState({numBottles: text})} />
{buttonOrSpinner}
);
}
}
const styles = StyleSheet.create({
vbox: {
flexDirection: 'column',
alignItems: 'stretch',
padding: 10,
marginTop: 20
},
});
","'use strict';
import PfText from './PfText'
import PfTextInput from './PfTextInput'
import PfButton from './PfButton'
import Constants from './Constants'
import React, { Component } from 'react'
import {
StyleSheet,
Text,
TextInput,
View,
TouchableHighlight,
ActivityIndicator,
ScrollView
} from 'react-native';
export default class RequestCollectionScreen extends Component {
constructor(props) {
super(props);
this.state = {
name: ""Pfandgeber"",
isAdding: false
}
}
render() {
const buttonOrSpinner = this.state.isAdding ?
( ) :
( );
return (
Find someone to collect your bottles and cans.
{buttonOrSpinner}
);
}
}
const styles = StyleSheet.create({
vbox: {
flexDirection: 'column',
alignItems: 'stretch',
padding: 10,
marginTop: 20
},
});
"
Validate Model function to allow permission,"from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, obj):
if self.has_role() and self.ids and obj:
if self.role in obj.role_accessors:
return get_value_from_accessor(obj, obj.role_accessors[self.role]) in self.ids
return True
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function):
return function(self.user)
return True
class UserBehaviour(RoleBehaviour):
role= 'user'
def has_role(self):
return True
def role_behaviour_factory():
return RoleBehaviour
class RoleBehaviourRegistry(object):
_registry = defaultdict(role_behaviour_factory)
def register(self, cls):
self._registry[cls.role] = cls
def get_role(self, role):
return self._registry[role]
registry = RoleBehaviourRegistry()","from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, obj):
if self.has_role() and self.ids and obj:
if self.role in obj.role_accessors:
return get_value_from_accessor(obj, obj.role_accessors[self.role]) in self.ids
return True
def can_apply_permission(self, obj, perm):
method = 'has_{}_{}_permission'.format(self.role, perm.name)
print method, hasattr(obj, method), getattr(obj, method), callable(getattr(obj, method))
if hasattr(obj, method):
function = getattr(obj, method)
if callable(function):
return function(self.user)
return True
class UserBehaviour(RoleBehaviour):
role= 'user'
def has_role(self):
return True
def role_behaviour_factory():
return RoleBehaviour
class RoleBehaviourRegistry(object):
_registry = defaultdict(role_behaviour_factory)
def register(self, cls):
self._registry[cls.role] = cls
def get_role(self, role):
return self._registry[role]
registry = RoleBehaviourRegistry()"
"Fix the docstring of create_plugin_base: Not internal, it's the main API","from types import SimpleNamespace
from django.db import models
__all__ = (""Region"", ""Template"", ""create_plugin_base"")
class Region(SimpleNamespace):
key = """"
title = ""unnamed""
inherited = False
class Template(SimpleNamespace):
key = """"
template_name = None
title = """"
regions = []
def create_plugin_base(content_base):
""""""
Create and return a base class for plugins
The base class contains a ``parent`` foreign key and the required
``region`` and ``ordering`` fields.
""""""
class PluginBase(models.Model):
parent = models.ForeignKey(
content_base,
related_name=""%(app_label)s_%(class)s_set"",
on_delete=models.CASCADE,
)
region = models.CharField(max_length=255)
ordering = models.IntegerField(default=0)
class Meta:
abstract = True
app_label = content_base._meta.app_label
ordering = [""ordering""]
def __str__(self):
return ""%s"" % (
self._meta.label,
self.region,
self.ordering,
self.pk,
)
@classmethod
def get_queryset(cls):
return cls.objects.all()
return PluginBase
","from types import SimpleNamespace
from django.db import models
__all__ = (""Region"", ""Template"", ""create_plugin_base"")
class Region(SimpleNamespace):
key = """"
title = ""unnamed""
inherited = False
class Template(SimpleNamespace):
key = """"
template_name = None
title = """"
regions = []
def create_plugin_base(content_base):
""""""
This is purely an internal method. Here, we create a base class for
the concrete content types, which are built in
``create_plugin``.
The three fields added to build a concrete content type class/model
are ``parent``, ``region`` and ``ordering``.
""""""
class PluginBase(models.Model):
parent = models.ForeignKey(
content_base,
related_name=""%(app_label)s_%(class)s_set"",
on_delete=models.CASCADE,
)
region = models.CharField(max_length=255)
ordering = models.IntegerField(default=0)
class Meta:
abstract = True
app_label = content_base._meta.app_label
ordering = [""ordering""]
def __str__(self):
return ""%s"" % (
self._meta.label,
self.region,
self.ordering,
self.pk,
)
@classmethod
def get_queryset(cls):
return cls.objects.all()
return PluginBase
"
Fix linting errors for schema tests.,"var assert = require('assert');
var schema = require('../../libs/schema');
var configSchema = require('../../schemas/config');
var goodConfig = require('../data/goodConfig');
describe('libs/schema.js', () => {
describe('validateBody()', () => {
it('should validate the json body of a post request', (done) => {
let mockReq = {body: goodConfig};
let mockRes = {};
let validate = schema.validateBody(configSchema);
validate(mockReq, mockRes, () => { done(); });
});
it('should throw 400 error on invalid json', (done) => {
let mockReq = {body: {}};
let mockRes = {
status: (code) => {
// Check for the 400 code
assert.equal(code, 400);
return {
send: (err) => {
// Verify an error was returned
assert.ok(err);
done();
}
};
}
};
let validate = schema.validateBody(configSchema);
validate(mockReq, mockRes, () => {
// Fail if next() is called
assert.ok(false);
});
});
});
});
","var assert = require('assert');
var schema = require('../../libs/schema');
var configSchema = require('../../schemas/config');
var goodConfig = require('../data/goodConfig');
describe('libs/schema.js', () => {
describe('validateBody()', () => {
it('should validate the json body of a post request', (done) => {
let mockReq = {body: goodConfig};
let mockRes = {};
let validate = schema.validateBody(configSchema);
validate(mockReq, mockRes, () => { done(); });
});
it('should throw 400 error on invalid json', (done) => {
let mockReq = {body: {}};
let mockRes = {
status: (code) => {
// Check for the 400 code
assert.equal(code, 400);
return {
send: (err) => {
// Verify an error was returned
assert.ok(err);
done();
}
}
}
}
let validate = schema.validateBody(configSchema);
validate(mockReq, mockRes, () => {
// Fail if next() is called
assert.ok(false);
});
});
});
});
"
Fix login controller to go to correct route.,"Application.Controllers.controller('login',
[""$scope"", ""$state"", ""User"", ""alertService"", ""mcapi"", ""Nav"", ""pubsub"", ""model.projects"", ""projectFiles"",
function ($scope, $state, User, alertService, mcapi, Nav, pubsub, projects, projectFiles) {
$scope.login = function () {
mcapi('/user/%/apikey', $scope.email, $scope.password)
.success(function (u) {
User.setAuthenticated(true, u);
pubsub.send(""tags.change"");
Nav.setActiveNav('home');
projects.clear();
projectFiles.clear();
projects.getList().then(function(projects) {
$state.go('projects.project.home', {id: projects[0].id});
});
})
.error(function (data) {
alertService.sendMessage(data.error);
}).put({password: $scope.password});
};
$scope.cancel = function () {
$state.transitionTo('home');
};
}]);
","Application.Controllers.controller('login',
[""$scope"", ""$state"", ""User"", ""alertService"", ""mcapi"", ""Nav"", ""pubsub"", ""model.projects"", ""projectFiles"",
function ($scope, $state, User, alertService, mcapi, Nav, pubsub, projects, projectFiles) {
$scope.login = function () {
mcapi('/user/%/apikey', $scope.email, $scope.password)
.success(function (u) {
User.setAuthenticated(true, u);
pubsub.send(""tags.change"");
Nav.setActiveNav('home');
projects.clear();
projectFiles.clear();
projects.getList().then(function(projects) {
$state.go('projects.project.overview', {id: projects[0].id});
});
})
.error(function (data) {
alertService.sendMessage(data.error);
}).put({password: $scope.password});
};
$scope.cancel = function () {
$state.transitionTo('home');
};
}]);
"
Add debian-squeeze support for os detection.,"from fabric.api import run, quiet
from braid import succeeds, cacheInEnvironment
@cacheInEnvironment
def distroName():
""""""
Get the name of the distro.
""""""
with quiet():
lsb = run('/usr/bin/lsb_release --id --short', warn_only=True)
if lsb.succeeded:
return lsb.lower()
distros = [
('centos', '/etc/centos-release'),
('fedora', '/etc/fedora-release'),
('rhel', '/etc/redhat-release'),
('debian', '/etc/debian_version'),
]
for distro, sentinel in distros:
if succeeds('/usr/bin/test -f {}'.format(sentinel)):
return distro
def distroFamily():
""""""
Get the family of the distro.
@returns: C{'debian'} or C{'fedora'}
""""""
families = {
'debian': ['debian', 'ubuntu'],
'fedora': ['fedora', 'centos', 'rhel'],
}
distro = distroName()
for family, members in families.iteritems():
if distro in members:
return family
return 'other'
@cacheInEnvironment
def arch():
""""""
Get the architechture of the machine.
""""""
return run('/bin/uname --machine')
@cacheInEnvironment
def isRoot():
""""""
Check if the current user is root.
""""""
return run('id -u') == '0'
__all__ = ['distroName', 'distroFamily', 'arch']
","from fabric.api import run, quiet
from braid import succeeds, cacheInEnvironment
@cacheInEnvironment
def distroName():
""""""
Get the name of the distro.
""""""
with quiet():
lsb = run('/usr/bin/lsb_release --id --short', warn_only=True)
if lsb.succeeded:
return lsb.lower()
distros = [
('centos', '/etc/centos-release'),
('fedora', '/etc/fedora-release'),
]
for distro, sentinel in distros:
if succeeds('/usr/bin/test -f {}'.format(sentinel)):
return distro
def distroFamily():
""""""
Get the family of the distro.
@returns: C{'debian'} or C{'fedora'}
""""""
families = {
'debian': ['debian', 'ubuntu'],
'fedora': ['fedora', 'centos', 'rhel'],
}
distro = distroName()
for family, members in families.iteritems():
if distro in members:
return family
return 'other'
@cacheInEnvironment
def arch():
""""""
Get the architechture of the machine.
""""""
return run('/bin/uname --machine')
@cacheInEnvironment
def isRoot():
""""""
Check if the current user is root.
""""""
return run('id -u') == '0'
__all__ = ['distroName', 'distroFamily', 'arch']
"
Sort on col num if line num are equal,"package com.sleekbyte.tailor.output;
public class ViolationMessage implements Comparable {
private final String filePath;
private final int lineNumber;
private final int columnNumber;
private final String classification;
private final String violationMessage;
public ViolationMessage(String filePath, int lineNumber, int columnNumber, String classification, String violationMessage) {
this.filePath = filePath;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.classification = classification;
this.violationMessage = violationMessage;
}
@Override
public int compareTo(final ViolationMessage message) {
int ret = this.lineNumber - message.lineNumber;
if (ret == 0) {
ret = this.columnNumber - message.columnNumber;
}
return ret;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ViolationMessage)) {
return false;
}
ViolationMessage message;
message = (ViolationMessage)o;
return this.filePath == message.filePath
&& this.lineNumber == message.lineNumber
&& this.columnNumber == message.columnNumber
&& this.classification == message.classification
&& this.violationMessage == message.violationMessage;
}
public String toString() {
if (columnNumber == 0) {
return String.format(""%s:%d: %s: %s"", this.filePath, this.lineNumber, this.classification, this.violationMessage);
}
return String.format(""%s:%d:%d: %s: %s"", this.filePath, this.lineNumber, this.columnNumber, this.classification, this.violationMessage);
}
}
","package com.sleekbyte.tailor.output;
public class ViolationMessage implements Comparable {
private final String filePath;
private final int lineNumber;
private final int columnNumber;
private final String classification;
private final String violationMessage;
public ViolationMessage(String filePath, int lineNumber, int columnNumber, String classification, String violationMessage) {
this.filePath = filePath;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.classification = classification;
this.violationMessage = violationMessage;
}
@Override
public int compareTo(final ViolationMessage message) {
int ret = this.lineNumber - message.lineNumber;
return ret;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ViolationMessage)) {
return false;
}
ViolationMessage message;
message = (ViolationMessage)o;
return this.filePath == message.filePath
&& this.lineNumber == message.lineNumber
&& this.columnNumber == message.columnNumber
&& this.classification == message.classification
&& this.violationMessage == message.violationMessage;
}
public String toString() {
if (columnNumber == 0) {
return String.format(""%s:%d: %s: %s"", this.filePath, this.lineNumber, this.classification, this.violationMessage);
}
return String.format(""%s:%d:%d: %s: %s"", this.filePath, this.lineNumber, this.columnNumber, this.classification, this.violationMessage);
}
}
"
Use HTTPS for communication with qrserver API,"'use strict';
var request = require('request');
var randomstring = require('randomstring');
var db = require('./database');
var handlers = {
showIntro: function(req, res) {
res.render('intro');
},
createGame: function(req, res) {
var gameKey = randomstring.generate(5);
db.getOrCreate(gameKey, function() {
res.redirect('/p/' + gameKey);
});
},
observeGame: function(req, res) {
var joinURL = req.protocol + '://' + req.headers.host + '/c/' + req.params.game;
res.render('master', {
joinURL: joinURL,
game: req.params.game
});
},
playGame: function(req, res) {
res.render('client', {game: req.params.game});
},
showQR: function(req, res) {
var joinURL = req.protocol + '://' + req.headers.host + '/c/' + req.params.game;
var url = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' + joinURL;
request.get(url).pipe(res);
},
bind: function(app) {
app.get('/', handlers.showIntro);
app.get('/p/', handlers.createGame);
app.get('/p/:game', handlers.observeGame);
app.get('/c/:game', handlers.playGame);
app.get('/qr/:game', handlers.showQR);
}
};
module.exports = handlers;
","'use strict';
var request = require('request');
var randomstring = require('randomstring');
var db = require('./database');
var handlers = {
showIntro: function(req, res) {
res.render('intro');
},
createGame: function(req, res) {
var gameKey = randomstring.generate(5);
db.getOrCreate(gameKey, function() {
res.redirect('/p/' + gameKey);
});
},
observeGame: function(req, res) {
var joinURL = req.protocol + '://' + req.headers.host + '/c/' + req.params.game;
res.render('master', {
joinURL: joinURL,
game: req.params.game
});
},
playGame: function(req, res) {
res.render('client', {game: req.params.game});
},
showQR: function(req, res) {
var joinURL = req.protocol + '://' + req.headers.host + '/c/' + req.params.game;
var url = 'http://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' + joinURL;
request.get(url).pipe(res);
},
bind: function(app) {
app.get('/', handlers.showIntro);
app.get('/p/', handlers.createGame);
app.get('/p/:game', handlers.observeGame);
app.get('/c/:game', handlers.playGame);
app.get('/qr/:game', handlers.showQR);
}
};
module.exports = handlers;
"
Make sure errors result in a non-zero exit code,"#!/usr/bin/env node
import process from 'process';
import path from 'path';
import yargs from 'yargs';
import { downloadSchema, generate } from '.';
// Make sure unhandled errors in async code are propagated correctly
process.on('unhandledRejection', (error) => { throw error });
yargs
.command(
'download-schema ',
'Download a GraphQL schema from a server',
{
output: {
demand: true,
describe: 'Output path for GraphQL schema file',
normalize: true
}
},
async argv => {
const outputPath = path.resolve(argv.output);
await downloadSchema(argv.server, outputPath);
}
)
.command(
'generate ',
'Generate code from a GraphQL schema and query documents',
{
schema: {
demand: true,
describe: 'Path to GraphQL schema file',
normalize: true
},
output: {
demand: true,
describe: 'Output directory for the generated files',
normalize: true
}
},
argv => {
const inputPaths = argv.input.map(input => path.resolve(input));
const schemaPath = path.resolve(argv.schema);
const outputPath = path.resolve(argv.output);
generate(inputPaths, schemaPath, outputPath);
},
)
.showHelpOnFail(false)
.help()
.strict()
.argv
","#!/usr/bin/env node
import path from 'path';
import yargs from 'yargs';
import { downloadSchema, generate } from '.';
yargs
.command(
'download-schema ',
'Download a GraphQL schema from a server',
{
output: {
demand: true,
describe: 'Output path for GraphQL schema file',
normalize: true
}
},
async argv => {
const outputPath = path.resolve(argv.output);
try {
await downloadSchema(argv.server, outputPath);
} catch (error) {
console.error(error);
}
}
)
.command(
'generate ',
'Generate code from a GraphQL schema and query documents',
{
schema: {
demand: true,
describe: 'Path to GraphQL schema file',
normalize: true
},
output: {
demand: true,
describe: 'Output directory for the generated files',
normalize: true
}
},
argv => {
try {
const inputPaths = argv.input.map(input => path.resolve(input));
const schemaPath = path.resolve(argv.schema);
const outputPath = path.resolve(argv.output);
generate(inputPaths, schemaPath, outputPath);
} catch (error) {
console.error(error.stack);
}
},
)
.showHelpOnFail(false)
.help()
.strict()
.argv
"
Add params_timestamp_key and response_timestamp_key methods,"class ApiSubscribeRequest(object):
""""""Api request class.""""""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
'response_key': None,
'params_timestamp_key': 'timestamp',
'response_timestamp_key': 'timestamp'}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
def params_timestamp_key(self, params_timestamp_key):
self._params['params_timestamp_key'] = params_timestamp_key
def response_timestamp_key(self, response_timestamp_key):
self._params['response_timestamp_key'] = response_timestamp_key
def extract(self):
return self._action, self._request, self._params
","class ApiSubscribeRequest(object):
""""""Api request class.""""""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
'response_key': None}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
def extract(self):
return self._action, self._request, self._params
"
Add error handler to System.import promises,"/*
* Copyright 2014 Workiva, LLC
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(karma, System) {
// Prevent immediately starting tests.
window.__karma__.loaded = function() {};
function extractModuleName(fileName){
return fileName.replace(/\.js$/, """");
}
var promises = [];
if(!System){
throw new Error(""SystemJS was not found. Please make sure you have "" +
""initialized jspm via installing a dependency with jspm, "" +
""or by running 'jspm dl-loader'."");
}
// Configure SystemJS baseURL
System.config({
baseURL: 'base'
});
// Load everything specified in loadFiles
karma.config.jspm.expandedFiles.map(function(modulePath){
var promise = System.import(extractModuleName(modulePath))
.catch(function(e){
setTimeout(function() {
throw e;
});
});
promises.push(promise);
});
// Promise comes from the es6_module_loader
Promise.all(promises).then(function(){
karma.start();
});
})(window.__karma__, window.System);
","/*
* Copyright 2014 Workiva, LLC
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(karma, System) {
// Prevent immediately starting tests.
window.__karma__.loaded = function() {};
function extractModuleName(fileName){
return fileName.replace(/\.js$/, """");
}
var promises = [];
if(!System){
throw new Error(""SystemJS was not found. Please make sure you have "" +
""initialized jspm via installing a dependency with jspm, "" +
""or by running 'jspm dl-loader'."");
}
// Configure SystemJS baseURL
System.config({
baseURL: 'base'
});
// Load everything specified in loadFiles
karma.config.jspm.expandedFiles.map(function(modulePath){
promises.push(System.import(extractModuleName(modulePath)));
});
// Promise comes from the es6_module_loader
Promise.all(promises).then(function(){
karma.start();
});
})(window.__karma__, window.System);
"
FT: Add check for sha256 hashed signature,"import crypto from 'crypto';
import { accountsKeyedbyAccessKey } from './vault.json';
export function hashSignature(stringToSign, secretKey, algorithm) {
const hmacObject = crypto.createHmac(algorithm, secretKey);
return hmacObject.update(stringToSign).digest('base64');
}
const vault = {
authenticateV2Request: (accessKey, signatureFromRequest,
stringToSign, callback) => {
const account = accountsKeyedbyAccessKey[accessKey];
if (!account) {
return callback('InvalidAccessKeyId');
}
const secretKey = account.secretKey;
// If the signature sent is 43 characters,
// this means that sha256 was used:
// 43 characters in base64
const algo = signatureFromRequest.length === 43 ?
'sha256' : 'sha1';
const reconstructedSig =
hashSignature(stringToSign, secretKey, algo);
if (signatureFromRequest !== reconstructedSig) {
return callback('SignatureDoesNotMatch');
}
const userInfoToSend = {
accountDisplayName: account.displayName,
canonicalID: account.canonicalID,
arn: account.arn,
IAMdisplayName: account.IAMdisplayName,
};
// For now, I am just sending back the canonicalID.
// TODO: Refactor so that the accessKey information
// passed to the API is the full accountInfo Object
// rather than just the canonicalID string.
// This is GH Issue#75
return callback(null, userInfoToSend.canonicalID);
}
};
export default vault;
","import crypto from 'crypto';
import { accountsKeyedbyAccessKey } from './vault.json';
export function hashSignature(stringToSign, secretKey, algorithm) {
const hmacObject = crypto.createHmac(algorithm, secretKey);
return hmacObject.update(stringToSign).digest('base64');
}
const vault = {
authenticateV2Request: (accessKey, signatureFromRequest,
stringToSign, callback) => {
const account = accountsKeyedbyAccessKey[accessKey];
if (!account) {
return callback('InvalidAccessKeyId');
}
const secretKey = account.secretKey;
const reconstructedSignature =
hashSignature(stringToSign, secretKey, 'sha1');
if (reconstructedSignature !== signatureFromRequest) {
return callback('SignatureDoesNotMatch');
}
const userInfoToSend = {
accountDisplayName: account.displayName,
canonicalID: account.canonicalID,
arn: account.arn,
IAMdisplayName: account.IAMdisplayName,
};
// For now, I am just sending back the canonicalID.
// TODO: Refactor so that the accessKey information
// passed to the API is the full accountInfo Object
// rather than just the canonicalID string.
// This is GH Issue#75
return callback(null, userInfoToSend.canonicalID);
}
};
export default vault;
"
Fix OS depending unit test failure,"package io.toolisticon.annotationprocessortoolkit.tools.generators;
import io.toolisticon.annotationprocessortoolkit.AbstractAnnotationProcessor;
import io.toolisticon.annotationprocessortoolkit.tools.FilerUtils;
import io.toolisticon.annotationprocessortoolkit.tools.MessagerUtils;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.util.Set;
/**
* Test annotation processor for testing {@link FilerUtils}.
*/
@SupportedAnnotationTypes(
""io.toolisticon.annotationprocessortoolkit.tools.generators.FileObjectUtilsTestAnnotation"")
public class FileObjectUtilsTestAnnotationProcessor extends AbstractAnnotationProcessor {
private SimpleResourceWriter simpleResourceWriter = null;
@Override
public boolean processAnnotations(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
for (Element element : roundEnv.getElementsAnnotatedWith(FileObjectUtilsTestAnnotation.class)) {
if (simpleResourceWriter == null) {
simpleResourceWriter = FilerUtils.createResource(""testOutput.txt"");
}
simpleResourceWriter.append(element.getSimpleName().toString() + System.lineSeparator());
}
} catch (Exception e) {
MessagerUtils.error(null, ""Wasn't able to use SimpleResourceWriter without error"");
} finally {
try {
simpleResourceWriter.close();
} catch (Exception e) {
}
}
return false;
}
}
","package io.toolisticon.annotationprocessortoolkit.tools.generators;
import io.toolisticon.annotationprocessortoolkit.AbstractAnnotationProcessor;
import io.toolisticon.annotationprocessortoolkit.tools.FilerUtils;
import io.toolisticon.annotationprocessortoolkit.tools.MessagerUtils;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import java.util.Set;
/**
* Test annotation processor for testing {@link FilerUtils}.
*/
@SupportedAnnotationTypes(
""io.toolisticon.annotationprocessortoolkit.tools.generators.FileObjectUtilsTestAnnotation"")
public class FileObjectUtilsTestAnnotationProcessor extends AbstractAnnotationProcessor {
private SimpleResourceWriter simpleResourceWriter = null;
@Override
public boolean processAnnotations(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
for (Element element : roundEnv.getElementsAnnotatedWith(FileObjectUtilsTestAnnotation.class)) {
if (simpleResourceWriter == null) {
simpleResourceWriter = FilerUtils.createResource(""testOutput.txt"");
}
simpleResourceWriter.append(element.getSimpleName().toString() + ""\n"");
}
} catch (Exception e) {
MessagerUtils.error(null, ""Wasn't able to use SimpleResourceWriter without error"");
} finally {
try {
simpleResourceWriter.close();
} catch (Exception e) {
}
}
return false;
}
}
"
Use Python2/3 compatible form of exec,"# Copyright (c) Calico Development Team.
# Distributed under the terms of the Modified BSD License.
# http://calicoproject.org/
from jupyter_kernel import Magic, option
class PythonMagic(Magic):
env = {}
def line_python(self, *args):
""""""%python CODE - evaluate code as Python""""""
code = "" "".join(args)
self.retval = self.eval(code)
def eval(self, code):
try:
return eval(code.strip(), self.env)
except:
try:
exec(code.strip(), self.env)
except Exception as exc:
return ""Error: "" + str(exc)
if ""retval"" in self.env:
return self.env[""retval""]
@option(
""-e"", ""--eval_output"", action=""store_true"", default=False,
help=""Use the retval value from the Python cell as code in the kernel language.""
)
def cell_python(self, eval_output=False):
""""""%%python - evaluate contents of cell as Python""""""
if self.code.strip():
if eval_output:
self.eval(self.code)
self.code = str(self.env[""retval""]) if ""retval"" in self.env else """"
self.retval = None
self.evaluate = True
else:
self.retval = self.eval(self.code)
self.evaluate = False
def post_process(self, retval):
if retval:
return retval
else:
return self.retval
def register_magics(kernel):
kernel.register_magics(PythonMagic)
","# Copyright (c) Calico Development Team.
# Distributed under the terms of the Modified BSD License.
# http://calicoproject.org/
from jupyter_kernel import Magic, option
class PythonMagic(Magic):
env = {}
def line_python(self, *args):
""""""%python CODE - evaluate code as Python""""""
code = "" "".join(args)
self.retval = self.eval(code)
def eval(self, code):
try:
return eval(code.strip(), self.env)
except:
try:
exec code.strip() in self.env
except Exception as exc:
return ""Error: "" + str(exc)
if ""retval"" in self.env:
return self.env[""retval""]
@option(
""-e"", ""--eval_output"", action=""store_true"", default=False,
help=""Use the retval value from the Python cell as code in the kernel language.""
)
def cell_python(self, eval_output=False):
""""""%%python - evaluate contents of cell as Python""""""
if self.code.strip():
if eval_output:
self.eval(self.code)
self.code = str(self.env[""retval""]) if ""retval"" in self.env else """"
self.retval = None
self.evaluate = True
else:
self.retval = self.eval(self.code)
self.evaluate = False
def post_process(self, retval):
if retval:
return retval
else:
return self.retval
def register_magics(kernel):
kernel.register_magics(PythonMagic)
"
Load already existings source maps if available.,"'use strict'
const concat = require('gulp-concat')
const cleancss = require('gulp-clean-css')
const sourcemaps = require('gulp-sourcemaps')
const filenames = require('gulp-filenames')
const hash = require('gulp-hash-filename')
const util = require('gulp-util')
exports.fn = function (gulp, paths, mode, done) {
var srcCss = [
paths.src + '**/css/bootstrap.css',
paths.src + '**/css/bootstrap-theme.css',
paths.src + '**/css/font-awesome.css',
paths.src + 'css/*'
]
return gulp.src(srcCss)
.pipe(!mode.production ? sourcemaps.init({loadMaps: true}) : util.noop())
.pipe(concat('app-bundle.css'))
.pipe(cleancss({keepSpecialComments: 0, sourceMap: false}))
.pipe(mode.production ? hash({'format': '{hash}{ext}'}) : util.noop())
.pipe(filenames('cssbundle'))
.pipe(!mode.production ? sourcemaps.write('.', {
mapSources: function (sourcePath) {
var prefix = ''
if (sourcePath.indexOf('/') === -1) {
prefix = 'css/'
}
var extendedSourcePath = paths.src.substr(2) + prefix + sourcePath
util.log('SourcePath within source map extended to:', util.colors.cyan(extendedSourcePath))
return extendedSourcePath
}
}) : util.noop())
.pipe(gulp.dest(paths.wwwroot))
}
","'use strict'
const concat = require('gulp-concat')
const cleancss = require('gulp-clean-css')
const sourcemaps = require('gulp-sourcemaps')
const filenames = require('gulp-filenames')
const hash = require('gulp-hash-filename')
const util = require('gulp-util')
exports.fn = function (gulp, paths, mode, done) {
var srcCss = [
paths.src + '**/css/bootstrap.css',
paths.src + '**/css/bootstrap-theme.css',
paths.src + '**/css/font-awesome.css',
paths.src + 'css/*'
]
return gulp.src(srcCss)
.pipe(!mode.production ? sourcemaps.init() : util.noop())
.pipe(concat('app-bundle.css'))
.pipe(cleancss({keepSpecialComments: 0, sourceMap: false}))
.pipe(mode.production ? hash({'format': '{hash}{ext}'}) : util.noop())
.pipe(filenames('cssbundle'))
.pipe(!mode.production ? sourcemaps.write('.', {
mapSources: function (sourcePath) {
var prefix = ''
if (sourcePath.indexOf('/') === -1) {
prefix = 'css/'
}
var extendedSourcePath = paths.src.substr(2) + prefix + sourcePath
util.log('SourcePath within source map extended to:', util.colors.cyan(extendedSourcePath))
return extendedSourcePath
}
}) : util.noop())
.pipe(gulp.dest(paths.wwwroot))
}
"
Use fs.exists instead of path.exists,"var inspect = require(""util"").inspect
var fs = require(""fs"")
module.exports = function (callback) {
try_in_order([
function (callback) {
if (process.env.RUN_SWF_VERBOSE) {
console.warn(""run-swf: looking for $FLASHPLAYER..."")
}
if (process.env.FLASHPLAYER) {
get_program(process.env.FLASHPLAYER, callback)
} else {
callback(null)
}
},
function (callback) {
get_osx_app_program(""Flash Player Debugger"", callback)
},
function (callback) {
get_osx_app_program(""Flash Player"", callback)
}
], callback)
function get_osx_app_program(name, callback) {
get_program(
""/Applications/"" + name + "".app/Contents/MacOS/"" + name,
callback
)
}
function get_program(filename, callback) {
if (process.env.RUN_SWF_VERBOSE) {
console.warn(""run-swf: looking for %s..."", inspect(filename))
}
fs.exists(filename, function (exists) {
callback(exists ? filename : null)
})
}
}
function try_in_order(functions, callback) {
functions = [].slice.call(functions)
;(function loop () {
if (functions.length === 0) {
callback(null)
} else {
functions.shift()(function (program) {
if (program) {
callback(program)
} else {
loop()
}
})
}
})()
}
","var inspect = require(""util"").inspect
var path = require(""path"")
module.exports = function (callback) {
try_in_order([
function (callback) {
if (process.env.RUN_SWF_VERBOSE) {
console.warn(""run-swf: looking for $FLASHPLAYER..."")
}
if (process.env.FLASHPLAYER) {
get_program(process.env.FLASHPLAYER, callback)
} else {
callback(null)
}
},
function (callback) {
get_osx_app_program(""Flash Player Debugger"", callback)
},
function (callback) {
get_osx_app_program(""Flash Player"", callback)
}
], callback)
function get_osx_app_program(name, callback) {
get_program(
""/Applications/"" + name + "".app/Contents/MacOS/"" + name,
callback
)
}
function get_program(filename, callback) {
if (process.env.RUN_SWF_VERBOSE) {
console.warn(""run-swf: looking for %s..."", inspect(filename))
}
path.exists(filename, function (exists) {
callback(exists ? filename : null)
})
}
}
function try_in_order(functions, callback) {
functions = [].slice.call(functions)
;(function loop () {
if (functions.length === 0) {
callback(null)
} else {
functions.shift()(function (program) {
if (program) {
callback(program)
} else {
loop()
}
})
}
})()
}
"
Increase clarity of reasons to not be verbose,"config = $config;
}
public function getItemId($request)
{
// item ID
if (! empty($request->url_elements[3])
&& is_numeric($request->url_elements[3])
) {
return (int) $request->url_elements[3];
}
return false;
}
public function getVerbosity($request)
{
if (! isset($request->parameters['verbose'])) {
return false;
}
if ($request->parameters['verbose'] !== 'yes') {
return false;
}
return true;
}
public function getStart($request)
{
return $request->paginationParameters['start'];
}
public function getResultsPerPage($request)
{
return (int) $request->paginationParameters['resultsperpage'];
}
public function getSort($request)
{
// unfiltered, you probably want to switch case this
return $this->getRequestParameter($request, 'sort');
}
protected function getRequestParameter($request, $parameter, $default = false)
{
if (isset($request->parameters[$parameter])) {
return $request->parameters[$parameter];
}
return $default;
}
}
","config = $config;
}
public function getItemId($request)
{
// item ID
if (! empty($request->url_elements[3])
&& is_numeric($request->url_elements[3])
) {
return (int) $request->url_elements[3];
}
return false;
}
public function getVerbosity($request)
{
// verbosity
return isset($request->parameters['verbose'])
&& $request->parameters['verbose'] == 'yes';
}
public function getStart($request)
{
return $request->paginationParameters['start'];
}
public function getResultsPerPage($request)
{
return (int) $request->paginationParameters['resultsperpage'];
}
public function getSort($request)
{
// unfiltered, you probably want to switch case this
return $this->getRequestParameter($request, 'sort');
}
protected function getRequestParameter($request, $parameter, $default = false)
{
if (isset($request->parameters[$parameter])) {
return $request->parameters[$parameter];
}
return $default;
}
}
"
Add test for custom servers,"assertNotFalse(
$inAddr,
""Server name $hostname did not resolve to a valid IP address""
);
});
}
/**
* @group internet
* @dataProvider provideServers
*/
public function testResolveWithCustomServer($server) {
\Amp\run(function () use ($server) {
$result = (yield \Amp\Dns\resolve(""google.com"", [
""server"" => $server
]));
list($addr, $type, $ttl) = $result[0];
$inAddr = @\inet_pton($addr);
$this->assertNotFalse(
$inAddr,
""Server name google.com did not resolve to a valid IP address via $server""
);
});
}
public function provideHostnames() {
return [
[""google.com""],
[""github.com""],
[""stackoverflow.com""],
[""localhost""],
[""192.168.0.1""],
[""::1""],
];
}
public function provideServers() {
return [
[""8.8.8.8""],
[""8.8.8.8:53""],
];
}
}
","assertNotFalse(
$inAddr,
""Server name $name did not resolve to a valid IP address""
);
}
});
}
}
"
Fix docblock issues noticed by Scrutinizer,"handlerLocator = $handlerLoader;
$this->methodNameInflector = $methodNameInflector;
}
/**
* Executes a command and optionally returns a value
*
* @throws CanNotInvokeHandlerException
* @param object $command
* @return mixed
*/
public function execute($command)
{
$handler = $this->handlerLocator->getHandlerForCommand($command);
$methodName = $this->methodNameInflector->inflect($command, $handler);
// is_callable is used here instead of method_exists, as method_exists
// will fail when given a handler that relies on __call.
if (!is_callable([$handler, $methodName])) {
throw CanNotInvokeHandlerException::onObject($command, ""Method '{$methodName}' does not exist on handler"");
}
return $handler->{$methodName}($command);
}
}
","handlerLocator = $handlerLoader;
$this->methodNameInflector = $methodNameInflector;
}
/**
* Executes a command and optionally returns a value
*
* @param object $command
* @return mixed
*/
public function execute($command)
{
$handler = $this->handlerLocator->getHandlerForCommand($command);
$methodName = $this->methodNameInflector->inflect($command, $handler);
// is_callable is used here instead of method_exists, as method_exists
// will fail when given a handler that relies on __call.
if (!is_callable([$handler, $methodName])) {
throw CanNotInvokeHandlerException::onObject($command, ""Method '{$methodName}' does not exist on handler"");
}
return $handler->{$methodName}($command);
}
}
"
Fix the one byte ESlint didn't like,"import React from 'react';
import PropTypes from 'prop-types';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: PropTypes.string.isRequired
}
render() {
return (
Create your first pipeline
Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.
Need inspiration? See the example pipelines GitHub repo.
New Pipeline
);
}
}
export default Welcome;
","import React from 'react';
import PropTypes from 'prop-types';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: PropTypes.string.isRequired
}
render() {
return (
Create your first pipeline
Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.
Need inspiration? See the example pipelines GitHub repo.
New Pipeline
);
}
}
export default Welcome;
"
Fix obtrusive compiler pass issue,"
*/
class TranslationPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('translator.default')) {
return;
}
$translator = $container->findDefinition('translator.default');
$r = new \ReflectionClass('SLLH\IsoCodesValidator\IsoCodesConstraintValidator');
$translationsDir = dirname($r->getFilename()).'/Resources/translations';
$finder = Finder::create()
->files()
->filter(function (\SplFileInfo $file) {
return 2 === substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/', $file->getBasename());
})
->in($translationsDir)
;
foreach ($finder as $file) {
list($domain, $locale, $format) = explode('.', $file->getBasename(), 3);
$translator->addMethodCall('addResource', array($format, (string) $file, $locale, $domain));
}
}
}
","
*/
class TranslationPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$translator = $container->findDefinition('translator.default');
$r = new \ReflectionClass('SLLH\IsoCodesValidator\IsoCodesConstraintValidator');
$translationsDir = dirname($r->getFilename()).'/Resources/translations';
$finder = Finder::create()
->files()
->filter(function (\SplFileInfo $file) {
return 2 === substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/', $file->getBasename());
})
->in($translationsDir)
;
foreach ($finder as $file) {
list($domain, $locale, $format) = explode('.', $file->getBasename(), 3);
$translator->addMethodCall('addResource', array($format, (string) $file, $locale, $domain));
}
}
}
"
Improve task name by allowing wider input range,"package seedu.taskitty.model.task;
import seedu.taskitty.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS =
""Task names should be alphabets, numbers, spaces and common punctuations, Meow!"";
public static final String NAME_VALIDATION_REGEX_FORMAT = ""[\\p{Alnum}!@$%&(),.? ]+"";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
String trimName = name.trim();
if (!isValidName(trimName)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = trimName;
}
/**
* Returns true if a given string is a valid person name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX_FORMAT);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
","package seedu.taskitty.model.task;
import seedu.taskitty.commons.exceptions.IllegalValueException;
/**
* Represents a Task's name in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = ""Task names should be spaces or alphanumeric characters"";
public static final String NAME_VALIDATION_REGEX_FORMAT = ""[\\p{Alnum} ]+"";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
String trimName = name.trim();
if (!isValidName(trimName)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = trimName;
}
/**
* Returns true if a given string is a valid person name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX_FORMAT);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
"
Use string post instead of constant,"endpoint = $endpoint;
}
/**
* Gets the redirect target url.
*/
public function getRedirectUrl()
{
return $this->endpoint;
}
/**
* Get the required redirect method (either GET or POST).
*/
public function getRedirectMethod()
{
return 'post';
}
/**
* Gets the redirect form data array, if the redirect method is POST.
*/
public function getRedirectData()
{
$data = $this->getData();
foreach ($data as $key => $value) {
if(empty($value))
{
unset($data[$key]);
}
}
return $data;
}
/**
* Is the response successful?
*
* @return boolean
*/
public function isSuccessful()
{
return true;
}
public function isRedirect()
{
return true;
}
}
","endpoint = $endpoint;
}
/**
* Gets the redirect target url.
*/
public function getRedirectUrl()
{
return $this->endpoint;
}
/**
* Get the required redirect method (either GET or POST).
*/
public function getRedirectMethod()
{
return OAUTH_HTTP_METHOD_POST;
}
/**
* Gets the redirect form data array, if the redirect method is POST.
*/
public function getRedirectData()
{
$data = $this->getData();
foreach ($data as $key => $value) {
if(empty($value))
{
unset($data[$key]);
}
}
return $data;
}
/**
* Is the response successful?
*
* @return boolean
*/
public function isSuccessful()
{
return true;
}
public function isRedirect()
{
return true;
}
}
"
Set the permission of the file logs for daily and single to be 02770," env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: ""single"", ""daily"", ""slack"", ""syslog"",
| ""errorlog"", ""custom"", ""stack""
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'permission' => 02770,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 7,
'permission' => 02770,
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
],
];
"," env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: ""single"", ""daily"", ""slack"", ""syslog"",
| ""errorlog"", ""custom"", ""stack""
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 7,
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
],
];
"
Use object SID instead of GUID,"newAdldapUserQuery()->where([
$this->getSchema()->objectSid() => $identifier,
])->first();
if ($user instanceof Authenticatable) {
return $user;
}
}
/**
* {@inheritdoc}
*/
public function retrieveByToken($identifier, $token)
{
return;
}
/**
* {@inheritdoc}
*/
public function updateRememberToken(Authenticatable $user, $token)
{
//
}
/**
* {@inheritdoc}
*/
public function retrieveByCredentials(array $credentials)
{
return $this->retrieveLdapUserByCredentials($credentials);
}
/**
* {@inheritdoc}
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
// Retrieve the authentication username for the AD user.
$username = $this->getLoginUsernameFromUser($user);
// Retrieve the users password.
$password = $this->getPasswordFromCredentials($credentials);
// Perform LDAP authentication.
return $this->authenticate($username, $password);
}
}
","newAdldapUserQuery()->where([
$this->getSchema()->objectGuid() => Utilities::stringGuidToHex($identifier),
])->first();
if ($user instanceof Authenticatable) {
return $user;
}
}
/**
* {@inheritdoc}
*/
public function retrieveByToken($identifier, $token)
{
return;
}
/**
* {@inheritdoc}
*/
public function updateRememberToken(Authenticatable $user, $token)
{
//
}
/**
* {@inheritdoc}
*/
public function retrieveByCredentials(array $credentials)
{
return $this->retrieveLdapUserByCredentials($credentials);
}
/**
* {@inheritdoc}
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
// Retrieve the authentication username for the AD user.
$username = $this->getUsernameFromAuthenticatable($user);
// Retrieve the users password.
$password = $this->getPasswordFromCredentials($credentials);
// Perform LDAP authentication.
return $this->authenticate($username, $password);
}
}
"
Fix geo location on mobile,"'use strict';
var GeolocationService = function ($rootScope, DeviceReadyService, $q) {
return {
getCurrentPosition: function(onSuccess, onError, options) {
return DeviceReadyService.ready.then(function () {
var deferred;
deferred = $q.defer();
navigator.geolocation.getCurrentPosition(function () {
var _this = this,
args = arguments;
if (typeof onSuccess === 'function') {
$rootScope.$apply(function () {
onSuccess.apply(_this, args[0]);
});
}
deferred.resolve(args[0]);
}, function () {
var _this = this,
args = arguments;
if (typeof onError === 'function') {
$rootScope.$apply(function () {
onError.apply(_this, args[0]);
});
}
deferred.reject(args[0]);
},
options);
return deferred.promise;
});
}
};
};
GeolocationService.$inject = ['$rootScope', 'DeviceReadyService', '$q'];
module.exports = GeolocationService;","'use strict';
var GeolocationService = function ($rootScope, DeviceReadyService, $q) {
return {
getCurrentPosition: function(onSuccess, onError, options) {
return DeviceReadyService.ready.then(function () {
var deferred;
deferred = $q.defer();
navigator.geolocation.getCurrentPosition(function () {
var _this = this,
args = arguments;
if (typeof onSuccess === 'function') {
$rootScope.$apply(function () {
onSuccess.apply(_this, args);
});
}
deferred.resolve(args);
}, function () {
var _this = this,
args = arguments;
if (typeof onError === 'function') {
$rootScope.$apply(function () {
onError.apply(_this, args);
});
}
deferred.reject(args);
},
options);
return deferred.promise;
});
}
};
};
GeolocationService.$inject = ['$rootScope', 'DeviceReadyService', '$q'];
module.exports = GeolocationService;"
Fix fov is not defined,"/**
* Camera: what the player sees
*/
class Camera {
/**
* Constructor
*
* @param {Corridor} rooms
* @param {Number} fov
* @param {Number} width
* @param {Number} height
* @param {Number} scale
* @param {Object} stage
*/
constructor(rooms, fov, width, height, scale, stage) {
this.rooms = rooms;
this.width = fov;
this.halfWidth = fov / 2;
this.screen = { width, height };
this.scale = scale;
this.graphic = new PIXI.Graphics();
stage.addChild(this.graphic);
}
/**
* Draw the player view at its current position
*
* @param {Number} position
*/
draw(position) {
const start = (position - this.halfWidth) * this.scale;
const end = (position + this.halfWidth) * this.scale;
const rooms = this.rooms.filter(start, end);
for (var i = rooms.length - 1; i >= 0; i--) {
this.drawRoom(start, end, rooms[i]);
}
}
/**
* Draw a room into the camera
*
* @param {Number} start
* @param {Number} end
* @param {Room} room
*/
drawRoom(start, end, room) {
console.log(room);
}
}
export default Camera;
","/**
* Camera: what the player sees
*/
class Camera {
/**
* Constructor
*
* @param {Corridor} rooms
* @param {Number} fov
* @param {Number} width
* @param {Number} height
* @param {Number} scale
* @param {Object} stage
*/
constructor(rooms, fov, width, height, scale, stage) {
this.rooms = rooms;
this.fov = fov;
this.screen = { width, height };
this.scale = scale;
this.graphic = new PIXI.Graphics();
stage.addChild(this.graphic);
}
/**
* Draw the player view at its current position
*
* @param {Number} position
*/
draw(position) {
const start = (position - fov/2) * this.scale;
const end = (position + fov/2) * this.scale;
const rooms = this.rooms.filter(start, end);
for (var i = rooms.length - 1; i >= 0; i--) {
this.drawRoom(start, end, rooms[i]);
}
}
/**
* Draw a room into the camera
*
* @param {Number} start
* @param {Number} end
* @param {Room} room
*/
drawRoom(start, end, room) {
}
}
export default Camera;
"
Change SimPy to simpy for the package name.,"# encoding: utf-8
from setuptools import setup, find_packages
import simpy
setup(
name='simpy',
version=simpy.__version__,
author='Ontje Lünsdorf, Stefan Scherfke',
author_email='the_com at gmx.de; stefan at sofa-rockers.org',
description='Event discrete, process based simulation for Python.',
long_description=(open('README.txt').read() + '\n\n' +
open('CHANGES.txt').read() + '\n\n' +
open('AUTHORS.txt').read()),
url='https://simpy.rtfd.org',
download_url='https://bitbucket.org/simpy/simpy/downloads',
license='MIT License',
install_requires=[],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Scientific/Engineering',
],
)
","# encoding: utf-8
from setuptools import setup, find_packages
import simpy
setup(
name='SimPy',
version=simpy.__version__,
author='Ontje Lünsdorf, Stefan Scherfke',
author_email='the_com at gmx.de; stefan at sofa-rockers.org',
description='Event discrete, process based simulation for Python.',
long_description=(open('README.txt').read() + '\n\n' +
open('CHANGES.txt').read() + '\n\n' +
open('AUTHORS.txt').read()),
url='https://simpy.rtfd.org',
download_url='https://bitbucket.org/simpy/simpy/downloads',
license='MIT License',
install_requires=[],
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Scientific/Engineering',
],
)
"
Remove statusbar command from default menu,"module.exports = [
{
id: ""application"",
caption: ""Codebox"",
items: [
{
caption: ""Settings"",
command: ""settings.open""
},
{ type: ""separator"" },
{
caption: ""About"",
command: ""application.about""
},
{
caption: ""Welcome"",
command: ""application.welcome""
},
{
caption: ""Releases Notes"",
command: ""application.changes""
}
]
},
{
id: ""file"",
caption: ""File"",
items: [
{
caption: ""New File"",
command: ""file.open""
},
{ type: ""separator"" },
{
caption: ""Save"",
command: ""editor.save""
},
{
caption: ""Save All"",
command: ""editor.save.all""
}
]
},
{
id: ""view"",
caption: ""View"",
items: [
{
caption: ""Toggle Menu Bar"",
command: ""view.menubar.toggle""
}
]
},
{
id: ""tools"",
caption: ""Tools"",
items: [
{
caption: ""Command Palette..."",
command: ""palette.open""
}
]
},
{
id: ""help"",
caption: ""Help"",
position: 100,
items: [
{
caption: ""Documentation"",
command: ""application.help""
},
{
caption: ""Send Feedback"",
command: ""application.feedback""
}
]
}
];
","module.exports = [
{
id: ""application"",
caption: ""Codebox"",
items: [
{
caption: ""Settings"",
command: ""settings.open""
},
{ type: ""separator"" },
{
caption: ""About"",
command: ""application.about""
},
{
caption: ""Welcome"",
command: ""application.welcome""
},
{
caption: ""Releases Notes"",
command: ""application.changes""
}
]
},
{
id: ""file"",
caption: ""File"",
items: [
{
caption: ""New File"",
command: ""file.open""
},
{ type: ""separator"" },
{
caption: ""Save"",
command: ""editor.save""
},
{
caption: ""Save All"",
command: ""editor.save.all""
}
]
},
{
id: ""view"",
caption: ""View"",
items: [
{
caption: ""Toggle Status Bar"",
command: ""view.statusbar.toggle""
},
{
caption: ""Toggle Menu Bar"",
command: ""view.menubar.toggle""
}
]
},
{
id: ""tools"",
caption: ""Tools"",
items: [
{
caption: ""Command Palette..."",
command: ""palette.open""
}
]
},
{
id: ""help"",
caption: ""Help"",
position: 100,
items: [
{
caption: ""Documentation"",
command: ""application.help""
},
{
caption: ""Send Feedback"",
command: ""application.feedback""
}
]
}
];
"
Raise AttributeError if key does not exist when trying to get it from a Record,"class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return ""Metadata({}, {})"".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **attributes):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
self.attributes = attributes
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
try:
return self.attributes[item]
except KeyError:
raise AttributeError
def __repr__(self):
return ""Record('{}', {}, {}, {})"".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
","class Metadata(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return ""Metadata({}, {})"".format(repr(self.name), repr(self.value))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Record(object):
def __init__(self, type, id, document=None, parent_ids=None, **extra):
self.document = document
self.type = type
self.id = id
self.parent_ids = parent_ids
self._extra = extra
@property
def parents(self):
if not self.parent_ids is None:
return [self.document[pid] for pid in self.parent_ids]
else:
return []
def __getattr__(self, item):
return self._extra[item]
def __repr__(self):
return ""Record('{}', {}, {}, {})"".format(self.type,
self.id,
self.parent_ids,
', '.join('{}={}'.format(k, repr(v)) for k, v in self._extra.items()))
def __eq__(self, other):
return self.__dict__ == other.__dict__
"
Use internally an array for performance reasons,"package jwebform.validation;
import jwebform.validation.criteria.Criteria;
import jwebform.validation.criteria.MaxLength;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* Validator, that checks a field
*
* @author jochen
*
*/
public class Validator {
private final Criterion [] criteria;
private static final Validator EMPTY_VALIDATOR = new Validator();
public Validator(Criterion... inputCriterium) {
criteria = inputCriterium;
}
public static Validator emptyValidator() {
return EMPTY_VALIDATOR;
}
public boolean isRequired() {
for (Criterion criterion : criteria) {
if (criterion == Criteria.required()) { // this is ok, because it uses a sigelton
return true;
}
}
return false;
}
public Optional getMaxLen() {
for (Criterion criterion : criteria) {
if (criterion instanceof MaxLength) { // this
return Optional.of((MaxLength) criterion);
}
}
return Optional.empty();
}
public ValidationResult validate(String value) { // RFE: Better just
// object??
return allCriteriaSatisfied(value);
}
// RFE: Maybe return here an array? So we can have more than one
// error-message per field.
private ValidationResult allCriteriaSatisfied(String value) {
for (Criterion criterion : criteria) {
ValidationResult vr = criterion.validate(value);
if (!vr.isValid()) {
return vr;
}
}
return ValidationResult.ok();
}
}
","package jwebform.validation;
import jwebform.validation.criteria.Criteria;
import jwebform.validation.criteria.MaxLength;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* Validator, that checks a field
*
* @author jochen
*
*/
public class Validator {
private final List criteria = new ArrayList<>();
private static final Validator EMPTY_VALIDATOR = new Validator();
public Validator(Criterion... inputCriterium) {
Collections.addAll(criteria, inputCriterium);
}
public static Validator emptyValidator() {
return EMPTY_VALIDATOR;
}
public boolean isRequired() {
for (Criterion criterion : criteria) {
if (criterion == Criteria.required()) { // this is ok, because it uses a sigelton
return true;
}
}
return false;
}
public Optional getMaxLen() {
for (Criterion criterion : criteria) {
if (criterion instanceof MaxLength) { // this
return Optional.of((MaxLength) criterion);
}
}
return Optional.empty();
}
public ValidationResult validate(String value) { // RFE: Better just
// object??
return allCriteriaSatisfied(value);
}
// RFE: Maybe return here an array? So we can have more than one
// error-message per field.
private ValidationResult allCriteriaSatisfied(String value) {
for (Criterion criterion : criteria) {
ValidationResult vr = criterion.validate(value);
if (!vr.isValid()) {
return vr;
}
}
return ValidationResult.ok();
}
}
"
Fix test for storing article without any content,"from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug=""xyz"")
self.article = ArticleFactory(title=""english_article"", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', ""pari"")
self.client.login(username=""pari"", password=""pari"")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
""This field cannot be blank""): # Slug and title fields cannot be null.
ArticleFactory(title="""")
def test_article_can_be_stored_without_content(self):
article = ArticleFactory(title='Test', content='')
self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
""This field cannot be blank""):
ArticleFactory(title='Test', language='')
","from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug=""xyz"")
self.article = ArticleFactory(title=""english_article"", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', ""pari"")
self.client.login(username=""pari"", password=""pari"")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
""This field cannot be blank""): # Slug and title fields cannot be null.
ArticleFactory(title="""")
def test_article_cannot_be_stored_without_content(self):
with self.assertRaisesRegexp(ValidationError,
""This field cannot be blank""):
ArticleFactory(title='Test', content='')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
""This field cannot be blank""):
ArticleFactory(title='Test', language='')
"
Load from the pre processed data,"from __future__ import division
import gzip
try:
from BytesIO import BytesIO
except ImportError:
from io import BytesIO
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import hdfs
import pandas as pd
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from mrjob.step import MRStep
class CascadeCount(MRJob):
OUTPUT_PROTOCOL = JSONValueProtocol
def configure_options(self):
super(CascadeCount, self).configure_options()
def mapper(self, _, line):
client = hdfs.client.Client(""http://"" + urlparse(line).netloc)
if line[-1] != ""#"":
with client.read(urlparse(line).path) as r:
# with open(urlparse(line).path) as r:
buf = BytesIO(r.read())
# If the data is in a GZipped file.
if "".gz"" in line:
gzip_f = gzip.GzipFile(fileobj=buf)
content = gzip_f.read()
buf = StringIO.StringIO(content)
dtf = pd.read_csv(buf, index_col=False, header=None, sep=""\t"", engine=""python"",
compression=None).drop_duplicates(subset=[2], keep='last')
yield ""apple"", len(dft.index)
def steps(self):
return [
MRStep(mapper_init=self.mapper_init,
mapper=self.mapper
)
]
if __name__ == '__main__':
CascadeCount.run()
","from __future__ import division
import gzip
try:
from BytesIO import BytesIO
except ImportError:
from io import BytesIO
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import hdfs
import pandas as pd
from mrjob.job import MRJob
from mrjob.protocol import JSONValueProtocol
from mrjob.step import MRStep
class CascadeCount(MRJob):
OUTPUT_PROTOCOL = JSONValueProtocol
def configure_options(self):
super(CascadeCount, self).configure_options()
def mapper(self, _, line):
client = hdfs.client.Client(""http://"" + urlparse(line).netloc)
if line[-1] != ""#"":
with client.read(urlparse(line).path) as r:
# with open(urlparse(line).path) as r:
buf = BytesIO(r.read())
# If the data is in a GZipped file.
if "".gz"" in line:
gzip_f = gzip.GzipFile(fileobj=buf)
content = gzip_f.read()
buf = StringIO.StringIO(content)
dtf = pd.read_csv(buf, index_col=False, header=None, sep=""\t"", engine=""python"",
compression=None).drop_duplicates(subset=[2], keep='last')
yield ""apple"", len(dft.index)
def steps(self):
return [
MRStep(mapper_init=self.mapper_init,
mapper=self.mapper
)
]
if __name__ == '__main__':
MRJobNetworkX.run()
"
Move listen port back to 443,"var express = require('express');
var webInterface = function(dbot) {
var dbot = dbot;
var pub = 'public';
var app = express.createServer();
app.use(express.compiler({ src: pub, enable: ['sass'] }));
app.use(express.static(pub));
app.set('view engine', 'jade');
app.get('/', function(req, res) {
res.redirect('/quotes');
//res.render('index', { });
});
app.get('/quotes', function(req, res) {
// Lists the quote categories
res.render('quotelist', { 'quotelist': Object.keys(dbot.db.quoteArrs) });
});
app.get('/quotes/:key', function(req, res) {
// Lists the quotes in a category
var key = req.params.key.toLowerCase();
if(dbot.db.quoteArrs.hasOwnProperty(key)) {
res.render('quotes', { 'quotes': dbot.db.quoteArrs[key], locals: {url_regex: RegExp.prototype.url_regex()}});
} else {
res.render('error', { 'message': 'No quotes under that key.' });
}
});
app.listen(443);
return {
'onDestroy': function() {
app.close();
}
};
};
exports.fetch = function(dbot) {
return webInterface(dbot);
};
","var express = require('express');
var webInterface = function(dbot) {
var dbot = dbot;
var pub = 'public';
var app = express.createServer();
app.use(express.compiler({ src: pub, enable: ['sass'] }));
app.use(express.static(pub));
app.set('view engine', 'jade');
app.get('/', function(req, res) {
res.redirect('/quotes');
//res.render('index', { });
});
app.get('/quotes', function(req, res) {
// Lists the quote categories
res.render('quotelist', { 'quotelist': Object.keys(dbot.db.quoteArrs) });
});
app.get('/quotes/:key', function(req, res) {
// Lists the quotes in a category
var key = req.params.key.toLowerCase();
if(dbot.db.quoteArrs.hasOwnProperty(key)) {
res.render('quotes', { 'quotes': dbot.db.quoteArrs[key], locals: {url_regex: RegExp.prototype.url_regex()}});
} else {
res.render('error', { 'message': 'No quotes under that key.' });
}
});
app.listen(9443);
return {
'onDestroy': function() {
app.close();
}
};
};
exports.fetch = function(dbot) {
return webInterface(dbot);
};
"
Write tests in a better way,"from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence(self):
original = 'Who is the president of the United States'
j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
'tree': {'type': 'sentence', 'value': original}}
answer = self.request(j)
self.assertEqual(len(answer), 0, answer)
def testWrongSentence(self):
original = 'Who is the pesident of the United States'
expected = 'Who is the president of the United States'
j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
'tree': {'type': 'sentence', 'value': original}}
answer = self.request(j)
self.assertEqual(len(answer), 1, answer)
self.assertEqual(answer[0].tree, Sentence(value=expected))
def testIrrelevantInput(self):
original = 'Who is the president of the United States'
j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
'tree': {'type': 'resource', 'value': original}}
answer = self.request(j)
self.assertEqual(len(answer), 0, answer)
","from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence(self):
original = 'Who is the president of the United States'
j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
'tree': {'type': 'sentence', 'value': original}}
answer = self.request(j)
self.assertEquals(len(answer), 0)
def testWrongSentence(self):
original = 'Who is the pesident of the United States'
expected = 'Who is the president of the United States'
j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
'tree': {'type': 'sentence', 'value': original}}
answer = self.request(j)
self.assertEquals(len(answer), 1)
self.assertIsInstance(answer[0].tree, Sentence)
result = answer[0].tree.__getattr__('value')
self.assertEqual(result, expected)
def testIrrelevantInput(self):
original = 'Who is the president of the United States'
j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [],
'tree': {'type': 'resource', 'value': original}}
answer = self.request(j)
self.assertEquals(len(answer), 0)
"
Fix a line too long lint error,"import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
""""""
Returns the METAR report given an airport code
""""""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
","import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
""""""
Returns the METAR report given an airport code
""""""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
"
"Use the list item, not the list.
Otherwise you get urls with `[u'1234']` in.","import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r = requests.get(url, headers=headers, params=params)
if not r.ok:
raise Exception('GitHub returned {0}'.format(r.status_code))
since = time.strptime(r.headers['date'], '%a, %d %b %Y %H:%M:%S %Z')
notifications = json.loads(r.content)
if not notifications:
cache = []
for notification in notifications:
if not notification['id'] in cache:
latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:][0]
issue_url = notification['subject']['url'].replace('api.', '').replace('repos/', '')
open_url = '{0}#{1}'.format(issue_url, latest_comment_id)
kwargs = {
'title': notification['repository']['full_name'],
'open': open_url,
'group': os.getpid(),
}
s = notification['subject']['url'].split('/')[-2:]
pync.Notifier.notify('{0} #{1}'.format(s[0].title(), s[1]), **kwargs)
cache.append(notification['id'])
time.sleep(5)
except KeyboardInterrupt:
sys.exit(0)
","import json
import os
import sys
import time
import requests
import pync
try:
cache = []
headers = {'Authorization': 'bearer {0}'.format(os.environ['GITHUB_TOKEN'])}
since = None
url = 'https://api.github.com/notifications'
while True:
params = {'since': since} if since else {}
r = requests.get(url, headers=headers, params=params)
if not r.ok:
raise Exception('GitHub returned {0}'.format(r.status_code))
since = time.strptime(r.headers['date'], '%a, %d %b %Y %H:%M:%S %Z')
notifications = json.loads(r.content)
if not notifications:
cache = []
for notification in notifications:
if not notification['id'] in cache:
latest_comment_id = notification['subject']['latest_comment_url'].split('/')[-1:]
issue_url = notification['subject']['url'].replace('api.', '').replace('repos/', '')
open_url = '{0}#{1}'.format(issue_url, latest_comment_id)
kwargs = {
'title': notification['repository']['full_name'],
'open': open_url,
'group': os.getpid(),
}
s = notification['subject']['url'].split('/')[-2:]
pync.Notifier.notify('{0} #{1}'.format(s[0].title(), s[1]), **kwargs)
cache.append(notification['id'])
time.sleep(5)
except KeyboardInterrupt:
sys.exit(0)
"
Replace console output for raw txt,"import requests
import os
import sys
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, dirs, files in os.walk(dir_):
for file_ in files:
movies.append({
'title': os.path.splitext(file_)[0].rsplit(' ', 1),
'fpath': os.path.join(root, file_)
})
return movies
def main(dir_=MOVIEDIR):
f = open(dir_ + '/movies.txt', 'w')
for t in get_titles(dir_):
movie = request_data(t['title'], t['year'])
f.write('{}\n{}\n\n{} | {}\n{} | {} | {} | {} on IMDb\n{}\n\n\n'.format(
movie['Title'],
movie['Plot'],
movie['Director'],
movie['Actors'],
movie['Released'],
movie['Runtime'],
movie['Rated'],
movie['imdbRating'],
'http://www.imdb.com/title/' + movie['imdbID'] + '/',
))
f.close()
if __name__ == '__main__':
main()
","import requests
import os
from pprint import pprint
from tabulate import tabulate
OMDB_URL = 'http://www.omdbapi.com/?type=movie&plot=short&tomatoes=true&t={}&y={}'
def request_data(title, year):
return requests.get(OMDB_URL.format(title, year)).json()
def get_titles(dir_):
movies = list()
for root, dirs, files in os.walk(dir_):
for file_ in files:
movies.append({
'title': os.path.splitext(file_)[0].rsplit(' ', 1),
'fpath': os.path.join(root, file_)
})
return movies
def main(dir_='/Users/kashavmadan/Downloads/movies'):
table = list()
table.append(['Title', 'Plot', 'Genre', 'Actors', 'Rating', 'Runtime', 'Released', 'Score'])
for t in get_titles(dir_):
movie = request_data(t['title'][0], t['title'][1])
table.append([
movie['Title'],
movie['Plot'],
movie['Genre'],
movie['Actors'],
movie['Rated'],
movie['Runtime'],
movie['Released'],
movie['imdbRating']])
f = open('movies.txt', 'w')
f.write(tabulate(table, headers='firstrow', tablefmt='fancy_grid'))
f.close()
if __name__ == '__main__':
main()
"
Update TreeBuilder instantiation - fixing 4.3 deprecation,"
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ashley_dawson_simple_pagination');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->arrayNode('defaults')
->addDefaultsIfNotSet()
->children()
->integerNode('items_per_page')->defaultValue(10)->min(1)->isRequired()->end()
->integerNode('pages_in_range')->defaultValue(5)->min(1)->isRequired()->end()
->scalarNode('template')->defaultValue('AshleyDawsonSimplePaginationBundle:Pagination:default.html.twig')->end()
->end()
->end()
;
return $treeBuilder;
}
}
","
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ashley_dawson_simple_pagination');
$rootNode
->children()
->arrayNode('defaults')
->addDefaultsIfNotSet()
->children()
->integerNode('items_per_page')->defaultValue(10)->min(1)->isRequired()->end()
->integerNode('pages_in_range')->defaultValue(5)->min(1)->isRequired()->end()
->scalarNode('template')->defaultValue('AshleyDawsonSimplePaginationBundle:Pagination:default.html.twig')->end()
->end()
->end()
;
return $treeBuilder;
}
}
"
Refactor request mechanics into an internal method on BaseService,"import logging
import requests
from .exceptions import APIError
from .version import __version__
logger = logging.getLogger(__name__)
class BaseService(object):
def __init__(self, api, **config):
self.api = api
self.config = {
'base_url': 'http://data.police.uk/api/',
'user_agent': 'police-api-client-python/%s' % __version__,
}
self.config.update(config)
def raise_for_status(self, request):
try:
request.raise_for_status()
except requests.models.HTTPError as e:
raise APIError(e)
def _make_request(self, verb, url, params={}):
request_kwargs = {
'headers': {
'User-Agent': self.config['user_agent'],
},
'timeout': self.config.get('timeout', 30),
}
if 'username' in self.config:
request_kwargs['auth'] = (self.config.get('username', ''),
self.config.get('password', ''))
if verb == 'GET':
request_kwargs['params'] = params
else:
request_kwargs['data'] = params
logger.debug('%s %s' % (verb, url))
r = requests.request(verb, url, **request_kwargs)
self.raise_for_status(r)
return r.json()
def request(self, verb, method, **kwargs):
url = self.config['base_url'] + method
return self._make_request(verb.upper(), url, kwargs)
","import logging
import requests
from .exceptions import APIError
from .version import __version__
logger = logging.getLogger(__name__)
class BaseService(object):
def __init__(self, api, **config):
self.api = api
self.config = {
'base_url': 'http://data.police.uk/api/',
'user_agent': 'police-api-client-python/%s' % __version__,
}
self.config.update(config)
def raise_for_status(self, request):
try:
request.raise_for_status()
except requests.models.HTTPError as e:
raise APIError(e)
def request(self, verb, method, **kwargs):
verb = verb.upper()
request_kwargs = {
'headers': {
'User-Agent': self.config['user_agent'],
},
'timeout': self.config.get('timeout', 30),
}
if 'username' in self.config:
request_kwargs['auth'] = (self.config.get('username', ''),
self.config.get('password', ''))
if verb == 'GET':
request_kwargs['params'] = kwargs
else:
request_kwargs['data'] = kwargs
url = self.config['base_url'] + method
logger.debug('%s %s' % (verb, url))
r = requests.request(verb, url, **request_kwargs)
self.raise_for_status(r)
return r.json()
"
"Use the README.rst file as the contents for the long_description
This renders a lot better on PyPI: https://pypi.python.org/pypi/charlesbot","from setuptools import setup, find_packages
import codecs
# README into long description
with codecs.open('README.rst', encoding='utf-8') as f:
readme = f.read()
setup(
name='charlesbot',
version='0.10.0',
description='CharlesBOT is a Python bot written to take advantage of Slack\'s Real Time Messaging API',
long_description=readme,
author='Marvin Pinto',
author_email='marvin@pinto.im',
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.4',
],
keywords='slack robot chatops automation',
url=""https://github.com/marvinpinto/charlesbot"",
packages=find_packages(
exclude=[
'Makefile',
'docker',
'images',
'requirements-dev.txt',
'requirements.txt',
'tests'
]
),
entry_points={
'console_scripts': ['charlesbot = charlesbot.__main__:main']
},
install_requires=[
""slackclient"",
""websocket-client"",
""cchardet"",
""aiohttp"",
""PyYAML"",
""aiocron"",
""croniter"",
""python-dateutil"",
],
test_suite='nose.collector'
)
","from setuptools import setup, find_packages
long_description = """"""
Full details available at https://github.com/marvinpinto/charlesbot
""""""
setup(
name='charlesbot',
version='0.10.0',
description='Slack Real Time Messaging robot written in Python 3!',
long_description=long_description,
author='Marvin Pinto',
author_email='marvin@pinto.im',
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.4',
],
keywords='slack robot chatops automation',
url=""https://github.com/marvinpinto/charlesbot"",
packages=find_packages(
exclude=[
'Makefile',
'docker',
'images',
'requirements-dev.txt',
'requirements.txt',
'tests'
]
),
entry_points={
'console_scripts': ['charlesbot = charlesbot.__main__:main']
},
install_requires=[
""slackclient"",
""websocket-client"",
""cchardet"",
""aiohttp"",
""PyYAML"",
""aiocron"",
""croniter"",
""python-dateutil"",
],
test_suite='nose.collector'
)
"
"Make malformed/mismatched manifest.json an infra failure
Summary:
- This was disabled for a while due to problems with phased jobsteps, but
Sentry shows that these errors occasionally still happen, but seem to be
""real"" errors now. Should almost certainly be marked infra failures.
- Also make malformed manifest a warning (and use exc_info=True) since
malformed vs mismatched jobstep id seem like approximately the same severity.
Test Plan:
Sentry indicates these happen rarely and when they do are probably
legitimate infra failures.
Reviewers: paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D152534","from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models import FailureReason
from .base import ArtifactHandler
class ManifestJsonHandler(ArtifactHandler):
""""""
Artifact handler for manifest.json files. Makes sure their contents are valid.
""""""
FILENAMES = ('manifest.json',)
def process(self, fp):
try:
contents = json.load(fp)
if contents['job_step_id'] != self.step.id.hex:
self.logger.warning('manifest.json had wrong step id (build=%s): expected %s but got %s',
self.step.job.build_id.hex, self.step.id.hex, contents['job_step_id'])
self._add_failure_reason()
except Exception:
self.logger.warning('Failed to parse manifest.json; (build=%s, step=%s)',
self.step.job.build_id.hex, self.step.id.hex, exc_info=True)
self._add_failure_reason()
def _add_failure_reason(self):
db.session.add(FailureReason(
step_id=self.step.id,
job_id=self.step.job_id,
build_id=self.step.job.build_id,
project_id=self.step.project_id,
reason='malformed_manifest_json'
))
self.step.result = Result.infra_failed
db.session.add(self.step)
db.session.commit()
","from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models import FailureReason
from .base import ArtifactHandler
class ManifestJsonHandler(ArtifactHandler):
""""""
Artifact handler for manifest.json files. Makes sure their contents are valid.
""""""
FILENAMES = ('manifest.json',)
def process(self, fp):
try:
contents = json.load(fp)
if contents['job_step_id'] != self.step.id.hex:
self.logger.warning('manifest.json had wrong step id (build=%s): expected %s but got %s',
self.step.job.build_id.hex, self.step.id.hex, contents['job_step_id'])
# TODO(nate): temporarily disabled
# self._add_failure_reason()
except Exception:
self.logger.exception('Failed to parse manifest.json; (build=%s, step=%s)',
self.step.job.build_id.hex, self.step.id.hex)
# TODO(nate): temporarily disabled
# self._add_failure_reason()
def _add_failure_reason(self):
db.session.add(FailureReason(
step_id=self.step.id,
job_id=self.step.job_id,
build_id=self.step.job.build_id,
project_id=self.step.project_id,
reason='malformed_manifest_json'
))
self.step.result = Result.infra_failed
db.session.add(self.step)
db.session.commit()
"
"Fix pep8, remove blank line on DetailView","#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
","#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.views.generic.detail import DetailView as DjangoDetailView
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from opps.views.generic.base import View
class DetailView(View, DjangoDetailView):
def get_template_names(self):
templates = []
domain_folder = self.get_template_folder()
templates.append('{}/{}/{}/detail.html'.format(domain_folder,
self.long_slug,
self.slug))
templates.append('{}/{}/detail.html'.format(domain_folder,
self.long_slug))
templates.append('{}/detail.html'.format(domain_folder))
return templates
def get_queryset(self):
self.site = get_current_site(self.request)
self.slug = self.kwargs.get('slug')
self.long_slug = self.get_long_slug()
if not self.long_slug:
return None
self.set_channel_rules()
filters = {}
filters['site_domain'] = self.site.domain
filters['channel_long_slug'] = self.long_slug
filters['slug'] = self.slug
preview_enabled = self.request.user and self.request.user.is_staff
if not preview_enabled:
filters['date_available__lte'] = timezone.now()
filters['published'] = True
queryset = super(DetailView, self).get_queryset()
return queryset.filter(**filters)._clone()
"
Remove trailing slash+hash from refs; fix,"'use strict';
var $ = require('./util/uri-helpers');
$.findByRef = require('./util/find-reference');
$.resolveSchema = require('./util/resolve-schema');
$.normalizeSchema = require('./util/normalize-schema');
var instance = module.exports = function() {
function $ref(fakeroot, schema, refs, ex) {
if (typeof fakeroot === 'object') {
ex = refs;
refs = schema;
schema = fakeroot;
fakeroot = undefined;
}
if (!Array.isArray(refs)) {
ex = !!refs;
refs = [];
}
function push(ref) {
if (typeof ref.id === 'string') {
var id = $.resolveURL(fakeroot, ref.id).replace(/\/#?$/, '');
if (id.indexOf('#') > -1) {
var parts = id.split('#');
if (parts[1].charAt() === '/') {
id = parts[0];
} else {
id = parts[1] || parts[0];
}
}
if (!$ref.refs[id]) {
$ref.refs[id] = ref;
}
}
}
refs.concat([schema]).forEach(function(ref) {
schema = $.normalizeSchema(fakeroot, ref, push);
push(schema);
});
return $.resolveSchema(schema, $ref.refs, ex);
}
$ref.refs = {};
$ref.util = $;
return $ref;
};
instance.util = $;
","'use strict';
var $ = require('./util/uri-helpers');
$.findByRef = require('./util/find-reference');
$.resolveSchema = require('./util/resolve-schema');
$.normalizeSchema = require('./util/normalize-schema');
var instance = module.exports = function() {
function $ref(fakeroot, schema, refs, ex) {
if (typeof fakeroot === 'object') {
ex = refs;
refs = schema;
schema = fakeroot;
fakeroot = undefined;
}
if (!Array.isArray(refs)) {
ex = !!refs;
refs = [];
}
function push(ref) {
if (typeof ref.id === 'string') {
var id = $.resolveURL(fakeroot, ref.id);
if (id.indexOf('#') > -1) {
var parts = id.split('#');
if (parts[1].charAt() === '/') {
id = parts[0];
} else {
id = parts[1] || parts[0];
}
}
if (!$ref.refs[id]) {
$ref.refs[id] = ref;
}
}
}
refs.concat([schema]).forEach(function(ref) {
schema = $.normalizeSchema(fakeroot, ref, push);
push(schema);
});
return $.resolveSchema(schema, $ref.refs, ex);
}
$ref.refs = {};
$ref.util = $;
return $ref;
};
instance.util = $;
"
Fix js bug with checked option,"(function () {
Playlist = function () {
this.key = ""#key"";
this.station = ""#station"";
this.format = "":input[name='optionsRadios']:checked"";
this.download = ""#download"";
this.quality = ""#quality"";
this.registerHandlers();
};
Playlist.prototype.registerHandlers = function () {
var self = this;
$(this.download).click(function (e) {
e.preventDefault();
var url = '/';
url += $(self.station).val() + '/';
url += $(self.quality).val() + '/';
url += $(self.key).val() + '.';
url += $(self.format).val();
window.location = url;
return false;
});
$(this.station).change(function () {
var station = $(self.station).val();
var hq = $(""#quality > option[value='320']"");
if(station === 'difm') {
$(hq).removeAttr('disabled');
}else {
$(hq).attr('disabled', 'disabled');
$(self.quality).val('128');
}
});
};
})();
var playlist = null;
$(document).ready(function () {
playlist = new Playlist();
});","(function () {
Playlist = function () {
this.key = $(""#key"");
this.station = $(""#station"");
this.format = $("":input[name='optionsRadios']:checked"");
this.download = $(""#download"");
this.quality = $(""#quality"");
this.registerHandlers();
};
Playlist.prototype.registerHandlers = function () {
var self = this;
$(this.download).click(function (e) {
e.preventDefault();
var url = '/';
url += $(self.station).val() + '/';
url += $(self.quality).val() + '/';
url += $(self.key).val() + '.';
url += $(self.format).val();
window.location = url;
return false;
});
$(this.station).change(function () {
var station = $(self.station).val();
var hq = $(""#quality > option[value='320']"");
if(station === 'difm') {
$(hq).removeAttr('disabled');
}else {
$(hq).attr('disabled', 'disabled');
$(self.quality).val('128');
}
});
};
})();
var playlist = null;
$(document).ready(function () {
playlist = new Playlist();
});"
"Revert ""Trying direct printing instead of logs""
This reverts commit 92953b6f541fc94e7f4b93d5d8ac1faa8d240ca9.","package org.zalando.nakadi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.HashSet;
import java.util.Set;
public class ShutdownHooks {
private static final Set HOOKS = new HashSet<>();
private static final Logger LOG = LoggerFactory.getLogger(ShutdownHooks.class);
static {
Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHooks::onNodeShutdown));
}
private static void onNodeShutdown() {
LOG.info(""Processing shutdown hooks"");
boolean haveHooks = true;
while (haveHooks) {
final Runnable hook;
synchronized (HOOKS) {
hook = HOOKS.isEmpty() ? null : HOOKS.iterator().next();
HOOKS.remove(hook);
haveHooks = !HOOKS.isEmpty();
}
if (null != hook) {
try {
hook.run();
} catch (final RuntimeException ex) {
LOG.warn(""Failed to call on shutdown hook for {}"", hook, ex);
}
}
}
LOG.info(""Finished processing shutdown hooks"");
}
public static Closeable addHook(final Runnable runnable) {
synchronized (HOOKS) {
HOOKS.add(runnable);
}
return () -> removeHook(runnable);
}
private static void removeHook(final Runnable runnable) {
synchronized (HOOKS) {
HOOKS.remove(runnable);
}
}
}
","package org.zalando.nakadi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.HashSet;
import java.util.Set;
public class ShutdownHooks {
private static final Set HOOKS = new HashSet<>();
private static final Logger LOG = LoggerFactory.getLogger(ShutdownHooks.class);
static {
Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHooks::onNodeShutdown));
}
private static void onNodeShutdown() {
System.out.println(""Processing shutdown hooks"");
boolean haveHooks = true;
while (haveHooks) {
final Runnable hook;
synchronized (HOOKS) {
hook = HOOKS.isEmpty() ? null : HOOKS.iterator().next();
HOOKS.remove(hook);
haveHooks = !HOOKS.isEmpty();
}
if (null != hook) {
try {
hook.run();
} catch (final RuntimeException ex) {
LOG.warn(""Failed to call on shutdown hook for {}"", hook, ex);
}
}
}
System.out.println(""Finished processing shutdown hooks"");
}
public static Closeable addHook(final Runnable runnable) {
synchronized (HOOKS) {
HOOKS.add(runnable);
}
return () -> removeHook(runnable);
}
private static void removeHook(final Runnable runnable) {
synchronized (HOOKS) {
HOOKS.remove(runnable);
}
}
}
"
Update invalid URI to correctly throw exception,"/*
* $Id: AltRepTest.java [23-Apr-2004]
*
* Copyright (c) 2004, Ben Fortuna All rights reserved.
*/
package net.fortuna.ical4j.model.parameter;
import java.net.URI;
import java.net.URISyntaxException;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.ParameterFactoryImpl;
import junit.framework.TestCase;
/**
* Test case for AltRep.
* @author benfortuna
*/
public class AltRepTest extends TestCase {
/*
* Class to test for void AltRep(String)
*/
public void testAltRepString() throws URISyntaxException {
try {
new AltRep("""");
fail(""URISyntaxException not thrown!"");
}
catch (URISyntaxException use) {
// test success.
}
AltRep ar = (AltRep) ParameterFactoryImpl.getInstance().createParameter(Parameter.ALTREP, ""mailto:valid@test.com"");
assertNotNull(ar.getUri());
}
/*
* Class to test for void AltRep(URI)
*/
public void testAltRepURI() throws URISyntaxException {
AltRep ar = new AltRep(new URI(""mailto:valid@test.com""));
assertNotNull(ar.getUri());
}
}
","/*
* $Id: AltRepTest.java [23-Apr-2004]
*
* Copyright (c) 2004, Ben Fortuna All rights reserved.
*/
package net.fortuna.ical4j.model.parameter;
import java.net.URI;
import java.net.URISyntaxException;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.ParameterFactoryImpl;
import junit.framework.TestCase;
/**
* Test case for AltRep.
* @author benfortuna
*/
public class AltRepTest extends TestCase {
/*
* Class to test for void AltRep(String)
*/
public void testAltRepString() throws URISyntaxException {
try {
new AltRep(""::...invalid..."");
fail(""URISyntaxException not thrown!"");
}
catch (URISyntaxException use) {
// test success.
}
AltRep ar = (AltRep) ParameterFactoryImpl.getInstance().createParameter(Parameter.ALTREP, ""mailto:valid@test.com"");
assertNotNull(ar.getUri());
}
/*
* Class to test for void AltRep(URI)
*/
public void testAltRepURI() throws URISyntaxException {
AltRep ar = new AltRep(new URI(""mailto:valid@test.com""));
assertNotNull(ar.getUri());
}
}
"
"Remove the version specifier for Henson
Henson 0.2 doesn't exist.","from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
super().finalize_options()
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
sys.exit(pytest.main(self.test_args))
def read(filename):
with open(filename) as f:
return f.read()
setup(
name='Henson-Logging',
version='0.3.0',
author='Andy Dirnberger, Jon Banafato, and others',
author_email='henson@iheart.com',
url='https://henson-logging.rtfd.org',
description='A library to use structured logging with a Henson application.',
long_description=read('README.rst'),
license='Apache License, Version 2.0',
packages=find_packages(exclude=['tests']),
zip_safe=False,
install_requires=[
'Henson',
'structlog',
],
tests_require=[
'pytest',
],
cmdclass={
'test': PyTest,
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Software Development :: Libraries :: Application Frameworks',
]
)
","from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
super().finalize_options()
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
sys.exit(pytest.main(self.test_args))
def read(filename):
with open(filename) as f:
return f.read()
setup(
name='Henson-Logging',
version='0.3.0',
author='Andy Dirnberger, Jon Banafato, and others',
author_email='henson@iheart.com',
url='https://henson-logging.rtfd.org',
description='A library to use structured logging with a Henson application.',
long_description=read('README.rst'),
license='Apache License, Version 2.0',
packages=find_packages(exclude=['tests']),
zip_safe=False,
install_requires=[
'Henson>=0.2.0',
'structlog',
],
tests_require=[
'pytest',
],
cmdclass={
'test': PyTest,
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Software Development :: Libraries :: Application Frameworks',
]
)
"
Fix bug in word generator,"class Dice extends React.Component {
constructor() {
super();
this.state = {
words: this.parseInput(decodeURIComponent(location.search.substring(5))),
div: document.createElement(""div"")
};
this.handleSubmit = this.handleSubmit.bind(this);
}
parseInput(input) {
return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
}
image(word) {
}
appendWord(text) {
var p = document.createElement(""p"");
p.appendChild(document.createTextNode(text));
return p;
}
appendImg(src) {
var img = document.createElement(""img"");
img.className = 'img';
img.src = random;
}
handleSubmit() {
var div = this.state.div;
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
var words = this.state.words;
for(var i = 0; i < words.length; i++) {
var random = words[i][Math.floor(Math.random()*(words[i].length-1))];
if (this.image(random)) {
div.appendChild(this.appendImg(random));
}
else {
div.appendChild(this.appendWord(random));
}
}
document.body.appendChild(div);
}
render() {
return (
);
}
}
ReactDOM.render(
,
document.getElementById('root')
);","class Dice extends React.Component {
constructor() {
super();
this.state = {
words: this.parseInput(decodeURIComponent(location.search.substring(5))),
div: document.createElement(""div"")
};
this.handleSubmit = this.handleSubmit.bind(this);
}
parseInput(input) {
return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
}
image(word) {
}
appendWord(text) {
var p = document.createElement(""p"");
p.appendChild(document.createTextNode(text));
return p;
}
appendImg(src) {
var img = document.createElement(""img"");
img.className = 'img';
img.src = random;
}
handleSubmit() {
var div = this.state.div;
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
var words = this.state.words;
for(var i = 0; i < words.length; i++) {
var random = words[i][Math.floor(Math.random()*(words.length-1))];
if (this.image(random)) {
div.appendChild(this.appendImg(random));
}
else {
div.appendChild(this.appendWord(random));
}
}
document.body.appendChild(div);
}
render() {
return (
);
}
}
ReactDOM.render(
,
document.getElementById('root')
);"
[preview] Set subscription to null after unsubscribe,"import React, {PropTypes} from 'react'
import observeForPreview from './observeForPreview'
import shallowEquals from 'shallow-equals'
export default class PreviewMaterializer extends React.PureComponent {
static propTypes = {
value: PropTypes.any.isRequired,
type: PropTypes.shape({
preview: PropTypes.shape({
select: PropTypes.object.isRequired,
prepare: PropTypes.func
}).isRequired
}),
children: PropTypes.func
};
state = {
loading: false,
error: null,
result: null
}
componentWillMount() {
const {type, value} = this.props
this.materialize(value, type)
}
componentWillUnmount() {
this.unsubscribe()
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
this.subscription = null
}
}
componentWillReceiveProps(nextProps) {
if (!shallowEquals(nextProps.value, this.props.value)) {
this.materialize(nextProps.value, nextProps.type)
}
}
materialize(value, type) {
this.unsubscribe()
this.subscription = observeForPreview(value, type)
.subscribe(res => {
this.setState({result: res})
})
}
render() {
const {result, loading, error} = this.state
if (loading) {
return Loading…
}
if (error) {
return Error: {error.message}
}
if (!result) {
return
}
return this.props.children(result)
}
}
","import React, {PropTypes} from 'react'
import observeForPreview from './observeForPreview'
import shallowEquals from 'shallow-equals'
export default class PreviewMaterializer extends React.PureComponent {
static propTypes = {
value: PropTypes.any.isRequired,
type: PropTypes.shape({
preview: PropTypes.shape({
select: PropTypes.object.isRequired,
prepare: PropTypes.func
}).isRequired
}),
children: PropTypes.func
};
state = {
loading: false,
error: null,
result: null
}
componentWillMount() {
const {type, value} = this.props
this.materialize(value, type)
}
componentWillUnmount() {
this.unsubscribe()
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
}
}
componentWillReceiveProps(nextProps) {
if (!shallowEquals(nextProps.value, this.props.value)) {
this.materialize(nextProps.value, nextProps.type)
}
}
materialize(value, type) {
this.unsubscribe()
this.subscription = observeForPreview(value, type)
.subscribe(res => {
this.setState({result: res})
})
}
render() {
const {result, loading, error} = this.state
if (loading) {
return Loading…
}
if (error) {
return Error: {error.message}
}
if (!result) {
return
}
return this.props.children(result)
}
}
"
Clean up some unused imports and comments,"from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
import numpy as np
import json
import sys
from analyze import Analyzer # for some train data labelling
def main(argv):
group = argv[0] if len(argv) > 0 else ""id""
train_size = int(argv[1]) if len(argv) > 1 else 1000
train_data = []
train_labels = []
analyzer = Analyzer(group)
for message, _ in analyzer.read_json(sys.stdin):
label = analyzer.analyze(message)[0]
train_data.append(message)
train_labels.append(label)
if len(train_data) >= train_size:
break
regressor = Pipeline([
('tfidf', TfidfVectorizer(input='content')),
('clf', RandomForestRegressor())
])
regressor.fit(train_data, train_labels)
for message, group in analyzer.read_json(sys.stdin):
# Call predict for every message which might be slow in practice but
# avoids memory hog due to not being able to use iterators if done in
# one batch.
prediction = regressor.predict([message])[0]
if analyzer.display:
# Take the color for this group of predictions
c = cmp(prediction, 0)
message = analyzer.colors[c] + message + analyzer.END_COLOR
analyzer.output(group, message, prediction, """")
if __name__ == ""__main__"":
main(sys.argv[1:])
","from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
import numpy as np
import json
import sys
import time
from analyze import Analyzer # for some train data labelling
def main(argv):
group = argv[0] if len(argv) > 0 else ""id""
train_size = int(argv[1]) if len(argv) > 1 else 1000
train_data = []
train_labels = []
analyzer = Analyzer(group)
for message, _ in analyzer.read_json(sys.stdin):
label = analyzer.analyze(message)[0]
train_data.append(message)
train_labels.append(label)
if len(train_data) >= train_size:
break
regressor = Pipeline([
('tfidf', TfidfVectorizer(input='content')),
('clf', RandomForestRegressor())
#('clf', KNeighborsRegressor())
])
regressor.fit(train_data, train_labels)
for message, group in analyzer.read_json(sys.stdin):
# Call predict for every message which might be slow in practice but
# avoids memory hog due to not being able to use iterators if done in
# one batch.
prediction = regressor.predict([message])[0]
if analyzer.display:
# Take the color for this group of predictions
c = cmp(prediction, 0)
message = analyzer.colors[c] + message + analyzer.END_COLOR
analyzer.output(group, message, prediction, """")
if __name__ == ""__main__"":
main(sys.argv[1:])
"
Fix na rota dos testes,"# coding: utf-8
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APIClient
class TestAPIViews(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.client = APIClient()
self.user = User.objects.create_user('testuser@test.com', password='testing')
self.user.save()
self.token = Token.objects.filter(user=self.user)
def _require_login(self):
self.client.login(username='testuser', password='testing')
def test_login_account(self):
""""""
Testa o login com um usuario de testes.
""""""
response = self.client.post(path='/v1/rest-auth/login/', data={""username"": 'testuser@test.com', ""password"": 'testing'}, format='json')
self.assertEqual(response.status_code, 200, 'Expected Response Code 200, received {0} instead.'.format(response.status_code))
def test_login_account_fail(self):
""""""
Testa o login nao autorizado com um usuario de testes.
""""""
response = self.client.post('/v1/rest-auth/login/',
{""username"": 'testuser@test.com', ""password"": 'testings'},
format='json')
self.assertEqual(response.status_code, 400,
'Expected Response Code 400, received {0} instead.'.format(response.status_code))
","# coding: utf-8
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APIClient
class TestAPIViews(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.client = APIClient()
self.user = User.objects.create_user('testuser@test.com', password='testing')
self.user.save()
self.token = Token.objects.filter(user=self.user)
def _require_login(self):
self.client.login(username='testuser', password='testing')
def test_login_account(self):
""""""
Testa o login com um usuario de testes.
""""""
response = self.client.post(path='/rest-auth/login/', data={""username"": 'testuser@test.com', ""password"": 'testing'}, format='json')
self.assertEqual(response.status_code, 200, 'Expected Response Code 200, received {0} instead.'.format(response.status_code))
def test_login_account_fail(self):
""""""
Testa o login nao autorizado com um usuario de testes.
""""""
response = self.client.post('/rest-auth/login/',
{""username"": 'testuser@test.com', ""password"": 'testings'},
format='json')
self.assertEqual(response.status_code, 400,
'Expected Response Code 400, received {0} instead.'.format(response.status_code))
"
"Fix Editor Save Button not allowing unpublish
Closes #2918","/* global console */
var EditorControllerMixin = Ember.Mixin.create({
//## Computed post properties
isPublished: Ember.computed.equal('status', 'published'),
isDraft: Ember.computed.equal('status', 'draft'),
/**
* By default, a post will not change its publish state.
* Only with a user-set value (via setSaveType action)
* can the post's status change.
*/
willPublish: function (key, value) {
if (arguments.length > 1) {
return value;
}
return this.get('isPublished');
}.property('isPublished'),
actions: {
save: function () {
var status = this.get('willPublish') ? 'published' : 'draft',
self = this;
this.set('status', status);
this.get('model').save().then(function () {
console.log('saved');
self.notifications.showSuccess('Post status saved as ' +
self.get('status') + '.');
}, this.notifications.showErrors);
},
setSaveType: function (newType) {
if (newType === 'publish') {
this.set('willPublish', true);
} else if (newType === 'draft') {
this.set('willPublish', false);
} else {
console.warn('Received invalid save type; ignoring.');
}
}
}
});
export default EditorControllerMixin;
","/* global console */
var EditorControllerMixin = Ember.Mixin.create({
//## Computed post properties
isPublished: Ember.computed.equal('status', 'published'),
isDraft: Ember.computed.equal('status', 'draft'),
/**
* By default, a post will not change its publish state.
* Only with a user-set value (via setSaveType action)
* can the post's status change.
*/
willPublish: function (key, val) {
if (val) {
return val;
}
return this.get('isPublished');
}.property('isPublished'),
actions: {
save: function () {
var status = this.get('willPublish') ? 'published' : 'draft',
self = this;
this.set('status', status);
this.get('model').save().then(function () {
console.log('saved');
self.notifications.showSuccess('Post status saved as ' +
self.get('status') + '.');
}, this.notifications.showErrors);
},
setSaveType: function (newType) {
if (newType === 'publish') {
this.set('willPublish', true);
} else if (newType === 'draft') {
this.set('willPublish', false);
} else {
console.warn('Received invalid save type; ignoring.');
}
}
}
});
export default EditorControllerMixin;
"
Add CAS user checking to prevent less-than-useful generic error from phpCAS,"@extends('layouts/app')
@section('title')
Error | {{ config('app.name') }}
@endsection
@section('content')
@component('layouts/title')
Whoops!
@endcomponent
Something went wrong. Please try your request again later. If you continue to receive this error,
please contact #it-helpdesk on
Slack.
Code: {{ $error_code }}
Message: {{ $error_message }}
@if(cas()->checkAuthentication())
User: {{ cas()->user() }}
@endif
Time: {{ time() }}
@endsection","@extends('layouts/app')
@section('title')
Error | {{ config('app.name') }}
@endsection
@section('content')
@component('layouts/title')
Whoops!
@endcomponent
Something went wrong. Please try your request again later. If you continue to receive this error,
please contact #it-helpdesk on
Slack.
Code: {{ $error_code }}
Message: {{ $error_message }}
User: {{ cas()->user() }}
Time: {{ time() }}
@endsection"
Extend heat map with better color scale.,"package flg.rendering;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class HeatMap
extends JPanel {
private static final long serialVersionUID = 1L;
public final static int PIXEL_SIZE = 3;
private float[][] heights;
public HeatMap(float[][] heights) {
super();
this.heights = heights;
}
@Override
public void paint(Graphics g) {
// draw the grid
for (int i = 0; i < this.heights[0].length; i++) {
for (int j = 0; j < this.heights[i].length; j++) {
float height = this.heights[i][j];
if (height <= -2) {
g.setColor(Color.decode(""#06109a"")); // dark blue
} else if (height > -2 && height <= -1.5) {
g.setColor(Color.decode(""#414df6"")); // brighter blue
} else if (height > -1.5 && height <= 0.5) {
g.setColor(Color.decode(""#10b223"")); // dark green
} else if (height > 0.5 && height <= 1.6) {
g.setColor(Color.decode(""#2eea1c"")); // brighter green
} else if (height > 1.6 && height <= 2.75) {
g.setColor(Color.GRAY);
} else if (height > 2.75) {
g.setColor(Color.WHITE);
}
int x = PIXEL_SIZE * i;
int y = PIXEL_SIZE * j;
g.fillRect(x, y, PIXEL_SIZE, PIXEL_SIZE);
}
}
}
}
","package flg.rendering;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class HeatMap
extends JPanel {
private static final long serialVersionUID = 1L;
public final static int PIXEL_SIZE = 5;
private float[][] heights;
public HeatMap(float[][] heights) {
super();
this.heights = heights;
}
@Override
public void paint(Graphics g) {
// draw the grid
for (int i = 0; i < this.heights[0].length; i++) {
for (int j = 0; j < this.heights[i].length; j++) {
float height = this.heights[i][j];
if (height <= -2) {
g.setColor(Color.BLUE);
} else if (height > -2 && height < 2) {
g.setColor(Color.GREEN);
} else if (height >= 2) {
g.setColor(Color.WHITE);
}
int x = PIXEL_SIZE * i;
int y = PIXEL_SIZE * j;
g.fillRect(x, y, PIXEL_SIZE, PIXEL_SIZE);
}
}
}
}
"
Handle null returns from client constructor,"package com.yubico.client.v2;
/**
* Created by IntelliJ IDEA.
* User: lwid
* Date: 1/28/11
* Time: 2:07 PM
* To change this template use File | Settings | File Templates.
*/
public class Cmd {
public static void main (String args []) throws Exception
{
if (args.length != 2) {
System.err.println(""\n*** Test your Yubikey against Yubico OTP validation server ***"");
System.err.println(""\nUsage: java -jar client.jar Auth_ID OTP"");
System.err.println(""\nEg. java -jar client.jar 28 vvfucnlcrrnejlbuthlktguhclhvegbungldcrefbnku"");
System.err.println(""\nTouch Yubikey to generate the OTP. Visit Yubico.com for more details."");
return;
}
int authId = Integer.parseInt(args[0]);
String otp = args[1];
YubicoClient yc = YubicoClient.getClient();
yc.setClientId(authId);
YubicoResponse response = yc.verify(otp);
if(response!=null && response.getStatus() == YubicoResponseStatus.OK) {
System.out.println(""\n* OTP verified OK"");
} else {
System.out.println(""\n* Failed to verify OTP"");
}
System.out.println(""\n* Last response: "" + response);
System.out.println(""\n"");
} // End of main
}
","package com.yubico.client.v2;
/**
* Created by IntelliJ IDEA.
* User: lwid
* Date: 1/28/11
* Time: 2:07 PM
* To change this template use File | Settings | File Templates.
*/
public class Cmd {
public static void main (String args []) throws Exception
{
if (args.length != 2) {
System.err.println(""\n*** Test your Yubikey against Yubico OTP validation server ***"");
System.err.println(""\nUsage: java -jar client.jar Auth_ID OTP"");
System.err.println(""\nEg. java -jar client.jar 28 vvfucnlcrrnejlbuthlktguhclhvegbungldcrefbnku"");
System.err.println(""\nTouch Yubikey to generate the OTP. Visit Yubico.com for more details."");
return;
}
int authId = Integer.parseInt(args[0]);
String otp = args[1];
YubicoClient yc = YubicoClient.getClient();
yc.setClientId(authId);
YubicoResponse response = yc.verify(otp);
if(response.getStatus() == YubicoResponseStatus.OK) {
System.out.println(""\n* OTP verified OK"");
} else {
System.out.println(""\n* Failed to verify OTP"");
}
System.out.println(""\n* Last response: "" + response);
System.out.println(""\n"");
} // End of main
}
"
"Revert ""fix: wah, typo - correct order for subtraction""
This reverts commit 2bf8308d058dd4d951ca38e49d58098074070591.
stop being stupid!","/* -*- coding: utf-8 -*- */
/* global cforum, Highcharts, t */
cforum.admin.jobs = {
jobsCount: null,
index: function() {
Highcharts.setOptions({
lang: t('highcharts')
});
var keys = cforum.admin.jobs.jobsCount.sort(function(a,b) {
var a_date = new Date(a.day);
var b_date = new Date(b.day);
return a_date.getTime() - b_date.getTime();
});
$(""#chart"").highcharts({
chart: { type: 'spline' },
title: null,
xAxis: {
categories: $.map(keys,
function(val, i) {
return Highcharts.dateFormat(""%A, %d. %B %Y"",
new Date(val.day));
})
},
yAxis: { title: { text: t('highcharts.cnt_jobs') } },
series: [{
name: t('highcharts.jobs'),
data: $.map(keys, function(val, i) { return val.cnt; })
}]
});
}
};
/* eof */
","/* -*- coding: utf-8 -*- */
/* global cforum, Highcharts, t */
cforum.admin.jobs = {
jobsCount: null,
index: function() {
Highcharts.setOptions({
lang: t('highcharts')
});
var keys = cforum.admin.jobs.jobsCount.sort(function(a,b) {
var a_date = new Date(a.day);
var b_date = new Date(b.day);
return b_date.getTime() - a_date.getTime();
});
$(""#chart"").highcharts({
chart: { type: 'spline' },
title: null,
xAxis: {
categories: $.map(keys,
function(val, i) {
return Highcharts.dateFormat(""%A, %d. %B %Y"",
new Date(val.day));
})
},
yAxis: { title: { text: t('highcharts.cnt_jobs') } },
series: [{
name: t('highcharts.jobs'),
data: $.map(keys, function(val, i) { return val.cnt; })
}]
});
}
};
/* eof */
"
Fix testing expected exception in php 5.4,"value('phpcpd.minLines'), is(greaterThan(0)));
assertThat($config->value('phpcpd.minTokens'), is(greaterThan(0)));
assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
assertThat($config->path('phpmd.standard'), is(nonEmptyString()));
}
public function testBuildAbsolutePath()
{
$config = new Config();
assertThat($config->path('phpmd.standard'), not(startsWith('app/')));
}
public function testOverrideDefaultConfig()
{
$config = new Config();
$config->loadCustomConfig(__DIR__);
assertThat($config->value('phpcpd.minLines'), is(5));
assertThat($config->value('phpcpd.minTokens'), is(70));
assertThat($config->value('phpcs.standard'), is('Zend'));
assertThat($config->path('phpmd.standard'), is(__DIR__ . ""/my-standard.xml""));
}
public function testIgnoreNonExistenConfig()
{
$directoryWithoutConfig = __DIR__ . '/../';
$config = new Config();
$config->loadCustomConfig($directoryWithoutConfig);
assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
}
public function testThrowExceptionWhenFileDoesNotExist()
{
$config = new Config();
$config->loadCustomConfig(__DIR__);
$this->setExpectedException('Exception');
$config->path('phpcs.standard');
}
}
","value('phpcpd.minLines'), is(greaterThan(0)));
assertThat($config->value('phpcpd.minTokens'), is(greaterThan(0)));
assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
assertThat($config->path('phpmd.standard'), is(nonEmptyString()));
}
public function testBuildAbsolutePath()
{
$config = new Config();
assertThat($config->path('phpmd.standard'), not(startsWith('app/')));
}
public function testOverrideDefaultConfig()
{
$config = new Config();
$config->loadCustomConfig(__DIR__);
assertThat($config->value('phpcpd.minLines'), is(5));
assertThat($config->value('phpcpd.minTokens'), is(70));
assertThat($config->value('phpcs.standard'), is('Zend'));
assertThat($config->path('phpmd.standard'), is(__DIR__ . ""/my-standard.xml""));
}
public function testIgnoreNonExistenConfig()
{
$directoryWithoutConfig = __DIR__ . '/../';
$config = new Config();
$config->loadCustomConfig($directoryWithoutConfig);
assertThat($config->value('phpcs.standard'), is(nonEmptyString()));
}
public function testThrowExceptionWhenFileDoesNotExist()
{
$config = new Config();
$config->loadCustomConfig(__DIR__);
$this->setExpectedException(\Exception::class);
$config->path('phpcs.standard');
}
}
"
Fix bad English message for pagination,"export default {
aor: {
action: {
delete: 'Delete',
show: 'Show',
list: 'List',
save: 'Save',
create: 'Create',
edit: 'Edit',
cancel: 'Cancel',
refresh: 'Refresh',
add_filter: 'Add filter',
delete_item: 'Delete %{name}',
create_item: 'Create %{name}',
list_item: '%{name} List',
},
message: {
yes: 'Yes',
no: 'No',
are_you_sure: 'Are you sure ?',
about: 'About',
},
navigation: {
page_out_of_boundaries: 'Page number %{page} out of boundaries',
page_out_from_end: 'Cannot go after last page',
page_out_from_begin: 'Cannot go before page 1',
page_range_info: '%{offsetBegin}-%{offsetEnd} of %{total}',
next: 'Next',
prev: 'Prev',
},
notification: {
updated: 'Element updated',
created: 'Element created',
deleted: 'Element deleted',
item_doesnt_exist: 'Element does not exist',
},
},
};
","export default {
aor: {
action: {
delete: 'Delete',
show: 'Show',
list: 'List',
save: 'Save',
create: 'Create',
edit: 'Edit',
cancel: 'Cancel',
refresh: 'Refresh',
add_filter: 'Add filter',
delete_item: 'Delete %{name}',
create_item: 'Create %{name}',
list_item: '%{name} List',
},
message: {
yes: 'Yes',
no: 'No',
are_you_sure: 'Are you sure ?',
about: 'About',
},
navigation: {
page_out_of_boundaries: 'Page number %{page} out of boundaries',
page_out_from_end: 'Cannot after last page',
page_out_from_begin: 'Cannot go before page 1',
page_range_info: '%{offsetBegin}-%{offsetEnd} of %{total}',
next: 'Next',
prev: 'Prev',
},
notification: {
updated: 'Element updated',
created: 'Element created',
deleted: 'Element deleted',
item_doesnt_exist: 'Element does not exist',
},
},
};
"
Add db index on field tag name,"# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from opps.core.models import Date, Slugged
class Tag(Date, Slugged):
name = models.CharField(_(u'Name'), max_length=255, unique=True,
db_index=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tag, self).save(*args, **kwargs)
__unicode__ = lambda self: self.name
class Meta:
verbose_name = _(u'Tag')
verbose_name_plural = _(u'Tags')
unique_together = ['slug', 'name']
class Tagged(models.Model):
tags = models.CharField(_(u'Tags'), max_length=4000, db_index=True,
blank=True, null=True,
help_text=_(u'A comma-separated list of tags.'))
def save(self, *args, **kwargs):
if self.tags:
tags = set(self.tags.split(','))
for tag in tags:
Tag.objects.get_or_create(name=tag)
self.tags = ','.join(tags)
super(Tagged, self).save(*args, **kwargs)
def get_tags(self):
if self.tags:
tags = []
for tag in self.tags.aplit(','):
t, created = Tag.objects.get_or_create(name=tag)
tags.append(t)
return tags
class Meta:
abstract = True
","# -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from opps.core.models import Date, Slugged
class Tag(Date, Slugged):
name = models.CharField(_(u'Name'), max_length=255, unique=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Tag, self).save(*args, **kwargs)
__unicode__ = lambda self: self.name
class Meta:
verbose_name = _(u'Tag')
verbose_name_plural = _(u'Tags')
class Tagged(models.Model):
tags = models.CharField(_(u'Tags'), max_length=4000, blank=True,
help_text=_(u'A comma-separated list of tags.'))
def save(self, *args, **kwargs):
if self.tags:
tags = set(self.tags.split(','))
for tag in tags:
Tag.objects.get_or_create(name=tag)
self.tags = ','.join(tags)
super(Tagged, self).save(*args, **kwargs)
def get_tags(self):
if self.tags:
tags = []
for tag in self.tags.aplit(','):
t, created = Tag.objects.get_or_create(name=tag)
tags.append(t)
return tags
class Meta:
abstract = True
"
"Fix an issue with the email notifier
Incorrect body format assumptions in the email notifier","# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import pprint
from django.utils.encoding import smart_text
from django.core.mail.backends.smtp import EmailBackend
class CustomEmailBackend(EmailBackend):
init_parameters = {""host"": {""label"": ""Host"", ""type"": ""string""},
""port"": {""label"": ""Port"", ""type"": ""int""},
""username"": {""label"": ""Username"", ""type"": ""string""},
""password"": {""label"": ""Password"", ""type"": ""password""},
""use_tls"": {""label"": ""Use TLS"", ""type"": ""bool""},
""use_ssl"": {""label"": ""Use SSL"", ""type"": ""bool""},
""sender"": {""label"": ""Sender Email"", ""type"": ""string""},
""recipients"": {""label"": ""Recipient List"", ""type"": ""list""}}
recipient_parameter = ""recipients""
sender_parameter = ""sender""
def format_body(self, body):
if ""body"" in body:
body_actual = body['body']
else:
body_actual = smart_text(""{} #{} had status {} on Ansible Tower, view details at {}\n\n"".format(body['friendly_name'],
body['id'],
body['status'],
body['url']))
body_actual += pprint.pformat(body, indent=4)
return body_actual
","# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import pprint
from django.utils.encoding import smart_text
from django.core.mail.backends.smtp import EmailBackend
class CustomEmailBackend(EmailBackend):
init_parameters = {""host"": {""label"": ""Host"", ""type"": ""string""},
""port"": {""label"": ""Port"", ""type"": ""int""},
""username"": {""label"": ""Username"", ""type"": ""string""},
""password"": {""label"": ""Password"", ""type"": ""password""},
""use_tls"": {""label"": ""Use TLS"", ""type"": ""bool""},
""use_ssl"": {""label"": ""Use SSL"", ""type"": ""bool""},
""sender"": {""label"": ""Sender Email"", ""type"": ""string""},
""recipients"": {""label"": ""Recipient List"", ""type"": ""list""}}
recipient_parameter = ""recipients""
sender_parameter = ""sender""
def format_body(self, body):
body_actual = smart_text(""{} #{} had status {} on Ansible Tower, view details at {}\n\n"".format(body['friendly_name'],
body['id'],
body['status'],
body['url']))
body_actual += pprint.pformat(body, indent=4)
return body_actual
"
Fix bundle arguments for latest browserify,"var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ lazy: false });
var source = require('vinyl-source-stream2');
var browserify = require('browserify');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('test', function() {
return gulp.src('test/**/*.test.js', { read: false })
.pipe($.mocha({
reporter: 'mocha-better-spec-reporter'
}));
});
gulp.task('script', function () {
var bundleStream = browserify({
entries: './lib/should.js',
builtins: ['util', 'assert'],
insertGlobals: false,
detectGlobals: false,
standalone: 'Should'
})
.bundle();
return bundleStream
.pipe(source('should.js'))
.pipe($.header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./'))
.pipe($.uglify())
.pipe($.header(banner, { pkg : pkg } ))
.pipe($.rename('should.min.js'))
.pipe(gulp.dest('./'));
});
","var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ lazy: false });
var source = require('vinyl-source-stream2');
var browserify = require('browserify');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('test', function() {
return gulp.src('test/**/*.test.js', { read: false })
.pipe($.mocha({
reporter: 'mocha-better-spec-reporter'
}));
});
gulp.task('script', function () {
var bundleStream = browserify({
entries: './lib/should.js',
builtins: ['util', 'assert']
})
.bundle({
insertGlobals: false,
detectGlobals: false,
standalone: 'Should'
});
return bundleStream
.pipe(source('should.js'))
.pipe($.header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./'))
.pipe($.uglify())
.pipe($.header(banner, { pkg : pkg } ))
.pipe($.rename('should.min.js'))
.pipe(gulp.dest('./'));
});"
Use normalizer to override unset 'class' attr on html step type,"
* @license: MIT
*/
namespace IDCI\Bundle\StepBundle\Step\Type\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\OptionsResolver\Options;
class HtmlStepFormType extends AbstractStepFormType
{
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
parent::buildView($view, $form, $options);
$content = $options['content'];
if (null !== $form->getData('content')) {
$content = $form->getData('content');
}
$view->vars = array_merge($view->vars, array(
'content' => $content,
));
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
parent::setDefaultOptions($resolver);
$resolver
->setDefaults(array(
'content' => null,
))
->setAllowedTypes(array('content' => array('null', 'string')))
->setNormalizers(array(
'attr' => function (Options $options, $value) {
if (!isset($value['class'])) {
$value['class'] = 'html_text';
}
return $value;
}
))
;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'idci_step_step_form_html';
}
}","
* @license: MIT
*/
namespace IDCI\Bundle\StepBundle\Step\Type\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class HtmlStepFormType extends AbstractStepFormType
{
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
parent::buildView($view, $form, $options);
$content = $options['content'];
if (null !== $form->getData('content')) {
$content = $form->getData('content');
}
$view->vars = array_merge($view->vars, array(
'content' => $content,
));
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
parent::setDefaultOptions($resolver);
$resolver
->setDefaults(array(
'content' => null,
'attr' => array('class' => 'html_text'),
))
->setAllowedTypes(array('content' => array('null', 'string')))
;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'idci_step_step_form_html';
}
}"
Adjust linting rules: allow desctructured unused vars,"module.exports = {
""env"": {
""browser"": true,
""es6"": true
},
""extends"": ""eslint:recommended"",
""globals"": {
""__BROWSER__"": true,
""__dirname"": true,
""__x"": true,
""global"": true,
""module"": true,
""process"": true,
""require"": true,
""Buffer"": true,
""DocumentTouch"": true
},
""parserOptions"": {
""ecmaFeatures"": {
""experimentalObjectRestSpread"": true,
""jsx"": true
},
""sourceType"": ""module""
},
""plugins"": [
""react""
],
""rules"": {
""eol-last"": [
""error"",
""always""
],
""indent"": [
""error"",
4,
{
""SwitchCase"": 1
}
],
""linebreak-style"": [
""error"",
""unix""
],
""no-case-declarations"": [
0
],
""no-empty"": [
""error"",
{
""allowEmptyCatch"": true
}
],
""no-unused-vars"": [
""error"",
{
""vars"": ""all"",
""args"": ""after-used"",
""ignoreRestSiblings"": true
}
],
""quotes"": [
""error"",
""single""
],
""semi"": [
""error"",
""never""
]
}
};
","module.exports = {
""env"": {
""browser"": true,
""es6"": true
},
""extends"": ""eslint:recommended"",
""globals"": {
""__BROWSER__"": true,
""__dirname"": true,
""__x"": true,
""global"": true,
""module"": true,
""process"": true,
""require"": true,
""Buffer"": true,
""DocumentTouch"": true
},
""parserOptions"": {
""ecmaFeatures"": {
""experimentalObjectRestSpread"": true,
""jsx"": true
},
""sourceType"": ""module""
},
""plugins"": [
""react""
],
""rules"": {
""eol-last"": [
""error"",
""always""
],
""indent"": [
""error"",
4,
{
""SwitchCase"": 1
}
],
""linebreak-style"": [
""error"",
""unix""
],
""no-case-declarations"": [
0
],
""no-empty"": [
""error"",
{
""allowEmptyCatch"": true
}
],
""quotes"": [
""error"",
""single""
],
""semi"": [
""error"",
""never""
]
}
};
"
Rename Elasticsearch to match the actual name,"from elasticsearch import Elasticsearch
# Find the stack on which we want to store the database connection.
# Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
class FlaskElasticsearch(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('ELASTICSEARCH_HOST', 'localhost:9200')
app.config.setdefault('ELASTICSEARCH_HTTP_AUTH', None)
# Use the newstyle teardown_appcontext if it's available,
# otherwise fall back to the request context
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.teardown)
else:
app.teardown_request(self.teardown)
def __getattr__(self, item):
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'elasticsearch'):
ctx.elasticsearch = Elasticsearch(hosts=[ctx.app.config.get('ELASTICSEARCH_HOST')],
http_auth=ctx.app.config.get('ELASTICSEARCH_HTTP_AUTH'))
return getattr(ctx.elasticsearch, item)
def teardown(self, exception):
ctx = stack.top
if hasattr(ctx, 'elasticsearch'):
ctx.elasticsearch = None
","from elasticsearch import Elasticsearch
# Find the stack on which we want to store the database connection.
# Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
class FlaskElasticSearch(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('ELASTICSEARCH_HOST', 'localhost:9200')
app.config.setdefault('ELASTICSEARCH_HTTP_AUTH', None)
# Use the newstyle teardown_appcontext if it's available,
# otherwise fall back to the request context
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.teardown)
else:
app.teardown_request(self.teardown)
def __getattr__(self, item):
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'elasticsearch'):
ctx.elasticsearch = Elasticsearch(hosts=[ctx.app.config.get('ELASTICSEARCH_HOST')],
http_auth=ctx.app.config.get('ELASTICSEARCH_HTTP_AUTH'))
return getattr(ctx.elasticsearch, item)
def teardown(self, exception):
ctx = stack.top
if hasattr(ctx, 'elasticsearch'):
ctx.elasticsearch = None
"
"Fix lead filter by status
Fix #19","search;
if ($request->country_id) {
$filters['country_id'] = $request->country_id;
$data['country_id'] = $request->country_id;
}
if ($request->seller_id) {
$filters['seller_id'] = $request->seller_id;
}
if ($request->status) {
$filter['status'] = $request->status;
}
$lead = new Lead();
$data['countries'] = Country::orderBy('name')->get();
$data['leads'] = $lead->getAllByCompanyId(Auth::user()->company_id, $search, $filters);
$data['search'] = $search;
$data['sellers'] = $user->getAllActiveByCompany(Auth::user()->company_id);
$data['statuses'] = $lead->getStatus();
return view('lead.index', $data);
}
}
","search;
if ($request->country_id) {
$filters['country_id'] = $request->country_id;
$data['country_id'] = $request->country_id;
}
if ($request->seller_id) {
$filters['seller_id'] = $request->seller_id;
}
$lead = new Lead();
$data['countries'] = Country::orderBy('name')->get();
$data['leads'] = $lead->getAllByCompanyId(Auth::user()->company_id, $search, $filters);
$data['search'] = $search;
$data['sellers'] = $user->getAllActiveByCompany(Auth::user()->company_id);
$data['statuses'] = $lead->getStatus();
return view('lead.index', $data);
}
}
"
Change the prefix from features/ to feature/.,"import sys
import click
from slugify import slugify
class SlugBranchGetter(object):
prefix = 'feature/'
def __init__(self, base_branch='master'):
self.base_branch = base_branch
def __call__(self, repo, issue):
discriminator = '{}{}'.format(self.prefix, issue.key)
slug = slugify(issue.fields.summary[:30])
full_name = '{}_{}'.format(discriminator, slug)
branches = [b for b in repo.listall_branches()
if b.startswith(discriminator)]
if len(branches) > 1:
click.secho('Multiple matching branches found!',
fg='red', bold=True)
click.echo()
click.echo('The prefix {} matched the following branches:'
.format(discriminator))
click.echo()
for b in branches:
click.echo(' {} {}'.format(click.style('*', fg='red'), b))
click.echo()
click.echo('Please remove all but one in order to continue.')
sys.exit(1)
elif branches:
branch = repo.lookup_branch(branches[0])
if branch.branch_name != full_name:
branch.rename(full_name)
branch = repo.lookup_branch(full_name)
else:
base = repo.lookup_branch(self.base_branch)
if not base:
click.secho('Base branch not found: ""{}"", aborting.'
.format(self.base_branch), fg='red', bold=True)
sys.exit(1)
branch = repo.create_branch(full_name, base.get_object())
return branch
","import sys
import click
from slugify import slugify
class SlugBranchGetter(object):
def __init__(self, base_branch='master'):
self.base_branch = base_branch
def __call__(self, repo, issue):
discriminator = 'features/{}'.format(issue.key)
slug = slugify(issue.fields.summary[:30])
full_name = '{}_{}'.format(discriminator, slug)
branches = [b for b in repo.listall_branches()
if b.startswith(discriminator)]
if len(branches) > 1:
click.secho('Multiple matching branches found!',
fg='red', bold=True)
click.echo()
click.echo('The prefix {} matched the following branches:'
.format(discriminator))
click.echo()
for b in branches:
click.echo(' {} {}'.format(click.style('*', fg='red'), b))
click.echo()
click.echo('Please remove all but one in order to continue.')
sys.exit(1)
elif branches:
branch = repo.lookup_branch(branches[0])
if branch.branch_name != full_name:
branch.rename(full_name)
branch = repo.lookup_branch(full_name)
else:
base = repo.lookup_branch(self.base_branch)
if not base:
click.secho('Base branch not found: ""{}"", aborting.'
.format(self.base_branch), fg='red', bold=True)
sys.exit(1)
branch = repo.create_branch(full_name, base.get_object())
return branch
"
Disable buttons while request is pending,"isic.views.TermsAcceptanceView = isic.View.extend({
events: {
'click #isic-terms-accept': function (event) {
// Disable buttons while request is pending
var buttons = this.$('.isic-terms-agreement-button-container button');
buttons.prop('disabled', true);
if (girder.currentUser) {
girder.currentUser.setAcceptTerms(function () {
// Refresh page
Backbone.history.loadUrl();
});
} else {
window.sessionStorage.setItem('acceptTerms', 'true');
Backbone.history.loadUrl();
}
},
'click #isic-terms-reject': function (event) {
girder.events.trigger('g:navigateTo', isic.views.FrontPageView);
}
},
initialize: function () {
this.termsOfUseWidget = new isic.views.TermsOfUseWidget({
parentView: this
});
this.render();
},
render: function () {
this.$el.html(isic.templates.termsAcceptancePage());
this.termsOfUseWidget.setElement(
this.$('#isic-terms-of-use-container')).render();
return this;
}
}, {
// Static methods
hasAcceptedTerms: function () {
if (girder.currentUser) {
return girder.currentUser.canAcceptTerms();
} else {
return window.sessionStorage.getItem('acceptTerms') === 'true';
}
}
});
isic.router.route('termsAcceptance', 'termsAcceptance', function () {
girder.events.trigger('g:navigateTo', isic.views.TermsAcceptanceView);
});
","isic.views.TermsAcceptanceView = isic.View.extend({
events: {
'click #isic-terms-accept': function (event) {
if (girder.currentUser) {
girder.currentUser.setAcceptTerms(function () {
// Refresh page
Backbone.history.loadUrl();
});
// TODO: disable buttons while request is pending
} else {
window.sessionStorage.setItem('acceptTerms', 'true');
Backbone.history.loadUrl();
}
},
'click #isic-terms-reject': function (event) {
girder.events.trigger('g:navigateTo', isic.views.FrontPageView);
}
},
initialize: function () {
this.termsOfUseWidget = new isic.views.TermsOfUseWidget({
parentView: this
});
this.render();
},
render: function () {
this.$el.html(isic.templates.termsAcceptancePage());
this.termsOfUseWidget.setElement(
this.$('#isic-terms-of-use-container')).render();
return this;
}
}, {
// Static methods
hasAcceptedTerms: function () {
if (girder.currentUser) {
return girder.currentUser.canAcceptTerms();
} else {
return window.sessionStorage.getItem('acceptTerms') === 'true';
}
}
});
isic.router.route('termsAcceptance', 'termsAcceptance', function () {
girder.events.trigger('g:navigateTo', isic.views.TermsAcceptanceView);
});
"
Update Template for Parser class,"
import ast
from . import parse
class Template:
def __init__(self, raw):
self.raw = raw
self.parser = parse.Parser(raw)
self.nodelist = self.parser()
code = ast.Expression(
body=ast.GeneratorExp(
elt=ast.Call(
func=ast.Name(id='str', ctx=ast.Load()),
args=[
ast.Call(
func=ast.Attribute(
value=ast.Name(id='x', ctx=ast.Load()),
attr='render',
ctx=ast.Load()
),
args=[ast.Name(id='context', ctx=ast.Load())],
keywords=[], starargs=None, kwargs=None
),
],
keywords=[], starargs=None, kwargs=None
),
generators=[
ast.comprehension(
target=ast.Name(id='x', ctx=ast.Store()),
iter=ast.Name(id='nodelist', ctx=ast.Load()),
ifs=[]
),
]
)
)
ast.fix_missing_locations(code)
self.code = compile(code, filename='', mode='eval')
def render(self, context):
global_ctx = {
'nodelist': self.nodelist,
'context': dict(context),
}
return ''.join(eval(self.code, global_ctx, {}))
","
import ast
from . import parse
class Template:
def __init__(self, raw):
self.raw = raw
self.nodelist = parse.parse(raw)
code = ast.Expression(
body=ast.GeneratorExp(
elt=ast.Call(
func=ast.Name(id='str', ctx=ast.Load()),
args=[
ast.Call(
func=ast.Attribute(
value=ast.Name(id='x', ctx=ast.Load()),
attr='render',
ctx=ast.Load()
),
args=[ast.Name(id='context', ctx=ast.Load())],
keywords=[], starargs=None, kwargs=None
),
],
keywords=[], starargs=None, kwargs=None
),
generators=[
ast.comprehension(
target=ast.Name(id='x', ctx=ast.Store()),
iter=ast.Name(id='nodelist', ctx=ast.Load()),
ifs=[]
),
]
)
)
ast.fix_missing_locations(code)
self.code = compile(code, filename='', mode='eval')
def render(self, context):
global_ctx = {
'nodelist': self.nodelist,
'context': dict(context),
}
return ''.join(eval(self.code, global_ctx, {}))
"
Comment testMTA() test case to prevent sending mail on every build.,"/*
* Created on Jan 24, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.opennms.core.utils;
/*
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import alt.dev.jmta.JMTA;
*/
import junit.framework.TestCase;
/**
* @author david
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class JavaMailerTest extends TestCase {
/* public void testMTA() throws Exception {
Properties props = new Properties();
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setContent(""Hello"", ""text/plain"");
message.setText(""Hello"");
message.setSubject(Calendar.getInstance().getTime() + "": testMTA message"");
String to = ""david@opennms.org"";
String from = ""david@opennms.org"";
Address address = new InternetAddress(from);
message.setFrom(address);
address = new InternetAddress(to);
message.setRecipients(Message.RecipientType.TO, to);
message.saveChanges();
JMTA.send(message);
}
*/
}
","/*
* Created on Jan 24, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.opennms.core.utils;
import java.util.Calendar;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import junit.framework.TestCase;
import alt.dev.jmta.JMTA;
/**
* @author david
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class JavaMailerTest extends TestCase {
public void testMTA() throws Exception {
Properties props = new Properties();
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setContent(""Hello"", ""text/plain"");
message.setText(""Hello"");
message.setSubject(Calendar.getInstance().getTime() + "": testMTA message"");
String to = ""david@opennms.org"";
String from = ""david@opennms.org"";
Address address = new InternetAddress(from);
message.setFrom(address);
address = new InternetAddress(to);
message.setRecipients(Message.RecipientType.TO, to);
message.saveChanges();
JMTA.send(message);
}
}
"
Throw if bond object is missing,"import Joi from 'joi';
import { calcPrice, calcYield } from './bond';
const schema = Joi.object().keys({
settlement: Joi.date().max(Joi.ref('maturity')).required(),
maturity: Joi.date().required(),
rate: Joi.number().min(0).max(1).required(),
redemption: Joi.number().positive().required(),
frequency: Joi.number().valid([1, 2, 4]).required(),
convention: Joi.string().valid([
'30U/360',
'ACTUAL/ACTUAL',
'ACTUAL/360',
'ACTUAL/365',
'30E/360']).required(),
});
module.exports = (bond) => {
if (!bond) throw new Error('A bond object is required');
const validation = Joi.validate(bond, schema);
if (validation.error) throw validation.error;
const validBond = validation.value;
return {
price: yld => calcPrice(validBond.settlement,
validBond.maturity,
validBond.rate,
yld,
validBond.redemption,
validBond.frequency,
validBond.convention),
yield: price => calcYield(validBond.settlement,
validBond.maturity,
validBond.rate,
price,
validBond.redemption,
validBond.frequency,
validBond.convention),
};
};
","import Joi from 'joi';
import { calcPrice, calcYield } from './bond';
const schema = Joi.object().keys({
settlement: Joi.date().max(Joi.ref('maturity')).required(),
maturity: Joi.date().required(),
rate: Joi.number().min(0).max(1).required(),
redemption: Joi.number().positive().required(),
frequency: Joi.number().valid([1, 2, 4]).required(),
convention: Joi.string().valid([
'30U/360',
'ACTUAL/ACTUAL',
'ACTUAL/360',
'ACTUAL/365',
'30E/360']).required(),
});
module.exports = (bond) => {
const validation = Joi.validate(bond, schema);
if (validation.error) throw validation.error;
const validBond = validation.value;
return {
price: yld => calcPrice(validBond.settlement,
validBond.maturity,
validBond.rate,
yld,
validBond.redemption,
validBond.frequency,
validBond.convention),
yield: price => calcYield(validBond.settlement,
validBond.maturity,
validBond.rate,
price,
validBond.redemption,
validBond.frequency,
validBond.convention),
};
};
"
Document that we don't support Django 1.7 yet,"from setuptools import setup
version = '0.14.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django >= 1.4, < 1.7',
'django-extensions',
'django-nose',
'requests',
'itsdangerous',
'south',
'mock',
],
tests_require = [
]
setup(name='lizard-auth-client',
version=version,
description=""A client for lizard-auth-server"",
long_description=long_description,
# Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=['Programming Language :: Python',
'Framework :: Django',
],
keywords=[],
author='Erik-Jan Vos, Remco Gerlich',
author_email='remco.gerlich@nelen-schuurmans.nl',
url='http://www.nelen-schuurmans.nl/',
license='MIT',
packages=['lizard_auth_client'],
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
entry_points={
'console_scripts': [
]},
)
","from setuptools import setup
version = '0.14.dev0'
long_description = '\n\n'.join([
open('README.rst').read(),
open('CREDITS.rst').read(),
open('CHANGES.rst').read(),
])
install_requires = [
'Django',
'django-extensions',
'django-nose',
'requests',
'itsdangerous',
'south',
'mock',
],
tests_require = [
]
setup(name='lizard-auth-client',
version=version,
description=""A client for lizard-auth-server"",
long_description=long_description,
# Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=['Programming Language :: Python',
'Framework :: Django',
],
keywords=[],
author='Erik-Jan Vos, Remco Gerlich',
author_email='remco.gerlich@nelen-schuurmans.nl',
url='http://www.nelen-schuurmans.nl/',
license='MIT',
packages=['lizard_auth_client'],
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
tests_require=tests_require,
extras_require={'test': tests_require},
entry_points={
'console_scripts': [
]},
)
"
Clean up HKID verification code,"Meteor.methods({
checkHKID: function (hkid) {
var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit.
var matchArray = hkid.match(hkidPat);
if(matchArray == null){idError()}
var checkSum = 0;
var charPart = matchArray[1];
var numPart = matchArray[2];
var checkDigit = matchArray[3];
if (charPart.length == 2) {
checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55);
checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55);
}
else {
checkSum += 8 * (charPart.charCodeAt(0)-55);
checkSum += 324;
}
for (var i = 0, j = 7; i < numPart.length; i++, j--){
checkSum += j * numPart.charAt(i);
}
var remaining = checkSum % 11;
var checkNumber = 11 - remaining;
if(checkDigit == checkNumber) {return(""valid"")}
function idError () {
throw new Meteor.Error('invalid', 'The HKID entered is invalid')
}
}
});","Meteor.methods({
checkHKID: function (hkid) {
var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/;
var matchArray = hkid.match(hkidPat);
if(matchArray == null){throw new Meteor.Error('invalid', 'The HKID entered is invalid')} else {
var checkSum = 0;
var charPart = matchArray[1];
var numPart = matchArray[2];
var checkDigit = matchArray[3];
if (charPart.length == 2) {
checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55);
checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55);
} else {
checkSum += 8 * (charPart.charCodeAt(0)-55);
checkSum += 324;
}
for (var i = 0, j = 7; i < numPart.length; i++, j--){
checkSum += j * numPart.charAt(i);
}
var remaining = checkSum % 11;
var checkNumber = 11 - remaining;
if(checkDigit == checkNumber) {} else {throw new Meteor.Error('invalid', 'The HKID entered is invalid')}
return(hkid)
}}
});"
Use only one test task,"module.exports = function (grunt) {
grunt.initConfig({
clean: ['tmp/'],
'module-graph': {
simple: {
src: ['tests/assets/*.js'],
dest: 'tmp/graph-simple.json'
},
full: {
options: {
includeBindings: true
},
src: ['tests/assets/*.js'],
dest: 'tmp/graph-full.json'
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['tests/*.js']
},
sd: {
options: {
reporter: 'xunit'
},
src: ['tests/*.js']
}
}
});
// load this module's tasks
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('test', [
'clean',
'module-graph',
'mochaTest'
]);
};
","module.exports = function (grunt) {
grunt.initConfig({
clean: ['tmp/'],
'module-graph': {
simple: {
src: ['tests/assets/*.js'],
dest: 'tmp/graph-simple.json'
},
full: {
options: {
includeBindings: true
},
src: ['tests/assets/*.js'],
dest: 'tmp/graph-full.json'
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['tests/*.js']
},
sd: {
options: {
reporter: 'xunit'
},
src: ['tests/*.js']
}
}
});
// load this module's tasks
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('test', [
'clean',
'module-graph',
'mochaTest:test'
]);
grunt.registerTask('testsd', [
'clean',
'module-graph',
'mochaTest:sd'
]);
};
"
Use https for links to ORCID,"# -*- encoding: utf-8 -*-
from django import template
from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.html import escape
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
def orcid_to_url(orcid):
return mark_safe('https://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid)))
@register.filter(is_safe=True)
def small_orcid(orcid):
""""""
We expect here that the ORCID id has been validated before.
This displays something like ""iD ...-1234-2349""
""""""
return mark_safe('
...%s' %
(orcid_to_url(orcid),
orcid,
static('img/orcid-small.png'),
orcid[9:]))
@register.filter(is_safe=True)
def full_orcid(orcid):
""""""
We expect here that the ORCID id has been validated before
This displays something like ""iD 0000-0002-1234-2349""
""""""
return mark_safe('
%s' %
(orcid_to_url(orcid),
orcid,
static('img/orcid-small.png'),
orcid))
","# -*- encoding: utf-8 -*-
from django import template
from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.html import escape
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
def orcid_to_url(orcid):
return mark_safe('http://{}/{}'.format(settings.ORCID_BASE_DOMAIN, escape(orcid)))
@register.filter(is_safe=True)
def small_orcid(orcid):
""""""
We expect here that the ORCID id has been validated before.
This displays something like ""iD ...-1234-2349""
""""""
return mark_safe('
...%s' %
(orcid_to_url(orcid),
orcid,
static('img/orcid-small.png'),
orcid[9:]))
@register.filter(is_safe=True)
def full_orcid(orcid):
""""""
We expect here that the ORCID id has been validated before
This displays something like ""iD 0000-0002-1234-2349""
""""""
return mark_safe('
%s' %
(orcid_to_url(orcid),
orcid,
static('img/orcid-small.png'),
orcid))
"
Fix testcase for Cache dispense,"app = new App(array(
'cache' => array(
'user' => array(
'type' => 'file',
)
)
));
}
public function testFactory()
{
$file = Cache::factory('file');
$this->assertInstanceOf('Pagon\Cache\File', $file);
}
public function testFactoryNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$none = Cache::factory('none');
}
public function testDispense()
{
$user_cache = Cache::dispense('cache.user');
$this->assertInstanceOf('Pagon\Cache\File', $user_cache);
$try_new_cache = Cache::dispense('user');
$this->assertEquals($try_new_cache, $user_cache);
}
public function testDispenseNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$user_cache = Cache::dispense('cache.user1');
}
}
","app = new App(array(
'cache' => array(
'user' => array(
'type' => 'file',
)
)
));
}
public function testFactory()
{
$file = Cache::factory('file');
$this->assertInstanceOf('Pagon\Cache\File', $file);
}
public function testFactoryNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$none = Cache::factory('none');
}
public function testDispense()
{
$user_cache = Cache::dispense('user');
$this->assertInstanceOf('Pagon\Cache\File', $user_cache);
$try_new_cache = Cache::dispense('user');
$this->assertEquals($try_new_cache, $user_cache);
}
public function testDispenseNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$user_cache = Cache::dispense('user1');
}
}
"
Refactor by using array T,"""""""Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
""""""
class Solution(object):
def generate(self, numRows):
""""""
:type numRows: int
:rtype: List[List[int]]
Time complexity: O(n^2).
Space complexity: O(n).
""""""
if numRows == 0:
return []
# Create base of Pascal triangle.
T = [[1] * (r + 1) for r in range(numRows)]
if numRows <= 2:
return T
# For each row >= 3, update middle numers by last row.
for r in range(2, numRows):
for i in range(1, r):
T[r][i] = T[r - 1][i - 1] + T[r - 1][i]
return T
def main():
numRows = 5
print('Pascal\'s triangle:\n{}'.format(
Solution().generate(numRows)))
if __name__ == '__main__':
main()
","""""""Leetcode 118. Pascal's Triangle
Easy
URL: https://leetcode.com/problems/pascals-triangle/
Given a non-negative integer numRows, generate the first numRows of
Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly
above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
""""""
class Solution(object):
def generate(self, numRows):
""""""
:type numRows: int
:rtype: List[List[int]]
Time complexity: O(n^2).
Space complexity: O(n).
""""""
if numRows == 0:
return []
# Create base of Pascal triangle.
triangle = [[1] * (r + 1) for r in range(numRows)]
if numRows <= 2:
return triangle
for r in range(2, numRows):
last_row = triangle[r - 1]
current_row = triangle[r]
# In middle of current row, sum last row's two numbers.
for i in range(1, r):
current_row[i] = last_row[i - 1] + last_row[i]
return triangle
def main():
numRows = 5
print('Pascal\'s triangle:\n{}'.format(
Solution().generate(numRows)))
if __name__ == '__main__':
main()
"
Increase frequency of order items pulling.,"from waldur_core.core import WaldurExtension
class MarketplaceRemoteExtension(WaldurExtension):
@staticmethod
def django_app():
return 'waldur_mastermind.marketplace_remote'
@staticmethod
def is_assembly():
return True
@staticmethod
def django_urls():
from .urls import urlpatterns
return urlpatterns
@staticmethod
def celery_tasks():
from datetime import timedelta
return {
'waldur-remote-pull-offerings': {
'task': 'waldur_mastermind.marketplace_remote.pull_offerings',
'schedule': timedelta(minutes=60),
'args': (),
},
'waldur-remote-pull-order-items': {
'task': 'waldur_mastermind.marketplace_remote.pull_order_items',
'schedule': timedelta(minutes=5),
'args': (),
},
'waldur-remote-pull-usage': {
'task': 'waldur_mastermind.marketplace_remote.pull_usage',
'schedule': timedelta(minutes=60),
'args': (),
},
'waldur-remote-sync-remote-project-permissions': {
'task': 'waldur_mastermind.marketplace_remote.sync_remote_project_permissions',
'schedule': timedelta(hours=6),
'args': (),
},
'waldur-remote-pull-invoices': {
'task': 'waldur_mastermind.marketplace_remote.pull_invoices',
'schedule': timedelta(minutes=60),
'args': (),
},
}
","from waldur_core.core import WaldurExtension
class MarketplaceRemoteExtension(WaldurExtension):
@staticmethod
def django_app():
return 'waldur_mastermind.marketplace_remote'
@staticmethod
def is_assembly():
return True
@staticmethod
def django_urls():
from .urls import urlpatterns
return urlpatterns
@staticmethod
def celery_tasks():
from datetime import timedelta
return {
'waldur-remote-pull-offerings': {
'task': 'waldur_mastermind.marketplace_remote.pull_offerings',
'schedule': timedelta(minutes=60),
'args': (),
},
'waldur-remote-pull-order-items': {
'task': 'waldur_mastermind.marketplace_remote.pull_order_items',
'schedule': timedelta(minutes=60),
'args': (),
},
'waldur-remote-pull-usage': {
'task': 'waldur_mastermind.marketplace_remote.pull_usage',
'schedule': timedelta(minutes=60),
'args': (),
},
'waldur-remote-sync-remote-project-permissions': {
'task': 'waldur_mastermind.marketplace_remote.sync_remote_project_permissions',
'schedule': timedelta(hours=6),
'args': (),
},
'waldur-remote-pull-invoices': {
'task': 'waldur_mastermind.marketplace_remote.pull_invoices',
'schedule': timedelta(minutes=60),
'args': (),
},
}
"
Update source of loader cordova script,"/*globals Polymer */
'use strict';
Polymer(
{
is: 'cordova-core',
properties: {
/**
* Return if cordova deviceready event has been fired.
*/
ready: {
notify: true,
readOnly: true,
type: Boolean,
value: false
},
/**
* Return if cordova application is paused.
*/
paused: {
notify: true,
readOnly: true,
type: Boolean,
value: false
}
},
attached() {
const cordovaEl = document.querySelector('#cordova');
document.addEventListener(
'deviceready',
this._setReady.bind(this, true),
false
);
document.addEventListener(
'pause',
this._setPaused.bind(this, true),
false
);
document.addEventListener(
'resume',
this._setPaused.bind(this, false),
false
);
if (!cordovaEl) {
let script = document.createElement('script');
script.id = 'cordova';
script.src = 'cordova.js';
document.body.appendChild(script);
}
},
detached() {
document.removeEventListener('deviceready', this._setReady);
document.removeEventListener('pause', this._setPaused);
document.removeEventListener('resume', this._setPaused);
}
}
);
","/*globals Polymer */
'use strict';
Polymer(
{
is: 'cordova-core',
properties: {
/**
* Return if cordova deviceready event has been fired.
*/
ready: {
notify: true,
readOnly: true,
type: Boolean,
value: false
},
/**
* Return if cordova application is paused.
*/
paused: {
notify: true,
readOnly: true,
type: Boolean,
value: false
}
},
attached() {
const cordovaEl = document.querySelector('#cordova');
document.addEventListener(
'deviceready',
this._setReady.bind(this, true),
false
);
document.addEventListener(
'pause',
this._setPaused.bind(this, true),
false
);
document.addEventListener(
'resume',
this._setPaused.bind(this, false),
false
);
if (!cordovaEl) {
const location = window.location;
let script = document.createElement('script');
let path = location.pathname.split('/').slice(0, -1).join('/');
script.id = 'cordova';
script.src = location.origin + path + '/cordova.js';
document.body.appendChild(script);
}
},
detached() {
document.removeEventListener('deviceready', this._setReady);
document.removeEventListener('pause', this._setPaused);
document.removeEventListener('resume', this._setPaused);
}
}
);
"
Update logging for message output and consistency.,"import logging
from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
# Import the Game Controller
from Game.GameController import GameController
class GameModes(MethodView):
def get(self):
logging.debug(""GameModes: GET: Initializing GameObject"")
game_object = GameController()
logging.debug(""GameModes: GET: GameObject initialized to {}"".format(game_object.save()))
logging.debug(""GameModes: GET: Checking if textmode flag set"")
if request.args.get('textmode', None):
logging.debug(""GameModes: GET: Responding with list of names"")
response_data = game_object.game_mode_names
else:
logging.debug(""GameModes: GET: Responding with JSON object: {}"".format(game_object.game_modes))
response_data = [{""mode"": gt.mode,
""digits"": gt.digits,
""digit-type"": gt.digit_type,
""guesses"": gt.guesses_allowed
} for gt in game_object.game_modes]
logging.debug(""GameModes: GET: Return {}"".format(response_data))
return build_response(
html_status=200,
response_data=response_data,
response_mimetype=""application/json""
)
","import logging
from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
# Import the Game Controller
from Game.GameController import GameController
class GameModes(MethodView):
def get(self):
logging.debug(""GameModes: GET: Initializing GameObject"")
game_object = GameController()
logging.debug(""GameModes: GET: GameObject initialized to {}"".format(game_object.save()))
logging.debug(""GameModes: GET: Checking if textmode flag set"")
if request.args.get('textmode', None):
logging.debug(""GameModes: GET: Responding with list of names"")
response_data = game_object.game_mode_names
else:
logging.debug(""GameModes: GET: Responding with JSON object"")
response_data = [{""mode"": gt.mode,
""digits"": gt.digits,
""digit-type"": gt.digit_type,
""guesses"": gt.guesses_allowed
} for gt in game_object.game_modes]
logging.debug(""GameModes: GET: Return {}"".format(response_data))
return build_response(
html_status=200,
response_data=response_data,
response_mimetype=""application/json""
)
"
Update to work through manifest and directly,"package THE_PACKAGE;
import java.io.IOException;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName = null;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// Error: no callbacks
throw new RuntimeException(""RubotoBroadcastReceiver does not accept callbacks"");
}
public void setScriptName(String name){
scriptName = name;
}
public THE_RUBOTO_CLASS() {
this(null);
}
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null) {
setScriptName(name);
if (Script.isInitialized()) {
loadScript();
}
}
}
protected void loadScript() {
Script.put(""$broadcast_receiver"", this);
if (scriptName != null) {
try {
new Script(scriptName).execute();
} catch(IOException e) {
throw new RuntimeException(""IOException loading broadcast receiver script"", e);
}
}
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
Script.put(""$context"", context);
Script.put(""$broadcast_receiver"", this);
Script.put(""$intent"", intent);
try {
Script.execute(""$broadcast_receiver.on_receive($context, $intent)"");
} catch(Exception e) {
e.printStackTrace();
}
}
}
","package THE_PACKAGE;
public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
private String scriptName;
private boolean initialized = false;
public void setCallbackProc(int id, Object obj) {
// Error: no callbacks
throw new RuntimeException(""RubotoBroadcastReceiver does not accept callbacks"");
}
public void setScriptName(String name){
scriptName = name;
}
public THE_RUBOTO_CLASS() {
this(null);
}
public THE_RUBOTO_CLASS(String name) {
super();
if (name != null)
setScriptName(name);
}
public void onReceive(android.content.Context context, android.content.Intent intent) {
if (Script.setUpJRuby(context)) {
Script.defineGlobalVariable(""$context"", context);
Script.defineGlobalVariable(""$broadcast_receiver"", this);
Script.defineGlobalVariable(""$intent"", intent);
try {
if (scriptName != null && !initialized) {
new Script(scriptName).execute();
initialized = true;
} else {
Script.execute(""$broadcast_receiver.on_receive($context, $intent)"");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
"
Fix phpmd error: USE declarations must go after the first namespace declaration,"form = (new FormFactory())->newInstance(TodoForm::class);
}
public function testFailedEmpty()
{
$submit = [];
$isValid = $this->form->apply($submit);
$this->assertFalse($isValid);
}
public function testFailedEmptyVale()
{
$submit = ['title' => ''];
$isValid = $this->form->apply($submit);
$this->assertFalse($isValid);
$msg = $this->form->getFailureMessages();
$expected = ['title' => ['必ず入力してください']];
$this->assertSame($expected, $msg);
}
public function testOk()
{
$submit = ['title' => 'test'];
$isValid = $this->form->apply($submit);
$this->assertTrue($isValid);
}
public function testFormView()
{
$formHtml = (string) $this->form;
$expected = '';
$this->assertSame($expected, $formHtml);
}
}
","form = (new FormFactory())->newInstance(TodoForm::class);
}
public function testFailedEmpty()
{
$submit = [];
$isValid = $this->form->apply($submit);
$this->assertFalse($isValid);
}
public function testFailedEmptyVale()
{
$submit = ['title' => ''];
$isValid = $this->form->apply($submit);
$this->assertFalse($isValid);
$msg = $this->form->getFailureMessages();
$expected = ['title' => ['必ず入力してください']];
$this->assertSame($expected, $msg);
}
public function testOk()
{
$submit = ['title' => 'test'];
$isValid = $this->form->apply($submit);
$this->assertTrue($isValid);
}
public function testFormView()
{
$formHtml = (string) $this->form;
$expected = '';
$this->assertSame($expected, $formHtml);
}
}
"
Remove kws: does not exist,"from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_description=open('README.rst').read(),
keywords='django apps',
license='New BSD License',
author='Horst Gutmann',
author_email='zerok@zerokspot.com',
url='http://github.com/zerok/django-flatblocks/',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
packages=find_packages('flatblocks'),
package_data={
'flatblocks': [
'templates/flatblocks/*.html',
'locale/*/*/*.mo',
'locale/*/*/*.po',
]
},
zip_safe=False,
requires = [
'Django (>=1.4)',
],
)
","from setuptools import setup, find_packages
setup(
name='django-flatblocks',
version='0.9',
description='django-flatblocks acts like django.contrib.flatpages but '
'for parts of a page; like an editable help box you want '
'show alongside the main content.',
long_description=open('README.rst').read(),
keywords='django apps',
license='New BSD License',
author='Horst Gutmann',
author_email='zerok@zerokspot.com',
url='http://github.com/zerok/django-flatblocks/',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
packages=find_packages('flatblocks'),
package_data={
'flatblocks': [
'templates/flatblocks/*.html',
'locale/*/*/*.mo',
'locale/*/*/*.po',
]
},
zip_safe=False,
requires = [
'Django (>=1.4)',
],
**kws
)
"
Add termite radius to integer parameters,"""""""Utilitary shared functions.""""""
boolean_parameters = ['show_labels', 'highlight_collisions',
'show_bounding_box', 'show_frame_info',
'show_d_lines', 'show_trails']
tuple_parameters = ['video_source_size', 'arena_size']
integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size', 'termite_radius']
list_parameters = ['filters']
def read_config_file(config_path):
""""""Read input file and creates parameters dictionary.
Args:
config_path (str): path to configuration file.
Returns:
parameters (dict): loaded parameters.
""""""
parameters = {}
with open(config_path, mode='r', encoding='utf-8') as input_file:
for line in input_file:
if not line[0] == '\n' and not line[0] == '#' and not line[0] == ' ':
param, value = line.strip().split(' ')
if param in tuple_parameters:
width, height = value.strip().split(',')
parameters[param] = tuple([int(width), int(height)])
elif param in list_parameters:
values = []
for field in value.strip().split(','):
if field != 'None':
filters.append(field)
parameters[param] = values
elif param in integer_parameters:
parameters[param] = int(value)
elif param in boolean_parameters:
if value.lower() == 'true':
parameters[param] = True
else:
parameters[param] = False
else:
parameters[param] = value
return parameters
","""""""Utilitary shared functions.""""""
boolean_parameters = ['show_labels', 'highlight_collisions',
'show_bounding_box', 'show_frame_info',
'show_d_lines', 'show_trails']
tuple_parameters = ['video_source_size', 'arena_size']
integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size']
list_parameters = ['filters']
def read_config_file(config_path):
""""""Read input file and creates parameters dictionary.
Args:
config_path (str): path to configuration file.
Returns:
parameters (dict): loaded parameters.
""""""
parameters = {}
with open(config_path, mode='r', encoding='utf-8') as input_file:
for line in input_file:
if not line[0] == '\n' and not line[0] == '#' and not line[0] == ' ':
param, value = line.strip().split(' ')
if param in tuple_parameters:
width, height = value.strip().split(',')
parameters[param] = tuple([int(width), int(height)])
elif param in list_parameters:
values = []
for field in value.strip().split(','):
if field != 'None':
filters.append(field)
parameters[param] = values
elif param in integer_parameters:
parameters[param] = int(value)
elif param in boolean_parameters:
if value.lower() == 'true':
parameters[param] = True
else:
parameters[param] = False
else:
parameters[param] = value
return parameters
"
Add method to load a page,"loadClass($name, 'Page');
if ($page === false || method_exists($page, $method) === false)
{
not_found();
}
else
{
$page->$method();
}
}
private function loadFile($name, $package='library', $data=array())
{
$vendors =& loadClass('Vendor', 'Core');
$list = $vendors->lists();
foreach ($list as $vendor)
{
if (file_exists($vendor . '/' . $package . '/' . $name . '.php'))
{
include ($vendor . '/' . $package . '/' . $name . '.php');
return true;
}
}
return false;
}
private function loadClass($name, $package='library')
{
$package = strtolower($package);
$name = strtolower($name);
if (isset($this->instance[$package]) && isset($this->instance[$package][$name]))
{
return $this->instance[$package][$name];
}
$hasFile = $this->loadFile($name, $package);
if ($hasFile === false || class_exists($name) === false)
{
return false;
}
$class = new $name();
$this->instance[$package][$name] = $class;
return $class;
}
}
?>
","lists();
foreach ($list as $vendor)
{
if (file_exists($vendor . '/' . $package . '/' . $name . '.php'))
{
include ($vendor . '/' . $package . '/' . $name . '.php');
return true;
}
}
return false;
}
private function loadClass($name, $package='library')
{
$package = strtolower($package);
$name = strtolower($name);
if (isset($this->instance[$package]) && isset($this->instance[$package][$name]))
{
return $this->instance[$package][$name];
}
$hasFile = $this->loadFile($name, $package);
if ($hasFile === false || class_exists($name) === false)
{
return false;
}
$class = new $name();
$this->instance[$package][$name] = $class;
return $class;
}
}
?>
"
Remove many to many key generation in test,"from model_mommy import mommy
from tests.BaseTestWithDB import BaseTestWithDB
from topics.models import CurriculumIntegration
from topics.models import CurriculumArea
from topics.models import Lesson
from tests.topics import create_topics_test_data
class CurriculumIntegrationModelTest(BaseTestWithDB):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def test_curriculum_integration(self):
# Setup Auxliary Data
topic = create_topics_test_data.create_test_topic(1)
curriculum_area = mommy.make(
CurriculumArea,
name=""cats""
)
prerequisite_lesson = mommy.make(
Lesson,
name=""dogs""
)
new_curriculum_integration = CurriculumIntegration.objects.create(
topic=topic,
slug=""slug"",
number=1,
name=""name"",
content=""content""
)
new_curriculum_integration.curriculum_areas.add(curriculum_area)
new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson)
query_result = CurriculumIntegration.objects.get(slug=""slug"")
self.assertEqual(query_result, new_curriculum_integration)
","from model_mommy import mommy
from tests.BaseTestWithDB import BaseTestWithDB
from topics.models import CurriculumIntegration
from topics.models import CurriculumArea
from topics.models import Lesson
from tests.topics import create_topics_test_data
class CurriculumIntegrationModelTest(BaseTestWithDB):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def test_curriculum_integration(self):
# Setup Auxliary Data
topic = create_topics_test_data.create_test_topic(1)
curriculum_area = mommy.make(
CurriculumArea,
make_m2m=True,
name=""cats""
)
prerequisite_lesson = mommy.make(
Lesson,
make_m2m=True,
name=""dogs""
)
# Test
new_curriculum_integration = CurriculumIntegration.objects.create(
topic=topic,
slug=""slug"",
number=1,
name=""name"",
content=""content""
)
new_curriculum_integration.curriculum_areas.add(curriculum_area)
new_curriculum_integration.prerequisite_lessons.add(prerequisite_lesson)
query_result = CurriculumIntegration.objects.get(slug=""slug"")
self.assertEqual(query_result, new_curriculum_integration)
"
Refactor day 1 into reusable FuelCalculator resources,"package day01;
import common.BaseSolution;
import common.InputReader;
public class Solution extends BaseSolution implements common.Solution {
public static void main(String[] args) {
new Solution().run();
}
class BaseFuelCalculator {
public int calculateFuel() {
int mass, totalFuel = 0;
InputReader reader = getInputReader();
String line = reader.next();
while (line != null) {
mass = Integer.parseInt(line);
totalFuel += getFuel(mass);
line = reader.next();
}
return totalFuel;
}
protected int getFuelForMass(int mass) {
return mass / 3 - 2;
}
protected int getFuel(int mass) {
return 0;
}
}
class Part1FuelCalculator extends BaseFuelCalculator {
protected int getFuel(int mass) {
return getFuelForMass(mass);
}
}
class Part2FuelCalculator extends BaseFuelCalculator {
protected int getFuel(int mass) {
int fuel = 0;
int fuelPiece = mass;
do {
fuelPiece = getFuelForMass(fuelPiece);
if (fuelPiece > 0) {
fuel += fuelPiece;
}
} while (fuelPiece > 0);
return fuel;
}
}
public String part1() {
return String.valueOf(new Part1FuelCalculator().calculateFuel());
}
public String part2() {
return String.valueOf(new Part2FuelCalculator().calculateFuel());
}
}
","package day01;
import common.BaseSolution;
import common.InputReader;
public class Solution extends BaseSolution implements common.Solution {
public static void main(String[] args) {
new Solution().run();
}
public String part1() {
int mass, totalFuel = 0;
InputReader reader = getInputReader();
String line = reader.next();
while (line != null) {
mass = Integer.parseInt(line);
totalFuel += getFuel(mass);
line = reader.next();
}
return String.valueOf(totalFuel);
}
private int getFuel(int mass) {
return mass / 3 - 2;
}
public String part2() {
int mass, totalFuel = 0;
InputReader reader = getInputReader();
String line = reader.next();
while (line != null) {
mass = Integer.parseInt(line);
totalFuel += getFuelWithResiduals(mass);
line = reader.next();
}
return String.valueOf(totalFuel);
}
private int getFuelWithResiduals(int mass) {
int fuel = 0;
int fuelPiece = mass;
do {
fuelPiece = getFuel(fuelPiece);
if (fuelPiece > 0) {
fuel += fuelPiece;
}
} while (fuelPiece > 0);
return fuel;
}
}
"
Remove unused import from UrlChecker (Debug adapter),"var http = require('http'),
https = require('https'),
fileType = require('file-type');
var UrlChecker = function() {
return this;
}
UrlChecker.prototype = {
checkUrl: function(url, ts) {
var method;
if(url.indexOf('https') === 0) {
method = https;
} else if(url.indexOf('http') === 0) {
method = http;
}
return new Promise((resolve) => {
if(method) {
method.get(url, res => {
res.once('data', chunk => {
res.destroy();
var ft = fileType(chunk);
if(ft && ft.mime) {
if(ft.mime.indexOf('image') === 0) {
resolve({
ts: ts,
type: 'image',
value: url
});
}
}
});
});
}
});
}
};
module.exports = UrlChecker;
","var rp = require('request'),
http = require('http'),
https = require('https'),
fileType = require('file-type');
var UrlChecker = function() {
return this;
}
UrlChecker.prototype = {
checkUrl: function(url, ts) {
var method;
if(url.indexOf('https') === 0) {
method = https;
} else if(url.indexOf('http') === 0) {
method = http;
}
return new Promise((resolve) => {
if(method) {
method.get(url, res => {
res.once('data', chunk => {
res.destroy();
var ft = fileType(chunk);
if(ft && ft.mime) {
if(ft.mime.indexOf('image') === 0) {
resolve({
ts: ts,
type: 'image',
value: url
});
}
}
});
});
}
});
}
};
module.exports = UrlChecker;
"
Return xls as type for application/vnd.ms-excel.,"(function(module) {
module.directive(""displayFileContents"", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: ""E"",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller(""DisplayFileContentsDirectiveController"", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = [""mcfile""];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return ""image"";
} else {
switch(mediatype.mime) {
case ""application/pdf"":
return ""pdf"";
case ""application/vnd.ms-excel"":
return ""xls"";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
","(function(module) {
module.directive(""displayFileContents"", displayFileContentsDirective);
function displayFileContentsDirective() {
return {
restrict: ""E"",
controller: 'DisplayFileContentsDirectiveController',
controllerAs: 'view',
bindToController: true,
scope: {
file: '=file'
},
templateUrl: 'application/core/projects/project/files/display-file-contents.html'
};
}
module.controller(""DisplayFileContentsDirectiveController"", DisplayFileContentsDirectiveController);
DisplayFileContentsDirectiveController.$inject = [""mcfile""];
/* @ngInject */
function DisplayFileContentsDirectiveController(mcfile) {
var ctrl = this;
ctrl.fileType = determineFileType(ctrl.file.mediatype);
ctrl.fileSrc = mcfile.src(ctrl.file.id);
//////////////
function determineFileType(mediatype) {
if (isImage(mediatype.mime)) {
return ""image"";
} else {
switch(mediatype.mime) {
case ""application/pdf"":
return ""pdf"";
case ""application/vnd.ms-excel"":
return ""excel"";
default:
return mediatype.mime;
}
}
}
}
}(angular.module('materialscommons')));
"
Add a test case of DispatcherBootstrap with other request,"env = [
'site' => [
'url' => '/'
],
'router' => [
'namespace' => '',
'/' => function() {
echo 'index';
},
'/test' => function() {
echo 'test';
}
],
'viewEngine' => [],
'viewResolver' => [
'App\ViewResolver\DummyResolver'
],
'viewPrefix' => [
'applyView' => []
]
];
}
public function testDispatch1()
{
$this->env['dispatcher'] = [
'request' => new ServerRequest([], [], '/', 'GET')
];
$bootstrap = new DispatcherBootstrap();
$this->expectOutputString('index');
$bootstrap->boot($this->env);
}
public function testDispatch2()
{
$this->env['dispatcher'] = [
'request' => new ServerRequest([], [], '/test', 'GET')
];
$bootstrap = new DispatcherBootstrap();
$this->expectOutputString('test');
$bootstrap->boot($this->env);
}
}","env = [
'site' => [
'url' => '/'
],
'router' => [
'namespace' => '',
'/' => function() {
echo 'index';
}
],
'viewEngine' => [],
'viewResolver' => [
'App\ViewResolver\DummyResolver'
],
'viewPrefix' => [
'applyView' => []
]
];
}
public function testDispatch()
{
$this->env['dispatcher'] = [
'request' => new ServerRequest([], [], '/', 'GET')
];
$bootstrap = new DispatcherBootstrap();
$this->expectOutputString('index');
$bootstrap->boot($this->env);
}
}"
Set minimal deposit amount in accordance with description,"(function () {
'use strict';
function WavesWalletDepositController ($scope, events, coinomatService, dialogService, notificationService,
applicationContext, bitcoinUriService) {
var deposit = this;
deposit.bitcoinAddress = '';
deposit.bitcoinAmount = '';
deposit.bitcoinUri = '';
deposit.refreshUri = function () {
var params = null;
if (deposit.bitcoinAmount >= 0.01) {
params = {
amount: deposit.bitcoinAmount
};
}
deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress, params);
};
$scope.$on(events.WALLET_DEPOSIT, function (event, eventData) {
deposit.assetBalance = eventData.assetBalance;
deposit.currency = deposit.assetBalance.currency.displayName;
if (deposit.assetBalance.currency.id !== Currency.BTC.id) {
$scope.home.featureUnderDevelopment();
return;
}
dialogService.open('#deposit-dialog');
coinomatService.getDepositDetails(deposit.assetBalance.currency, applicationContext.account.address)
.then(function (depositDetails) {
deposit.bitcoinAddress = depositDetails.address;
deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress);
})
.catch(function (exception) {
notificationService.error(exception.message);
});
});
}
WavesWalletDepositController.$inject = ['$scope', 'wallet.events', 'coinomatService', 'dialogService',
'notificationService', 'applicationContext', 'bitcoinUriService'];
angular
.module('app.wallet')
.controller('walletDepositController', WavesWalletDepositController);
})();
","(function () {
'use strict';
function WavesWalletDepositController ($scope, events, coinomatService, dialogService, notificationService,
applicationContext, bitcoinUriService) {
var deposit = this;
deposit.bitcoinAddress = '';
deposit.bitcoinAmount = '';
deposit.bitcoinUri = '';
deposit.refreshUri = function () {
var params = null;
if (deposit.bitcoinAmount > 0) {
params = {
amount: deposit.bitcoinAmount
};
}
deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress, params);
};
$scope.$on(events.WALLET_DEPOSIT, function (event, eventData) {
deposit.assetBalance = eventData.assetBalance;
deposit.currency = deposit.assetBalance.currency.displayName;
if (deposit.assetBalance.currency.id !== Currency.BTC.id) {
$scope.home.featureUnderDevelopment();
return;
}
dialogService.open('#deposit-dialog');
coinomatService.getDepositDetails(deposit.assetBalance.currency, applicationContext.account.address)
.then(function (depositDetails) {
deposit.bitcoinAddress = depositDetails.address;
deposit.bitcoinUri = bitcoinUriService.generate(deposit.bitcoinAddress);
})
.catch(function (exception) {
notificationService.error(exception.message);
});
});
}
WavesWalletDepositController.$inject = ['$scope', 'wallet.events', 'coinomatService', 'dialogService',
'notificationService', 'applicationContext', 'bitcoinUriService'];
angular
.module('app.wallet')
.controller('walletDepositController', WavesWalletDepositController);
})();
"
Fix critical claim bug on token,"header = new Header();
$this->payload = new Payload();
}
/**
* @param HeaderParameter\ParameterInterface $parameter
* @param bool $critical
*/
public function addHeader(HeaderParameter\ParameterInterface $parameter, $critical = false)
{
$this->header->setParameter($parameter, $critical);
}
/**
* @param Claim\ClaimInterface $claim
*/
public function addClaim(Claim\ClaimInterface $claim)
{
$this->payload->setClaim($claim);
}
/**
* @return Token\Header
*/
public function getHeader()
{
return $this->header;
}
/**
* @return Token\Payload
*/
public function getPayload()
{
return $this->payload;
}
/**
* @return string
*/
public function getSignature()
{
return $this->signature;
}
/**
* @param string $signature
*/
public function setSignature($signature)
{
$this->signature = $signature;
}
}
","header = new Header();
$this->payload = new Payload();
}
/**
* @param HeaderParameter\ParameterInterface $parameter
*/
public function addHeader(HeaderParameter\ParameterInterface $parameter)
{
$this->header->setParameter($parameter);
}
/**
* @param Claim\ClaimInterface $claim
* @param bool $critical
*/
public function addClaim(Claim\ClaimInterface $claim, $critical = false)
{
$this->payload->setClaim($claim);
if ($critical) {
$this->header->addCriticalClaim($claim);
}
}
/**
* @return Token\Header
*/
public function getHeader()
{
return $this->header;
}
/**
* @return Token\Payload
*/
public function getPayload()
{
return $this->payload;
}
/**
* @return string
*/
public function getSignature()
{
return $this->signature;
}
/**
* @param string $signature
*/
public function setSignature($signature)
{
$this->signature = $signature;
}
}
"
Improve import logic for clearer error messages,"class Importer(object):
def __init__(self):
self.update_dict = {}
self.dirnames = [
""vmetas"", ""infos"", ""controllers"", ""parts"", ""includes"", ""blocks""]
def import_subpackages(self, path, filter=()):
import os
dirname = os.path.join(os.path.dirname(__file__), *path)
for f in os.listdir(dirname):
if not filter or f in filter:
if os.path.isdir(os.path.join(dirname, f)):
self.try_import_path(path + [f])
# Try the import of subpackages too
self.import_subpackages(path + [f], self.dirnames)
def try_import_path(self, path):
import importlib
name = ""."".join(path)
try:
self.update_dict[name] = importlib.import_module(
""malcolm.modules.%s"" % name)
except ImportError:
import logging
# Create a module level logger
log = logging.getLogger(__name__)
log.warning(""Importing %s failed"", name, exc_info=True)
def prepare(self, globals_d):
self.import_subpackages([])
globals_d.update(self.update_dict)
__all__ = list(self.update_dict)
return __all__
__all__ = Importer().prepare(globals())
del Importer
","class Importer(object):
def __init__(self):
self.update_dict = {}
self.ignore = [""docs""]
def import_subpackages(self, path):
import os
dirname = os.path.join(os.path.dirname(__file__), *path)
for f in os.listdir(dirname):
if f not in self.ignore and os.path.isdir(os.path.join(dirname, f)):
self.try_import_path(path + [f])
def try_import_path(self, path):
import importlib
name = ""."".join(path)
try:
self.update_dict[name] = importlib.import_module(
""malcolm.modules.%s"" % name)
except ImportError:
import logging
# Create a module level logger
log = logging.getLogger(__name__)
log.info(""Importing %s failed"", name, exc_info=True)
# Try the import of subpackages too
self.import_subpackages(path)
def prepare(self, globals_d):
self.import_subpackages([])
globals_d.update(self.update_dict)
__all__ = list(self.update_dict)
return __all__
__all__ = Importer().prepare(globals())
del Importer
"
Fix sort for vue list,"sortBy(function ($item, $key) use ($order, $callback) {
return $order->search($callback($item, $key));
}, $options, $descending);
if ($holdKey) {
return $sorted;
}
return $sorted->values();
});
Collection::macro('sortByKind', function ($options = SORT_REGULAR, $descending = false) {
$kinds = collect(config('jmaxml.kinds'))->keys();
return $this->sortWithOrderBy('kind_of_info', $kinds, $options, $descending, false);
});
Collection::macro('sortByType', function ($options = SORT_REGULAR, $descending = false) {
$types = collect(config('jmaxml.feedtypes'));
return $this->sortWithOrderBy('type', $types, $options, $descending, false);
});
}
}
","sortBy(function ($item, $key) use ($order, $callback) {
return $order->search($callback($item, $key));
}, $options, $descending);
});
Collection::macro('sortByKind', function ($options = SORT_REGULAR, $descending = false) {
$kinds = collect(config('jmaxml.kinds'))->keys();
return $this->sortWithOrderBy($kinds, 'kind_of_info', $options, $descending);
});
Collection::macro('sortByType', function ($options = SORT_REGULAR, $descending = false) {
$types = collect(config('jmaxml.feedtypes'));
return $this->sortWithOrderBy($types, 'type', $options, $descending);
});
}
}
"
"Use traditional constructors of TimestampParser against Embulk core deprecation
Some constructors of them have been deprecated on the Embulk core side.
See https://github.com/embulk/embulk/issues/745 for the details.","package org.embulk.parser.apache.log;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.spi.Exec;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.time.Timestamp;
import org.embulk.spi.time.TimestampParser;
import static org.embulk.spi.type.Types.TIMESTAMP;
public class TimestampLogElement extends LogElement {
private final TimestampParser parser;
public TimestampLogElement(TimestampParser.Task task, String name, String regex) {
this(task, name, regex, ""%d/%b/%Y:%T %z"");
}
private static interface ParserIntlTask extends Task, TimestampParser.Task {}
private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
// TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
// Traditional constructor is used here for compatibility.
final ConfigSource configSource = Exec.newConfigSource();
configSource.set(""format"", pattern);
configSource.set(""timezone"", task.getDefaultTimeZone());
this.parser = new TimestampParser(
Exec.newConfigSource().loadConfig(ParserIntlTask.class),
configSource.loadConfig(ParserIntlColumnOption.class));
}
@Override
public Timestamp parse(String s) {
try{
return parser.parse(s);
}catch (Exception e){
return null;
}
}
@Override
public void setToPageBuilder(PageBuilder pageBuilder, int i, String value) {
Timestamp parse = parse(value);
if(parse != null){
pageBuilder.setTimestamp(i, parse);
}else{
pageBuilder.setNull(i);
}
}
}
","package org.embulk.parser.apache.log;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.time.Timestamp;
import org.embulk.spi.time.TimestampParser;
import static org.embulk.spi.type.Types.TIMESTAMP;
public class TimestampLogElement extends LogElement {
private final TimestampParser parser;
public TimestampLogElement(TimestampParser.Task task, String name, String regex) {
this(task, name, regex, ""%d/%b/%Y:%T %z"");
}
public TimestampLogElement(TimestampParser.Task task, String name, String regex, String pattern) {
super(name, regex, TIMESTAMP);
this.parser = new TimestampParser(task.getJRuby(), pattern, task.getDefaultTimeZone());
}
@Override
public Timestamp parse(String s) {
try{
return parser.parse(s);
}catch (Exception e){
return null;
}
}
@Override
public void setToPageBuilder(PageBuilder pageBuilder, int i, String value) {
Timestamp parse = parse(value);
if(parse != null){
pageBuilder.setTimestamp(i, parse);
}else{
pageBuilder.setNull(i);
}
}
}
"
Format records before referencing the message attribute,"import logging
import sys
class SentryHandler(logging.Handler):
def emit(self, record):
from sentry.client.models import get_client
from sentry.client.middleware import SentryLogMiddleware
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMiddleware.thread, 'request', None)
self.format(record)
# Avoid typical config issues by overriding loggers behavior
if record.name == 'sentry.errors':
print >> sys.stderr, ""Recursive log message sent to SentryHandler""
print >> sys.stderr, record.message
return
get_client().create_from_record(record, request=request)
try:
import logbook
except ImportError:
pass
else:
class SentryLogbookHandler(logbook.Handler):
def emit(self, record):
from sentry.client.models import get_client
self.format(record)
# Avoid typical config issues by overriding loggers behavior
if record.name == 'sentry.errors':
print >> sys.stderr, ""Recursive log message sent to SentryHandler""
print >> sys.stderr, record.message
return
kwargs = dict(
message=record.message,
level=record.level,
logger=record.channel,
data=record.extra,
)
client = get_client()
if record.exc_info:
return client.create_from_exception(record.exc_info, **kwargs)
return client.create_from_text(**kwargs)
","import logging
import sys
class SentryHandler(logging.Handler):
def emit(self, record):
from sentry.client.models import get_client
from sentry.client.middleware import SentryLogMiddleware
# Fetch the request from a threadlocal variable, if available
request = getattr(SentryLogMiddleware.thread, 'request', None)
# Avoid typical config issues by overriding loggers behavior
if record.name == 'sentry.errors':
print >> sys.stderr, ""Recursive log message sent to SentryHandler""
print >> sys.stderr, record.message
return
self.format(record)
get_client().create_from_record(record, request=request)
try:
import logbook
except ImportError:
pass
else:
class SentryLogbookHandler(logbook.Handler):
def emit(self, record):
from sentry.client.models import get_client
# Avoid typical config issues by overriding loggers behavior
if record.name == 'sentry.errors':
print >> sys.stderr, ""Recursive log message sent to SentryHandler""
print >> sys.stderr, record.message
return
kwargs = dict(
message=record.message,
level=record.level,
logger=record.channel,
data=record.extra,
)
client = get_client()
if record.exc_info:
return client.create_from_exception(record.exc_info, **kwargs)
return client.create_from_text(**kwargs)
"
Put new activity at the top of the array.,"""use strict"";
(function () {
angular
.module(""argo"")
.factory(""activityService"", activityService);
activityService.$inject = [""$http"", ""$q"", ""sessionService""];
function activityService($http, $q, sessionService) {
var activities = [],
service = {
getActivities: getActivities,
addActivity: addActivity
};
return service;
function getActivities() {
var deferred = $q.defer();
sessionService.isLogged().then(function (credentials) {
$http.post(""/api/transactions"", {
environment: credentials.environment,
token: credentials.token,
accountId: credentials.accountId
}).then(function (transactions) {
activities = transactions.data;
deferred.resolve(activities);
});
});
return deferred.promise;
}
function addActivity(activity) {
activities.splice(0, 0, {
id: activity.id,
type: activity.type,
instrument: activity.instrument,
units: activity.units,
price: activity.price,
pl: activity.pl,
// PROFIT (PIPS)
// PROFIT (%)
accountBalance: activity.accountBalance,
time: activity.time
});
}
}
}());
","""use strict"";
(function () {
angular
.module(""argo"")
.factory(""activityService"", activityService);
activityService.$inject = [""$http"", ""$q"", ""sessionService""];
function activityService($http, $q, sessionService) {
var activities = [],
service = {
getActivities: getActivities,
addActivity: addActivity
};
return service;
function getActivities() {
var deferred = $q.defer();
sessionService.isLogged().then(function (credentials) {
$http.post(""/api/transactions"", {
environment: credentials.environment,
token: credentials.token,
accountId: credentials.accountId
}).then(function (transactions) {
activities = transactions.data;
deferred.resolve(activities);
});
});
return deferred.promise;
}
function addActivity(activity) {
activities.push({
id: activity.id,
type: activity.type,
instrument: activity.instrument,
units: activity.units,
price: activity.price,
pl: activity.pl,
// PROFIT (PIPS)
// PROFIT (%)
accountBalance: activity.accountBalance,
time: activity.time
});
}
}
}());
"
"Remove unnecessary param, it's the default","YUI.add(""stream-user"", function(Y) {
""use strict"";
var falco = Y.namespace(""Falco""),
streams = Y.namespace(""Falco.Streams""),
User;
User = function() {};
User.prototype = {
_create : function() {
var stream;
stream = falco.twitter.stream(""user"");
stream.on(""tweet"", this._tweet.bind(this));
stream.on(""friends"", this._friends.bind(this));
this._stream = stream;
},
_tweet : function(data) {
this.fire(""tweet"", {
tweet : data,
src : ""user""
});
},
_friends : function(data) {
this.fire(""friends"", data.friends.map(function(id) {
return {
id : id
};
}));
}
};
Y.augment(User, streams.Base);
streams.User = User;
streams.user = new User();
}, ""@VERSION@"", {
requires : [
// YUI
""oop"",
""event-custom"",
// Streams
""stream-base""
]
});
","YUI.add(""stream-user"", function(Y) {
""use strict"";
var falco = Y.namespace(""Falco""),
streams = Y.namespace(""Falco.Streams""),
User;
User = function() {};
User.prototype = {
_create : function() {
var stream;
stream = falco.twitter.stream(""user"", {
with : ""followings""
});
stream.on(""tweet"", this._tweet.bind(this));
stream.on(""friends"", this._friends.bind(this));
this._stream = stream;
},
_tweet : function(data) {
this.fire(""tweet"", {
tweet : data,
src : ""user""
});
},
_friends : function(data) {
this.fire(""friends"", data.friends.map(function(id) {
return {
id : id
};
}));
}
};
Y.augment(User, streams.Base);
streams.User = User;
streams.user = new User();
}, ""@VERSION@"", {
requires : [
// YUI
""oop"",
""event-custom"",
// Streams
""stream-base""
]
});
"
Increase pause time of home slider,"var LightSliderHomeInit = function() {
//
// Init
//
this.init();
};
LightSliderHomeInit.prototype.init = function() {
var that = this;
$('[data-slider-home]').lightSlider({
item: 1,
slideMargin: 0,
pager: false,
loop: true,
auto: true,
pauseOnHover: true,
pause: 5000,
onAfterSlide: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.removeClass('active');
$($pages[slider.getCurrentSlideCount()-1]).addClass('active');
},
onSliderLoad: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.each(function(idx) {
var that = $(this);
that.click(function(e) {
e.preventDefault();
$pages.removeClass('active');
that.addClass('active');
slider.goToSlide(idx+1);
return false;
});
});
}
});
};
module.exports = LightSliderHomeInit;
","var LightSliderHomeInit = function() {
//
// Init
//
this.init();
};
LightSliderHomeInit.prototype.init = function() {
var that = this;
$('[data-slider-home]').lightSlider({
item: 1,
slideMargin: 0,
pager: false,
loop: true,
auto: true,
pauseOnHover: true,
pause: 3000,
onAfterSlide: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.removeClass('active');
$($pages[slider.getCurrentSlideCount()-1]).addClass('active');
},
onSliderLoad: function(slider) {
var $pages = slider.parents('.slider-home').find('.slider-home__pager li');
$pages.each(function(idx) {
var that = $(this);
that.click(function(e) {
e.preventDefault();
$pages.removeClass('active');
that.addClass('active');
slider.goToSlide(idx+1);
return false;
});
});
}
});
};
module.exports = LightSliderHomeInit;
"
Improve naming in test case,"swift_mailer = \Mockery::mock('swift_mailer')->shouldReceive('send')->once()
->with(\Mockery::on($this->validateEmail()))->getMock();
$this->template = \Mockery::mock('template')->shouldIgnoreMissing();
$this->config_email = 'admin@example.com';
$this->config_title = 'Reset';
$this->user_email = 'user@example.com';
$this->user_id = 123;
$this->reset_code = '987abc';
$this->reset_mailer = new ResetEmailer($this->swift_mailer, $this->template, $this->config_email, $this->config_title);
}
public function tearDown()
{
\Mockery::close();
}
/** @test */
public function it_sends_the_expected_email()
{
$this->reset_mailer->send($this->user_id, $this->user_email, $this->reset_code);
}
private function validateEmail()
{
return function ($message) {
return $message->getTo() === array($this->user_email => null);
};
}
}
","swift_mailer = \Mockery::mock('mailer')->shouldReceive('send')->once()
->with(\Mockery::on($this->validateEmail()))->getMock();
$this->template = \Mockery::mock('template')->shouldIgnoreMissing();
$this->config_email = 'admin@example.com';
$this->config_title = 'Reset';
$this->user_email = 'user@example.com';
$this->user_id = 123;
$this->reset_code = '987abc';
$this->mailer = new ResetEmailer($this->swift_mailer, $this->template, $this->config_email, $this->config_title);
}
public function tearDown()
{
\Mockery::close();
}
/** @test */
public function it_sends_the_expected_email()
{
$this->mailer->send($this->user_id, $this->user_email, $this->reset_code);
}
private function validateEmail()
{
return function ($message) {
return $message->getTo() === array($this->user_email => null);
};
}
}
"
Add python_requires to help pip,"import io
import os
import re
from setuptools import setup, find_packages
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
version = re.search(r'^__version__ = [\'""]([^\'""]*)[\'""]', f.read())
if version:
return version.group(1)
else:
raise RuntimeError(""Unable to find version string."")
setup(
name='auth0-python',
version=find_version(),
description='Auth0 Python SDK',
author='Auth0',
author_email='support@auth0.com',
license='MIT',
packages=find_packages(),
install_requires=['requests'],
extras_require={'test': ['mock']},
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
url='https://github.com/auth0/auth0-python',
)
","import io
import os
import re
from setuptools import setup, find_packages
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
version = re.search(r'^__version__ = [\'""]([^\'""]*)[\'""]', f.read())
if version:
return version.group(1)
else:
raise RuntimeError(""Unable to find version string."")
setup(
name='auth0-python',
version=find_version(),
description='Auth0 Python SDK',
author='Auth0',
author_email='support@auth0.com',
license='MIT',
packages=find_packages(),
install_requires=['requests'],
extras_require={'test': ['mock']},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
url='https://github.com/auth0/auth0-python',
)
"
Refresh retrieved CLI session variables.,"
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package org.jsimpledb.parse.expr;
import com.google.common.base.Preconditions;
import org.jsimpledb.parse.ParseSession;
/**
* {@link Value} that represents a {@link ParseSession} variable.
*
* @see ParseSession#getVars
*/
public class VarValue extends AbstractLValue {
private final String name;
/**
* Constructor.
*
* @param name variable name
* @throws IllegalArgumentException if name is null
* @throws IllegalArgumentException if name is not a valid Java identifier
*/
public VarValue(String name) {
new AbstractNamed(name) { }; // validates the name
this.name = name;
}
/**
* Get the variable name.
*
* @return variable name
*/
public String getName() {
return this.name;
}
@Override
public Object get(ParseSession session) {
final Value value = session.getVars().get(this.name);
if (value == null)
throw new EvalException(""variable `"" + name + ""' is not defined"");
return MethodUtil.refresh(value.get(session));
}
@Override
public Class> getType(ParseSession session) {
final Value value = session.getVars().get(this.name);
return value != null ? value.getType(session) : Object.class;
}
@Override
public void set(ParseSession session, Value value) {
Preconditions.checkArgument(value != null, ""null value"");
session.getVars().put(this.name, value);
}
}
","
/*
* Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
*/
package org.jsimpledb.parse.expr;
import com.google.common.base.Preconditions;
import org.jsimpledb.parse.ParseSession;
/**
* {@link Value} that represents a {@link ParseSession} variable.
*
* @see ParseSession#getVars
*/
public class VarValue extends AbstractLValue {
private final String name;
/**
* Constructor.
*
* @param name variable name
* @throws IllegalArgumentException if name is null
* @throws IllegalArgumentException if name is not a valid Java identifier
*/
public VarValue(String name) {
new AbstractNamed(name) { }; // validates the name
this.name = name;
}
/**
* Get the variable name.
*
* @return variable name
*/
public String getName() {
return this.name;
}
@Override
public Object get(ParseSession session) {
final Value value = session.getVars().get(this.name);
if (value == null)
throw new EvalException(""variable `"" + name + ""' is not defined"");
return value.get(session);
}
@Override
public Class> getType(ParseSession session) {
final Value value = session.getVars().get(this.name);
return value != null ? value.getType(session) : Object.class;
}
@Override
public void set(ParseSession session, Value value) {
Preconditions.checkArgument(value != null, ""null value"");
session.getVars().put(this.name, value);
}
}
"
Windows: Change 'platforms' to 'platform' when testing 'create',"// Copyright © 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.
var ShellJS = require(""shelljs"");
var Application = require(""../../src/Application"");
var Util = require(""../../test-util/Util.js"");
var _packageId = ""com.example.foo"";
exports.tests = {
main: function(test) {
test.expect(1);
// Just call main without args, this should display help.
// Need to strip extra command-line args though, so the
// command parser is not confused.
process.argv = process.argv.slice(0, 2);
// As long as no exception hits us we're good.
var app = require(""../../src/Main"");
app.run(function (errno) {
test.equal(errno, 0);
test.done();
});
},
create: function(test) {
test.expect(1);
// Good test.
var tmpdir = Util.createTmpDir();
ShellJS.pushd(tmpdir);
var app = require(""../../src/Main"");
Application.call(app, tmpdir, _packageId);
app.create(_packageId, {platform: ""windows""}, function(errno) {
test.equal(errno, 0);
ShellJS.popd();
ShellJS.rm(""-rf"", tmpdir);
test.done();
});
}
};
","// Copyright © 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.
var ShellJS = require(""shelljs"");
var Application = require(""../../src/Application"");
var Util = require(""../../test-util/Util.js"");
var _packageId = ""com.example.foo"";
exports.tests = {
main: function(test) {
test.expect(1);
// Just call main without args, this should display help.
// Need to strip extra command-line args though, so the
// command parser is not confused.
process.argv = process.argv.slice(0, 2);
// As long as no exception hits us we're good.
var app = require(""../../src/Main"");
app.run(function (errno) {
test.equal(errno, 0);
test.done();
});
},
create: function(test) {
test.expect(1);
// Good test.
var tmpdir = Util.createTmpDir();
ShellJS.pushd(tmpdir);
var app = require(""../../src/Main"");
Application.call(app, tmpdir, _packageId);
app.create(_packageId, {platforms: ""windows""}, function(errno) {
test.equal(errno, 0);
ShellJS.popd();
ShellJS.rm(""-rf"", tmpdir);
test.done();
});
}
};
"
Rename the result image to avoid overwriting the original image,"# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4
""""""
第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果
""""""
from PIL import Image, ImageDraw, ImageFont
import sys
def add_num_to_img(file_path):
im = Image.open(file_path)
im_draw = ImageDraw.Draw(im)
font = ImageFont.truetype(""arial.ttf"", int(im.size[0]/5))
im_draw.text((int(im.size[0]-im.size[0]/10), 5), ""4"", (256, 0, 0), font=font)
del im_draw
im.save('./result.png')
if __name__ == ""__main__"":
if len(sys.argv) <= 1:
print(""Need at least 1 parameter. Try to execute 'python 0000.py $image_path'"")
else:
for infile in sys.argv[1:]:
try:
add_num_to_img(infile)
print(""Success!"")
except IOError:
print(""Can't open image!"")
pass
","# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Author:renzongxian
# Date:2014-11-30
# Python 3.4
""""""
第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果
""""""
from PIL import Image, ImageDraw, ImageFont
import sys
def add_num_to_img(file_path):
im = Image.open(file_path)
im_draw = ImageDraw.Draw(im)
font = ImageFont.truetype(""arial.ttf"", int(im.size[0]/5))
im_draw.text((int(im.size[0]-im.size[0]/10), 5), ""4"", (256, 0, 0), font=font)
del im_draw
im.save(file_path)
if __name__ == ""__main__"":
if len(sys.argv) <= 1:
print(""Need at least 1 parameter. Try to execute 'python 0000.py $image_path'"")
else:
for infile in sys.argv[1:]:
try:
add_num_to_img(infile)
print(""Success!"")
except IOError:
print(""Can't open image!"")
pass
"
Fix fast visibility change not registering change,"
define([
'flight/lib/component',
'tpl!./form'
], function(
defineComponent,
formTemplate) {
'use strict';
return defineComponent(VisibilityEditor);
function VisibilityEditor() {
this.defaultAttrs({
fieldSelector: 'input'
})
this.after('initialize', function() {
this.$node.html(formTemplate({
value: $.trim(_.isUndefined(this.attr.value) ? '' : this.attr.value)
}));
this.on('visibilityclear', this.onClear);
this.on('change keyup paste', {
fieldSelector: this.onChange
});
this.onChange();
});
this.onClear = function(event, data) {
this.select('fieldSelector').val('');
};
this.onChange = function(event, data) {
var value = $.trim(this.select('fieldSelector').val());
this.trigger('visibilitychange', {
value: value,
valid: true
});
};
}
});
","
define([
'flight/lib/component',
'tpl!./form'
], function(
defineComponent,
formTemplate) {
'use strict';
return defineComponent(VisibilityEditor);
function VisibilityEditor() {
this.defaultAttrs({
fieldSelector: 'input'
})
this.after('initialize', function() {
this.$node.html(formTemplate({
value: $.trim(_.isUndefined(this.attr.value) ? '' : this.attr.value)
}));
this.onChange = _.debounce(this.onChange.bind(this), 250);
this.on('visibilityclear', this.onClear);
this.on('change keyup paste', {
fieldSelector: this.onChange
});
this.onChange();
});
this.onClear = function(event, data) {
this.select('fieldSelector').val('');
};
this.onChange = function(event, data) {
var value = $.trim(this.select('fieldSelector').val());
this.trigger('visibilitychange', {
value: value,
valid: true
});
};
}
});
"
Rename path parameter in contrib.cms.BundleCMSSW.,"# -*- coding: utf-8 -*-
""""""
CMS-related tasks.
https://home.cern/about/experiments/cms
""""""
__all__ = [""BundleCMSSW""]
import os
import luigi
from law import Task, LocalFileTarget, NO_STR
from law.decorator import log
from law.util import rel_path, interruptable_popen
class BundleCMSSW(Task):
task_namespace = ""law.cms""
cmssw_path = luigi.Parameter(description=""the path to the CMSSW checkout to bundle"")
exclude = luigi.Parameter(default=NO_STR, description=""regular expression for excluding files ""
""or directories, relative to the CMSSW checkout path"")
def __init__(self, *args, **kwargs):
super(BundleCMSSW, self).__init__(*args, **kwargs)
self.cmssw_path = os.path.expandvars(os.path.expanduser(os.path.abspath(self.cmssw_path)))
def output(self):
return LocalFileTarget(""{}.tgz"".format(os.path.basename(self.cmssw_path)))
@log
def run(self):
with self.output().localize(""w"") as tmp:
self.bundle(tmp.path)
def bundle(self, dst_path):
cmd = [rel_path(__file__, ""bundle_cmssw.sh""), self.cmssw_path, dst_path]
if self.exclude != NO_STR:
cmd += [self.exclude]
code = interruptable_popen(cmd)[0]
if code != 0:
raise Exception(""cmssw bundling failed"")
","# -*- coding: utf-8 -*-
""""""
CMS-related tasks.
https://home.cern/about/experiments/cms
""""""
__all__ = [""BundleCMSSW""]
import os
import luigi
from law import Task, LocalFileTarget, NO_STR
from law.decorator import log
from law.util import rel_path, interruptable_popen
class BundleCMSSW(Task):
task_namespace = ""law.cms""
path = luigi.Parameter(description=""the path to the CMSSW checkout to bundle"")
exclude = luigi.Parameter(default=NO_STR, description=""regular expression for excluding files ""
""or directories, relative to the CMSSW checkout path"")
def __init__(self, *args, **kwargs):
super(BundleCMSSW, self).__init__(*args, **kwargs)
self.path = os.path.expandvars(os.path.expanduser(os.path.abspath(self.path)))
def output(self):
return LocalFileTarget(""{}.tgz"".format(os.path.basename(self.path)))
@log
def run(self):
with self.output().localize(""w"") as tmp:
self.bundle(tmp.path)
def bundle(self, dst_path):
cmd = [rel_path(__file__, ""bundle_cmssw.sh""), self.path, dst_path]
if self.exclude != NO_STR:
cmd += [self.exclude]
code = interruptable_popen(cmd)[0]
if code != 0:
raise Exception(""cmssw bundling failed"")
"
Define noop close() for FakeFile,"import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("""")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
def close(self):
""""""
Always hold fake files open.
""""""
pass
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
","import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("""")
ftype = 'dir'
size = 4096
else:
init(value)
ftype = 'file'
size = len(value)
attr = ssh.SFTPAttributes()
attr.st_mode = {'file': stat.S_IFREG, 'dir': stat.S_IFDIR}[ftype]
attr.st_size = size
attr.filename = os.path.basename(path)
self.attributes = attr
def __str__(self):
return self.getvalue()
def write(self, value):
StringIO.write(self, value)
self.attributes.st_size = len(self.getvalue())
class FakeFilesystem(dict):
def __init__(self, d=None):
# Replicate input dictionary using our custom __setitem__
d = d or {}
for key, value in d.iteritems():
self[key] = value
def __setitem__(self, key, value):
if isinstance(value, StringTypes) or value is None:
value = FakeFile(value, key)
super(FakeFilesystem, self).__setitem__(key, value)
"
Add clusterDB to python egg,"from distutils.core import setup
from distutils.command.install import install
import os
import shutil
class issue(Exception):
def __init__(self, errorStr):
self.errorStr = errorStr
def __str__(self):
return repr(self.errorStr)
class post_install(install):
def copyStuff(self, dataDir, destDir):
if os.path.isdir(dataDir) == False:
os.makedirs(dataDir)
_bsDir = os.path.abspath(destDir)
if os.path.exists(_bsDir) == False:
raise issue('No files at: ' % (_bsDir,))
_files = [_bsDir+'/'+_file for _file in os.listdir(_bsDir)]
for _file in _files:
print 'copying %s -> %s' % (_file, dataDir,)
shutil.copy2(_file, dataDir)
def run(self):
install.run(self)
setup(cmdclass = {'install': post_install},
name = 'deeptools',
description = 'Deep Tools',
author = 'Deep Grant',
author_email = 'ralph.wiggum@icloud.com',
url = 'http://deepis.com',
version = '0.1',
packages = ['deep',
'deep.tools',
],
scripts = ['scripts/clusterDb.py',
]
)
","from distutils.core import setup
from distutils.command.install import install
import os
import shutil
class issue(Exception):
def __init__(self, errorStr):
self.errorStr = errorStr
def __str__(self):
return repr(self.errorStr)
class post_install(install):
def copyStuff(self, dataDir, destDir):
if os.path.isdir(dataDir) == False:
os.makedirs(dataDir)
_bsDir = os.path.abspath(destDir)
if os.path.exists(_bsDir) == False:
raise issue('No files at: ' % (_bsDir,))
_files = [_bsDir+'/'+_file for _file in os.listdir(_bsDir)]
for _file in _files:
print 'copying %s -> %s' % (_file, dataDir,)
shutil.copy2(_file, dataDir)
def run(self):
install.run(self)
setup(cmdclass = {'install': post_install},
name = 'deeptools',
description = 'Deep Tools',
author = 'Deep Grant',
author_email = 'ralph.wiggum@icloud.com',
url = 'http://deepis.com',
version = '0.1',
packages = ['deep',
'deep.tools',
],
scripts = [
]
)
"
Use information from stub for finding decorator in decorators list,"package com.jetbrains.python.psi.impl;
import com.intellij.lang.ASTNode;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.psi.PyDecorator;
import com.jetbrains.python.psi.PyDecoratorList;
import com.jetbrains.python.psi.PyElementVisitor;
import com.jetbrains.python.psi.stubs.PyDecoratorListStub;
import org.jetbrains.annotations.NotNull;
/**
* @author dcheryasov
*/
public class PyDecoratorListImpl extends PyBaseElementImpl implements PyDecoratorList{
public PyDecoratorListImpl(ASTNode astNode) {
super(astNode);
}
@Override
protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
pyVisitor.visitPyDecoratorList(this);
}
public PyDecoratorListImpl(final PyDecoratorListStub stub) {
super(stub, PyElementTypes.DECORATOR_LIST);
}
@NotNull
public PyDecorator[] getDecorators() {
final PyDecorator[] decoarray = new PyDecorator[0];
return getStubOrPsiChildren(PyElementTypes.DECORATOR_CALL, decoarray);
//return decoarray;
}
@Override
public PyDecorator findDecorator(String name) {
final PyDecorator[] decorators = getDecorators();
for (PyDecorator decorator : decorators) {
final PyQualifiedName qName = decorator.getQualifiedName();
if (qName != null && name.equals(qName.toString())) {
return decorator;
}
}
return null;
}
}
","package com.jetbrains.python.psi.impl;
import com.intellij.lang.ASTNode;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.psi.PyDecoratorList;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.stubs.PyDecoratorListStub;
import com.jetbrains.python.psi.PyDecorator;
import com.jetbrains.python.psi.PyElementVisitor;
import org.jetbrains.annotations.NotNull;
/**
* @author dcheryasov
*/
public class PyDecoratorListImpl extends PyBaseElementImpl implements PyDecoratorList{
public PyDecoratorListImpl(ASTNode astNode) {
super(astNode);
}
@Override
protected void acceptPyVisitor(PyElementVisitor pyVisitor) {
pyVisitor.visitPyDecoratorList(this);
}
public PyDecoratorListImpl(final PyDecoratorListStub stub) {
super(stub, PyElementTypes.DECORATOR_LIST);
}
@NotNull
public PyDecorator[] getDecorators() {
final PyDecorator[] decoarray = new PyDecorator[0];
return getStubOrPsiChildren(PyElementTypes.DECORATOR_CALL, decoarray);
//return decoarray;
}
@Override
public PyDecorator findDecorator(String name) {
final PyDecorator[] decorators = getDecorators();
for (PyDecorator decorator : decorators) {
final PyExpression callee = decorator.getCallee();
if (callee != null && name.equals(callee.getText())) {
return decorator;
}
}
return null;
}
}
"
Fix path to visualmetrics script after moving js.,"'use strict';
const execa = require('execa'),
log = require('intel'),
get = require('lodash.get'),
path = require('path');
const SCRIPT_PATH = path.join(
__dirname,
'..',
'..',
'..',
'..',
'vendor',
'visualmetrics.py'
);
module.exports = {
checkDependencies() {
return execa(SCRIPT_PATH, ['--check']);
},
run(videoPath, imageDirPath, options) {
const runOnAndroid = get(options, 'chrome.android.package', false);
const filmstripQuality = get(options, 'videoParams.filmstripQuality', 75);
const createFilmstrip = get(options, 'videoParams.createFilmstrip', true);
const fullSizeFilmstrip = get(
options,
'videoParams.filmstripFullSize',
false
);
const scriptArgs = [
'--video',
videoPath,
'--orange',
'--perceptual',
'--force',
'--startwhite',
'--renderignore',
5,
'--json'
];
if (runOnAndroid) {
scriptArgs.push('--viewport');
}
if (createFilmstrip) {
scriptArgs.push('-q');
scriptArgs.push(filmstripQuality);
scriptArgs.unshift('--dir', imageDirPath);
if (fullSizeFilmstrip) {
scriptArgs.push('--full');
}
}
log.verbose('Running visualmetrics.py ' + scriptArgs.join(' '));
return execa(SCRIPT_PATH, scriptArgs).then(result =>
JSON.parse(result.stdout)
);
}
};
","'use strict';
const execa = require('execa'),
log = require('intel'),
get = require('lodash.get'),
path = require('path');
const SCRIPT_PATH = path.join(
__dirname,
'..',
'..',
'..',
'vendor',
'visualmetrics.py'
);
module.exports = {
checkDependencies() {
return execa(SCRIPT_PATH, ['--check']);
},
run(videoPath, imageDirPath, options) {
const runOnAndroid = get(options, 'chrome.android.package', false);
const filmstripQuality = get(options, 'videoParams.filmstripQuality', 75);
const createFilmstrip = get(options, 'videoParams.createFilmstrip', true);
const fullSizeFilmstrip = get(
options,
'videoParams.filmstripFullSize',
false
);
const scriptArgs = [
'--video',
videoPath,
'--orange',
'--perceptual',
'--force',
'--startwhite',
'--renderignore',
5,
'--json'
];
if (runOnAndroid) {
scriptArgs.push('--viewport');
}
if (createFilmstrip) {
scriptArgs.push('-q');
scriptArgs.push(filmstripQuality);
scriptArgs.unshift('--dir', imageDirPath);
if (fullSizeFilmstrip) {
scriptArgs.push('--full');
}
}
log.verbose('Running visualmetrics.py ' + scriptArgs.join(' '));
return execa(SCRIPT_PATH, scriptArgs).then(result =>
JSON.parse(result.stdout)
);
}
};
"
Replace with Google Street View,"""use strict"";
const fs = require('fs');
const url = require('url');
const qs = require('querystring');
const _ = require('lodash');
const builder = require('botbuilder');
const config = fs.existsSync('../config/index.js') ? require('../config') : {};
const api = require('../api');
function getImage(request) {
request = request || {};
return request.media_url || url.format({
protocol : 'https',
host : 'maps.googleapis.com',
pathname : '/maps/api/streetview',
search : qs.stringify({
location : `${request.lat},${request.long}`,
size : '600x300',
key : process.env.GOOGLE_STREET_VIEW_API_KEY || config.GOOGLE_STREET_VIEW_API_KEY
})
});
}
module.exports = [
function (session) {
api.getRequests()
.then((results) => {
console.log(results);
const requests = _.chain(results).get('data').take(10).value();
const cards = requests.map((request) => {
return new builder.HeroCard(session)
.title(request.service_name)
.text(request.description)
.images([
builder.CardImage.create(session, getImage(request))
]);
});
const message = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(cards);
session.send(message);
session.endDialog();
})
.catch((err) => {
// Handle error
});
}
];","""use strict"";
const fs = require('fs');
const url = require('url');
const qs = require('querystring');
const _ = require('lodash');
const builder = require('botbuilder');
const config = fs.existsSync('../config/index.js') ? require('../config') : {};
const api = require('../api');
function getImage(request) {
request = request || {};
return request.media_url || url.format({
protocol : 'https',
host : 'maps.googleapis.com',
pathname : '/maps/api/staticmap',
search : qs.stringify({
center : `${request.lat},${request.long}`,
zoom : 17,
size : '600x300',
key : process.env.GOOGLE_MAPS_API_KEY || config.GOOGLE_MAPS_API_KEY
})
});
}
module.exports = [
function (session) {
api.getRequests()
.then((results) => {
const requests = _.chain(results).get('data').take(10).value();
const cards = requests.map((request) => {
return new builder.HeroCard(session)
.title(request.service_name)
.text(request.description)
.images([
builder.CardImage.create(session, getImage(request))
]);
});
const message = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(cards);
session.send(message);
});
}
];"
Add the @Override decorator to onBackPressed().,"/*
* Copyright (c) Mattia Barbon
* distributed under the terms of the MIT license
*/
package org.barbon.acash;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
public class AboutDialog extends Dialog {
public AboutDialog(Context context) {
super(context);
setTitle(R.string.about_title);
setContentView(R.layout.about_dialog);
TextView click1 = (TextView) findViewById(R.id.about_clickable_1);
TextView click2 = (TextView) findViewById(R.id.about_clickable_2);
click1.setMovementMethod(LinkMovementMethod.getInstance());
click2.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
public void onBackPressed() {
// saves ""displayed_about"" more oft than needed, but it should
// not be a problem
SharedPreferences prefs =
getContext().getSharedPreferences(""global"", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(""displayed_about"", true);
editor.commit();
super.onBackPressed();
}
/* returns true if the dialog has not been shown yet */
public static boolean showFirstTime(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(""global"", Context.MODE_PRIVATE);
return !prefs.getBoolean(""displayed_about"", false);
}
}
","/*
* Copyright (c) Mattia Barbon
* distributed under the terms of the MIT license
*/
package org.barbon.acash;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
public class AboutDialog extends Dialog {
public AboutDialog(Context context) {
super(context);
setTitle(R.string.about_title);
setContentView(R.layout.about_dialog);
TextView click1 = (TextView) findViewById(R.id.about_clickable_1);
TextView click2 = (TextView) findViewById(R.id.about_clickable_2);
click1.setMovementMethod(LinkMovementMethod.getInstance());
click2.setMovementMethod(LinkMovementMethod.getInstance());
}
public void onBackPressed() {
// saves ""displayed_about"" more oft than needed, but it should
// not be a problem
SharedPreferences prefs =
getContext().getSharedPreferences(""global"", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(""displayed_about"", true);
editor.commit();
super.onBackPressed();
}
/* returns true if the dialog has not been shown yet */
public static boolean showFirstTime(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(""global"", Context.MODE_PRIVATE);
return !prefs.getBoolean(""displayed_about"", false);
}
}
"
Make sure we are the first decorator,"processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
if (!$config['enabled']) {
return;
}
switch($config['translation_service']) {
case 'google':
$translatorServiceDef = $container->register('happyr.translation.auto.service', GoogleTranslator::class);
$translatorServiceDef->addArgument($config['google_key']);
break;
default:
throw new \RuntimeException('You must choose a translation service for AutoFallbackTranslatorBundle.');
}
$translatorServiceDef->addMethodCall('setCachePool', [new Reference($config['cache_service'])]);
$container->findDefinition('happyr.translation.auto_fallback_translator')
->replaceArgument(0, $config['default_locale'])
->replaceArgument(2, $translatorServiceDef)
->setDecoratedService('translator', null, 10);
}
}
","processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
if (!$config['enabled']) {
return;
}
switch($config['translation_service']) {
case 'google':
$translatorServiceDef = $container->register('happyr.translation.auto.service', GoogleTranslator::class);
$translatorServiceDef->addArgument($config['google_key']);
break;
default:
throw new \RuntimeException('You must choose a translation service for AutoFallbackTranslatorBundle.');
}
$translatorServiceDef->addMethodCall('setCachePool', [new Reference($config['cache_service'])]);
$container->findDefinition('happyr.translation.auto_fallback_translator')
->replaceArgument(0, $config['default_locale'])
->replaceArgument(2, $translatorServiceDef)
->setDecoratedService('translator');
}
}
"
Add authentication check in group controller,"zfcUserAuthentication()->hasIdentity()) {
$this->flashMessenger()->addErrorMessage('You have to be logged in to create an account');
return $this->redirect()->toRoute('home');
}
/** @var \Zend\Form\Form $groupEntity */
$groupForm = $this->getServiceLocator()->get('Application\Form\Group');
$groupEntity = new Group();
$groupForm->bind($groupEntity);
if ($this->getRequest()->isPost()) {
$groupForm->setData($this->getRequest()->getPost());
if ($groupForm->isValid()) {
$entityManager = $this->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$entityManager->persist($groupEntity);
$entityManager->flush();
return $this->redirect()->toRoute('group');
}
}
return new ViewModel(['groupForm' => $groupForm]);
}
}
","getServiceLocator()->get('Application\Form\Group');
$groupEntity = new Group();
$groupForm->bind($groupEntity);
if ($this->getRequest()->isPost()) {
$groupForm->setData($this->getRequest()->getPost());
if ($groupForm->isValid()) {
$entityManager = $this->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$entityManager->persist($groupEntity);
$entityManager->flush();
return $this->redirect()->toRoute('group');
}
}
return new ViewModel(['groupForm' => $groupForm]);
}
}
"
"Use lstatSync to know is a file exist
access function follow symbolic links and tests if target file exist and
not the link","const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get writeFile() {
return util.promisify(fs.writeFile)
}
static get mkdir() {
return util.promisify(fs.mkdir)
}
static get rename() {
return util.promisify(fs.rename)
}
static fileExist(filename = '') {
try {
fs.lstatSync(filename)
} catch (e) {
return false
}
return true
}
static mkdirp(pathname = '') {
const pathParts = pathname.split('/')
return pathParts.reduce((promise, part) => promise
.then(previousPath => {
const newPath = path.join(previousPath, part)
if (FsUtils.fileExist(newPath)) {
return newPath
}
return FsUtils.mkdir(newPath)
.catch(error => {
if (error.code !== 'EEXIST') {
throw new Error('dir_create_failed')
}
})
.then(() => newPath)
}), Promise.resolve(pathname[0] === '/' ? '/' : ''))
}
}
module.exports = exports = { FsUtils }
","const fs = require('fs')
const util = require('util')
const path = require('path')
class FsUtils {
static get chmod() {
return util.promisify(fs.chmod)
}
static get readFile() {
return util.promisify(fs.readFile)
}
static get symlink() {
return util.promisify(fs.symlink)
}
static get writeFile() {
return util.promisify(fs.writeFile)
}
static get mkdir() {
return util.promisify(fs.mkdir)
}
static get rename() {
return util.promisify(fs.rename)
}
static fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
static mkdirp(pathname = '') {
const pathParts = pathname.split('/')
return pathParts.reduce((promise, part) => promise
.then(previousPath => {
const newPath = path.join(previousPath, part)
if (FsUtils.fileExist(newPath)) {
return newPath
}
return FsUtils.mkdir(newPath)
.catch(error => {
if (error.code !== 'EEXIST') {
throw new Error('dir_create_failed')
}
})
.then(() => newPath)
}), Promise.resolve(pathname[0] === '/' ? '/' : ''))
}
}
module.exports = exports = { FsUtils }
"
"Include all audio, video and subtitles streams","'''
Minimal VLC client for AceProxy. Messages class.
'''
class VlcMessage(object):
class request(object):
SHUTDOWN = 'shutdown'
@staticmethod
def startBroadcast(stream_name, input, out_port, muxer='ts', pre_access=''):
return 'new ""' + stream_name + '"" broadcast input ""' + input + '"" output ' + (pre_access + ':' if pre_access else '#') + \
'http{mux=' + muxer + ',dst=:' + \
str(out_port) + '/' + stream_name + '} option sout-keep option sout-all enabled' + \
""\r\n"" + 'control ""' + stream_name + '"" play'
@staticmethod
def stopBroadcast(stream_name):
return 'del ""' + stream_name + '""'
@staticmethod
def pauseBroadcast(stream_name):
return 'control ""' + stream_name + '"" pause'
@staticmethod
def unPauseBroadcast(stream_name):
return 'control ""' + stream_name + '"" play'
class response(object):
WRONGPASS = 'Wrong password'
AUTHOK = 'Welcome, Master'
BROADCASTEXISTS = 'Name already in use'
SYNTAXERR = 'Wrong command syntax'
STARTOK = 'new'
STOPOK = 'del'
STOPERR = 'media unknown'
SHUTDOWN = 'Bye-bye!'
","'''
Minimal VLC client for AceProxy. Messages class.
'''
class VlcMessage(object):
class request(object):
SHUTDOWN = 'shutdown'
@staticmethod
def startBroadcast(stream_name, input, out_port, muxer='ts', pre_access=''):
return 'new ""' + stream_name + '"" broadcast input ""' + input + '"" output ' + (pre_access + ':' if pre_access else '#') + \
'http{mux=' + muxer + ',dst=:' + \
str(out_port) + '/' + stream_name + '} enabled' + \
""\r\n"" + 'control ""' + stream_name + '"" play'
@staticmethod
def stopBroadcast(stream_name):
return 'del ""' + stream_name + '""'
@staticmethod
def pauseBroadcast(stream_name):
return 'control ""' + stream_name + '"" pause'
@staticmethod
def unPauseBroadcast(stream_name):
return 'control ""' + stream_name + '"" play'
class response(object):
WRONGPASS = 'Wrong password'
AUTHOK = 'Welcome, Master'
BROADCASTEXISTS = 'Name already in use'
SYNTAXERR = 'Wrong command syntax'
STARTOK = 'new'
STOPOK = 'del'
STOPERR = 'media unknown'
SHUTDOWN = 'Bye-bye!'
"
Use jQuery for misc. UI code,"var IPHistory = (function() {
'use strict';
var no_messages_error = ""Your account has no Login/Logout activity."";
function updateTable(batch) {
IPHistoryUI.updateTable(batch);
if (batch.length) {
return;
}
$('#login-history-table tbody')
.append($('
', {class: 'flex-tr'})
.append($(' | ', {colspan: 6})
.append($('', {
class: 'notice-msg center-text',
text: text.localize(no_messages_error)
})
)
)
);
}
function handler(response) {
if (response.error && response.error.message) {
$('#err').text(response.error.message);
return;
}
updateTable(response.login_history);
}
// localize, title, create tables
// register the callback on IPHistoryQueue
function init() {
var $title = $('#login_history-title').children().first();
$title.text(text.localize($title.text()));
IPHistoryUI.createEmptyTable().appendTo('#login_history-ws-container');
IPHistoryQueue.register(handler);
IPHistoryQueue.fetchNext({limit: 50});
}
function clean() {
$('#login_history-ws-container .error-msg').text('');
IPHistoryUI.clearTableContent();
IPHistoryQueue.clear();
}
return {
init: init,
clean: clean,
};
})();
","var IPHistory = (function() {
'use strict';
var no_messages_error = ""Your account has no Login/Logout activity."";
function updateTable(batch) {
IPHistoryUI.updateTable(batch);
if (batch.length) {
return;
}
$('#login-history-table tbody')
.append($('
', {class: 'flex-tr'})
.append($(' | ', {colspan: 6})
.append($('', {
class: 'notice-msg center-text',
text: text.localize(no_messages_error)
})
)
)
);
}
function handler(response) {
if (response.error && response.error.message) {
document.getElementById('err').textContent = response.error.message;
return;
}
updateTable(response.login_history);
}
// localize, title, create tables
// register the callback on IPHistoryQueue
function init() {
var titleElement = document.getElementById('login_history-title').firstElementChild;
titleElement.textContent = text.localize(titleElement.textContent);
IPHistoryUI.createEmptyTable().appendTo('#login_history-ws-container');
IPHistoryQueue.register(handler);
IPHistoryQueue.fetchNext({limit: 50});
}
function clean() {
$('#login_history-ws-container .error-msg').text('');
IPHistoryUI.clearTableContent();
IPHistoryQueue.clear();
}
return {
init: init,
clean: clean,
};
})();
"
Add freeze task to invoke,"from invoke import run, task
TESTPYPI = ""https://testpypi.python.org/pypi""
@task
def lint(ctx):
""""""Run flake8 to lint code""""""
run(""flake8"")
@task
def freeze(ctx):
""""""Freeze the pip requirements""""""
run(""pip freeze -l > requirements.txt"")
@task(lint)
def test(ctx):
""""""Lint, unit test, and check setup.py""""""
cmd = ""{} {}"".format(
""nosetests"",
""--with-coverage --cover-erase --cover-package=keysight --cover-html"")
run(cmd)
@task
def release(ctx, deploy=False, test=False, version=''):
""""""Tag release, run Travis-CI, and deploy to PyPI
""""""
if test:
run(""python setup.py check"")
run(""python setup.py register sdist upload --dry-run"")
if deploy:
run(""python setup.py check"")
if version:
run(""git checkout master"")
run(""git tag -a v{ver} -m 'v{ver}'"".format(ver=version))
run(""git push"")
run(""git push origin --tags"")
else:
print(""- Have you updated the version?"")
print(""- Have you updated CHANGELOG.md?"")
print(""- Have you fixed any last minute bugs?"")
print(""If you answered yes to all of the above questions,"")
print(""then run `invoke release --deploy -vX.YY.ZZ` to:"")
print(""- Checkout master"")
print(""- Tag the git release with provided vX.YY.ZZ version"")
print(""- Push the master branch and tags to repo"")
print(""- Deploy to PyPi using Travis"")
","from invoke import run, task
TESTPYPI = ""https://testpypi.python.org/pypi""
@task
def lint(ctx):
""""""Run flake8 to lint code""""""
run(""flake8"")
@task(lint)
def test(ctx):
""""""Lint, unit test, and check setup.py""""""
cmd = ""{} {}"".format(
""nosetests"",
""--with-coverage --cover-erase --cover-package=keysight --cover-html"")
run(cmd)
@task()
def release(ctx, deploy=False, test=False, version=''):
""""""Tag release, run Travis-CI, and deploy to PyPI
""""""
if test:
run(""python setup.py check"")
run(""python setup.py register sdist upload --dry-run"")
if deploy:
run(""python setup.py check"")
if version:
run(""git checkout master"")
run(""git tag -a v{ver} -m 'v{ver}'"".format(ver=version))
run(""git push"")
run(""git push origin --tags"")
else:
print(""- Have you updated the version?"")
print(""- Have you updated CHANGELOG.md?"")
print(""- Have you fixed any last minute bugs?"")
print(""If you answered yes to all of the above questions,"")
print(""then run `invoke release --deploy -vX.YY.ZZ` to:"")
print(""- Checkout master"")
print(""- Tag the git release with provided vX.YY.ZZ version"")
print(""- Push the master branch and tags to repo"")
print(""- Deploy to PyPi using Travis"")
"
"Remove misleading example - api.Notifications() was removed from the API in favour of a callback.
(We need processing associated with the callback to be complete by the time the callback completes.
Use of a channel would require that we copy the C notification into the Go heap on every notification and
I didn't want to require that cost)
Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@ninjablocks.com>","//
// openzwave provides a thin Go wrapper around the openzwave library.
//
// The following shows a simple use of the API which will log every notification received.
//
// var loop = func(api openzwave.API) {
// fmt.Printf(""event loop starts\n"")
// for {
// select {
// case quitNow := <-api.QuitSignal():
// _ = quitNow
// fmt.Printf(""event loop ends\n"")
// return
// }
// }
// }
//
// os.Exit(openzwave.
// BuildAPI(""../go-openzwave/openzwave/config"", """", """").
// AddIntOption(""SaveLogLevel"", LOG_LEVEL.NONE).
// AddIntOption(""QueueLogLevel"", LOG_LEVEL.NONE).
// AddIntOption(""DumpTrigger"", LOG_LEVEL.NONE).
// AddIntOption(""PollInterval"", 500).
// AddBoolOption(""IntervalBetweenPolls"", true).
// AddBoolOption(""ValidateValueChanges"", true).
// Run(loop))
package openzwave
","//
// openzwave provides a thin Go wrapper around the openzwave library.
//
// The following shows a simple use of the API which will log every notification received.
//
// var loop = func(api openzwave.API) {
// fmt.Printf(""event loop starts\n"")
// for {
// select {
// case notification := <-api.Notifications():
// fmt.Printf(""notification received - %v"", notification)
// api.FreeNotification(notification)
// case quitNow := <-api.QuitSignal():
// _ = quitNow
// fmt.Printf(""event loop ends\n"")
// return
// }
// }
// }
//
// os.Exit(openzwave.
// BuildAPI(""../go-openzwave/openzwave/config"", """", """").
// AddIntOption(""SaveLogLevel"", LOG_LEVEL.NONE).
// AddIntOption(""QueueLogLevel"", LOG_LEVEL.NONE).
// AddIntOption(""DumpTrigger"", LOG_LEVEL.NONE).
// AddIntOption(""PollInterval"", 500).
// AddBoolOption(""IntervalBetweenPolls"", true).
// AddBoolOption(""ValidateValueChanges"", true).
// Run(loop))
package openzwave
"
Add Slackclient to the package requirements,"from __future__ import unicode_literals
import re
from setuptools import find_packages, setup
def get_version(filename):
with open(filename) as fh:
metadata = dict(re.findall(""__([a-z]+)__ = '([^']+)'"", fh.read()))
return metadata['version']
setup(
name='Mopidy-Tachikoma',
version=get_version('mopidy_tachikoma/__init__.py'),
url='https://github.com/palfrey/mopidy-tachikoma',
license='GNU Affero General Public License, Version 3',
author='Tom Parker',
author_email='palfrey@tevp.net',
description='Mopidy extension for talking to Slack',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'slackclient',
'Mopidy >= 1.0',
'Pykka >= 1.1',
],
entry_points={
'mopidy.ext': [
'tachikoma = mopidy_tachikoma:Extension',
],
},
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Multimedia :: Sound/Audio :: Players',
],
)
","from __future__ import unicode_literals
import re
from setuptools import find_packages, setup
def get_version(filename):
with open(filename) as fh:
metadata = dict(re.findall(""__([a-z]+)__ = '([^']+)'"", fh.read()))
return metadata['version']
setup(
name='Mopidy-Tachikoma',
version=get_version('mopidy_tachikoma/__init__.py'),
url='https://github.com/palfrey/mopidy-tachikoma',
license='GNU Affero General Public License, Version 3',
author='Tom Parker',
author_email='palfrey@tevp.net',
description='Mopidy extension for talking to Slack',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'Mopidy >= 1.0',
'Pykka >= 1.1',
],
entry_points={
'mopidy.ext': [
'tachikoma = mopidy_tachikoma:Extension',
],
},
classifiers=[
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Multimedia :: Sound/Audio :: Players',
],
)
"
"Use a generator for rendering, and pass nodelist unwrapped","
import ast
from . import parse
class Template:
def __init__(self, raw):
self.raw = raw
self.nodelist = parse.parse(raw)
code = ast.Expression(
body=ast.GeneratorExp(
elt=ast.Call(
func=ast.Name(id='str', ctx=ast.Load()),
args=[
ast.Call(
func=ast.Attribute(
value=ast.Name(id='x', ctx=ast.Load()),
attr='render',
ctx=ast.Load()
),
args=[ ast.Name(id='context', ctx=ast.Load()), ],
keywords=[], starargs=None, kwargs=None
),
],
keywords=[], starargs=None, kwargs=None
),
generators=[
ast.comprehension(
target=ast.Name(id='x', ctx=ast.Store()),
iter=ast.Name(id='nodelist', ctx=ast.Load()),
ifs=[]
),
]
)
)
ast.fix_missing_locations(code)
self.code = compile(code, filename='', mode='eval')
def render(self, context):
global_ctx = {
'nodelist': self.nodelist,
'context': dict(context),
}
return ''.join(eval(self.code, global_ctx, {}))
","
import ast
from . import parse
class Template:
def __init__(self, raw):
self.raw = raw
self.root = parse.parse(raw)
code = ast.Expression(
body=ast.ListComp(
elt=ast.Call(
func=ast.Name(id='str', ctx=ast.Load()),
args=[
ast.Call(
func=ast.Attribute(
value=ast.Name(id='x', ctx=ast.Load()),
attr='render',
ctx=ast.Load()
),
args=[
ast.Name(id='context', ctx=ast.Load()),
], keywords=[], starargs=None, kwargs=None
),
], keywords=[], starargs=None, kwargs=None
),
generators=[
ast.comprehension(
target=ast.Name(id='x', ctx=ast.Store()),
iter=ast.Name(id='nodelist', ctx=ast.Load()),
ifs=[]
),
]
)
)
ast.fix_missing_locations(code)
self.code = compile(code, filename='', mode='eval')
def render(self, context):
global_ctx = {
'nodelist': self.root.nodelist,
'context': dict(context),
}
return ''.join(eval(self.code, global_ctx, {}))
"
Update jshint to work with the correct files.,"module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
geojson_to_gmaps: {
src: 'geojson-to-gmaps.js',
options: {
specs: 'spec/*Spec.js',
helpers: 'spec/*Helper.js',
vendor: 'vendor/*.js'
}
}
},
jshint: {
all: ['Gruntfile.js', 'geojson-to-gmaps.js', 'spec/**/*.js']
},
uglify: {
options: {
banner: ""/***\n\ngeojson-to-gmaps.js\n\n"" + grunt.file.read('LICENSE') + ""\n\n***/\n""
},
my_target: {
files: {
'geojson-to-gmaps.min.js': ['geojson-to-gmaps.js']
}
}
}
});
// Load the plugin that provides the ""uglify"" task.
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['jasmine']);
grunt.registerTask('build', 'Build a release.', ['jasmine', 'uglify']);
};
","module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
geojson_to_gmaps: {
src: 'geojson-to-gmaps.js',
options: {
specs: 'spec/*Spec.js',
helpers: 'spec/*Helper.js',
vendor: 'vendor/*.js'
}
}
},
jshint: {
all: ['Gruntfile.js', 'src/**/*.js', 'spec/**/*.js']
},
uglify: {
options: {
banner: ""/***\n\ngeojson-to-gmaps.js\n\n"" + grunt.file.read('LICENSE') + ""\n\n***/\n""
},
my_target: {
files: {
'geojson-to-gmaps.min.js': ['geojson-to-gmaps.js']
}
}
}
});
// Load the plugin that provides the ""uglify"" task.
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['jasmine']);
grunt.registerTask('build', 'Build a release.', ['jasmine', 'uglify']);
};
"
"Move newline handling to a function.
Allows library users to choose to force trailing newlines.","#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse
class RootRequired(Exception):
""""""Our standard exception.""""""
pass
def send(data, tty):
if len(data):
# Handle trailing newline
if data[-1][-1] != '\n':
data += '\n'
send_raw(data, tty)
def send_raw(data, tty):
""""""Send each char of data to tty.""""""
if(os.getuid() != 0):
raise RootRequired('Only root can send input to other TTYs.')
for c in data:
fcntl.ioctl(tty, termios.TIOCSTI, c)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tty', type=argparse.FileType('w'),
help='display a square of a given number')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', action='store_true',
help='Do not force a trailing newline character.')
group.add_argument('--stdin', action='store_true',
help='Read input from stdin.')
args, data = parser.parse_known_args()
# Prepare data
if args.stdin:
data = sys.stdin.read()
else:
data = ' '.join(data)
# Send data
try:
if args.n:
send_raw(data, args.tty)
else:
send(data, args.tty)
except RootRequired, e:
sys.exit(print('ERROR:', e, file=sys.stderr))
","from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse
class RootRequired(Exception):
""""""Our standard exception.""""""
pass
def send(data, tty):
""""""Send each char of data to tty.""""""
if(os.getuid() != 0):
raise RootRequired('Only root can send input to other TTYs.')
for c in data:
fcntl.ioctl(tty, termios.TIOCSTI, c)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('tty', type=argparse.FileType('w'),
help='display a square of a given number')
group = parser.add_mutually_exclusive_group()
group.add_argument('-n', action='store_true',
help='Do not print the trailing newline character.')
group.add_argument('--stdin', action='store_true',
help='Read input from stdin.')
args, data = parser.parse_known_args()
# Prepare data
if args.stdin:
data = sys.stdin.read()
else:
data = ' '.join(data)
# Send data
try:
send(data, args.tty)
except RootRequired, e:
sys.exit(print('ERROR:', e, file=sys.stderr))
# Handle trailing newline
if data[-1][-1] != '\n' and not args.n:
send('\n', args.tty)
"
[docs]: Add a bit of description for the window js.,"/**
* UI module for keyboard interaction with window view.
*/
!function () {
var keys
, timer
, timeout = 300
, issueURLs = []
, issueIndex = ''
;
var issues = Array.prototype.slice.call( document.querySelectorAll( '.issue' ) );
function range( start, count, obj ) {
Array.apply( 0, Array( count ) ).forEach( function ( val, index ) {
obj[ index + start ] = index;
});
return obj;
}
function goToIssue( index ) {
issueIndex = '';
window.location.assign( issueURLs[ index ] );
return;
}
keys = range( 48, 10, {} );
keys = range( 96, 10, keys );
issues.forEach( function ( issue ) {
issueURLs.push( issue.getAttribute( 'data-file' ) );
issue.addEventListener( 'click', function (e) {
if ( e.target.classList.contains( 'rule-id' ) ) return;
var index = issues.reduce( function ( prev, node, index ) {
if ( node == e.currentTarget ) {
return index;
}
return prev;
}, undefined );
goToIssue( index );
});
});
document.addEventListener( 'keydown', function ( e ) {
var num = keys[ e.which ];
if ( num === undefined ) return;
issueIndex += num;
clearTimeout( timer );
timer = setTimeout( function() {
goToIssue( issueIndex - 1 );
}, timeout );
});
}();","!function () {
var keys
, timer
, timeout = 300
, issueURLs = []
, issueIndex = ''
;
var issues = Array.prototype.slice.call( document.querySelectorAll( '.issue' ) );
function range( start, count, obj ) {
Array.apply( 0, Array( count ) ).forEach( function ( val, index ) {
obj[ index + start ] = index;
});
return obj;
}
function goToIssue( index ) {
issueIndex = '';
window.location.assign( issueURLs[ index ] );
return;
}
keys = range( 48, 10, {} );
keys = range( 96, 10, keys );
issues.forEach( function ( issue ) {
issueURLs.push( issue.getAttribute( 'data-file' ) );
issue.addEventListener( 'click', function (e) {
if ( e.target.classList.contains( 'rule-id' ) ) return;
var index = issues.reduce( function ( prev, node, index ) {
if ( node == e.currentTarget ) {
return index;
}
return prev;
}, undefined );
goToIssue( index );
});
});
document.addEventListener( 'keydown', function ( e ) {
var num = keys[ e.which ];
if ( num === undefined ) return;
issueIndex += num;
clearTimeout( timer );
timer = setTimeout( function() {
goToIssue( issueIndex - 1 );
}, timeout );
});
}();"
Fix for refreshing the max amount of the knob when the max value its bound to is changed,"angular.module('ui.knob', [])
.directive('knob', function () {
return {
restrict: 'EACM',
template: function(elem, attrs){
return '';
},
replace: true,
scope: true,
link: function (scope, elem, attrs) {
scope.knob = scope.$eval(attrs.knobData);
var renderKnob = function(){
scope.knob = scope.$eval(attrs.knobData);
var opts = {};
if(!angular.isUndefined(attrs.knobOptions)){
opts = scope.$eval(attrs.knobOptions);
}
if(!angular.isUndefined(attrs.knobMax)){
var max = scope.$eval(attrs.knobMax);
if(!angular.isUndefined(max)){
opts.max = max;
}
}
$elem = $(elem);
$elem.val(scope.knob);
$elem.change();
$elem.knob(opts);
};
var updateMax = function updateMax() {
var max = scope.$eval(attrs.knobMax);
var val = scope.$eval(attrs.knobData);
$elem = $(elem);
$elem.trigger('configure', {
'max': parseInt(max)
}).trigger('change');
$elem.val(val);
$elem.change();
}
scope.$watch(attrs.knobData, function () {
renderKnob();
});
scope.$watch(attrs.knobMax, function() {
updateMax();
});
scope.$watch(attrs.knobOptions, function () {
renderKnob();
}, true);
}
};
});","angular.module('ui.knob', [])
.directive('knob', function () {
return {
restrict: 'EACM',
template: function(elem, attrs){
return '';
},
replace: true,
scope: true,
link: function (scope, elem, attrs) {
scope.knob = scope.$eval(attrs.knobData);
var renderKnob = function(){
scope.knob = scope.$eval(attrs.knobData);
var opts = {};
if(!angular.isUndefined(attrs.knobOptions)){
opts = scope.$eval(attrs.knobOptions);
}
if(!angular.isUndefined(attrs.knobMax)){
var max = scope.$eval(attrs.knobMax);
if(!angular.isUndefined(max)){
opts.max = max;
}
}
$elem = $(elem);
$elem.val(scope.knob);
$elem.change();
$elem.knob(opts);
};
scope.$watch(attrs.knobData, function () {
renderKnob();
});
scope.$watch(attrs.knobOptions, function () {
renderKnob();
}, true);
}
};
});"
"Revert ""Add new hooks for global level (@BeforeAll and @AfterAll) that run only once before all and after all existing features/scenarios. Unit test and cucumber test to cover the new hooks and the running order between hooks.""
This reverts commit 34332ef30d22ad24aa8186b5112f93f0ba8e1b3d.","package cucumber.runtime.java.hooks;
public class HttpServerStub {
private boolean isStarted;
private Request request;
public void start() {
if (isStarted) {
throw new IllegalStateException(""Server already started!"");
}
try {
Thread.sleep(2000);
isStarted = true;
} catch (InterruptedException e) {}
}
public void stop() {
if (!isStarted) {
throw new IllegalStateException(""Server is not running!"");
}
try {
Thread.sleep(2000);
isStarted = false;
} catch (InterruptedException e) {}
}
public boolean isStarted() {
return isStarted;
}
public int send(Request request) {
if (!isStarted) {
throw new IllegalStateException(""server is not running"");
}
this.request = request;
return 200;
}
public String receive() {
if (!isStarted) {
throw new IllegalStateException(""server is not running"");
}
return request.getData();
}
public void clean() {
request = new Request(null);
}
static class Request {
private T data;
Request(T data) {
this.data = data;
}
T getData() {
return data;
}
}
}
","package cucumber.runtime.java.hooks;
public class HttpServerStub {
private boolean isStarted;
private Request request;
public void start() {
if (isStarted) {
throw new IllegalStateException(""Server already started!"");
}
try {
Thread.sleep(2000);
isStarted = true;
} catch (InterruptedException e) {}
}
public void stop() {
if (!isStarted) {
throw new IllegalStateException(""Server is not running!"");
}
try {
Thread.sleep(2000);
isStarted = false;
} catch (InterruptedException e) {}
}
public boolean isStarted() {
return isStarted;
}
public int send(Request request) {
if (!isStarted) {
throw new IllegalStateException(""server is not running"");
}
this.request = request;
return 200;
}
public String retrieve() {
if (!isStarted) {
throw new IllegalStateException(""server is not running"");
}
return request.getData();
}
public void clean() {
request = new Request(null);
}
static class Request {
private T data;
Request(T data) {
this.data = data;
}
T getData() {
return data;
}
}
}
"
Make sure that current-tenant thread local storage is reset in the event of an exception,"package grails.plugin.multitenant.core.filter;
import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
*
* @author Kim A. Betti
*/
public class CurrentTenantFilter implements Filter {
private CurrentTenant currentTenant; // thread local storage
private TenantResolver tenantResolver; // provided by implementation
@Override
public void init(FilterConfig fc) throws ServletException {
ServletContext servletContext = fc.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
currentTenant = (CurrentTenant) ctx.getBean(""currentTenant"");
tenantResolver = (TenantResolver) ctx.getBean(""tenantResolver"");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
int currentTenantId = tenantResolver.resolve(httpRequest);
currentTenant.set(currentTenantId);
}
filterChain.doFilter(request, response);
} finally {
currentTenant.set(-1);
}
}
@Override
public void destroy() {
}
}","package grails.plugin.multitenant.core.filter;
import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class CurrentTenantFilter implements Filter {
private CurrentTenant currentTenant;
private TenantResolver tenantResolver;
@Override
public void init(FilterConfig fc) throws ServletException {
ServletContext servletContext = fc.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
currentTenant = (CurrentTenant) ctx.getBean(""currentTenant"");
tenantResolver = (TenantResolver) ctx.getBean(""tenantResolver"");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
int currentTenantId = tenantResolver.resolve(httpRequest);
currentTenant.set(currentTenantId);
}
filterChain.doFilter(request, response);
currentTenant.set(-1);
}
@Override
public void destroy() {
}
}
"
Add a line by line parser,"class Asset:
""""""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
""""""
def __init__(self, file=None, *args, **argv):
self.fh = None
if file:
self.name = file
self.fh = open(file, 'r')
self.eof = False
def __iter__(self):
return self
def len(self):
""""""
Returns the length of the asset
""""""
for i, l in enumerate(self.fh):
pass
# rewind the file
self.fh.seek(0)
return i + 1
def parse_line(self, line):
""""""
Override this method if you need line
by line parsing of an Asset.
""""""
return line.replace('\n','')
def next_asset(self):
""""""
Return the next asset.
""""""
# XXX this is really written with my feet.
# clean me up please...
line = self.fh.readline()
if line:
return self.parse_line(line)
else:
self.fh.seek(0)
raise StopIteration
def next(self):
try:
return self.next_asset()
except:
raise StopIteration
","class Asset:
""""""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
""""""
def __init__(self, file=None, *args, **argv):
self.fh = None
if file:
self.name = file
self.fh = open(file, 'r')
self.eof = False
def __iter__(self):
return self
def len(self):
""""""
Returns the length of the asset
""""""
for i, l in enumerate(self.fh):
pass
# rewind the file
self.fh.seek(0)
return i + 1
def next_asset(self):
""""""
Return the next asset.
""""""
# XXX this is really written with my feet.
# clean me up please...
line = self.fh.readline()
if line:
return line.replace('\n','')
else:
self.fh.seek(0)
raise StopIteration
def next(self):
try:
return self.next_asset()
except:
raise StopIteration
"
Check if it is not an image,"$( document ).ready( function() {
function showUploadedImage( source ) {
$( ""#userImage"" ).attr( ""src"", source );
}
$( ""#image-form"" ).submit( function() {
var image = document.getElementById( ""image"" ).files[ 0 ];
if ( !image ) {
$( '#image-form' ).prepend( ""This isn't an image
"" )
return false;
}
var token = $( ""input[type=hidden]"" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( ""#imageSubmit"" ).hide();
$( ""#uploading"" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( ""image"", image );
formdata.append( ""token"", token );
$.ajax( {
url: ""image/create"",
type: ""POST"",
data: formdata,
cache: false,
dataType: false,
processData: false,
contentType: false,
success: function( res ) {
$( ""#imageSubmit"" ).show();
$( ""#uploading"" ).hide();
},
error: function( res ) {
$( ""#imageSubmit"" ).show();
$( ""#uploading"" ).hide();
}
} );
return false;
} );
} );
","$( document ).ready( function() {
function showUploadedImage( source ) {
$( ""#userImage"" ).attr( ""src"", source );
}
$( ""#image-form"" ).submit( function() {
var image = document.getElementById( ""image"" ).files[ 0 ];
var token = $( ""input[type=hidden]"" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( ""#imageSubmit"" ).hide();
$( ""#uploading"" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( ""image"", image );
formdata.append( ""token"", token );
$.ajax( {
url: ""image/create"",
type: ""POST"",
data: formdata,
cache: false,
dataType: false,
processData: false,
contentType: false,
success: function( res ) {
$( ""#imageSubmit"" ).show();
$( ""#uploading"" ).hide();
},
error: function( res ) {
$( ""#imageSubmit"" ).show();
$( ""#uploading"" ).hide();
}
} );
return false;
} );
} );
"
Check 'id' exists before accessing the value,"properties = array(
'id' => property_exists($rawData, 'id') ? $rawData->{'id'} : null,
'alias' => $rawData->{'alias'},
'nsc' => @$rawData->{'nsc'},
'accountNumber' => @$rawData->{'accountNumber'},
'bic' => @$rawData->{'bic'},
'iban' => @$rawData->{'iban'}
);
}
public function get($key) {
return $this->properties[$key];
}
/**
* Provide a friendly representation
*
* @return string friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->properties as $key => $value) {
if ($value instanceof \DateTime) {
$context[] = ""$key="".$value->format('Y-m-d\TH:i:s');
} else {
$context[] = ""$key=$value"";
}
}
return '[ Fire.Business.Model.ExternalAccount: ' . implode(' ', $context) . ' ]';
}
}
","properties = array(
'id' => $rawData->{'id'},
'alias' => $rawData->{'alias'},
'nsc' => @$rawData->{'nsc'},
'accountNumber' => @$rawData->{'accountNumber'},
'bic' => @$rawData->{'bic'},
'iban' => @$rawData->{'iban'}
);
}
public function get($key) {
return $this->properties[$key];
}
/**
* Provide a friendly representation
*
* @return string friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->properties as $key => $value) {
if ($value instanceof \DateTime) {
$context[] = ""$key="".$value->format('Y-m-d\TH:i:s');
} else {
$context[] = ""$key=$value"";
}
}
return '[ Fire.Business.Model.ExternalAccount: ' . implode(' ', $context) . ' ]';
}
}
"
"Remove wind-related weathericons css rules
Doing so removes hundreds upon hundreds of unused rules, reducing
the size of the main css file by more than half (~12kb to ~4kb).","import React, { Component } from 'react';
import moment from 'moment';
import { kelvinToFahrenheit } from '../util';
import 'weather-icons-tmp/css/weather-icons.css';
import '../stylesheets/components/ForecastItem.scss';
class ForecastItem extends Component {
render() {
let temperature = kelvinToFahrenheit(this.props.forecast.main.temp);
let forecastDate = moment(this.props.forecast.dt_txt);
let weatherSymbolId = 'wi wi-owm-' + this.props.forecast.weather[0].id;
return (
{forecastDate.format('MMM Do')}
{temperature}
{this.props.forecast.weather[0].description}
);
}
}
ForecastItem.propTypes = {
forecast: React.PropTypes.object
};
export default ForecastItem;
","import React, { Component } from 'react';
import moment from 'moment';
import { kelvinToFahrenheit } from '../util';
import 'weather-icons-tmp/css/weather-icons-wind.css';
import 'weather-icons-tmp/css/weather-icons.css';
import '../stylesheets/components/ForecastItem.scss';
class ForecastItem extends Component {
render() {
let temperature = kelvinToFahrenheit(this.props.forecast.main.temp);
let forecastDate = moment(this.props.forecast.dt_txt);
let weatherSymbolId = 'wi wi-owm-' + this.props.forecast.weather[0].id;
return (
{forecastDate.format('MMM Do')}
{temperature}
{this.props.forecast.weather[0].description}
);
}
}
ForecastItem.propTypes = {
forecast: React.PropTypes.object
};
export default ForecastItem;
"
Fix the deserializer when no relationships is present.,"'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships &&
params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
","'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
"
Fix typo: `succesfully` -> `successfully`,"# -*- coding: utf-8 -*-
'''
Created on Tue Aug 15 11:26:23 2017
This script processes NCBI data exports (from ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/IDS/)
to extract lists of organism accession IDs, later used for downloading complete genome sequences.
@author: mbonsma / thisisjaid
'''
import os
import pandas as pd
import argparse
parser = argparse.ArgumentParser(add_help=True, description='''phageParser - collect_accessions.py -
This script processes NCBI data exports
(from ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/IDS/)
to generate lists of organism accession IDs, later used for downloading
complete genome sequences''')
parser.add_argument('-o', metavar='output_file', action='store', type=str, default='accessions.csv',
help='Full path to results output file (default: accessions.csv)')
parser.add_argument('file', action='store', help='Full path to NCBI data export file')
args = parser.parse_args()
records = pd.read_csv(args.file,sep='\t', header=None)
records.to_csv(args.o,header=False,sep=',',columns=[1],index=False)
print('Accession file successfully written out at:',args.o)
","# -*- coding: utf-8 -*-
'''
Created on Tue Aug 15 11:26:23 2017
This script processes NCBI data exports (from ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/IDS/)
to extract lists of organism accession IDs, later used for downloading complete genome sequences.
@author: mbonsma / thisisjaid
'''
import os
import pandas as pd
import argparse
parser = argparse.ArgumentParser(add_help=True, description='''phageParser - collect_accessions.py -
This script processes NCBI data exports
(from ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/IDS/)
to generate lists of organism accession IDs, later used for downloading
complete genome sequences''')
parser.add_argument('-o', metavar='output_file', action='store', type=str, default='accessions.csv',
help='Full path to results output file (default: accessions.csv)')
parser.add_argument('file', action='store', help='Full path to NCBI data export file')
args = parser.parse_args()
records = pd.read_csv(args.file,sep='\t', header=None)
records.to_csv(args.o,header=False,sep=',',columns=[1],index=False)
print('Accession file succesfully written out at:',args.o)
"
Update phpdoc for last commit,"getConnection();
// Check the connection type
if ($connection instanceof \duxet\Rethinkdb\Connection)
{
return new QueryBuilder($connection);
}
return parent::newBaseQueryBuilder();
}
/**
* Create a new Eloquent query builder for the model.
*
* @param \duxet\Rethinkdb\Query\Builder $query
* @return \duxet\Rethinkdb\Eloquent\Builder|static
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}
}","getConnection();
// Check the connection type
if ($connection instanceof \duxet\Rethinkdb\Connection)
{
return new QueryBuilder($connection);
}
return parent::newBaseQueryBuilder();
}
/**
* Create a new Eloquent query builder for the model.
*
* @param \duxet\Rethinkdb\Query\Builder $query
* @return \duxet\Rethinkdb\Eloquent\Builder|static
*/
public function newEloquentBuilder($query)
{
return new Builder($query);
}
}"
Fix some double quote issues.,"import $ from ""jquery"";
require(""../vendor/jqconsole"");
function ConsoleController($rootScope) {
var ctrl = this;
// Handle non-login websocket responses, meaning, EvalResponse
$rootScope.$on(
""EvalResponse"",
function (event, response) {
ctrl.jqconsole[""Write""](
response.replace(""\r"", """"), ""jqconsole-output"");
});
}
ConsoleController.$inject = [""$rootScope""];
function ConsoleLink(scope, element, attr, ctrl) {
ctrl.jqconsole = $(element).find(""#console"").jqconsole(""Hi\n"", ""\n>>>"");
var startPrompt = function () {
// Start the prompt with history enabled.
ctrl.jqconsole[""Prompt""](true, function (input) {
// Output input with the class jqconsole-output.
ctrl.jqconsole[""Write""](input + ""\n"", ""jqconsole-output"");
// Restart the prompt.
startPrompt();
});
};
startPrompt();
}
ConsoleLink.$inject = [""scope"", ""element"", ""attr"", ""ctrl""];
export default function Console() {
return {
restrict: ""E"",
scope: {},
bindToController: {},
template: ``,
controller: ConsoleController,
controllerAs: ""ctrl"",
link: ConsoleLink
};
}
","import $ from ""jquery"";
require(""../vendor/jqconsole"");
function ConsoleController($rootScope) {
var ctrl = this;
// Handle non-login websocket responses, meaning, EvalResponse
$rootScope.$on(
""EvalResponse"",
function (event, response) {
ctrl.jqconsole['Write'](
response.replace(""\r"", """"), ""jqconsole-output"");
});
}
ConsoleController.$inject = [""$rootScope""];
function ConsoleLink(scope, element, attr, ctrl) {
ctrl.jqconsole = $(element).find(""#console"").jqconsole(""Hi\n"", ""\n>>>"");
var startPrompt = function () {
// Start the prompt with history enabled.
ctrl.jqconsole[""Prompt""](true, function (input) {
// Output input with the class jqconsole-output.
ctrl.jqconsole[""Write""](input + ""\n"", ""jqconsole-output"");
// Restart the prompt.
startPrompt();
});
};
startPrompt();
}
ConsoleLink.$inject = [""scope"", ""element"", ""attr"", ""ctrl""];
export default function Console() {
return {
restrict: ""E"",
scope: {},
bindToController: {},
template: '',
controller: ConsoleController,
controllerAs: ""ctrl"",
link: ConsoleLink
};
}
"
Handle ctrl-c and ctrl-d properly,"#!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s$ ' % os.getcwd()
def read_command():
line = input(prompt())
return line
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
return True
def run_builtin(cmd, cmd_text):
if shutil.which(cmd[0]):
os.system(cmd_text)
if cmd[0] == 'cd':
os.chdir(cmd[1])
elif cmd[0] == 'pwd':
print(os.getcwd())
elif cmd[0] == 'exit':
sys.exit()
if __name__ == ""__main__"":
while True:
try:
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd)
if cmd[0] in builtin_cmds:
run_builtin(cmd, cmd_text)
else:
#pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True)
os.system(cmd_text)
except KeyboardInterrupt:
print('')
pass
except SystemExit:
break
except EOFError:
print('')
break
except:
traceback.print_exc()
","#!/usr/bin/env python3
import os
import shutil
import sys
import readline
import traceback
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
builtin_cmds = {'cd', 'pwd', 'exit',}
def prompt():
return '%s$ ' % os.getcwd()
def read_command():
line = input(prompt())
return line
def parse_command(cmd_text):
return (cmd_text, cmd_text.strip().split())
def record_command(command):
return True
def run_builtin(cmd, cmd_text):
if shutil.which(cmd[0]):
os.system(cmd_text)
if cmd[0] == 'cd':
os.chdir(cmd[1])
elif cmd[0] == 'pwd':
print(os.getcwd())
elif cmd[0] == 'exit':
sys.exit()
if __name__ == ""__main__"":
while True:
try:
cmd_text = read_command()
cmd_text, cmd = parse_command(cmd_text)
record_command(cmd)
if cmd[0] in builtin_cmds:
run_builtin(cmd, cmd_text)
else:
#pid = subprocess.Popen(cmd_text, stdin=None, stdout=None, shell=True)
os.system(cmd_text)
except SystemExit:
break
except:
traceback.print_exc()
"
Make sequence wrap + clear li," View Protein
-
Name
-
Acronym
-
Sequence
-
Moecular Mass
Id |
Name |
Protein |
Spacegroup |
Comment |
Shipment |
Dewar |
Container |
Snapshot |
Data Collections |
|
"," View Protein
-
Name
-
Acronym
-
Sequence
-
Moecular Mass
Id |
Name |
Protein |
Spacegroup |
Comment |
Shipment |
Dewar |
Container |
Snapshot |
Data Collections |
|
"
"Disable this test on PHP 7.4, too","
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject;
use PHPUnit\Framework\TestCase;
use PHPUnit\TestFixture\MockObject\ClassWithoutParentButParentReturnType;
use SebastianBergmann\Type\UnknownType;
/**
* @small
*/
final class MockMethodTest extends TestCase
{
public function testGetNameReturnsMethodName(): void
{
$method = new MockMethod(
'ClassName',
'methodName',
false,
'',
'',
'',
new UnknownType,
'',
false,
false,
null,
false
);
$this->assertEquals('methodName', $method->getName());
}
/**
* @requires PHP < 7.4
*/
public function testFailWhenReturnTypeIsParentButThereIsNoParentClass(): void
{
$class = new \ReflectionClass(ClassWithoutParentButParentReturnType::class);
$this->expectException(\RuntimeException::class);
MockMethod::fromReflection($class->getMethod('foo'), false, false);
}
}
","
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject;
use PHPUnit\Framework\TestCase;
use PHPUnit\TestFixture\MockObject\ClassWithoutParentButParentReturnType;
use SebastianBergmann\Type\UnknownType;
/**
* @small
*/
final class MockMethodTest extends TestCase
{
public function testGetNameReturnsMethodName(): void
{
$method = new MockMethod(
'ClassName',
'methodName',
false,
'',
'',
'',
new UnknownType,
'',
false,
false,
null,
false
);
$this->assertEquals('methodName', $method->getName());
}
/**
* @requires PHP < 8
*/
public function testFailWhenReturnTypeIsParentButThereIsNoParentClass(): void
{
$class = new \ReflectionClass(ClassWithoutParentButParentReturnType::class);
$this->expectException(\RuntimeException::class);
MockMethod::fromReflection($class->getMethod('foo'), false, false);
}
}
"
Allow expiration of gift card to be set,"escape($expires) . ' 23:59:59""';
} else {
$expires= ""NULL"";
}
$q= ""INSERT INTO giftcard
SET pin = SUBSTR(RAND(), 5, 4),
expires = $expires,
active = 1"";
$r= $db->query($q);
if (!$r) die(jsonp(array(""error"" => ""Unable to create card."",
""detail"" => $db->error)));
$q= ""SELECT CONCAT(id, pin) card, id, pin FROM giftcard
WHERE id = LAST_INSERT_ID()"";
$r= $db->query($q);
if (!$r) die(jsonp(array(""error"" => ""Unable to create card."",
""detail"" => $db->error)));
$card= $r->fetch_assoc();
if ($balance) {
$q= ""INSERT INTO giftcard_txn
SET card_id = $card[id],
amount = $balance,
entered = NOW()"";
$r= $db->query($q);
if (!$r) die(jsonp(array(""error"" => ""Unable to add balance to card."",
""detail"" => $db->error)));
}
echo jsonp(array(""card"" => $card['card'],
""balance"" => sprintf(""%.2f"", $balance),
""success"" =>sprintf(""Card activated with \$%.2f balance."",
$balance)));
","query($q);
if (!$r) die(jsonp(array(""error"" => ""Unable to create card."",
""detail"" => $db->error)));
$q= ""SELECT CONCAT(id, pin) card, id, pin FROM giftcard
WHERE id = LAST_INSERT_ID()"";
$r= $db->query($q);
if (!$r) die(jsonp(array(""error"" => ""Unable to create card."",
""detail"" => $db->error)));
$card= $r->fetch_assoc();
if ($balance) {
$q= ""INSERT INTO giftcard_txn
SET card_id = $card[id],
amount = $balance,
entered = NOW()"";
$r= $db->query($q);
if (!$r) die(jsonp(array(""error"" => ""Unable to add balance to card."",
""detail"" => $db->error)));
}
echo jsonp(array(""card"" => $card['card'],
""balance"" => sprintf(""%.2f"", $balance),
""success"" =>sprintf(""Card activated with \$%.2f balance."",
$balance)));
"
FIX : in handling of sample dataset,"# Author: Alexandre Gramfort
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
""""""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
""""""
archive_name = ""MNE-sample-data-processed.tar.gz""
url = ""ftp://surfer.nmr.mgh.harvard.edu/pub/data/"" + archive_name
folder_name = ""MNE-sample-data""
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print ""Downloading data, please Wait (600 MB)...""
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print ""Decompressiong the archive: "" + archive_name
tarfile.open(archive_name, ""r:gz"").extractall(path=path)
print
path = op.join(path, folder_name)
return path
","# Author: Alexandre Gramfort
# License: BSD Style.
import os
import os.path as op
def data_path(path='.'):
""""""Get path to local copy of Sample dataset
Parameters
----------
dir : string
Location of where to look for the sample dataset.
If not set. The data will be automatically downloaded in
the local folder.
""""""
archive_name = ""MNE-sample-data-processed.tar.gz""
url = ""ftp://surfer.nmr.mgh.harvard.edu/pub/data/"" + archive_name
folder_name = ""MNE-sample-data-processed""
martinos_path = '/homes/6/gramfort/cluster/work/data/MNE-sample-data-processed.tar.gz'
if not os.path.exists(op.join(path, folder_name)):
if os.path.exists(martinos_path):
archive_name = martinos_path
elif not os.path.exists(archive_name):
import urllib
print ""Downloading data, please Wait (600 MB)...""
print url
opener = urllib.urlopen(url)
open(archive_name, 'wb').write(opener.read())
print
import tarfile
print ""Decompressiong the archive: "" + archive_name
tarfile.open(archive_name, ""r:gz"").extractall(path=path)
print
path = op.join(path, folder_name)
return path
"
"Fix i18nPlugin issue introduced with g/277926
Test Plan
1. Pull down code
2. `yarn storybook` should open storybook
3. Should not throw an error for storybook regarding i18nPlugin
Change-Id: I2fc15dfae332819d8e45993314f4d0529427520c
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278846
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
Reviewed-by: Charley Kline <05950d7e90ba5e3da323378368c22b3ffaaf6647@instructure.com>
Product-Review: Charley Kline <05950d7e90ba5e3da323378368c22b3ffaaf6647@instructure.com>
QA-Review: Chawn Neal <908eabd8c84ff6c7c139535b8d37802d58ad1683@instructure.com>","const I18nPlugin = require('../ui-build/webpack/i18nPlugin')
const path = require('path')
const baseWebpackConfig = require('../ui-build/webpack')
const root = path.resolve(__dirname, '..')
module.exports = {
stories: [
'../ui/**/*.stories.mdx',
'../ui/**/*.stories.@(js|jsx|ts|tsx)'
],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials'
],
webpackFinal: async (config) => {
config.module.noParse = [/i18nliner\/dist\/lib\/i18nliner/]
config.plugins.push(I18nPlugin)
config.resolveLoader.modules = [
path.resolve(__dirname, '../ui-build/webpack'),
'node_modules'
]
config.resolve.modules = [
path.resolve(__dirname, '../ui/shims'),
path.resolve(__dirname, '../public/javascripts'), // for translations
'node_modules'
]
config.resolve.alias = {...baseWebpackConfig.resolve.alias, ...config.resolve.alias}
config.module.rules = [
...config.module.rules,
{
test: /\.coffee$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['coffee-loader']
},
{
test: /\.handlebars$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['i18nLinerHandlebars']
}
]
return config
}
}
","const I18nPlugin = require('../ui-build/webpack/i18nPlugin')
const path = require('path')
const baseWebpackConfig = require('../ui-build/webpack')
const root = path.resolve(__dirname, '..')
module.exports = {
stories: [
'../ui/**/*.stories.mdx',
'../ui/**/*.stories.@(js|jsx|ts|tsx)'
],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials'
],
webpackFinal: async (config) => {
config.module.noParse = [/i18nliner\/dist\/lib\/i18nliner/]
config.plugins.push(new I18nPlugin())
config.resolveLoader.modules = [
path.resolve(__dirname, '../ui-build/webpack'),
'node_modules'
]
config.resolve.modules = [
path.resolve(__dirname, '../ui/shims'),
path.resolve(__dirname, '../public/javascripts'), // for translations
'node_modules'
]
config.resolve.alias = {...baseWebpackConfig.resolve.alias, ...config.resolve.alias}
config.module.rules = [
...config.module.rules,
{
test: /\.coffee$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['coffee-loader']
},
{
test: /\.handlebars$/,
include: [path.resolve(__dirname, '../ui')],
loaders: ['i18nLinerHandlebars']
}
]
return config
}
}
"
"Add test to test if os_family grain is provided.
Corey Quinn reported a issue where __grains__['os_family'] returned a
KeyError. This commits adds a check to the grains module test to ensure
os_family is present.","'''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
'os_family',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
","'''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
"
Add comments back to file,"/* globals module */
var EOL = require('os').EOL;
module.exports = {
description: 'Register test helpers',
afterInstall: function( options ) {
// Import statement
var firstFile = 'tests/helpers/start-app.js';
var firstText = ""import slRegisterTestHelpers from './sl/register-test-helpers';"";
var firstLocationText = ""import Ember from 'ember';"" + EOL;
// Execution of registration function
var secondFile = 'tests/helpers/start-app.js';
var secondText = "" slRegisterTestHelpers();"";
var secondLocationText = ""application.setupForTesting();"" + EOL;
// .jshintrc file
var thirdFile = 'tests/.jshintrc';
var thirdText = ' ""contains"",' + EOL + ' ""requires"",';
var thirdLocationText = '""predef"": [' + EOL;
// Import statement
return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } )
// Execution of registration function
.then( function() {
return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } );
}.bind( this ))
// .jshintrc file
.then( function() {
return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } );
}.bind( this ))
.then( function() {
return this.addAddonToProject( 'ember-sinon' );
}.bind( this ));
},
normalizeEntityName: function() {}
};
","/* globals module */
var EOL = require('os').EOL;
module.exports = {
description: 'Register test helpers',
afterInstall: function( options ) {
// Import statement
var firstFile = 'tests/helpers/start-app.js';
var firstText = ""import slRegisterTestHelpers from './sl/register-test-helpers';"";
var firstLocationText = ""import Ember from 'ember';"" + EOL;
// Execution of registration function
var secondFile = 'tests/helpers/start-app.js';
var secondText = "" slRegisterTestHelpers();"";
var secondLocationText = ""application.setupForTesting();"" + EOL;
// .jshintrc file
var thirdFile = 'tests/.jshintrc';
var thirdText = ' ""contains"",' + EOL + ' ""requires"",';
var thirdLocationText = '""predef"": [' + EOL;
return this.insertIntoFile( firstFile, firstText, { after: firstLocationText } )
// Execution of registration function
.then( function() {
return this.insertIntoFile( secondFile, secondText, { after: secondLocationText } );
}.bind( this ))
.then( function() {
return this.insertIntoFile( thirdFile, thirdText, { after: thirdLocationText } );
}.bind( this ))
.then( function() {
return this.addAddonToProject( 'ember-sinon' );
}.bind( this ));
},
normalizeEntityName: function() {}
};
"
Prepend width and height to options array in url() method," $width], $options);
}
if ($height) {
$options = array_merge(['h' => $height], $options);
}
if (! empty($options)) {
return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
}
return $this->getStorage()->url($this->path().'/'.$this->name());
}
/**
* Prepare and convert options from array to string
*
* @param array $options
*/
protected function prepareOptions(array $options = [])
{
$string = implode(',', array_map(
function ($value, $key) {
return $key.'_'.$value;
},
$options,
array_keys($options)
));
$from = ['width', 'height'];
$to = ['w', 'h'];
return str_replace($from, $to, $string);
}
}
","getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
}
return $this->getStorage()->url($this->path().'/'.$this->name());
}
/**
* Prepare and convert options from array to string
*
* @param array $options
*/
protected function prepareOptions(array $options = [])
{
$string = implode(',', array_map(
function ($value, $key) {
return $key.'_'.$value;
},
$options,
array_keys($options)
));
$from = ['width', 'height'];
$to = ['w', 'h'];
return str_replace($from, $to, $string);
}
}
"
Support for Attribute in prov-n and round trip testing (usage and generation),"package org.openprovenance.prov.xml;
import java.util.List;
import java.util.LinkedList;
import javax.xml.namespace.QName;
import java.util.Hashtable;
import javax.xml.bind.JAXBElement;
public class AttributeProcessor {
final private Hashtable>> namespaceIndex=
new Hashtable>>();
final private List attributes;
public AttributeProcessor(List attributes) {
this.attributes=attributes;
}
/* Processing of attributes */
Hashtable> attributesWithNamespace(String namespace) {
Hashtable> result=namespaceIndex.get(namespace);
if (result==null) {
result=new Hashtable>();
namespaceIndex.put(namespace,result);
}
for (Attribute attribute: attributes) {
QName name=attribute.getElementName();
if (namespace.equals(name.getNamespaceURI())) {
List ll=result.get(name.getLocalPart());
if (ll==null) {
List tmp=new LinkedList();
tmp.add(attribute);
result.put(name.getLocalPart(),tmp);
} else {
ll.add(attribute);
}
}
}
return result;
}
}","package org.openprovenance.prov.xml;
import java.util.List;
import java.util.LinkedList;
import javax.xml.namespace.QName;
import java.util.Hashtable;
import javax.xml.bind.JAXBElement;
public class AttributeProcessor {
final private Hashtable>> namespaceIndex=
new Hashtable>>();
final private List