text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add fields to users table | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->date('dob');
$table->char('gender', 1);
$table->string('sexuality');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
Use @RegisterExtension
in junit5-extension-model project | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
public class ExceptionTest {
@RegisterExtension
static IgnoreIOExceptionExtension ignoreIOExceptionExtension = new IgnoreIOExceptionExtension();
@Test
public void firstTest() throws IOException {
throw new IOException("IO Exception");
}
@Test
public void secondTest() throws IOException {
throw new IOException("My IO Exception");
}
}
| /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.bonigarcia;
import java.io.IOException;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
public class ExceptionTest {
@ExtendWith(IgnoreIOExceptionExtension.class)
@Test
public void firstTest() throws IOException {
throw new IOException("IO Exception");
}
@Disabled
@Test
public void secondTest() throws IOException {
throw new IOException("My IO Exception");
}
}
|
Clean up article serializer a bit | from rest_framework import serializers
from apps.article.models import Article, Tag
from apps.authentication.serializers import UserSerializer
class ArticleSerializer(serializers.ModelSerializer):
author = UserSerializer(source='created_by')
absolute_url = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Article
fields = (
'absolute_url', 'additional_authors', 'author', 'changed_date', 'content', 'created_date',
'featured', 'heading', 'id',
'ingress', 'ingress_short', 'photographers', 'published_date', 'slug', 'video', 'images', 'article_tags',
)
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('name', 'short_name')
| from rest_framework import serializers
from apps.article.models import Article, Tag
from apps.authentication.serializers import UserSerializer
class ArticleSerializer(serializers.ModelSerializer):
author = UserSerializer(source='created_by') # serializers.StringRelatedField(source='created_by')
absolute_url = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Article
fields = (
'absolute_url', 'additional_authors', 'author', 'changed_date', 'content', 'created_date',
'featured', 'heading', 'id',
# 'image_article_front_featured', 'image_article_front_small', 'image_article_full', 'image_article_main', 'image_article_related',
'ingress', 'ingress_short', 'photographers', 'published_date', 'slug', 'video', 'images', 'article_tags',
)
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('name', 'short_name')
|
Update lambda handler function to dispatch to interaction model | """
Entry point for lambda
"""
from _ebcf_alexa import interaction_model, incoming_types, speechlet
import logging
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG)
ALEXA_SKILL_ID = 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'
def lambda_handler(event_dict: dict, context) -> dict:
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
LOG.debug(repr(event_dict))
event = incoming_types.LambdaEvent(event_dict)
LOG.info("Start Lambda Event for event.session.application.applicationId=%s",
event.session.application.application_id)
# This is the official application id
if event.session.application.application_id != ALEXA_SKILL_ID:
raise ValueError("Invalid Application ID: %s" % event.session.application.application_id)
return interaction_model.handle_event(event).dict()
| """
Entry point for lambda
"""
from _ebcf_alexa import interaction_model
import logging
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG)
def lambda_handler(event, context) -> dict:
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
LOG.info("Start Lambda Event for event.session.application.applicationId=%s",
event['session']['application']['applicationId'])
# This is the official application id
if (event['session']['application']['applicationId'] !=
'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'):
raise ValueError("Invalid Application ID")
request_type = event['request']['type']
try:
handler = interaction_model.REQUEST_HANDLERS[request_type]
except KeyError:
LOG.error('Unknown request type: %s', request_type)
raise ValueError('Unknown Request Type')
speechlet = handler(event['request'], event['session'])
return speechlet.dict()
|
Fix Industrial Foregoing Compat crash | package com.infinityraider.agricraft.plugins.industrialforegoing;
import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import java.util.List;
public class AgriPlantRecollectable extends PlantRecollectable {
protected AgriPlantRecollectable() {
super(AgriCraft.instance.getModId());
this.setRegistryName(AgriCraft.instance.getModId(), "plant_recollectable");
}
@Override
public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
}
@Override
public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
List<ItemStack> drops = Lists.newArrayList();
AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
return drops;
}
@Override
public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
return true;
}
}
| package com.infinityraider.agricraft.plugins.industrialforegoing;
import com.buuz135.industrial.api.plant.PlantRecollectable;
import com.google.common.collect.Lists;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.api.v1.AgriApi;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import java.util.List;
public class AgriPlantRecollectable extends PlantRecollectable {
protected AgriPlantRecollectable() {
super(AgriCraft.instance.getModId());
}
@Override
public boolean canBeHarvested(Level world, BlockPos blockPos, BlockState blockState) {
return AgriApi.getCrop(world, blockPos).map(crop -> crop.hasPlant() && crop.isMature()).orElse(false);
}
@Override
public List<ItemStack> doHarvestOperation(Level world, BlockPos blockPos, BlockState blockState) {
List<ItemStack> drops = Lists.newArrayList();
AgriApi.getCrop(world, blockPos).ifPresent(crop -> crop.harvest(drops::add, null));
return drops;
}
@Override
public boolean shouldCheckNextPlant(Level world, BlockPos blockPos, BlockState blockState) {
return true;
}
}
|
Work on model file handling | import os
import sys
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append(one_up_path)
import model_creator
import util_functions
def create(text,score,prompt_string,model_path):
model_path=util_functions.create_model_path(model_path)
results = {'errors': [],'created' : False}
try:
e_set = model_creator.create_essay_set(text, score, prompt_string)
except:
results['errors'].append("essay set creation failed.")
try:
feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set)
except:
results['errors'].append("feature extraction and model creation failed.")
full_path=os.path.join(base_path,model_path)
util_functions.create_directory(full_path)
model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, full_path)
results['created']=True
"""
except:
results['errors'].append("could not write model to: {0}".format(model_path))
"""
return results
def check(model_path):
model_path=util_functions.create_model_path(model_path)
try:
with open(model_path) as f: pass
except IOError as e:
return False
return True
| import os
import sys
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append(one_up_path)
import model_creator
import util_functions
def create(text,score,prompt_string,model_path):
model_path=util_functions.create_model_path(model_path)
results = {'errors': [],'created' : False}
try:
e_set = model_creator.create_essay_set(text, score, prompt_string)
except:
results['errors'].append("essay set creation failed.")
try:
feature_ext, classifier = model_creator.extract_features_and_generate_model(e_set)
except:
results['errors'].append("feature extraction and model creation failed.")
try:
util_functions.create_directory(model_path)
model_creator.dump_model_to_file(prompt_string, feature_ext, classifier, text, score, args.model_path)
results['created']=True
except:
results['errors'].append("could not write model to: {0}".format(model_path))
return results
def check(model_path):
model_path=util_functions.create_model_path(model_path)
try:
with open(model_path) as f: pass
except IOError as e:
return False
return True
|
Remove spaces around '=' for default param | class Garden:
DEFAULT_STUDENTS = ("Alice Bob Charlie David Eve Fred Ginny "
"Harriet Ileana Joseph Kincaid Larry").split()
PLANTS = {'G': 'Grass',
'C': 'Clover',
'R': 'Radishes',
'V': 'Violets'}
def __init__(self, diagram, students=DEFAULT_STUDENTS):
self.diagram = diagram
self.rows = [list(row) for row in diagram.split()]
self.plant_rows = [[self.PLANTS[c] for c in row] for row in self.rows]
self.students = sorted(students)
def plants(self, name):
return self.plants_for_index(self.students.index(name))
# Dislike how these are hardcoded indices
def plants_for_index(self, i):
return [self.plant_rows[0][i * 2],
self.plant_rows[0][i * 2 + 1],
self.plant_rows[1][i * 2],
self.plant_rows[1][i * 2 + 1]]
| class Garden:
DEFAULT_STUDENTS = ("Alice Bob Charlie David Eve Fred Ginny "
"Harriet Ileana Joseph Kincaid Larry").split()
PLANTS = {'G': 'Grass',
'C': 'Clover',
'R': 'Radishes',
'V': 'Violets'}
def __init__(self, diagram, students = DEFAULT_STUDENTS):
self.diagram = diagram
self.rows = [list(row) for row in diagram.split()]
self.plant_rows = [[self.PLANTS[c] for c in row] for row in self.rows]
self.students = sorted(students)
def plants(self, name):
return self.plants_for_index(self.students.index(name))
# Dislike how these are hardcoded indices
def plants_for_index(self, i):
return [self.plant_rows[0][i * 2],
self.plant_rows[0][i * 2 + 1],
self.plant_rows[1][i * 2],
self.plant_rows[1][i * 2 + 1]]
|
Set showArraySize to false by default | module.exports = {
theme: "default",
addons: {
prependHeader: true,
maxJsonSize: 400,
alwaysFold: false,
alwaysRenderAllContent: false,
sortKeys: false,
clickableUrls: true,
openLinksInNewWindow: true,
autoHighlight: true
},
structure: {
readOnly: true,
lineNumbers: true,
lineWrapping: true,
foldGutter: true,
tabSize: 2,
indentCStyle: false,
showArraySize: false
},
style: [
".CodeMirror {",
" font-family: monaco, Consolas, Menlo, Courier, monospace;",
" font-size: 16px;",
" line-height: 1.5em;",
"}"
].join('\n')
}
| module.exports = {
theme: "default",
addons: {
prependHeader: true,
maxJsonSize: 400,
alwaysFold: false,
alwaysRenderAllContent: false,
sortKeys: false,
clickableUrls: true,
openLinksInNewWindow: true,
autoHighlight: true
},
structure: {
readOnly: true,
lineNumbers: true,
lineWrapping: true,
foldGutter: true,
tabSize: 2,
indentCStyle: false,
showArraySize:true
},
style: [
".CodeMirror {",
" font-family: monaco, Consolas, Menlo, Courier, monospace;",
" font-size: 16px;",
" line-height: 1.5em;",
"}"
].join('\n')
}
|
Fix errors when user click execution id
Missing request argument when calling task list
Change-Id: Idc282c267fc99513dd96a80f6f4a745bfefec2c8
Closes-Bug: #1471778 | # -*- coding: utf-8 -*-
#
# Copyright 2014 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from horizon import tables
from mistraldashboard import api
from mistraldashboard.executions.tables import ExecutionsTable
from mistraldashboard.executions.tables import TaskTable
class IndexView(tables.DataTableView):
table_class = ExecutionsTable
template_name = 'mistral/executions/index.html'
def get_data(self):
return api.execution_list(self.request)
class TaskView(tables.DataTableView):
table_class = TaskTable
template_name = 'mistral/executions/index.html'
def get_data(self):
return api.task_list(self.request, self.kwargs['execution_id'])
| # -*- coding: utf-8 -*-
#
# Copyright 2014 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from horizon import tables
from mistraldashboard import api
from mistraldashboard.executions.tables import ExecutionsTable
from mistraldashboard.executions.tables import TaskTable
class IndexView(tables.DataTableView):
table_class = ExecutionsTable
template_name = 'mistral/executions/index.html'
def get_data(self):
return api.execution_list(self.request)
class TaskView(tables.DataTableView):
table_class = TaskTable
template_name = 'mistral/executions/index.html'
def get_data(self):
return api.task_list(self.kwargs['execution_id'])
|
Remove stray comment, update docstring and minor PEP8 changes | """
prep_kml class used to manipulate police.uk KML data, used with prepgml4ogr.py
"""
import os
from lxml import etree
class prep_kml():
def __init__(self, inputfile):
self.inputfile = inputfile
self.infile = os.path.basename(inputfile)
self.feat_types = ['Placemark']
def get_feat_types(self):
return self.feat_types
def prepare_feature(self, feat_str):
# Parse the xml string into something useful
feat_elm = etree.fromstring(feat_str)
feat_elm = self._prepare_feat_elm(feat_elm)
return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8');
def _prepare_feat_elm(self, feat_elm):
feat_elm = self._add_filename_elm(feat_elm)
return feat_elm
def _add_filename_elm(self, feat_elm):
elm = etree.SubElement(feat_elm, "name")
elm.text = self.infile[:-4]
elm = etree.SubElement(feat_elm, "description")
elm.text = os.path.dirname(self.inputfile).split('/')[-1]
return feat_elm
| """
A collection of classes used to manipulate Police KML data, used with prepgml4ogr.py.
"""
import os
from lxml import etree
class prep_kml():
def __init__ (self, inputfile):
self.inputfile = inputfile
self.infile = os.path.basename(inputfile)
self.feat_types = ['Placemark']
def get_feat_types(self):
return self.feat_types
def prepare_feature(self, feat_str):
# Parse the xml string into something useful
feat_elm = etree.fromstring(feat_str)
feat_elm = self._prepare_feat_elm(feat_elm)
return etree.tostring(feat_elm, encoding='UTF-8', pretty_print=True).decode('utf_8');
def _prepare_feat_elm(self, feat_elm):
feat_elm = self._add_filename_elm(feat_elm)
return feat_elm
def _add_filename_elm(self, feat_elm):
# Create an element with the fid
elm = etree.SubElement(feat_elm, "name")
elm.text = self.infile[:-4]
elm = etree.SubElement(feat_elm, "description")
elm.text = os.path.dirname(self.inputfile).split('/')[-1]
return feat_elm
|
Handle the case where statements end in comma instead of semi-colon | /*
* qmlizer.js - fix the output of uglify so that it works properly in
* Qt/qml.
*
* Copyright © 2018, LGE, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require('fs');
function qmlize(text) {
// replace reserved keyword as with "as"
text = text.replace(/([\,\{]\s*)(as)(\s*:)/gm, '$1"$2"$3')
text = text.replace(/(new\s+[^\(\)\{\}\s;,]+)(\s*[;,])/gm, '$1()$2')
text = text.replace(/(new\s+[^\(\)\{\}\s;,]+)(\s*\})/gm, '$1();$2')
text = text.replace(/(\{\s*break)(\s*\})/gm, '$1;$2')
return text;
}
(function () {
console.log(process.argv);
if (process.argv.length == 4) {
var data = fs.readFileSync(process.argv[2], {encoding: 'utf8'});
fs.writeFileSync(process.argv[3], qmlize(data), {encoding: 'utf8'});
}
})();
| var fs = require('fs');
function qmlize(text) {
// replace reserved keyword as with "as"
text = text.replace(/([\,\{]\s*)(as)(\s*:)/gm, '$1"$2"$3')
text = text.replace(/(new\s+[^\(\)\{\}\s;]+)(\s*;)/gm, '$1()$2')
text = text.replace(/(new\s+[^\(\)\{\}\s;]+)(\s*\})/gm, '$1();$2')
text = text.replace(/(\{\s*break)(\s*\})/gm, '$1;$2')
return text;
}
(function () {
console.log(process.argv);
if (process.argv.length == 4) {
var data = fs.readFileSync(process.argv[2], {encoding: 'utf8'});
fs.writeFileSync(process.argv[3], qmlize(data), {encoding: 'utf8'});
}
})();
|
Add admi to add Applications to the Pages.
https://github.com/madewithbytes/us_ignite/issues/79
The applications can be added to a page and ordered
in the admin. | from django.contrib import admin
from us_ignite.apps.models import (Application, ApplicationURL,
ApplicationImage, Domain, Feature,
Page, PageApplication)
class ApplicationURLInline(admin.TabularInline):
model = ApplicationURL
class ApplicationImageInline(admin.TabularInline):
model = ApplicationImage
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'stage', 'status')
search_fields = ['name', 'slug', 'short_description', 'description']
list_filter = ['stage', 'status', 'created']
date_hierarchy = 'created'
inlines = [ApplicationURLInline, ApplicationImageInline]
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
class FeatureAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
class PageApplicationInline(admin.TabularInline):
raw_id_fields = ('application', )
model = PageApplication
class PageAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'status', 'created', )
list_filter = ('status', 'created', )
date_hierarchy = 'created'
inlines = [PageApplicationInline]
admin.site.register(Application, ApplicationAdmin)
admin.site.register(Domain, DomainAdmin)
admin.site.register(Feature, FeatureAdmin)
admin.site.register(Page, PageAdmin)
| from django.contrib import admin
from us_ignite.apps.models import (Application, ApplicationURL,
ApplicationImage, Domain, Feature)
class ApplicationURLInline(admin.TabularInline):
model = ApplicationURL
class ApplicationImageInline(admin.TabularInline):
model = ApplicationImage
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'stage', 'status')
search_fields = ['name', 'slug', 'short_description', 'description']
list_filter = ['stage', 'status', 'created']
date_hierarchy = 'created'
inlines = [ApplicationURLInline, ApplicationImageInline]
class DomainAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
class FeatureAdmin(admin. ModelAdmin):
list_display = ('name', 'slug')
admin.site.register(Application, ApplicationAdmin)
admin.site.register(Domain, DomainAdmin)
admin.site.register(Feature, FeatureAdmin)
|
Add toJSON method to display id instead of _id | var mongoose = require('mongoose'),
shortid = require('shortid');
var UserSchema = new mongoose.Schema({
_id: {type: String, required: true, unique: true, 'default': shortid.generate},
username: {type: String, unique: true, sparse: true, trim: true, lowercase: true},
name: {type: String, required: true},
email: {type: String},
password: {type: String},
is_active: {type: Boolean, 'default': true},
is_admin: {type: Boolean, 'default': false},
created: {type: Date, required: true, 'default': Date.now},
google_id: {type: String}
});
UserSchema.set('toObject', {
transform: function (document, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
});
UserSchema.set('toJSON', {
transform: function (document, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
});
var User = mongoose.model('User', UserSchema);
module.exports = {
User: User
};
| var mongoose = require('mongoose'),
shortid = require('shortid');
var UserSchema = new mongoose.Schema({
_id: {type: String, required: true, unique: true, 'default': shortid.generate},
username: {type: String, unique: true, sparse: true, trim: true, lowercase: true},
name: {type: String, required: true},
email: {type: String},
password: {type: String},
is_active: {type: Boolean, 'default': true},
is_admin: {type: Boolean, 'default': false},
created: {type: Date, required: true, 'default': Date.now},
google_id: {type: String}
});
UserSchema.set('toObject', {
transform: function (document, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
});
var User = mongoose.model('User', UserSchema);
module.exports = {
User: User
};
|
Feature: Handle two arguments while converting to JSON | '''
Sequential Price-Trend Models: MACD with Price-Bar-Chunk (MDC)
'''
import numpy
import json
from techmodels.overlays.trend.price.chunk import sign_chunker
from techmodels.indicators.trend.price.macd import MACDIndicator
def macd_chunk(data, nfast=10, nslow=35, nema=5, getter=lambda x: x):
prices = numpy.array(map(getter, data))
macd_oscillator = MACDIndicator(prices, nfast, nslow, nema)
# Skip the first nfast values
cropped_indicator = macd_oscillator.indicator()[nfast + 1:]
cropped_data = data[nfast + 1:]
chunks = sign_chunker(cropped_indicator, cropped_data)
return chunks
def macd_chunk_json(data, pricetype=u'close'):
python_list = json.loads(data)
chunks = macd_chunk(python_list, getter=lambda x: x[pricetype])
return json.dumps(chunks)
| '''
Sequential Price-Trend Models: MACD with Price-Bar-Chunk (MDC)
'''
import numpy
import json
from techmodels.overlays.trend.price.chunk import sign_chunker
from techmodels.indicators.trend.price.macd import MACDIndicator
def macd_chunk(data, nfast=10, nslow=35, nema=5, getter=lambda x: x):
prices = numpy.array(map(getter, data))
macd_oscillator = MACDIndicator(prices, nfast, nslow, nema)
# Skip the first nfast values
cropped_indicator = macd_oscillator.indicator()[nfast + 1:]
cropped_data = data[nfast + 1:]
chunks = sign_chunker(cropped_indicator, cropped_data)
return chunks
def macd_chunk_json(input):
python_list = json.loads(input)
chunks = macd_chunk(python_list, getter=lambda x: x[u'close'])
return json.dumps(chunks)
|
Use kitchen.i18n to setup gettext. Setup b_() for exceptions. | # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# python-fedora is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with python-fedora; if not, see <http://www.gnu.org/licenses/>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import kitchen
# Setup gettext for all of kitchen.
# Remember -- _() is for marking most messages
# b_() is for marking messages that are used in exceptions
(_, N_) = kitchen.i18n.easy_gettext_setup('python-fedora')
(b_, bN_) = kitchen.i18n.eay_gettext_setup('python-fedora', use_unicode=False)
from fedora import release
__version__ = release.VERSION
__all__ = ('__version__', 'accounts', 'client', 'release', 'tg')
| # Copyright 2008 Red Hat, Inc.
# This file is part of python-fedora
#
# python-fedora is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# python-fedora is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with python-fedora; if not, see <http://www.gnu.org/licenses/>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
'''
Python Fedora
Modules to communicate with and help implement Fedora Services.
'''
import gettext
translation = gettext.translation('python-fedora', '/usr/share/locale',
fallback=True)
_ = translation.ugettext
from fedora import release
__version__ = release.VERSION
__all__ = ('_', 'release', '__version__',
'accounts', 'client', 'tg')
|
Allow file paths to be given to set_log_target. | """
.. module:: dbsync.logs
:synopsis: Logging facilities for the library.
"""
import logging
#: All the library loggers
loggers = set()
log_handler = None
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
loggers.add(logger)
if log_handler is not None:
logger.addHandler(log_handler)
return logger
def set_log_target(fo):
"""
Set a stream as target for dbsync's logging. If a string is given,
it will be considered to be a path to a file.
"""
global log_handler
if log_handler is None:
log_handler = logging.FileHandler(fo) if isinstance(fo, basestring) \
else logging.StreamHandler(fo)
log_handler.setLevel(logging.WARNING)
log_handler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
for logger in loggers:
logger.addHandler(log_handler)
| """
.. module:: dbsync.logs
:synopsis: Logging facilities for the library.
"""
import logging
#: All the library loggers
loggers = set()
log_handler = None
def get_logger(name):
logger = logging.getLogger(name)
logger.setLevel(logging.WARNING)
loggers.add(logger)
if log_handler is not None:
logger.addHandler(log_handler)
return logger
def set_log_target(fo):
"Set a stream as target for dbsync's logging."
global log_handler
if log_handler is None:
log_handler = logging.StreamHandler(fo)
log_handler.setLevel(logging.WARNING)
log_handler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
for logger in loggers:
logger.addHandler(log_handler)
|
Fix for multiple usage types
Argument list/Actual parameters | /*
var args = ['jar', 'username', 'password']
raw function login (jar, username, password)
exported function login ()
check number of arguments if necessary
options object: login(arguments[0])
individual arguments:
for each argument add to an options array corresponding with argument order
login(options)
*/
// Includes
var options = require('../options.js');
// Define
var defaults = {
'jar': options.jar
};
function appendDefaults (opt, argumentList) {
for (var index in defaults) {
if (!opt[index] && argumentList.indexOf(index) > -1) {
opt[index] = defaults[index];
}
}
return opt;
}
exports.wrapExport = function (wrapFunction, argumentList) {
if (argumentList.length > 0) {
return function () {
var options = {};
if (arguments.length > 0) {
var first = arguments[0];
if (arguments.length === 1 && (argumentList.length !== 1 || (first instanceof Object && first[argumentList[0]]))) {
options = first;
} else {
for (var i = 0; i <= arguments.length; i++) {
options[argumentList[i]] = arguments[i];
}
}
}
return wrapFunction(options);
};
} else {
return wrapFunction;
}
};
| /*
var args = ['jar', 'username', 'password']
raw function login (jar, username, password)
exported function login ()
check number of arguments if necessary
options object: login(arguments[0])
individual arguments:
for each argument add to an options array corresponding with argument order
login(options)
*/
// Includes
var options = require('../options.js');
// Define
var defaults = {
'jar': options.jar
};
function appendDefaults (opt, argumentList) {
for (var index in defaults) {
if (!opt[index] && argumentList.indexOf(index) > -1) {
opt[index] = defaults[index];
}
}
return opt;
}
exports.wrapExport = function (wrapFunction, argumentList) {
if (argumentList.length > 0) {
return function () {
var options = {};
if (arguments.length > 0) {
if (typeof arguments[0] === 'object') {
options = arguments[0];
} else {
for (var i = 0; i <= arguments.length; i++) {
options[argumentList[i]] = arguments[i];
}
}
}
return wrapFunction(options);
};
} else {
return wrapFunction;
}
};
|
Fix namespacing of User class | <?php
namespace DrawMyAttention\ExpAuth;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use App\User;
class ExpressionEngineUserProvider extends EloquentUserProvider{
public function __construct(HasherContract $hasher, $model)
{
parent::__construct($hasher, $model);
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
$options = array();
if ($user instanceof User) {
$options['salt'] = $user->salt;
$options['byte_size'] = strlen($user->getAuthPassword());
}
return $this->hasher->check($plain, $user->getAuthPassword(), $options);
}
}
| <?php
namespace DrawMyAttention\ExpAuth;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use App\User;
class ExpressionEngineUserProvider extends EloquentUserProvider{
public function __construct(HasherContract $hasher, $model)
{
parent::__construct($hasher, $model);
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
$options = array();
if ($user instanceof App\User) {
$options['salt'] = $user->salt;
$options['byte_size'] = strlen($user->getAuthPassword());
}
return $this->hasher->check($plain, $user->getAuthPassword(), $options);
}
}
|
Add support for pix4d meta file format.
Former-commit-id: 7330412d726bf8cc4bd9d8659fb067e4921af798 | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import Pose
import ProjectMgr
# for all the images in the project image_dir, detect features using the
# specified method and parameters
parser = argparse.ArgumentParser(description='Set the aircraft poses from flight data.')
parser.add_argument('--project', required=True, help='project directory')
parser.add_argument('--sentera', help='use the specified sentera image-metadata.txt file (lat,lon,alt,yaw,pitch,roll)')
parser.add_argument('--pix4d', help='use the specified pix4d csv file (lat,lon,alt,roll,pitch,yaw)')
args = parser.parse_args()
proj = ProjectMgr.ProjectMgr(args.project)
proj.load_image_info()
pose_set = False
if args.sentera != None:
Pose.setAircraftPoses(proj, args.sentera, order='ypr')
pose_set = True
elif args.pix4d != None:
Pose.setAircraftPoses(proj, args.pix4d, order='rpy')
pose_set = True
if not pose_set:
print "Error: no flight data specified or problem with flight data"
print "No poses computed"
exit
# compute the project's NED reference location (based on average of
# aircraft poses)
proj.compute_ned_reference_lla()
print "NED reference location:", proj.ned_reference_lla
proj.save()
| #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import Pose
import ProjectMgr
# for all the images in the project image_dir, detect features using the
# specified method and parameters
parser = argparse.ArgumentParser(description='Set the aircraft poses from flight data.')
parser.add_argument('--project', required=True, help='project directory')
parser.add_argument('--sentera', help='use the specified sentera image-metadata.txt file')
args = parser.parse_args()
proj = ProjectMgr.ProjectMgr(args.project)
proj.load_image_info()
pose_set = False
if args.sentera != None:
Pose.setAircraftPoses(proj, args.sentera)
pose_set = True
if not pose_set:
print "Error: no flight data specified or problem with flight data"
print "No poses computed"
exit
# compute the project's NED reference location (based on average of
# aircraft poses)
proj.compute_ned_reference_lla()
print "NED reference location:", proj.ned_reference_lla
proj.save()
|
Fix ember-cli-deploy-redis v 0.5 bug
According new algorythm of how https://github.com/ember-cli-deploy/ember-cli-deploy-redis works - it only stores revision. So we have to additionally apply application name | 'use strict';
var redis = require('redis'),
coRedis = require('co-redis'),
koa = require('koa');
var app = koa(),
client = redis.createClient(
process.env.REDIS_PORT,
process.env.REDIS_HOST
),
dbCo = coRedis(client);
if (process.env.REDIS_SECRET) {
client.auth(process.env.REDIS_SECRET);
}
client.on('error', function (err) {
console.log('Redis client error: ' + err);
});
app.use(function* () {
var indexkey;
if (this.request.query.index_key) {
indexkey = process.env.APP_NAME +':'+ this.request.query.index_key;
} else {
indexkey = yield dbCo.get(process.env.APP_NAME +':current');
indexkey = process.env.APP_NAME + ':' + indexkey;
}
var index = yield dbCo.get(indexkey);
if (index) {
this.body = index;
} else {
this.status = 404;
}
});
app.listen(process.env.PORT || 3000);
| 'use strict';
var redis = require('redis'),
coRedis = require('co-redis'),
koa = require('koa');
var app = koa(),
client = redis.createClient(
process.env.REDIS_PORT,
process.env.REDIS_HOST
),
dbCo = coRedis(client);
if (process.env.REDIS_SECRET) {
client.auth(process.env.REDIS_SECRET);
}
client.on('error', function (err) {
console.log('Redis client error: ' + err);
});
app.use(function* () {
var indexkey;
if (this.request.query.index_key) {
indexkey = process.env.APP_NAME +':'+ this.request.query.index_key;
} else {
indexkey = yield dbCo.get(process.env.APP_NAME +':current');
}
var index = yield dbCo.get(indexkey);
if (index) {
this.body = index;
} else {
this.status = 404;
}
});
app.listen(process.env.PORT || 3000);
|
Rename assetPath to match the template | var express = require('express'),
routes = require(__dirname + '/app/routes.js'),
app = express(),
port = (process.env.PORT || 3000);
// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk_modules/views');
app.set('views', __dirname + '/app/views');
// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_template/assets'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_frontend_toolkit'));
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
// send assetPath to all views
app.use(function (req, res, next) {
res.locals.assetPath="/public/";
next();
});
// routes (found in routes.js)
routes.bind(app, '/public/');
// start the app
app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
| var express = require('express'),
routes = require(__dirname + '/app/routes.js'),
app = express(),
port = (process.env.PORT || 3000);
// Application settings
app.engine('html', require(__dirname + '/lib/template-engine.js').__express);
app.set('view engine', 'html');
app.set('vendorViews', __dirname + '/govuk_modules/views');
app.set('views', __dirname + '/app/views');
// Middleware to serve static assets
app.use('/public', express.static(__dirname + '/public'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_template/assets'));
app.use('/public', express.static(__dirname + '/govuk_modules/govuk_frontend_toolkit'));
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
// send assetPath to all views
app.use(function (req, res, next) {
res.locals.asset_path="/public/";
next();
});
// routes (found in routes.js)
routes.bind(app, '/public/');
// start the app
app.listen(port);
console.log('');
console.log('Listening on port ' + port);
console.log('');
|
Fix player stack: users were added multiple times | var models = require('../models');
var GameController = require("./GameController");
var playerQueue = [];
exports.startGame = function(req, res) {
var player1 = req.body.username;
var game = GameController.findGame(player1).then(function(game) {
// player has ongoing game
if (game != null) {
res.json({'game': game});
}
// Start a new game if opponent exists and opponent is not the same player. Pops the last element in queue.
else if (playerQueue.length > 0 && playerQueue.indexOf(player1) === -1) {
GameController.startGame(player1, playerQueue.pop()).then(function(game) {
models.Game.find({
include: [models.Board],
where: {id: game.id}
}).then(function(game) {
res.json({'game': game});
});
});
}
// Put the player in the queue if the player isn't already there
else if(playerQueue.indexOf(player1) === -1) {
playerQueue.unshift(player1);
res.json({'game': null});
}
});
};
| var models = require('../models');
var GameController = require("./GameController");
var playerQueue = [];
exports.startGame = function(req, res) {
var player1 = req.body.username;
var game = GameController.findGame(player1).then(function(game) {
// player has ongoing game
if (game != null) {
res.json({'game': game});
}
// Start a new game if opponent exists and opponent is not the same player. Pops the last element in queue.
else if (playerQueue.length > 0 && playerQueue.indexOf(player1) === -1) {
GameController.startGame(player1, playerQueue.pop()).then(function(game) {
models.Game.find({
include: [models.Board],
where: {id: game.id}
}).then(function(game) {
res.json({'game': game});
});
});
}
// If no players in queue, put this player in start of queue.
else {
playerQueue.unshift(player1);
res.json({'game': null});
}
});
};
|
Fix method name for getting the monitored sites | package de.gernd.simplemon.endpoints;
import de.gernd.simplemon.endpoints.model.AddSiteToMonitorRequest;
import de.gernd.simplemon.endpoints.model.GetMonitoredSitesResponse;
import de.gernd.simplemon.service.SimpleMonitoringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
@Component
@Path("/monitored-sites")
@Produces("application/json")
@Consumes("application/json")
public class SimpleMonitoringEndpoint {
@Autowired
private SimpleMonitoringService monitoringService;
/**
* Method for retrieving all currently monitored sites
*
* @return All currently monitored sites
*/
@Path("/")
@GET
public Response getMonitoredSites() {
GetMonitoredSitesResponse response = new GetMonitoredSitesResponse();
List<String> monitoredSites = monitoringService.getMonitoredSites();
response.monitoredSites = monitoredSites;
return Response.ok(monitoredSites).build();
}
/**
* Method for retrieving all currently monitored sites
*/
@Path("/")
@POST
public Response addSite(AddSiteToMonitorRequest addSiteToMonitorRequest){
monitoringService.startMonitoring(addSiteToMonitorRequest.url);
return Response.ok().build();
}
}
| package de.gernd.simplemon.endpoints;
import de.gernd.simplemon.endpoints.model.AddSiteToMonitorRequest;
import de.gernd.simplemon.endpoints.model.GetMonitoredSitesResponse;
import de.gernd.simplemon.service.SimpleMonitoringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
@Component
@Path("/monitored-sites")
@Produces("application/json")
@Consumes("application/json")
public class SimpleMonitoringEndpoint {
@Autowired
private SimpleMonitoringService monitoringService;
/**
* Method for retrieving all currently monitored sites
*
* @return All currently monitored sites
*/
@Path("/")
@GET
public Response monitor() {
GetMonitoredSitesResponse response = new GetMonitoredSitesResponse();
List<String> monitoredSites = monitoringService.getMonitoredSites();
response.monitoredSites = monitoredSites;
return Response.ok(monitoredSites).build();
}
/**
* Method for retrieving all currently monitored sites
*/
@Path("/")
@POST
public Response addSite(AddSiteToMonitorRequest addSiteToMonitorRequest){
monitoringService.startMonitoring(addSiteToMonitorRequest.url);
return Response.ok().build();
}
}
|
Add app.context() to populate context for render_template | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from subprocess import call
from ca import app, db, mail
from ca.models import Request
from flask import Flask, render_template
from flask_mail import Message
def mail_certificate(id, email):
with app.app_context():
msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email])
msg.body = render_template('mail.txt')
with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp:
msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read())
mail.send(msg)
for request in Request.query.filter(Request.generation_date == None).all(): # noqa
prompt = "Do you want to generate a certificate for {}, {} ?"
print(prompt.format(request.id, request.email))
print("Type y to continue")
confirm = input('>')
if confirm in ['Y', 'y']:
print('generating certificate')
call([app.config['COMMAND_BUILD'], request.id, request.email])
#call([app.config['COMMAND_MAIL'], request.id, request.email])
mail_certificate(request.id, request.email)
request.generation_date = datetime.date.today()
db.session.commit()
print()
else:
print('skipping generation \n')
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from subprocess import call
from ca import app, db, mail
from ca.models import Request
from flask import Flask, render_template
from flask_mail import Message
def mail_certificate(id, email):
msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email])
msg.body = render_template('mail.txt')
with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp:
msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read())
mail.send(msg)
for request in Request.query.filter(Request.generation_date == None).all(): # noqa
prompt = "Do you want to generate a certificate for {}, {} ?"
print(prompt.format(request.id, request.email))
print("Type y to continue")
confirm = input('>')
if confirm in ['Y', 'y']:
print('generating certificate')
call([app.config['COMMAND_BUILD'], request.id, request.email])
#call([app.config['COMMAND_MAIL'], request.id, request.email])
mail_certificate(request.id, request.email)
request.generation_date = datetime.date.today()
db.session.commit()
print()
else:
print('skipping generation \n')
|
Use gulp default task to build all | var path = require('path');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var bower_components = require('main-bower-files')();
var gopath = function() {
var gpm_dir = __dirname + path.sep + '.godeps';
if (process.env.GOPATH.split(path.delimiter).indexOf(gpm_dir) != -1) {
return process.env.GOPATH;
}
return gpm_dir + path.delimiter + process.env.GOPATH;
}
gulp.task('css', function() {
return gulp.src(bower_components)
.pipe($.filter('**/*.css'))
.pipe($.concat('main.css'))
.pipe($.minifyCss())
.pipe(gulp.dest('./public'));
});
gulp.task('js', function() {
return gulp.src(bower_components)
.pipe($.filter('**/*.js'))
.pipe($.concat('main.js'))
.pipe($.uglify())
.pipe(gulp.dest('./public'));
});
gulp.task('go', function() {
var newenv = process.env;
newenv.GOPATH = gopath();
return $.run('go build -o goose', {env: newenv}).exec();
});
gulp.task('default', ['go', 'css', 'js'], function() {});
| var path = require('path');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var bower_components = require('main-bower-files')();
var gopath = function() {
var gpm_dir = __dirname + path.sep + '.godeps';
if (process.env.GOPATH.split(path.delimiter).indexOf(gpm_dir) != -1) {
return process.env.GOPATH;
}
return gpm_dir + path.delimiter + process.env.GOPATH;
}
gulp.task('css', function() {
return gulp.src(bower_components)
.pipe($.filter('**/*.css'))
.pipe($.concat('main.css'))
.pipe($.minifyCss())
.pipe(gulp.dest('./public'));
});
gulp.task('js', function() {
return gulp.src(bower_components)
.pipe($.filter('**/*.js'))
.pipe($.concat('main.js'))
.pipe($.uglify())
.pipe(gulp.dest('./public'));
});
gulp.task('go', function() {
var newenv = process.env;
newenv.GOPATH = gopath();
return $.run('go build -o goose', {env: newenv}).exec();
});
gulp.task('default', function() {
// place code for your default task here
});
|
Fix for python2.6: decode doesn't take keyword arguments. | import os
import shlex
import sys
from canaryd_packages import six
# Not ideal but using the vendored in (to requests) chardet package
from canaryd_packages.requests.packages import chardet
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug('Executing command: {0}'.format(command))
if (
not kwargs.get('shell', False)
and not isinstance(command, (list, tuple))
):
command = shlex.split(command)
output = check_output( # noqa
command,
close_fds=True,
stderr=STDOUT, # noqa
*args, **kwargs
)
if isinstance(output, six.binary_type):
encoding = chardet.detect(output)['encoding']
output = output.decode(encoding)
return output
| import os
import shlex
import sys
from canaryd_packages import six
# Not ideal but using the vendored in (to requests) chardet package
from canaryd_packages.requests.packages import chardet
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug('Executing command: {0}'.format(command))
if (
not kwargs.get('shell', False)
and not isinstance(command, (list, tuple))
):
command = shlex.split(command)
output = check_output( # noqa
command,
close_fds=True,
stderr=STDOUT, # noqa
*args, **kwargs
)
if isinstance(output, six.binary_type):
encoding = chardet.detect(output)['encoding']
output = output.decode(encoding=encoding)
return output
|
Correct a minor error in the description of `OutMessage` | package molecule
// InMessage is a message sent to a molecule by an external agent.
//
// An in-message comprises a request, an optional cookie value and a
// dynamic payload. The meaning of the cookie depends on the request.
// Similarly, the actual contents of the payload depend on the
// request.
//
// Thus, it is highly imperative that other agents that correspond
// with a molecule be aware of what requests molecules understand, and
// what payloads are to be delivered as part of the message.
type InMessage struct {
Request uint8
Cookie uint64
Payload interface{}
}
// OutMessage is a message sent by a molecule in response to an
// in-message.
//
// An out-message comprises a status (result code), an optional cookie
// value and a dynamic payload. The meaning of the cookie depends on
// the request. Similarly, the actual contents of the payload depend
// on the request.
//
// Thus, it is highly imperative that other agents that correspond
// with a molecule be aware of what responses molecules send, and what
// payloads are delivered as part of the message.
type OutMessage struct {
Status int16
Cookie uint64
Payload interface{}
}
| package molecule
// InMessage is a message sent to a molecule by an external agent.
//
// An in-message comprises a request, an optional cookie value and a
// dynamic payload. The meaning of the cookie depends on the request.
// Similarly, the actual contents of the payload depend on the
// request.
//
// Thus, it is highly imperative that other agents that correspond
// with a molecule be aware of what requests molecules understand, and
// what payloads are to be delivered as part of the message.
type InMessage struct {
Request uint8
Cookie uint64
Payload interface{}
}
// OutMessage is a message sent by a molecule in response to an
// in-message.
//
// An out-message comprises a status (result code), an optional cookie
// value and a dynamic payload. The meaning of the cookie depends on
// the request. Similarly, the actual contents of the payload depend
// on the request.
//
// Thus, it is highly imperative that other agents that correspond
// with a molecule be aware of what responses molecules send, and what
// payloads are to be delivered as part of the message.
type OutMessage struct {
Status int16
Cookie uint64
Payload interface{}
}
|
Simplify result check to cover null and undefined. | 'use strict';
const KMSProvider = require('../../providers/kms');
/**
* Route handler for KMS secrets
* @param {StorageService} storage
* @returns {function}
*/
function KMS(storage) {
return (req, res, next) => {
// KMS doesn't require a token so we can just pass an empty string
storage.lookup('', req.body, KMSProvider)
.then((result) => {
if (result) {
Object.keys(result).forEach((key) => {
result[key.toLowerCase()] = result[key];
if (key.toLowerCase() !== key) {
delete result[key];
}
});
}
// Check for both undefined and null. `!= null` handles both cases.
if (result != null && result.hasOwnProperty('plaintext')) { // eslint-disable-line eqeqeq
result.plaintext = Buffer.from(result.plaintext, 'base64').toString();
}
if (result != null && result.hasOwnProperty('correlation_id')) { // eslint-disable-line eqeqeq
res.correlationId = result.correlation_id;
delete result.correlation_id;
}
res.json(result);
})
.catch(next);
};
}
module.exports = KMS;
| 'use strict';
const KMSProvider = require('../../providers/kms');
/**
* Route handler for KMS secrets
* @param {StorageService} storage
* @returns {function}
*/
function KMS(storage) {
return (req, res, next) => {
// KMS doesn't require a token so we can just pass an empty string
storage.lookup('', req.body, KMSProvider)
.then((result) => {
if (result != null) { // eslint-disable-line eqeqeq
Object.keys(result).forEach((key) => {
result[key.toLowerCase()] = result[key];
if (key.toLowerCase() !== key) {
delete result[key];
}
});
}
// Check for both undefined and null. `!= null` handles both cases.
if (result != null && result.hasOwnProperty('plaintext')) { // eslint-disable-line eqeqeq
result.plaintext = Buffer.from(result.plaintext, 'base64').toString();
}
if (result != null && result.hasOwnProperty('correlation_id')) { // eslint-disable-line eqeqeq
res.correlationId = result.correlation_id;
delete result.correlation_id;
}
res.json(result);
})
.catch(next);
};
}
module.exports = KMS;
|
Create dm channel if it doesn't exist | import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
if not requestor.dm_channel:
# No dm channel - create it
await requestor.create_dm()
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
| import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
dmChannel = requestor.dm_channel
if len(textList) > maxMessage and dmChannel.id != target.id :
# PM the contents to the requestor
await target.send("Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await target.send(message)
return True
|
Relocate core status codes to the 450-499 range | #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
# Status codes for a job
# Generic success
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
| #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
# Status codes for a job
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
|
Disable `compress` option for UglifyJS by default. Just 1% gain in gzipped, but possible huge perfomance loss with minified src. | /**
* class UglifyCompressor
*
* Engine for CSS minification. You will need `uglify-js` Node module installed:
*
* npm install uglify-js
*
*
* ##### SUBCLASS OF
*
* [[Template]]
**/
'use strict';
// 3rd-party
var UglifyJS; // initialized later
// internal
var Template = require('../template');
var prop = require('../common').prop;
////////////////////////////////////////////////////////////////////////////////
// Class constructor
var UglifyCompressor = module.exports = function UglifyCompressor() {
Template.apply(this, arguments);
UglifyJS = UglifyJS || Template.libs["uglify-js"] || require("uglify-js");
// Ensure UglifyJS v2 API
if (!!UglifyJS.parser) {
throw new Error("UglifyJS v1 not supported, please upgrade library.");
}
};
require('util').inherits(UglifyCompressor, Template);
// Compress data
UglifyCompressor.prototype.evaluate = function (/*context, locals*/) {
return UglifyJS.minify(this.data, { fromString: true, compress: false }).code;
};
// Expose default MimeType of an engine
prop(UglifyCompressor, 'defaultMimeType', 'application/javascript');
| /**
* class UglifyCompressor
*
* Engine for CSS minification. You will need `uglify-js` Node module installed:
*
* npm install uglify-js
*
*
* ##### SUBCLASS OF
*
* [[Template]]
**/
'use strict';
// 3rd-party
var UglifyJS; // initialized later
// internal
var Template = require('../template');
var prop = require('../common').prop;
////////////////////////////////////////////////////////////////////////////////
// Class constructor
var UglifyCompressor = module.exports = function UglifyCompressor() {
Template.apply(this, arguments);
UglifyJS = UglifyJS || Template.libs["uglify-js"] || require("uglify-js");
// Ensure UglifyJS v2 API
if (!!UglifyJS.parser) {
throw new Error("UglifyJS v1 not supported, please upgrade library.");
}
};
require('util').inherits(UglifyCompressor, Template);
// Compress data
UglifyCompressor.prototype.evaluate = function (/*context, locals*/) {
return UglifyJS.minify(this.data, { fromString: true }).code;
};
// Expose default MimeType of an engine
prop(UglifyCompressor, 'defaultMimeType', 'application/javascript');
|
Clone datasource in ComponentWillMount to rerendender ListView | import React, {Component, View, ListView} from 'react-native';
import PinListItem from './PinListItem.js';
export default class PinList extends Component {
constructor(props) {
super(props);
this.state = {
// create the data source
dataSource: new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
})
};
}
componentWillReceiveProps(nextProps) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(nextProps.pins)
});
}
componentWillMount() {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.props.pins)
});
}
renderItem(pin) {
const {deletePin} = this.props;
return (
// pass down pin info to PinListItem
<PinListItem
pin={pin}
deletePin={deletePin}
/>
);
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem.bind(this)}
/>
);
}
}
| import React, {Component, View, ListView} from 'react-native';
import PinListItem from './PinListItem.js';
export default class PinList extends Component {
constructor(props) {
super(props);
this.state = {
// create the data source
dataSource: new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
})
};
}
componentWillReceiveProps(nextProps) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(nextProps.pins)
});
}
renderItem(pin) {
const {deletePin} = this.props;
return (
// pass down pin info to PinListItem
<PinListItem
pin={pin}
deletePin={deletePin}
/>
);
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem.bind(this)}
/>
);
}
}
|
Improve show configuration command output | <?php
namespace Alchemy\WorkerBundle\Commands;
use Alchemy\Queue\MessageQueueRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Yaml;
class ShowQueueConfigurationCommand extends Command
{
/**
* @var MessageQueueRegistry
*/
private $queueRegistry;
/**
* @param MessageQueueRegistry $queueRegistry
*/
public function __construct(MessageQueueRegistry $queueRegistry)
{
parent::__construct();
$this->queueRegistry = $queueRegistry;
}
protected function configure()
{
$this->setName('workers:show-configuration');
}
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln([ '', 'Configured queues: ' ]);
foreach ($this->queueRegistry->getConfigurations() as $name => $configuration) {
$output->writeln([ ' ' . $name . ': ' . Yaml::dump($configuration, 0), '' ]);
}
}
}
| <?php
namespace Alchemy\WorkerBundle\Commands;
use Alchemy\Queue\MessageQueueRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ShowQueueConfigurationCommand extends Command
{
/**
* @var MessageQueueRegistry
*/
private $queueRegistry;
/**
* @param MessageQueueRegistry $queueRegistry
*/
public function __construct(MessageQueueRegistry $queueRegistry)
{
parent::__construct();
$this->queueRegistry = $queueRegistry;
}
protected function configure()
{
$this->setName('workers:show-configuration');
}
public function execute(InputInterface $input, OutputInterface $output)
{
foreach ($this->queueRegistry->getConfigurations() as $configuration) {
var_dump($configuration);
}
var_dump($this->queueRegistry->getQueue('worker-queue'));
}
}
|
Set main() to test data. | package eu.liveandgov.wp1.human_activity_recognition;
import eu.liveandgov.wp1.human_activity_recognition.containers.CountWindow;
import eu.liveandgov.wp1.human_activity_recognition.containers.TaggedWindow;
import eu.liveandgov.wp1.human_activity_recognition.helper.Persistor;
import eu.liveandgov.wp1.human_activity_recognition.producers.*;
/**
* Created with IntelliJ IDEA.
* User: cehlen
* Date: 06/01/14
* Time: 21:23
* To change this template use File | Settings | File Templates.
*/
public class Main {
public static void main(String args[]) {
CSVReader csvReader = new CSVReader();
WindowProducer windowProducer = new WindowProducer(1001, 995);
csvReader.setConsumer(windowProducer);
QualityFilter qualityFilter = new QualityFilter(50.0, 10, "windowFreq.log");
windowProducer.setConsumer(qualityFilter);
Interpolator interpolator = new Interpolator(50.0);
qualityFilter.setConsumer(interpolator);
PrintProducer<CountWindow> pp = new PrintProducer<CountWindow>("InterpolatedWindow");
interpolator.setConsumer(pp);
Persistor<CountWindow> pers = new Persistor<CountWindow>("out.csv");
pp.setConsumer(pers);
csvReader.read("Test/test.csv");
}
}
| package eu.liveandgov.wp1.human_activity_recognition;
import eu.liveandgov.wp1.human_activity_recognition.containers.CountWindow;
import eu.liveandgov.wp1.human_activity_recognition.containers.TaggedWindow;
import eu.liveandgov.wp1.human_activity_recognition.helper.Persistor;
import eu.liveandgov.wp1.human_activity_recognition.producers.*;
/**
* Created with IntelliJ IDEA.
* User: cehlen
* Date: 06/01/14
* Time: 21:23
* To change this template use File | Settings | File Templates.
*/
public class Main {
public static void main(String args[]) {
CSVReader csvReader = new CSVReader();
WindowProducer windowProducer = new WindowProducer(5000, 4995);
csvReader.setConsumer(windowProducer);
QualityFilter qualityFilter = new QualityFilter(50.0, 1.0, "windowFreq.log");
windowProducer.setConsumer(qualityFilter);
Interpolator interpolator = new Interpolator(50.0);
qualityFilter.setConsumer(interpolator);
Persistor<CountWindow> p = new Persistor("out.csv");
interpolator.setConsumer(p);
csvReader.read("/Users/cehlen/TrainingData/WALKING/12");
}
}
|
Use the more betterer os._exit | import logging
import os
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError
from flow_workflow.historian.messages import UpdateMessage
LOG = logging.getLogger(__name__)
class WorkflowHistorianMessageHandler(object):
message_class = UpdateMessage
def __init__(self, broker=None, storage=None, queue_name=None):
self.broker = broker
self.storage = storage
self.queue_name = queue_name
def __call__(self, message):
message_dict = message.to_dict()
LOG.info("Updating [net_key='%s', operation_id='%s']: %r",
message.net_key, message.operation_id, message_dict)
try:
self.storage.update(message_dict)
except (ResourceClosedError, TimeoutError, DisconnectionError):
LOG.exception("This historian cannot handle messages anymore because it lost access to Oracle... exiting.")
os._exit(1)
| import logging
import sys
from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError
from flow_workflow.historian.messages import UpdateMessage
LOG = logging.getLogger(__name__)
class WorkflowHistorianMessageHandler(object):
message_class = UpdateMessage
def __init__(self, broker=None, storage=None, queue_name=None):
self.broker = broker
self.storage = storage
self.queue_name = queue_name
def __call__(self, message):
message_dict = message.to_dict()
LOG.info("Updating [net_key='%s', operation_id='%s']: %r",
message.net_key, message.operation_id, message_dict)
try:
self.storage.update(message_dict)
except (ResourceClosedError, TimeoutError, DisconnectionError):
LOG.exception("This historian cannot handle messages anymore because it lost access to Oracle... exiting.")
sys._exit()
|
Fix unused import flag by codacy | # -*- coding: utf-8 -*-
"""
This module is used to manage optional dependencies.
Example usage::
from birdy.dependencies import ipywidgets as widgets
"""
import warnings
from .exceptions import IPythonWarning
# TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook,
# but we currently don't know how to handle this (see #89 and #138).
warnings.filterwarnings('ignore', category=IPythonWarning)
try:
import ipywidgets
except ImportError:
ipywidgets = None
warnings.warn('Jupyter Notebook is not supported. Please install *ipywidgets*.', IPythonWarning)
try:
import IPython
except ImportError:
IPython = None
warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning)
try:
import ipyleaflet # noqa: F401
except ImportError:
ipyleaflet = None
warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning)
| # -*- coding: utf-8 -*-
"""
This module is used to manage optional dependencies.
Example usage::
from birdy.dependencies import ipywidgets as widgets
"""
import warnings
from .exceptions import IPythonWarning
# TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook,
# but we currently don't know how to handle this (see #89 and #138).
warnings.filterwarnings('ignore', category=IPythonWarning)
try:
import ipywidgets
except ImportError:
ipywidgets = None
warnings.warn('Jupyter Notebook is not supported. Please install *ipywidgets*.', IPythonWarning)
try:
import IPython
except ImportError:
IPython = None
warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning)
try:
import ipyleaflet
except ImportError:
ipyleaflet = None
warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning)
|
Tweak filtering of applicants on assignment | from django.db.models import Q
from rest_framework_json_api.django_filters import DjangoFilterBackend
from bluebottle.assignments.transitions import ApplicantTransitions
class ApplicantListFilter(DjangoFilterBackend):
"""
Filter that shows all applicant if user is owner,
otherwise only show accepted applicants.
"""
def filter_queryset(self, request, queryset, view):
if request.user.is_authenticated():
queryset = queryset.filter(
Q(user=request.user) |
Q(activity__owner=request.user) |
Q(activity__initiative__activity_manager=request.user) |
Q(status__in=[
ApplicantTransitions.values.active,
ApplicantTransitions.values.accepted,
ApplicantTransitions.values.succeeded
])
)
else:
queryset = queryset.filter(status__in=[
ApplicantTransitions.values.new,
ApplicantTransitions.values.succeeded
])
return super(ApplicantListFilter, self).filter_queryset(request, queryset, view)
| from django.db.models import Q
from rest_framework_json_api.django_filters import DjangoFilterBackend
from bluebottle.assignments.transitions import ApplicantTransitions
class ApplicantListFilter(DjangoFilterBackend):
"""
Filter that shows all applicant if user is owner,
otherwise only show accepted applicants.
"""
def filter_queryset(self, request, queryset, view):
if request.user.is_authenticated():
queryset = queryset.filter(
Q(user=request.user) |
Q(activity__owner=request.user) |
Q(status__in=[
ApplicantTransitions.values.new,
ApplicantTransitions.values.succeeded
])
)
else:
queryset = queryset.filter(status__in=[
ApplicantTransitions.values.new,
ApplicantTransitions.values.succeeded
])
return super(ApplicantListFilter, self).filter_queryset(request, queryset, view)
|
Add debug info on error call | <?php
namespace Soil\QueueHttpEndpointBundle\Controller;
use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Created by PhpStorm.
* User: fliak
* Date: 5.2.15
* Time: 15.14
*/
class EndpointController {
/**
* @var GearmanClient
*/
protected $gearmanClient;
protected $queueStream;
public function __construct($gearmanClient, $queueStream) {
$this->gearmanClient = $gearmanClient;
$this->queueStream = $queueStream;
}
public function putJobAction(Request $request) {
try {
$data = $request->getContent();
$this->gearmanClient->send($this->queueStream, $data);
$response = new JsonResponse([
'success' => true
]);
}
catch(\Exception $e) {
$response = new JsonResponse([
'success' => false,
'error' => $e->getMessage(),
'workload' => $data
], 500);
}
return $response;
}
} | <?php
namespace Soil\QueueHttpEndpointBundle\Controller;
use Soilby\EventComponent\Service\GearmanClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Created by PhpStorm.
* User: fliak
* Date: 5.2.15
* Time: 15.14
*/
class EndpointController {
/**
* @var GearmanClient
*/
protected $gearmanClient;
protected $queueStream;
public function __construct($gearmanClient, $queueStream) {
$this->gearmanClient = $gearmanClient;
$this->queueStream = $queueStream;
}
public function putJobAction(Request $request) {
try {
$data = $request->get('data');
$this->gearmanClient->send($this->queueStream, $data);
$response = new JsonResponse([
'success' => true
]);
}
catch(\Exception $e) {
$response = new JsonResponse([
'success' => false,
'error' => $e->getMessage()
], 500);
}
return $response;
}
} |
DASHB-204: Add bunch of new events | /*
*
* CODENVY CONFIDENTIAL
* ________________
*
* [2012] - [2014] Codenvy, S.A.
* All Rights Reserved.
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.analytics.metrics;
/** @author Anatoliy Bazko */
public class RunnerTotalTime extends AbstractLongValueResulted {
private static final String TIME = "time";
public RunnerTotalTime() {
super(MetricType.RUNNER_TOTAL_TIME);
}
@Override
public String[] getTrackedFields() {
return new String[]{TIME};
}
@Override
public String getDescription() {
return "The total time of runners";
}
}
| /*
*
* CODENVY CONFIDENTIAL
* ________________
*
* [2012] - [2014] Codenvy, S.A.
* All Rights Reserved.
* NOTICE: All information contained herein is, and remains
* the property of Codenvy S.A. and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Codenvy S.A.
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Codenvy S.A..
*/
package com.codenvy.analytics.metrics;
/** @author Anatoliy Bazko */
public class RunnerTotalTime extends AbstractLongValueResulted {
private static final String TIME = "time";
protected RunnerTotalTime() {
super(MetricType.RUNNER_TOTAL_TIME);
}
@Override
public String[] getTrackedFields() {
return new String[]{TIME};
}
@Override
public String getDescription() {
return "The total time of runners";
}
}
|
Refactor the error logger A BIT. | package assert
import (
"fmt"
"io"
"os"
)
type location struct {
Test string
FileName string
Line int
}
type errorLogger interface {
Log(location *location, message string)
}
var theLogger errorLogger = &errorLoggerImpl{writer: os.Stdout}
type errorLoggerImpl struct {
writer io.Writer
prevTestName string
prevTestLine int
}
const (
failOutput = "--- FAIL: %s\n\t%s:%d\n\t\t%s\n"
failOutputWithoutFailLine = "\t%s:%d\n\t\t%s\n"
failOutputWithoutLineNumber = "\t\t%s\n"
)
func (logger *errorLoggerImpl) Log(location *location, message string) {
args := []interface{}{location.Test, location.FileName, location.Line, message}
if logger.prevTestName != location.Test {
fmt.Fprintf(logger.writer, failOutput, args...)
} else if logger.prevTestLine != location.Line {
fmt.Fprintf(logger.writer, failOutputWithoutFailLine, args[1:]...)
} else {
fmt.Fprintf(logger.writer, failOutputWithoutLineNumber, message)
}
logger.prevTestName = location.Test
logger.prevTestLine = location.Line
}
| package assert
import (
"fmt"
"io"
"os"
)
type location struct {
Test string
FileName string
Line int
}
type errorLogger interface {
Log(location *location, message string)
}
var theLogger errorLogger = &errorLoggerImpl{writer: os.Stdout}
type errorLoggerImpl struct {
writer io.Writer
prevTestName string
prevTestLine int
}
const (
failOutput = "--- FAIL: %s\n\t%s:%d\n\t\t%s\n"
failOutputWithoutFailLine = "\t%s:%d\n\t\t%s\n"
failOutputWithoutLineNumber = "\t\t%s\n"
)
func (logger *errorLoggerImpl) Log(location *location, message string) {
args := []interface{}{location.Test, location.FileName, location.Line, message}
if logger.prevTestName != location.Test {
fmt.Fprintf(logger.writer, failOutput, args...)
} else {
if logger.prevTestLine != location.Line {
fmt.Fprintf(logger.writer, failOutputWithoutFailLine, args[1:]...)
} else {
fmt.Fprintf(logger.writer, failOutputWithoutLineNumber, message)
}
}
logger.prevTestName = location.Test
logger.prevTestLine = location.Line
}
|
Throw an error if someon wants to buffer too much data in memory. | var sprintf = require('sprintf').sprintf;
var log = require('util/log');
var MAX_BUFFER_SIZE = 10 * 1024 * 1024;
function attachMiddleware(maxSize) {
if (maxSize > MAX_BUFFER_SIZE) {
throw new Error(sprintf('Buffering more then %d bytes of data in memory is a bad idea',
MAX_BUFFER_SIZE));
}
return function bodyDecoder(req, res, next) {
var cl, bodyLen = 0;
req.buffer = '';
cl = req.headers['content-length'];
if (cl) {
cl = parseInt(cl, 10);
if (cl >= maxSize) {
log.info('Denying client for too large content length');
res.writeHead(413, {Connection: 'close'});
res.end();
}
}
function onData(chunk) {
req.buffer += chunk;
bodyLen += chunk.length;
if (bodyLen >= maxSize) {
log.info('Denying client for body too large');
res.writeHead(413, {Connection: 'close'});
res.end();
req.removeListener('data', onData);
}
}
req.setEncoding('utf8');
req.on('data', onData);
req.on('end', next);
};
}
exports.attachMiddleware = attachMiddleware;
| var log = require('util/log');
function attachMiddleware(maxSize) {
return function bodyDecoder(req, res, next) {
var cl, bodyLen = 0;
req.buffer = '';
cl = req.headers['content-length'];
if (cl) {
cl = parseInt(cl, 10);
if (cl >= maxSize) {
log.info('Denying client for too large content length');
res.writeHead(413, {Connection: 'close'});
res.end();
}
}
function onData(chunk) {
req.buffer += chunk;
bodyLen += chunk.length;
if (bodyLen >= maxSize) {
log.info('Denying client for body too large');
res.writeHead(413, {Connection: 'close'});
res.end();
req.removeListener('data', onData);
}
}
req.setEncoding('utf8');
req.on('data', onData);
req.on('end', next);
};
}
exports.attachMiddleware = attachMiddleware;
|
Use the API as it was intended | import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string('server', 'site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
| import sys
from django.conf import settings
class classproperty(property):
"""
Use it to decorate a classmethod to make it a "class property".
"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def get_server_name():
# Import here to avoid cyclic import
from ideascube.models import Setting
# This used to be a setting. Keep honoring it for now, so we don't break
# expectations from users of already deployed boxes.
default = getattr(settings, 'IDEASCUBE_NAME', 'Ideas Cube')
return Setting.get_string(
namespace='server', key='site-name', default=default)
# We do not use functool.partial cause we want to mock stderr for unittest
# If we use partial we keep a ref to the original sys.stderr and output is not
# captured.
def printerr(*args, **kwargs):
kwargs['file'] = sys.stderr
kwargs['flush'] = True
return print(*args, **kwargs)
|
Fix initial viewMode parsing typo | import { history, document } from 'global';
import qs from 'qs';
import { toId } from '@storybook/router/utils';
export function pathToId(path) {
const match = (path || '').match(/^\/story\/(.+)/);
if (!match) {
throw new Error(`Invalid path '${path}', must start with '/story/'`);
}
return match[1];
}
export const setPath = ({ storyId, viewMode }) => {
const { path, selectedKind, selectedStory, ...rest } = qs.parse(document.location.search, {
ignoreQueryPrefix: true,
});
const newPath = `${document.location.pathname}?${qs.stringify({
...rest,
id: storyId,
viewMode,
})}`;
history.replaceState({}, '', newPath);
};
export const getIdFromLegacyQuery = ({ path, selectedKind, selectedStory }) =>
(path && pathToId(path)) || (selectedKind && selectedStory && toId(selectedKind, selectedStory));
export const parseQueryParameters = search => {
const { id } = qs.parse(search, { ignoreQueryPrefix: true });
return id;
};
export const initializePath = () => {
const query = qs.parse(document.location.search, { ignoreQueryPrefix: true });
let { id: storyId, viewMode } = query; // eslint-disable-line prefer-const
if (!storyId) {
storyId = getIdFromLegacyQuery(query);
if (storyId) {
setPath({ storyId, viewMode });
}
}
return { storyId, viewMode };
};
| import { history, document } from 'global';
import qs from 'qs';
import { toId } from '@storybook/router/utils';
export function pathToId(path) {
const match = (path || '').match(/^\/story\/(.+)/);
if (!match) {
throw new Error(`Invalid path '${path}', must start with '/story/'`);
}
return match[1];
}
export const setPath = ({ storyId, viewMode }) => {
const { path, selectedKind, selectedStory, ...rest } = qs.parse(document.location.search, {
ignoreQueryPrefix: true,
});
const newPath = `${document.location.pathname}?${qs.stringify({
...rest,
id: storyId,
viewMode,
})}`;
history.replaceState({}, '', newPath);
};
export const getIdFromLegacyQuery = ({ path, selectedKind, selectedStory }) =>
(path && pathToId(path)) || (selectedKind && selectedStory && toId(selectedKind, selectedStory));
export const parseQueryParameters = search => {
const { id } = qs.parse(search, { ignoreQueryPrefix: true });
return id;
};
export const initializePath = () => {
const query = qs.parse(document.location.search, { ignoreQueryPrefix: true });
let { id: storyId, viewMode } = query; // eslint-disable-line prefer-const
if (!storyId) {
storyId = getIdFromLegacyQuery(query);
if (storyId) {
setPath({ storyId, viewMode });
}
}
return { storyId };
};
|
Move back to old way... | package net.darkmist.alib.escape.jsp;
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import net.darkmist.alib.escape.Escaper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class BaseTag extends BodyTagSupport
{
private static final Class<BaseTag> CLASS = BaseTag.class;
private static final Logger logger = LoggerFactory.getLogger(CLASS);
private Escaper escaper;
protected BaseTag(Escaper escaper)
{
this.escaper = escaper;
}
@Override
public int doAfterBody() throws JspTagException
{
try
{
escaper.escape(getPreviousOut(), bodyContent.getString());
}
catch (IOException e)
{
throw new JspTagException("IOException writing encoded output.", e);
}
bodyContent.clearBody();
return SKIP_BODY;
}
}
| package net.darkmist.alib.escape.jsp;
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import net.darkmist.alib.escape.Escaper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class BaseTag implements Tag
{
private static final Class<BaseTag> CLASS = BaseTag.class;
private static final Logger logger = LoggerFactory.getLogger(CLASS);
private Escaper escaper;
private PageContext pc;
private Tag parent;
protected BaseTag(Escaper escaper)
{
this.escaper = escaper;
}
@Override
public void setPageContext(PageContext pc_)
{
this.pc = pc_;
}
@Override
public void setParent(Tag t)
{
parent = t;
}
@Override
public Tag getParent()
{
return parent;
}
@Override
public int doStartTag() throws JspTagException
{
pc.pushBody(escaper.escape(pc.getOut()));
return EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspTagException
{
pc.popBody();
return EVAL_PAGE;
}
@Override
public void release()
{
pc = null;
parent = null;
}
}
|
Fix build again after merge error in Github. | package rocks.nt.apm.jmeter.config.influxdb;
/**
* Constants (Tag, Field, Measurement) names for the requests measurement.
*
* @author Alexander Wert
*
*/
public interface RequestMeasurement {
/**
* Measurement name.
*/
String MEASUREMENT_NAME = "requestsRaw";
/**
* Tags.
*
* @author Alexander Wert
*
*/
public interface Tags {
/**
* Request name tag.
*/
String REQUEST_NAME = "requestName";
}
/**
* Fields.
*
* @author Alexander Wert
*
*/
public interface Fields {
/**
* Response time field.
*/
String RESPONSE_TIME = "responseTime";
/**
* Error count field.
*/
String ERROR_COUNT = "errorCount";
/**
* Thread name field
*/
String THREAD_NAME = "threadName";
/**
* Test name field
*/
String TEST_NAME = "testName";
/**
* Node name field
*/
String NODE_NAME = "nodeName";
}
}
| package rocks.nt.apm.jmeter.config.influxdb;
/**
* Constants (Tag, Field, Measurement) names for the requests measurement.
*
* @author Alexander Wert
*
*/
public interface RequestMeasurement {
/**
* Measurement name.
*/
String MEASUREMENT_NAME = "requestsRaw";
/**
* Tags.
*
* @author Alexander Wert
*
*/
public interface Tags {
/**
* Request name tag.
*/
String REQUEST_NAME = "requestName";
}
/**
* Fields.
*
* @author Alexander Wert
*
*/
public interface Fields {
/**
* Response time field.
*/
String RESPONSE_TIME = "responseTime";
/**
* Error count field.
*/
String ERROR_COUNT = "errorCount";
/**
* Thread name field
*/
String THREAD_NAME = "threadName";
/**
* Test name field
*/
String TEST_NAME = "testName";
* Node name field
*/
String NODE_NAME = "nodeName";
}
}
|
BAP-1534: Fix acl access levels selector on root entity | <?php
namespace Oro\Bundle\SecurityBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
class AclPermissionController extends Controller
{
/**
* @Route(
* "/acl-access-levels/{oid}", name="oro_security_access_levels" , requirements={"oid"="\w+:[\w\(\)]+"
* })
*/
public function aclAccessLevelsAction($oid)
{
if (strpos($oid, 'entity') !== false) {
$oid = str_replace('_', '\\', $oid);
}
$levels = $this
->get('oro_security.acl.manager')
->getAccessLevels($oid);
$translator = $this->get('translator');
foreach ($levels as $id => $label) {
$levels[$id] = $translator->trans('oro.security.access-level.' . $label);
}
return new JsonResponse(
$levels
);
}
}
| <?php
namespace Oro\Bundle\SecurityBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
class AclPermissionController extends Controller
{
/**
* @Route(
* "/acl-access-levels/{oid}", name="oro_security_access_levels" , requirements={"oid"="((\w+):)+(.*)"
* })
*/
public function aclAccessLevelsAction($oid)
{
if (strpos($oid, 'entity') !== false) {
$oid = str_replace('_', '\\', $oid);
}
$levels = $this
->get('oro_security.acl.manager')
->getAccessLevels($oid);
$translator = $this->get('translator');
foreach ($levels as $id => $label) {
$levels[$id] = $translator->trans('oro.security.access-level.' . $label);
}
return new JsonResponse(
$levels
);
}
}
|
Update so logout responses are instantanteous | package info.freelibrary.jiiify.handlers;
import static info.freelibrary.jiiify.RoutePatterns.LOGIN;
import info.freelibrary.jiiify.Configuration;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
public class LogoutHandler extends JiiifyHandler {
public LogoutHandler(final Configuration aConfig) {
super(aConfig);
}
@Override
public void handle(final RoutingContext aContext) {
final HttpServerResponse response = aContext.response();
final Session session = aContext.session();
if (LOGGER.isDebugEnabled()) {
final JsonObject principal = aContext.user().principal();
final String user = principal.getString("name");
final String email = principal.getString("email");
LOGGER.debug("Logging out of session '{}': {} ({})", session.id(), user, email);
}
aContext.clearUser();
response.setStatusCode(303).putHeader("Location", LOGIN).end();
}
}
| package info.freelibrary.jiiify.handlers;
import static info.freelibrary.jiiify.RoutePatterns.LOGIN;
import info.freelibrary.jiiify.Configuration;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
public class LogoutHandler extends JiiifyHandler {
public LogoutHandler(final Configuration aConfig) {
super(aConfig);
}
@Override
public void handle(final RoutingContext aContext) {
final HttpServerResponse response = aContext.response();
final Session session = aContext.session();
if (LOGGER.isDebugEnabled()) {
final JsonObject principal = aContext.user().principal();
final String user = principal.getString("name");
final String email = principal.getString("email");
LOGGER.debug("Logging out of session '{}': {} ({})", session.id(), user, email);
}
session.destroy();
response.setStatusCode(303).putHeader("Location", LOGIN).end();
}
}
|
Increment azure-sdk dependency to match version in OBS. | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from azurectl.version import __VERSION__
config = {
'description': 'Manage Azure PubCloud Service',
'author': 'PubCloud Development team',
'url': 'https://github.com/SUSE/azurectl',
'download_url': 'https://github.com/SUSE/azurectl',
'author_email': 'public-cloud-dev@susecloud.net',
'version': __VERSION__,
'install_requires': [
'docopt==0.6.2',
'APScheduler==3.0.2',
'pyliblzma==0.5.3',
'azure==0.11.1',
'python-dateutil==2.1'
],
'packages': ['azurectl'],
'entry_points': {
'console_scripts': ['azurectl=azurectl.azurectl:main'],
},
'name': 'azurectl'
}
setup(**config)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from azurectl.version import __VERSION__
config = {
'description': 'Manage Azure PubCloud Service',
'author': 'PubCloud Development team',
'url': 'https://github.com/SUSE/azurectl',
'download_url': 'https://github.com/SUSE/azurectl',
'author_email': 'public-cloud-dev@susecloud.net',
'version': __VERSION__,
'install_requires': [
'docopt==0.6.2',
'APScheduler==3.0.2',
'pyliblzma==0.5.3',
'azure==0.11.0',
'python-dateutil==2.1'
],
'packages': ['azurectl'],
'entry_points': {
'console_scripts': ['azurectl=azurectl.azurectl:main'],
},
'name': 'azurectl'
}
setup(**config)
|
Add a version of the init method that accepts Context as a parameter
Closes #34 | package com.jakewharton.threetenabp;
import android.app.Application;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import org.threeten.bp.zone.TzdbZoneRulesProvider;
import org.threeten.bp.zone.ZoneRulesProvider;
/** Android-specific initializer for the JSR-310 library. */
public final class AndroidThreeTen {
private static final AtomicBoolean initialized = new AtomicBoolean();
public static void init(Application application) {
init((Context) application);
}
public static void init(Context context) {
if (initialized.getAndSet(true)) {
return;
}
TzdbZoneRulesProvider provider;
InputStream is = null;
try {
is = context.getAssets().open("org/threeten/bp/TZDB.dat");
provider = new TzdbZoneRulesProvider(is);
} catch (IOException e) {
throw new IllegalStateException("TZDB.dat missing from assets.", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
}
ZoneRulesProvider.registerProvider(provider);
}
private AndroidThreeTen() {
throw new AssertionError("No instances.");
}
}
| package com.jakewharton.threetenabp;
import android.app.Application;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import org.threeten.bp.zone.TzdbZoneRulesProvider;
import org.threeten.bp.zone.ZoneRulesProvider;
/** Android-specific initializer for the JSR-310 library. */
public final class AndroidThreeTen {
private static final AtomicBoolean initialized = new AtomicBoolean();
public static void init(Application application) {
if (initialized.getAndSet(true)) {
return;
}
TzdbZoneRulesProvider provider;
InputStream is = null;
try {
is = application.getAssets().open("org/threeten/bp/TZDB.dat");
provider = new TzdbZoneRulesProvider(is);
} catch (IOException e) {
throw new IllegalStateException("TZDB.dat missing from assets.", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
}
ZoneRulesProvider.registerProvider(provider);
}
private AndroidThreeTen() {
throw new AssertionError("No instances.");
}
}
|
Set up route for scraping wikipedia | var express = require('express');
var router = express.Router();
const {
getEntry,
getAllEntries,
addEntry,
deleteEntry
} = require('./../db/entries')
const {
getDataFromUrl,
getDataFromName
} = require('./../scrape/getData')
const getPeopleFromWiki = require('./../scrape/getPeopleFromWiki')
/* GET entries */
router.get('/:letter', function(req, res) {
getPeopleFromWiki(`https://en.wikipedia.org/wiki/Category:Living_people?from=${req.params.letter}`)
.then(urls => {
urls.forEach(url => {
getDataFromUrl(url)
.then(data => addEntry(data))
.then(response => console.log(response, "added"))
.catch(error => console.log(error))
})
})
.then(() => res.send('Wikipedia scraped and entered'))
.catch(error => {
res.send('Error!', error)
})
});
module.exports = router;
| var express = require('express');
var router = express.Router();
const {
getEntry,
getAllEntries,
addEntry,
deleteEntry
} = require('./../db/entries')
const {
getDataFromUrl,
getDataFromName
} = require('./../scrape/getData')
const getPeopleFromWiki = require('./../scrape/getPeopleFromWiki')
/* GET entries */
router.get('/', function(req, res) {
getPeopleFromWiki('https://en.wikipedia.org/wiki/Category:Living_people?from=D')
.then(urls => {
urls.forEach(url => {
getDataFromUrl(url)
.then(data => addEntry(data))
.catch(error => console.log(error))
})
})
.then(() => res.send('Wikipedia scraped and entered'))
.catch(error => {
res.send('Error!', error)
})
});
module.exports = router;
|
Add another method to the submodule interface | <?php
/**
*
* @package OpenFlame Web Framework
* @copyright (c) 2010 OpenFlameCMS.com
* @license http://opensource.org/licenses/mit-license.php The MIT License
* @link https://github.com/OpenFlame/OpenFlame-Framework
*
* Minimum Requirement: PHP 5.3.0
*/
namespace OpenFlame\Framework\Header\Submodule;
use OpenFlame\Framework\Core;
if(!defined('OpenFlame\\ROOT_PATH')) exit;
/**
* OpenFlame Web Framework - Header management submodule interface,
* Makes sure that we have the methods necessary to manipulate the header management submodule object.
*
*
* @license http://opensource.org/licenses/mit-license.php The MIT License
* @link https://github.com/OpenFlame/OpenFlame-Framework
*/
interface SubmoduleInterface
{
public static function newInstance();
public function setManager(\OpenFlame\Framework\Header\Manager $manager);
public function injectHeaders();
}
| <?php
/**
*
* @package OpenFlame Web Framework
* @copyright (c) 2010 OpenFlameCMS.com
* @license http://opensource.org/licenses/mit-license.php The MIT License
* @link https://github.com/OpenFlame/OpenFlame-Framework
*
* Minimum Requirement: PHP 5.3.0
*/
namespace OpenFlame\Framework\Header\Submodule;
use OpenFlame\Framework\Core;
if(!defined('OpenFlame\\ROOT_PATH')) exit;
/**
* OpenFlame Web Framework - Header management submodule interface,
* Makes sure that we have the methods necessary to manipulate the header management submodule object.
*
*
* @license http://opensource.org/licenses/mit-license.php The MIT License
* @link https://github.com/OpenFlame/OpenFlame-Framework
*/
interface SubmoduleInterface
{
public static function newInstance();
public function setManager(\OpenFlame\Framework\Header\Manager $manager);
}
|
Use correct env to check if on github | """Tests for execute commands function"""
import os
import subprocess
import pytest
from scout.server.extensions.loqus_extension import execute_command
TRAVIS = os.getenv("TRAVIS")
GITHUB = os.getenv("CI")
def test_run_execute_command():
"""Test run echo with execute command"""
# GIVEN a command to run in the shell
output = "hello world"
cmd = ["echo", output]
# WHEN running it with execute command
res = execute_command(cmd)
# THEN assert the output is correct
assert res.strip() == output
@pytest.mark.skipif(TRAVIS, reason="Unknown problems on travis")
@pytest.mark.skipif(GITHUB, reason="Unknown problems on github actions")
def test_run_failing_command():
"""Test run a failing command with execute command"""
# GIVEN a command that will fail when run in the shell
cmd = ["cd", "nonexistingdirectory"]
exception = subprocess.CalledProcessError
# WHEN running it with execute command
with pytest.raises(exception):
# THEN assert that an exception is raised
execute_command(cmd)
@pytest.mark.skipif(TRAVIS, reason="Unknown problems on travis")
@pytest.mark.skipif(GITHUB, reason="Unknown problems on github actions")
def test_run_command_no_output():
"""Test run a command without output"""
# GIVEN a command that returns no output
cmd = ["cd", "./"]
# WHEN running it with execute command
res = execute_command(cmd)
# THEN assert that the empty string is returned
assert res == ""
| """Tests for execute commands function"""
import os
import subprocess
import pytest
from scout.server.extensions.loqus_extension import execute_command
TRAVIS = os.getenv("TRAVIS")
GITHUB = os.getenv("GITHUB")
def test_run_execute_command():
"""Test run echo with execute command"""
# GIVEN a command to run in the shell
output = "hello world"
cmd = ["echo", output]
# WHEN running it with execute command
res = execute_command(cmd)
# THEN assert the output is correct
assert res.strip() == output
@pytest.mark.skipif(TRAVIS, reason="Unknown problems on travis")
@pytest.mark.skipif(GITHUB, reason="Unknown problems on github actions")
def test_run_failing_command():
"""Test run a failing command with execute command"""
# GIVEN a command that will fail when run in the shell
cmd = ["cd", "nonexistingdirectory"]
exception = subprocess.CalledProcessError
# WHEN running it with execute command
with pytest.raises(exception):
# THEN assert that an exception is raised
execute_command(cmd)
@pytest.mark.skipif(TRAVIS, reason="Unknown problems on travis")
@pytest.mark.skipif(GITHUB, reason="Unknown problems on github actions")
def test_run_command_no_output():
"""Test run a command without output"""
# GIVEN a command that returns no output
cmd = ["cd", "./"]
# WHEN running it with execute command
res = execute_command(cmd)
# THEN assert that the empty string is returned
assert res == ""
|
Add session_timeout to ReservationAdmin list_display | from django.contrib import admin
from karspexet.ticket.models import Account, Reservation, Ticket, Voucher, PricingModel
class ReservationAdmin(admin.ModelAdmin):
list_display = ('show', 'total', 'finalized', 'reservation_code', 'session_timeout', 'tickets')
list_filter = ('finalized', 'show')
class TicketAdmin(admin.ModelAdmin):
list_display = ('price', 'ticket_type', 'show', 'seat', 'account', 'ticket_code')
class VoucherAdmin(admin.ModelAdmin):
list_display = ('amount', 'code', 'expiry_date', 'created_by')
list_filter = ('expiry_date', 'created_by')
class PricingModelAdmin(admin.ModelAdmin):
list_display = ('seating_group', 'prices', 'valid_from')
class AccountAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'phone')
admin.site.register(Reservation, ReservationAdmin)
admin.site.register(Ticket, TicketAdmin)
admin.site.register(Voucher, VoucherAdmin)
admin.site.register(PricingModel, PricingModelAdmin)
admin.site.register(Account, AccountAdmin)
| from django.contrib import admin
from karspexet.ticket.models import Account, Reservation, Ticket, Voucher, PricingModel
class ReservationAdmin(admin.ModelAdmin):
list_display = ('show', 'total', 'finalized', 'reservation_code', 'tickets')
list_filter = ('finalized', 'show')
class TicketAdmin(admin.ModelAdmin):
list_display = ('price', 'ticket_type', 'show', 'seat', 'account', 'ticket_code')
class VoucherAdmin(admin.ModelAdmin):
list_display = ('amount', 'code', 'expiry_date', 'created_by')
list_filter = ('expiry_date', 'created_by')
class PricingModelAdmin(admin.ModelAdmin):
list_display = ('seating_group', 'prices', 'valid_from')
class AccountAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'phone')
admin.site.register(Reservation, ReservationAdmin)
admin.site.register(Ticket, TicketAdmin)
admin.site.register(Voucher, VoucherAdmin)
admin.site.register(PricingModel, PricingModelAdmin)
admin.site.register(Account, AccountAdmin)
|
Allow term to be specified via get parameter | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* This file contains the Search controller
*/
/**
* The controller for the search pages
*/
class Search extends CI_Controller {
/**
* The search page call
*/
function index()
{
$this->load->helper('form');
$this->load->library('form_validation');
$submit = $this->input->post('submit');
$search_results = array();
$search_term = $this->input->get_post('term', TRUE);
if($submit)
{
if($this->form_validation->run('search'))
{
$this->load->model('spark');
$search_results = Spark::search($search_term);
}
else
{
UserHelper::setNotice('Whoops. There were some errors. Check below and re-submit!');
}
}
$data['search_term'] = $search_term;
$data['sparks'] = $search_results;
echo json_encode($data);
}
}
| <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* This file contains the Search controller
*/
/**
* The controller for the search pages
*/
class Search extends CI_Controller {
/**
* The search page call
*/
function index()
{
$this->load->helper('form');
$this->load->library('form_validation');
$submit = $this->input->post('submit');
$search_results = array();
$search_term = $this->input->post('term');
if($submit)
{
if($this->form_validation->run('search'))
{
$this->load->model('spark');
$search_results = Spark::search($search_term);
}
else
{
UserHelper::setNotice('Whoops. There were some errors. Check below and re-submit!');
}
}
$data['search_term'] = $search_term;
$data['sparks'] = $search_results;
echo json_encode($data);
}
}
|
Update Heart actors helper class to handle args | #! -*- coding:utf-8 -*-
import time
import threading
class Heart(threading.Thread):
"""Implementation of an heart beating routine
To be used by actors to send swf heartbeats notifications
once in a while.
:param heartbeating_closure: Function to be called on heart
beat tick. It takes not argument as input
:type heartbeating_closure: function
:param heartbeat_interval: interval between each heartbeats (in seconds)
:type heartbeat_interval: integer
:param closure_args: feel free to provide arguments to your heartbeating closure
"""
def __init__(self, heartbeating_closure, closure_args,
heartbeat_interval, *args, **kwargs):
threading.Thread.__init__(self)
self.heartbeating_closure = heartbeating_closure
self.closure_args = closure_args
self.heartbeat_interval = heartbeat_interval
self.keep_beating = True
def stop(self):
"""Explicitly call for a heart stop.
.join() method should be called after stop though.
"""
self.keep_beating = False
def run(self):
while self.keep_beating is True:
self.heartbeating_closure(self.closure_args)
time.sleep(self.heartbeat_interval)
| #! -*- coding:utf-8 -*-
import time
import threading
class Heart(threading.Thread):
"""Implementation of an heart beating routine
To be used by actors to send swf heartbeats notifications
once in a while.
:param heartbeating_closure: Function to be called on heart
beat tick. It takes not argument as input
:type heartbeating_closure: function
:param heartbeat_interval: interval between each heartbeats (in seconds)
:type heartbeat_interval: integer
"""
def __init__(self, heartbeating_closure,
heartbeat_interval, *args, **kwargs):
threading.Thread.__init__(self)
self.heartbeating_closure = heartbeating_closure
self.heartbeat_interval = heartbeat_interval
self.keep_beating = True
def stop(self):
"""Explicitly call for a heart stop.
.join() method should be called after stop though.
"""
self.keep_beating = False
def run(self):
while self.keep_beating is True:
self.heartbeating_closure()
time.sleep(self.heartbeat_interval)
|
Remove debug output from test | package main
import "testing"
func TestLineBreaking(t *testing.T) {
var tests = []struct {
text string
result string
}{
{
`\\name[Domestic scent](…Properly……I want to take a bath……
today…Let's go home.……)`,
`\\name[Domestic scent](…Properly……I want to take a bath……
today…Let's go home.……)`,
},
{
`"Money %s\\\\G I got!"`,
`"Money %s\\\\G I got!"`,
},
}
for _, pair := range tests {
r := breakLines(pair.text)
if r != pair.result {
t.Errorf("For\n%q\nexpected\n%q\ngot\n%q\n", pair.text, pair.result, r)
}
}
}
| package main
import (
"testing"
log "github.com/Sirupsen/logrus"
)
func TestLineBreaking(t *testing.T) {
log.SetLevel(log.DebugLevel)
var tests = []struct {
text string
result string
}{
{
`\\name[Domestic scent](…Properly……I want to take a bath……
today…Let's go home.……)`,
`\\name[Domestic scent](…Properly……I want to take a bath……
today…Let's go home.……)`,
},
{
`"Money %s\\\\G I got!"`,
`"Money %s\\\\G I got!"`,
},
}
for _, pair := range tests {
r := breakLines(pair.text)
if r != pair.result {
t.Errorf("For\n%q\nexpected\n%q\ngot\n%q\n", pair.text, pair.result, r)
}
}
}
|
Add aiohttp as a execution requirement | # Copyright 2020 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='astivi@google.com',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0, aiohttp==3.6.2'],
packages=setuptools.find_packages(),
)
| # Copyright 2019 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import setuptools
setuptools.setup(
name='megalist_dataflow',
version='0.1',
author='Alvaro Stivi',
author_email='astivi@google.com',
url='https://cse.googlesource.com/solutions/megalist',
install_requires=['googleads==20.0.0', 'google-api-python-client==1.7.9',
'bloom-filter==1.3', 'google-cloud-core==1.0.2',
'google-cloud-datastore==1.9.0'],
packages=setuptools.find_packages(),
)
|
Replace player ids with player objects
This is no longer needed, since in memory storage keeps all references | package pw.scho.battleship.model;
import java.util.UUID;
public class Game {
private Board firstBoard;
private Board secondBoard;
private Player firstPlayer;
private Player secondPlayer;
private UUID id;
public Game() {
this.id = UUID.randomUUID();
}
public Player getSecondPlayer() {
return secondPlayer;
}
public void setSecondPlayer(Player secondPlayer) {
this.secondPlayer = secondPlayer;
}
public Player getFirstPlayer() {
return firstPlayer;
}
public void setFirstPlayer(Player firstPlayer) {
this.firstPlayer = firstPlayer;
}
public UUID getId() {
return id;
}
public Board getFirstBoard() {
return firstBoard;
}
public void setFirstBoard(Board firstBoard) {
this.firstBoard = firstBoard;
}
public Board getSecondBoard() {
return secondBoard;
}
public void setSecondBoard(Board secondBoard) {
this.secondBoard = secondBoard;
}
}
| package pw.scho.battleship.model;
import java.util.UUID;
public class Game {
private Board firstBoard;
private Board secondBoard;
private UUID firstPlayerId;
private UUID secondPlayerId;
private UUID id;
public Game() {
this.id = UUID.randomUUID();
}
public UUID getId() {
return id;
}
public Board getFirstBoard() {
return firstBoard;
}
public void setFirstBoard(Board firstBoard) {
this.firstBoard = firstBoard;
}
public Board getSecondBoard() {
return secondBoard;
}
public void setSecondBoard(Board secondBoard) {
this.secondBoard = secondBoard;
}
public UUID getFirstPlayerId() {
return firstPlayerId;
}
public void setFirstPlayerId(UUID firstPlayerId) {
this.firstPlayerId = firstPlayerId;
}
public UUID getSecondPlayerId() {
return secondPlayerId;
}
public void setSecondPlayerId(UUID secondPlayerId) {
this.secondPlayerId = secondPlayerId;
}
}
|
Fix Input.wasKeyPressed for the first keypress | 'use strict';
export default class Input {
constructor(element, canvas) {
this.pressedKeys = {};
this.framePressedKeys = {};
this.previousPressedKeys = {};
element.addEventListener('keydown', (e) => {
this.pressedKeys[e.keyCode] = true;
});
element.addEventListener('keyup', (e) => {
this.pressedKeys[e.keyCode] = false;
});
element.addEventListener('blur', (e) => {
this.pressedKeys = {};
});
canvas.oncontextmenu = (e) => {
e.preventDefault();
};
}
update() {
for (var key in this.framePressedKeys) {
this.previousPressedKeys[key] = this.framePressedKeys[key];
}
for (var key in this.pressedKeys) {
this.framePressedKeys[key] = this.pressedKeys[key];
}
}
wasKeyPressed(key) {
return this.framePressedKeys[key] && !this.previousPressedKeys[key];
}
wasKeyReleased(key) {
return !this.framePressedKeys[key] && this.previousPressedKeys[key];
}
isKeyDown(key) {
return this.pressedKeys[key] === true;
}
}
| 'use strict';
export default class Input {
constructor(element, canvas) {
this.pressedKeys = {};
this.framePressedKeys = {};
this.previousPressedKeys = {};
element.addEventListener('keydown', (e) => {
this.pressedKeys[e.keyCode] = true;
});
element.addEventListener('keyup', (e) => {
this.pressedKeys[e.keyCode] = false;
});
element.addEventListener('blur', (e) => {
this.pressedKeys = {};
});
canvas.oncontextmenu = (e) => {
e.preventDefault();
};
}
update() {
for (var key in this.framePressedKeys) {
this.previousPressedKeys[key] = this.framePressedKeys[key];
}
for (var key in this.pressedKeys) {
this.framePressedKeys[key] = this.pressedKeys[key];
}
}
wasKeyPressed(key) {
return this.framePressedKeys[key] === true && this.previousPressedKeys[key] === false;
}
wasKeyReleased(key) {
return this.framePressedKeys[key] === false && this.previousPressedKeys[key] === true;
}
isKeyDown(key) {
return this.pressedKeys[key] === true;
}
}
|
Define repr for Article model | from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Article(Base):
"""Model for Articles"""
__tablename__ = 'articles'
_id = Column(Integer, primary_key=True)
source = Column(String)
title = Column(String)
url = Column(String)
author = Column(String)
date_published = Column(DateTime)
def __init__(self, article):
self.source = article.source
self.title = article.title
self.url = article.url
self.author = article.author
self.date_published = article.date_published
def __repr__(self):
return ("<Article(source={0}, title={1}, url={2}, author={3}, "
"date_published={4})>".format(self.source, self.title,
self.url, self.author, self.date_published))
engine = create_engine('')
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
db_session = DBSession()
| from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Article(Base):
"""Model for Articles"""
__tablename__ = 'articles'
_id = Column(Integer, primary_key=True)
source = Column(String)
title = Column(String)
url = Column(String)
author = Column(String)
date_published = Column(DateTime)
def __init__(self, article):
self.source = article.source
self.title = article.title
self.url = article.url
self.author = article.author
self.date_published = article.date_published
def __repr__(self):
return "<Article(source={0})>"
engine = create_engine('')
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
db_session = DBSession()
|
Update license header to reference BSD. | # hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
| # hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
|
Fix default post deletion policy method | <?php namespace Riari\Forum\Policies;
use Illuminate\Support\Facades\Gate;
use Riari\Forum\Models\Post;
class PostPolicy
{
/**
* Permission: Edit post.
*
* @param object $user
* @param Post $post
* @return bool
*/
public function edit($user, Post $post)
{
return $user->getKey() === $post->author_id;
}
/**
* Permission: Delete post.
*
* @param object $user
* @param Post $post
* @return bool
*/
public function delete($user, Post $post)
{
return Gate::forUser($user)->allows('deletePosts', $post->thread) || $user->getKey() === $post->author_id;
}
}
| <?php namespace Riari\Forum\Policies;
use Illuminate\Support\Facades\Gate;
use Riari\Forum\Models\Post;
class PostPolicy
{
/**
* Permission: Edit post.
*
* @param object $user
* @param Post $post
* @return bool
*/
public function edit($user, Post $post)
{
return $user->getKey() === $post->author_id;
}
/**
* Permission: Delete post.
*
* @param object $user
* @param Post $post
* @return bool
*/
public function delete($user, Post $post)
{
return Gate::forUser($user)->allows('deletePosts', $post->thread) || $user->getKey() === $post->user_id;
}
}
|
Fix broken import in migraiton script | import { registerMigration } from './migrationUtils';
import { forEachDocumentBatchInCollection } from '../queryUtil.js';
import { LWEvents } from '../../lib/collections/lwevents'
import { ReadStatuses } from '../../lib/collections/readStatus/collection.js'
registerMigration({
name: "denormalizeReadStatus",
idempotent: true,
action: async () => {
forEachDocumentBatchInCollection({
collection: LWEvents,
batchSize: 10000,
filter: {name: "post-view"},
callback: (postViews) => {
const updates = postViews.map(view => ({
updateOne: {
filter: {
postId: view.docmentId,
userId: view.userId,
},
update: {
$max: {
lastUpdated: view.createdAt,
},
$set: {
isRead: true
},
},
upsert: true,
}
}));
ReadStatuses.rawCollection().bulkWrite(updates);
}
})
}
}); | import { registerMigration } from './migrationUtils';
import { forEachDocumentBatchInCollection } from '../queryUtil.js';
import { LWEvents } from '../../lib/collections/lwevents'
import { ReadStatuses } from '../../lib/collections/readStatus'
registerMigration({
name: "denormalizeReadStatus",
idempotent: true,
action: async () => {
forEachDocumentBatchInCollection({
collection: LWEvents,
batchSize: 10000,
filter: {name: "post-view"},
callback: (postViews) => {
const updates = postViews.map(view => ({
updateOne: {
filter: {
postId: view.docmentId,
userId: view.userId,
},
update: {
$max: {
lastUpdated: view.createdAt,
},
$set: {
isRead: true
},
},
upsert: true,
}
}));
ReadStatuses.rawCollection().bulkWrite(updates);
}
})
}
}); |
Set default logger to file | #!/usr/bin/env python
# MAKE IT UNICODE OK
import sys
reload( sys )
sys.setdefaultencoding( 'utf-8' )
import os, sys
import Bot
import logging
if __name__ == '__main__':
logging.basicConfig( filename = 'ircbot.log', level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
logging.info( "Welcome to botje" )
fork = True
if len( sys.argv ) > 1:
if sys.argv[1] == '-nofork':
fork = False
if fork:
try:
pid = os.fork()
if pid > 0:
logging.info( 'Forked into PID {0}'.format( pid ) )
sys.exit(0)
sys.stdout = open( '/tmp/ircbot.log', 'w' )
except OSError as error:
logging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )
sys.exit(1)
botje = Bot.Bot()
while True:
try:
botje.start()
except Bot.BotReloadException:
logging.info( 'Force reloading Bot class' )
botje = None
reload(Bot)
botje = Bot.Bot()
logging.info( 'Botje died, restarting in 5...' )
import time
time.sleep( 5 )
| #!/usr/bin/env python
# MAKE IT UNICODE OK
import sys
reload( sys )
sys.setdefaultencoding( 'utf-8' )
import os, sys
import Bot
import logging
if __name__ == '__main__':
logging.basicConfig( level = logging.DEBUG, format = '[%(asctime)s] %(levelname)s: %(message)s' )
logging.getLogger().addHandler( logging.FileHandler( 'ircbot.log' ) )
logging.info( "Welcome to botje" )
fork = True
if len( sys.argv ) > 1:
if sys.argv[1] == '-nofork':
fork = False
if fork:
try:
pid = os.fork()
if pid > 0:
logging.info( 'Forked into PID {0}'.format( pid ) )
sys.exit(0)
sys.stdout = open( '/tmp/ircbot.log', 'w' )
except OSError as error:
logging.error( 'Unable to fork. Error: {0} ({1})'.format( error.errno, error.strerror ) )
sys.exit(1)
botje = Bot.Bot()
while True:
try:
botje.start()
except Bot.BotReloadException:
logging.info( 'Force reloading Bot class' )
botje = None
reload(Bot)
botje = Bot.Bot()
logging.info( 'Botje died, restarting in 5...' )
import time
time.sleep( 5 )
|
Update <input> size on load | /*globals Panel*/
'use strict'
/**
* Handle our custom text input implementation
* The main reason we need this is to allow the user copy the resulting
* query as text
* @param {HTMLElement} el
* @class
*/
function Input(el) {
var that = this
/** @member {HTMLElement} */
this.el = Panel.get(el)
/** @member {?function()} */
this.oninput = null
/**
* @member {string} value
*/
Object.defineProperty(this, 'value', {
get: function () {
return this._inputEl.value
},
set: function (newValue) {
this._inputEl.value = newValue
this._inputEl.style.width = (this._inputEl.value.length + 1) + 'ch'
}
})
/**
* @member {HTMLElement}
* @private
*/
this._inputEl = document.createElement('input')
// Build internal HTML
this.el.classList.add('custom-input')
this.el.appendChild(this._inputEl)
this._inputEl.oninput = function () {
that._inputEl.style.width = (that._inputEl.value.length + 1) + 'ch'
if (that.oninput) {
that.oninput.call(that)
}
}
} | /*globals Panel*/
'use strict'
/**
* Handle our custom text input implementation
* The main reason we need this is to allow the user copy the resulting
* query as text
* @param {HTMLElement} el
* @class
*/
function Input(el) {
var that = this
/** @member {HTMLElement} */
this.el = Panel.get(el)
/** @member {?function()} */
this.oninput = null
/**
* @member {string} value
*/
Object.defineProperty(this, 'value', {
get: function () {
return this._inputEl.value
},
set: function (newValue) {
this._inputEl.value = newValue
}
})
/**
* @member {HTMLElement}
* @private
*/
this._inputEl = document.createElement('input')
// Build internal HTML
this.el.classList.add('custom-input')
this.el.appendChild(this._inputEl)
this._inputEl.oninput = function () {
that._inputEl.style.width = (that._inputEl.value.length + 1) + 'ch'
if (that.oninput) {
that.oninput.call(that)
}
}
} |
Remove unused fields from server transport | package thrift_nats
import (
"errors"
"time"
"git.apache.org/thrift.git/lib/go/thrift"
"github.com/nats-io/nats"
)
type natsServerTransport struct {
conn *nats.Conn
listening bool
}
func newNATSServerTransport(conn *nats.Conn) *natsServerTransport {
return &natsServerTransport{conn: conn}
}
func (n *natsServerTransport) Listen() error {
n.listening = true
return nil
}
func (n *natsServerTransport) Accept() (thrift.TTransport, error) {
return nil, errors.New("Use AcceptNATS")
}
func (n *natsServerTransport) AcceptNATS(listenTo, replyTo string,
timeout time.Duration) thrift.TTransport {
return NewNATSTransport(n.conn, listenTo, replyTo, timeout)
}
func (n *natsServerTransport) IsListening() bool {
return n.listening
}
func (n *natsServerTransport) Close() error {
n.listening = false
return nil
}
func (n *natsServerTransport) Interrupt() error {
return nil
}
| package thrift_nats
import (
"errors"
"time"
"git.apache.org/thrift.git/lib/go/thrift"
"github.com/nats-io/nats"
)
type natsServerTransport struct {
conn *nats.Conn
accepted chan struct{}
transport thrift.TTransport
listening bool
}
func newNATSServerTransport(conn *nats.Conn) *natsServerTransport {
return &natsServerTransport{conn: conn}
}
func (n *natsServerTransport) Listen() error {
n.listening = true
return nil
}
func (n *natsServerTransport) Accept() (thrift.TTransport, error) {
return nil, errors.New("Use AcceptNATS")
}
func (n *natsServerTransport) AcceptNATS(listenTo, replyTo string,
timeout time.Duration) thrift.TTransport {
return NewNATSTransport(n.conn, listenTo, replyTo, timeout)
}
func (n *natsServerTransport) IsListening() bool {
return n.listening
}
func (n *natsServerTransport) Close() error {
return nil
}
func (n *natsServerTransport) Interrupt() error {
return nil
}
|
Add wrapper to svg for proper alignment | import classNames from 'classnames';
import React from 'react';
import Icon from './Icon';
const Alert = ({children, flushBottom, showIcon, type}) => {
const classes = classNames('alert', {
[`alert-${type}`]: type != null,
'flush-bottom': flushBottom === true
});
let icon = null;
if (showIcon) {
const ids = {
danger: 'yield',
success: 'checkmark'
};
icon = (
<div className="alert-icon">
<Icon id={ids[type]} size="mini" />
</div>
);
}
return (
<div className={classes}>
{icon}
<div className="alert-content">
{children}
</div>
</div>
);
};
Alert.defaultProps = {
flushBottom: false,
showIcon: true,
type: 'danger'
};
Alert.propTypes = {
children: React.PropTypes.node.isRequired,
flushBottom: React.PropTypes.bool,
showIcon: React.PropTypes.bool,
type: React.PropTypes.oneOf(['danger', 'success'])
};
module.exports = Alert;
| import classNames from 'classnames';
import React from 'react';
import Icon from './Icon';
const Alert = ({children, flushBottom, showIcon, type}) => {
const classes = classNames('alert', {
[`alert-${type}`]: type != null,
'flush-bottom': flushBottom === true
});
let icon = null;
if (showIcon) {
const ids = {
danger: 'yield',
success: 'checkmark'
};
icon = (
<Icon className="alert-icon" id={ids[type]} size="mini" />
);
}
return (
<div className={classes}>
{icon}
<div className="alert-content">
{children}
</div>
</div>
);
};
Alert.defaultProps = {
flushBottom: false,
showIcon: true,
type: 'danger'
};
Alert.propTypes = {
children: React.PropTypes.node.isRequired,
flushBottom: React.PropTypes.bool,
showIcon: React.PropTypes.bool,
type: React.PropTypes.oneOf(['danger', 'success'])
};
module.exports = Alert;
|
FIX: Remove unused parameters in test script | from pytfa.redgem.redgem import RedGEM
from pytfa.io import import_matlab_model
from pytfa.io.base import load_thermoDB
from pytfa.thermo.tmodel import ThermoModel
from pytfa.io import read_compartment_data, apply_compartment_data, read_lexicon, annotate_from_lexicon
path_to_model = 'models/small_ecoli.mat'
thermoDB = "data/thermo_data.thermodb"
path_to_lexicon = 'models/iJO1366/lexicon.csv'
path_to_compartment_data = 'models/iJO1366/compartment_data.json'
model = import_matlab_model(path_to_model)
thermo_data = load_thermoDB(thermoDB)
lexicon = read_lexicon(path_to_lexicon)
compartment_data = read_compartment_data(path_to_compartment_data)
tfa_model = ThermoModel(thermo_data, model)
annotate_from_lexicon(tfa_model, lexicon)
apply_compartment_data(tfa_model, compartment_data)
tfa_model.name = 'Lumped Model'
path_to_params = 'tests/redgem_params.yml'
redgem = RedGEM(tfa_model, path_to_params, False)
redgem.run()
| from pytfa.redgem.redgem import RedGEM
from pytfa.io import import_matlab_model
from pytfa.io.base import load_thermoDB
from pytfa.thermo.tmodel import ThermoModel
from pytfa.io import read_compartment_data, apply_compartment_data, read_lexicon, annotate_from_lexicon
path_to_model = 'models/small_ecoli.mat'
thermoDB = "data/thermo_data.thermodb"
carbon_uptake = 60000
growth = 0.5
model = import_matlab_model(path_to_model)
thermo_data = load_thermoDB(thermoDB)
lexicon = read_lexicon('models/iJO1366/lexicon.csv')
compartment_data = read_compartment_data('models/iJO1366/compartment_data.json')
tfa_model = ThermoModel(thermo_data, model)
annotate_from_lexicon(tfa_model, lexicon)
apply_compartment_data(tfa_model, compartment_data)
tfa_model.name = 'Lumped Model'
path_to_params = 'tests/redgem_params.yml'
redgem = RedGEM(tfa_model, path_to_params, False)
redgem.run()
|
Add validation for the key submitted in the POST body. | import {encrypt} from '../../kms';
export default async (req, res, next) => {
const plaintext = req.body.secret;
let keyObj;
try {
keyObj = JSON.parse(req.body.key);
} catch (err) {
console.log(err);
keyObj = null;
}
if (!keyObj) {
return next(new Error('CMK not defined'));
}
if (!keyObj.hasOwnProperty('region') || !keyObj.hasOwnProperty('key')) {
return next(new Error('Invalid key format'));
}
if (!plaintext) {
return next(new Error('Plaintext not entered'));
}
const region = keyObj.region;
const key = keyObj.key;
const params = {
KeyId: key,
Plaintext: plaintext,
region
};
let data;
try {
data = await encrypt(params);
} catch (err) {
return next(err);
}
const resp = {
region: data.region
};
if (data instanceof Error) {
resp.status = 'ERROR';
resp.text = data.message;
} else {
resp.status = 'SUCCESS';
resp.text = `$tokend:
type: kms
resource: /v1/kms/decrypt
region: ${data.region}
ciphertext: "${data.ciphertext}"
datakey: "${data.datakey}"`;
}
return res.json(resp);
};
| import {encrypt} from '../../kms';
export default async (req, res, next) => {
const plaintext = req.body.secret;
let keyObj;
try {
keyObj = JSON.parse(req.body.key);
} catch (err) {
console.log(err);
keyObj = null;
}
if (!keyObj) {
return next(new Error('CMK not defined'));
}
if (!plaintext) {
return next(new Error('Plaintext not entered'));
}
const region = keyObj.region;
const key = keyObj.key;
const params = {
KeyId: key,
Plaintext: plaintext,
region
};
let data;
try {
data = await encrypt(params);
} catch (err) {
return next(err);
}
const resp = {
region: data.region
};
if (data instanceof Error) {
resp.status = 'ERROR';
resp.text = data.message;
} else {
resp.status = 'SUCCESS';
resp.text = `$tokend:
type: kms
resource: /v1/kms/decrypt
region: ${data.region}
ciphertext: "${data.ciphertext}"
datakey: "${data.datakey}"`;
}
return res.json(resp);
};
|
Add API for preventing close on click behavoir on map. | define( ['backbone', 'backbone.marionette', 'communicator', 'velocity',
'views/layout/app.layout', 'views/layout/flyouts.layout'],
function( Backbone, Marionette, Communicator, V,
AppLayout, FlyoutsLayout ) {
'use strict';
var App = new Marionette.Application(),
container = new Marionette.Region( {
el: "#erfgeoviewer"
}),
closeOnClick = true;
App.layout = new AppLayout();
App.layout.render();
container.show( App.layout );
App.flyouts = new FlyoutsLayout();
App.flyouts.render();
App.layout.getRegion('flyout').show( App.flyouts );
Communicator.mediator.on('map:setCloseOnClick', function(value) {
closeOnClick = value;
});
Communicator.mediator.on("map:tile-layer-clicked", function() {
if (!closeOnClick) {
return;
}
if (!App.flyouts.getRegion('detail').hasView() || !App.flyouts.getRegion('detail').isVisible() ) {
App.flyouts.getRegion('right').hideFlyout();
}
App.flyouts.getRegion('bottom').hideFlyout();
App.flyouts.getRegion('detail').hideFlyout();
});
App.on( "start", function() {
Backbone.history.start();
} );
return App;
} );
| define( ['backbone', 'backbone.marionette', 'communicator', 'velocity',
'views/layout/app.layout', 'views/layout/flyouts.layout'],
function( Backbone, Marionette, Communicator, V,
AppLayout, FlyoutsLayout ) {
'use strict';
var App = new Marionette.Application();
var container = new Marionette.Region( {
el: "#erfgeoviewer"
} );
App.layout = new AppLayout();
App.layout.render();
container.show( App.layout );
App.flyouts = new FlyoutsLayout();
App.flyouts.render();
App.layout.getRegion('flyout').show( App.flyouts );
Communicator.mediator.on("map:tile-layer-clicked", function() {
if (!App.flyouts.getRegion('detail').hasView() || !App.flyouts.getRegion('detail').isVisible() ) {
App.flyouts.getRegion('right').hideFlyout();
}
App.flyouts.getRegion('bottom').hideFlyout();
App.flyouts.getRegion('detail').hideFlyout();
});
App.on( "start", function() {
Backbone.history.start();
} );
return App;
} );
|
Add /q- as an alias for /q remove | var name = ['/q- ', '/q remove '];
var description = 'Removes a song from your playlist.';
var usage = '`/q remove [queue location]`:\n`/q- [queue location]:`';
var messageHandler = require(global.paths.lib + 'message-handler');
var queueHandler = require(global.paths.lib + 'queue-handler');
var tt = require(global.paths.lib + 'turntable-handler');
var google = require('googleapis');
var youtube = google.youtube('v3');
var Discord = require('discord.js');
var uuid = require('uuid/v4');
var handleMessage = function(bot, message) {
var positionString = message.content.substring(message.content.startsWith('/q-') ? 4 : 10, message.content.length);
if (positionString == '') {
return message.reply('please provide a position.');
}
queueHandler.removeSong(bot, message, parseInt(positionString));
};
var matches = function(input) {
return _.startsWith(input, '/q remove') || _.startsWith(input, '/q-');
};
module.exports = {
name: name,
description: description,
usage: usage,
handleMessage: handleMessage,
matches: matches
};
| var name = ['/q remove '];
var description = 'Removes a song from your playlist.';
var usage = '`/q remove [song name or YouTube ID]`:';
var messageHandler = require(global.paths.lib + 'message-handler');
var queueHandler = require(global.paths.lib + 'queue-handler');
var tt = require(global.paths.lib + 'turntable-handler');
var google = require('googleapis');
var youtube = google.youtube('v3');
var Discord = require('discord.js');
var uuid = require('uuid/v4');
var handleMessage = function(bot, message) {
// TODO: This will need to occur in a lib handler
// TODO: This loop will act as the bot's main event loop when a DJ session is active
// TODO: Optimize for bandwidth constraints (e.g. cache downloaded songs)
if (message.content.length < 10) {
return message.reply('please provide a position.');
}
var queuePosition = parseInt(message.content.substring(10, message.content.length));
queueHandler.removeSong(bot, message, queuePosition);
};
var matches = function(input) {
return _.startsWith(input, '/q remove ') || input == '/q remove';
};
module.exports = {
name: name,
description: description,
usage: usage,
handleMessage: handleMessage,
matches: matches
};
|
Add listener for referential when creating a user | import * as Constants from '../constants/ActionTypes'
import Immutable from 'seamless-immutable'
const referential = (state = Immutable({}), action) => {
switch (action.type) {
case Constants.DATA_FETCH_SUBMITTED: {
return state.set('loading', true)
}
case Constants.DATA_FETCH_ERROR: {
return state.set('loading', false)
}
case Constants.APPLICATION_FETCH_AUDIENCES_SUCCESS:
case Constants.APPLICATION_FETCH_USERS_SUCCESS:
case Constants.APPLICATION_FETCH_ORGANIZATIONS_SUCCESS:
case Constants.APPLICATION_ADD_AUDIENCE_SUCCESS:
case Constants.APPLICATION_ADD_USER_SUCCESS:
case Constants.APPLICATION_UPDATE_AUDIENCE_SUCCESS:
case Constants.DATA_FETCH_SUCCESS: {
console.log("DATA_FETCH_SUCCESS", action.payload)
let payload = Immutable(action.payload.toJS())
return state.set('loading', false).merge(payload.without('result'), {deep: true})
}
case Constants.APPLICATION_DELETE_AUDIENCE_SUCCESS:
case Constants.DATA_DELETE_SUCCESS: {
let payload = Immutable(action.payload.toJS())
return state.setIn(['entities', payload.type], state.entities[payload.type].without(payload.id))
}
default: {
return state;
}
}
}
export default referential; | import * as Constants from '../constants/ActionTypes'
import Immutable from 'seamless-immutable'
const referential = (state = Immutable({}), action) => {
switch (action.type) {
case Constants.DATA_FETCH_SUBMITTED: {
return state.set('loading', true)
}
case Constants.DATA_FETCH_ERROR: {
return state.set('loading', false)
}
case Constants.APPLICATION_FETCH_AUDIENCES_SUCCESS:
case Constants.APPLICATION_UPDATE_AUDIENCE_SUCCESS:
case Constants.APPLICATION_ADD_AUDIENCE_SUCCESS:
case Constants.APPLICATION_FETCH_USERS_SUCCESS:
case Constants.APPLICATION_FETCH_ORGANIZATIONS_SUCCESS:
case Constants.DATA_FETCH_SUCCESS: {
console.log("DATA_FETCH_SUCCESS", action.payload)
let payload = Immutable(action.payload.toJS())
return state.set('loading', false).merge(payload.without('result'), {deep: true})
}
case Constants.APPLICATION_DELETE_AUDIENCE_SUCCESS:
case Constants.DATA_DELETE_SUCCESS: {
let payload = Immutable(action.payload.toJS())
return state.setIn(['entities', payload.type], state.entities[payload.type].without(payload.id))
}
default: {
return state;
}
}
}
export default referential; |
Remove 'is_live' from draft visibility check. | OWNER_PERMISSIONS = ['challenges.%s_submission' % v for v in ['edit', 'delete']]
class SubmissionBackend(object):
"""Provide custom permission logic for submissions."""
supports_object_permissions = True
supports_anonymous_user = True
def authenticate(self):
"""This backend doesn't provide any authentication functionality."""
return None
def has_perm(self, user_obj, perm, obj=None):
if perm in OWNER_PERMISSIONS:
# Owners can edit and delete their own submissions
if obj is not None and user_obj == obj.created_by.user:
return True
if perm == 'challenges.view_submission' and obj is not None:
# Live, non-draft submissions are visible to anyone. Other
# submissions are visible only to admins and their owners
return ((not obj.is_draft) or user_obj == obj.created_by.user)
return False
| OWNER_PERMISSIONS = ['challenges.%s_submission' % v for v in ['edit', 'delete']]
class SubmissionBackend(object):
"""Provide custom permission logic for submissions."""
supports_object_permissions = True
supports_anonymous_user = True
def authenticate(self):
"""This backend doesn't provide any authentication functionality."""
return None
def has_perm(self, user_obj, perm, obj=None):
if perm in OWNER_PERMISSIONS:
# Owners can edit and delete their own submissions
if obj is not None and user_obj == obj.created_by.user:
return True
if perm == 'challenges.view_submission' and obj is not None:
# Live, non-draft submissions are visible to anyone. Other
# submissions are visible only to admins and their owners
return ((obj.is_live and not obj.is_draft) or
user_obj == obj.created_by.user)
return False
|
Fix return type and add decimal points | 'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
// MAIN //
/**
* Evaluates the natural logarithm of the cumulative distribution function (logCDF) for a degenerate distribution with mean `mu`.
*
* @param {number} x - input value
* @param {number} mu - constant value of distribution
* @returns {number} natural logarithm of cumulative distribution function
*
* @example
* var y = logcdf( 2.0, 3.0 );
* // returns Number.NEGATIVE_INFINITY
* @example
* var y = logcdf( 4.0, 3.0 );
* // returns 0.0
* @example
* var y = logcdf( 3.0, 3.0 );
* // returns 0.0
* @example
* var y = logcdf( NaN, 0.0 );
* // returns NaN
* @example
* var y = logcdf( 0.0, NaN );
* // returns NaN
*/
function logcdf( x, mu ) {
if ( isnan( x ) || isnan( mu ) ) {
return NaN;
}
return ( x < mu ) ? NINF : 0.0;
} // end FUNCTION logcdf()
// EXPORTS //
module.exports = logcdf;
| 'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
// MAIN //
/**
* Evaluates the logarithm of the cumulative distribution function (CDF) for a degenerate distribution with a point mass at `mu`.
*
* @param {number} x - input value
* @param {number} mu - constant value of distribution
* @returns {Probability} evaluated logarithm of cumulative distribution function
*
* @example
* var y = logcdf( 2.0, 3.0 );
* // returns Number.NEGATIVE_INFINITY
* @example
* var y = logcdf( 4.0, 3.0 );
* // returns 0
* @example
* var y = logcdf( 3.0, 3.0 );
* // returns 0
* @example
* var y = logcdf( NaN, 0.0 );
* // returns NaN
* @example
* var y = logcdf( 0.0, NaN );
* // returns NaN
*/
function logcdf( x, mu ) {
if ( isnan( x ) || isnan( mu ) ) {
return NaN;
}
return x < mu ? NINF : 0.0;
} // end FUNCTION logcdf()
// EXPORTS //
module.exports = logcdf;
|
Add request duration in milliseconds | 'use strict';
const Profiler = require('../../stats/profiler-proxy');
const { name: prefix } = require('../../../package.json');
module.exports = function profiler ({ statsClient, logOnEvent = 'finish' }) {
return function profilerMiddleware (req, res, next) {
const start = new Date();
const { logger } = res.locals;
req.profiler = new Profiler({
profile: global.settings.useProfiler,
statsd_client: statsClient
});
req.profiler.start(prefix);
res.on(logOnEvent, () => {
req.profiler.add({ response: new Date() - start });
req.profiler.end();
const stats = req.profiler.toJSON();
logger.info({ stats, duration: stats.response / 1000, duration_ms: stats.response }, 'Request profiling stats');
try {
req.profiler.sendStats();
} catch (err) {
logger.warn({ exception: err }, 'Could not send stats to StatsD');
}
});
next();
};
};
| 'use strict';
const Profiler = require('../../stats/profiler-proxy');
const { name: prefix } = require('../../../package.json');
module.exports = function profiler ({ statsClient, logOnEvent = 'finish' }) {
return function profilerMiddleware (req, res, next) {
const start = new Date();
const { logger } = res.locals;
req.profiler = new Profiler({
profile: global.settings.useProfiler,
statsd_client: statsClient
});
req.profiler.start(prefix);
res.on(logOnEvent, () => {
req.profiler.add({ response: new Date() - start });
req.profiler.end();
const stats = req.profiler.toJSON();
logger.info({ stats, duration: stats.response / 1000 }, 'Request profiling stats');
try {
req.profiler.sendStats();
} catch (err) {
logger.warn({ exception: err }, 'Could not send stats to StatsD');
}
});
next();
};
};
|
Make md.render have the same API as rst.render | # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
if rendered:
return clean(rendered)
else:
return None
| # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
return clean(rendered or raw), bool(rendered)
|
Change double quotes to single quotes. | module.exports = function(config) {
config.set({
basePath: '../',
files: [
'https://maps.googleapis.com/maps/api/js?sensor=false',
'test/lib/angular/angular.js',
'test/lib/angular/angular-mocks.js',
'src/module.js',
'src/directives/*.js',
'src/services/*.js',
'src/controllers/*.js',
'test/unit/**/*.js'
],
frameworks: ['jasmine'],
autoWatch: true,
singleRun: false,
browsers: ['PhantomJS'],
reportSlowerThan: 500,
preprocessors: {
'src/**/*.js': 'coverage'
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type : 'html',
dir : 'test/coverage/'
}
});
};
| module.exports = function(config) {
config.set({
basePath: '../',
files: [
'https://maps.googleapis.com/maps/api/js?sensor=false',
'test/lib/angular/angular.js',
'test/lib/angular/angular-mocks.js',
'src/module.js',
'src/directives/*.js',
'src/services/*.js',
'src/controllers/*.js',
'test/unit/**/*.js'
],
frameworks: ["jasmine"],
autoWatch: true,
singleRun: false,
browsers: ['PhantomJS'],
reportSlowerThan: 500,
preprocessors: {
'src/**/*.js': 'coverage'
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type : 'html',
dir : 'test/coverage/'
}
});
};
|
Switch out map in code | var battleState = {
map: null,
battle: null,
create: function() {
//TODO: anything needed on battle start add here
// tilemap(key, tileWidth, tileHeight, width, height) → {Phaser.Tilemap}
// FOR TESTING PURPOSES
var tilemap = game.add.tilemap("testmap", 32, 32, 8, 12);
tilemap.addTilesetImage("tileset", "tilesheet");
tilemap.createLayer("Tile Layer 1");
map = new Map();
var army = [new Grenadier(new Pos(2, 2)),
new Warrior(new Pos(1, 3)),
new Mech(new Pos(1, 2)),
new MotorBike(new Pos(0, 8)),
new IronGuard(new Pos(3, 3)),
new Cannon(new Pos(3, 2)),
new Mortar(new Pos(1, 1)),
new Biplane(new Pos(10, 1))];
battle = new Battle(map,[new Player(new ArmyDwarf(army)), new Player(new ArmyDwarf([]))]);
},
update: function() {
//TODO: Anything dealing with the battle here
battle.update();
},
render: function() {
// battle.showSelectedMoves().forEach(function(tileRect) {
// game.debug.geom(tileRect,'rgba(0,0,255,0.5');
// });
}
}
| var battleState = {
map: null,
battle: null,
create: function() {
//TODO: anything needed on battle start add here
// tilemap(key, tileWidth, tileHeight, width, height) → {Phaser.Tilemap}
// FOR TESTING PURPOSES
var tilemap = game.add.tilemap("testmap", 32, 32, 12, 12);
tilemap.addTilesetImage("tileset", "tilesheet");
tilemap.createLayer("Tile Layer 1");
map = new Map();
var army = [new Grenadier(new Pos(2, 2)),
new Warrior(new Pos(1, 3)),
new Mech(new Pos(1, 2)),
new MotorBike(new Pos(0, 8)),
new IronGuard(new Pos(3, 3)),
new Cannon(new Pos(3, 2)),
new Mortar(new Pos(1, 1)),
new Biplane(new Pos(10, 1))];
battle = new Battle(map,[new Player(new ArmyDwarf(army)), new Player(new ArmyDwarf([]))]);
},
update: function() {
//TODO: Anything dealing with the battle here
battle.update();
},
render: function() {
// battle.showSelectedMoves().forEach(function(tileRect) {
// game.debug.geom(tileRect,'rgba(0,0,255,0.5');
// });
}
}
|
refactor(addresses): Rename Address migration class name
Rename Address migration class name
see #53 | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAddressesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('city_id');
$table->unsignedInteger('country_id');
$table->unsignedInteger('district_id');
$table->string('street');
$table->string('zip_code');
$table->string('phone_number');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('addresses');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Addresses extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('city_id');
$table->unsignedInteger('country_id');
$table->unsignedInteger('district_id');
$table->string('street');
$table->string('zip_code');
$table->string('phone_number');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('addresses');
}
}
|
Clean up login and signup screens to prep for functionality infusion. | package com.passel;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class LogInActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_log_in, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (R.id.action_settings == item.getItemId()) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| package com.passel;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.passel.R;
public class LogInActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_log_in, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Read the https env var as well | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
if (!isset($env) || $env !== 'dev') {
// force ssl
$app->before(function (Request $request) {
// skip SSL & non-GET/HEAD requests
if (strtolower($request->server->get('HTTPS')) == 'on' || strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
return;
}
return new RedirectResponse('https://'.substr($request->getUri(), 7));
});
$app->after(function (Request $request, Response $response) {
if (!$response->headers->has('Strict-Transport-Security')) {
$response->headers->set('Strict-Transport-Security', 'max-age=31104000');
}
});
}
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
if (!isset($env) || $env !== 'dev') {
// force ssl
$app->before(function (Request $request) {
// skip SSL & non-GET/HEAD requests
if (strtolower($request->headers->get('X_FORWARDED_PROTO')) == 'https' || !$request->isMethodSafe()) {
return;
}
return new RedirectResponse('https://'.substr($request->getUri(), 7));
});
$app->after(function (Request $request, Response $response) {
if (!$response->headers->has('Strict-Transport-Security')) {
$response->headers->set('Strict-Transport-Security', 'max-age=31104000');
}
});
}
|
Update chrome clean pipelines plugin to work with concourse 5
This commit updates the divs that we wish to remove from the pipeline view. | // ==UserScript==
// @name Remove concourse elements
// @namespace cloudpipeline.digital
// @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens.
// @include https://deployer.*.cloudpipeline.digital/*
// @include https://deployer.cloud.service.gov.uk/*
// @include https://deployer.london.cloud.service.gov.uk/*
// @version 1
// @grant none
// ==/UserScript==
const readyStateCheckInterval = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(readyStateCheckInterval);
console.log('Monitor mode is go');
const $legend = document.querySelector('#legend');
$legend.style.display = 'none';
const $infoBox = document.querySelector('.lower-right-info');
$infoBox.style.display = 'none';
const $topBar = document.querySelector('#top-bar-app');
$topBar.style.display = 'none';
const $groupsBar = document.querySelector('#groups-bar');
$groupsBar.style.display = 'none';
const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', '');
document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`);
}
}, 2000);
| // ==UserScript==
// @name Remove concourse elements
// @namespace cloudpipeline.digital
// @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens.
// @include https://deployer.*.cloudpipeline.digital/*
// @include https://deployer.cloud.service.gov.uk/*
// @include https://deployer.london.cloud.service.gov.uk/*
// @version 1
// @grant none
// ==/UserScript==
const readyStateCheckInterval = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(readyStateCheckInterval);
console.log('Monitor mode is go');
const $legend = document.querySelector('.legend');
$legend.style.display = 'none';
const $infoBox = document.querySelector('.lower-right-info');
$infoBox.style.display = 'none';
const $topBar = document.querySelector('#top-bar-app');
$topBar.style.display = 'none';
const $groupsBar = document.querySelector('.groups-bar');
$groupsBar.style.display = 'none';
const $bottom = document.querySelector('.bottom');
// Remove the padding because the top bar isn't there any more.
$bottom.style.paddingTop = '0';
const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', '');
document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`);
}
}, 2000);
|
Define and initialize variables at top of func body | /**
* Insert elements into sorted array using binary search to indentify correct index
* @module lib/index
*/
module.exports = binarySearchInsert
/**
* @param {Array} sortedArray
* @param {*} item
* @param {Function} comparator
* @return Number
*/
function binarySearchInsert (sortedArray, item, comparator) {
var high = sortedArray.length - 1;
var lastIndex = high;
var low = 0;
var mid;
if (high === -1) {
sortedArray.push(item);
return 0;
}
while (low <= high) {
// https://github.com/darkskyapp/binary-search
// http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
mid = low + (high - low >> 1);
let cmp = comparator(sortedArray[mid], item);
if (cmp <= 0.0) {
// searching too low
low = mid + 1;
} else {
// searching too high
high = mid - 1;
}
}
if (mid === lastIndex) {
let cmp = comparator(sortedArray[mid], item);
if (cmp <= 0.0) {
mid++;
}
}
sortedArray.splice(mid, 0, item)
return mid;
}
| /**
* Insert elements into sorted array using binary search to indentify correct index
* @module lib/index
*/
module.exports = binarySearchInsert
/**
* @param {Array} sortedArray
* @param {*} item
* @param {Function} comparator
* @return Number
*/
function binarySearchInsert (sortedArray, item, comparator) {
var low = 0;
var high = sortedArray.length - 1;
var lastIndex = high;
if (high === -1) {
sortedArray.push(item);
return 0;
}
var mid;
while (low <= high) {
// https://github.com/darkskyapp/binary-search
// http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
mid = low + (high - low >> 1);
let cmp = comparator(sortedArray[mid], item);
if (cmp <= 0.0) {
// searching too low
low = mid + 1;
} else {
// searching too high
high = mid - 1;
}
}
if (mid === lastIndex) {
let cmp = comparator(sortedArray[mid], item);
if (cmp <= 0.0) {
mid++;
}
}
sortedArray.splice(mid, 0, item)
return mid;
}
|
Fix nunjucks command so travis is happy | import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
try:
os.makedirs(path('static/js/templates'))
except OSError:
pass
try:
os.makedirs(path('static/tpl'))
except OSError:
pass
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
| import os
import subprocess
from django.conf import settings
from django.core.management.base import BaseCommand
ROOT = os.path.realpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
path = lambda *a: os.path.join(ROOT, *a)
class Command(BaseCommand):
help = 'Precompiles nunjuck templates'
def handle(self, *args, **kwargs):
files = os.listdir(path('static/tpl'))
for f in files:
if f.endswith('.html'):
tpl = f[:-5]
cmd = '%s %s > %s' % (
settings.NUNJUCKS_PRECOMPILE_BIN,
path('static/tpl'),
path('static/js/templates/%s.js' % tpl))
subprocess.call(cmd, shell=True)
|
Add session ack mode property to info. | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.amqpjms.jms.meta;
public final class JmsSessionInfo implements JmsResource {
private final JmsSessionId sessionId;
private int acknowledgementMode;
public JmsSessionInfo(JmsConnectionInfo connectionMeta, long sessionId) {
this.sessionId = new JmsSessionId(connectionMeta.getConnectionId(), sessionId);
}
public JmsSessionInfo(JmsSessionId sessionId) {
this.sessionId = sessionId;
}
public JmsSessionId getSessionId() {
return sessionId;
}
@Override
public void visit(JmsResourceVistor vistor) throws Exception {
vistor.processSessionInfo(this);
}
public int getAcknowledgementMode() {
return acknowledgementMode;
}
public void setAcknowledgementMode(int acknowledgementMode) {
this.acknowledgementMode = acknowledgementMode;
}
}
| /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.amqpjms.jms.meta;
public final class JmsSessionInfo implements JmsResource {
protected final JmsSessionId sessionId;
public JmsSessionInfo(JmsConnectionInfo connectionMeta, long sessionId) {
this.sessionId = new JmsSessionId(connectionMeta.getConnectionId(), sessionId);
}
public JmsSessionInfo(JmsSessionId sessionId) {
this.sessionId = sessionId;
}
public JmsSessionId getSessionId() {
return sessionId;
}
@Override
public void visit(JmsResourceVistor vistor) throws Exception {
vistor.processSessionInfo(this);
}
}
|
Check for `randomBytes` before trying to use Node.js crypto
Browserify's `require()` will return an empty Object here, which evaluates to
`true`, so check for the function we need before trying to use it. | var window = require('global/window');
var nodeCrypto = require('crypto');
function getRandomValues(buf) {
if (window.crypto && window.crypto.getRandomValues) {
window.crypto.getRandomValues(buf);
}
else if (typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
window.msCrypto.getRandomValues(buf);
}
else if (nodeCrypto.randomBytes) {
if (buf.length > 65536) {
var e = new Error();
e.code = 22;
e.message = 'Failed to execute \'getRandomValues\' on \'Crypto\': The ' +
'ArrayBufferView\'s byte length (' + buf.length + ') exceeds the ' +
'number of bytes of entropy available via this API (65536).';
e.name = 'QuotaExceededError';
throw e;
}
var bytes = nodeCrypto.randomBytes(buf.length);
buf.set(bytes);
}
else {
throw new Error('No secure random number generator available.');
}
};
module.exports = getRandomValues; | var window = require('global/window');
var nodeCrypto = require('crypto');
function getRandomValues(buf) {
if (window.crypto && window.crypto.getRandomValues) {
window.crypto.getRandomValues(buf);
}
else if (typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
window.msCrypto.getRandomValues(buf);
}
else if (nodeCrypto) {
if (buf.length > 65536) {
var e = new Error();
e.code = 22;
e.message = 'Failed to execute \'getRandomValues\' on \'Crypto\': The ' +
'ArrayBufferView\'s byte length (' + buf.length + ') exceeds the ' +
'number of bytes of entropy available via this API (65536).';
e.name = 'QuotaExceededError';
throw e;
}
var bytes = nodeCrypto.randomBytes(buf.length);
buf.set(bytes);
}
else {
throw new Error('No secure random number generator available.');
}
};
module.exports = getRandomValues; |
Add php-cs-fixer config for test annotations | <?php
$rules = [
'@Symfony' => true,
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
'phpdoc_to_comment' => false,
'phpdoc_align' => false,
'php_unit_method_casing' => false,
'phpdoc_separation' => ['groups' => [['test', 'dataProvider', 'covers']]],
];
$finder = PhpCsFixer\Finder::create()
->in([
__DIR__.'/src',
__DIR__.'/tests',
])
->notPath('FormattingTestClass.php')
->notPath('function_names.php')
;
$config = new PhpCsFixer\Config();
$config
->setFinder($finder)
->setRiskyAllowed(true)
->setRules($rules)
->setUsingCache(true)
;
return $config;
| <?php
$rules = [
'@Symfony' => true,
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
'phpdoc_to_comment' => false,
'phpdoc_align' => false,
'php_unit_method_casing' => false,
];
$finder = PhpCsFixer\Finder::create()
->in([
__DIR__.'/src',
__DIR__.'/tests',
])
->notPath('FormattingTestClass.php')
->notPath('function_names.php')
;
$config = new PhpCsFixer\Config();
$config
->setFinder($finder)
->setRiskyAllowed(true)
->setRules($rules)
->setUsingCache(true)
;
return $config;
|
Change title text and center it. | const React = require('react')
const { connect } = require('react-redux')
const RequestsContainer = require('./requests')
const SidebarContainer = require('./sidebar')
const AppBar = require('material-ui/AppBar').default
const titleStyle = {
textAlign: 'center',
height: '40px',
lineHeight: '40px'
}
/* eslint-disable react/jsx-indent */
const App = ({ requests }) => <div className='app-container'>
<SidebarContainer />
<main className='main-container'>
<AppBar showMenuIconButton={false} titleStyle={titleStyle} title='Requests' />
<RequestsContainer requests={requests} />
</main>
</div>
App.propTypes = {
requests: React.PropTypes.array.isRequired
}
const mapStateToProps = ({ requests }) => ({ requests })
module.exports = connect(mapStateToProps)(App)
/* eslint-enable react/jsx-indent */
| const React = require('react')
const { connect } = require('react-redux')
const RequestsContainer = require('./requests')
const SidebarContainer = require('./sidebar')
const AppBar = require('material-ui/AppBar').default
const App = ({ requests }) => <div className='app-container'>
<SidebarContainer />
<main className='main-container'>
<AppBar title='Proxy' />
<RequestsContainer requests={requests} />
</main>
</div>
App.propTypes = {
requests: React.PropTypes.array.isRequired
}
const mapStateToProps = ({ requests }) => ({ requests })
module.exports = connect(mapStateToProps)(App)
|
Remove template file when done configuring | module.exports = {
"replace": {
"_i18n/template.en-US.json": {
"author": /docprofsky/g,
"info-name": "info.name",
"info-use": "info.use",
"info-detail": "info.detail"
},
"package.json": {
"author": /docprofsky/g,
"name": /template(?!_)/g
},
"template.js": {
"name": /template/g
},
"template.ps.js": {
"name": /template/g
},
"template.html": {
"name": /template/g
},
"template.css": {
"name": /template/g
}
},
"files": {
"rename": [
"_i18n/template.en-US.json",
"template.css",
"template.html",
"template.js",
"template.ps.js"
],
"delete": [
".git",
"replace-values.js"
]
}
}
| module.exports = {
"replace": {
"_i18n/template.en-US.json": {
"author": /docprofsky/g,
"info-name": "info.name",
"info-use": "info.use",
"info-detail": "info.detail"
},
"package.json": {
"author": /docprofsky/g,
"name": /template(?!_)/g
},
"template.js": {
"name": /template/g
},
"template.ps.js": {
"name": /template/g
},
"template.html": {
"name": /template/g
},
"template.css": {
"name": /template/g
}
},
"files": {
"rename": [
"_i18n/template.en-US.json",
"template.css",
"template.html",
"template.js",
"template.ps.js"
],
"delete": [
".git"
]
}
}
|
Fix extending service provider name | <?php
/*
* This file is part of Laravel Commentable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Commentable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Commentable;
use BrianFaust\ServiceProvider\AbstractServiceProvider;
class CommentableServiceProvider extends AbstractServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
$this->publishMigrations();
$this->publishConfig();
}
/**
* Register the application services.
*/
public function register(): void
{
parent::register();
$this->mergeConfig();
}
/**
* Get the default package name.
*
* @return string
*/
public function getPackageName(): string
{
return 'commentable';
}
}
| <?php
/*
* This file is part of Laravel Commentable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Commentable.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Commentable;
use BrianFaust\ServiceProvider\ServiceProvider;
class CommentableServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
$this->publishMigrations();
$this->publishConfig();
}
/**
* Register the application services.
*/
public function register(): void
{
parent::register();
$this->mergeConfig();
}
/**
* Get the default package name.
*
* @return string
*/
public function getPackageName(): string
{
return 'commentable';
}
}
|
Add titles to FA icons | import htmlify
from socket import gethostname as hostname
from time import time as unixTime
def showFooter():
# Footer
htmlify.dispHTML("br")
htmlify.dispHTML("hr")
heart = "<i class=\"fa fa-heart\" aria-hidden=\"true\" title=\"love\"></i>"
so = "<i class=\"fa fa-stack-overflow\" aria-hidden=\"true\" title=\"StackOverflow\"></i>"
tProfileLink = htmlify.getHTML("a", contents="Theo C", href="http://github.com/DyingEcho")
iProfileLink = htmlify.getHTML("a", contents="Isaac L", href="http://github.com/il8677")
htmlify.dispHTML("small", contents="Made with " + heart + " and " + so + " by " + tProfileLink + " and " + iProfileLink)
renderTime = unixTime()
htmlify.dispHTML("br")
htmlify.dispHTML("small", contents="Rendered at " + str(round(renderTime)) + " by " + hostname())
| import htmlify
from socket import gethostname as hostname
from time import time as unixTime
def showFooter():
# Footer
htmlify.dispHTML("br")
htmlify.dispHTML("hr")
heart = "<i class=\"fa fa-heart\" aria-hidden=\"true\"></i>"
so = "<i class=\"fa fa-stack-overflow\" aria-hidden=\"true\"></i>"
tProfileLink = htmlify.getHTML("a", contents="Theo C", href="http://github.com/DyingEcho")
iProfileLink = htmlify.getHTML("a", contents="Isaac L", href="http://github.com/il8677")
htmlify.dispHTML("small", contents="Made with " + heart + " and " + so + " by " + tProfileLink + " and " + iProfileLink)
renderTime = unixTime()
htmlify.dispHTML("br")
htmlify.dispHTML("small", contents="Rendered at " + str(round(renderTime)) + " by " + hostname())
|
Remove @AfterAll, did not cause problem after all | package com.github.havarunner.scenarios.duplicated;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
abstract class VerifyThatTestAreRunOnlyOnceTestSuperClass {
protected final AtomicInteger suiteObject;
protected final List<String> scenarios;
VerifyThatTestAreRunOnlyOnceTestSuperClass(AtomicInteger suiteObject, List<String> scenarios) {
this.suiteObject = suiteObject;
this.scenarios = scenarios;
}
@Test
public void verifyTestIsRanOnlyOncePerScenario() {
final int runNumber = suiteObject.addAndGet(1);
System.out.println("Run: "+runNumber+ " for scenario: "+scenarios);
synchronized (VerifyThatTestAreRunOnlyOnceTestOneImpl.class) {
assertTrue(runNumber+" / "+VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size()+ " currentScenario: "+scenarios, VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size() >= runNumber);
}
}
}
| package com.github.havarunner.scenarios.duplicated;
import com.github.havarunner.annotation.AfterAll;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
abstract class VerifyThatTestAreRunOnlyOnceTestSuperClass {
protected final AtomicInteger suiteObject;
protected final List<String> scenarios;
VerifyThatTestAreRunOnlyOnceTestSuperClass(AtomicInteger suiteObject, List<String> scenarios) {
this.suiteObject = suiteObject;
this.scenarios = scenarios;
}
@Test
public void verifyTestIsRanOnlyOncePerScenario() {
final int runNumber = suiteObject.addAndGet(1);
System.out.println("Run: "+runNumber+ " for scenario: "+scenarios);
synchronized (VerifyThatTestAreRunOnlyOnceTestOneImpl.class) {
assertTrue(runNumber+" / "+VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size()+ " currentScenario: "+scenarios, VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size() >= runNumber);
}
}
@AfterAll
public void afterAll() {
}
}
|
CRM-4553: Fix undefined index notice and array_pop() PHP Warning in functional tests
- delete unused use | <?php
namespace Oro\Bundle\ImapBundle\Form\EventListener;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class DecodeFolderSubscriber implements EventSubscriberInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SUBMIT => ['decodeFolders', 255]
];
}
/**
* Decode folders from json pack
*
* @param FormEvent $event
*/
public function decodeFolders(FormEvent $event)
{
$data = $event->getData();
if (!$data || !is_array($data) || !array_key_exists('folders', $data)) {
return;
}
if (!is_string($data['folders'])) {
return;
}
$data['folders'] = json_decode($data['folders'], true);
$event->setData($data);
}
}
| <?php
namespace Oro\Bundle\ImapBundle\Form\EventListener;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class DecodeFolderSubscriber implements EventSubscriberInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SUBMIT => ['decodeFolders', 255]
];
}
/**
* Decode folders from json pack
*
* @param FormEvent $event
*/
public function decodeFolders(FormEvent $event)
{
$data = $event->getData();
if (!$data || !is_array($data) || !array_key_exists('folders', $data)) {
return;
}
if (!is_string($data['folders'])) {
return;
}
$data['folders'] = json_decode($data['folders'], true);
$event->setData($data);
}
}
|
mrp: Add tvOS 13.4 build number | """Lookup methods for device data."""
import re
from pyatv.const import DeviceModel
_MODEL_LIST = {
"AppleTV2,1": DeviceModel.Gen2,
"AppleTV3,1": DeviceModel.Gen3,
"AppleTV3,2": DeviceModel.Gen3,
"AppleTV5,3": DeviceModel.Gen4,
"AppleTV6,2": DeviceModel.Gen4K,
}
# Incomplete list here!
_VERSION_LIST = {
"17J586": "13.0",
"17K82": "13.2",
"17K449": "13.3",
"17K795": "13.3.1",
"17L256": "13.4",
}
def lookup_model(identifier):
"""Lookup device model from identifier."""
return _MODEL_LIST.get(identifier, DeviceModel.Unknown)
def lookup_version(build):
"""Lookup OS version from build."""
if not build:
return None
version = _VERSION_LIST.get(build)
if version:
return version
match = re.match(r"^(\d+)[A-Z]", build)
if match:
base = int(match.groups()[0])
# 17A123 corresponds to tvOS 13.x, 16A123 to tvOS 12.x and so on
return str(base - 4) + ".x"
return None
| """Lookup methods for device data."""
import re
from pyatv.const import DeviceModel
_MODEL_LIST = {
"AppleTV2,1": DeviceModel.Gen2,
"AppleTV3,1": DeviceModel.Gen3,
"AppleTV3,2": DeviceModel.Gen3,
"AppleTV5,3": DeviceModel.Gen4,
"AppleTV6,2": DeviceModel.Gen4K,
}
# Incomplete list here!
_VERSION_LIST = {
"17J586": "13.0",
"17K82": "13.2",
"17K449": "13.3",
"17K795": "13.3.1",
}
def lookup_model(identifier):
"""Lookup device model from identifier."""
return _MODEL_LIST.get(identifier, DeviceModel.Unknown)
def lookup_version(build):
"""Lookup OS version from build."""
if not build:
return None
version = _VERSION_LIST.get(build)
if version:
return version
match = re.match(r"^(\d+)[A-Z]", build)
if match:
base = int(match.groups()[0])
# 17A123 corresponds to tvOS 13.x, 16A123 to tvOS 12.x and so on
return str(base - 4) + ".x"
return None
|
Call the mongo connect method with the current configuration. | 'use strict';
var app = require('./server'),
environment = process.env.NODE_ENV,
getConfig = require('./config/config').getConfig,
configPath = './config',
mongo = require('./db/mongo'),
config;
if (!environment) {
throw new Error('Node environment not set (NODE_ENV).');
} else {
console.log('Running with environment:', environment);
}
config = getConfig(environment, configPath, require);
if(!config.server || !config.server.port) {
throw new Error('Server configuration missing');
}
mongo.connect(config)
.then(function () {
app.listen(config.server.port);
console.log('Server started on port ' + config.server.port);
})
.catch(function (error) {
if (error) {
throw new Error('Error starting up: ' + error.message);
}
});
| 'use strict';
var app = require('./server'),
environment = process.env.NODE_ENV,
getConfig = require('./config/config').getConfig,
configPath = './config',
mongo = require('./db/mongo'),
config;
if (!environment) {
throw new Error('Node environment not set (NODE_ENV).');
} else {
console.log('Running with environment:', environment);
}
config = getConfig(environment, configPath, require);
if(!config.server || !config.server.port) {
throw new Error('Server configuration missing');
}
mongo.connect()
.then(function () {
app.listen(config.server.port);
console.log('Server started on port ' + config.server.port);
})
.catch(function (error) {
if (error) {
throw new Error('Error starting up: ' + error.message);
}
});
|
Change event propagation in socket.io | // Requires
var wireFriendly = require('../utils').wireFriendly;
function setup(options, imports, register) {
// Import
var events = imports.events;
var io = imports.socket_io.io;
// Send events to user
io.of('/events').on('connection', function(socket) {
// Send to client
var handler = function(data) {
socket.emit("event", {
"event": this.event,
"data": wireFriendly(data)
});
};
// Clean up on disconnect
var cleanup = function() {
events.offAny(handler);
};
// Construct
events.onAny(handler);
// Disconnect cleanly
socket.on('disconnect', cleanup);
});
// Register
register(null, {});
}
// Exports
module.exports = setup;
| // Requires
var wireFriendly = require('../utils').wireFriendly;
function setup(options, imports, register) {
// Import
var events = imports.events;
var io = imports.socket_io.io;
// Send events to user
io.of('/events').on('connection', function(socket) {
// Send to client
var handler = function(data) {
socket.emit(this.event, wireFriendly(data));
};
// Clean up on disconnect
var cleanup = function() {
events.offAny(handler);
};
// Construct
events.onAny(handler);
// Disconnect cleanly
socket.on('disconnect', cleanup);
});
// Register
register(null, {});
}
// Exports
module.exports = setup;
|
Use textual defaults for status constants | import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BasePlaybackController(object):
PAUSED = 'paused'
PLAYING = 'playing'
STOPPED = 'stopped'
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
| import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BasePlaybackController(object):
PAUSED = 1
PLAYING = 2
STOPPED = 3
def __init__(self, backend):
self.backend = backend
self.state = self.STOPPED
self.current_track = None
self.playlist_position = None
def play(self, id=None, position=None):
raise NotImplementedError
def next(self):
raise NotImplementedError
|
Extend AppCompatEditText instead of system EditText | package com.alexstyl.specialdates.search;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class BackKeyEditText extends android.support.v7.widget.AppCompatEditText {
public BackKeyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
private OnBackKeyPressedListener listener;
public void setOnBackKeyPressedListener(OnBackKeyPressedListener listener) {
this.listener = listener;
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && listener.onBackButtonPressed()) {
return true;
}
return super.onKeyPreIme(keyCode, event);
}
}
| package com.alexstyl.specialdates.search;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class BackKeyEditText extends EditText {
public BackKeyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
private OnBackKeyPressedListener listener;
public void setOnBackKeyPressedListener(OnBackKeyPressedListener listener) {
this.listener = listener;
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && listener.onBackButtonPressed()) {
return true;
}
return super.onKeyPreIme(keyCode, event);
}
}
|
Fix for Node.js 0.6.0: Build seems to be now in Release instead of default | var EventEmitter = require('events').EventEmitter;
var util = require('util');
var expat = require('../build/Release/node-expat');
/**
* Simple wrapper because EventEmitter has turned pure-JS as of node
* 0.5.x.
*/
exports.Parser = function(encoding) {
this.parser = new expat.Parser(encoding);
var that = this;
this.parser.emit = function() {
that.emit.apply(that, arguments);
};
};
util.inherits(exports.Parser, EventEmitter);
exports.Parser.prototype.parse = function(buf, isFinal) {
return this.parser.parse(buf, isFinal);
};
exports.Parser.prototype.setEncoding = function(encoding) {
return this.parser.setEncoding(encoding);
};
exports.Parser.prototype.getError = function() {
return this.parser.getError();
};
exports.Parser.prototype.stop = function() {
return this.parser.stop();
};
exports.Parser.prototype.pause = function() {
return this.stop();
};
exports.Parser.prototype.resume = function() {
return this.parser.resume();
};
| var EventEmitter = require('events').EventEmitter;
var util = require('util');
var expat = require('../build/default/node-expat');
/**
* Simple wrapper because EventEmitter has turned pure-JS as of node
* 0.5.x.
*/
exports.Parser = function(encoding) {
this.parser = new expat.Parser(encoding);
var that = this;
this.parser.emit = function() {
that.emit.apply(that, arguments);
};
};
util.inherits(exports.Parser, EventEmitter);
exports.Parser.prototype.parse = function(buf, isFinal) {
return this.parser.parse(buf, isFinal);
};
exports.Parser.prototype.setEncoding = function(encoding) {
return this.parser.setEncoding(encoding);
};
exports.Parser.prototype.getError = function() {
return this.parser.getError();
};
exports.Parser.prototype.stop = function() {
return this.parser.stop();
};
exports.Parser.prototype.pause = function() {
return this.stop();
};
exports.Parser.prototype.resume = function() {
return this.parser.resume();
};
|
Change the order of the Web_Alltests suite | <?php
require_once dirname(__FILE__).'/../phpunit.php';
if(!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Web_AllTests::main');
}
require_once 'TAssetManagerTest.php';
require_once 'THttpCookieCollectionTest.php';
require_once 'THttpCookieTest.php';
require_once 'THttpRequestTest.php';
require_once 'THttpResponseTest.php';
require_once 'THttpSessionTest.php';
require_once 'THttpUtilityTest.php';
require_once 'TUriTest.php';
require_once 'UI/AllTests.php';
class Web_AllTests {
public static function main() {
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('System.Web');
$suite->addTestSuite('THttpRequestTest');
$suite->addTestSuite('TAssetManagerTest');
$suite->addTestSuite('THttpCookieCollectionTest');
$suite->addTestSuite('THttpCookieTest');
$suite->addTestSuite('THttpResponseTest');
$suite->addTestSuite('THttpSessionTest');
$suite->addTestSuite('THttpUtilityTest');
$suite->addTestSuite('TUriTest');
$suite->addTest(Web_UI_AllTests::suite());
return $suite;
}
}
if(PHPUnit_MAIN_METHOD == 'Web_AllTests::main') {
Web_AllTests::main();
}
?>
| <?php
require_once dirname(__FILE__).'/../phpunit.php';
if(!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Web_AllTests::main');
}
require_once 'TAssetManagerTest.php';
require_once 'THttpCookieCollectionTest.php';
require_once 'THttpCookieTest.php';
require_once 'THttpRequestTest.php';
require_once 'THttpResponseTest.php';
require_once 'THttpSessionTest.php';
require_once 'THttpUtilityTest.php';
require_once 'TUriTest.php';
require_once 'UI/AllTests.php';
class Web_AllTests {
public static function main() {
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('System.Web');
$suite->addTestSuite('TAssetManagerTest');
$suite->addTestSuite('THttpCookieCollectionTest');
$suite->addTestSuite('THttpCookieTest');
$suite->addTestSuite('THttpRequestTest');
$suite->addTestSuite('THttpResponseTest');
$suite->addTestSuite('THttpSessionTest');
$suite->addTestSuite('THttpUtilityTest');
$suite->addTestSuite('TUriTest');
$suite->addTest(Web_UI_AllTests::suite());
return $suite;
}
}
if(PHPUnit_MAIN_METHOD == 'Web_AllTests::main') {
Web_AllTests::main();
}
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.