text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Simplify arrow function in map | import { Store } from 'consus-core/flux';
import StudentStore from './student-store';
import { checkOutItems } from '../lib/api-client';
let items = [];
let timer = null;
function clearTimer() {
clearTimeout(timer);
timer = null;
}
class CartStore extends Store {
getItems() {
return items;
}
isOnTimeout(){
return timer !== null;
}
}
const store = new CartStore();
store.TIMEOUT_TIME = 60000;
store.registerHandler('STUDENT_FOUND', () => {
if(store.isOnTimeout()){
clearTimer();
}
});
store.registerHandler('CHECKOUT_ITEM_FOUND', data => {
if(store.isOnTimeout()){
clearTimer();
}
let item = {
address: data.address,
status: data.status
};
items.push(item);
timer = setTimeout(() => {
checkOutItems(StudentStore.getStudent().id, items.map(item => item.address));
timer = null;
}, store.TIMEOUT_TIME);
store.emitChange();
});
store.registerHandler('CHECKOUT_SUCCESS', () => {
clearTimer();
store.waitFor(StudentStore);
items = [];
store.emitChange();
});
store.registerHandler('CLEAR_ALL_DATA', () => {
items = [];
store.emitChange();
});
store.registerHandler('CLEAR_ITEMS', () => {
items = [];
store.emitChange();
});
export default store;
| import { Store } from 'consus-core/flux';
import StudentStore from './student-store';
import { checkOutItems } from '../lib/api-client';
let items = [];
let timer = null;
function clearTimer() {
clearTimeout(timer);
timer = null;
}
class CartStore extends Store {
getItems() {
return items;
}
isOnTimeout(){
return timer !== null;
}
}
const store = new CartStore();
store.TIMEOUT_TIME = 60000;
store.registerHandler('STUDENT_FOUND', () => {
if(store.isOnTimeout()){
clearTimer();
}
});
store.registerHandler('CHECKOUT_ITEM_FOUND', data => {
if(store.isOnTimeout()){
clearTimer();
}
let item = {
address: data.address,
status: data.status
};
items.push(item);
timer = setTimeout(() => {
checkOutItems(StudentStore.getStudent().id, items.map(item =>{return item.address;}));
timer = null;
}, store.TIMEOUT_TIME);
store.emitChange();
});
store.registerHandler('CHECKOUT_SUCCESS', () => {
clearTimer();
store.waitFor(StudentStore);
items = [];
store.emitChange();
});
store.registerHandler('CLEAR_ALL_DATA', () => {
items = [];
store.emitChange();
});
store.registerHandler('CLEAR_ITEMS', () => {
items = [];
store.emitChange();
});
export default store;
|
Remove call to deprecated Controller::getRequest() | <?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
class SecurityController extends Controller
{
public function loginAction(Request $request)
{
$session = $request->getSession();
$error = null;
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
// Add the following lines
if ($session->has('_security.target_path')) {
if (false !== strpos($session->get('_security.target_path'), $this->generateUrl('fos_oauth_server_authorize'))) {
$session->set('_fos_oauth_server.ensure_logout', true);
}
}
return $this->render('AppBundle:Security:login.html.twig', array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
'error_type' => $error?get_class($error):null,
));
}
}
| <?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
class SecurityController extends Controller
{
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
$error = null;
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
// Add the following lines
if ($session->has('_security.target_path')) {
if (false !== strpos($session->get('_security.target_path'), $this->generateUrl('fos_oauth_server_authorize'))) {
$session->set('_fos_oauth_server.ensure_logout', true);
}
}
return $this->render('AppBundle:Security:login.html.twig', array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
'error_type' => $error?get_class($error):null,
));
}
}
|
Set package URL to where it'll be uploaded. | #! /usr/bin/python
import os
import setuptools
import sys
# FIXME explain why this is here
sys.path.insert(0,
os.path.join(
os.path.dirname(__file__),
"lib",
))
import opensub
setuptools.setup(
author="Bence Romsics",
author_email="[email protected]",
classifiers=[
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Topic :: Multimedia :: Video",
"Topic :: Utilities",
],
description="CLI utilities for opensubtitles.org.",
install_requires=[
"docopt",
"six",
],
name="opensub",
package_dir={
"": "lib",
},
packages=[
"opensub",
],
scripts=[
"bin/opensub-get",
"bin/opensub-hash",
],
tests_require=[
"nose",
],
url="https://github.com/rubasov/opensub-utils",
version=opensub.__version__,
zip_safe=False,
)
| #! /usr/bin/python
import os
import setuptools
import sys
# FIXME explain why this is here
sys.path.insert(0,
os.path.join(
os.path.dirname(__file__),
"lib",
))
import opensub
setuptools.setup(
author="Bence Romsics",
author_email="[email protected]",
classifiers=[
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: POSIX",
"Programming Language :: Python :: 2.7",
"Topic :: Multimedia :: Video",
"Topic :: Utilities",
],
description="CLI utilities for opensubtitles.org.",
install_requires=[
"docopt",
"six",
],
name="opensub",
package_dir={
"": "lib",
},
packages=[
"opensub",
],
scripts=[
"bin/opensub-get",
"bin/opensub-hash",
],
tests_require=[
"nose",
],
url="http://github.com/rubasov/...", # FIXME
version=opensub.__version__,
zip_safe=False,
)
|
Update service worker cache version | var CACHE_NAME = 'buddhabrot-2017-10-17';
var urlsToCache = [
'.',
'/',
'/main.js',
'/material-components-web.min.css',
'/material-components-web.min.js',
'/rust-logo-blk.svg',
'/rustybrot.asmjs.js',
'/rustybrot.wasm',
'/rustybrot.wasm.js',
'/worker-compositor.js',
'/worker-producer.js',
'/manifest.json',
'/icon.png'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
this.addEventListener('activate', function(event) {
var cacheWhitelist = ['buddhabrot-2017-10-17'];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
}); | var CACHE_NAME = 'buddhabrot-2017-10-12-2';
var urlsToCache = [
'.',
'/',
'/main.js',
'/material-components-web.min.css',
'/material-components-web.min.js',
'/rust-logo-blk.svg',
'/rustybrot.asmjs.js',
'/rustybrot.wasm',
'/rustybrot.wasm.js',
'/worker-compositor.js',
'/worker-producer.js',
'/manifest.json',
'/icon.png'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
this.addEventListener('activate', function(event) {
var cacheWhitelist = ['buddhabrot-2017-10-12-2'];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
}); |
Add unit support for spacers | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
| # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]), int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
|
Fix error on profiles page when there is no active machine | # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Settings.ContainerRegistry import ContainerRegistry
from cura.QualityManager import QualityManager
from cura.Settings.ProfilesModel import ProfilesModel
## QML Model for listing the current list of valid quality and quality changes profiles.
#
class QualityAndUserProfilesModel(ProfilesModel):
def __init__(self, parent = None):
super().__init__(parent)
## Fetch the list of containers to display.
#
# See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers().
def _fetchInstanceContainers(self):
global_container_stack = Application.getInstance().getGlobalContainerStack()
if not global_container_stack:
return []
# Fetch the list of qualities
quality_list = super()._fetchInstanceContainers()
# Fetch the list of quality changes.
quality_manager = QualityManager.getInstance()
machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom())
if machine_definition.getMetaDataEntry("has_machine_quality"):
definition_id = machine_definition.getId()
else:
definition_id = "fdmprinter"
filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id }
quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
return quality_list + quality_changes_list
| # Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Settings.ContainerRegistry import ContainerRegistry
from cura.QualityManager import QualityManager
from cura.Settings.ProfilesModel import ProfilesModel
## QML Model for listing the current list of valid quality and quality changes profiles.
#
class QualityAndUserProfilesModel(ProfilesModel):
def __init__(self, parent = None):
super().__init__(parent)
## Fetch the list of containers to display.
#
# See UM.Settings.Models.InstanceContainersModel._fetchInstanceContainers().
def _fetchInstanceContainers(self):
# Fetch the list of qualities
quality_list = super()._fetchInstanceContainers()
# Fetch the list of quality changes.
quality_manager = QualityManager.getInstance()
application = Application.getInstance()
machine_definition = quality_manager.getParentMachineDefinition(application.getGlobalContainerStack().getBottom())
if machine_definition.getMetaDataEntry("has_machine_quality"):
definition_id = machine_definition.getId()
else:
definition_id = "fdmprinter"
filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id }
quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
return quality_list + quality_changes_list
|
Update to work with a layout | var gulp = require('gulp');
var Elixir = require('laravel-elixir');
var inky = require('inky');
var prettify = require('gulp-prettify');
var fs = require('fs');
var siphon = require('siphon-media-query');
var lazypipe = require('lazypipe');
var inlineCss = require('gulp-inline-css');
var htmlmin = require('gulp-htmlmin');
var injectString = require('gulp-inject-string');
var Task = Elixir.Task;
Elixir.extend('processEmails', function(options) {
new Task('processEmails', function() {
return gulp
.src('resources/emails/**/*.blade.php')
.pipe(inky())
.pipe(prettify({ indent_size: 2 }))
.pipe(injectString.replace('->', '->'))
.pipe(injectString.replace('=>', '=>'))
.pipe(injectString.replace('"', '"'))
.pipe(injectString.replace(''', '\''))
.pipe(inliner('resources/assets/css/foundation.css'))
.pipe(gulp.dest('resources/views/emails'));
})
.watch('./resources/emails/**');
function inliner(css) {
var css = fs.readFileSync(css).toString();
var pipe = lazypipe()
.pipe(injectString.replace, '<!-- <style> -->', '<style>'+css+'</style>')
.pipe(inlineCss)
.pipe(htmlmin, {
collapseWhitespace: true,
minifyCSS: true
});
return pipe();
}
});
| var gulp = require('gulp');
var Elixir = require('laravel-elixir');
var inky = require('inky');
var prettify = require('gulp-prettify');
var fs = require('fs');
var siphon = require('siphon-media-query');
var lazypipe = require('lazypipe');
var inlineCss = require('gulp-inline-css');
var htmlmin = require('gulp-htmlmin');
var injectString = require('gulp-inject-string');
var Task = Elixir.Task;
Elixir.extend('processEmails', function(options) {
new Task('processEmails', function() {
return gulp
.src('resources/emails/*.blade.php')
.pipe(inky())
.pipe(prettify({ indent_size: 2 }))
.pipe(injectString.replace('->', '->'))
.pipe(injectString.replace('=>', '=>'))
.pipe(inliner('resources/assets/css/foundation.css'))
.pipe(gulp.dest('resources/views/emails'));
})
.watch('./resources/emails/**');
function inliner(css) {
var css = fs.readFileSync(css).toString();
var pipe = lazypipe()
.pipe(injectString.replace, '<!-- <style> -->', '<style>'+css+'</style>')
.pipe(inlineCss)
.pipe(htmlmin, {
collapseWhitespace: true,
minifyCSS: true
});
return pipe();
}
});
|
Set les champs money to not required | <?php
namespace PiggyBox\ShopBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('origin')
->add('preservation')
->add('price', 'money', array(
'required' => false,
))
->add('weightPrice', 'money', array(
'required' => false,
))
->add('priceType', 'choice', array(
'choices' => array(
'unit_fixed_price' => 'Unit Fixed Price',
'unit_variable_price' => 'Unit Variable Price',
'chunk_price' => 'Chunk Price'),
'required' => true,
))
->add('productWeightPerSlice')
->add('file')
->add('category')
->add('minWeight')
->add('maxWeight')
->add('minPerson')
->add('maxPerson')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PiggyBox\ShopBundle\Entity\Product'
));
}
public function getName()
{
return 'piggybox_shopbundle_producttype';
}
}
| <?php
namespace PiggyBox\ShopBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('origin')
->add('preservation')
->add('price', 'money')
->add('weightPrice', 'money')
->add('priceType', 'choice', array(
'choices' => array(
'unit_fixed_price' => 'Unit Fixed Price',
'unit_variable_price' => 'Unit Variable Price',
'chunk_price' => 'Chunk Price'),
'required' => true,
))
->add('productWeightPerSlice')
->add('file')
->add('category')
->add('minWeight')
->add('maxWeight')
->add('minPerson')
->add('maxPerson')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PiggyBox\ShopBundle\Entity\Product'
));
}
public function getName()
{
return 'piggybox_shopbundle_producttype';
}
}
|
Make foreign keys unsigned for pivot table generation | <?php namespace Way\Generators\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class PivotGeneratorCommand extends BaseGeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:pivot';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a pivot table';
public function fire()
{
$tables = $this->sortDesiredTables();
$this->call(
'generate:migration',
array(
'name' => "pivot_{$tables[0]}_{$tables[1]}_table",
'--fields' => "{$tables[0]}_id:integer:unsigned, {$tables[1]}_id:integer:unsigned"
)
);
}
public function sortDesiredTables()
{
$tableOne = str_singular($this->argument('tableOne'));
$tableTwo = str_singular($this->argument('tableTwo'));
$tables = array($tableOne, $tableTwo);
sort($tables);
return $tables;
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('tableOne', InputArgument::REQUIRED, 'Name of the first table.'),
array('tableTwo', InputArgument::REQUIRED, 'Name of the second table.')
);
}
}
| <?php namespace Way\Generators\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class PivotGeneratorCommand extends BaseGeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:pivot';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a pivot table';
public function fire()
{
$tables = $this->sortDesiredTables();
$this->call(
'generate:migration',
array(
'name' => "pivot_{$tables[0]}_{$tables[1]}_table",
'--fields' => "{$tables[0]}_id:integer, {$tables[1]}_id:integer"
)
);
}
public function sortDesiredTables()
{
$tableOne = str_singular($this->argument('tableOne'));
$tableTwo = str_singular($this->argument('tableTwo'));
$tables = array($tableOne, $tableTwo);
sort($tables);
return $tables;
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('tableOne', InputArgument::REQUIRED, 'Name of the first table.'),
array('tableTwo', InputArgument::REQUIRED, 'Name of the second table.')
);
}
}
|
Fix failing tests on setup.py test | from plasmapy.classes import BasePlasma, GenericPlasma
# Get rid of any previously registered classes.
BasePlasma._registry = {}
class NoDataSource(BasePlasma):
pass
class IsDataSource(BasePlasma):
@classmethod
def is_datasource_for(cls, **kwargs):
return True
class IsNotDataSource(BasePlasma):
@classmethod
def is_datasource_for(cls, **kwargs):
return False
class TestRegistrar:
def test_no_data_source(self):
"""
NoDataSource class should not be registered since it has
no method named ``is_datasource_for``.
"""
assert not BasePlasma._registry.get(NoDataSource)
def test_is_data_source(self):
"""
IsDataSource class should be registered since it has a
method named ``is_datasource_for`` and must return True.
"""
assert BasePlasma._registry.get(IsDataSource)
assert BasePlasma._registry[IsDataSource]()
# Delete the class from _registry once test is done
# to not interfere with plasma factory tests
del BasePlasma._registry[IsDataSource]
def test_is_not_data_source(self):
"""
IsNotDataSource class should be registered since it has a
method named ``is_datasource_for`` but must return False.
"""
assert BasePlasma._registry.get(IsNotDataSource)
assert not BasePlasma._registry[IsNotDataSource]()
del BasePlasma._registry[IsNotDataSource]
def test_subclasses():
assert issubclass(GenericPlasma, BasePlasma)
| from plasmapy.classes import BasePlasma, GenericPlasma
class NoDataSource(BasePlasma):
pass
class IsDataSource(BasePlasma):
@classmethod
def is_datasource_for(cls, **kwargs):
return True
class IsNotDataSource(BasePlasma):
@classmethod
def is_datasource_for(cls, **kwargs):
return False
class TestRegistrar:
def test_no_data_source(self):
"""
NoDataSource class should not be registered since it has
no method named ``is_datasource_for``.
"""
assert not BasePlasma._registry.get(NoDataSource)
def test_is_data_source(self):
"""
IsDataSource class should be registered since it has a
method named ``is_datasource_for`` and must return True.
"""
assert BasePlasma._registry.get(IsDataSource)
assert BasePlasma._registry[IsDataSource]()
# Delete the class from _registry once test is done
# to not interfere with plasma factory tests
del BasePlasma._registry[IsDataSource]
def test_is_not_data_source(self):
"""
IsNotDataSource class should be registered since it has a
method named ``is_datasource_for`` but must return False.
"""
assert BasePlasma._registry.get(IsNotDataSource)
assert not BasePlasma._registry[IsNotDataSource]()
del BasePlasma._registry[IsNotDataSource]
def test_subclasses():
assert issubclass(GenericPlasma, BasePlasma)
|
Remove error responsibility from APIResponse | import {
TYPES,
thingType,
COMMENT,
USER,
LINK,
MESSAGE,
} from './thingTypes';
export default class APIResponse {
constructor(meta={}) {
this.meta = meta;
this.results = [];
this.links = {};
this.comments = {};
this.users = {};
this.messages = {};
this.typeToTable = {
[COMMENT]: this.comments,
[LINK]: this.links,
[USER]: this.users,
[MESSAGE]: this.messages,
};
}
addResult(model) {
const record = this.makeRecord(model);
if (record) {
this.results.push(record);
this.addToTable(record, model);
}
return this;
}
addModel(model) {
const record = this.makeRecord(model);
if (record) {
this.addToTable(record, model);
}
return this;
}
makeRecord(model) {
const { uuid } = model;
if (!uuid) { return; }
const type = TYPES[model.kind] || thingType(uuid);
if (!type) { return; }
return { type, uuid };
}
addToTable(record, model) {
const table = this.typeToTable[record.type];
if (table) { table[record.uuid] = model; }
return this;
}
getModelFromRecord(record) {
const table = this.typeToTable[record.type];
if (table) { return table[record.uuid]; }
}
}
| import {
TYPES,
thingType,
COMMENT,
USER,
LINK,
MESSAGE,
} from './thingTypes';
export default class APIResponse {
constructor(meta={}) {
this.meta = meta;
this.results = [];
this.errors;
this.links = {};
this.comments = {};
this.users = {};
this.messages = {};
this.typeToTable = {
[COMMENT]: this.comments,
[LINK]: this.links,
[USER]: this.users,
[MESSAGE]: this.messages,
};
}
setErrors(errors) {
this.errors = errors;
}
addResult(model) {
const record = this.makeRecord(model);
if (record) {
this.results.push(record);
this.addToTable(record, model);
}
return this;
}
addModel(model) {
const record = this.makeRecord(model);
if (record) {
this.addToTable(record, model);
}
return this;
}
makeRecord(model) {
const { uuid } = model;
if (!uuid) { return; }
const type = TYPES[model.kind] || thingType(uuid);
if (!type) { return; }
return { type, uuid };
}
addToTable(record, model) {
const table = this.typeToTable[record.type];
if (table) { table[record.uuid] = model; }
return this;
}
getModelFromRecord(record) {
const table = this.typeToTable[record.type];
if (table) { return table[record.uuid]; }
}
}
|
Revert "fix: ensure a scope is used"
This reverts commit 3fbfbb1b2687de3d7c056a6790ad735b19eb9254.
No longer necessary, this is now fixed in vatesfr/xo-server@8c7d254244fdf0438ab8f0bf9ee7c082f7318f09 | import { Strategy } from 'passport-google-oauth20'
// ===================================================================
export const configurationSchema = {
type: 'object',
properties: {
callbackURL: {
type: 'string',
description: 'Must be exactly the same as specified on the Google developer console.'
},
clientID: {
type: 'string'
},
clientSecret: {
type: 'string'
},
scope: {
default: 'https://www.googleapis.com/auth/plus.login',
description: 'Note that changing this value will break existing users.',
enum: [ 'https://www.googleapis.com/auth/plus.login', 'email' ],
enumNames: [ 'Google+ name', 'Simple email address' ]
}
},
required: ['callbackURL', 'clientID', 'clientSecret']
}
// ===================================================================
class AuthGoogleXoPlugin {
constructor ({ xo }) {
this._conf = null
this._xo = xo
}
configure (conf) {
this._conf = conf
}
load () {
const conf = this._conf
const xo = this._xo
xo.registerPassportStrategy(new Strategy(conf, async (accessToken, refreshToken, profile, done) => {
try {
done(null, await xo.registerUser(
'google',
conf.scope === 'email'
? profile.emails[0].value
: profile.displayName
))
} catch (error) {
done(error.message)
}
}))
}
}
// ===================================================================
export default opts => new AuthGoogleXoPlugin(opts)
| import { Strategy } from 'passport-google-oauth20'
// ===================================================================
export const configurationSchema = {
type: 'object',
properties: {
callbackURL: {
type: 'string',
description: 'Must be exactly the same as specified on the Google developer console.'
},
clientID: {
type: 'string'
},
clientSecret: {
type: 'string'
},
scope: {
default: 'https://www.googleapis.com/auth/plus.login',
description: 'Note that changing this value will break existing users.',
enum: [ 'https://www.googleapis.com/auth/plus.login', 'email' ],
enumNames: [ 'Google+ name', 'Simple email address' ]
}
},
required: ['callbackURL', 'clientID', 'clientSecret']
}
// ===================================================================
class AuthGoogleXoPlugin {
constructor ({ xo }) {
this._conf = null
this._xo = xo
}
configure (conf) {
this._conf = conf
}
load () {
const conf = {
// TODO: find a better way to inject default values
scope: configurationSchema.properties.scope.default,
...this._conf
}
const xo = this._xo
xo.registerPassportStrategy(new Strategy(conf, async (accessToken, refreshToken, profile, done) => {
try {
done(null, await xo.registerUser(
'google',
conf.scope === 'email'
? profile.emails[0].value
: profile.displayName
))
} catch (error) {
done(error.message)
}
}))
}
}
// ===================================================================
export default opts => new AuthGoogleXoPlugin(opts)
|
Initialize set results before button action. The UI client can be used for receiving messages only. | import converters.JsonConverter;
import datamodel.Request;
import httpserver.RequestSender;
import httpserver.WebServer;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class Controller {
public TextField response;
private WebServer ws = new WebServer();
public TextField command;
@FXML
public TextArea results;
@FXML
public void initialize(){
ws.setResults(results);
}
public void runCommand(ActionEvent actionEvent) {
results.setText("");
response.setText("");
Thread th = new Thread() {
@Override
public void run() {
String commandString = command.getText();
Request request = new Request();
request.setClientId("13");
request.setCommand(commandString);
request.setResponseAddress("http://localhost:8008/jobFinished");
request.setProcessors(new String[] {"processors.XmlToJsonConverter","processors.TlsFilter"});
request.setAdapter("adapters.EventHubAdapter");
String requestJsonString = JsonConverter.objectToJsonString(request);
String requestResponse = RequestSender.sendRequest("http://localhost:8000/job", request);
Platform.runLater(new Runnable() {
@Override
public void run() {
response.setText(requestResponse);
}
});
}
};
th.start();
}
}
| import converters.JsonConverter;
import datamodel.Request;
import httpserver.RequestSender;
import httpserver.WebServer;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class Controller {
public TextField response;
private WebServer ws = new WebServer();
public TextField command;
@FXML
public TextArea results;
public void runCommand(ActionEvent actionEvent) {
results.setText("");
response.setText("");
ws.setResults(results);
Thread th = new Thread() {
@Override
public void run() {
String commandString = command.getText();
Request request = new Request();
request.setClientId("13");
request.setCommand(commandString);
request.setResponseAddress("http://localhost:8008/jobFinished");
request.setProcessors(new String[] {"processors.XmlToJsonConverter","processors.TlsFilter"});
request.setAdapter("adapters.EventHubAdapter");
String requestJsonString = JsonConverter.objectToJsonString(request);
String requestResponse = RequestSender.sendRequest("http://localhost:8000/job", request);
Platform.runLater(new Runnable() {
@Override
public void run() {
response.setText(requestResponse);
}
});
}
};
th.start();
}
}
|
Move annonymous function handling resolved route into named function. | var Driver = require('./Driver').Driver;
function turnpike_server() {
return function(req, res) {
var d = domain.create();
d.on('error', function(er){
console.error('Error encountered in connection handler', er.stack);
try {
var countdown = setTimeout(function(){
process.exit(1);
}, 30000);
countdown.unref();
Driver.server.close();
cluser.worker.disconnect();
res.writeHead(500, "Unknown fatal server error", {'Content-Type': 'text/plain'});
res.end("500\nInternal server error.");
}
catch (er2) {
console.error('Failure sending 500 status during error handler'. er2.stack);
}
});
d.add(req);
d.add(res);
d.run(function(){
var connection = new Connection(req, res);
connection.end(function(){
console.log("Serving: " + req.url);
Router.resolve(
function(err, route) {
route_handler(connection, err, route)
},
url.parse(req.url).pathname);
});
});
};
}
function route_handler(connection, err, route) {
var controller;
connection.route = route;
controller = AutoLoader.invoke(connection.route.controller);
if (typeof(controller) == "function" ) {
connection.controller = controller = new controller(connection);
controller.prepare(controller.deliver);
}
else {
connection.die(404);
}
}
module.exports = turnpike_server;
| var Driver = require('./Driver').Driver;
function turnpike_server() {
return function(req, res) {
var d = domain.create();
d.on('error', function(er){
console.error('Error encountered in connection handler', er.stack);
try {
var countdown = setTimeout(function(){
process.exit(1);
}, 30000);
countdown.unref();
Driver.server.close();
cluser.worker.disconnect();
res.writeHead(500, "Unknown fatal server error", {'Content-Type': 'text/plain'});
res.end("500\nInternal server error.");
}
catch (er2) {
console.error('Failure sending 500 status during error handler'. er2.stack);
}
});
d.add(req);
d.add(res);
d.run(function(){
var connection = new Connection(req, res);
var controller;
connection.end(function(){
console.log("Serving: " + req.url);
Router.resolve(function(err, route){
connection.route = route;
controller = AutoLoader.invoke(connection.route.controller);
if (typeof(controller) == "function" ) {
connection.controller = controller = new controller(connection);
controller.prepare(controller.deliver);
}
else {
connection.die(404);
}
},url.parse(req.url).pathname);
});
});
};
}
module.exports = turnpike_server;
|
Switch project view when user picks a different project. | Application.Directives.directive("sidebarProjects", sidebarProjectsDirective);
function sidebarProjectsDirective() {
return {
restrict: "AE",
replace: true,
templateUrl: "index/sidebar-projects.html",
controller: "sidebarProjectsDirectiveController"
};
}
Application.Controllers.controller("sidebarProjectsDirectiveController",
["$scope", "current", "sidebarUtil",
"mcapi", "model.projects", "$state",
sidebarProjectsDirectiveController]);
function sidebarProjectsDirectiveController($scope, current, sidebarUtil, mcapi, Projects, $state) {
$scope.showProjects = false;
$scope.setProject = function(project) {
$scope.project = project;
current.setProject(project);
$scope.showProjects = false;
$scope.project.fileCount = sidebarUtil.projectFileCount($scope.project);
$scope.project.projectSize = sidebarUtil.projectSize($scope.project);
$state.go("projects.project.home", {id: project.id});
};
$scope.createProject = function(){
if ($scope.model.name === "") {
return;
}
mcapi('/projects')
.success(function (data) {
Projects.getList(true).then(function(projects) {
$scope.projects = projects;
});
}).post({'name': $scope.model.name});
};
}
| Application.Directives.directive("sidebarProjects", sidebarProjectsDirective);
function sidebarProjectsDirective() {
return {
restrict: "AE",
replace: true,
templateUrl: "index/sidebar-projects.html",
controller: "sidebarProjectsDirectiveController"
};
}
Application.Controllers.controller("sidebarProjectsDirectiveController",
["$scope", "current", "sidebarUtil",
"mcapi", "model.projects",
sidebarProjectsDirectiveController]);
function sidebarProjectsDirectiveController($scope, current, sidebarUtil, mcapi, Projects) {
$scope.showProjects = false;
$scope.setProject = function(project) {
$scope.project = project;
current.setProject(project);
$scope.showProjects = false;
$scope.project.fileCount = sidebarUtil.projectFileCount($scope.project);
$scope.project.projectSize = sidebarUtil.projectSize($scope.project);
};
$scope.createProject = function(){
if ($scope.model.name === "") {
return;
}
mcapi('/projects')
.success(function (data) {
console.dir(data);
Projects.getList(true).then(function(projects) {
$scope.projects = projects;
});
}).post({'name': $scope.model.name});
};
}
|
Clean up unused packages in tests | var chai = require('chai'),
sinon = require('sinon'),
rewire = require('rewire');
var expect = chai.expect;
var assert = chai.assert;
describe("It scans for devices", function() {
var detector,
loggerMock,
sonumiLoggerMock,
networkAdapterMock;
var deviceDetector = rewire("../lib/detector");
beforeEach(function() {
loggerMock = sinon.stub();
loggerMock.log = sinon.stub();
loggerMock.addLogFile = sinon.stub();
sonumiLoggerMock = sinon.stub();
sonumiLoggerMock.init = sinon.stub().returns(loggerMock);
networkAdapterMock = sinon.stub();
networkAdapterMock.scan = sinon.spy();
configMock = {
"logging": {
"logDir": "/tmp/"
}
};
deviceDetector.__set__({
config: configMock,
logger: loggerMock,
sonumiLogger: sonumiLoggerMock
});
detector = new deviceDetector({ network: networkAdapterMock });
});
it('should retrieve a list of connected devices from the network adapter', function() {
detector.scan();
assert(networkAdapterMock.scan.calledOnce);
});
});
| var chai = require('chai'),
sinon = require('sinon'),
rewire = require('rewire');
require('sinon-as-promised');
var expect = chai.expect;
var assert = chai.assert;
describe("Scan", function() {
var detector,
loggerMock,
sonumiLoggerMock,
networkAdapterMock;
var deviceDetector = rewire("../lib/detector");
beforeEach(function() {
loggerMock = sinon.stub();
loggerMock.log = sinon.stub();
loggerMock.addLogFile = sinon.stub();
sonumiLoggerMock = sinon.stub();
sonumiLoggerMock.init = sinon.stub().returns(loggerMock);
networkAdapterMock = sinon.stub();
networkAdapterMock.scan = sinon.spy();
configMock = {
"logging": {
"logDir": "/tmp/"
}
};
deviceDetector.__set__({
config: configMock,
logger: loggerMock,
sonumiLogger: sonumiLoggerMock
});
detector = new deviceDetector({ network: networkAdapterMock });
});
it('should retrieve a list of connected devices from the network adapter', function() {
detector.scan();
assert(networkAdapterMock.scan.calledOnce);
});
});
describe("LAN adapter", function() {
// test that the lan adapter scans the network
});
|
tool-core: Change the order of the progress bar and the brand icon | package com.speedment.tool.core.internal.toolbar;
import com.speedment.common.injector.annotation.ExecuteBefore;
import com.speedment.common.injector.annotation.InjectKey;
import com.speedment.common.injector.annotation.WithState;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.resource.FontAwesome;
import com.speedment.tool.core.toolbar.ToolbarComponent;
import static com.speedment.common.injector.State.INITIALIZED;
/**
* @author Emil Forslund
* @since 3.1.5
*/
@InjectKey(DefaultToolbarItems.class)
public final class DefaultToolbarItems {
@ExecuteBefore(INITIALIZED)
void install(
@WithState(INITIALIZED) ToolbarComponent toolbar,
@WithState(INITIALIZED) UserInterfaceComponent ui) {
toolbar.install("reload", new SimpleToolbarItemImpl(
"Reload", FontAwesome.REFRESH, ev -> ui.reload(),
"Reload the metadata from the database and merge any changes " +
"with the existing configuration."
));
toolbar.install("generate", new SimpleToolbarItemImpl(
"Generate", FontAwesome.PLAY_CIRCLE, ev -> ui.generate(),
"Generate code using the current configuration. Automatically " +
"save the configuration before generation."
));
toolbar.install("brand", new BrandToolbarItem());
toolbar.install("progress", new GenerationProgressToolbarItem());
}
}
| package com.speedment.tool.core.internal.toolbar;
import com.speedment.common.injector.annotation.ExecuteBefore;
import com.speedment.common.injector.annotation.InjectKey;
import com.speedment.common.injector.annotation.WithState;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.resource.FontAwesome;
import com.speedment.tool.core.toolbar.ToolbarComponent;
import static com.speedment.common.injector.State.INITIALIZED;
/**
* @author Emil Forslund
* @since 3.1.5
*/
@InjectKey(DefaultToolbarItems.class)
public final class DefaultToolbarItems {
@ExecuteBefore(INITIALIZED)
void install(
@WithState(INITIALIZED) ToolbarComponent toolbar,
@WithState(INITIALIZED) UserInterfaceComponent ui) {
toolbar.install("reload", new SimpleToolbarItemImpl(
"Reload", FontAwesome.REFRESH, ev -> ui.reload(),
"Reload the metadata from the database and merge any changes " +
"with the existing configuration."
));
toolbar.install("generate", new SimpleToolbarItemImpl(
"Generate", FontAwesome.PLAY_CIRCLE, ev -> ui.generate(),
"Generate code using the current configuration. Automatically " +
"save the configuration before generation."
));
toolbar.install("progress", new GenerationProgressToolbarItem());
toolbar.install("brand", new BrandToolbarItem());
}
}
|
Make uvloop except be explicit ImportError | #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
from MoMMI.master import master
def main() -> None:
version = sys.version_info
if version.major < 3 or (version.major == 3 and version.minor < 6):
logging.critical("You need at least Python 3.6 to run MoMMI.")
sys.exit(1)
setup_logs()
parser = argparse.ArgumentParser()
parser.add_argument("--config-dir", "-c",
default="./config",
help="The directory to read config files from.",
dest="config",
type=Path)
parser.add_argument("--storage-dir", "-s",
default="./data",
help="The directory to use for server data storage.",
dest="data",
type=Path)
args = parser.parse_args()
master.start(args.config, args.data)
if __name__ == "__main__":
main()
| #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except:
pass
from MoMMI.master import master
def main() -> None:
version = sys.version_info
if version.major < 3 or (version.major == 3 and version.minor < 6):
logging.critical("You need at least Python 3.6 to run MoMMI.")
sys.exit(1)
setup_logs()
parser = argparse.ArgumentParser()
parser.add_argument("--config-dir", "-c",
default="./config",
help="The directory to read config files from.",
dest="config",
type=Path)
parser.add_argument("--storage-dir", "-s",
default="./data",
help="The directory to use for server data storage.",
dest="data",
type=Path)
args = parser.parse_args()
master.start(args.config, args.data)
if __name__ == "__main__":
main()
|
Adjust the CI job name. |
var job_name = "liveoak";
var CI = function() {
this.json_url = "https://projectodd.ci.cloudbees.com/job/" + job_name + "/api/json?depth=1";
$.ajax( {
url: this.json_url,
jsonp: 'jsonp',
dataType: 'jsonp',
type: 'GET',
success: this.handle_job_jsonp,
} );
}
CI.prototype = {
handle_job_jsonp: function(data) {
var builds = data.builds;
console.log(builds);
$(builds).each( function(i, build) {
try {
var sha1 = build.actions[2].lastBuiltRevision.SHA1;
} catch ( ignored ) {
sha1 = '';
}
var timestamp = new Date( build.timestamp );
$('#builds').append(
$('<tr class="' + build.result + '">').append(
$( '<td>' ).append( build.number )
).append(
$( '<td style="font-size:smaller">' ).append( timestamp.toUTCString() )
).append(
$( '<td>' ).append( $('<a>').attr('href', build.url).append( build.result.toLowerCase() ) )
).append(
$( '<td>' ).append( sha1.substring(0,7) )
)
);
} );
},
}
var ci = new CI();
|
var job_name = "experimental";
var CI = function() {
this.json_url = "https://projectodd.ci.cloudbees.com/job/" + job_name + "/api/json?depth=1";
$.ajax( {
url: this.json_url,
jsonp: 'jsonp',
dataType: 'jsonp',
type: 'GET',
success: this.handle_job_jsonp,
} );
}
CI.prototype = {
handle_job_jsonp: function(data) {
var builds = data.builds;
console.log(builds);
$(builds).each( function(i, build) {
try {
var sha1 = build.actions[2].lastBuiltRevision.SHA1;
} catch ( ignored ) {
sha1 = '';
}
var timestamp = new Date( build.timestamp );
$('#builds').append(
$('<tr class="' + build.result + '">').append(
$( '<td>' ).append( build.number )
).append(
$( '<td style="font-size:smaller">' ).append( timestamp.toUTCString() )
).append(
$( '<td>' ).append( $('<a>').attr('href', build.url).append( build.result.toLowerCase() ) )
).append(
$( '<td>' ).append( sha1.substring(0,7) )
)
);
} );
},
}
var ci = new CI();
|
Fix Python module search path | from utils.helpers import error, find_mbed_dir, is_mbed_dir
import sys, os
from utils import set_project_dir
from commands.set import CmdSet
from commands.get import CmdGet
from commands.clone import CmdClone
from commands.compile import CmdCompile
from commands.list import CmdList
################################################################################
# Local functions
def help_and_exit(cmds):
error("Syntax: mbed <command> [arguments]")
error("Valid commands:")
for c in cmds:
error(" " + c.get_help() + "")
os._exit(1)
def run(args):
cmds = [CmdSet(), CmdGet()]
if is_mbed_dir():
cmds = cmds + [CmdCompile(), CmdList()]
else:
cmds = cmds = [CmdClone()]
if len(args) == 0:
error("No command given.")
help_and_exit(cmds)
cmd_map = dict([(c.get_name(), c) for c in cmds])
cmd = args[0].lower()
if not cmd in cmd_map:
error("Invalid command '%s'." % args[0])
help_and_exit(cmds)
res = cmd_map[cmd](args[1:])
if res == None:
error("Invalid command syntax")
error(cmd_map[cmd].get_help())
elif res == False:
os._exit(1)
################################################################################
# Entry point
if __name__ == "__main__":
base = find_mbed_dir()
if base:
set_project_dir(base)
sys.path.append(base)
run(sys.argv[1:])
| from utils.helpers import error, find_mbed_dir, is_mbed_dir
import sys, os
from utils import set_project_dir
from commands.set import CmdSet
from commands.get import CmdGet
from commands.clone import CmdClone
from commands.compile import CmdCompile
from commands.list import CmdList
################################################################################
# Local functions
def help_and_exit(cmds):
error("Syntax: mbed <command> [arguments]")
error("Valid commands:")
for c in cmds:
error(" " + c.get_help() + "")
os._exit(1)
def run(args):
cmds = [CmdSet(), CmdGet()]
if is_mbed_dir():
cmds = cmds + [CmdCompile(), CmdList()]
else:
cmds = cmds = [CmdClone()]
if len(args) == 0:
error("No command given.")
help_and_exit(cmds)
cmd_map = dict([(c.get_name(), c) for c in cmds])
cmd = args[0].lower()
if not cmd in cmd_map:
error("Invalid command '%s'." % args[0])
help_and_exit(cmds)
res = cmd_map[cmd](args[1:])
if res == None:
error("Invalid command syntax")
error(cmd_map[cmd].get_help())
elif res == False:
os._exit(1)
################################################################################
# Entry point
if __name__ == "__main__":
set_project_dir(find_mbed_dir())
run(sys.argv[1:])
|
Remove URL test due to bad validator | import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
| import json
import unittest
import requests
import validators
class DomainsTests(unittest.TestCase):
def test_json_is_valid(self):
with open("../world_universities_and_domains.json") as json_file:
valid_json = json.load(json_file)
for university in valid_json:
self.assertIn("name", university)
self.assertIn("domains", university)
self.assertIsInstance(university["domains"], list)
for domain in university["domains"]:
self.assertTrue(validators.domain(domain))
self.assertIn("web_pages", university)
self.assertIsInstance(university["web_pages"], list)
for web_page in university["web_pages"]:
self.assertTrue(validators.url(web_page))
self.assertIn("alpha_two_code", university)
self.assertIn("state-province", university)
self.assertIn("country", university)
def check_is_alive():
""" check url then if url isn't alive, add to file """
with open('../world_universities_and_domains.json') as json_raw:
universities = json.load(json_raw)
for university in universities[:]:
try:
for web_page in university["web_pages"]:
print(web_page)
requests.get(web_page, allow_redirects=False, timeout=10.0)
except requests.exceptions.ConnectionError as exc:
print('- Website doesn\'t exists: ', exc)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
Fix OpDateFormat test in other time zones and separate into dedicated methods | package com.addthis.hydra.data.query;
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
public class TestOpDateFormat extends TestOp {
@Test
public void testConvertDatesInPlace() throws Exception {
doOpTest(
new DataTableHelper().
tr().td("140101").
tr().td("140108"),
"datef=0:yyMMdd:yyww",
new DataTableHelper().
tr().td("1401").
tr().td("1402")
);
}
@Test
public void testConvertDatesDifferentColumn() throws Exception {
doOpTest(
new DataTableHelper().
tr().td("140101", "0").
tr().td("140108", "0"),
"datef=0:yyMMdd:yyww:1",
new DataTableHelper().
tr().td("140101", "1401").
tr().td("140108", "1402")
);
}
@Test
public void testParseUnixMillis() throws Exception {
long testTimeMillis = 1418078000000l;
String outputFormat = "yyMMdd";
// Manually convert the test-time to yyMMdd in the local time zone
String expectedResult = DateTimeFormat.forPattern(outputFormat).print(testTimeMillis);
doOpTest(
new DataTableHelper().
tr().td(Long.toString(testTimeMillis), "0"),
String.format("datef=0:unixmillis:%s:1", outputFormat),
new DataTableHelper().
tr().td(Long.toString(testTimeMillis), expectedResult)
);
}
}
| package com.addthis.hydra.data.query;
import org.junit.Test;
public class TestOpDateFormat extends TestOp {
@Test
public void testOpDateFormat() throws Exception {
doOpTest(
new DataTableHelper().
tr().td("140101").
tr().td("140108"),
"datef=0:yyMMdd:yyww",
new DataTableHelper().
tr().td("1401").
tr().td("1402")
);
doOpTest(
new DataTableHelper().
tr().td("140101", "0").
tr().td("140108", "0"),
"datef=0:yyMMdd:yyww:1",
new DataTableHelper().
tr().td("140101", "1401").
tr().td("140108", "1402")
);
doOpTest(
new DataTableHelper().
tr().td("1418078000000", "0"),
"datef=0:unixmillis:yyMMdd:1",
new DataTableHelper().
tr().td("1418078000000", "141208")
);
}
}
|
Add a few debug logs | import debugModule from "debug";
const debug = debugModule("debugger:session:selectors");
import { createSelectorTree, createLeaf } from "reselect-tree";
import evm from "lib/evm/selectors";
import solidity from "lib/solidity/selectors";
const session = createSelectorTree({
/**
* session.info
*/
info: {
/**
* session.info.affectedInstances
*/
affectedInstances: createLeaf(
[evm.info.instances, evm.info.contexts, solidity.info.sources, solidity.info.sourceMaps],
(instances, contexts, sources, sourceMaps) => Object.assign({},
...Object.entries(instances).map(
([address, {context}]) => {
debug("instances %O", instances);
debug("contexts %O", contexts);
let { contractName, binary } = contexts[context];
let { sourceMap } = sourceMaps[context];
let { source } = sourceMap ?
// look for source ID between second and third colons (HACK)
sources[sourceMap.match(/^[^:]+:[^:]+:([^:]+):/)[1]] :
{};
return {
[address]: {
contractName, source, binary
}
};
}
)
)
)
}
});
export default session;
| import debugModule from "debug";
const debug = debugModule("debugger:session:selectors");
import { createSelectorTree, createLeaf } from "reselect-tree";
import evm from "lib/evm/selectors";
import solidity from "lib/solidity/selectors";
const session = createSelectorTree({
/**
* session.info
*/
info: {
/**
* session.info.affectedInstances
*/
affectedInstances: createLeaf(
[evm.info.instances, evm.info.contexts, solidity.info.sources, solidity.info.sourceMaps],
(instances, contexts, sources, sourceMaps) => Object.assign({},
...Object.entries(instances).map(
([address, {context}]) => {
let { contractName, binary } = contexts[context];
let { sourceMap } = sourceMaps[context];
let { source } = sourceMap ?
// look for source ID between second and third colons (HACK)
sources[sourceMap.match(/^[^:]+:[^:]+:([^:]+):/)[1]] :
{};
return {
[address]: {
contractName, source, binary
}
};
}
)
)
)
}
});
export default session;
|
Refactor the selected $watch callback to be defined as a method on $scope | import 'angular';
export default [function () {
return {
restrict: 'E',
transclude: true,
replace: true,
templateUrl: '/modules/ui-kit/sol-tabs/sol-tabs.html',
scope: {
selected: '@'
},
link: function ($scope, $element, $attrs) {
Object.assign($scope, {
get tabs () {
return $element.find('[tab-id]').toArray().map((o) => {
return {
id: o.getAttribute('tab-id'),
title: o.getAttribute('tab-title'),
icon: o.getAttribute('tab-icon'),
$el: o
};
});
},
select: (selected) => {
$scope.selected = selected;
},
getIconClass: (icon) => {
if (!!icon)
return 'fa fa-' + icon;
return '';
},
applySelection: () => {
let selected = parseInt($scope.selected, 10) || 0;
if ($scope.tabs.length) {
$scope.tabs.forEach((tab) => {
$element.find(`[tab-id="${tab.id}"]`)[0].removeAttribute('selected');
});
let selectedId = $scope.tabs[selected].id;
$element.find(`[tab-id="${selectedId}"]`)[0].setAttribute('selected', '');
}
}
});
$scope.$watch('selected', $scope.applySelection);
}
};
}];
| import 'angular';
export default [function () {
return {
restrict: 'E',
transclude: true,
replace: true,
templateUrl: '/modules/ui-kit/sol-tabs/sol-tabs.html',
scope: {
selected: '@'
},
link: function ($scope, $element, $attrs) {
Object.assign($scope, {
get tabs () {
return $element.find('[tab-id]').toArray().map((o) => {
return {
id: o.getAttribute('tab-id'),
title: o.getAttribute('tab-title'),
icon: o.getAttribute('tab-icon'),
$el: o
};
});
},
select: (selected) => {
$scope.selected = selected;
},
getIconClass: (icon) => {
if (!!icon)
return 'fa fa-' + icon;
return '';
}
});
$scope.$watch('selected', (selected) => {
selected = parseInt(selected, 10) || 0;
if ($scope.tabs.length) {
$scope.tabs.forEach((tab) => {
$element.find(`[tab-id="${tab.id}"]`)[0].removeAttribute('selected');
});
let selectedId = $scope.tabs[selected].id;
$element.find(`[tab-id="${selectedId}"]`)[0].setAttribute('selected', '');
}
});
}
};
}];
|
Fix 0 coming out as empty cell | <?php
namespace AM2Studio\Laravel\Exporter;
trait Exporter
{
public function exportOneSheet($collection, array $columns, $title, $filename, $format = 'xls', $creator = '', $company = '')
{
$rows = [];
$rows[] = array_values($columns);
foreach ($collection as $item) {
$row = [];
foreach ($columns as $attribute => $title) {
$pos = strpos($attribute, '.');
if ($pos !== false) {
$right = $attribute;
while ($pos !== false) {
$left = substr($right, 0, $pos);
$right = substr($right, ($pos + 1));
$pos = strpos($right, '.');
$relation = $item->$left;
}
$row[] = $relation->$right;
} else {
$row[] = $item->$attribute;
}
}
$rows[] = $row;
};
return \Maatwebsite\Excel\Facades\Excel::create($filename, function ($excel) use ($rows, $title, $creator, $company) {
$excel->setTitle($title);
$excel->setCreator($creator)->setCompany($company);
$excel->sheet($title, function ($sheet) use ($rows) {
$sheet->fromArray($rows, null, 'A1', true, false);
});
})->download($format);
}
public function exportMoreSheets($headings, $model, $config)
{
exit('not implemented');
}
}
| <?php
namespace AM2Studio\Laravel\Exporter;
trait Exporter
{
public function exportOneSheet($collection, array $columns, $title, $filename, $format = 'xls', $creator = '', $company = '')
{
$rows = [];
$rows[] = array_values($columns);
foreach ($collection as $item) {
$row = [];
foreach ($columns as $attribute => $title) {
$pos = strpos($attribute, '.');
if ($pos !== false) {
$right = $attribute;
while ($pos !== false) {
$left = substr($right, 0, $pos);
$right = substr($right, ($pos + 1));
$pos = strpos($right, '.');
$relation = $item->$left;
}
$row[] = $relation->$right;
} else {
$row[] = $item->$attribute;
}
}
$rows[] = $row;
};
return \Maatwebsite\Excel\Facades\Excel::create($filename, function ($excel) use ($rows, $title, $creator, $company) {
$excel->setTitle($title);
$excel->setCreator($creator)->setCompany($company);
$excel->sheet($title, function ($sheet) use ($rows) {
$sheet->fromArray($rows, null, 'A1', false, false);
});
})->download($format);
}
public function exportMoreSheets($headings, $model, $config)
{
exit('not implemented');
}
}
|
Add position to price selector | var timeout = 20000;
var demoCommands = {
getSelector: function(client) {
if(client.globals.environment === 'xvfb_mobile')
return this.elements.searchResult.selector;
else
return this.elements.filters.selector;
},
chooseCategory4K: function(client) {
return this .waitForElementPresent('@category4K', timeout)
.click('@category4K')
},
clickColumnView: function(client) {
return this .waitForElementPresent('@columnView', timeout)
.click('@columnView')
},
clickFirstElementList: function(client) {
return this .waitForElementPresent('@firstProduct', timeout)
.click('@firstProduct')
}
};
module.exports = {
commands: [demoCommands],
elements: {
searchResult: {
selector: '.nav-search-input'
},
filters: {
selector: '.applied-fliter'
},
category4K: {
selector: '[href="http://televisores.mercadolibre.com.ar/televisores/tv-4k/tv-led-hd"]'
},
columnView: {
selector: '[href="http://televisores.mercadolibre.com.ar/televisores/tv-4k/tv-led-hd_DisplayType_G"]'
},
firstProduct: {
selector: '.article:nth-of-type(1)'
},
itemTitle: {
selector: '.list-view-item-title'
},
itemPrice: {
selector: '.ch-price:nth-of-type(1)'
}
}
}; | var timeout = 20000;
var demoCommands = {
getSelector: function(client) {
if(client.globals.environment === 'xvfb_mobile')
return this.elements.searchResult.selector;
else
return this.elements.filters.selector;
},
chooseCategory4K: function(client) {
return this .waitForElementPresent('@category4K', timeout)
.click('@category4K')
},
clickColumnView: function(client) {
return this .waitForElementPresent('@columnView', timeout)
.click('@columnView')
},
clickFirstElementList: function(client) {
return this .waitForElementPresent('@firstProduct', timeout)
.click('@firstProduct')
}
};
module.exports = {
commands: [demoCommands],
elements: {
searchResult: {
selector: '.nav-search-input'
},
filters: {
selector: '.applied-fliter'
},
category4K: {
selector: '[href="http://televisores.mercadolibre.com.ar/televisores/tv-4k/tv-led-hd"]'
},
columnView: {
selector: '[href="http://televisores.mercadolibre.com.ar/televisores/tv-4k/tv-led-hd_DisplayType_G"]'
},
firstProduct: {
selector: '.article'
},
itemTitle: {
selector: '.list-view-item-title'
},
itemPrice: {
selector: '.ch-price'
}
}
}; |
Fix push stream prototype constructor. | define([
'./stream',
'../functional/isFunction',
'../functional/isDefined',
'../functional/invoke'
], function (Stream, isFunction, isDefined, invoke) {
'use strict';
/**
* @param {Function} [implementation]
* @param {Function} [destroy]
* @constructor
*/
function PushStream(implementation, destroy) {
var callbacks = [], self = this;
Stream.call(this, function (sinkNext, sinkError, sinkComplete) {
isFunction(implementation) && implementation(sinkNext, sinkError, sinkComplete);
callbacks.push({
value: sinkNext,
error: sinkError,
complete: sinkComplete
});
});
function push(value, error) {
if (isDefined(error)) {
invoke(callbacks, 'error', error, self);
} else if (isDefined(value)) {
invoke(callbacks, 'value', value);
} else {
invoke(callbacks, 'complete');
isFunction(destroy) && destroy();
}
}
this.push = push;
}
PushStream.constructor = PushStream;
PushStream.prototype = Object.create(Stream.prototype);
PushStream.prototype.constructor = PushStream;
return PushStream;
});
| define([
'./stream',
'../functional/isFunction',
'../functional/isDefined',
'../functional/invoke'
], function (Stream, isFunction, isDefined, invoke) {
'use strict';
/**
* @param {Function} [implementation]
* @param {Function} [destroy]
* @constructor
*/
function PushStream(implementation, destroy) {
var callbacks = [], self = this;
Stream.call(this, function (sinkNext, sinkError, sinkComplete) {
isFunction(implementation) && implementation(sinkNext, sinkError, sinkComplete);
callbacks.push({
value: sinkNext,
error: sinkError,
complete: sinkComplete
});
});
function push(value, error) {
if (isDefined(error)) {
invoke(callbacks, 'error', error, self);
} else if (isDefined(value)) {
invoke(callbacks, 'value', value);
} else {
invoke(callbacks, 'complete');
isFunction(destroy) && destroy();
}
}
this.push = push;
}
PushStream.constructor = PushStream;
PushStream.prototype = Object.create(Stream.prototype);
return PushStream;
});
|
Add 1 level depth and also categories fields to employee serializer | from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'categories',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
| from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
Revert "We shouldn’t clear history, since we’re starting a new history file."
Yeah. That was a brain fart. We absolutely should.
This reverts commit 939eec2127dd22534ccabc81d9411ad870176c4e. | <?php
/*
* This file is part of Psy Shell
*
* (c) 2013 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Readline;
use Psy\Readline\Libedit;
class LibeditTest extends \PHPUnit_Framework_TestCase
{
private $historyFile;
private $readline;
public function setUp()
{
if (!function_exists('readline')) {
$this->markTestSkipped('Libedit not enabled');
}
if (`which unvis 2>/dev/null` === null) {
$this->markTestSkipped('Missing unvis library');
}
readline_clear_history();
$this->historyFile = tempnam(sys_get_temp_dir().'/psysh/test/', 'history');
$this->readline = new Libedit($this->historyFile);
}
public function testHistory()
{
$this->assertEmpty($this->readline->listHistory());
$this->readline->addHistory('foo');
$this->assertEquals(array('foo'), $this->readline->listHistory());
$this->readline->addHistory('bar');
$this->assertEquals(array('foo', 'bar'), $this->readline->listHistory());
$this->readline->addHistory('baz');
$this->assertEquals(array('foo', 'bar', 'baz'), $this->readline->listHistory());
$this->readline->clearHistory();
$this->assertEmpty($this->readline->listHistory());
}
}
| <?php
/*
* This file is part of Psy Shell
*
* (c) 2013 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Psy\Test\Readline;
use Psy\Readline\Libedit;
class LibeditTest extends \PHPUnit_Framework_TestCase
{
private $historyFile;
private $readline;
public function setUp()
{
if (!function_exists('readline')) {
$this->markTestSkipped('Libedit not enabled');
}
if (`which unvis 2>/dev/null` === null) {
$this->markTestSkipped('Missing unvis library');
}
$this->historyFile = tempnam(sys_get_temp_dir().'/psysh/test/', 'history');
$this->readline = new Libedit($this->historyFile);
}
public function testHistory()
{
$this->assertEmpty($this->readline->listHistory());
$this->readline->addHistory('foo');
$this->assertEquals(array('foo'), $this->readline->listHistory());
$this->readline->addHistory('bar');
$this->assertEquals(array('foo', 'bar'), $this->readline->listHistory());
$this->readline->addHistory('baz');
$this->assertEquals(array('foo', 'bar', 'baz'), $this->readline->listHistory());
$this->readline->clearHistory();
$this->assertEmpty($this->readline->listHistory());
}
}
|
:hammer: Fix Travis CI build error | // Karma configuration
// Generated on Wed Aug 30 2017 09:45:21 GMT+0800 (中国标准时间)
const karmaConfig = require('./karma.conf.common.js')
module.exports = function(config) {
config.set(
Object.assign(
{},
karmaConfig,
{
browserStack: {
username: 'shianqi',
accessKey: 'f1d96776-1238-4ae3-b015-36118bef1a1a',
retryLimit: 5,
captureTimeout: 1800,
timeout: 1800,
concurrency: 2,
browserNoActivityTimeout: 1800,
browserDisconnectTimeout: 1800,
browserDisconnectTolerance: 3,
pollingTimeout: 30000
},
customLaunchers: {
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
browser_version: '55.0',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefix_mac: {
base: 'BrowserStack',
os: 'OS X',
os_version: 'Sierra',
browser: 'firefox',
browser_version: '50.0'
},
bs_ie9_windows: {
base: 'BrowserStack',
browser: 'ie',
browser_version: '9.0',
os: 'Windows',
os_version: '7'
}
},
browsers: [
'bs_chrome_mac',
'bs_firefix_mac'
],
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
}
)
)
}
| // Karma configuration
// Generated on Wed Aug 30 2017 09:45:21 GMT+0800 (中国标准时间)
const karmaConfig = require('./karma.conf.common.js')
module.exports = function(config) {
config.set(
Object.assign(
{},
karmaConfig,
{
customLaunchers: {
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
browser_version: '55.0',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefix_mac: {
base: 'BrowserStack',
os: 'OS X',
os_version: 'Sierra',
browser: 'firefox',
browser_version: '50.0'
},
bs_ie9_windows: {
base: 'BrowserStack',
browser: 'ie',
browser_version: '9.0',
os: 'Windows',
os_version: '7'
}
},
browsers: [
'bs_chrome_mac',
'bs_firefix_mac'
],
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
}
)
)
}
|
Use library to print matrices. | import CtCILibrary.AssortedMethods;
import org.junit.Test;
import static org.junit.Assert.*;
public class Q6Test {
interface RotateMatrix90 {
void rotate90(int[][] mat);
}
public void testRotateMatrix90(RotateMatrix90 rotateMatrix90) {
int[][] inputMatrix = {
{1,2,3},
{4,5,6},
{7,8,9}};
int[][] outputMatrix = {
{3,6,9},
{2,5,8},
{1,4,7}};
int[][] expectedOutputMatrix = {
{1,2,3},
{4,5,6},
{7,8,9}};
rotateMatrix90.rotate90(outputMatrix);
System.out.println("Input:");
AssortedMethods.printMatrix(inputMatrix);
System.out.println();
System.out.println();
System.out.println("Expected output:");
AssortedMethods.printMatrix(expectedOutputMatrix);
System.out.println();
System.out.println();
System.out.println("Output:");
AssortedMethods.printMatrix(outputMatrix);
System.out.println();
System.out.println();
assertArrayEquals(expectedOutputMatrix, outputMatrix);
}
@Test
public void testRotateMatrix90_InPlace() throws Exception {
testRotateMatrix90(Q6::rotateMatrix90_InPlace);
}
} | import org.junit.Test;
import static org.junit.Assert.*;
public class Q6Test {
interface RotateMatrix90 {
void rotate90(int[][] mat);
}
public void testRotateMatrix90(RotateMatrix90 rotateMatrix90) {
int[][] inputMatrix = {
{1,2,3},
{4,5,6},
{7,8,9}};
int[][] outputMatrix = {
{3,6,9},
{2,5,8},
{1,4,7}};
int[][] expectedOutputMatrix = {
{1,2,3},
{4,5,6},
{7,8,9}};
rotateMatrix90.rotate90(outputMatrix);
System.out.println("Input:");
printMatrix(inputMatrix);
System.out.println();
System.out.println();
System.out.println("Expected output:");
printMatrix(expectedOutputMatrix);
System.out.println();
System.out.println();
System.out.println("Output:");
printMatrix(outputMatrix);
System.out.println();
System.out.println();
assertArrayEquals(expectedOutputMatrix, outputMatrix);
}
@Test
public void testRotateMatrix90_InPlace() throws Exception {
testRotateMatrix90(Q6::rotateMatrix90_InPlace);
}
private static void printMatrix(int[][] a) {
for (int[] row : a) {
for (int col : row) {
System.out.print(col + " ");
}
System.out.println();
}
}
} |
Fix req stream race condition due to middleware | // Requires
var _ = require('underscore');
var express = require('express');
function setup(options, imports, register) {
// Import
var app = imports.server.app;
var workspace = imports.workspace;
// Apply middlewares
app.use(express.cookieParser());
app.use(express.cookieSession({
key: ['sess', workspace.id].join('.'),
secret: workspace.secret,
}));
// Get User and set it to res object
app.use(function getUser(req, res, next) {
// Pause request stream
req.pause();
var uid = req.session.userId;
if(uid) {
return workspace.getUser(uid)
.then(function(user) {
// Set user
res.user = user;
next();
})
.fail(function(err) {
res.user = null;
next();
});
}
return next();
});
// Block queries for unAuthenticated users
var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list'];
app.use(function filterAuth(req, res, next) {
// Resume request now
// So our handlers can use it as a stream
req.resume();
if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) {
return next();
}
// Unauthorized
return res.send(403, {
ok: false,
data: {},
error: "Could not run RPC request because user has not authenticated",
method: req.path,
});
});
// Register
register(null, {});
}
// Exports
module.exports = setup;
| // Requires
var _ = require('underscore');
var express = require('express');
function setup(options, imports, register) {
// Import
var app = imports.server.app;
var workspace = imports.workspace;
// Apply middlewares
app.use(express.cookieParser());
app.use(express.cookieSession({
key: ['sess', workspace.id].join('.'),
secret: workspace.secret,
}));
// Get User and set it to res object
app.use(function getUser(req, res, next) {
var uid = req.session.userId;
if(uid) {
return workspace.getUser(uid)
.then(function(user) {
// Set user
res.user = user;
next();
})
.fail(function(err) {
res.user = null;
next();
});
}
return next();
});
// Block queries for unAuthenticated users
var AUTHORIZED_PATHS = ['/', '/auth/join', '/users/list'];
app.use(function filterAuth(req, res, next) {
if(_.contains(AUTHORIZED_PATHS, req.path) || res.user) {
return next();
}
// Unauthorized
return res.send(403, {
ok: false,
data: {},
error: "Could not run RPC request because user has not authenticated",
method: req.path,
});
});
// Register
register(null, {});
}
// Exports
module.exports = setup;
|
Use bold line number for verse. | from bs4 import BeautifulSoup
from bs4 import Comment
from bs4 import NavigableString
import plumeria.util.http as http
from plumeria.command import commands, CommandError
from plumeria.command.parse import Text
from plumeria.util.ratelimit import rate_limit
@commands.register("bible", "esv", category="Search", params=[Text('verse')])
@rate_limit()
async def search_esv(message, verse):
"""
Search for a bible passage from the English Standard Version.
Example::
bible Romans 12:16
"""
r = await http.get("http://www.esvapi.org/v2/rest/passageQuery", params={
"key": "IP",
"passage": verse,
"output-format": "crossway-xml-1.0"
})
doc = BeautifulSoup(r.text(), features="lxml")
if not doc.passage:
raise CommandError("Verse not found.")
lines = []
for verse_unit in doc.passage.content.find_all('verse-unit'):
num = int(verse_unit.find('verse-num').text)
woc = verse_unit.find('woc')
if woc:
text = woc.text
else:
text = "".join([str(node) for node in verse_unit.children
if isinstance(node, NavigableString) and not isinstance(node, Comment)])
lines.append("**{}** {}".format(num, text.strip()))
return "\n".join(lines)
| from bs4 import BeautifulSoup
from bs4 import Comment
from bs4 import NavigableString
import plumeria.util.http as http
from plumeria.command import commands, CommandError
from plumeria.command.parse import Text
from plumeria.util.ratelimit import rate_limit
@commands.register("bible", "esv", category="Search", params=[Text('verse')])
@rate_limit()
async def search_esv(message, verse):
"""
Search for a bible passage from the English Standard Version.
Example::
bible Romans 12:16
"""
r = await http.get("http://www.esvapi.org/v2/rest/passageQuery", params={
"key": "IP",
"passage": verse,
"output-format": "crossway-xml-1.0"
})
doc = BeautifulSoup(r.text(), features="lxml")
if not doc.passage:
raise CommandError("Verse not found.")
lines = []
for verse_unit in doc.passage.content.find_all('verse-unit'):
num = int(verse_unit.find('verse-num').text)
woc = verse_unit.find('woc')
if woc:
text = woc.text
else:
text = "".join([str(node) for node in verse_unit.children
if isinstance(node, NavigableString) and not isinstance(node, Comment)])
lines.append("({}) {}".format(num, text.strip()))
return "\n".join(lines)
|
Update record temperature to use the stored sensors | var ds18b20 = require('ds18b20');
var crontab = require('node-crontab');
var config = require('../config.json');
var logger = require('./logger.js');
var sensors = [];
function recordTemperature() {
sensors.forEach(function (sensor) {
ds18b20.temperature(sensor, function(err, value) {
logger.log(value);
});
});
};
function setupSensors() {
var promise = new Promise(function (resolve, reject) {
var tmpSensors;
var response;
tmpSensors = [];
ds18b20.sensors(function(err, ids) {
for(index in ids){
tmpSensors.push(ids[index]);
console.log(ids[index]);
}
console.log('Are all sensors accounted for? [y/n] ');
prompt.start();
prompt.get(['inputResponse'], function (err, result) {
if (result.inputResponse.toLowerCase() == 'y') {
resolve(tmpSensors);
} else {
reject('Please reconnect sensors and retry.');
}
});
});
});
return promise;
};
var jobId = crontab.scheduleJob(config.schedule, recordTemperature);
console.log('CronJob scheduled: '+ jobId);
recordTemperature(); | var ds18b20 = require('ds18b20');
var crontab = require('node-crontab');
var config = require('../config.json');
var logger = require('./logger.js');
function recordTemperature(){
ds18b20.sensors(function(err, ids) {
for(index in ids){
ds18b20.temperature(ids[index], function(err, value) {
var sensors = [];
logger.log(value);
});
}
});
}
function setupSensors() {
var promise = new Promise(function (resolve, reject) {
var tmpSensors;
var response;
tmpSensors = [];
ds18b20.sensors(function(err, ids) {
for(index in ids){
tmpSensors.push(ids[index]);
console.log(ids[index]);
}
console.log('Are all sensors accounted for? [y/n] ');
prompt.start();
prompt.get(['inputResponse'], function (err, result) {
if (result.inputResponse.toLowerCase() == 'y') {
resolve(tmpSensors);
} else {
reject('Please reconnect sensors and retry.');
}
});
});
});
return promise;
};
var jobId = crontab.scheduleJob(config.schedule, recordTemperature);
console.log('CronJob scheduled: '+ jobId);
recordTemperature(); |
Remove use of 'share()' in provider to be laravel 5.4 compatible | <?php
namespace Chalcedonyt\Specification\Providers;
use Chalcedonyt\Specification\Commands\SpecificationGeneratorCommand;
use Illuminate\Support\ServiceProvider;
class SpecificationServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$source_config = __DIR__ . '/../config/specification.php';
$this->publishes([$source_config => '../config/specification.php'], 'config');
$this->loadViewsFrom(__DIR__ . '/../views', 'specification');
}
/**
* Register any package services.
*
* @return void
*/
public function register()
{
$source_config = __DIR__ . '/../config/specification.php';
$this->mergeConfigFrom($source_config, 'specification');
// register our command here
$this->app->singleton('command.specification.generate',
function ($app) {
return new SpecificationGeneratorCommand($app['config'], $app['view'], $app['files']);
}
);
$this->commands('command.specification.generate');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['specification', 'command.specification.generate'];
}
}
| <?php
namespace Chalcedonyt\Specification\Providers;
use Chalcedonyt\Specification\Commands\SpecificationGeneratorCommand;
use Illuminate\Support\ServiceProvider;
class SpecificationServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$source_config = __DIR__ . '/../config/specification.php';
$this->publishes([$source_config => '../config/specification.php'], 'config');
$this->loadViewsFrom(__DIR__ . '/../views', 'specification');
}
/**
* Register any package services.
*
* @return void
*/
public function register()
{
$source_config = __DIR__ . '/../config/specification.php';
$this->mergeConfigFrom($source_config, 'specification');
// register our command here
$this->app['command.specification.generate'] = $this->app->share(
function ($app) {
return new SpecificationGeneratorCommand($app['config'], $app['view'], $app['files']);
}
);
$this->commands('command.specification.generate');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['specification', 'command.specification.generate'];
}
}
|
Undo accidental global leakage of sys | #!/usr/bin/env python
import contextlib as __stickytape_contextlib
@__stickytape_contextlib.contextmanager
def __stickytape_temporary_dir():
import tempfile
import shutil
dir_path = tempfile.mkdtemp()
try:
yield dir_path
finally:
shutil.rmtree(dir_path)
with __stickytape_temporary_dir() as __stickytape_working_dir:
def __stickytape_write_module(path, contents):
import os, os.path, errno
def make_package(path):
parts = path.split("/")
partial_path = __stickytape_working_dir
for part in parts:
partial_path = os.path.join(partial_path, part)
if not os.path.exists(partial_path):
os.mkdir(partial_path)
open(os.path.join(partial_path, "__init__.py"), "w").write("\n")
make_package(os.path.dirname(path))
full_path = os.path.join(__stickytape_working_dir, path)
with open(full_path, "w") as module_file:
module_file.write(contents)
import sys as __stickytape_sys
__stickytape_sys.path.insert(0, __stickytape_working_dir)
| #!/usr/bin/env python
import contextlib as __stickytape_contextlib
@__stickytape_contextlib.contextmanager
def __stickytape_temporary_dir():
import tempfile
import shutil
dir_path = tempfile.mkdtemp()
try:
yield dir_path
finally:
shutil.rmtree(dir_path)
with __stickytape_temporary_dir() as __stickytape_working_dir:
def __stickytape_write_module(path, contents):
import os, os.path, errno
def make_package(path):
parts = path.split("/")
partial_path = __stickytape_working_dir
for part in parts:
partial_path = os.path.join(partial_path, part)
if not os.path.exists(partial_path):
os.mkdir(partial_path)
open(os.path.join(partial_path, "__init__.py"), "w").write("\n")
make_package(os.path.dirname(path))
full_path = os.path.join(__stickytape_working_dir, path)
with open(full_path, "w") as module_file:
module_file.write(contents)
import sys
sys.path.insert(0, __stickytape_working_dir)
|
Fix Bot Errors with Selecting Wrong Users
Also fix validation in case the zeroth user isn't correct, which is happening a bunch.
Compare the names casefolded incase of mismatch in capitalization. | from twitch import TwitchClient
class TwitchHandler:
async def validateStream(url, twitch_id):
client = TwitchClient(client_id=twitch_id)
channelName = url.split('/')[-1]
channels = client.search.channels(channelName)
if channels:
for ch in channels:
if ch.name.casefold() == channelName.casefold():
return 'World of Warcraft' in ch.game
return False
async def fetchStreamInfo(url, twitch_id):
client = TwitchClient(client_id=twitch_id)
channelName = url.split('/')[-1]
channels = client.search.channels(channelName)
title = None
description = None
avatar = None
views = None
followers = None
if channels:
channel = channels[0]
for ch in channels:
if ch.name.casefold() == channelName.casefold():
channel = ch
break
avatar = channel.logo
title = channel.status
description = channel.description
views = channel.views
followers = channel.followers
return title, description, avatar, views, followers
| from twitch import TwitchClient
class TwitchHandler:
async def validateStream(url, twitch_id):
client = TwitchClient(client_id=twitch_id)
channelName = url.split('/')[-1]
channels = client.search.channels(channelName)
if channels:
channel = channels[0]
return 'World of Warcraft' in channel.game
return False
async def fetchStreamInfo(url, twitch_id):
client = TwitchClient(client_id=twitch_id)
channelName = url.split('/')[-1]
channels = client.search.channels(channelName)
title = None
description = None
avatar = None
views = None
followers = None
if channels:
channel = channels[0]
for ch in channels:
if ch.display_name == channelName:
channel = ch
break
avatar = channel.logo
title = channel.status
description = channel.description
views = channel.views
followers = channel.followers
return title, description, avatar, views, followers
|
Remove unused middleware stuff and add model events | <?php
return [
'route' => 'warden',
'auth' => [
/*
* Set this to your own custom middleware, just please know that it
* should ensure that the user is logged in.
*/
'middleware' => ['web', 'auth'],
'middleware_api' => ['api'],
],
'views' => [
'base-layout' => 'spark::layouts.app',
],
/**
* Just to make sure that there are fewer things to edit,
* by default we use the auth.model configuration from
* the default location to ensure this will work oob
*/
'models' => [
'user' => [
// For model events themselves, please reference the
// Eloquent events from the laravel docs website.
// Can be seen here: https://laravel.com/docs/master/eloquent#events
'model' => App\Models\User::class,
'relations' => [
'roles' => [
'update' => function($user){
\Log::info('A users roles has been updated');
},
'new' => function ($user){
\Log::info('A users role has been created');
},
'delete' => function ($user){
\Log::info('A users role has been deleted/removed');
}
]
]
],
],
];
| <?php
return [
'route' => 'warden',
'auth' => [
/*
* Set this to your own custom middleware, just please know that it
* should ensure that the user is logged in.
*/
'middleware' => Kregel\Warden\Http\Middleware\Authentication::class,
'middleware_name' => 'custom-auth',
/*
* Name of a login route, it's recommended to have it named, but incase
* that doesn't work we have the 'fail_over_route' config to choose.
*/
'route' => 'login',
/*
* If the desired route does not exist then use the one below instead
* If you plan to use this with Spark, edi the fail_over_route to
* /login instead of /auth/login
*/
'fail_over_route' => '/auth/login',
],
/*
* Actual application configuration
*/
'using' => [
'fontawesome' => true,
'csrf' => true,
],
'views' => [
'base-layout' => 'spark::layouts.app',
],
/**
* Just to make sure that there are fewer things to edit,
* by default we use the auth.model configuration from
* the default location to ensure this will work oob
*/
'models' => [
'user' => [
// For model events themselves, please reference the
// Eloquent events from the laravel docs website.
// Can be seen here: https://laravel.com/docs/5.1/eloquent#events
'model' => App\Models\User::class,
'relations' => [
'roles' => [
'update' => function($user){
\Log::info('A users roles has been updated');
},
'new' => function ($user){
\Log::info('A users role has been created');
},
'delete' => function ($user){
\Log::info('A users role has been deleted/removed');
}
]
]
],
],
];
|
Remove positional argument "name" from Textbox
Users should just use the kwarg name; no sense in having both.
Closes #239 | from .. import bar, manager
import base
class TextBox(base._TextBox):
"""
A flexible textbox that can be updated from bound keys, scripts and
qsh.
"""
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("fontshadow", None,
"font shadow color, default is None(no shadow)"),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, text=" ", width=bar.CALCULATED, **config):
"""
- text: Initial widget text.
- width: An integer width, bar.STRETCH, or bar.CALCULATED .
"""
base._TextBox.__init__(self, text, width, **config)
def update(self, text):
self.text = text
self.bar.draw()
def cmd_update(self, text):
"""
Update the text in a TextBox widget.
"""
self.update(text)
def cmd_get(self):
"""
Retrieve the text in a TextBox widget.
"""
return self.text
| from .. import bar, manager
import base
class TextBox(base._TextBox):
"""
A flexible textbox that can be updated from bound keys, scripts and
qsh.
"""
defaults = manager.Defaults(
("font", "Arial", "Text font"),
("fontsize", None, "Font pixel size. Calculated if None."),
("fontshadow", None,
"font shadow color, default is None(no shadow)"),
("padding", None, "Padding left and right. Calculated if None."),
("background", None, "Background colour."),
("foreground", "#ffffff", "Foreground colour.")
)
def __init__(self, name, text=" ", width=bar.CALCULATED, **config):
"""
- name: Name for this widget. Used to address the widget from
scripts, commands and qsh.
- text: Initial widget text.
- width: An integer width, bar.STRETCH, or bar.CALCULATED .
"""
self.name = name
base._TextBox.__init__(self, text, width, **config)
def update(self, text):
self.text = text
self.bar.draw()
def cmd_update(self, text):
"""
Update the text in a TextBox widget.
"""
self.update(text)
def cmd_get(self):
"""
Retrieve the text in a TextBox widget.
"""
return self.text
|
Remove some Python environment variables from user subprocess environment. | import sys, os, subprocess
remove_vars = ("PYTHONHOME", "PYTHONPATH", "VERSIONER_PYTHON_PREFER_32_BIT")
def make_environment(env=None):
if env is None:
env = os.environ
env = env.copy()
for var in remove_vars:
if var in env:
del env[var]
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONIOENCODING"] = "UTF-8"
return env
def run_shell_command(cmdline, pipe_output=True, env=None, **kwargs):
if sys.platform == "win32":
args = cmdline
else:
args = [os.environ.get("SHELL", "/bin/sh")]
process = subprocess.Popen(args,
stdin = subprocess.PIPE if sys.platform != "win32" else None,
stdout = subprocess.PIPE if pipe_output else None,
stderr = subprocess.STDOUT if pipe_output else None,
bufsize = 1,
close_fds = (sys.platform != "win32"),
shell = (sys.platform == "win32"),
env = make_environment(env),
**kwargs)
if sys.platform != "win32":
process.stdin.write(cmdline)
process.stdin.close()
return process
def kill_shell_process(process, force=False):
if sys.platform != "win32":
signal = "-KILL" if force else "-TERM"
rc = subprocess.call(["pkill", signal, "-P", str(process.pid)])
if rc == 0:
return
if force:
process.kill()
else:
process.terminate()
| import sys, os, subprocess
def make_environment(env=None):
if env is None:
env = os.environ
env = env.copy()
env["PYTHONUNBUFFERED"] = "1"
env["PYTHONIOENCODING"] = "UTF-8"
return env
def run_shell_command(cmdline, pipe_output=True, env=None, **kwargs):
if sys.platform == "win32":
args = cmdline
else:
args = [os.environ.get("SHELL", "/bin/sh")]
process = subprocess.Popen(args,
stdin = subprocess.PIPE if sys.platform != "win32" else None,
stdout = subprocess.PIPE if pipe_output else None,
stderr = subprocess.STDOUT if pipe_output else None,
bufsize = 1,
close_fds = (sys.platform != "win32"),
shell = (sys.platform == "win32"),
env = make_environment(env),
**kwargs)
if sys.platform != "win32":
process.stdin.write(cmdline)
process.stdin.close()
return process
def kill_shell_process(process, force=False):
if sys.platform != "win32":
signal = "-KILL" if force else "-TERM"
rc = subprocess.call(["pkill", signal, "-P", str(process.pid)])
if rc == 0:
return
if force:
process.kill()
else:
process.terminate()
|
BB-562: Add possibility to inject code into forms and view templates
- CR fixes | <?php
namespace Oro\Bundle\UIBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormView;
use Twig_Environment;
use Oro\Bundle\UIBundle\View\ScrollData;
class BeforeListRenderEvent extends Event
{
/**
* @var \Twig_Environment
*/
protected $environment;
/**
* @var ScrollData
*/
protected $scrollData;
/**
* @var FormView|null
*/
protected $formView;
/**
* @param \Twig_Environment $environment
* @param ScrollData $scrollData
* @param FormView|null $formView
*/
public function __construct(Twig_Environment $environment, ScrollData $scrollData, FormView $formView = null)
{
$this->environment = $environment;
$this->scrollData = $scrollData;
$this->formView = $formView;
}
/**
* @return \Twig_Environment
*/
public function getEnvironment()
{
return $this->environment;
}
/**
* @return FormView|null
*/
public function getFormView()
{
return $this->formView;
}
/**
* @return ScrollData
*/
public function getScrollData()
{
return $this->scrollData;
}
/**
* @param ScrollData $scrollData
* @return BeforeListRenderEvent
*/
public function setScrollData(ScrollData $scrollData)
{
$this->scrollData = $scrollData;
return $this;
}
}
| <?php
namespace Oro\Bundle\UIBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormView;
use Twig_Environment;
use Oro\Bundle\UIBundle\View\ScrollData;
class BeforeListRenderEvent extends Event
{
/**
* @var \Twig_Environment
*/
protected $environment;
/**
* @var ScrollData
*/
protected $scrollData;
/**
* @var FormView|null
*/
protected $formView;
/**
* @param \Twig_Environment $environment
* @param ScrollData $scrollData
* @param FormView|null $formView
*/
public function __construct(Twig_Environment $environment, ScrollData $scrollData, FormView $formView = null)
{
$this->formView = $formView;
$this->scrollData = $scrollData;
$this->environment = $environment;
}
/**
* @return \Twig_Environment
*/
public function getEnvironment()
{
return $this->environment;
}
/**
* @return FormView|null
*/
public function getFormView()
{
return $this->formView;
}
/**
* @return ScrollData
*/
public function getScrollData()
{
return $this->scrollData;
}
/**
* @param ScrollData $scrollData
* @return BeforeListRenderEvent
*/
public function setScrollData(ScrollData $scrollData)
{
$this->scrollData = $scrollData;
return $this;
}
}
|
Add wait cursor when loading folder create menu | // folder-create-menu.js
jQuery(function($) {
$('#create-menu').one('click', function() {
var wait = calli.wait();
$.ajax({
type: 'GET',
url: $('#create-menu-json')[0].href + encodeURIComponent(calli.getUserIri()),
xhrFields: calli.withCredentials,
dataType: 'json',
success: function(data) {
var ul = $('#create-menu-more');
var section;
$(data.rows).each(function(){
if (section != this[4]) {
if (section) {
ul.append('<li role="presentation" class="divider"></li>');
}
section = this[4];
var header = $('<li class="dropdown-header"></li>');
header.text(section);
ul.append(header);
}
var li = $('<li></li>');
var a = $('<a role="menuitem"></a>');
a.attr('href', this[0]);
a.text(this[1]);
if (this[2]) {
a.attr('title', this[2]);
}
if (this[3]) {
var img = $('<img class="icon"></img>');
img.attr('src', this[3]);
a.prepend(' ');
a.prepend(img);
}
li.append(a);
ul.append(li);
});
wait.over();
}
});
return true;
});
});
| // folder-create-menu.js
jQuery(function($) {
$('#create-menu').one('click', function() {
$.ajax({
type: 'GET',
url: $('#create-menu-json')[0].href + encodeURIComponent(calli.getUserIri()),
xhrFields: calli.withCredentials,
dataType: 'json',
success: function(data) {
var ul = $('#create-menu-more');
var section;
$(data.rows).each(function(){
if (section != this[4]) {
if (section) {
ul.append('<li role="presentation" class="divider"></li>');
}
section = this[4];
var header = $('<li class="dropdown-header"></li>');
header.text(section);
ul.append(header);
}
var li = $('<li></li>');
var a = $('<a role="menuitem"></a>');
a.attr('href', this[0]);
a.text(this[1]);
if (this[2]) {
a.attr('title', this[2]);
}
if (this[3]) {
var img = $('<img class="icon"></img>');
img.attr('src', this[3]);
a.prepend(' ');
a.prepend(img);
}
li.append(a);
ul.append(li);
});
}
});
return true;
});
});
|
Update bar status query download | import { computed, transaction, action, autorun } from 'mobx'
import { BarQueryDownload } from './barquery.js'
import { config } from '/utils/config.js'
export class BarStatusDownload extends BarQueryDownload {
name = 'bar status'
// update bar status every 30s
cacheInfo = config.defaultRefreshCacheInfo
periodicRefresh = 30
@computed get query() {
return {
BarStatus: {
args: {
/* NOTE: Use require() to resolve cyclic dependency */
barID: this.props.barID,
},
result: {
bar_status: {
qdodger_bar: 'Bool',
taking_orders: 'Bool',
table_service: 'String',
pickup_locations: [{
name: 'String',
open: 'Bool',
}],
}
}
}
}
}
@computed get barStatus() {
return this.lastValue && this.lastValue.bar_status
}
}
| import { computed, transaction, action, autorun } from 'mobx'
import { BarQueryDownload } from './barquery.js'
import { config } from '/utils/config.js'
export class BarStatusDownload extends BarQueryDownload {
name = 'bar status'
// update bar status every 30s
cacheInfo = config.defaultRefreshCacheInfo
periodicRefresh = 30
@computed get query() {
return {
BarStatus: {
args: {
/* NOTE: Use require() to resolve cyclic dependency */
barID: this.props.barID,
},
result: {
bar_status: {
qdodger_bar: 'Bool',
taking_orders: 'Bool',
table_service: 'String',
pickup_locations: ['String'],
}
}
}
}
}
@computed get barStatus() {
return this.lastValue && this.lastValue.bar_status
}
}
|
Sort new cmd: allow empty separator | from cudatext import *
def _sort(s, sep_k, sep_v):
if sep_k:
if not sep_k in s:
return s
key, val = s.split(sep_k, 1)
vals = sorted(val.split(sep_v))
return key+sep_k+sep_v.join(vals)
else:
vals = sorted(s.split(sep_v))
return sep_v.join(vals)
def do_sort_sep_values():
while 1:
res = dlg_input_ex(2,
'Sort: separator chars',
'Separator of prefix, to skip prefix (optional):', '=',
'Separator of values after prefix:', ',')
if res is None:
return
sep_k, sep_v = res
if len(sep_k)>1:
msg_status('Separators must have length=1')
continue
if len(sep_v)!=1:
msg_status('Separators must have length=1')
continue
if sep_k==sep_v:
msg_status('Separators cannot be the same')
continue
break
cnt = 0
for i in range(ed.get_line_count()):
s = ed.get_text_line(i)
s2 = _sort(s, sep_k, sep_v)
if s!=s2:
ed.set_text_line(i, s2)
cnt += 1
if cnt>0:
msg_status('Sorted, changed %d line(s)'%cnt)
else:
msg_status('Lines are already sorted')
| from cudatext import *
def _sort(s, sep_k, sep_v):
if not sep_k in s:
return s
key, val = s.split(sep_k, 1)
vals = sorted(val.split(sep_v))
return key+sep_k+sep_v.join(vals)
def do_sort_sep_values():
while 1:
res = dlg_input_ex(2,
'Sort: separator chars',
'Separator of prefix, to skip prefix:', '=',
'Separator of values after prefix:', ',')
if res is None:
return
sep_k, sep_v = res
if len(sep_k)!=1 or len(sep_v)!=1:
msg_status('Separators must have length=1')
continue
if sep_k==sep_v:
msg_status('Separators cannot be the same')
continue
break
cnt = 0
for i in range(ed.get_line_count()):
s = ed.get_text_line(i)
s2 = _sort(s, sep_k, sep_v)
if s!=s2:
ed.set_text_line(i, s2)
cnt += 1
if cnt>0:
msg_status('Sorted, changed %d line(s)'%cnt)
else:
msg_status('Lines are already sorted')
|
WebRTC: Fix builder triggering in client.webrtc.fyi
In https://codereview.chromium.org/867283002 I missed to
add the new builders to the triggering.
[email protected]
Review URL: https://codereview.chromium.org/875733002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293797 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from buildbot.schedulers.basic import SingleBranchScheduler
from master.factory import annotator_factory
m_annotator = annotator_factory.AnnotatorFactory()
def Update(c):
c['schedulers'].extend([
SingleBranchScheduler(name='webrtc_windows_scheduler',
branch='trunk',
treeStableTimer=0,
builderNames=[
'Win32 Debug (parallel)',
'Win32 Release (parallel)',
'Win64 Debug (parallel)',
'Win64 Release (parallel)',
]),
])
specs = [
{
'name': 'Win32 Debug (parallel)',
'slavebuilddir': 'win',
},
{
'name': 'Win32 Release (parallel)',
'slavebuilddir': 'win',
},
{
'name': 'Win64 Debug (parallel)',
'slavebuilddir': 'win',
},
{
'name': 'Win64 Release (parallel)',
'slavebuilddir': 'win',
},
]
c['builders'].extend([
{
'name': spec['name'],
'factory': m_annotator.BaseFactory('webrtc/standalone'),
'notify_on_missing': True,
'category': 'win',
'slavebuilddir': spec['slavebuilddir'],
} for spec in specs
])
| # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from buildbot.schedulers.basic import SingleBranchScheduler
from master.factory import annotator_factory
m_annotator = annotator_factory.AnnotatorFactory()
def Update(c):
c['schedulers'].extend([
SingleBranchScheduler(name='webrtc_windows_scheduler',
branch='trunk',
treeStableTimer=0,
builderNames=['Win32 Debug (parallel)']),
])
specs = [
{
'name': 'Win32 Debug (parallel)',
'slavebuilddir': 'win',
},
{
'name': 'Win32 Release (parallel)',
'slavebuilddir': 'win',
},
{
'name': 'Win64 Debug (parallel)',
'slavebuilddir': 'win',
},
{
'name': 'Win64 Release (parallel)',
'slavebuilddir': 'win',
},
]
c['builders'].extend([
{
'name': spec['name'],
'factory': m_annotator.BaseFactory('webrtc/standalone'),
'notify_on_missing': True,
'category': 'win',
'slavebuilddir': spec['slavebuilddir'],
} for spec in specs
])
|
Add new class to description | import React, { Component } from 'react';
import ReactCSSTransitionReplace from 'react-css-transition-replace';
import { connect } from 'react-redux';
import store from '../store.js';
class Description extends Component {
constructor(props) {
super(props);
}
isFinished() {
return (this.props.names.index + 1) > this.props.names[this.props.gender.selected].length
}
showDesc() {
if (!this.isFinished()) {
return this.props.names[this.props.gender.selected][this.props.names.index].desc
}
}
showID() {
if (!this.isFinished()) {
return this.props.names[this.props.gender.selected][this.props.names.index].id
} else {
return "Onki navn eftir"
}
}
render() {
return (
<div>
<ReactCSSTransitionReplace
transitionName="fade-wait"
transitionEnterTimeout={600}
transitionLeaveTimeout={600}>
<h2 className="name-description" key={this.showID()}><small><i>{this.showDesc()}</i></small></h2>
</ReactCSSTransitionReplace>
</div>
);
}
}
const mapStateToProps = function (store) {
return {
names: store.names,
gender: store.gender
};
}
export default connect(mapStateToProps)(Description);
| import React, { Component } from 'react';
import ReactCSSTransitionReplace from 'react-css-transition-replace';
import { connect } from 'react-redux';
import store from '../store.js';
class Description extends Component {
constructor(props) {
super(props);
}
isFinished() {
return (this.props.names.index + 1) > this.props.names[this.props.gender.selected].length
}
showDesc() {
if (!this.isFinished()) {
return this.props.names[this.props.gender.selected][this.props.names.index].desc
}
}
showID() {
if (!this.isFinished()) {
return this.props.names[this.props.gender.selected][this.props.names.index].id
} else {
return "Onki navn eftir"
}
}
render() {
return (
<div>
<ReactCSSTransitionReplace
transitionName="fade-wait"
transitionEnterTimeout={600}
transitionLeaveTimeout={600}>
<h2 className="subtitlte" key={this.showID()}><small><i>{this.showDesc()}</i></small></h2>
</ReactCSSTransitionReplace>
</div>
);
}
}
const mapStateToProps = function (store) {
return {
names: store.names,
gender: store.gender
};
}
export default connect(mapStateToProps)(Description);
|
Allow to use own Repositories like UserRepository | <?php
/**
* @author: Patsura Dmitry http://github.com/ovr <[email protected]>
*/
namespace Lynx;
use Doctrine\DBAL\Connection;
class EntityManager
{
/**
* @var Connection
*/
protected $connection;
/**
* @var Repository[]
*/
protected $repositories;
public function __construct(\Doctrine\DBAL\Connection $connection)
{
$this->connection = $connection;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
public function createQueryBuilder()
{
return $this->connection->createQueryBuilder();
}
/**
* @param $className
* @param $id
* @return null|object
*/
public function find($className, $id)
{
return $this->getRepository($className)->getOne($id);
}
/**
* @param $className
* @return Repository
*/
public function getRepository($className)
{
if (isset($this->repositories[$className])) {
return $this->repositories[$className];
}
if (class_exists($className . 'Repository', true)) {
$class = $className . 'Repository';
return $this->repositories[$className] = new $class($this, $className);
}
return $this->repositories[$className] = new Repository($this, $className);
}
/**
* @param $className
* @return object
*/
public function getObject($className)
{
$instantiator = new \Doctrine\Instantiator\Instantiator();
return $instantiator->instantiate($className);
}
}
| <?php
/**
* @author: Patsura Dmitry http://github.com/ovr <[email protected]>
*/
namespace Lynx;
use Doctrine\DBAL\Connection;
class EntityManager
{
/**
* @var Connection
*/
protected $connection;
/**
* @var Repository[]
*/
protected $repositories;
public function __construct(\Doctrine\DBAL\Connection $connection)
{
$this->connection = $connection;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
public function createQueryBuilder()
{
return $this->connection->createQueryBuilder();
}
/**
* @param $className
* @param $id
* @return null|object
*/
public function find($className, $id)
{
return $this->getRepository($className)->getOne($id);
}
/**
* @param $name
* @return Repository
*/
public function getRepository($name)
{
if (isset($this->repositories[$name])) {
return $this->repositories[$name];
}
return $this->repositories[$name] = new Repository($this, $name);
}
/**
* @param $className
* @return object
*/
public function getObject($className)
{
$instantiator = new \Doctrine\Instantiator\Instantiator();
return $instantiator->instantiate($className);
}
}
|
Move identifier setter to setEventManager | <?php
namespace ZfcBase\EventManager;
use Zend\EventManager\EventCollection,
Zend\EventManager\EventManager;
abstract class EventProvider
{
/**
* @var EventCollection
*/
protected $events;
/**
* Set the event manager instance used by this context
*
* @param EventCollection $events
* @return mixed
*/
public function setEventManager(EventCollection $events)
{
$identifiers = array(__CLASS__, get_class($this));
if (isset($this->eventIdentifier)) {
if ((is_string($this->eventIdentifier))
|| (is_array($this->eventIdentifier))
|| ($this->eventIdentifier instanceof Traversable)
) {
$identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
} elseif (is_object($this->eventIdentifier)) {
$identifiers[] = $this->eventIdentifier;
}
// silently ignore invalid eventIdentifier types
}
$events->setIdentifiers($identifiers);
$this->events = $events;
return $this;
}
/**
* Retrieve the event manager
*
* Lazy-loads an EventManager instance if none registered.
*
* @return EventCollection
*/
public function events()
{
if (!$this->events instanceof EventCollection) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
}
| <?php
namespace ZfcBase\EventManager;
use Zend\EventManager\EventCollection,
Zend\EventManager\EventManager;
abstract class EventProvider
{
/**
* @var EventCollection
*/
protected $events;
/**
* Set the event manager instance used by this context
*
* @param EventCollection $events
* @return mixed
*/
public function setEventManager(EventCollection $events)
{
$this->events = $events;
return $this;
}
/**
* Retrieve the event manager
*
* Lazy-loads an EventManager instance if none registered.
*
* @return EventCollection
*/
public function events()
{
if (!$this->events instanceof EventCollection) {
$identifiers = array(__CLASS__, get_class($this));
if (isset($this->eventIdentifier)) {
if ((is_string($this->eventIdentifier))
|| (is_array($this->eventIdentifier))
|| ($this->eventIdentifier instanceof Traversable)
) {
$identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
} elseif (is_object($this->eventIdentifier)) {
$identifiers[] = $this->eventIdentifier;
}
// silently ignore invalid eventIdentifier types
}
$this->setEventManager(new EventManager($identifiers));
}
return $this->events;
}
}
|
Fix how to get tags and fields name
The old implementation returns 'integer', 'float' in the result list. | """ InfluxAlchemy Client. """
from . import query
from .measurement import Measurement
class InfluxAlchemy(object):
""" InfluxAlchemy database session.
client (InfluxDBClient): Connection to InfluxDB database
"""
def __init__(self, client):
self.bind = client
# pylint: disable=protected-access
assert self.bind._database is not None, \
"InfluxDB client database cannot be None"
def query(self, *entities):
""" Query InfluxDB entities. Entities are either Measurements or
Tags/Fields.
"""
return query.InfluxDBQuery(entities, self)
def measurements(self):
""" Get measurements of an InfluxDB. """
results = self.bind.query("SHOW MEASUREMENTS;")
for res in results.get_points():
yield Measurement.new(str(res["name"]))
def tags(self, measurement):
""" Get tags of a measurements in InfluxDB. """
tags = self.bind.query("SHOW tag keys FROM %s" % measurement)
pts = sorted(set(t['tagKey'] for t in tags.get_points()))
return pts
def fields(self, measurement):
""" Get fields of a measurements in InfluxDB. """
fields = self.bind.query("SHOW field keys FROM %s" % measurement)
pts = sorted(set(f['fieldKey'] for f in fields.get_points()))
return pts
| """ InfluxAlchemy Client. """
from . import query
from .measurement import Measurement
class InfluxAlchemy(object):
""" InfluxAlchemy database session.
client (InfluxDBClient): Connection to InfluxDB database
"""
def __init__(self, client):
self.bind = client
# pylint: disable=protected-access
assert self.bind._database is not None, \
"InfluxDB client database cannot be None"
def query(self, *entities):
""" Query InfluxDB entities. Entities are either Measurements or
Tags/Fields.
"""
return query.InfluxDBQuery(entities, self)
def measurements(self):
""" Get measurements of an InfluxDB. """
results = self.bind.query("SHOW MEASUREMENTS;")
for res in results.get_points():
yield Measurement.new(str(res["name"]))
def tags(self, measurement):
""" Get tags of a measurements in InfluxDB. """
tags = self.bind.query("SHOW tag keys FROM %s" % measurement)
pts = sorted(set(y for x in tags.get_points() for y in x.values()))
return pts
def fields(self, measurement):
""" Get fields of a measurements in InfluxDB. """
fields = self.bind.query("SHOW field keys FROM %s" % measurement)
pts = sorted(set(y for x in fields.get_points() for y in x.values()))
return pts
|
Replace loaders -> rules. Edit webpack.optimize.CommonsChunkPlugin config | const rules = require("./rules");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const path = require("path");
module.exports = {
context: path.join(__dirname, ".."),
entry: ["./src/index.ts"],
output: {
filename: "build.js",
path: path.resolve("./dist"),
publicPath: "/"
},
devtool: "",
resolve: {
extensions: [
".ts",
".js",
".json"
]
},
resolveLoader: {
modules: ["node_modules"]
},
plugins: [
new CleanWebpackPlugin(["dist"], {
root: path.join(__dirname, "..")
}),
new UglifyJSPlugin({
uglifyOptions: {
ecma: 5,
compress: {
dead_code: true,
drop_console: true,
toplevel: true,
unsafe_proto: true,
warnings: true
},
output: {
indent_level: 2,
beautify: false
}
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: "manifest",
filename: "manifest.js",
minChunks: Infinity
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
inject: "body",
hash: true
})
],
module: {
rules: rules
}
};
| const loaders = require("./loaders");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const path = require("path");
module.exports = {
context: path.join(__dirname, ".."),
entry: ["./src/index.ts"],
output: {
filename: "build.js",
path: path.resolve("./dist"),
publicPath: "/"
},
devtool: "",
resolve: {
extensions: [
".ts",
".js",
".json"
]
},
resolveLoader: {
modules: ["node_modules"]
},
plugins: [
new CleanWebpackPlugin(["dist"], {
root: path.join(__dirname, "..")
}),
new UglifyJSPlugin({
uglifyOptions: {
ecma: 5,
compress: {
dead_code: true,
drop_console: true,
toplevel: true,
unsafe_proto: true,
warnings: true
},
output: {
indent_level: 2,
beautify: false
}
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: "vendors",
filename: "vendors.js",
minChunks: Infinity
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
inject: "body",
hash: true
})
],
module: {
loaders: loaders
}
};
|
Adjust the time factor to align frontent and backend auth.
Fixes #27 | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client',
environment: environment,
baseURL: '/',
locationType: 'auto',
'ember-simple-auth-token': {
serverTokenEndpoint: 'http://localhost:8080/api-token-auth/',
serverTokenRefreshEndpoint: 'http://localhost:8080/api-token-refresh/',
refreshLeeway: 20,
timeFactor: 1000, // backend is in seconds and the frontend is in ms.
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'client',
environment: environment,
baseURL: '/',
locationType: 'auto',
'ember-simple-auth-token': {
serverTokenEndpoint: 'http://localhost:8080/api-token-auth/',
serverTokenRefreshEndpoint: 'http://localhost:8080/api-token-refresh/',
refreshLeeway: 20
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Add a forgoten close tag | <!DOCTYPE html>
<html lang="en">
<head>
<title>EndofCodes Demo</title>
<?php
include 'helpers/html.php';
includeStyle( "general" );
includeStyle( "header" );
includeStyle( "home" );
includeStyle( "register" );
includeStyle( "login" );
?>
<meta charset="utf-8" />
</head>
<body>
<div id="header">
<ul>
<li><a href="index.php">Endofcodes</a></li>
<li><a href="">Rules</a></li>
<?php
if ( isset( $_SESSION[ 'user' ]['username' ] ) ) {
?><li><a href="index.php?resource=user&method=view&username=<?php
echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
?>">Profile</a></li><?php
}
?>
<li><a href="http://blog.endofcodes.com">Blog</a></li>
<?php
if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
?><li id="login" class="username"><?php
echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
?></li><?php
}
else {
?><li id="login"><a href="index.php?resource=session&method=create">Login</a></li><?php
}
?>
</ul>
</div>
| <!DOCTYPE html>
<html lang="en">
<head>
<title>EndofCodes Demo</title>
<?php
include 'helpers/html.php';
includeStyle( "general" );
includeStyle( "header" );
includeStyle( "home" );
includeStyle( "register" );
includeStyle( "login" );
?>
<meta charset="utf-8">
</head>
<body>
<div id="header">
<ul>
<li><a href="index.php">Endofcodes</a></li>
<li><a href="">Rules</a></li>
<?php
if ( isset( $_SESSION[ 'user' ]['username' ] ) ) {
?><li><a href="index.php?resource=user&method=view&username=<?php
echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
?>">Profile</a></li><?php
}
?>
<li><a href="http://blog.endofcodes.com">Blog</a></li>
<?php
if ( isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
?><li id="login" class="username"><?php
echo htmlspecialchars( $_SESSION[ 'user' ][ 'username' ] );
?></li><?php
}
else {
?><li id="login"><a href="index.php?resource=session&method=create">Login</a></li><?php
}
?>
</ul>
</div>
|
Use find_packages() instead of manually specifying package name, so that subpackages get included | from setuptools import setup, find_packages
setup(name="manhattan",
version='0.2',
description='Robust Server-Side Analytics',
long_description='',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
keywords='',
url='http://github.com/cartlogic/manhattan',
author='Scott Torborg',
author_email='[email protected]',
install_requires=[
'sqlalchemy>=0.7',
'webob',
'redis>=2.7.2',
'pytz',
'pyzmq',
'simplejson',
],
license='MIT',
packages=find_packages(),
entry_points=dict(
console_scripts=[
'manhattan-server=manhattan.server:main',
'manhattan-client=manhattan.client:main',
'manhattan-log-server=manhattan.log.remote:server',
]
),
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False)
| from setuptools import setup
setup(name="manhattan",
version='0.2',
description='Robust Server-Side Analytics',
long_description='',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: Site Management',
],
keywords='',
url='http://github.com/cartlogic/manhattan',
author='Scott Torborg',
author_email='[email protected]',
install_requires=[
'sqlalchemy>=0.7',
'webob',
'redis>=2.7.2',
'pytz',
'pyzmq',
'simplejson',
],
license='MIT',
packages=['manhattan'],
entry_points=dict(
console_scripts=[
'manhattan-server=manhattan.server:main',
'manhattan-client=manhattan.client:main',
'manhattan-log-server=manhattan.log.remote:server',
]
),
test_suite='nose.collector',
tests_require=['nose'],
zip_safe=False)
|
Remove dead code from login modal window | var myUsername = null;
var URL = window.location.hostname + ':8080';
var socket = io.connect(URL);
var channel;
var ready = false;
var active = true;
var first = true;
function updateOwnMessagesInHistory() {
$('#message-list li').each(function() {
if ($(this).find('strong').text() == myUsername) {
$(this).find('div').removeClass('other').addClass('self');
}
});
}
$(document).ready(function() {
var title = document.title;
var titlePrefix = '';
var unread = 0;
function updateTitle() {
if (active) {
titlePrefix = '';
}
else {
titlePrefix = '(' + unread + ') ';
}
document.title = titlePrefix + title;
}
var url = $(location).attr('href');
parts = url.split('/');
channel = parts.slice(-1)[0]
if (channel == '') {
channel = 'ting';
}
$(document).on({
'show': function() {
active = true;
unread = 0;
updateTitle();
},
'hide': function() {
active = false;
}
});
//socket.on('disconnect', function() {
// $('#messages').append('<li><strong><span class='text-warning'>The server is not available</span></strong></li>');
// $('#message').attr('disabled', 'disabled');
// $('#send').attr('disabled', 'disabled');
//});
});
var Ting = React.createClass({
render: function() {
}
});
| var myUsername = null;
var URL = window.location.hostname + ':8080';
var socket = io.connect(URL);
var channel;
var ready = false;
var active = true;
var first = true;
function updateOwnMessagesInHistory() {
$('#message-list li').each(function() {
if ($(this).find('strong').text() == myUsername) {
$(this).find('div').removeClass('other').addClass('self');
}
});
}
$(document).ready(function() {
var title = document.title;
var titlePrefix = '';
var unread = 0;
function updateTitle() {
if (active) {
titlePrefix = '';
}
else {
titlePrefix = '(' + unread + ') ';
}
document.title = titlePrefix + title;
}
var url = $(location).attr('href');
parts = url.split('/');
channel = parts.slice(-1)[0]
if (channel == '') {
channel = 'ting';
}
$('#modal').modal('show');
$('#username').focus();
$(document).on({
'show': function() {
active = true;
unread = 0;
updateTitle();
},
'hide': function() {
active = false;
}
});
//socket.on('disconnect', function() {
// $('#messages').append('<li><strong><span class='text-warning'>The server is not available</span></strong></li>');
// $('#message').attr('disabled', 'disabled');
// $('#send').attr('disabled', 'disabled');
//});
});
var Ting = React.createClass({
render: function() {
}
});
|
Add support for intent slot's value as a object | 'use strict';
const _ = require('underscore');
function buildSlots(slots) {
const res = {};
_.each(slots, (value, key) => {
res[key] = {
name: key,
value: value
};
if(! _.isString(value)){
res[key] = {...res[key],...value}
}
});
return res;
}
function buildSession(e) {
return e ? e.sessionAttributes : {};
}
function init(options) {
let isNew = true;
// public API
const api = {
init,
build
};
function build(intentName, slots, prevEvent) {
if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request');
const res = { // override more stuff later as we need
session: {
sessionId: options.sessionId,
application: {
applicationId: options.appId
},
attributes: buildSession(prevEvent),
user: {
userId: options.userId,
accessToken: options.accessToken
},
new: isNew
},
request: {
type: 'IntentRequest',
requestId: options.requestId,
locale: options.locale,
timestamp: (new Date()).toISOString(),
intent: {
name: intentName,
slots: buildSlots(slots)
}
},
version: '1.0'
};
isNew = false;
return res;
}
return api;
}
module.exports = {init};
| 'use strict';
const _ = require('underscore');
function buildSlots(slots) {
const res = {};
_.each(slots, (value, key) => {
res[key] = {
name: key,
value: value
};
});
return res;
}
function buildSession(e) {
return e ? e.sessionAttributes : {};
}
function init(options) {
let isNew = true;
// public API
const api = {
init,
build
};
function build(intentName, slots, prevEvent) {
if (!options.appId) throw String('AppId not specified. Please run events.init(appId) before building a Request');
const res = { // override more stuff later as we need
session: {
sessionId: options.sessionId,
application: {
applicationId: options.appId
},
attributes: buildSession(prevEvent),
user: {
userId: options.userId,
accessToken: options.accessToken
},
new: isNew
},
request: {
type: 'IntentRequest',
requestId: options.requestId,
locale: options.locale,
timestamp: (new Date()).toISOString(),
intent: {
name: intentName,
slots: buildSlots(slots)
}
},
version: '1.0'
};
isNew = false;
return res;
}
return api;
}
module.exports = {init};
|
Modify getPrice to report name of item actually queried | import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const [{data: [priceData]}, {data: {name: itemName}}] = await Promise.all([
axios.get(`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`),
axios.get(`${esiURL}universe/types/${itemid}/?datasource=tranquility&language=en-us`)
]);
const sellFivePercent = humanize(priceData.sell.fivePercent);
const buyFivePercent = humanize(priceData.buy.fivePercent);
message.channel.sendMessage(
`__Price of **${itemName}** in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) |
Add description for java 95 | import java.util.ArrayList;
import java.util.List;
/**
* Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
* <p>
* For example,
* Given n = 3, your program should return all 5 unique BST's shown below.
* <p>
* 1 3 3 2 1
* \ / / / \ \
* 3 2 1 1 3 2
* / / \ \
* 2 1 2 3
* <p>
* Created by drfish on 27/05/2017.
*/
public class _095UniqueBinarySearchTreesII {
public List<TreeNode> generateTrees(int n) {
List<TreeNode> result = genTrees(1, n);
if (result.get(0) == null) {
return new ArrayList<>();
} else {
return result;
}
}
private List<TreeNode> genTrees(int start, int end) {
List<TreeNode> result = new ArrayList<>();
if (start > end) {
result.add(null);
}
for (int i = start; i <= end; i++) {
List<TreeNode> leftTrees = genTrees(start, i - 1);
List<TreeNode> rightTrees = genTrees(i + 1, end);
for (TreeNode leftTree : leftTrees) {
for (TreeNode rightTree : rightTrees) {
TreeNode root = new TreeNode(i);
root.left = leftTree;
root.right = rightTree;
result.add(root);
}
}
}
return result;
}
}
| import java.util.ArrayList;
import java.util.List;
/**
* Created by drfish on 27/05/2017.
*/
public class _095UniqueBinarySearchTreesII {
public List<TreeNode> generateTrees(int n) {
List<TreeNode> result = genTrees(1, n);
if (result.get(0) == null) {
return new ArrayList<>();
} else {
return result;
}
}
private List<TreeNode> genTrees(int start, int end) {
List<TreeNode> result = new ArrayList<>();
if (start > end) {
result.add(null);
}
for (int i = start; i <= end; i++) {
List<TreeNode> leftTrees = genTrees(start, i - 1);
List<TreeNode> rightTrees = genTrees(i + 1, end);
for (TreeNode leftTree : leftTrees) {
for (TreeNode rightTree : rightTrees) {
TreeNode root = new TreeNode(i);
root.left = leftTree;
root.right = rightTree;
result.add(root);
}
}
}
return result;
}
}
|
Change trove classifier; 'BSD' was invalid
List of available is here:
https://pypi.python.org/pypi?:action=list_classifiers | #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta'
, 'Environment :: Console'
, 'Environment :: Console :: Curses'
, 'Intended Audience :: Developers'
, 'License :: OSI Approved :: BSD License'
, 'Natural Language :: English'
, 'Operating System :: MacOS :: MacOS X'
, 'Operating System :: Microsoft :: Windows'
, 'Operating System :: POSIX'
, 'Programming Language :: Python'
, 'Topic :: Software Development :: Testing'
]
setup( name = 'assertEquals'
, version = '0.4.3'
, packages = [ 'assertEquals'
, 'assertEquals.cli'
, 'assertEquals.interactive'
, 'assertEquals.interactive.screens'
, 'assertEquals.tests'
, 'assertEquals.tests.interactive'
]
, entry_points = { 'console_scripts'
: [ 'assertEquals = assertEquals.cli.main:main' ]
}
, description = 'assertEquals is an epic testing interface for Python.'
, author = 'Chad Whitacre'
, author_email = '[email protected]'
, url = 'https://www.github.com/whit537/assertEquals/'
, classifiers = classifiers
)
| #!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup
classifiers = [
'Development Status :: 4 - Beta'
, 'Environment :: Console'
, 'Environment :: Console :: Curses'
, 'Intended Audience :: Developers'
, 'License :: BSD'
, 'Natural Language :: English'
, 'Operating System :: MacOS :: MacOS X'
, 'Operating System :: Microsoft :: Windows'
, 'Operating System :: POSIX'
, 'Programming Language :: Python'
, 'Topic :: Software Development :: Testing'
]
setup( name = 'assertEquals'
, version = '0.4.3'
, packages = [ 'assertEquals'
, 'assertEquals.cli'
, 'assertEquals.interactive'
, 'assertEquals.interactive.screens'
, 'assertEquals.tests'
, 'assertEquals.tests.interactive'
]
, entry_points = { 'console_scripts'
: [ 'assertEquals = assertEquals.cli.main:main' ]
}
, description = 'assertEquals is an epic testing interface for Python.'
, author = 'Chad Whitacre'
, author_email = '[email protected]'
, url = 'https://www.github.com/whit537/assertEquals/'
, classifiers = classifiers
)
|
Fix parsing of commander options | /**
* Main CLI parser class
*/
class Config
{
/**
* @param {Command} argv
*/
constructor (argv)
{
// commander just returns undefined for missing flags, so transform them to boolean
/**
* @private
* @type {boolean}
*/
this.dev = !!argv.d || !!argv.dev;
/**
* @private
* @type {boolean}
*/
this.debug = !!argv.debug;
/**
* @private
* @type {boolean}
*/
this.sourceMaps = !!argv.withSourceMaps;
/**
* @private
* @type {boolean}
*/
this.watch = !!argv.watch;
/**
* @private
* @type {boolean}
*/
this.lint = !!argv.lint;
}
/**
* Returns whether this is a debug build
*
* @return {boolean}
*/
isDebug ()
{
return this.debug || this.dev;
}
/**
* Returns whether to include sourcemaps
*
* @return {boolean}
*/
includeSourceMaps ()
{
return this.sourceMaps || this.dev;
}
/**
* Returns whether the watcher should be activated
*
* @return {boolean}
*/
isWatch ()
{
return this.watch || this.dev;
}
/**
* Returns whether the code should be linted
*
* @return {boolean}
*/
isLint ()
{
return this.lint || this.dev;
}
}
module.exports = Config;
| /**
* Main CLI parser class
*/
class Config
{
/**
* @param {Command} argv
*/
constructor (argv)
{
/**
* @private
* @type {boolean}
*/
this.dev = argv.d || argv.dev;
/**
* @private
* @type {boolean}
*/
this.debug = argv.debug;
/**
* @private
* @type {boolean}
*/
this.sourceMaps = argv.withSourceMaps;
/**
* @private
* @type {boolean}
*/
this.watch = argv.watch;
/**
* @private
* @type {boolean}
*/
this.lint = argv.lint;
}
/**
* Returns whether this is a debug build
*
* @return {boolean}
*/
isDebug ()
{
return this.debug || this.dev;
}
/**
* Returns whether to include sourcemaps
*
* @return {boolean}
*/
includeSourceMaps ()
{
return this.sourceMaps || this.dev;
}
/**
* Returns whether the watcher should be activated
*
* @return {boolean}
*/
isWatch ()
{
return this.watch || this.dev;
}
/**
* Returns whether the code should be linted
*
* @return {boolean}
*/
isLint ()
{
return this.lint || this.dev;
}
}
module.exports = Config;
|
Revert "Check if app is mounted"
This reverts commit cb9e2bfb6b03435513750b741da1a5896ae4ad5d. | import React, { Component } from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import ImgurImage from './ImgurImage';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0};
}
loadImages(page = 0) {
searchGallery(undefined, undefined, page).then((result) => {
this.setState({images: result.data, page: page});
});
}
componentDidMount() {
this.loadImages();
}
render() {
return (
<div>
<Navbar
brand='React Imgur viewer'
fixedTop={true}>
<Nav right>
<NavItem
onClick={() => this.loadImages(this.state.page - 1)}
disabled={this.state.page <= 0}>
<i className='glyphicon glyphicon-arrow-left'></i> Previous page
</NavItem>
<NavItem onClick={() => this.loadImages(this.state.page + 1)}>
Next page <i className='glyphicon glyphicon-arrow-right'></i>
</NavItem>
</Nav>
</Navbar>
<div
className='container'
style={{paddingTop: '70px'}}>
{this.state.images.map(function(image) {
return (
<ImgurImage
image={image}
key={image.id} />
);
})}
</div>
</div>
);
}
}
| import React, { Component } from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import ImgurImage from './ImgurImage';
import { searchGallery } from './../services/imgur';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {images: [], page: 0};
}
loadImages(page = 0) {
searchGallery(undefined, undefined, page).then((result) => {
if (this.isMounted()) {
this.setState({images: result.data, page: page});
}
});
}
componentDidMount() {
this.loadImages();
}
render() {
return (
<div>
<Navbar
brand='React Imgur viewer'
fixedTop={true}>
<Nav right>
<NavItem
onClick={() => this.loadImages(this.state.page - 1)}
disabled={this.state.page <= 0}>
<i className='glyphicon glyphicon-arrow-left'></i> Previous page
</NavItem>
<NavItem onClick={() => this.loadImages(this.state.page + 1)}>
Next page <i className='glyphicon glyphicon-arrow-right'></i>
</NavItem>
</Nav>
</Navbar>
<div
className='container'
style={{paddingTop: '70px'}}>
{this.state.images.map(function(image) {
return (
<ImgurImage
image={image}
key={image.id} />
);
})}
</div>
</div>
);
}
}
|
Update Stylus filter with include paths
Since the Stylus filter works with stdin, the compiler doesn't know the
source directory, and thus can't resolve any imports. This adds the
source directory to the include path using the `--include` option, and
also adds the `STYLUS_EXTRA_PATHS` option to configure any extra
include paths. | import os
from webassets.filter import ExternalTool, option
__all__ = ('Stylus',)
class Stylus(ExternalTool):
"""Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.
Requires the Stylus executable to be available externally. You can install
it using the `Node Package Manager <http://npmjs.org/>`_::
$ npm install stylus
Supported configuration options:
STYLUS_BIN
The path to the Stylus binary. If not set, assumes ``stylus`` is in the
system path.
STYLUS_PLUGINS
A Python list of Stylus plugins to use. Each plugin will be included
via Stylus's command-line ``--use`` argument.
STYLUS_EXTRA_ARGS
A Python list of any additional command-line arguments.
STYLUS_EXTRA_PATHS
A Python list of any additional import paths.
"""
name = 'stylus'
options = {
'stylus': 'STYLUS_BIN',
'plugins': option('STYLUS_PLUGINS', type=list),
'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
'extra_paths': option('STYLUS_EXTRA_PATHS', type=list),
}
max_debug_level = None
def input(self, _in, out, **kwargs):
args = [self.stylus or 'stylus']
source_dir = os.path.dirname(kwargs['source_path'])
paths = [source_dir] + (self.extra_paths or [])
for path in paths:
args.extend(('--include', path))
for plugin in self.plugins or []:
args.extend(('--use', plugin))
if self.extra_args:
args.extend(self.extra_args)
self.subprocess(args, out, _in)
| from webassets.filter import ExternalTool, option
__all__ = ('Stylus',)
class Stylus(ExternalTool):
"""Converts `Stylus <http://learnboost.github.com/stylus/>`_ markup to CSS.
Requires the Stylus executable to be available externally. You can install
it using the `Node Package Manager <http://npmjs.org/>`_::
$ npm install stylus
Supported configuration options:
STYLUS_BIN
The path to the Stylus binary. If not set, assumes ``stylus`` is in the
system path.
STYLUS_PLUGINS
A Python list of Stylus plugins to use. Each plugin will be included
via Stylus's command-line ``--use`` argument.
STYLUS_EXTRA_ARGS
A Python list of any additional command-line arguments.
"""
name = 'stylus'
options = {
'stylus': 'STYLUS_BIN',
'plugins': option('STYLUS_PLUGINS', type=list),
'extra_args': option('STYLUS_EXTRA_ARGS', type=list),
}
max_debug_level = None
def input(self, _in, out, **kwargs):
args = [self.stylus or 'stylus']
for plugin in self.plugins or []:
args.extend(('--use', plugin))
if self.extra_args:
args.extend(self.extra_args)
self.subprocess(args, out, _in)
|
Support ipv6 for status endpoint security | package org.apereo.cas.configuration.model.core.web.security;
import org.springframework.core.io.Resource;
/**
* This is {@link AdminPagesSecurityProperties}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class AdminPagesSecurityProperties {
private String ip = "127\\.0\\.0\\.1|0:0:0:0:0:0:0:1";
private String adminRoles = "ROLE_ADMIN";
private String loginUrl;
private String service;
private Resource users;
private boolean actuatorEndpointsEnabled;
public boolean isActuatorEndpointsEnabled() {
return actuatorEndpointsEnabled;
}
public void setActuatorEndpointsEnabled(final boolean actuatorEndpointsEnabled) {
this.actuatorEndpointsEnabled = actuatorEndpointsEnabled;
}
public String getIp() {
return ip;
}
public void setIp(final String ip) {
this.ip = ip;
}
public String getAdminRoles() {
return adminRoles;
}
public void setAdminRoles(final String adminRoles) {
this.adminRoles = adminRoles;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(final String loginUrl) {
this.loginUrl = loginUrl;
}
public String getService() {
return service;
}
public void setService(final String service) {
this.service = service;
}
public Resource getUsers() {
return users;
}
public void setUsers(final Resource users) {
this.users = users;
}
}
| package org.apereo.cas.configuration.model.core.web.security;
import org.springframework.core.io.Resource;
/**
* This is {@link AdminPagesSecurityProperties}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class AdminPagesSecurityProperties {
private String ip = "127\\.0\\.0\\.1";
private String adminRoles = "ROLE_ADMIN";
private String loginUrl;
private String service;
private Resource users;
private boolean actuatorEndpointsEnabled;
public boolean isActuatorEndpointsEnabled() {
return actuatorEndpointsEnabled;
}
public void setActuatorEndpointsEnabled(final boolean actuatorEndpointsEnabled) {
this.actuatorEndpointsEnabled = actuatorEndpointsEnabled;
}
public String getIp() {
return ip;
}
public void setIp(final String ip) {
this.ip = ip;
}
public String getAdminRoles() {
return adminRoles;
}
public void setAdminRoles(final String adminRoles) {
this.adminRoles = adminRoles;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(final String loginUrl) {
this.loginUrl = loginUrl;
}
public String getService() {
return service;
}
public void setService(final String service) {
this.service = service;
}
public Resource getUsers() {
return users;
}
public void setUsers(final Resource users) {
this.users = users;
}
}
|
Update StatViewSet to generic, add necessary mixins | # from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, mixins, permissions # , serializers
from .models import Stat, Activity
# from .permissions import IsAPIUser
from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer
# Create your views here.
# class UserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
# permission_classes = (permissions.IsAuthenticated,
# IsAPIUser)
class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
# def get_queryset(self):
# return self.request.user.activity_set.all()
def get_serializer_class(self):
if self.action == 'list':
return ActivitySerializer
else:
return ActivityListSerializer
class StatViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin,
mixins.UpdateModelMixin, mixins.DestroyModelMixin):
serializer_class = StatSerializer
def get_queryset(self):
activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk'])
return Stat.objects.all().filter(
# user=self.request.user,
activity=activity)
def get_serializer_context(self):
context = super().get_serializer_context().copy()
activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk'])
context['activity'] = activity
return context
# def perform_create(self, serializer):
# serializers.save(user=self.request.user)
| # from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, permissions # , serializers
from .models import Stat, Activity
from .permissions import IsAPIUser
from .serializers import ActivitySerializer, ActivityListSerializer, StatSerializer
# Create your views here.
# class UserViewSet(viewsets.ModelViewSet):
# permission_classes = (permissions.IsAuthenticated,
# IsAPIUser)
#
# def list(self, request, *args, **kwargs):
# return []
class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
# def get_queryset(self):
# return self.request.user.activity_set.all()
def get_serializer_class(self):
if self.action == 'list':
return ActivitySerializer
else:
return ActivityListSerializer
class StatViewSet(viewsets.ModelViewSet):
serializer_class = StatSerializer
def get_queryset(self):
activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk'])
return Stat.objects.all().filter(
# user=self.request.user,
activity=activity)
def get_serializer_context(self):
context = super().get_serializer_context().copy()
activity = get_object_or_404(Activity, pk=self.kwargs['activity_pk'])
context['activity'] = activity
return context
# def perform_create(self, serializer):
# serializers.save(user=self.request.user)
|
Revert "api key deleted from the list of required parameters" | package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {
public static final String API_KEY_QUERY_PARAMETER = "key";
private final ApplicationStore reader;
public ApiKeySourcesFetcher(ApplicationStore reader) {
this.reader = checkNotNull(reader);
}
@Override
public ImmutableSet<String> getParameterNames() {
return ImmutableSet.of(API_KEY_QUERY_PARAMETER);
}
@Override
public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException {
String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
if (apiKey == null) {
apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
}
if (apiKey != null) {
Optional<Application> app = reader.applicationForKey(apiKey);
if (!app.isPresent() || app.get().isRevoked()) {
throw new InvalidApiKeyException(apiKey);
}
return Optional.of(app.get().getSources());
}
return Optional.absent();
}
}
| package org.atlasapi.application.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.servlet.http.HttpServletRequest;
import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {
public static final String API_KEY_QUERY_PARAMETER = "key";
private final ApplicationStore reader;
public ApiKeySourcesFetcher(ApplicationStore reader) {
this.reader = checkNotNull(reader);
}
@Override
public ImmutableSet<String> getParameterNames() {
return ImmutableSet.of();
}
@Override
public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException {
String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
if (apiKey == null) {
apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
}
if (apiKey != null) {
Optional<Application> app = reader.applicationForKey(apiKey);
if (!app.isPresent() || app.get().isRevoked()) {
throw new InvalidApiKeyException(apiKey);
}
return Optional.of(app.get().getSources());
}
return Optional.absent();
}
}
|
Add additional logging to initialise game | /* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope, accounts) {
$scope.availableAccounts = accounts.availableAccounts;
$scope.selectedAccount = accounts.defaultAccount;
$scope.startcolor = 'white';
$scope.username = null;
$scope.etherbet = 0;
$scope.isSelectedAccount = function (account) {
return $scope.selectedAccount === account;
};
function initializeGame() {
$rootScope.$broadcast('message', 'Your game is being created, please wait a moment...',
'loading', 'startgame');
try {
console.log('Trying to initialize game', $scope.username,
{
from: $scope.selectedAccount,
value: web3.toWei($scope.etherbet, 'ether')
});
Chess.initGame($scope.username, $scope.startcolor === 'white',
{
from: $scope.selectedAccount,
value: web3.toWei($scope.etherbet, 'ether')
});
}
catch(e) {
console.log('Error on initialize game', e);
$rootScope.$broadcast('message', 'Could not initialize the game', 'loading', 'startgame');
}
}
$scope.selectOrCreateAccount = function($event) {
$event.preventDefault();
accounts.requestAccount(function(e, address) {
$scope.selectedAccount = address;
});
};
$scope.initializeGame = function (form) {
if(form.$valid) {
initializeGame();
}
};
$scope.getBalance = accounts.getBalance;
});
| /* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope, accounts) {
$scope.availableAccounts = accounts.availableAccounts;
$scope.selectedAccount = accounts.defaultAccount;
$scope.startcolor = 'white';
$scope.username = null;
$scope.etherbet = 0;
$scope.isSelectedAccount = function (account) {
return $scope.selectedAccount === account;
};
function initializeGame() {
$rootScope.$broadcast('message', 'Your game is being created, please wait a moment...',
'loading', 'startgame');
try {
Chess.initGame($scope.username, $scope.startcolor === 'white',
{
from: $scope.selectedAccount,
value: web3.toWei($scope.etherbet, 'ether')
});
}
catch(e) {
console.log('Error on initialize game', e);
$rootScope.$broadcast('message', 'Could not initialize the game', 'loading', 'startgame');
}
}
$scope.selectOrCreateAccount = function($event) {
$event.preventDefault();
accounts.requestAccount(function(e, address) {
$scope.selectedAccount = address;
});
};
$scope.initializeGame = function (form) {
if(form.$valid) {
initializeGame();
}
};
$scope.getBalance = accounts.getBalance;
});
|
Add entry point for test-informant | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup, find_packages
PACKAGE_VERSION = '0.1'
deps = ['flask',
'Jinja2',
'manifestparser',
'mongoengine',
'mozfile',
'mozillapulse']
setup(name='test-informant',
version=PACKAGE_VERSION,
description='A web service for monitoring and reporting the state of test manifests.',
long_description='See https://github.com/ahal/test-informant',
classifiers=['Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords='mozilla',
author='Andrew Halberstadt',
author_email='[email protected]',
url='https://github.com/ahal/test-informant',
license='MPL 2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=deps,
entry_points="""
[console_scripts]
test-informant = informant.pulse_listener:run
""")
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup, find_packages
PACKAGE_VERSION = '0.1'
deps = ['flask',
'Jinja2',
'manifestparser',
'mongoengine',
'mozfile',
'mozillapulse']
setup(name='test-informant',
version=PACKAGE_VERSION,
description='A web service for monitoring and reporting the state of test manifests.',
long_description='See https://github.com/ahal/test-informant',
classifiers=['Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords='mozilla',
author='Andrew Halberstadt',
author_email='[email protected]',
url='https://github.com/ahal/test-informant',
license='MPL 2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=deps)
|
Add command to quickly open a notes file | import neovim
import os
from datetime import datetime
@neovim.plugin
class VimpBuffers(object):
def __init__(self, vim):
self.vim = vim
@neovim.command("ToggleTerminalBuffer")
def toggle_terminal_buffer(self):
current_buffer = self.vim.current.buffer
# find the currently open terminal and close it
for idx, window in enumerate(self.vim.current.tabpage.windows, 1):
if window.buffer.name.startswith("term://"):
self.vim.command("{0}wincmd w".format(idx))
self.vim.command("wincmd c".format(idx))
# go back to the window where the command was executed from
window_number = self.vim.eval(
"bufwinnr({0})".format(current_buffer.number)
)
self.vim.command("{0}wincmd w".format(window_number))
return
# find the terminal buffer in the list of buffers, open it in a split
for buf in self.vim.buffers:
if buf.name.startswith("term://"):
self.vim.command("botright sb {0}".format(buf.number))
return
# create a new terminal when there is no terminal buffer
self.vim.command("botright new")
self.vim.command(":terminal")
@neovim.command("ShowTodaysNotes")
def open_log_file(self):
filepath = os.path.join(
os.environ.get("NOTES_DIR"),
"%s.md" % datetime.now().strftime("%Y-%m-%d")
)
self.vim.command("vs %s" % filepath)
| import neovim
@neovim.plugin
class VimpBuffers(object):
def __init__(self, vim):
self.vim = vim
@neovim.command("ToggleTerminalBuffer")
def toggle_terminal_buffer(self):
current_buffer = self.vim.current.buffer
# find the currently open terminal and close it
for idx, window in enumerate(self.vim.current.tabpage.windows, 1):
if window.buffer.name.startswith("term://"):
self.vim.command("{0}wincmd w".format(idx))
self.vim.command("wincmd c".format(idx))
# go back to the window where the command was executed from
window_number = self.vim.eval(
"bufwinnr({0})".format(current_buffer.number)
)
self.vim.command("{0}wincmd w".format(window_number))
return
# find the terminal buffer in the list of buffers, open it in a split
for buf in self.vim.buffers:
if buf.name.startswith("term://"):
self.vim.command("botright sb {0}".format(buf.number))
return
# create a new terminal when there is no terminal buffer
self.vim.command("botright new")
self.vim.command(":terminal")
|
Validate URI in project config schema | <?php
namespace Drubo\Config\Project;
use Drubo\Config\ConfigSchema;
use Drubo\DruboAwareInterface;
use Drubo\DruboAwareTrait;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Validator\Constraints\Url;
/**
* Schema class for drubo project configuration files.
*/
class ProjectConfigSchema extends ConfigSchema implements ConfigurationInterface, DruboAwareInterface {
use DruboAwareTrait;
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('config');
$environmentList = $this->getDrubo()
->getEnvironmentList()
->toArray();
$rootNode
->children()
->scalarNode('environment')
->isRequired()
->cannotBeEmpty()
->validate()
->ifNotInArray($environmentList)
->thenInvalid('Invalid environment %s')
->end()
->end()
->scalarNode('uri')
->isRequired()
->cannotBeEmpty()
->validate()
->always(function ($v) {
$violations = $this->getDrubo()
->getValidator()
->validate($v, new Url());
/** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
throw new \Exception($violation->getMessage());
}
return $v;
})
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Drubo\Config\Project;
use Drubo\Config\ConfigSchema;
use Drubo\DruboAwareInterface;
use Drubo\DruboAwareTrait;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\UrlValidator;
/**
* Schema class for drubo project configuration files.
*/
class ProjectConfigSchema extends ConfigSchema implements ConfigurationInterface, DruboAwareInterface {
use DruboAwareTrait;
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder() {
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('config');
$environmentList = $this->getDrubo()
->getEnvironmentList()
->toArray();
$rootNode
->children()
->scalarNode('environment')
->isRequired()
->cannotBeEmpty()
->validate()
->ifNotInArray($environmentList)
->thenInvalid('Invalid environment %s')
->end()
->end()
->scalarNode('uri')
->isRequired()
->cannotBeEmpty()
->validate()
->always(function ($v) {
// TODO Url validation
// $x = new UrlValidator();
// $x->validate($v, new Url());
return $v;
})
->end()
->end()
->end();
return $treeBuilder;
}
}
|
Move json print methods into if statement | import os
import json
from dateutil.parser import parse
from scrapi.util import safe_filename
def migrate_from_old_scrapi():
for dirname, dirs, filenames in os.walk('archive'):
for filename in filenames:
oldpath = os.path.join(dirname, filename)
source, sid, dt = dirname.split('/')[1:]
dt = parse(dt).isoformat()
sid = safe_filename(sid)
newpath = os.path.join('archive', source, sid, dt, filename)
if filename == 'manifest.json':
with open(oldpath) as old:
old_json = json.load(old)
new_json = {
'consumerVersion': old_json['version'],
'normalizeVersion': old_json['version'],
'timestamp': dt,
'source': source,
'id': sid
}
old_json = json.dumps(old_json, indent=4, sort_keys=True)
new_json = json.dumps(new_json, indent=4, sort_keys=True)
print old_json
print new_json
print '{} -> {}'.format(oldpath, newpath)
| import os
import json
from dateutil.parser import parse
from scrapi.util import safe_filename
def migrate_from_old_scrapi():
for dirname, dirs, filenames in os.walk('archive'):
for filename in filenames:
oldpath = os.path.join(dirname, filename)
source, sid, dt = dirname.split('/')[1:]
dt = parse(dt).isoformat()
sid = safe_filename(sid)
newpath = os.path.join('archive', source, sid, dt, filename)
if filename == 'manifest.json':
with open(oldpath) as old:
old_json = json.load(old)
new_json = {
'consumerVersion': old_json['version'],
'normalizeVersion': old_json['version'],
'timestamp': dt,
'source': source,
'id': sid
}
old_json = json.dumps(old_json, indent=4, sort_keys=True)
new_json = json.dumps(new_json, indent=4, sort_keys=True)
print '{} -> {}'.format(oldpath, newpath)
print old_json
print new_json
|
Rewrite inserting function. It can be a lot simpler now we know we're always dealing with up-to-date data. |
def import_question(posts, namespaces, id, title, body, tags, last_activity_date, last_updated_date, score, answer_count, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
posts.update({"question_id": id}, post, True);
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
|
def import_question(posts, namespaces, id, title, body, tags, last_activity_date, last_updated_date, score, answer_count, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = posts.find_one({"question_id": int(id)})
previously_existed = False
update = True
if post:
previously_existed = True
# Only update title, score etc. if this is the latest data
update = post["last_activity"] < last_activity_date
else:
post = {
"question_id": int(id),
"url": "http://stackoverflow.com/questions/%s" % id
}
post["namespaces"] = namespaces_for_post
if update:
post["title"] = title
post["score"] = int(score)
post["answers"] = int(answer_count)
post["accepted_answer"] = has_accepted_answer
post["last_activity"] = last_activity_date
post["last_updated"] = last_updated_date
if previously_existed:
posts.update({"question_id": int(id)}, post)
else:
posts.insert(post)
update_text = "Fully updated" if update else "Partially updated"
print "%s %s question from %s (%s)" % (update_text if previously_existed else "Inserted", ", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
|
Update 1.0 release with latest version of pid sequence migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from pidman.pid.noid import decode_noid, encode_noid
from pidman.pid import models as pid_models
def pid_sequence_lastvalue(apps, schema_editor):
# if the database has existing pids, update the sequence last value
# so it will start minting pids starting after the current set
Pid = apps.get_model("pid", "Pid")
Sequence = apps.get_model("sequences", "Sequence")
if Pid.objects.count():
# pid noids are generated in sequence, so the pid with the
# highest pk _should_ be the one with the highest noid
max_noid = Pid.objects.all().order_by('pk').last().pid
# (previously using aggregate max, but doesn't seem to find
# the highest pid value correctly)
last_val = decode_noid(max_noid)
pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME)
pid_seq.last = last_val
pid_seq.save()
def remove_pid_sequence(apps, schema_editor):
Sequence = apps.get_model("sequences", "Sequence")
Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete()
class Migration(migrations.Migration):
dependencies = [
('pid', '0001_initial'),
('sequences', '0001_initial'),
]
operations = [
migrations.RunPython(pid_sequence_lastvalue,
remove_pid_sequence),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from pidman.pid.noid import decode_noid
from pidman.pid import models as pid_models
def pid_sequence_lastvalue(apps, schema_editor):
# if the database has existing pids, update the sequence last value
# so it will start minting pids starting after the current set
Pid = apps.get_model("pid", "Pid")
Sequence = apps.get_model("sequences", "Sequence")
if Pid.objects.count():
print Pid.objects.count()
max_noid = Pid.objects.all() \
.aggregate(models.Max('pid')).values()[0]
last_val = decode_noid(max_noid)
pid_seq, created = Sequence.objects.get_or_create(name=pid_models.Pid.SEQUENCE_NAME)
pid_seq.last = last_val
pid_seq.save()
def remove_pid_sequence(apps, schema_editor):
Sequence = apps.get_model("sequences", "Sequence")
Sequence.objects.get(name=pid_models.Pid.SEQUENCE_NAME).delete()
class Migration(migrations.Migration):
dependencies = [
('pid', '0001_initial'),
('sequences', '0001_initial'),
]
operations = [
migrations.RunPython(pid_sequence_lastvalue,
remove_pid_sequence),
]
|
Switch to using the `add_arguments` method.
This is an alternative to using the `option_list` and
`optparse.make_option`. Django deprecated the use of `optparse` in
management commands in Django 1.8 and removed it in Django 1.10. | import tempfile
import sys
from django.core.management.base import BaseCommand
from ...lockfile import FileLock, FileLocked
from ...mail import send_queued
from ...logutils import setup_loghandlers
logger = setup_loghandlers()
default_lockfile = tempfile.gettempdir() + "/post_office"
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('-p', '--processes',
type='int',
help='Number of processes used to send emails',
default=1
)
parser.add_argument('-L', '--lockfile',
type='string',
default=default_lockfile,
help='Absolute path of lockfile to acquire'
)
parser.add_argument('-l', '--log-level',
type='int',
help='"0" to log nothing, "1" to only log errors'
)
def handle(self, *args, **options):
logger.info('Acquiring lock for sending queued emails at %s.lock' %
options['lockfile'])
try:
with FileLock(options['lockfile']):
try:
send_queued(options['processes'], options.get('log_level'))
except Exception as e:
logger.error(e, exc_info=sys.exc_info(), extra={'status_code': 500})
raise
except FileLocked:
logger.info('Failed to acquire lock, terminating now.')
| import tempfile
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from ...lockfile import FileLock, FileLocked
from ...mail import send_queued
from ...logutils import setup_loghandlers
logger = setup_loghandlers()
default_lockfile = tempfile.gettempdir() + "/post_office"
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-p', '--processes', type='int',
help='Number of processes used to send emails', default=1),
make_option('-L', '--lockfile', type='string', default=default_lockfile,
help='Absolute path of lockfile to acquire'),
make_option('-l', '--log-level', type='int',
help='"0" to log nothing, "1" to only log errors'),
)
def handle(self, *args, **options):
logger.info('Acquiring lock for sending queued emails at %s.lock' %
options['lockfile'])
try:
with FileLock(options['lockfile']):
try:
send_queued(options['processes'], options.get('log_level'))
except Exception as e:
logger.error(e, exc_info=sys.exc_info(), extra={'status_code': 500})
raise
except FileLocked:
logger.info('Failed to acquire lock, terminating now.')
|
Indent with 8 spaces instead of 2 tabs
Similar to the rest. | <?= '<?php' ?>
/**
* An helper file for Laravel 4, to provide autocomplete information to your IDE
* Generated for Laravel <?= $version ?> on <?= date("Y-m-d") ?>.
*
* @author Barry vd. Heuvel <[email protected]>
* @see https://github.com/barryvdh/laravel-ide-helper
*/
<?php foreach($namespaces as $namespace => $aliases): ?>
namespace <?= $namespace == '__root' ? '' : $namespace ?>{
<?php if($namespace == '__root'): ?>
exit("This file should not be included, only analyzed by your IDE");
<?= $helpers ?>
<?php endif; ?>
<?php foreach($aliases as $alias): ?>
<?= $alias->getClassType() ?> <?= $alias->getAlias() ?> <?= $alias->getExtends() ? 'extends ' . $alias->getExtends() : '' ?>{
<?php foreach($alias->getMethods() as $method): ?>
<?= trim($method->getDocComment(' ')) ?>
public static function <?= $method->getName() ?>(<?= $method->getParamsWithDefault() ?>){<?php if($method->getDeclaringClass() !== $method->getRoot()): ?>
//Method inherited from <?= $method->getDeclaringClass() ?>
<?php endif; ?>
<?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getName() ?>(<?= $method->getParams() ?>);
}
<?php endforeach; ?>
}
<?php endforeach; ?>
}
<?php endforeach; ?>
| <?= '<?php' ?>
/**
* An helper file for Laravel 4, to provide autocomplete information to your IDE
* Generated for Laravel <?= $version ?> on <?= date("Y-m-d") ?>.
*
* @author Barry vd. Heuvel <[email protected]>
* @see https://github.com/barryvdh/laravel-ide-helper
*/
<?php foreach($namespaces as $namespace => $aliases): ?>
namespace <?= $namespace == '__root' ? '' : $namespace ?>{
<?php if($namespace == '__root'): ?>
exit("This file should not be included, only analyzed by your IDE");
<?= $helpers ?>
<?php endif; ?>
<?php foreach($aliases as $alias): ?>
<?= $alias->getClassType() ?> <?= $alias->getAlias() ?> <?= $alias->getExtends() ? 'extends ' . $alias->getExtends() : '' ?>{
<?php foreach($alias->getMethods() as $method): ?>
<?= trim($method->getDocComment()) ?>
public static function <?= $method->getName() ?>(<?= $method->getParamsWithDefault() ?>){<?php if($method->getDeclaringClass() !== $method->getRoot()): ?>
//Method inherited from <?= $method->getDeclaringClass() ?>
<?php endif; ?>
<?= $method->shouldReturn() ? 'return ': '' ?><?= $method->getRoot() ?>::<?= $method->getName() ?>(<?= $method->getParams() ?>);
}
<?php endforeach; ?>
}
<?php endforeach; ?>
}
<?php endforeach; ?>
|
Move redundant check to first point of contact | import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
continue
if items[index] > items[pivot]:
greater.append(items[index])
else:
less.append(items[index])
return sort(less) + [items[pivot]] + sort(greater)
def quicksort(items):
""" In-place quicksort with random pivot """
if len(items) < 2:
return
if items is None:
raise TypeError("Collection cannot be of type None")
_quicksort(items, 0, len(items) - 1)
def _quicksort(items, first, last):
if first >= last:
return
pivot = items[random.randint(first, last)]
head, tail = first, last
while head <= tail:
while items[head] < pivot:
head += 1
while items[tail] > pivot:
tail -= 1
if head <= tail:
items[head], items[tail] = items[tail], items[head]
head += 1
tail -= 1
_quicksort(items, first, tail)
_quicksort(items, head, last)
| import random
def sort(items):
if items is None:
raise TypeError("Collection cannot be of type None")
if len(items) < 2:
return items
pivot = random.randint(0, len(items) - 1)
greater = []
less = []
for index in range(0, len(items)):
if index == pivot:
continue
if items[index] > items[pivot]:
greater.append(items[index])
else:
less.append(items[index])
return sort(less) + [items[pivot]] + sort(greater)
def quicksort(items):
""" In-place quicksort with random pivot """
if items is None:
raise TypeError("Collection cannot be of type None")
_quicksort(items, 0, len(items) - 1)
def _quicksort(items, first, last):
if first >= last:
return
if len(items) < 2:
return
pivot = items[random.randint(first, last)]
head, tail = first, last
while head <= tail:
while items[head] < pivot:
head += 1
while items[tail] > pivot:
tail -= 1
if head <= tail:
items[head], items[tail] = items[tail], items[head]
head += 1
tail -= 1
_quicksort(items, first, tail)
_quicksort(items, head, last)
|
Add support for otf fonts | const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './app/src/app.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.js'
},
plugins: [
// Copy our app's index.html to the build folder.
new CopyWebpackPlugin([
{from: './app/index.html', to: "index.html"}
])
],
module: {
rules: [
{
test: /\.css$/,
use: [
{loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"
}
}
]
},
{test: /\.json$/, use: 'json-loader'},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader'
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader',
options: {
limit: 25000,
}
},
{
test: /\.(ttf|svg|eot|otf)$/,
loader: 'file-loader',
options: {
name: 'fonts/[hash].[ext]',
},
},
]
}
}
| const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './app/src/app.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.js'
},
plugins: [
// Copy our app's index.html to the build folder.
new CopyWebpackPlugin([
{from: './app/index.html', to: "index.html"}
])
],
module: {
rules: [
{
test: /\.css$/,
use: [
{loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"
}
}
]
},
{test: /\.json$/, use: 'json-loader'},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader'
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader',
options: {
limit: 25000,
}
},
{
test: /\.(ttf|svg|eot)$/,
loader: 'file-loader',
options: {
name: 'fonts/[hash].[ext]',
},
},
]
}
}
|
Fix 'remember_me' column not found error | <?php
namespace Illuminate\Auth;
trait Authenticatable
{
/**
* Variable containing "remember me" column name.
*
* @var string
*/
protected $remember_column = 'remember_token';
/**
* Get the name of the unique identifier for the user.
*
* @return string
*/
public function getAuthIdentifierName()
{
return $this->getKeyName();
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
if (! empty($this->getRememberTokenName())) {
return $this->{$this->getRememberTokenName()};
}
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
if (! empty($this->getRememberTokenName())) {
$this->{$this->getRememberTokenName()} = $value;
}
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return $this->remember_column;
}
}
| <?php
namespace Illuminate\Auth;
trait Authenticatable
{
/**
* Get the name of the unique identifier for the user.
*
* @return string
*/
public function getAuthIdentifierName()
{
return $this->getKeyName();
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->{$this->getRememberTokenName()};
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->{$this->getRememberTokenName()} = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
}
|
Fix typo in copy/pasta controllerneeds suite | describe('lib/rules/disallow-controllerneeds', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowControllerNeeds: undefined});
}).to.throws(/requires a boolean value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowControllerNeeds: {}});
}).to.throws(/requires a boolean value/i);
});
});
describe('with true', function() {
checker.rules({disallowControllerNeeds: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report controller injection',
code: function() {
Ember.Controller.extend({
comments: Ember.inject.controller(),
newComments: Ember.computed.alias('comments.newest')
});
}
}, {
it: 'should report needs string',
errors: 1,
code: function() {
Ember.Controller.extend({
needs: "post",
});
}
}, {
it: 'should report needs array',
errors: 1,
code: function() {
Ember.Controller.extend({
needs: ['comments'],
newComments: Ember.computed.alias('controllers.comments.newest')
});
}
}
/* jshint ignore:end */
]);
});
});
| describe('lib/rules/disallow-positionalparams-extend', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowControllerNeeds: undefined});
}).to.throws(/requires a boolean value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowControllerNeeds: {}});
}).to.throws(/requires a boolean value/i);
});
});
describe('with true', function() {
checker.rules({disallowControllerNeeds: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report controller injection',
code: function() {
Ember.Controller.extend({
comments: Ember.inject.controller(),
newComments: Ember.computed.alias('comments.newest')
});
}
}, {
it: 'should report needs string',
errors: 1,
code: function() {
Ember.Controller.extend({
needs: "post",
});
}
}, {
it: 'should report needs array',
errors: 1,
code: function() {
Ember.Controller.extend({
needs: ['comments'],
newComments: Ember.computed.alias('controllers.comments.newest')
});
}
}
/* jshint ignore:end */
]);
});
});
|
Hide and show the component element inside of the container. | /**
* @module Core
*/
define([
'core/modules/GelatoView'
], function(GelatoView) {
/**
* @class GelatoComponent
* @extends GelatoView
*/
var GelatoComponent = GelatoView.extend({
/**
* @property component
* @typeof {jQuery}
*/
$component: null,
/**
* @method renderTemplate
* @param {String} template
* @returns {GelatoView}
*/
renderTemplate: function(template) {
GelatoView.prototype.renderTemplate.call(this, template);
this.$component = $(this.$('gelato-component').get(0));
return this;
},
/**
* @method getName
* @returns {String}
*/
getName: function() {
return this.$component.data('name');
},
/**
* @method height
* @param {Number} [size]
* @returns {Number}
*/
height: function(size) {
return this.$component.height(size);
},
/**
* @method hide
* @returns {GelatoView}
*/
hide: function() {
this.$component.hide();
return this;
},
/**
* @method show
* @returns {GelatoView}
*/
show: function() {
this.$component.show();
return this;
},
/**
* @method width
* @param {Number} [size]
* @returns {Number}
*/
width: function(size) {
return this.$component.width(size);
}
});
return GelatoComponent;
}); | /**
* @module Core
*/
define([
'core/modules/GelatoView'
], function(GelatoView) {
/**
* @class GelatoComponent
* @extends GelatoView
*/
var GelatoComponent = GelatoView.extend({
/**
* @property component
* @typeof {jQuery}
*/
$component: null,
/**
* @method renderTemplate
* @param {String} template
* @returns {GelatoView}
*/
renderTemplate: function(template) {
GelatoView.prototype.renderTemplate.call(this, template);
this.$component = $(this.$('gelato-component').get(0));
return this;
},
/**
* @method getComponent
* @returns {jQuery}
*/
getComponent: function() {
return this.$component;
},
/**
* @method getName
* @returns {String}
*/
getName: function() {
return this.$component.data('name');
},
/**
* @method height
* @param {Number} [size]
* @returns {Number}
*/
height: function(size) {
return this.$component.height(size);
},
/**
* @method width
* @param {Number} [size]
* @returns {Number}
*/
width: function(size) {
return this.$component.width(size);
}
});
return GelatoComponent;
}); |
Fix a bug in documentation generation | /* task for generating html from sisdocs markdown */
module.exports = function(grunt) {
'use strict';
var marked = require('marked');
var hljs = require('highlight.js');
var renderer = new marked.Renderer();
var oldLink = renderer.link;
renderer.link = function(href, title, text) {
if (href[0] === '#' && text.indexOf('.') !== -1) {
href = '#' + text.replace(/[^\w:]/g, '-').toLowerCase();
}
return oldLink.call(this, href, title, text);
};
marked.setOptions({
breaks : true,
highlight: function(code, lang) {
var result = hljs.highlight(lang, code).value;
return result;
},
renderer : renderer
});
grunt.registerMultiTask('sismd', "Converts SIS-web markdown to html", function() {
var options = this.options({ });
this.files.forEach(function(file) {
var data = file.src.filter(function(path) {
if (!grunt.file.isFile(path)) {
grunt.log.warn("File does not exist. %s", source);
return false;
}
return true;
}).map(function(path) {
return grunt.file.read(path);
}).join("\n");
var dest = file.dest;
if (options.preprocess) {
data = options.preprocess(data);
}
var output = marked(data);
grunt.file.write(dest, output);
});
});
};
| /* task for generating html from sisdocs markdown */
module.exports = function(grunt) {
'use strict';
var marked = require('marked');
var hljs = require('highlight.js');
marked.setOptions({
breaks : true,
highlight: function(code, lang) {
var result = hljs.highlight(lang, code).value;
return result;
}
});
grunt.registerMultiTask('sismd', "Converts SIS-web markdown to html", function() {
var options = this.options({ });
this.files.forEach(function(file) {
var data = file.src.filter(function(path) {
if (!grunt.file.isFile(path)) {
grunt.log.warn("File does not exist. %s", source);
return false;
}
return true;
}).map(function(path) {
return grunt.file.read(path);
}).join("\n");
var dest = file.dest;
if (options.preprocess) {
data = options.preprocess(data);
}
var output = marked(data);
grunt.file.write(dest, output);
});
});
};
|
Add `${temp_file}` marker to `cmd`
Implicit adding of the `${temp_file}` by the framework has been deprecated and SublimeLinter also logs about it. | from SublimeLinter.lint import Linter, util
class CSSLint(Linter):
cmd = 'csslint --format=compact ${temp_file}'
regex = r'''(?xi)
^.+:\s* # filename
# csslint emits errors that pertain to the code as a whole,
# in which case there is no line/col information, so that
# part is optional.
(?:line\ (?P<line>\d+),\ col\ (?P<col>\d+),\ )?
(?:(?P<error>error)|(?P<warning>warning))\ -\ (?P<message>.*)
'''
word_re = r'^([#\.]?[-\w]+)'
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'css'
defaults = {
'selector': 'source.css - meta.attribute-with-value',
'--errors=,': '',
'--warnings=,': '',
'--ignore=,': ''
}
def split_match(self, match):
"""
Extract and return values from match.
We override this method so that general errors that do not have
a line number can be placed at the beginning of the code.
"""
match, line, col, error, warning, message, near = super().split_match(match)
if line is None and message:
line = 0
col = 0
return match, line, col, error, warning, message, near
| from SublimeLinter.lint import Linter, util
class CSSLint(Linter):
cmd = 'csslint --format=compact'
regex = r'''(?xi)
^.+:\s* # filename
# csslint emits errors that pertain to the code as a whole,
# in which case there is no line/col information, so that
# part is optional.
(?:line\ (?P<line>\d+),\ col\ (?P<col>\d+),\ )?
(?:(?P<error>error)|(?P<warning>warning))\ -\ (?P<message>.*)
'''
word_re = r'^([#\.]?[-\w]+)'
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'css'
defaults = {
'selector': 'source.css - meta.attribute-with-value',
'--errors=,': '',
'--warnings=,': '',
'--ignore=,': ''
}
def split_match(self, match):
"""
Extract and return values from match.
We override this method so that general errors that do not have
a line number can be placed at the beginning of the code.
"""
match, line, col, error, warning, message, near = super().split_match(match)
if line is None and message:
line = 0
col = 0
return match, line, col, error, warning, message, near
|
Change groupname from 64 char to 256 | <?php
namespace modl;
class RosterLink extends Model
{
public $session;
public $jid;
public $rosterask;
public $rostersubscription;
public $publickey;
public $rostername;
public $groupname;
public $_struct = [
'session' => ['type' => 'string','size' => 64,'key' => true],
'jid' => ['type' => 'string','size' => 96,'key' => true],
'rostername' => ['type' => 'string','size' => 96],
'rosterask' => ['type' => 'string','size' => 16],
'rostersubscription' => ['type' => 'string','size' => 4,'mandatory' => true],
'groupname' => ['type' => 'string','size' => 256]
];
function set($stanza)
{
$this->jid = (string)$stanza->attributes()->jid;
if (isset($stanza->attributes()->name)
&& (string)$stanza->attributes()->name != '')
$this->rostername = (string)$stanza->attributes()->name;
else
$this->rostername = (string)$stanza->attributes()->jid;
$this->rosterask = (string)$stanza->attributes()->ask;
$this->rostersubscription = (string)$stanza->attributes()->subscription;
$this->groupname = (string)$stanza->group;
}
}
| <?php
namespace modl;
class RosterLink extends Model
{
public $session;
public $jid;
public $rosterask;
public $rostersubscription;
public $publickey;
public $rostername;
public $groupname;
public $_struct = [
'session' => ['type' => 'string','size' => 64,'key' => true],
'jid' => ['type' => 'string','size' => 96,'key' => true],
'rostername' => ['type' => 'string','size' => 96],
'rosterask' => ['type' => 'string','size' => 16],
'rostersubscription' => ['type' => 'string','size' => 4,'mandatory' => true],
'groupname' => ['type' => 'string','size' => 64]
];
function set($stanza)
{
$this->jid = (string)$stanza->attributes()->jid;
if (isset($stanza->attributes()->name)
&& (string)$stanza->attributes()->name != '')
$this->rostername = (string)$stanza->attributes()->name;
else
$this->rostername = (string)$stanza->attributes()->jid;
$this->rosterask = (string)$stanza->attributes()->ask;
$this->rostersubscription = (string)$stanza->attributes()->subscription;
$this->groupname = (string)$stanza->group;
}
}
|
Fix stderr from playerctl bar | # py3status module for playerctl
import subprocess
def run(*cmdlist):
return subprocess.run(
cmdlist,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
| # py3status module for playerctl
import subprocess
def run(*cmdlist):
return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode()
def player_args(players):
if not players:
return 'playerctl',
else:
return 'playerctl', '-p', players
def get_status(players):
status = run(*player_args(players), 'status')[:-1]
if status in ('Playing', 'Paused'):
return status
return ''
def get_info(players, fmt):
args = 'metadata', '--format', f'{fmt}'
return run(*player_args(players), *args).strip()
class Py3status:
players = ''
format = '{{ artist }} / {{ title }}'
def spotbar(self):
text_format = "[[ {info} ]]|[ {status} ]"
params = {'status': get_status(self.players)}
if params['status'] == 'Playing':
params['info'] = get_info(self.players, self.format)
if params['info'] == '/ -':
params['info'] = None
return {
'full_text': self.py3.safe_format(text_format, params),
'cached_until': self.py3.time_in(seconds=1)
}
def on_click(self, event):
if event['button'] == 1:
run('playerctl', 'play-pause')
if __name__ == '__main__':
from py3status.module_test import module_test
module_test(Py3status)
|
Allow ManyToMany relationship sapce_people until better solution | package com.parrit.entities;
import javax.persistence.*;
import java.util.Collection;
@Entity
public class Space {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToMany(targetEntity = Person.class)
private Collection<Person> people;
private String name;
public Space() {}
public Space(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Collection<Person> getPeople() {
return people;
}
public void setPeople(Collection<Person> people) {
this.people = people;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Space space = (Space) o;
if (id != space.id) return false;
if (people != null ? !people.equals(space.people) : space.people != null) return false;
if (name != null ? !name.equals(space.name) : space.name == null) return false;
return true;
}
@Override
public String toString() {
return "Space{" +
"id=" + id +
", people=" + people +
", name='" + name + '\'' +
'}';
}
}
| package com.parrit.entities;
import javax.persistence.*;
import java.util.Collection;
@Entity
public class Space {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(targetEntity = Person.class)
private Collection<Person> people;
private String name;
public Space() {}
public Space(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Collection<Person> getPeople() {
return people;
}
public void setPeople(Collection<Person> people) {
this.people = people;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Space space = (Space) o;
if (id != space.id) return false;
if (people != null ? !people.equals(space.people) : space.people != null) return false;
if (name != null ? !name.equals(space.name) : space.name == null) return false;
return true;
}
@Override
public String toString() {
return "Space{" +
"id=" + id +
", people=" + people +
", name='" + name + '\'' +
'}';
}
}
|
Handle query middleware failing tests | 'use strict';
require('../helper');
const server = require('../../app/server')();
const assert = require('../support/assert');
const qs = require('querystring');
const QUERY = `SELECT 14 as foo`;
const API_KEY = 1234;
describe.only('Handle query middleware', function() {
['GET', 'POST'].forEach(method => {
it(`${method} without query fails`, function(done) {
assert.response(server,
{
method,
url: '/api/v1/sql?' + qs.stringify({
api_key: API_KEY
}),
headers: {
host: 'vizzuality.cartodb.com'
}
},
{ statusCode: 400 },
function(err, res) {
assert.ok(!err);
const response = JSON.parse(res.body);
assert.deepEqual(response, { error: ["You must indicate a sql query"] });
done();
}
);
});
it(`${method} query`, function(done) {
assert.response(server,
{
method,
url: '/api/v1/sql?' + qs.stringify({
q: QUERY,
api_key: API_KEY
}),
headers: {
host: 'vizzuality.cartodb.com'
}
},
{ statusCode: 200 },
function(err, res) {
assert.ok(!err);
const response = JSON.parse(res.body);
assert.equal(response.rows.length, 1);
assert.equal(response.rows[0].foo, 14);
done();
}
);
});
});
});
| 'use strict';
require('../helper');
const server = require('../../app/server')();
const assert = require('../support/assert');
const qs = require('querystring');
const QUERY = `SELECT 14 as foo`;
const API_KEY = 1234;
const BODY_PAYLOAD = {
q: QUERY,
api_key: API_KEY
};
describe.only('Handle query middleware', function() {
['GET', 'POST'].forEach(method => {
it(`${method} query`, function(done) {
assert.response(server,
{
method,
url: '/api/v1/sql?' + qs.stringify(BODY_PAYLOAD),
headers: {
host: 'vizzuality.cartodb.com'
}
},
{ statusCode: 200 },
function(err, res) {
assert.ok(!err);
const response = JSON.parse(res.body);
assert.equal(response.rows.length, 1);
assert.equal(response.rows[0].foo, 14);
done();
}
);
});
});
});
|
Update marko example to hapi v17 | 'use strict';
// Load modules
const Hapi = require('hapi');
const Vision = require('../..');
const Path = require('path');
const Marko = require('marko');
// Declare internals
const internals = {
templatePath: '.'
};
const today = new Date();
internals.thisYear = today.getFullYear();
const rootHandler = (request, h) => {
const relativePath = Path.relative(`${__dirname}/../..`, `${__dirname}/templates/${internals.templatePath}`);
return h.view('index', {
title: `Running ${relativePath} | Hapi ${request.server.version}`,
message: 'Hello Marko!',
year: internals.thisYear
});
};
internals.main = async () => {
const server = Hapi.Server({ port: 3000 });
await server.register(Vision);
server.views({
engines: {
marko: {
compile: (src, options) => {
const template = Marko.load(options.filename, { preserveWhitespace: true, writeToDisk: false });
return (context) => {
return template.renderToString(context);
};
}
}
},
relativeTo: __dirname,
path: `templates/${internals.templatePath}`
});
server.route({ method: 'GET', path: '/', handler: rootHandler });
await server.start();
console.log('Server is running at ' + server.info.uri);
};
internals.main();
| 'use strict';
// Load modules
const Hapi = require('hapi');
const Vision = require('../..');
const Path = require('path');
const Marko = require('marko');
// Declare internals
const internals = {
templatePath: '.'
};
const today = new Date();
internals.thisYear = today.getFullYear();
const rootHandler = (request, h) => {
const relativePath = Path.relative(`${__dirname}/../..`, `${__dirname}/templates/${internals.templatePath}`);
return h.view('index', {
title: `Running ${relativePath} | Hapi ${request.server.version}`,
message: 'Hello Marko!',
year: internals.thisYear
});
};
internals.main = async () => {
const server = Hapi.Server({port: 3000});
await server.register(Vision);
server.views({
engines: {
marko: {
compile: (src, options) => {
const template = Marko.load(options.filename, { preserveWhitespace: true, writeToDisk: false });
return (context) => {
return template.renderToString(context);
};
}
}
},
relativeTo: __dirname,
path: `templates/${internals.templatePath}`
});
server.route({method: 'GET', path: '/', handler: rootHandler});
await server.start();
console.log('Server is running at ' + server.info.uri);
};
internals.main();
|
Update connection to script to waitSeconds to load js |
from collections import OrderedDict
from IPython.display import Javascript
import json
from krisk.util import join_current_dir
ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/'
ECHARTS_FILE = 'echarts.min'
d_paths = OrderedDict({})
THEMES = ['dark','vintage','roma','shine','infographic','macarons']
THEMES_URL='//echarts.baidu.com/asset/theme/'
PATH_LOCAL = join_current_dir('static')
# PATH_LOCAL = 'pandas-echarts/krisk/static'
#TODO FIX LOCAL PATH! NEED TO DO nbextension install
# def init_notebook():
# """Inject Javascript to notebook, default using local js.
# """
# return Javascript("""
# require.config({
# baseUrl : '%s',
# paths: {
# echarts: 'echarts.min'
# }
# });
# """ % PATH_LOCAL)
def init_notebook():
"""Inject Javascript to notebook, default using local js.
"""
return Javascript("""
require.config({
baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static",
paths: {
echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min"
},
waitSeconds: 15
});
""")
def get_paths():
return ['echarts'] + THEMES
|
from collections import OrderedDict
from IPython.display import Javascript
import json
from krisk.util import join_current_dir
ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/'
ECHARTS_FILE = 'echarts.min'
d_paths = OrderedDict({})
THEMES = ['dark','vintage','roma','shine','infographic','macarons']
THEMES_URL='//echarts.baidu.com/asset/theme/'
PATH_LOCAL = join_current_dir('static')
# PATH_LOCAL = 'pandas-echarts/krisk/static'
#TODO FIX LOCAL PATH! NEED TO DO nbextension install
# def init_notebook():
# """Inject Javascript to notebook, default using local js.
# """
# return Javascript("""
# require.config({
# baseUrl : '%s',
# paths: {
# echarts: 'echarts.min'
# }
# });
# """ % PATH_LOCAL)
def init_notebook():
"""Inject Javascript to notebook, default using local js.
"""
return Javascript("""
require.config({
baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static",
paths: {
echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min"
}
});
""")
def get_paths():
return ['echarts'] + THEMES
|
Fix "Cannot read property 'startContainer' of undefined" caused by code assuming that saveSelection always returns a range or null and never undefined. Update saveSelection to never return undefined. | define([], function() {
var saveSelection, restoreSelection;
if (window.getSelection && document.createRange) {
saveSelection = function(el) {
var sel = window.getSelection && window.getSelection();
if (sel && sel.rangeCount > 0) {
return sel.getRangeAt(0);
} else {
return null;
}
};
restoreSelection = function(el, sel) {
var range = document.createRange();
range.setStart(sel.startContainer, sel.startOffset);
range.setEnd(sel.endContainer, sel.endOffset)
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.body.createTextRange) {
saveSelection = function(el) {
return document.selection.createRange();
};
restoreSelection = function(el, sel) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.setStart(sel.startContanier, sel.startOffset);
textRange.setEnd(sel.endContainer, sel.endOffset);
textRange.select();
};
}
});
| define([], function() {
var saveSelection, restoreSelection;
if (window.getSelection && document.createRange) {
saveSelection = function(el) {
var sel = window.getSelection && window.getSelection();
if (sel && sel.rangeCount > 0) {
return sel.getRangeAt(0);
}
};
restoreSelection = function(el, sel) {
var range = document.createRange();
range.setStart(sel.startContainer, sel.startOffset);
range.setEnd(sel.endContainer, sel.endOffset)
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.body.createTextRange) {
saveSelection = function(el) {
return document.selection.createRange();
};
restoreSelection = function(el, sel) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.setStart(sel.startContanier, sel.startOffset);
textRange.setEnd(sel.endContainer, sel.endOffset);
textRange.select();
};
}
});
|
fix(Storage): Use promises correctly, fixes storage clearing error display | 'use strict';
/**
* @ngdoc function
* @name MatchCalendarApp.controller:SettingsCtrl
* @description
* # SettingsCtrl
* Controller of the MatchCalendarApp
*/
angular.module('MatchCalendarApp')
.controller('SettingsCtrl', function ($scope, NotifcationTimeFormat, $localForage, $modal, $window) {
$scope.addSubreddit = function (name) {
if (name === '' || name === null || name === undefined) {
return;
}
if ($scope.settings.subreddits.indexOf(name) === -1) {
$scope.settings.subreddits.push(name);
}
};
$scope.removeSubreddit = function (index) {
$scope.settings.subreddits.splice(index, 1);
};
$scope.removeNotificationTime = function (index) {
$scope.settings.notificationTimes.splice(index, 1);
};
$scope.newNotificationTime = function () {
$scope.settings.notificationTimes.push({value: 600});
};
$scope.translateSeconds = function (duration) {
return NotifcationTimeFormat.translateSeconds(duration);
};
$scope.clearStorage = function() {
$localForage.clear().then(
function() {
$window.location.reload();
},
function() {
$modal.open({
template: 'Failed to clear storage. You may need to clear it manually'
});
}
);
};
});
| 'use strict';
/**
* @ngdoc function
* @name MatchCalendarApp.controller:SettingsCtrl
* @description
* # SettingsCtrl
* Controller of the MatchCalendarApp
*/
angular.module('MatchCalendarApp')
.controller('SettingsCtrl', function ($scope, NotifcationTimeFormat, $localForage, $modal, $window) {
$scope.addSubreddit = function (name) {
if (name === '' || name === null || name === undefined) {
return;
}
if ($scope.settings.subreddits.indexOf(name) === -1) {
$scope.settings.subreddits.push(name);
}
};
$scope.removeSubreddit = function (index) {
$scope.settings.subreddits.splice(index, 1);
};
$scope.removeNotificationTime = function (index) {
$scope.settings.notificationTimes.splice(index, 1);
};
$scope.newNotificationTime = function () {
$scope.settings.notificationTimes.push({value: 600});
};
$scope.translateSeconds = function (duration) {
return NotifcationTimeFormat.translateSeconds(duration);
};
$scope.clearStorage = function() {
$localForage.clear().then(function() {
$window.location.reload();
}).fail(function() {
$modal.open({
template: 'Failed to clear storage. You may need to clear it manually'
});
});
};
});
|
Add a assertion to test the href of the link | // Polyfill MouseEvent for PhantomJS
if(MouseEvent === undefined) {
function MouseEvent(eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return mouseEvent;
}
}
function simulateMouseDown(element) {
var ev = new MouseEvent("mousedown", {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent(ev);
}
describe('Prefetch', function() {
describe('#hooks()', function() {
var el = document.createElement("a");
el.id = "myLink";
el.href = "http://localhost";
el.innerHTML = "Click me";
document.body.appendChild(el);
var prefetch = new Prefetch();
it("shouldn't create any link when no hyperlink have been clicked", function(done) {
var links = document.querySelectorAll("link[rel=prefetch]");
expect(links.length).to.equal(0);
done();
});
it('should create a link tag when the hyperlink is been clicked', function(done) {
var myLink = document.getElementById("myLink");
simulateMouseDown(myLink);
setTimeout(function() {
var links = document.querySelectorAll("link[rel=prefetch]");
expect(links.length).to.equal(1);
expect(links[0].href).to.equal(el.href);
done();
}, 5);
});
});
}); | // Polyfills
if(MouseEvent === undefined) {
function MouseEvent(eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return mouseEvent;
}
}
function simulateMouseDown(element) {
var ev = new MouseEvent("mousedown", {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent(ev);
}
var prefetch;
describe('Prefetch', function() {
describe('#hooks()', function() {
var el = document.createElement("a");
el.id = "myLink";
el.href = "localhost";
el.innerHTML = "Click me";
document.body.appendChild(el);
prefetch = new Prefetch();
it("shouldn't create any link when no hyperlink have been clicked", function(done) {
var links = document.querySelectorAll("link[rel=prefetch]");
expect(links.length).to.equal(0);
done();
});
it('should create a link tag when the hyperlink is been clicked', function(done) {
var myLink = document.getElementById("myLink");
simulateMouseDown(myLink);
setTimeout(function() {
var links = document.querySelectorAll("link[rel=prefetch]");
expect(links.length).to.equal(1);
done();
}, 5);
});
});
}); |
Make the cheapest shipping method the default one | from django.core.exceptions import ImproperlyConfigured
from oscar.apps.shipping.methods import Free, NoShippingRequired
class Repository(object):
"""
Repository class responsible for returning ShippingMethod
objects for a given user, basket etc
"""
def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):
"""
Return a list of all applicable shipping method objects
for a given basket.
We default to returning the Method models that have been defined but
this behaviour can easily be overridden by subclassing this class
and overriding this method.
"""
methods = [Free()]
return self.add_basket_to_methods(basket, methods)
def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs):
methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs)
if len(methods) == 0:
raise ImproperlyConfigured("You need to define some shipping methods")
return min(methods, key=lambda method: method.basket_charge_incl_tax())
def add_basket_to_methods(self, basket, methods):
for method in methods:
method.set_basket(basket)
return methods
def find_by_code(self, code):
"""
Return the appropriate Method object for the given code
"""
known_methods = [Free, NoShippingRequired]
for klass in known_methods:
if code == getattr(klass, 'code'):
return klass()
return None
| from django.core.exceptions import ImproperlyConfigured
from oscar.apps.shipping.methods import Free, NoShippingRequired
class Repository(object):
"""
Repository class responsible for returning ShippingMethod
objects for a given user, basket etc
"""
def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):
"""
Return a list of all applicable shipping method objects
for a given basket.
We default to returning the Method models that have been defined but
this behaviour can easily be overridden by subclassing this class
and overriding this method.
"""
methods = [Free()]
return self.add_basket_to_methods(basket, methods)
def get_default_shipping_method(self, user, basket, shipping_addr=None, **kwargs):
methods = self.get_shipping_methods(user, basket, shipping_addr, **kwargs)
if len(methods) == 0:
raise ImproperlyConfigured("You need to define some shipping methods")
return methods[0]
def add_basket_to_methods(self, basket, methods):
for method in methods:
method.set_basket(basket)
return methods
def find_by_code(self, code):
"""
Return the appropriate Method object for the given code
"""
known_methods = [Free, NoShippingRequired]
for klass in known_methods:
if code == getattr(klass, 'code'):
return klass()
return None
|
Remove quotation marks from returned strings. | function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: {
command: {
expr: code,
mode: mode
}
},
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = result.replace(/[<]/g, "<");
result = result.replace(/[>]/g, ">");
return result;
}
function onValidate(input) {
return (input != "");
}
function onHandle(line, report) {
var input = $.trim(line);
// perform evaluation
var data = eval_clojure(input);
// handle error
if (data.error) {
return [{msg: data.message, className: "jquery-console-message-error"}];
}
// display expr results
return [{
msg: data.result.replace(/"/g, ""),
className: "jquery-console-message-value"
}];
}
var controller;
$(document).ready(function() {
controller = $("#console").console({
welcomeMessage:'',
promptLabel: '> ',
commandValidate: onValidate,
commandHandle: onHandle,
autofocus:true,
animateScroll:true,
promptHistory:true
});
});
| function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: {
command: {
expr: code,
mode: mode
}
},
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = result.replace(/[<]/g, "<");
result = result.replace(/[>]/g, ">");
return result;
}
function onValidate(input) {
return (input != "");
}
function onHandle(line, report) {
var input = $.trim(line);
// perform evaluation
var data = eval_clojure(input);
// handle error
if (data.error) {
return [{msg: data.message, className: "jquery-console-message-error"}];
}
// display expr results
return [{msg: data.result, className: "jquery-console-message-value"}];
}
var controller;
$(document).ready(function() {
controller = $("#console").console({
welcomeMessage:'',
promptLabel: '> ',
commandValidate: onValidate,
commandHandle: onHandle,
autofocus:true,
animateScroll:true,
promptHistory:true
});
});
|
Set proxy port to right address | /*
| For up-to-date information about the options:
| http://www.browsersync.io/docs/options/
*/
module.exports = {
"ui": false, // { "port": 8181, "weinre": { "port": 8080 } },
"files": ['./'],
"watchOptions": {
ignoreInitial: true
},
"port": 8080,
"proxy": {
target: 'localhost:9292',
},
"serveStatic": [],
"ghostMode": {
"clicks": true,
"scroll": true,
"forms": {
"submit": true,
"inputs": true,
"toggles": true
}
},
"reloadOnRestart": false,
"notify": true,
"scrollProportionally": true,
"scrollThrottle": 0,
"scrollRestoreTechnique": "window.browse",
"reloadDelay": 0,
"reloadDebounce": 0,
"reloadThrottle": 0,
"plugins": [],
"injectChanges": true,
"startPath": null,
"minify": true,
"host": null,
"localOnly": true,
"codeSync": true,
"timestamps": true,
"socket": {
"socketIoOptions": {
"log": false
},
"socketIoClientConfig": {
"reconnectionAttempts": 50
},
"path": "/browser-sync/socket.io",
"clientPath": "/browser-sync",
"namespace": "/browser-sync",
"clients": {
"heartbeatTimeout": 5000
}
}
};
| /*
| For up-to-date information about the options:
| http://www.browsersync.io/docs/options/
*/
module.exports = {
"ui": false, // { "port": 8181, "weinre": { "port": 8080 } },
"files": ['./'],
"watchOptions": {
ignoreInitial: true
},
"port": 8080,
"proxy": {
target: 'localhost:9393',
},
"serveStatic": [],
"ghostMode": {
"clicks": true,
"scroll": true,
"forms": {
"submit": true,
"inputs": true,
"toggles": true
}
},
"reloadOnRestart": false,
"notify": true,
"scrollProportionally": true,
"scrollThrottle": 0,
"scrollRestoreTechnique": "window.browse",
"reloadDelay": 0,
"reloadDebounce": 0,
"reloadThrottle": 0,
"plugins": [],
"injectChanges": true,
"startPath": null,
"minify": true,
"host": null,
"localOnly": true,
"codeSync": true,
"timestamps": true,
"socket": {
"socketIoOptions": {
"log": false
},
"socketIoClientConfig": {
"reconnectionAttempts": 50
},
"path": "/browser-sync/socket.io",
"clientPath": "/browser-sync",
"namespace": "/browser-sync",
"clients": {
"heartbeatTimeout": 5000
}
}
};
|
Fix detach product(s) instead delete it | <?php namespace Octommerce\Octommerce\Console;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Octommerce\Octommerce\Models\Cart;
use Octommerce\Octommerce\Models\Settings;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class DeleteCart extends Command
{
/**
* @var string The console command name.
*/
protected $name = 'octommerce:delete-cart';
/**
* @var string The console command description.
*/
protected $description = 'Delete unused cart in a few days';
/**
* Execute the console command.
* @return void
*/
public function fire()
{
// Default value is 30 days
$inDays = Settings::get('delete_cart_in_days') ?: 30;
$maxDate = Carbon::now()->subDays($inDays);
Cart::with('products')
->whereDate('updated_at', '<', $maxDate)
->get()
->each(function($cart) {
$cart->products()->detach();
$cart->delete();
});
}
/**
* Get the console command arguments.
* @return array
*/
protected function getArguments()
{
return [];
}
/**
* Get the console command options.
* @return array
*/
protected function getOptions()
{
return [];
}
}
| <?php namespace Octommerce\Octommerce\Console;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Octommerce\Octommerce\Models\Cart;
use Octommerce\Octommerce\Models\Settings;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class DeleteCart extends Command
{
/**
* @var string The console command name.
*/
protected $name = 'octommerce:delete-cart';
/**
* @var string The console command description.
*/
protected $description = 'Delete unused cart in a few days';
/**
* Execute the console command.
* @return void
*/
public function fire()
{
// Default value is 30 days
$inDays = Settings::get('delete_cart_in_days') ?: 30;
$maxDate = Carbon::now()->subDays($inDays);
Cart::with('products')
->whereDate('updated_at', '<', $maxDate)
->get()
->each(function($cart) {
$cart->products()->delete();
$cart->delete();
});
}
/**
* Get the console command arguments.
* @return array
*/
protected function getArguments()
{
return [];
}
/**
* Get the console command options.
* @return array
*/
protected function getOptions()
{
return [];
}
}
|
Handle review deletion when updating categories for a context | from django.conf import settings
from django.shortcuts import render
from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from models import Context, Review, Keyword, Category
def index(request):
context = {'DEBUG': settings.DEBUG}
return render(request, 'index.html', context)
class PostContext(APIView):
def post(self, request, id):
context = Context.objects.get(id=id)
counter = 0
keyword_proposed = context.keyword_given
created = False
if request.data.get('keyword_proposed'):
keyword_proposed, created = Keyword.objects.get_or_create(
name=request.data.get('keyword_proposed')['name']
)
existing_review_count = Review.objects.filter(user=request.user, context=context).count()
# If there are existing reviews, delete them first
if existing_review_count:
for review in Review.objects.filter(user=request.user, context=context):
review.delete()
# TODO: Don't delete reviews for categories that are both in existing_reviews and in the request's categories
# Create a review for each category in the request
if not existing_review_count:
for category in request.data.get('categories'):
Review.objects.create(
context=context,
category=Category.objects.get(id=category),
keyword_given=context.keyword_given,
keyword_proposed=keyword_proposed,
user=request.user,
status=Review.PENDING)
counter += 1
return Response({
"keyword_created": created,
"keyword_proposed": keyword_proposed.name,
"reviews_created": counter,
"existing_review_count": existing_review_count
})
| from django.conf import settings
from django.shortcuts import render
from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from models import Context, Review, Keyword, Category
def index(request):
context = {'DEBUG': settings.DEBUG}
return render(request, 'index.html', context)
class PostContext(APIView):
def post(self, request, id):
context = Context.objects.get(id=id)
counter = 0
keyword_proposed = context.keyword_given
created = False
if request.data.get('keyword_proposed'):
keyword_proposed, created = Keyword.objects.get_or_create(
name=request.data.get('keyword_proposed')['name']
)
existing_review_count = Review.objects.filter(context=context).count()
if not existing_review_count:
for category in request.data.get('categories'):
Review.objects.create(
context=context,
category=Category.objects.get(id=category),
keyword_given=context.keyword_given,
keyword_proposed=keyword_proposed,
user=request.user,
status=Review.PENDING)
counter += 1
return Response({
"keyword_created": created,
"keyword_proposed": keyword_proposed.name,
"reviews_created": counter,
"existing_review_count": existing_review_count
})
|
Change api endpoints due to undocumented breaking changes | <?php namespace Dxi\Commands\Dataset\Contact;
use Dxi\Commands\Command;
class Create extends Command {
/**
* Get the payload for the command
*
* @return array
*/
public function getRequiredParams()
{
return [
'firstname',
'dataset',
[
'ddi_home',
'ddi_mobile',
'ddi_work'
]
];
}
/**
* Set the phone number
*
* @param $phone
* @return $this
*/
public function getPhone($phone)
{
$phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home');
$this->params[$phoneType] = $phone;
return $this;
}
/**
* Get the method for the command
*
* @return string
*/
public function getMethod()
{
return 'ecnow_records';
}
/**
* Get the url path
*
* @return string
*/
public function getUrlPath()
{
return '/ecnow.php';
}
/**
* Get the action for the command
*
* @return string
*/
public function getAction()
{
return strtolower(class_basename(__CLASS__));
}
} | <?php namespace Dxi\Commands\Dataset\Contact;
use Dxi\Commands\Command;
class Create extends Command {
/**
* Get the payload for the command
*
* @return array
*/
public function getRequiredParams()
{
return [
'firstname',
'dataset',
[
'ddi_home',
'ddi_mobile',
'ddi_work'
]
];
}
/**
* Set the phone number
*
* @param $phone
* @return $this
*/
public function getPhone($phone)
{
$phoneType = (preg_match('/^(07|\+447)/', $phone, $ret) ? 'ddi_mobile' : 'ddi_home');
$this->params[$phoneType] = $phone;
return $this;
}
/**
* Get the method for the command
*
* @return string
*/
public function getMethod()
{
return 'ecnow_data';
}
/**
* Get the url path
*
* @return string
*/
public function getUrlPath()
{
return '/database.php';
}
/**
* Get the action for the command
*
* @return string
*/
public function getAction()
{
return strtolower(class_basename(__CLASS__));
}
} |
Add max width to images | module.exports = {
siteMetadata: {
name: `Iiro Jäppinen`,
siteTitle: 'iiro.fi',
siteUrl: `https://iiro.fi/`
},
plugins: [
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
'gatsby-transformer-remark',
'gatsby-transformer-sharp',
{
resolve: 'gatsby-typegen-remark',
options: {
plugins: [
{
resolve: 'gatsby-typegen-remark-responsive-image',
options: {
maxWidth: 1280,
},
},
'gatsby-typegen-remark-prismjs',
'gatsby-typegen-remark-copy-linked-files',
'gatsby-typegen-remark-smartypants',
],
},
},
'gatsby-typegen-filesystem',
'gatsby-typegen-sharp',
'gatsby-plugin-sharp',
{
resolve: 'gatsby-plugin-manifest',
options: {
name: `Iiro Jäppinen`,
short_name: 'iiro.fi',
icons: [
{
src: '/icon.png',
sizes: '1024x1024',
type: 'image/png',
},
],
start_url: '/',
background_color: 'white',
theme_color: 'white',
display: 'minimal-ui',
},
},
'gatsby-plugin-offline',
'gatsby-plugin-preact'
]
}
| module.exports = {
siteMetadata: {
name: `Iiro Jäppinen`,
siteTitle: 'iiro.fi',
siteUrl: `https://iiro.fi/`
},
plugins: [
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
'gatsby-transformer-remark',
'gatsby-transformer-sharp',
{
resolve: 'gatsby-typegen-remark',
options: {
plugins: [
'gatsby-typegen-remark-responsive-image',
'gatsby-typegen-remark-prismjs',
'gatsby-typegen-remark-copy-linked-files',
'gatsby-typegen-remark-smartypants',
],
},
},
'gatsby-typegen-filesystem',
'gatsby-typegen-sharp',
'gatsby-plugin-sharp',
{
resolve: 'gatsby-plugin-manifest',
options: {
name: `Iiro Jäppinen`,
short_name: 'iiro.fi',
icons: [
{
src: '/icon.png',
sizes: '1024x1024',
type: 'image/png',
},
],
start_url: '/',
background_color: 'white',
theme_color: 'white',
display: 'minimal-ui',
},
},
'gatsby-plugin-offline',
'gatsby-plugin-preact'
]
}
|
Add zipcode to Freegeoip results | 'use strict';
(function () {
var net = require('net');
/**
* Constructor
*/
var FreegeoipGeocoder = function(httpAdapter) {
if (!httpAdapter || httpAdapter == 'undefinded') {
throw new Error('FreegeoipGeocoder need an httpAdapter');
}
this.httpAdapter = httpAdapter;
};
FreegeoipGeocoder.prototype._endpoint = 'http://freegeoip.net/json/';
FreegeoipGeocoder.prototype.geocode = function(value, callback) {
if (!net.isIP(value)) {
throw new Error('FreegeoipGeocoder suport only ip geocoding');
}
var _this = this;
this.httpAdapter.get(this._endpoint + value , { }, function(err, result) {
if (err) {
throw err;
} else {
var results = [];
results.push({
'latitude' : result.latitude,
'longitude' : result.longitude,
'country' : result.country_name,
'city' : result.city,
'zipcode' : result.zipcode,
'streetName': null,
'streetNumber' : null,
'countryCode' : result.country_code
});
callback(false, results);
}
});
};
FreegeoipGeocoder.prototype.reverse = function(lat, lng, callback) {
throw new Error('FreegeoipGeocoder no support reverse geocoding');
};
module.exports = FreegeoipGeocoder;
})(); | 'use strict';
(function () {
var net = require('net');
/**
* Constructor
*/
var FreegeoipGeocoder = function(httpAdapter) {
if (!httpAdapter || httpAdapter == 'undefinded') {
throw new Error('FreegeoipGeocoder need an httpAdapter');
}
this.httpAdapter = httpAdapter;
};
FreegeoipGeocoder.prototype._endpoint = 'http://freegeoip.net/json/';
FreegeoipGeocoder.prototype.geocode = function(value, callback) {
if (!net.isIP(value)) {
throw new Error('FreegeoipGeocoder suport only ip geocoding');
}
var _this = this;
this.httpAdapter.get(this._endpoint + value , { }, function(err, result) {
if (err) {
throw err;
} else {
var results = [];
results.push({
'latitude' : result.latitude,
'longitude' : result.longitude,
'country' : result.country_name,
'city' : result.city,
'zipcode' : null,
'streetName': null,
'streetNumber' : null,
'countryCode' : result.country_code
});
callback(false, results);
}
});
};
FreegeoipGeocoder.prototype.reverse = function(lat, lng, callback) {
throw new Error('FreegeoipGeocoder no support reverse geocoding');
};
module.exports = FreegeoipGeocoder;
})(); |
Fix maxLength governor not accepting null value | import PreprocessShader from './preprocessShader';
import Shader from './shader';
export default class ShaderManager {
constructor(renderer) {
this.renderer = renderer;
this.shaders = [];
this.current = null;
this.handler = null;
// Preprocess shader's governor list
this.governors = {
max: {
checker: (shader, current) => shader >= current,
allocator: current => current
},
equal: {
checker: (shader, current) => shader === current,
allocator: current => current
},
maxLength: {
checker: (shader, current) =>
shader >= (current == null ? 0 : current.length),
allocator: current => current == null ? 0 : current.length
}
};
}
create(vert, frag, noPreprocess = false) {
let shader;
if (noPreprocess) {
shader = new Shader(this.renderer, vert, frag);
} else {
shader = new PreprocessShader(this.renderer, vert, frag);
}
this.shaders.push(shader);
return shader;
}
use(shader, uniforms) {
let returned = shader.getShader(uniforms, this.current);
if (this.handler != null) {
returned = this.handler(returned, uniforms, this.renderer);
}
this.current = returned.use(uniforms, this.current);
}
reset() {
this.current = null;
this.shaders.forEach(shader => shader.dispose());
}
}
| import PreprocessShader from './preprocessShader';
import Shader from './shader';
export default class ShaderManager {
constructor(renderer) {
this.renderer = renderer;
this.shaders = [];
this.current = null;
this.handler = null;
// Preprocess shader's governor list
this.governors = {
max: {
checker: (shader, current) => shader >= current,
allocator: current => current
},
equal: {
checker: (shader, current) => shader === current,
allocator: current => current
},
maxLength: {
checker: (shader, current) => shader >= current.length,
allocator: current => current.length
}
};
}
create(vert, frag, noPreprocess = false) {
let shader;
if (noPreprocess) {
shader = new Shader(this.renderer, vert, frag);
} else {
shader = new PreprocessShader(this.renderer, vert, frag);
}
this.shaders.push(shader);
return shader;
}
use(shader, uniforms) {
let returned = shader.getShader(uniforms, this.current);
if (this.handler != null) {
returned = this.handler(returned, uniforms, this.renderer);
}
this.current = returned.use(uniforms, this.current);
}
reset() {
this.current = null;
this.shaders.forEach(shader => shader.dispose());
}
}
|
Add skipAuthorization to options instead of a variable in our method | var JWTHelper = require('./jwt-helper');
var JWTConfig = require('./jwt-config');
var JWTRequest = {
setAuthorizationHeader(options, token) {
if (!options.headers) options.headers = {};
options.headers[JWTConfig.authHeader] = `${JWTConfig.authPrefix} ${token}`;
return options;
},
handleUnAuthorizedFetch(url, options) {
return fetch(url, options).then((response) => response.json());
},
handleAuthorizedFetch(url, options) {
return new Promise((resolve, reject) => {
JWTHelper.getToken().then((token) => {
if (token && !JWTHelper.isTokenExpired(token)) {
options = this.setAuthorizationHeader(options, token);
fetch(url, options).then((response) => {
resolve(response.json())
});
} else {
reject('Token is either not valid or has expired.');
}
})
})
},
fetch(url, options) {
options = options || {};
if (options.skipAuthorization) {
return this.handleUnAuthorizedFetch(url, options);
} else {
return this.handleAuthorizedFetch(url, options);
}
}
};
module.exports = JWTRequest; | var JWTHelper = require('./jwt-helper');
var JWTConfig = require('./jwt-config');
var JWTRequest = {
setAuthorizationHeader(options, token) {
if (!options.headers) options.headers = {};
options.headers[JWTConfig.authHeader] = `${JWTConfig.authPrefix} ${token}`;
return options;
},
handleUnAuthorizedFetch(url, options) {
return fetch(url, options).then((response) => response.json());
},
handleAuthorizedFetch(url, options) {
return new Promise((resolve, reject) => {
JWTHelper.getToken().then((token) => {
if (token && !JWTHelper.isTokenExpired(token)) {
options = this.setAuthorizationHeader(options, token);
fetch(url, options).then((response) => {
resolve(response.json())
});
} else {
reject('Token is either not valid or has expired.');
}
})
})
},
fetch(url, options, skipAuthorization) {
options = options || {};
if (skipAuthorization) {
return this.handleUnAuthorizedFetch(url, options);
} else {
return this.handleAuthorizedFetch(url, options);
}
}
};
module.exports = JWTRequest; |
Use optparser for generate length | #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
length = options.n if options.n else DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option("-n", type='int', help="With 'generate', the length of the generated password")
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
| #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
if len(arguments) == 2:
length = int(arguments[1])
else:
length = DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
|
Subsets and Splits