text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix broken import to shaded orbitz jar
Signed-off-by: Tommy Shiou <fd59d852321c3431be8a979962d50c7894293a47@turn.com>
|
/*
* Copyright (C) 2016 Turn Inc. All Rights Reserved.
* Proprietary and confidential.
*/
package com.turn.edc.storage;
import com.turn.edc.exception.KeyNotFoundException;
import com.turn.edc.router.StoreRequest;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.google.common.eventbus.Subscribe;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ConnectionFactory layer connector interface
*
* @author tshiou
*/
public abstract class StorageConnector {
private static final Logger LOG = LoggerFactory.getLogger(StorageConnector.class);
public abstract void set(String key, byte[] value, int ttl, int timeout) throws IOException;
public abstract void set(String key, String subkey, byte[] value, int ttl, int timeout) throws IOException;
public abstract byte[] get(String key, int timeout) throws KeyNotFoundException, TimeoutException, IOException;
public abstract byte[] get(String key, String subkey, int timeout) throws KeyNotFoundException, TimeoutException, IOException;
public abstract void close();
@Subscribe
public void handleStoreRequest(StoreRequest request) {
try {
this.set(request.getKey(), request.getSubkey(), request.getPayload(), request.getTtl(), 10);
} catch (IOException e) {
LOG.error("Store request failed");
LOG.debug(ExceptionUtils.getStackTrace(e));
}
}
}
|
/*
* Copyright (C) 2016 Turn Inc. All Rights Reserved.
* Proprietary and confidential.
*/
package com.turn.edc.storage;
import com.turn.edc.exception.KeyNotFoundException;
import com.turn.edc.router.StoreRequest;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.google.common.eventbus.Subscribe;
import com.orbitz.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ConnectionFactory layer connector interface
*
* @author tshiou
*/
public abstract class StorageConnector {
private static final Logger LOG = LoggerFactory.getLogger(StorageConnector.class);
public abstract void set(String key, byte[] value, int ttl, int timeout) throws IOException;
public abstract void set(String key, String subkey, byte[] value, int ttl, int timeout) throws IOException;
public abstract byte[] get(String key, int timeout) throws KeyNotFoundException, TimeoutException, IOException;
public abstract byte[] get(String key, String subkey, int timeout) throws KeyNotFoundException, TimeoutException, IOException;
public abstract void close();
@Subscribe
public void handleStoreRequest(StoreRequest request) {
try {
this.set(request.getKey(), request.getSubkey(), request.getPayload(), request.getTtl(), 10);
} catch (IOException e) {
LOG.error("Store request failed");
LOG.debug(ExceptionUtils.getStackTrace(e));
}
}
}
|
Move return view to controller
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {
return view('pages.dashboard');
})->name('page.dashboard');
Route::get('/siswa','Pages\UserController@siswa')->name('page.list-siswa');
Route::get('/guru','Pages\UserController@guru')->name('page.list-guru');
Route::get('/staf','Pages\UserController@staf')->name('page.list-staf');
Route::get('/users/create','Pages\UserController@create')->name('page.create-user');
Route::get('/users/{id}/edit','Pages\UserController@edit')->name('page.edit-user');
Route::get('/activity','Pages\ActivityController@index')->name('page.list-activity');
Route::get('/activity/create','Pages\ActivityController@create')->name('page.create-activity');
Route::get('/activity/{id}/edit','Pages\ActivityController@edit')->name('page.edit-activity');
Route::get('/calendar', function () {
return view('pages.calendar');
})->name('page.calendar');
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {
return view('pages.dashboard');
})->name('page.dashboard');
Route::get('/list-guru', function () {
return view('pages.list-guru');
})->name('page.list-guru');
Route::get('/list-siswa', function () {
return view('pages.list-siswa');
})->name('page.list-siswa');
Route::get('/list-staf', function () {
return view('pages.list-staf');
})->name('page.list-staf');
Route::get('/list-agenda', function () {
return view('pages.list-activity');
})->name('page.list-agenda');
Route::get('/calendar', function () {
return view('pages.calendar');
})->name('page.calendar');
Route::get('/user/create', function () {
return view('pages.create-user');
})->name('page.create-user');
Route::get('/agenda/create', function () {
return view('pages.create-activity');
})->name('page.create-agenda');
Route::get('/user/edit', function () {
return view('pages.update-user');
})->name('page.edit-user');
Route::get('/agenda/edit', function () {
return view('pages.update-activity');
})->name('page.edit-agenda');
|
Change "best" to "the best"
|
'use strict';
module.exports = defineRules;
var competitivePhrases = [
'compete', 'competition', 'competitive', 'cutting edge', 'fail', 'forefront',
'superstar', 'the best', 'top', 'win'
];
var expectationPhrases = [
'hit the ground running',
'juggle',
'tight deadline', 'tight deadlines'
];
function defineRules (linter) {
// Competitive environment
linter.addRule(function (spec, result) {
var competitionMentions = spec.containsAnyOfPhrases(competitivePhrases);
if (competitionMentions.length > 0) {
result.addNotice('The job sounds competitive and performance-based');
result.addRealismFailPoints(competitionMentions.length / 2);
result.addRecruiterFailPoints(competitionMentions.length / 2);
}
});
// Unrealistic expectations
linter.addRule(function (spec, result) {
var expectationMentions = spec.containsAnyOfPhrases(expectationPhrases);
if (expectationMentions.length > 0) {
result.addNotice('The job sounds like it\'s expecting too much from a new starter');
result.addRealismFailPoints(expectationMentions.length);
}
});
}
|
'use strict';
module.exports = defineRules;
var competitivePhrases = [
'best', 'compete', 'competition', 'competitive', 'cutting edge', 'fail', 'forefront',
'superstar', 'top', 'win'
];
var expectationPhrases = [
'hit the ground running',
'juggle',
'tight deadline', 'tight deadlines'
];
function defineRules (linter) {
// Competitive environment
linter.addRule(function (spec, result) {
var competitionMentions = spec.containsAnyOfPhrases(competitivePhrases);
if (competitionMentions.length > 0) {
result.addNotice('The job sounds competitive and performance-based');
result.addRealismFailPoints(competitionMentions.length / 2);
result.addRecruiterFailPoints(competitionMentions.length / 2);
}
});
// Unrealistic expectations
linter.addRule(function (spec, result) {
var expectationMentions = spec.containsAnyOfPhrases(expectationPhrases);
if (expectationMentions.length > 0) {
result.addNotice('The job sounds like it\'s expecting too much from a new starter');
result.addRealismFailPoints(expectationMentions.length);
}
});
}
|
Add macfsevents dependency on Mac OS X
|
from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='turbulent/bbeausej',
author_email='b@turbulent.ca',
license='MIT',
long_description=readme,
description='substance - local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={ 'substance': ['support/*'] },
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
|
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
setup(name='substance',
version=__version__,
author='turbulent/bbeausej',
author_email='b@turbulent.ca',
license='MIT',
long_description=readme,
description='substance - local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={ 'substance': ['support/*'] },
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
|
Fix /destroy_all_the_things endpoint, state are lower case
|
var express = require('express');
var kue = require('kue');
var Bot = require('../models/bot');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/destroy_all_the_things', function(req, res, next) {
['queued', 'active', 'failed', 'complete', 'delayed'].forEach(function(state) {
kue.Job.rangeByState(state, 0, 10000, 'asc', function(err, jobs) {
jobs.forEach(function(job) {
job.remove(function(err) {
if (err) console.log(err);
});
});
});
});
Bot.remove({})
.then(function(result) {
})
.catch(function(err) {
res.status(500).send(err);
});
res.send();
});
module.exports = router;
|
var express = require('express');
var kue = require('kue');
var Bot = require('../models/bot');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.post('/destroy_jobs', function(req, res, next) {
kue.Job.rangeByState('delayed', 0, 10000, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
job.remove(function() {});
});
res.send();
});
});
router.post('/destroy_all_the_things', function(req, res, next) {
['Queued', 'Active', 'Failed', 'Complete', 'Delayed'].forEach(function(state) {
kue.Job.rangeByState(state, 0, 999999, 'asc', function( err, jobs ) {
jobs.forEach(function(job) {
job.remove(function(err) {
if (err) console.log(err);
});
});
});
});
Bot.remove({})
.then(function(result) {
})
.catch(function(err) {
res.status(500).send(err);
});
res.send();
});
module.exports = router;
|
Fix issues with class naming
|
#!/usr/bin/env python
# -*- coding: utf-8
from __future__ import absolute_import
import six
from .common import ObjectMeta
from ..base import Model
from ..fields import Field, ListField
class LabelSelectorRequirement(Model):
key = Field(six.text_type)
operator = Field(six.text_type)
values = ListField(six.text_type)
class LabelSelector(Model):
matchExpressions = Field(LabelSelectorRequirement)
matchLabels = Field(dict)
class PodDisruptionBudgetSpec(Model):
minAvailable = Field(six.text_type)
maxUnavailable = Field(six.text_type)
selector = Field(LabelSelector)
class PodDisruptionBudget(Model):
class Meta:
url_template = "/apis/autoscaling/v1/namespaces/{namespace}/poddisruptionbudget/{name}"
metadata = Field(ObjectMeta)
spec = Field(PodDisruptionBudgetSpec)
|
#!/usr/bin/env python
# -*- coding: utf-8
from __future__ import absolute_import
import six
from .common import ObjectMeta
from ..base import Model
from ..fields import Field, ListField
class PodDisruptionBudgetMatchExpressions(Model):
key = Field(six.text_type)
operator = Field(six.text_type)
values = ListField(six.text_type)
class PodDisruptionBudgetSelector(Model):
matchExpressions = Field(PodDisruptionBudgetMatchExpressions)
matchLabels = Field(dict)
class PodDisruptionBudgetSpec(Model):
minAvailable = Field(six.text_type)
maxUnavailable = Field(six.text_type)
selector = Field(PodDisruptionBudgetSelector)
class PodDisruptionBudget(Model):
class Meta:
url_template = "/apis/autoscaling/v1/namespaces/{namespace}/poddisruptionbudget/{name}"
metadata = Field(ObjectMeta)
spec = Field(PodDisruptionBudgetSpec)
|
Add new line at the end of error message
|
package xhl.core;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import xhl.core.elements.CodeList;
import xhl.core.exceptions.EvaluationException;
/**
* LanguageProcessor, which reads code from the file and outputs error messages
* to the standard error output.
*
* @author Sergej Chodarev
*/
public class ConsoleLanguageProcessor extends LanguageProcessor {
public ConsoleLanguageProcessor(Language lang) {
super(lang);
}
public void process(String filename) throws FileNotFoundException,
IOException {
Reader reader = new Reader();
CodeList program = reader.read(new FileReader(filename));
try {
execute(program);
} catch (EvaluationException e) {
System.err.printf("%s: %s\n", e.getPosition(), e);
}
}
}
|
package xhl.core;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import xhl.core.elements.CodeList;
import xhl.core.exceptions.EvaluationException;
/**
* LanguageProcessor, which reads code from the file and outputs error messages
* to the standard error output.
*
* @author Sergej Chodarev
*/
public class ConsoleLanguageProcessor extends LanguageProcessor {
public ConsoleLanguageProcessor(Language lang) {
super(lang);
}
public void process(String filename) throws FileNotFoundException,
IOException {
Reader reader = new Reader();
CodeList program = reader.read(new FileReader(filename));
try {
execute(program);
} catch (EvaluationException e) {
System.err.printf("%s: %s", e.getPosition(), e);
}
}
}
|
Break the parameters into multiples parameters
|
<?php
namespace Majora\OAuthServerBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* Class MajoraOAuthServerExtension.
*
* @author Raphael De Freitas <raphael@de-freitas.net>
*/
class MajoraOAuthServerExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('majora_oauth_server.storage.access_token', $config['storage']['access_token']);
$container->setParameter('majora_oauth_server.storage.auth_code', $config['storage']['auth_code']);
$container->setParameter('majora_oauth_server.storage.client', $config['storage']['client']);
$container->setParameter('majora_oauth_server.storage.refresh_token', $config['storage']['refresh_token']);
}
/**
* {@inheritdoc}
*/
public function getAlias()
{
return 'majora_oauth_server';
}
}
|
<?php
namespace Majora\OAuthServerBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* Class MajoraOAuthServerExtension.
*
* @author Raphael De Freitas <raphael@de-freitas.net>
*/
class MajoraOAuthServerExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('majora_oauth_server.config', $config);
}
/**
* {@inheritdoc}
*/
public function getAlias()
{
return 'majora_oauth_server';
}
}
|
Upgrade lxml package from 4.3.0 -> 4.3.4
|
import os
import sys
from setuptools import setup, find_packages
os.chdir(os.path.dirname(sys.argv[0]) or ".")
import libsongtext
version = '%s.%s.%s' % libsongtext.__version__
try:
long_description = open('README.rst', 'U').read()
except IOError:
long_description = 'See https://github.com/ysim/songtext'
setup(
name='songtext',
version=version,
description='a command-line song lyric fetcher',
long_description=long_description,
url='https://github.com/ysim/songtext',
author='ysim',
author_email='opensource@yiqingsim.net',
packages=find_packages(),
entry_points={
'console_scripts': [
'songtext = libsongtext.songtext:main',
],
},
install_requires=[
'click==7.0',
'cssselect==1.0.3',
'lxml==4.3.4',
'requests==2.21.0',
],
license='BSD',
keywords='console command line music song lyrics',
classifiers=[
'Environment :: Console',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
],
)
|
import os
import sys
from setuptools import setup, find_packages
os.chdir(os.path.dirname(sys.argv[0]) or ".")
import libsongtext
version = '%s.%s.%s' % libsongtext.__version__
try:
long_description = open('README.rst', 'U').read()
except IOError:
long_description = 'See https://github.com/ysim/songtext'
setup(
name='songtext',
version=version,
description='a command-line song lyric fetcher',
long_description=long_description,
url='https://github.com/ysim/songtext',
author='ysim',
author_email='opensource@yiqingsim.net',
packages=find_packages(),
entry_points={
'console_scripts': [
'songtext = libsongtext.songtext:main',
],
},
install_requires=[
'click==7.0',
'cssselect==1.0.3',
'lxml==4.3.0',
'requests==2.21.0',
],
license='BSD',
keywords='console command line music song lyrics',
classifiers=[
'Environment :: Console',
'Operating System :: OS Independent',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
],
)
|
Allow newer versions of click
|
from setuptools import setup
setup(
name='aws-fuzzy-finder',
version='1.0.0',
url='https://github.com/pmazurek/aws-fuzzy-finder',
description='SSH into AWS instances using fuzzy search through tags.',
download_url='https://github.com/pmazurek/aws-fuzzy-finder/tarball/v1.0.0',
author='Piotr Mazurek, Daria Rudkiewicz',
keywords=['aws', 'ssh', 'fuzzy', 'ec2'],
packages=['aws_fuzzy_finder'],
package_data={'': [
'libs/fzf-0.17.0-linux_386',
'libs/fzf-0.17.0-linux_amd64',
'libs/fzf-0.17.0-darwin_386',
'libs/fzf-0.17.0-darwin_amd64',
]},
install_requires=[
'boto3==1.3.1',
'click>=6.6',
'boto3-session-cache==1.0.2'
],
entry_points=dict(
console_scripts=[
'aws-fuzzy = aws_fuzzy_finder.main:entrypoint',
]
)
)
|
from setuptools import setup
setup(
name='aws-fuzzy-finder',
version='1.0.0',
url='https://github.com/pmazurek/aws-fuzzy-finder',
description='SSH into AWS instances using fuzzy search through tags.',
download_url='https://github.com/pmazurek/aws-fuzzy-finder/tarball/v1.0.0',
author='Piotr Mazurek, Daria Rudkiewicz',
keywords=['aws', 'ssh', 'fuzzy', 'ec2'],
packages=['aws_fuzzy_finder'],
package_data={'': [
'libs/fzf-0.17.0-linux_386',
'libs/fzf-0.17.0-linux_amd64',
'libs/fzf-0.17.0-darwin_386',
'libs/fzf-0.17.0-darwin_amd64',
]},
install_requires=[
'boto3==1.3.1',
'click==6.6',
'boto3-session-cache==1.0.2'
],
entry_points=dict(
console_scripts=[
'aws-fuzzy = aws_fuzzy_finder.main:entrypoint',
]
)
)
|
Add a comment about line endings in Stardoc files.
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
# Force Unix-style line endings for consistent results. See
# https://github.com/bazelbuild/stardoc/issues/110.
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""
import argparse
import pathlib
def _main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument('input', type=pathlib.Path)
parser.add_argument('output', type=pathlib.Path)
opts = parser.parse_args()
text = opts.input.read_text(encoding='utf-8')
with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file:
file.write(text)
if __name__ == '__main__':
_main()
|
Remove testing CachePath from example.
|
var app = module.exports = require('appjs').createApp();
app.serveFilesFrom(__dirname + '/content');
var window = app.createWindow({
width : 640,
height : 460,
icons : __dirname + '/content/icons'
});
window.on('create', function(){
console.log("Window Created");
window.frame.show();
window.frame.center();
});
window.on('ready', function(){
console.log("Window Ready");
window.require = require;
window.process = process;
window.module = module;
function F12(e){ return e.keyIdentifier === 'F12' }
function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey }
window.addEventListener('keydown', function(e){
if (F12(e) || Command_Option_J(e)) {
window.frame.openDevTools();
}
});
});
window.on('close', function(){
console.log("Window Closed");
});
|
var app = module.exports = require('appjs').createApp({CachePath: '/Users/dbartlett/.cache1'});
app.serveFilesFrom(__dirname + '/content');
var window = app.createWindow({
width : 640,
height : 460,
icons : __dirname + '/content/icons'
});
window.on('create', function(){
console.log("Window Created");
window.frame.show();
window.frame.center();
});
window.on('ready', function(){
console.log("Window Ready");
window.require = require;
window.process = process;
window.module = module;
function F12(e){ return e.keyIdentifier === 'F12' }
function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey }
window.addEventListener('keydown', function(e){
if (F12(e) || Command_Option_J(e)) {
window.frame.openDevTools();
}
});
});
window.on('close', function(){
console.log("Window Closed");
});
|
Fix for global package, style changes
Change-Id: I351fbcc07dcdb8080c84f55168df0eeec773c632
|
#!/usr/bin/env node
/*
* Copyright (C) 2022 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
import path from 'path';
import { fileURLToPath } from 'url';
import { spawn } from 'node:child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const appRoot = path.resolve(__dirname);
const ls = spawn(appRoot + '/node_modules/mocha/bin/_mocha', [appRoot + '/test/index-test.js']);
ls.stdout.on('data', (data) => {
console.log(data.toString());
});
ls.stderr.on('data', (data) => {
console.error(data.toString());
});
ls.on('close', (code) => {
if (code === 0) {
console.log('Tests completed successfully');
} else {
console.log(`Tests exited with error code ${code}`);
}
});
|
#!/usr/bin/env node
/*
* Copyright (C) 2022 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const appRoot = path.resolve(__dirname);
import { spawn } from 'node:child_process';
const ls = spawn(appRoot+'/node_modules/mocha/bin/_mocha', [appRoot+'/test/index-test.js']);
ls.stdout.on('data', (data) => {
console.log(data.toString());
});
ls.stderr.on('data', (data) => {
console.error(data.toString());
});
ls.on('close', (code) => {
if (code == 0) {
console.log('Tests completed successfully')
} else {
console.log(`Tests exited with error code ${code}`);
}
});
|
Fix massive SPAM of errors from QR code in the browser console.
|
/*global angular*/
(function () {
'use strict';
angular.module('core').directive('qrDeviceInteraction', function () {
var template = '';
template += '<a href="{{qrConfig.slideUrl}}" target="_blank" ng-if="qrConfig">';
template += ' <qr text="qrConfig.slideUrl" type-number="qrConfig.typeNumber" correction-level="qrConfig.correctionLevel"';
template += ' size="qrConfig.size" input-mode="qrConfig.inputMode" image="qrConfig.image">';
template += ' </qr>';
template += '</a>';
return {
restrict: 'AE',
template: template
};
});
}());
|
/*global angular*/
(function () {
'use strict';
angular.module('core').directive('qrDeviceInteraction', function () {
var template = '';
template += '<a href="{{qrConfig.slideUrl}}" target="_blank">';
template += ' <qr text="qrConfig.slideUrl" type-number="qrConfig.typeNumber" correction-level="qrConfig.correctionLevel"';
template += ' size="qrConfig.size" input-mode="qrConfig.inputMode" image="qrConfig.image">';
template += ' </qr>';
template += '</a>';
return {
restrict: 'AE',
template: template,
};
});
}());
|
Fix app specific JS for adminsysconfig.
|
// --
// Core.Agent.Admin.SysConfig.js - provides the special module functions for the AdminSysConfig
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.Agent.Admin.SysConfig.js,v 1.2 2010-06-22 11:24:49 mg Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
Core.Agent.Admin = Core.Agent.Admin || {};
/**
* @namespace
* @exports TargetNS as Core.Agent.Admin.SysConfig
* @description
* This namespace contains the special module functions for the SysConfig module.
*/
Core.Agent.Admin.SysConfig = (function (TargetNS) {
/**
* @function
* @return nothing
* This function initializes the special module functions
*/
TargetNS.Init = function () {
$('#AdminSysConfig h3 input:checkbox').click(function () {
$(this).parent('h3').parent('fieldset').toggleClass('Invalid');
});
};
return TargetNS;
}(Core.Agent.Admin.SysConfig || {}));
|
// --
// Core.Agent.Admin.SysConfig.js - provides the special module functions for the AdminSysConfig
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.Agent.Admin.SysConfig.js,v 1.1 2010-06-04 11:19:31 mn Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
Core.Agent.Admin = Core.Agent.Admin || {};
/**
* @namespace
* @exports TargetNS as Core.Agent.Admin.SysConfig
* @description
* This namespace contains the special module functions for the SysConfig module.
*/
Core.Agent.Admin.SysConfig = (function (TargetNS) {
/**
* @function
* @return nothing
* This function initializes the special module functions
*/
TargetNS.Init = function () {
$('.AdminSysConfig h3 input:checkbox').click(function () {
$(this).parent('h3').parent('fieldset').toggleClass('Invalid');
});
};
return TargetNS;
}(Core.Agent.Admin.SysConfig || {}));
|
Fix order by doc comment.
|
// DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
/**
* Builds indexes from content items and map functions.
*/
function Index(scope) {
this.scope = scope;
}
Index.service = 'index';
Index.feature = 'query';
Index.scope = 'shell';
/**
* Creates or gets an index.
* @param {RegExp|string} [context.idFilter] A regular expression that validates
* content item ids before they are read and indexed.
* @param {Function} context.map The map function takes a content item and returns
* an array of index entries, a single index entry, or null.
* An index entry should have an id property.
* It is recommended to name the map function.
* @param {Function} [context.orderBy] The function that defines the order
* on which the index entries should be sorted.
* It takes an index entry, and returns the sort order.
* The sort order can be a simple string, date, number, or it can be an array,
* in which case the items in the array will be used one after the other.
* It is recommended to name the order function.
* @returns {object} The index object.
*/
Index.prototype.getIndex = function getIndex(context) {
var indexStore = this.scope.require('index-store');
return indexStore.getIndex(context.idFilter, context.map, context.orderBy);
};
module.exports = Index;
|
// DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
/**
* Builds indexes from content items and map functions.
*/
function Index(scope) {
this.scope = scope;
}
Index.service = 'index';
Index.feature = 'query';
Index.scope = 'shell';
/**
* Creates or gets an index.
* @param {RegExp|string} [context.idFilter] A regular expression that validates
* content item ids before they are read and indexed.
* @param {Function} context.map The map function takes a content item and returns
* an array of index entries, a single index entry, or null.
* An index entry should have an id property.
* It is recommended to name the map function.
* @param {Function} [context.orderBy] The function that defines the order
* on which the index entries should be sorted.
* It takes two index entries A and B, and returns -1 if A comes before B,
* and +1 if A comes after B.
* It is recommended to name the order function.
* @returns {object} The index object.
*/
Index.prototype.getIndex = function getIndex(context) {
var indexStore = this.scope.require('index-store');
return indexStore.getIndex(context.idFilter, context.map, context.orderBy);
};
module.exports = Index;
|
Add predict path for Residual
|
from .model import Model
from ...api import layerize
from .affine import Affine
import cytoolz as toolz
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layer[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
from .model import Model
from ...api import layerize
from .affine import Affine
import cytoolz as toolz
def Residual(layer):
def residual_fwd(X, drop=0.):
y, bp_y = layer.begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
model = layerize(residual_fwd)
model._layers.append(layer)
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
model.on_data_hooks.append(on_data)
return model
|
Update error message for Select command (if a task is already done)
|
package seedu.ezdo.commons.core;
/**
* Container for user visible messages.
*/
public class Messages {
public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid.";
public static final String MESSAGE_TASK_DONE = "The task has a status marked as done.";
public static final String MESSAGE_TASKS_LISTED_OVERVIEW = "%1$d tasks listed!";
//@@author A0141010L
public static final String MESSAGE_WRONG_LIST = "Please return to the task list "
+ "if you want to mark a task as done.";
//@@author A0139248X
public static final String MESSAGE_TASK_DATES_INVALID = "Start date is after due date!";
}
|
package seedu.ezdo.commons.core;
/**
* Container for user visible messages.
*/
public class Messages {
public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid.";
public static final String MESSAGE_TASKS_LISTED_OVERVIEW = "%1$d tasks listed!";
//@@author A0141010L
public static final String MESSAGE_WRONG_LIST = "Please return to the task list "
+ "if you want to mark a task as done.";
//@@author A0139248X
public static final String MESSAGE_TASK_DATES_INVALID = "Start date is after due date!";
}
|
Rename controller action delete to destroy
|
<?php
declare(strict_types=1);
namespace Cortex\Foundation\Transformers;
use Spatie\MediaLibrary\Models\Media;
use League\Fractal\TransformerAbstract;
class MediaTransformer extends TransformerAbstract
{
/**
* @return array
*/
public function transform(Media $media): array
{
return [
'id' => (int) $media->getKey(),
'name' => (string) $media->name,
'file_name' => (string) $media->file_name,
'mime_type' => (string) $media->mime_type,
'size' => (string) $media->getHumanReadableSizeAttribute(),
'created_at' => (string) $media->created_at,
'updated_at' => (string) $media->updated_at,
'delete' => (string) route('adminarea.rooms.media.destroy', ['room' => $media->model, 'media' => $media]),
];
}
}
|
<?php
declare(strict_types=1);
namespace Cortex\Foundation\Transformers;
use Spatie\MediaLibrary\Models\Media;
use League\Fractal\TransformerAbstract;
class MediaTransformer extends TransformerAbstract
{
/**
* @return array
*/
public function transform(Media $media): array
{
return [
'id' => (int) $media->getKey(),
'name' => (string) $media->name,
'file_name' => (string) $media->file_name,
'mime_type' => (string) $media->mime_type,
'size' => (string) $media->getHumanReadableSizeAttribute(),
'created_at' => (string) $media->created_at,
'updated_at' => (string) $media->updated_at,
'delete' => (string) route('adminarea.rooms.media.delete', ['room' => $media->model, 'media' => $media]),
];
}
}
|
Add lower version bound on `"oedialect"` dependency
For some reason readthedocs use an earlier version and fails when trying
to use it.
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="feedinlib",
version="0.1.0rc1",
description="Creating time series from pv or wind power plants.",
url="http://github.com/oemof/feedinlib",
author="oemof developer group",
author_email="windpowerlib@rl-institut.de",
license="MIT",
packages=["feedinlib"],
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
zip_safe=False,
install_requires=[
"cdsapi >= 0.1.4",
"numpy >= 1.7.0",
"oedialect >= 0.0.5",
"open_FRED-cli",
"pandas >= 0.13.1",
"pvlib >= 0.6.0",
"windpowerlib >= 0.2.0",
"xarray >= 0.12.0",
],
extras_require={
"dev": ["jupyter", "pytest", "shapely", "sphinx_rtd_theme"],
"examples": ["jupyter", "shapely"],
},
)
|
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="feedinlib",
version="0.1.0rc1",
description="Creating time series from pv or wind power plants.",
url="http://github.com/oemof/feedinlib",
author="oemof developer group",
author_email="windpowerlib@rl-institut.de",
license="MIT",
packages=["feedinlib"],
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
zip_safe=False,
install_requires=[
"cdsapi >= 0.1.4",
"numpy >= 1.7.0",
"oedialect",
"open_FRED-cli",
"pandas >= 0.13.1",
"pvlib >= 0.6.0",
"windpowerlib >= 0.2.0",
"xarray >= 0.12.0",
],
extras_require={
"dev": ["jupyter", "pytest", "shapely", "sphinx_rtd_theme"],
"examples": ["jupyter", "shapely"],
},
)
|
Apply spoilers to the entire user activity stream.
|
(function() {
Discourse.addInitializer(function () {
var applySpoilers = function($post) {
// text
$('.spoiler:not(:has(img))', $post).removeClass('spoiler')
.spoilText();
// images
$('.spoiler:has(img)', $post).removeClass('spoiler')
.wrap("<div style='display: inline-block; overflow: hidden;'></div>")
.spoilImage();
};
Em.run.next(function() {
applySpoilers();
Discourse.PostView.prototype.on("postViewInserted", applySpoilers);
Discourse.ComposerView.prototype.on("previewRefreshed", applySpoilers);
Discourse.UserStreamView.prototype.on("didInsertElement", applySpoilers);
});
});
})();
|
(function() {
Discourse.addInitializer(function () {
var applySpoilers = function($post) {
// text
$('.spoiler:not(:has(img))', $post).removeClass('spoiler')
.spoilText();
// images
$('.spoiler:has(img)', $post).removeClass('spoiler')
.wrap("<div style='display: inline-block; overflow: hidden;'></div>")
.spoilImage();
};
Em.run.next(function() {
applySpoilers();
Discourse.PostView.prototype.on("postViewInserted", applySpoilers);
Discourse.ComposerView.prototype.on("previewRefreshed", applySpoilers);
});
});
})();
|
Test to see if changes are published to Github contribution graph.
|
package patterns;
public class Singleton {
public static void main(String[] args) {
Elvis theKing = Elvis.INSTANCE;
theKing.hasLeftTheBuilding();
AnotherElvis anotherKing = AnotherElvis.getInstance();
anotherKing.hasLeftTheBuilding();
EnumElvis enumElvis = EnumElvis.INSTANCE;
enumElvis.hasLeftTheBuilding();
}
}
// With public static method.
class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() {}
public void hasLeftTheBuilding() {
System.out.println("Elvis:Long live the king!");
}
}
// With static factory.
class AnotherElvis {
private static final AnotherElvis INSTANCE = new AnotherElvis();
private AnotherElvis() {}
public static AnotherElvis getInstance() { return INSTANCE; }
public void hasLeftTheBuilding() {
System.out.println("AnotherElvis: Long live the king!");
}
}
// With Enum.
enum EnumElvis {
INSTANCE;
public void hasLeftTheBuilding() {
System.out.println("EnumElvis:Long live the king!");
}
}
//
|
package patterns;
public class Singleton {
public static void main(String[] args) {
Elvis theKing = Elvis.INSTANCE;
theKing.hasLeftTheBuilding();
AnotherElvis anotherKing = AnotherElvis.getInstance();
anotherKing.hasLeftTheBuilding();
EnumElvis enumElvis = EnumElvis.INSTANCE;
enumElvis.hasLeftTheBuilding();
}
}
// With public static method.
class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() {}
public void hasLeftTheBuilding() {
System.out.println("Elvis:Long live the king!");
}
}
// With static factory.
class AnotherElvis {
private static final AnotherElvis INSTANCE = new AnotherElvis();
private AnotherElvis() {}
public static AnotherElvis getInstance() { return INSTANCE; }
public void hasLeftTheBuilding() {
System.out.println("AnotherElvis: Long live the king!");
}
}
// With Enum.
enum EnumElvis {
INSTANCE;
public void hasLeftTheBuilding() {
System.out.println("EnumElvis:Long live the king!");
}
}
|
Fix faulty writeFileSync logic for creating a new settings.json file
JSON keys must be wrapped in double-quotes
|
const fs = require('fs-extra'),
Path = require('path');
var _settings = { // Private storage of settings
global: {},
local: {}
},
_currPath; // Path to the settings.json file
var Settings = {
GetGlobal: (name) => {
return _settings.global[name] || null;
//return _settings.global[name];
},
GetLocal: (name) => {
return _settings.local[name] || null;
//return _settings.local[name];
},
SetGlobal: (name, data) => { _settings.global[name] = data; },
SetLocal: (name, data) => { _settings.local[name] = data; },
Save: function() {
fs.ensureFileSync(_currPath);
fs.writeJsonSync(_currPath, _settings);
},
Load: function(dir) {
// Load the settings into memory
_currPath = Path.resolve(dir, 'settings.json');
if(!fs.existsSync(_currPath)) {
// Ensure the settings.json file exists with
// at least empty `global` and `local` objects
fs.writeFileSync(_currPath, '{"global": {}, "local": {}}');
}
_settings = fs.readJsonSync(_currPath);
}
}
module.exports = Settings;
|
const fs = require('fs-extra'),
Path = require('path');
var _settings = { // Private storage of settings
global: {},
local: {}
},
_currPath; // Path to the settings.json file
var Settings = {
GetGlobal: (name) => {
return _settings.global[name] || null;
//return _settings.global[name];
},
GetLocal: (name) => {
return _settings.local[name] || null;
//return _settings.local[name];
},
SetGlobal: (name, data) => { _settings.global[name] = data; },
SetLocal: (name, data) => { _settings.local[name] = data; },
Save: function() {
fs.ensureFileSync(_currPath);
fs.writeJsonSync(_currPath, _settings);
},
Load: function(dir) {
// Load the settings into memory
_currPath = Path.resolve(dir, 'settings.json');
if(!fs.existsSync(_currPath)) {
// Ensure the settings.json file exists with
// at least empty `global` and `local` objects
fs.writeFileSync(_currPath, '{global: {}, local: {}}');
}
_settings = fs.readJsonSync(_currPath);
}
}
module.exports = Settings;
|
Fix `data-style` warning in examples
|
import React from 'react';
import {findDOMNode} from 'react-dom';
const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead';
class GitHubStarsButton extends React.Component {
componentDidMount() {
const node = findDOMNode(this);
node.dataset.size = window.innerWidth > 480 ? 'large': null;
}
render() {
return (
<a
aria-label={`Star ${AUTHOR_REPO} on GitHub`}
className="github-button"
data-count-aria-label="# stargazers on GitHub"
data-count-href={`/${AUTHOR_REPO}/stargazers`}
data-show-count={true}
href={`https://github.com/${AUTHOR_REPO}`}>
Star
</a>
);
}
}
export default GitHubStarsButton;
|
import React from 'react';
import {findDOMNode} from 'react-dom';
const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead';
class GitHubStarsButton extends React.Component {
componentDidMount() {
const node = findDOMNode(this);
node.dataset.style = window.innerWidth > 480 ? 'mega': null;
}
render() {
return (
<a
aria-label={`Star ${AUTHOR_REPO} on GitHub`}
className="github-button"
data-count-aria-label="# stargazers on GitHub"
data-count-href={`/${AUTHOR_REPO}/stargazers`}
data-show-count={true}
href={`https://github.com/${AUTHOR_REPO}`}>
Star
</a>
);
}
}
export default GitHubStarsButton;
|
Check that scope is an array
|
var deep = require('deep-get-set');
exports.register = function(plugin, options, next) {
plugin.servers[0].ext('onPreAuth', function(request, next) {
var i, matches, result, scope, _i, _len, _ref;
if (request.route.auth.scope !== null) {
_ref = request.route.auth.scope;
if (_ref.constructor !== Array) {
_ref = [_ref];
}
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
scope = _ref[i];
matches = scope.match(/{(.*)}/);
if (matches !== null) {
result = deep(request, matches[1]);
scope = scope.replace(/{.*}/, result);
request.route.auth.scope[i] = scope;
}
}
}
return next();
});
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
|
var deep = require('deep-get-set');
exports.register = function(plugin, options, next) {
plugin.servers[0].ext('onPreAuth', function(request, next) {
var i, matches, result, scope, _i, _len, _ref;
if (request.route.auth.scope !== null) {
_ref = request.route.auth.scope;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
scope = _ref[i];
matches = scope.match(/{(.*)}/);
if (matches !== null) {
result = deep(request, matches[1]);
scope = scope.replace(/{.*}/, result);
request.route.auth.scope[i] = scope;
}
}
}
return next();
});
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
|
Add `text` attribute to response from `chat`
|
from time import time
from ..core import Minette
from ..models import Message
class MinetteForTest(Minette):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.default_channel = kwargs.get("default_channel", "")
self.case_id = str(int(time() * 10000000))
def chat(self, request, **kwargs):
self.logger.info("start testcase: " + self.case_id)
# convert to Message
if isinstance(request, str):
request = Message(text=request, **kwargs)
# set channel and channel_user_id for this test case
if request.channel == "console":
request.channel = self.default_channel or request.channel
if request.channel_user_id == "anonymous":
request.channel_user_id = "user" + self.case_id
# chat and return response
response = super().chat(request)
if response.messages:
response.text = response.messages[0].text
else:
response.text = ""
self.logger.info("end testcase: " + self.case_id)
return response
|
from time import time
from ..core import Minette
from ..models import Message
class MinetteForTest(Minette):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.default_channel = kwargs.get("default_channel", "")
self.case_id = str(int(time() * 10000000))
def chat(self, request, **kwargs):
self.logger.info("start testcase: " + self.case_id)
# convert to Message
if isinstance(request, str):
request = Message(text=request, **kwargs)
# set channel and channel_user_id for this test case
if request.channel == "console":
request.channel = self.default_channel or request.channel
if request.channel_user_id == "anonymous":
request.channel_user_id = "user" + self.case_id
# chat and return response
response = super().chat(request)
self.logger.info("end testcase: " + self.case_id)
return response
|
Sort the generated manager file by protocol name
20070831193701-4210b-ede9decef118aba3937b0291512956927333dbe6.gz
|
#!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name
object_path = "/org/freedesktop/Telepathy/ConnectionManager/%s" % manager_name
object = telepathy.client.ConnectionManager(service_name, object_path)
manager = object[CONN_MGR_INTERFACE]
print "[ConnectionManager]"
print "BusName=%s" % service_name
print "ObjectPath=%s" % object_path
print
protocols = manager.ListProtocols()
protocols.sort()
for protocol in protocols:
print "[Protocol %s]" % protocol
for param in manager.GetParameters(protocol):
print "param-%s=%s" % (param[0], param[2]),
# FIXME: deal with the "register" flag
if param[1] == 1L:
print "required",
print
print
|
#!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name
object_path = "/org/freedesktop/Telepathy/ConnectionManager/%s" % manager_name
object = telepathy.client.ConnectionManager(service_name, object_path)
manager = object[CONN_MGR_INTERFACE]
print "[ConnectionManager]"
print "BusName=%s" % service_name
print "ObjectPath=%s" % object_path
print
for protocol in manager.ListProtocols():
print "[Protocol %s]" % protocol
for param in manager.GetParameters(protocol):
print "param-%s=%s" % (param[0], param[2]),
# FIXME: deal with the "register" flag
if param[1] == 1L:
print "required",
print
print
|
Deal with GPys numpy dependency
|
from setuptools import setup
from os import path
current_dir = path.abspath(path.dirname(__file__))
with open(path.join(current_dir, 'README.md'), 'r') as f:
long_description = f.read()
with open(path.join(current_dir, 'requirements.txt'), 'r') as f:
install_requires = f.read().split('\n')
setup(
name='safeopt',
version='0.1.1',
author='Felix Berkenkamp',
author_email='befelix@inf.ethz.ch',
packages=['safeopt'],
url='https://github.com/befelix/SafeOpt',
license='MIT',
description='Safe Bayesian optimization',
long_description=long_description,
setup_requires='numpy',
install_requires=install_requires,
keywords='Bayesian optimization, Safety',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5'],
)
|
from setuptools import setup
from os import path
current_dir = path.abspath(path.dirname(__file__))
with open(path.join(current_dir, 'README.md'), 'r') as f:
long_description = f.read()
with open(path.join(current_dir, 'requirements.txt'), 'r') as f:
install_requires = f.read().split('\n')
setup(
name='safeopt',
version='0.1.1',
author='Felix Berkenkamp',
author_email='befelix@inf.ethz.ch',
packages=['safeopt'],
url='https://github.com/befelix/SafeOpt',
license='MIT',
description='Safe Bayesian optimization',
long_description=long_description,
install_requires=install_requires,
keywords='Bayesian optimization, Safety',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5'],
)
|
Fix image file path at generated html file.
|
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const marked = require('marked');
const ECT = require('ect');
function md2html(filePath, cb) {
fs.readFile(filePath, 'utf8', (err, mdString) => {
if (err) {
cb(err);
return;
}
const markedRenderer = new marked.Renderer();
markedRenderer.image = function(href, title, text) {
const imgAbsolutePath = path.resolve(path.dirname(filePath), href);
return marked.Renderer.prototype.image.call(this, imgAbsolutePath, title, text);
}
const content = marked(mdString, { renderer: markedRenderer });
const data = { title: filePath, content : content, dirname : __dirname };
const renderer = ECT({ root : __dirname });
const html = renderer.render('template.ect', data);
cb(null, html);
});
}
function toHtmlFile(mdFilePath, cb) {
md2html(mdFilePath, (err, html) => {
if (err) {
cb(err);
return;
}
const name = path.basename(mdFilePath, path.extname(mdFilePath))
const htmlPath = path.join(os.tmpdir(), name + '.html');
fs.writeFile(htmlPath, html, (err) => {
cb(err, htmlPath)
});
});
}
exports.toHtmlFile = toHtmlFile;
|
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const marked = require('marked');
const ECT = require('ect');
function md2html(filePath, cb) {
fs.readFile(filePath, 'utf8', (err, mdString) => {
if (err) {
cb(err);
return;
}
const content = marked(mdString);
const renderer = ECT({ root : __dirname });
const data = { title: filePath, content : content, dirname : __dirname };
const html = renderer.render('template.ect', data);
cb(null, html);
});
}
function toHtmlFile(mdFilePath, cb) {
md2html(mdFilePath, (err, html) => {
if (err) {
cb(err);
return;
}
const name = path.basename(mdFilePath, path.extname(mdFilePath))
const htmlPath = path.join(os.tmpdir(), name + '.html');
fs.writeFile(htmlPath, html, (err) => {
cb(err, htmlPath)
});
});
}
exports.toHtmlFile = toHtmlFile;
|
Remove debug line added by mistake
|
<?php
require_once("boot.php");
function cronhooks_run(&$argv, &$argc){
global $a, $db;
if(is_null($a)) {
$a = new App;
}
if(is_null($db)) {
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
};
require_once('include/session.php');
require_once('include/datetime.php');
require_once('include/pidfile.php');
load_config('config');
load_config('system');
$lockpath = get_config('system','lockpath');
if ($lockpath != '') {
$pidfile = new pidfile($lockpath, 'cron.lck');
if($pidfile->is_already_running()) {
logger("cronhooks: Already running");
exit;
}
}
$a->set_baseurl(get_config('system','url'));
load_hooks();
logger('cronhooks: start');
$d = datetime_convert();
call_hooks('cron', $d);
return;
}
if (array_search(__file__,get_included_files())===0){
cronhooks_run($argv,$argc);
killme();
}
|
<?php
require_once("boot.php");
function cronhooks_run(&$argv, &$argc){
global $a, $db;
if(is_null($a)) {
$a = new App;
}
if(is_null($db)) {
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
};
require_once('include/session.php');
require_once('include/datetime.php');
require_once('include/pidfile.php');
load_config('config');
load_config('system');
$lockpath = get_config('system','lockpath');
if ($lockpath != '') {
$pidfile = new pidfile($lockpath, 'cron.lck');
if($pidfile->is_already_running()) {
logger("cronhooks: Already running");
exit;
}
}
$a->set_baseurl(get_config('system','url'));
load_hooks();
logger('cronhooks: start');
echo("@@@ cronhooks start\n");
$d = datetime_convert();
call_hooks('cron', $d);
return;
}
if (array_search(__file__,get_included_files())===0){
cronhooks_run($argv,$argc);
killme();
}
|
Automate Transfers: Paths stored as binary to handle encodings
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Binary, Boolean, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Binary())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Boolean, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Text())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
Integrate webpack into gulp task
|
const gulp = require('gulp');
const webpack = require('webpack');
const gutil = require('gulp-util');
const eslint = require('gulp-eslint');
const webpackConfig = require('./webpack.config');
gulp.task('script', (done) => {
webpack(webpackConfig).run((err, stats) => {
if (err) {
gutil.log(gutil.colors.red(err));
} else {
gutil.log(stats.toString());
}
done();
});
});
gulp.task('lint', () => {
gulp.src(['**/*.js', '!node_modules/**', '!dist/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('default', ['lint', 'script']);
|
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
gulp.task('script', () => {
gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(concat('details-polyfill.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
gulp.task('lint', () => {
gulp.src(['**/*.js', '!node_modules/**', '!dist/*.js'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('default', ['lint', 'script']);
|
Print all evaluation metrics associated with the model
|
#!/usr/bin/env python3
import argparse
import pickle
import tensorflow.keras as keras
import numpy as np
import sys
import cv2
parser = argparse.ArgumentParser(description='Train the network given ')
parser.add_argument('-b', '--database-path', dest='imgdb_path',
help='Path to the image database containing test data.'
'Default is img.db in current folder.')
parser.add_argument('-m', '--model-path', dest='model_path',
help='Store the trained model using this path. Default is model.h5.')
args = parser.parse_args()
imgdb_path = "img.db"
model_path = "model.h5"
res = {"x": 16, "y": 16}
if args.model_path is not None:
model_path = args.model_path
if args.imgdb_path is not None:
imgdb_path = args.imgdb_path
with open(imgdb_path, "rb") as f:
mean = pickle.load(f)
print("mean=" + str(mean))
x = pickle.load(f)
y = pickle.load(f)
model = keras.models.load_model(model_path)
print(model.summary())
x = np.array(x)
y = np.array(y)
result = model.evaluate(x,y)
print("Evaluation result")
print("=================")
for idx in range(0, len(result)):
print(model.metrics_names[idx] + ":", result[idx])
|
#!/usr/bin/env python3
import argparse
import pickle
import tensorflow.keras as keras
import numpy as np
import sys
import cv2
parser = argparse.ArgumentParser(description='Train the network given ')
parser.add_argument('-b', '--database-path', dest='imgdb_path',
help='Path to the image database containing test data.'
'Default is img.db in current folder.')
parser.add_argument('-m', '--model-path', dest='model_path',
help='Store the trained model using this path. Default is model.h5.')
args = parser.parse_args()
imgdb_path = "img.db"
model_path = "model.h5"
res = {"x": 16, "y": 16}
if args.model_path is not None:
model_path = args.model_path
if args.imgdb_path is not None:
imgdb_path = args.imgdb_path
with open(imgdb_path, "rb") as f:
mean = pickle.load(f)
print("mean=" + str(mean))
x = pickle.load(f)
y = pickle.load(f)
model = keras.models.load_model(model_path)
print(model.summary())
x = np.array(x)
y = np.array(y)
result = model.evaluate(x,y)
print("Evaluation result")
print("=================")
print("loss: {} precision: {}".format(result[0], result[1]))
|
Fix plugin manager with phar
|
<?php
/*
* This file is part of the Automate package.
*
* (c) Julien Jacottet <jjacottet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Automate;
use Automate\Plugin\PluginInterface;
class PluginManager
{
/**
* @var PluginInterface[]
*/
private $plugins = array();
public function __construct()
{
foreach (new \DirectoryIterator(__DIR__ .'/Plugin/') as $file) {
if($file->isFile()) {
$class = 'Automate\\Plugin\\' . substr($file->getFilename(), 0, -4);
$ref = new \ReflectionClass($class);
if(!$ref->isAbstract() && $ref->implementsInterface(PluginInterface::class)) {
$this->plugins[] = new $class;
}
}
}
}
/**
* @return PluginInterface[]
*/
public function getPlugins()
{
return $this->plugins;
}
}
|
<?php
/*
* This file is part of the Automate package.
*
* (c) Julien Jacottet <jjacottet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Automate;
use Automate\Plugin\PluginInterface;
class PluginManager
{
/**
* @var PluginInterface[]
*/
private $plugins = array();
public function __construct()
{
foreach (glob(__DIR__ .'/Plugin/*Plugin.php') as $filename) {
$file = new \SplFileInfo($filename);
$class = 'Automate\\Plugin\\' . substr($file->getFilename(), 0, -4);
$ref = new \ReflectionClass($class);
if(!$ref->isAbstract() && $ref->implementsInterface(PluginInterface::class)) {
$this->plugins[] = new $class;
}
}
}
/**
* @return PluginInterface[]
*/
public function getPlugins()
{
return $this->plugins;
}
}
|
Remove opacity from “What is this?” link 💋
|
import React from 'react'
import Bubbles from './Bubbles'
export default class Welcome extends React.Component {
render() {
const { opacity } = this.props
const containerStyle = {
background: '#E64369',
bottom: 0,
color: 'white',
display: 'flex',
flexDirection: 'column',
fontFamily: 'Helvetica Neue, Helvetica',
fontSize: 30,
fontWeight: '100',
justifyContent: 'center',
left: 0,
position: 'absolute',
right: 0,
textAlign: 'center',
top: 0,
}
const openSourceProject = {
color: 'white',
fontSize: 16,
margin: 0,
padding: 5,
position: 'absolute',
right: 0,
textDecoration: 'none',
top: 0,
}
return (
<div style={{ ...containerStyle, opacity: opacity }}>
<p>
<Bubbles />
</p>
<p>Searching videos outside of your bubble…</p>
<a href="http://github.com/pirelenito/unbubble" style={openSourceProject}>
What is this?
</a>
</div>
)
}
}
|
import React from 'react'
import Bubbles from './Bubbles'
export default class Welcome extends React.Component {
render() {
const { opacity } = this.props
const containerStyle = {
background: '#E64369',
bottom: 0,
color: 'white',
display: 'flex',
flexDirection: 'column',
fontFamily: 'Helvetica Neue, Helvetica',
fontSize: 30,
fontWeight: '100',
justifyContent: 'center',
left: 0,
position: 'absolute',
right: 0,
textAlign: 'center',
top: 0,
}
const openSourceProject = {
color: 'white',
fontSize: 16,
margin: 0,
opacity: 0.5,
padding: 5,
position: 'absolute',
right: 0,
textDecoration: 'none',
top: 0,
}
return (
<div style={{ ...containerStyle, opacity: opacity }}>
<p>
<Bubbles />
</p>
<p>Searching videos outside of your bubble…</p>
<a href="http://github.com/pirelenito/unbubble" style={openSourceProject}>
What is this?
</a>
</div>
)
}
}
|
Remove unused statement & format for python3
|
#!/usr/bin/env python
# Python script to fetch interface name and their operation status
from ncclient import manager
def connect(host, port, user, password):
conn = manager.connect(host=host,
port=port,
username=user,
password=password,
timeout=10,
device_params = {'name':'junos'},
hostkey_verify=False)
rpc = "<get-interface-information><terse/></get-interface-information>"
response = conn.rpc(rpc)
interface_name = response.xpath('//physical-interface/name')
interface_status = response.xpath('//physical-interface/oper-status')
for name, status in zip(interface_name, interface_status):
name = name.text.split('\n')[1]
status = status.text.split('\n')[1]
print ("{}-{}".format(name, status))
if __name__ == '__main__':
connect('router', 830, 'netconf', 'juniper!')
|
#!/usr/bin/env python
# Python script to fetch interface name and their operation status
from ncclient import manager
def connect(host, port, user, password):
conn = manager.connect(host=host,
port=port,
username=user,
password=password,
timeout=10,
device_params = {'name':'junos'},
hostkey_verify=False)
rpc = "<get-interface-information><terse/></get-interface-information>"
response = conn.rpc(rpc)
interface_name = response.xpath('//physical-interface/name')
interface_status = response.xpath('//physical-interface/oper-status')
interface_dict = dict()
for name, status in zip(interface_name, interface_status):
name = name.text.split('\n')[1]
status = status.text.split('\n')[1]
print "{}-{}".format(name, status)
if __name__ == '__main__':
connect('router', 830, 'netconf', 'juniper!')
|
Use hasattr instead of try/except to call django setup.
|
import os
import pytest
try:
from django.conf import settings
except ImportError:
settings = None # NOQA
def is_configured():
if settings is None:
return False
return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE')
@pytest.fixture(autouse=True, scope='session')
def _django_runner(request):
if not is_configured():
return
from django.test.simple import DjangoTestSuiteRunner
import django
if hasattr(django, 'setup'):
django.setup()
runner = DjangoTestSuiteRunner(interactive=False)
runner.setup_test_environment()
request.addfinalizer(runner.teardown_test_environment)
config = runner.setup_databases()
def teardown_database():
runner.teardown_databases(config)
request.addfinalizer(teardown_database)
return runner
|
import os
import pytest
try:
from django.conf import settings
except ImportError:
settings = None # NOQA
def is_configured():
if settings is None:
return False
return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE')
@pytest.fixture(autouse=True, scope='session')
def _django_runner(request):
if not is_configured():
return
from django.test.simple import DjangoTestSuiteRunner
try:
import django
django.setup()
except AttributeError:
pass
runner = DjangoTestSuiteRunner(interactive=False)
runner.setup_test_environment()
request.addfinalizer(runner.teardown_test_environment)
config = runner.setup_databases()
def teardown_database():
runner.teardown_databases(config)
request.addfinalizer(teardown_database)
return runner
|
Fix broken redirects and serving of older websites
|
var express = require('express')
var vhost = require('vhost')
var app2014 = require('./2014/app')
var app2015 = require('./2015/app')
var app2016 = require('./2016/app')
var appSplash = require('./splash/app')
var redirect = express()
redirect.get('/', function (req, res) {
res.redirect(301, 'https://2016.coldfrontconf.com')
})
var server = express()
server.set('port', process.env.PORT || 8080)
server.use(vhost('2014.coldfrontconf.com', app2014))
server.use(vhost('2015.coldfrontconf.com', app2015))
server.use(vhost('2016.coldfrontconf.com', app2016))
server.use(vhost('coldfrontconf.com', redirect))
server.use(vhost('localhost', app2016))
server.listen(server.get('port'), function () {
console.log('Express server listening on port %d in %s mode', server.get('port'), server.settings.env)
})
|
var express = require('express')
var vhost = require('vhost')
var app2014 = require('./2014/app')
var app2015 = require('./2015/app')
var app2016 = require('./2016/app')
var appSplash = require('./splash/app')
//var redirect = express()
//redirect.get('/', function (req, res) {
// res.redirect(301, 'https://2016.coldfrontconf.com')
//})
var server = express()
server.set('port', process.env.PORT || 8080)
//server.use(vhost('2014.coldfrontconf.com', app2014))
//server.use(vhost('2015.coldfrontconf.com', app2015))
//server.use(vhost('2016.coldfrontconf.com', app2016))
//server.use(vhost('coldfrontconf.com', redirect))
server.use(vhost('localhost', app2016))
server.listen(server.get('port'), function () {
console.log('Express server listening on port %d in %s mode', server.get('port'), server.settings.env)
})
|
Add default description on user model
|
const Sequelize = require('sequelize');
const db = require('../db.js');
const Users = db.define('users',
{
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true,
},
facebook_id: {
type: Sequelize.STRING,
},
first_name: {
type: Sequelize.STRING,
},
last_name: {
type: Sequelize.STRING,
},
photo_url: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.STRING(256),
defaultValue: 'Click here to edit!',
},
// would like to add counter cache for request count and connection count
},
{
freezeTableName: true,
}
);
module.exports = Users;
|
const Sequelize = require('sequelize');
const db = require('../db.js');
const Users = db.define('users',
{
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV1,
primaryKey: true,
},
facebook_id: {
type: Sequelize.STRING,
},
first_name: {
type: Sequelize.STRING,
},
last_name: {
type: Sequelize.STRING,
},
photo_url: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.STRING(256),
},
// would like to add counter cache for request count and connection count
},
{
freezeTableName: true,
}
);
module.exports = Users;
|
Add title and shorten advisory
|
'use strict';
var cvss = require('cvss');
module.exports = function (err, data, pkgPath) {
if (err) {
return 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n' + err;
}
var pipeWrap = function (items) {
return '|' + items.join('|') + '|';
};
var header = ['Severity', 'Title', 'Module', 'Installed', 'Patched', 'Include Path', 'More Info'];
var rows = [];
rows.push( pipeWrap(header) );
rows.push( pipeWrap( Array(header.length).fill('--') ) );
data.forEach( function (finding) {
var advisory_number = finding.advisory.substr(finding.advisory.lastIndexOf('/'));
rows.push(
pipeWrap(
[cvss.getRating(finding.cvss_score), finding.title, finding.module, finding.version, finding.patched_versions === '<1.0.0' ? 'None' : finding.patched_versions, '{nav ' + finding.path.join(' > ') + '}', '[[' + finding.advisory + '|nspa' + advisory_number + ']]']
)
);
});
return rows.join('\n');
};
|
'use strict';
var cvss = require('cvss');
module.exports = function (err, data, pkgPath) {
if (err) {
return 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n' + err;
}
var pipeWrap = function (items) {
return '|' + items.join('|') + '|';
};
var header = ['Severity', 'Name', 'Installed', 'Patched', 'Include Path', 'More Info'];
var rows = [];
rows.push( pipeWrap(header) );
rows.push( pipeWrap( Array(header.length).fill('--') ) );
data.forEach( function (finding) {
rows.push(
pipeWrap(
[cvss.getRating(finding.cvss_score), finding.module, finding.version, finding.patched_versions === '<0.0.0' ? 'None' : finding.patched_versions, finding.path.join(' > '), finding.advisory]
)
);
});
return rows.join('\n');
};
|
Set USE_TZ=True, django 4 raises a warning if this is not set to a value
|
# Minimum settings that are needed to run django test suite
import os
import secrets
import tempfile
USE_TZ = True
SECRET_KEY = secrets.token_hex()
if "postgresql" in os.getenv("TOX_ENV_NAME", "") or os.getenv("TEST_DATABASE") == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dirtyfields_test',
'USER': os.getenv('POSTGRES_USER', 'postgres'),
'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'postgres'),
'HOST': 'localhost',
'PORT': '5432', # default postgresql port
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dirtyfields.db',
}
}
INSTALLED_APPS = ('tests', )
MEDIA_ROOT = tempfile.mkdtemp(prefix="django-dirtyfields-test-media-root-")
|
# Minimum settings that are needed to run django test suite
import os
import secrets
import tempfile
SECRET_KEY = secrets.token_hex()
if "postgresql" in os.getenv("TOX_ENV_NAME", "") or os.getenv("TEST_DATABASE") == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dirtyfields_test',
'USER': os.getenv('POSTGRES_USER', 'postgres'),
'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'postgres'),
'HOST': 'localhost',
'PORT': '5432', # default postgresql port
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dirtyfields.db',
}
}
INSTALLED_APPS = ('tests', )
MEDIA_ROOT = tempfile.mkdtemp(prefix="django-dirtyfields-test-media-root-")
|
Change redirect to application redirect
|
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from news.models import Article, Event
from door.models import DoorStatus
from datetime import datetime
from itertools import chain
def index(request):
number_of_news = 3
# Sorts the news to show the events nearest in future and then fill in with the newest articles
event_list = Event.objects.filter(time_end__gte=datetime.now())[0:number_of_news:-1]
article_list = Article.objects.order_by('-pub_date')[0:number_of_news - len(event_list)]
news_list = list(chain(event_list, article_list))
try:
door_status = DoorStatus.objects.get(name='hackerspace').status
except DoorStatus.DoesNotExist:
door_status = True
context = {
'news_list': news_list,
'door_status': door_status,
}
return render(request, 'index.html', context)
def opptak(request):
return HttpResponseRedirect(reverse('article', args=[6]))
def test404(request):
return render(request, '404.html')
|
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from news.models import Article, Event
from door.models import DoorStatus
from datetime import datetime
from itertools import chain
def index(request):
number_of_news = 3
# Sorts the news to show the events nearest in future and then fill in with the newest articles
event_list = Event.objects.filter(time_end__gte=datetime.now())[0:number_of_news:-1]
article_list = Article.objects.order_by('-pub_date')[0:number_of_news - len(event_list)]
news_list = list(chain(event_list, article_list))
try:
door_status = DoorStatus.objects.get(name='hackerspace').status
except DoorStatus.DoesNotExist:
door_status = True
context = {
'news_list': news_list,
'door_status': door_status,
}
return render(request, 'index.html', context)
def opptak(request):
return HttpResponseRedirect(reverse('application_form'))
def test404(request):
return render(request, '404.html')
|
Change Jasmine import syntax to satisfy Travis
|
const path = require('path')
const MarkdownRenderer = require('../src/renderer').MarkdownRenderer
describe ('Renderer', () => {
var renderer
var callback
beforeEach(() => {
callback = jasmine.createSpy('callback')
renderer = new MarkdownRenderer(callback)
})
it('converts a markdown file', (done) => {
const markdownFilePath = path.join(__dirname, 'md', 'header.md')
renderer.loadFile(markdownFilePath).then(() => {
expect(callback).toHaveBeenCalledWith(
'<div class="markdown-body"><h1 id="hello">Hello</h1></div>'
)
done()
}, done.fail)
})
it('converts a markdown string', (done) => {
var markdown = '## Hi'
renderer.load(markdown).then(() => {
expect(callback).toHaveBeenCalledWith(
'<div class="markdown-body"><h2 id="hi">Hi</h2></div>'
)
done()
}, done.fail)
})
it('preserves new lines in code', (done) => {
const markdownFilePath = path.join(__dirname, 'md', 'code.md')
renderer.loadFile(markdownFilePath).then(() => {
expect(callback).toHaveBeenCalledWith(
'<div class="markdown-body"><pre><code>var x = 3\nvar y = null\n</code></pre></div>'
)
done()
}, done.fail)
})
})
|
const path = require('path')
const { MarkdownRenderer } = require('../src/renderer')
describe ('Renderer', () => {
var renderer
var callback
beforeEach(() => {
callback = jasmine.createSpy('callback')
renderer = new MarkdownRenderer(callback)
})
it('converts a markdown file', (done) => {
const markdownFilePath = path.join(__dirname, 'md', 'header.md')
renderer.loadFile(markdownFilePath).then(() => {
expect(callback).toHaveBeenCalledWith(
'<div class="markdown-body"><h1 id="hello">Hello</h1></div>'
)
done()
}, done.fail)
})
it('converts a markdown string', (done) => {
var markdown = '## Hi'
renderer.load(markdown).then(() => {
expect(callback).toHaveBeenCalledWith(
'<div class="markdown-body"><h2 id="hi">Hi</h2></div>'
)
done()
}, done.fail)
})
it('preserves new lines in code', (done) => {
const markdownFilePath = path.join(__dirname, 'md', 'code.md')
renderer.loadFile(markdownFilePath).then(() => {
expect(callback).toHaveBeenCalledWith(
'<div class="markdown-body"><pre><code>var x = 3\nvar y = null\n</code></pre></div>'
)
done()
}, done.fail)
})
})
|
Handle decompression bomb errors as well as warnings.
|
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from PIL import Image
from PIL.Image import DecompressionBombError as DBE
from PIL.Image import DecompressionBombWarning as DBW
from ingestors.exc import ProcessingException
class ImageSupport(object):
"""Provides helpers for image extraction."""
def parse_image(self, data):
"""Parse an image file into PIL."""
try:
image = Image.open(StringIO(data))
image.load()
return image
except (DBE, DBW) as dce:
raise ProcessingException("Image too large: %r" % dce)
except IOError as ioe:
raise ProcessingException("Unknown image format: %r" % ioe)
except (RuntimeError, SyntaxError) as err:
raise ProcessingException("Failed to load image: %r" % err)
|
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from PIL import Image
from PIL.Image import DecompressionBombWarning
from ingestors.exc import ProcessingException
class ImageSupport(object):
"""Provides helpers for image extraction."""
def parse_image(self, data):
"""Parse an image file into PIL."""
try:
image = Image.open(StringIO(data))
image.load()
return image
except DecompressionBombWarning as dce:
raise ProcessingException("Image too large: %r" % dce)
except IOError as ioe:
raise ProcessingException("Unknown image format: %r" % ioe)
except (RuntimeError, SyntaxError) as err:
raise ProcessingException("Failed to load image: %r" % err)
|
Debug : unfund variable $table ->suppression
|
<?php
class DegustationAffectationValidator extends sfValidatorSchema {
public function __construct($obj, $fields= null, $options = array(), $messages = array()) {
$this->obj = $obj;
parent::__construct($fields, $options, $messages);
}
public function configure($options = array(), $messages = array()) {
$this->addMessage('impossible_table', "La table selectionnée n'existe pas dans cette dégustation");
}
protected function doClean($values) {
$errorSchema = new sfValidatorErrorSchema($this);
$hasError = false;
$degustation = DegustationClient::getInstance()->find($values['degustation']);
$infos = $degustation->getInfosDegustation();
if ($values['numero_table'] > $infos['nbTables'] +1) {
$errorSchema->addError(new sfValidatorError($this, 'impossible_table'), 'numero_table');
$hasError = true;
}
if ($hasError) {
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}
|
<?php
class DegustationAffectationValidator extends sfValidatorSchema {
public function __construct($obj, $fields= null, $options = array(), $messages = array()) {
$this->obj = $obj;
parent::__construct($fields, $options, $messages);
}
public function configure($options = array(), $messages = array()) {
$this->addMessage('impossible_table', "La table n'existe pas ".$table);
}
protected function doClean($values) {
$errorSchema = new sfValidatorErrorSchema($this);
$hasError = false;
$degustation = DegustationClient::getInstance()->find($values['degustation']);
$infos = $degustation->getInfosDegustation();
if ($values['numero_table'] > $infos['nbTables']) {
$errorSchema->addError(new sfValidatorError($this, 'impossible_table'), 'numero_table');
$hasError = true;
}
if ($hasError) {
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}
|
Return TODO rather than None, add pkg_name property for PackageData
|
class PackageData(object):
def __init__(self, local_file, name, version):
self.local_file = local_file
self.name = name
self.version = version
def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
return 'TODO:'
@property
def pkg_name(self, name):
if self.name.lower().find('py') != -1:
return self.name
else:
return 'python-%s'
class PypiData(PackageData):
def __init__(self, local_file, name, version, md5, url):
super(PackageData, self).__init__(local_file, name, version)
self.md5 = md5
self.url = url
class LocalData(PackageData):
def __init__(self, local_file, name, version):
super(PackageData, self).__init__(local_file, name, version)
|
class PackageData(object):
def __init__(self, local_file, name, version):
self.local_file = local_file
self.name = name
self.version = version
def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
return None
class PypiData(PackageData):
def __init__(self, local_file, name, version, md5, url):
super(PackageData, self).__init__(local_file, name, version)
self.md5 = md5
self.url = url
class LocalData(PackageData):
def __init__(self, local_file, name, version):
super(PackageData, self).__init__(local_file, name, version)
|
Make sure the whole canvas is cleared.
|
Doc = Base.extend({
beans: true,
initialize: function(canvas) {
if (canvas) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.size = new Size(canvas.offsetWidth, canvas.offsetHeight);
}
Paper.documents.push(this);
this.activate();
this.layers = [];
this.activeLayer = new Layer();
this.currentStyle = null;
this.symbols = [];
},
getCurrentStyle: function() {
return this._currentStyle;
},
setCurrentStyle: function(style) {
this._currentStyle = new PathStyle(this, style);
},
activate: function() {
Paper.activateDocument(this);
},
redraw: function() {
if (this.canvas) {
this.ctx.clearRect(0, 0, this.size.width + 1, this.size.height);
for (var i = 0, l = this.layers.length; i < l; i++) {
this.layers[i].draw(this.ctx);
}
}
}
});
|
Doc = Base.extend({
beans: true,
initialize: function(canvas) {
if (canvas) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.size = new Size(canvas.offsetWidth, canvas.offsetHeight);
}
Paper.documents.push(this);
this.activate();
this.layers = [];
this.activeLayer = new Layer();
this.currentStyle = null;
this.symbols = [];
},
getCurrentStyle: function() {
return this._currentStyle;
},
setCurrentStyle: function(style) {
this._currentStyle = new PathStyle(this, style);
},
activate: function() {
Paper.activateDocument(this);
},
redraw: function() {
if (this.canvas) {
this.ctx.clearRect(0, 0, this.size.width, this.size.height);
for (var i = 0, l = this.layers.length; i < l; i++) {
this.layers[i].draw(this.ctx);
}
}
}
});
|
Fix chainer v4 error about type_check._argname
|
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argname'):
# typecheck._argname is introduced by Chainer v6
type_check._argname(in_types, ('x',))
x_type, = in_types
type_check.expect(x_type.dtype.kind == 'f')
def forward(self, inputs):
self.retain_inputs((0,))
x, = inputs
xp = cuda.get_array_module(x)
y = xp.arctanh(x)
return utils.force_array(y, dtype=x.dtype),
def backward(self, indexes, grad_outputs):
x, = self.get_retained_inputs()
gy, = grad_outputs
gx = 1. / (1 - x ** 2) * gy
return gx,
def arctanh(x):
"""Elementwise inverse hyperbolic tangent function.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Arctanh().apply((x,))[0]
|
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
type_check._argname(in_types, ('x',))
x_type, = in_types
type_check.expect(x_type.dtype.kind == 'f')
def forward(self, inputs):
self.retain_inputs((0,))
x, = inputs
xp = cuda.get_array_module(x)
y = xp.arctanh(x)
return utils.force_array(y, dtype=x.dtype),
def backward(self, indexes, grad_outputs):
x, = self.get_retained_inputs()
gy, = grad_outputs
gx = 1. / (1 - x ** 2) * gy
return gx,
def arctanh(x):
"""Elementwise inverse hyperbolic tangent function.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Arctanh().apply((x,))[0]
|
Fixed: Resolve the path to the RequireJS instead of hardcoding it.
|
/**
* Copyright (c) 2014, CKSource - Frederico Knabben. All rights reserved.
* Licensed under the terms of the MIT License (see LICENSE.md).
*/
'use strict';
var path = require( 'path' ),
_ = require( 'lodash' ),
files = [
path.join( require.resolve( 'requirejs' ), '../../require.js' ),
path.join( __dirname, '/adapter.js' )
],
requireConfig = {};
module.exports = {
name: 'bender-pagebuilder-amd',
files: files,
include: files,
build: function( data ) {
data.parts.push( '<head><script>require.config(' + JSON.stringify( requireConfig ) + ');</script></head>' );
return data;
},
init: function( done ) {
var config = this.conf.amd || this.conf[ 'bender-amd' ];
if ( this.conf[ 'bender-amd' ] ) {
this.logger.warn( '"bender-amd" config property is deprecated, please use "amd" instead' );
}
if ( config ) {
_.extend( requireConfig, config );
}
done();
}
};
|
/**
* Copyright (c) 2014, CKSource - Frederico Knabben. All rights reserved.
* Licensed under the terms of the MIT License (see LICENSE.md).
*/
'use strict';
var path = require( 'path' ),
_ = require( 'lodash' ),
files = [
path.join( __dirname, '/../node_modules/requirejs/require.js' ),
path.join( __dirname, '/adapter.js' )
],
requireConfig = {};
module.exports = {
name: 'bender-pagebuilder-amd',
files: files,
include: files,
build: function( data ) {
data.parts.push( '<head><script>require.config(' + JSON.stringify( requireConfig ) + ');</script></head>' );
return data;
},
init: function( done ) {
var config = this.conf.amd || this.conf[ 'bender-amd' ];
if ( this.conf[ 'bender-amd' ] ) {
this.logger.warn( '"bender-amd" config property is deprecated, please use "amd" instead' );
}
if ( config ) {
_.extend( requireConfig, config );
}
done();
}
};
|
Add back check for string 'undefined'
(There was probably some case where this was happening instead of the 'null' thing)
|
const utils = require('../lib/utils')
const insecurity = require('../lib/insecurity')
const models = require('../models/index')
const challenges = require('../data/datacache').challenges
module.exports = function retrieveBasket () {
return (req, res, next) => {
const id = req.params.id
models.Basket.find({ where: { id }, include: [ { model: models.Product, paranoid: false } ] })
.then(basket => {
/* jshint eqeqeq:false */
if (utils.notSolved(challenges.basketAccessChallenge)) {
const user = insecurity.authenticatedUsers.from(req)
if (user && id && id !== 'undefined' && id !== 'null' && user.bid != id) { // eslint-disable-line eqeqeq
utils.solve(challenges.basketAccessChallenge)
}
}
res.json(utils.queryResultToJson(basket))
}).catch(error => {
next(error)
})
}
}
|
const utils = require('../lib/utils')
const insecurity = require('../lib/insecurity')
const models = require('../models/index')
const challenges = require('../data/datacache').challenges
module.exports = function retrieveBasket () {
return (req, res, next) => {
const id = req.params.id
models.Basket.find({ where: { id }, include: [ { model: models.Product, paranoid: false } ] })
.then(basket => {
/* jshint eqeqeq:false */
if (utils.notSolved(challenges.basketAccessChallenge)) {
const user = insecurity.authenticatedUsers.from(req)
if (user && id && id !== 'null' && user.bid != id) { // eslint-disable-line eqeqeq
utils.solve(challenges.basketAccessChallenge)
}
}
res.json(utils.queryResultToJson(basket))
}).catch(error => {
next(error)
})
}
}
|
Make test asynchronous if it wants to be
|
/* global describe, it */
import {exec} from '../../../src/utils/util';
import assert from 'assert';
require('chai').should();
describe("Oi CLI", () => {
it("can be invoked", (done) => {
const result = exec('node dist/bin/oi.js -v');
console.log(result);
console.log(result.toString());
console.log(result.code);
console.log(result.stdout);
console.log(result.stdout.trim());
console.log(result.stdout.trim().match(/^\d+\.\d+\.\d+$/));
try {
result.stdout.trim().should.match(/^\d+\.\d+\.\d+$/);
done();
} catch (e) {
console.error('ERROR:', e);
done(e);
throw Error('FAIL');
}
});
});
|
/* global describe, it */
import {exec} from '../../../src/utils/util';
import assert from 'assert';
require('chai').should();
describe("Oi CLI", () => {
it("can be invoked", () => {
const result = exec('node dist/bin/oi.js -v');
console.log(result);
console.log(result.toString());
console.log(result.code);
console.log(result.stdout);
console.log(result.stdout.trim());
console.log(result.stdout.trim().match(/^\d+\.\d+\.\d+$/));
try {
result.stdout.trim().should.match(/^\d+\.\d+\.\d+$/);
} catch (e) {
console.error('ERROR:', e);
throw Error('FAIL');
}
});
});
|
Add better check for being in a CMS-page request
|
# -*- coding: utf-8 -*-
from app_data import AppDataContainer, app_registry
from cms.apphook_pool import apphook_pool
from django.core.urlresolvers import resolve
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config
"""
app = None
if getattr(request, 'current_page', None):
app = apphook_pool.get_apphook(request.current_page.application_urls)
config = None
namespace = resolve(request.path_info).namespace
if app and app.app_config:
config = app.get_config(namespace)
return namespace, config
def setup_config(form_class, config_model):
"""
Register the provided form as config form for the provided config model
:param form_class: Form class derived from AppDataForm
:param config_model: Model class derived from AppHookConfig
:return:
"""
app_registry.register('config', AppDataContainer.from_form(form_class), config_model)
|
# -*- coding: utf-8 -*-
from app_data import AppDataContainer, app_registry
from cms.apphook_pool import apphook_pool
from django.core.urlresolvers import resolve
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config
"""
app = None
if request.current_page:
app = apphook_pool.get_apphook(request.current_page.application_urls)
config = None
namespace = resolve(request.path_info).namespace
if app and app.app_config:
config = app.get_config(namespace)
return namespace, config
def setup_config(form_class, config_model):
"""
Register the provided form as config form for the provided config model
:param form_class: Form class derived from AppDataForm
:param config_model: Model class derived from AppHookConfig
:return:
"""
app_registry.register('config', AppDataContainer.from_form(form_class), config_model)
|
Remove paragraphs since they add unnecessary vertical padding.
|
var key = require('../utils/key');
var sync = require('synchronize');
var request = require('request');
var _ = require('underscore');
// The API that returns the in-email representation.
module.exports = function(req, res) {
var url = req.query.url.trim();
// Giphy image urls are in the format:
// http://giphy.com/gifs/<seo-text>-<alphanumeric id>
var matches = url.match(/\-([a-zA-Z0-9]+)$/);
if (!matches) {
res.status(400).send('Invalid URL format');
return;
}
var id = matches[1];
var response;
try {
response = sync.await(request({
url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id),
qs: {
api_key: key
},
gzip: true,
json: true,
timeout: 15 * 1000
}, sync.defer()));
} catch (e) {
res.status(500).send('Error');
return;
}
var image = response.body.data.images.original;
var width = image.width > 600 ? 600 : image.width;
var html = '<img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/>';
res.json({
body: html
});
};
|
var key = require('../utils/key');
var sync = require('synchronize');
var request = require('request');
var _ = require('underscore');
// The API that returns the in-email representation.
module.exports = function(req, res) {
var url = req.query.url.trim();
// Giphy image urls are in the format:
// http://giphy.com/gifs/<seo-text>-<alphanumeric id>
var matches = url.match(/\-([a-zA-Z0-9]+)$/);
if (!matches) {
res.status(400).send('Invalid URL format');
return;
}
var id = matches[1];
var response;
try {
response = sync.await(request({
url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id),
qs: {
api_key: key
},
gzip: true,
json: true,
timeout: 15 * 1000
}, sync.defer()));
} catch (e) {
res.status(500).send('Error');
return;
}
var image = response.body.data.images.original;
var width = image.width > 600 ? 600 : image.width;
var html = '<p><img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/></p>';
res.json({
body: html
});
};
|
Update docker images to version 34
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.tests.product.launcher.env;
public final class EnvironmentDefaults
{
public static final String DOCKER_IMAGES_VERSION = "34";
public static final String HADOOP_BASE_IMAGE = "prestodev/hdp2.6-hive";
public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";
private EnvironmentDefaults() {}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.tests.product.launcher.env;
public final class EnvironmentDefaults
{
public static final String DOCKER_IMAGES_VERSION = "33";
public static final String HADOOP_BASE_IMAGE = "prestodev/hdp2.6-hive";
public static final String HADOOP_IMAGES_VERSION = DOCKER_IMAGES_VERSION;
public static final String TEMPTO_ENVIRONMENT_CONFIG = "/dev/null";
private EnvironmentDefaults() {}
}
|
Correct path to parent dir
|
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from gravity import __version__ # noqa: E402
project = 'Gravity'
copyright = '2022, The Galaxy Project'
author = 'The Galaxy Project'
release = '__version__'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
|
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from gravity import __version__ # noqa: E402
project = 'Gravity'
copyright = '2022, The Galaxy Project'
author = 'The Galaxy Project'
release = '__version__'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']
|
Remove deprecated override on createJSModules method
|
package com.marcshilling.idletimer;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class IdleTimerPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new IdleTimerManager(reactContext)
);
}
// Deprecated in React Native 0.47.0
// @Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package com.marcshilling.idletimer;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class IdleTimerPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new IdleTimerManager(reactContext)
);
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Update notification model to spit out id
|
<?php
namespace Kregel\Radio\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Kregel\FormModel\Traits\Formable;
use Kregel\Warden\Traits\Wardenable;
class Notification extends Model
{
use Formable;
protected $table = 'radio_notifications';
protected $fillable = [
'channel_id', 'user_id', 'is_unread', 'name', 'description' , 'link', 'type'
];
public static function boot()
{
Notification::created(function (Notification $notify){
$data = collect($notify->toArray())->merge([
'uuid' => $notify->user->channel->uuid,
'is_unread' => 1
]);
Redis::publish($data['uuid'], collect($data));
});
}
protected $casts = [
'is_unread' => 'bool'
];
public function user()
{
return $this->belongsTo(config('auth.providers.users.model'));
}
}
|
<?php
namespace Kregel\Radio\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Kregel\FormModel\Traits\Formable;
use Kregel\Warden\Traits\Wardenable;
class Notification extends Model
{
use Formable;
protected $table = 'radio_notifications';
protected $fillable = [
'channel_id', 'user_id', 'is_unread', 'name', 'description' , 'link', 'type'
];
public static function boot()
{
Notification::creating(function (Notification $notify){
$data = collect($notify->toArray())->merge([
'uuid' => $notify->user->channel->uuid,
'is_unread' => 1
]);
Redis::publish($data['uuid'], collect($data));
});
}
protected $casts = [
'is_unread' => 'bool'
];
public function user()
{
return $this->belongsTo(config('auth.providers.users.model'));
}
}
|
Revert "fix links from test page"
This reverts commit 27dd0e3170bb185e385deed11b153d86983ae0c6.
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
// Personally, hash is nicer for test work. The browser knows not
// to do a full page refresh when you manually edit the url.
locationType: 'hash',
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 = 'auto';
// 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: 'dummy',
environment: environment,
baseURL: '/',
// Personally, hash is nicer for test work. The browser knows not
// to do a full page refresh when you manually edit the url.
locationType: 'hash',
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 verison_slug redirection back in for now.
|
from django.conf.urls.defaults import url, patterns
from urls import urlpatterns as main_patterns
urlpatterns = patterns('',
url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.subproject_serve_docs',
name='subproject_docs_detail'
),
url(r'^projects/(?P<project_slug>[\w.-]+)',
'core.views.subproject_serve_docs',
name='subproject_docs_detail'
),
url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.serve_docs',
name='docs_detail'
),
url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>.*)/$',
'core.views.serve_docs',
{'filename': 'index.html'},
name='docs_detail'
),
url(r'^(?P<version_slug>.*)/$',
'core.views.subdomain_handler',
name='version_subdomain_handler'
),
url(r'^$', 'core.views.subdomain_handler'),
)
urlpatterns += main_patterns
|
from django.conf.urls.defaults import url, patterns
from urls import urlpatterns as main_patterns
urlpatterns = patterns('',
url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.subproject_serve_docs',
name='subproject_docs_detail'
),
url(r'^projects/(?P<project_slug>[\w.-]+)',
'core.views.subproject_serve_docs',
name='subproject_docs_detail'
),
url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.serve_docs',
name='docs_detail'
),
url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>.*)/$',
'core.views.serve_docs',
{'filename': 'index.html'},
name='docs_detail'
),
url(r'^$', 'core.views.subdomain_handler'),
)
urlpatterns += main_patterns
|
Simplify setTimeout using bind() in a useful way
|
function RetryOperation(timeouts) {
this._timeouts = timeouts;
this._fn = null;
this._errors = [];
}
module.exports = RetryOperation;
RetryOperation.prototype.retry = function(err) {
if (!err) {
return false;
}
this._errors.push(err);
var timeout = this._timeouts.shift();
if (timeout === undefined) {
return false;
}
setTimeout(this._fn.bind(this), timeout);
return true;
};
RetryOperation.prototype.try = function(fn) {
this._fn = fn;
this._fn();
};
RetryOperation.prototype.errors = function() {
return this._errors;
};
RetryOperation.prototype.mainError = function() {
if (this._errors.length === 0) {
return null;
}
var counts = {};
var mainError = null;
var mainErrorCount = 0;
for (var i = 0; i < this._errors.length; i++) {
var error = this._errors[i];
var message = error.message;
var count = (counts[message] || 0) + 1;
counts[message] = count;
if (count >= mainErrorCount) {
mainError = error;
mainErrorCount = count;
}
}
return mainError;
};
|
function RetryOperation(timeouts) {
this._timeouts = timeouts;
this._fn = null;
this._errors = [];
}
module.exports = RetryOperation;
RetryOperation.prototype.retry = function(err) {
if (!err) {
return false;
}
this._errors.push(err);
var timeout = this._timeouts.shift();
if (timeout === undefined) {
return false;
}
setTimeout(function() {
this._fn();
}.bind(this), timeout);
return true;
};
RetryOperation.prototype.try = function(fn) {
this._fn = fn;
this._fn();
};
RetryOperation.prototype.errors = function() {
return this._errors;
};
RetryOperation.prototype.mainError = function() {
if (this._errors.length === 0) {
return null;
}
var counts = {};
var mainError = null;
var mainErrorCount = 0;
for (var i = 0; i < this._errors.length; i++) {
var error = this._errors[i];
var message = error.message;
var count = (counts[message] || 0) + 1;
counts[message] = count;
if (count >= mainErrorCount) {
mainError = error;
mainErrorCount = count;
}
}
return mainError;
};
|
Use the same random alg in tokengen as pwdcrytpt
|
package us.kbase.auth2.cryptutils;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64; // requires java 8
public class TokenGenerator {
//TODO ONMOVE unit tests
//TODO ONMOVE docs
//TODO ONDB don't store the token, store a hash. For user requested tokens, associate a name. Store the date of creation & lifetime.
// Inspiration from http://stackoverflow.com/a/41156/643675
// note SecureRandom is thread safe
private final SecureRandom random;
public TokenGenerator() throws NoSuchAlgorithmException {
random = SecureRandom.getInstance("SHA1PRNG");
}
public String getToken() {
final byte[] b = new byte[21]; //168 bits so 28 b64 chars
random.nextBytes(b);
return new String(Base64.getEncoder().encode(b),
StandardCharsets.UTF_8);
}
//TODO ONMOVE remove
public static void main(String[] args) throws Exception {
String t = new TokenGenerator().getToken();
System.out.println(t + " " + t.length());
}
}
|
package us.kbase.auth2.cryptutils;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64; // requires java 8
public class TokenGenerator {
//TODO ONMOVE unit tests
//TODO ONMOVE docs
//TODO ONDB don't store the token, store a hash. For user requested tokens, associate a name. Store the date of creation & lifetime.
// Inspiration from http://stackoverflow.com/a/41156/643675
// note SecureRandom is thread safe
private final SecureRandom random;
public TokenGenerator() {
random = new SecureRandom();
}
public String getToken() {
final byte[] b = new byte[21]; //168 bits so 28 b64 chars
random.nextBytes(b);
return new String(Base64.getEncoder().encode(b),
StandardCharsets.UTF_8);
}
//TODO ONMOVE remove
public static void main(String[] args) throws Exception {
String t = new TokenGenerator().getToken();
System.out.println(t + " " + t.length());
}
}
|
Increase the upper range for animation duration.
|
$(function() {
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function newBubble () {
var radius = randomInt(10, 208);
var animationDuration = randomInt(4.2, 11.8);
if (event) {
var left = event.clientX;
var top = event.clientY;
}
else {
var left = randomInt(radius, $(document).width() - radius);
var top = randomInt(radius, $(document).height() - radius);
}
$("<div />").appendTo("#bubbles")
.css ({
'height': radius,
'left': left,
'margin-top': -radius/2,
'margin-left': -radius/2,
'top': top,
'-webkit-animation-duration': animationDuration + 's',
'width': radius
})
.delay(animationDuration * 1000)
.queue(function() {
$(this).remove();
});
}
function generateBubbles() {
newBubble();
clearInterval(timer);
timer = setInterval(generateBubbles, randomInt(252, 2542));
}
var timer = setInterval(generateBubbles, 500);
$("body").click(function() {
newBubble();
});
});
|
$(function() {
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function newBubble () {
var radius = randomInt(10, 208);
var animationDuration = randomInt(4.2, 9.8);
if (event) {
var left = event.clientX;
var top = event.clientY;
}
else {
var left = randomInt(radius, $(document).width() - radius);
var top = randomInt(radius, $(document).height() - radius);
}
$("<div />").appendTo("#bubbles")
.css ({
'height': radius,
'left': left,
'margin-top': -radius/2,
'margin-left': -radius/2,
'top': top,
'-webkit-animation-duration': animationDuration + 's',
'width': radius
})
.delay(animationDuration * 1000)
.queue(function() {
$(this).remove();
});
}
function generateBubbles() {
newBubble();
clearInterval(timer);
timer = setInterval(generateBubbles, randomInt(252, 2542));
}
var timer = setInterval(generateBubbles, 500);
$("body").click(function() {
newBubble();
});
});
|
Indent promise chain two space
|
import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) =>
{
const SOURCE = '/builders';
const [data, setData] = React.useState([]);
/**
* Fetch data when component is mounted.
* Pass in empty array as second paramater to prevent
* infinite callbacks as component refreshes.
* @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a>
*/
React.useEffect(() => {
fetch(SOURCE)
.then(res => res.json())
.then(json => setData(json))
.catch(setData([]));
}, []);
return (
<div>
{data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)}
</div>
);
}
);
|
import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) =>
{
const SOURCE = '/builders';
const [data, setData] = React.useState([]);
/**
* Fetch data when component is mounted.
* Pass in empty array as second paramater to prevent
* infinite callbacks as component refreshes.
* @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a>
*/
React.useEffect(() => {
fetch(SOURCE)
.then(res => res.json())
.then(json => setData(json))
.catch(setData([]));
}, []);
return (
<div>
{data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)}
</div>
);
}
);
|
Update docblock return type for search against backend
|
<?php
namespace Imbo\MetadataSearch\Interfaces;
/**
* Metadata search backend interface
*
* @author Kristoffer Brabrand <kristoffer@brabrand.net>
*/
interface SearchBackendInterface {
/**
* Set metadata for an image in the metadata search backend
*
* @param string $publicKey Public key the image belongs to
* @param string $imageIdentifier Image identifier
* @param array $metadata Metadata array containing key value pairs
* @return bool
*/
public function set($publicKey, $imageIdentifier, array $metadata);
/**
* Delete metadata for an image in the metadata search backend
*
* @param string $publicKey Public key the image belongs to
* @param string $imageIdentifier Image identifier
* @return bool
*/
public function delete($publicKey, $imageIdentifier);
/**
* Query the backend and return imageIdentifiers for matching images
*
* The following query params must be provided.
*
* page => Page number
* limit => Limit to a number of images pr. page
* from => Unix timestamp to fetch from. Pass null to omit
* to => Unit timestamp to fetch to. Pass null to omit
*
* @param string $publicKey
* @param Imbo\MetadataSearch\Interfaces/DslAstInterface $ast AST to base querying on
* @param array $queryParams
* @return Imbo\MetadataSearch\Model\BackendResponse
*/
public function search($publicKey, DslAstInterface $ast, array $queryParams);
}
|
<?php
namespace Imbo\MetadataSearch\Interfaces;
/**
* Metadata search backend interface
*
* @author Kristoffer Brabrand <kristoffer@brabrand.net>
*/
interface SearchBackendInterface {
/**
* Set metadata for an image in the metadata search backend
*
* @param string $publicKey Public key the image belongs to
* @param string $imageIdentifier Image identifier
* @param array $metadata Metadata array containing key value pairs
* @return bool
*/
public function set($publicKey, $imageIdentifier, array $metadata);
/**
* Delete metadata for an image in the metadata search backend
*
* @param string $publicKey Public key the image belongs to
* @param string $imageIdentifier Image identifier
* @return bool
*/
public function delete($publicKey, $imageIdentifier);
/**
* Query the backend and return imageIdentifiers for matching images
*
* The following query params must be provided.
*
* page => Page number
* limit => Limit to a number of images pr. page
* from => Unix timestamp to fetch from. Pass null to omit
* to => Unit timestamp to fetch to. Pass null to omit
*
* @param string $publicKey
* @param Imbo\MetadataSearch\Interfaces/DslAstInterface $ast AST to base querying on
* @param array $queryParams
* @return string[] Array with imageIdentifiers
*/
public function search($publicKey, DslAstInterface $ast, array $queryParams);
}
|
Update test for Node 0.10
|
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var rollupBabelLibBundler = require('../lib');
describe('rollup-babel-lib-bundler', function() {
it('is a function', function() {
expect(rollupBabelLibBundler).to.be.a('function');
});
it('returns a promise', function(done) {
var promise = rollupBabelLibBundler();
// On Node 0.10, promise is shimmed
if (typeof promise !== 'object') {
expect(promise).to.be.a('Promise');
}
expect(promise).to.eventually.be.rejected.and.notify(done);
});
it('creates new files', function(done) {
var promise = rollupBabelLibBundler({
entry: 'test/sample.js',
});
expect(promise).to.eventually.be.a('array').and.notify(done);
});
});
|
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var rollupBabelLibBundler = require('../lib');
describe('rollup-babel-lib-bundler', function() {
it('is a function', function() {
expect(rollupBabelLibBundler).to.be.a('function');
});
it('returns a promise', function(done) {
var promise = rollupBabelLibBundler();
expect(promise).to.be.a('Promise');
expect(promise).to.eventually.be.rejected.and.notify(done);
});
it('creates new files', function(done) {
var promise = rollupBabelLibBundler({
entry: 'test/sample.js',
});
expect(promise).to.eventually.be.a('array').and.notify(done);
});
});
|
Improve import of spaCy, to prevent cycles
|
import numpy
SPACY_MODELS = {}
VECTORS = {}
def get_spacy(lang, **kwargs):
global SPACY_MODELS
import spacy
if lang not in SPACY_MODELS:
SPACY_MODELS[lang] = spacy.load(lang, **kwargs)
return SPACY_MODELS[lang]
def get_vectors(ops, lang):
global VECTORS
key = (ops.device, lang)
if key not in VECTORS:
nlp = get_spacy(lang)
nV = max(lex.rank for lex in nlp.vocab)+1
nM = nlp.vocab.vectors_length
vectors = numpy.zeros((nV, nM), dtype='float32')
for lex in nlp.vocab:
if lex.has_vector:
vectors[lex.rank] = lex.vector / lex.vector_norm
VECTORS[key] = ops.asarray(vectors)
return VECTORS[key]
|
import numpy
try:
import spacy
except ImportError:
spacy = None
SPACY_MODELS = {}
VECTORS = {}
def get_spacy(lang, **kwargs):
global SPACY_MODELS
if spacy is None:
raise ImportError("Could not import spacy. Is it installed?")
if lang not in SPACY_MODELS:
SPACY_MODELS[lang] = spacy.load(lang, **kwargs)
return SPACY_MODELS[lang]
def get_vectors(ops, lang):
global VECTORS
key = (ops.device, lang)
if key not in VECTORS:
nlp = get_spacy(lang)
nV = max(lex.rank for lex in nlp.vocab)+1
nM = nlp.vocab.vectors_length
vectors = numpy.zeros((nV, nM), dtype='float32')
for lex in nlp.vocab:
if lex.has_vector:
vectors[lex.rank] = lex.vector / lex.vector_norm
VECTORS[key] = ops.asarray(vectors)
return VECTORS[key]
|
Drop mention of what phase of parsing errored.
These are... implementation details that are not at all meaningful to an end-user. And also still quite distinguishable if you really care enough to ask for full stacks by setting the DEBUG var.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us>
|
package def
import (
"bytes"
"github.com/go-yaml/yaml"
"github.com/ugorji/go/codec"
"polydawn.net/repeatr/lib/cereal"
)
var codecBounceHandler = &codec.CborHandle{}
func ParseYaml(ser []byte) *Formula {
// Turn tabs into spaces so that tabs are acceptable inputs.
ser = cereal.Tab2space(ser)
// Bounce the serial form into another temporary intermediate form.
// Yes. Feel the sadness in your soul.
// This lets us feed a byte area to ugorji codec that it understands,
// because it doesn't have any mechanisms to accept in-memory structs.
var raw interface{}
if err := yaml.Unmarshal(ser, &raw); err != nil {
panic(ConfigError.New("Could not parse formula: %s", err))
}
var buf bytes.Buffer
if err := codec.NewEncoder(&buf, codecBounceHandler).Encode(raw); err != nil {
panic(ConfigError.New("Could not parse formula: %s", err))
}
// Actually decode with the smart codecs.
var frm Formula
if err := codec.NewDecoder(&buf, codecBounceHandler).Decode(&frm); err != nil {
panic(ConfigError.New("Could not parse formula: %s", err))
}
return &frm
}
|
package def
import (
"bytes"
"github.com/go-yaml/yaml"
"github.com/ugorji/go/codec"
"polydawn.net/repeatr/lib/cereal"
)
var codecBounceHandler = &codec.CborHandle{}
func ParseYaml(ser []byte) *Formula {
// Turn tabs into spaces so that tabs are acceptable inputs.
ser = cereal.Tab2space(ser)
// Bounce the serial form into another temporary intermediate form.
// Yes. Feel the sadness in your soul.
// This lets us feed a byte area to ugorji codec that it understands,
// because it doesn't have any mechanisms to accept in-memory structs.
var raw interface{}
if err := yaml.Unmarshal(ser, &raw); err != nil {
panic(ConfigError.New("Could not parse formula: %s", err))
}
var buf bytes.Buffer
if err := codec.NewEncoder(&buf, codecBounceHandler).Encode(raw); err != nil {
panic(ConfigError.New("Could not parse formula (stg2): %s", err))
}
// Actually decode with the smart codecs.
var frm Formula
if err := codec.NewDecoder(&buf, codecBounceHandler).Decode(&frm); err != nil {
// one would really hope this is impossible...
panic(ConfigError.New("Could not parse formula (stg3): %s", err))
}
return &frm
}
|
Add BLOCK pipeline definition to the default pipelines
|
/*
* Copyright (c) 2015-2017 Dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.panda_lang.panda.implementation.interpreter.parser.pipeline;
/**
* Used by {@link org.panda_lang.panda.implementation.interpreter.parser.pipeline.registry.ParserRegistration}
*/
public class DefaultPipelines {
/**
* Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.OverallParser}
*/
public static final String OVERALL = "overall";
/**
* Used by {@link org.panda_lang.panda.language.structure.prototype.parser.ClassPrototypeParser}
*/
public static final String PROTOTYPE = "prototype";
/**
* Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.ScopeParser}
*/
public static final String SCOPE = "scope";
/**
* Used by {@link org.panda_lang.panda.language.structure.block.BlockParser}
*/
public static final String BLOCK = "block";
}
|
/*
* Copyright (c) 2015-2017 Dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.panda_lang.panda.implementation.interpreter.parser.pipeline;
/**
* Used by {@link org.panda_lang.panda.implementation.interpreter.parser.pipeline.registry.ParserRegistration}
*/
public class DefaultPipelines {
/**
* Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.OverallParser}
*/
public static final String OVERALL = "overall";
/**
* Used by {@link org.panda_lang.panda.language.structure.prototype.parser.ClassPrototypeParser}
*/
public static final String PROTOTYPE = "prototype";
/**
* Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.ScopeParser}
*/
public static final String SCOPE = "scope";
}
|
Rename config method and make an immutable copy
|
package com.salesforce.storm.spout.sideline;
import com.salesforce.storm.spout.sideline.config.SidelineSpoutConfig;
import com.salesforce.storm.spout.sideline.handler.SidelineSpoutHandler;
import com.salesforce.storm.spout.sideline.handler.SidelineVirtualSpoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* Spout that supports sidelining messages by filters.
*/
public class SidelineSpout extends DynamicSpout {
private static final Logger logger = LoggerFactory.getLogger(SidelineSpout.class);
/**
* Used to overload and modify settings before passing them to the constructor.
* @param config Supplied configuration.
* @return Resulting configuration.
*/
private static Map<String, Object> modifyConfig(Map<String, Object> _config) {
final Map<String, Object> config = Tools.immutableCopy(_config);
config.put(SidelineSpoutConfig.SPOUT_HANDLER_CLASS, SidelineSpoutHandler.class.getName());
config.put(SidelineSpoutConfig.VIRTUAL_SPOUT_HANDLER_CLASS, SidelineVirtualSpoutHandler.class.getName());
return config;
}
/**
* Spout that supports sidelining messages by filters.
* @param config Spout configuration.
*/
public SidelineSpout(Map config) {
super(modifyConfig(config));
}
}
|
package com.salesforce.storm.spout.sideline;
import com.salesforce.storm.spout.sideline.config.SidelineSpoutConfig;
import com.salesforce.storm.spout.sideline.handler.SidelineSpoutHandler;
import com.salesforce.storm.spout.sideline.handler.SidelineVirtualSpoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* Spout instance.
*/
public class SidelineSpout extends DynamicSpout {
private static final Logger logger = LoggerFactory.getLogger(SidelineSpout.class);
/**
* Used to overload and modify settings before passing them to the constructor.
* @param config Supplied configuration.
* @return Resulting configuration.
*/
private static Map getConfig(Map config) {
config.put(SidelineSpoutConfig.SPOUT_HANDLER_CLASS, SidelineSpoutHandler.class.getName());
config.put(SidelineSpoutConfig.VIRTUAL_SPOUT_HANDLER_CLASS, SidelineVirtualSpoutHandler.class.getName());
return config;
}
public SidelineSpout(Map config) {
super(getConfig(config));
}
}
|
Fix up unit tests so they all pass.
|
import logging
class IncludePath(object):
def __init__(self, project_layout, project_services):
self.project_layout = project_layout
self.project_services = project_services
def resolveIncludePaths(self, folder_path):
logger = logging.getLogger('Archie')
logger.debug('List include folders for path %s', folder_path)
paths = []
source_folders = self.project_services.listFolders(folder_path)
for source_folder in source_folders:
tier = self.project_layout.tierForModule(source_folder)
if tier == 0:
logger.debug('Private module %s is included', source_folder)
paths.append(source_folder)
tier = self.project_layout.tierForModule(folder_path)
logger.debug('Folder path %s has tier %d', folder_path, tier)
for t in range(1, tier + 1):
tier_folder =self.project_layout.getIncludeFolder(t)
logger.debug('Tier %d folder %s is included', t, tier_folder)
paths.append(tier_folder)
return paths
|
import logging
class IncludePath(object):
def __init__(self, project_layout, project_services):
self.project_layout = project_layout
self.project_services = project_services
def resolveIncludePaths(self, folder_path):
logger = logging.getLogger('Archie')
logger.debug('List include folders for path %s', folder_path)
paths = []
source_folders = self.project_services.listFolders(folder_path)
for source_folder in source_folders:
tier = self.project_layout.tierForModule(source_folder)
if tier == 0:
logger.debug('Private module %s is included', source_folder)
paths.append(source_folder)
tier = self.project_layout.tierForModule(folder_path)
logger.debug('Folder path %s has tier %d', folder_path, tier)
for t in range(1, tier + 1):
logger.debug('Tier %d folder %s is included', t, source_folder)
paths.append(self.project_layout.getIncludeFolder(t))
return paths
|
Test that DeployOptions sets two options
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for the implementation ``flocker-deploy``.
"""
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
def test_custom_configs(self):
"""Custom config files can be specified."""
options = self.options()
options.parseOptions([b"/path/somefile.json", b"/path/anotherfile.json"])
self.assertEqual(options, {deploy: b"/path/somefile.json", app: b"/path/anotherfile.json"})
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
def test_success(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Unit tests for the implementation ``flocker-deploy``.
"""
from twisted.trial.unittest import TestCase, SynchronousTestCase
from ...testtools import FlockerScriptTestsMixin, StandardOptionsTestsMixin
from ..script import DeployScript, DeployOptions
class FlockerDeployTests(FlockerScriptTestsMixin, TestCase):
"""Tests for ``flocker-deploy``."""
script = DeployScript
options = DeployOptions
command_name = u'flocker-deploy'
class DeployOptionsTests(StandardOptionsTestsMixin, SynchronousTestCase):
"""Tests for :class:`DeployOptions`."""
options = DeployOptions
class FlockerDeployMainTests(SynchronousTestCase):
"""
Tests for ``DeployScript.main``.
"""
def test_deferred_result(self):
"""
``DeployScript.main`` returns ``True`` on success.
"""
script = DeployScript()
self.assertTrue(script.main(reactor=object(), options={}))
|
chore(release): Check that RELEASE_TOKEN is set
[#96495576]
|
import {map} from 'event-stream';
import gulp from 'gulp';
import {addReleaseNotesToTag} from './helpers/github-service';
import {log} from 'gulp-util';
const plugins = require('gulp-load-plugins')();
gulp.task('release-zip', () => {
const tagName = process.env.TRAVIS_TAG;
if (!tagName) {
log('Skipping - because we did not cut a new release');
return;
}
return gulp.src(`release/pui-${tagName}/**/*`, {base: 'release/'})
.pipe(plugins.zip(`pui.zip`))
.pipe(gulp.dest('.'));
});
gulp.task('release-add-release-notes', () => {
const tagName = process.env.TRAVIS_TAG;
if (!tagName) {
log('Skipping - because we did not cut a new release');
return;
}
if (!process.env.RELEASE_TOKEN) {
log('Skipping - please set the RELEASE_TOKEN env var');
return;
}
return gulp.src('LATEST_CHANGES.md')
.pipe(map(async (latestChangesFile, callback) => {
log(`Updating release notes for ${tagName}...`);
try {
await addReleaseNotesToTag(tagName, latestChangesFile.contents.toString());
callback();
}
catch(error) {
console.error(error);
callback(error);
}
}));
});
|
import {map} from 'event-stream';
import gulp from 'gulp';
import {addReleaseNotesToTag} from './helpers/github-service';
import {log} from 'gulp-util';
const plugins = require('gulp-load-plugins')();
gulp.task('release-zip', () => {
const tagName = process.env.TRAVIS_TAG;
if (!tagName) {
log('Skipping - because we did not cut a new release');
return;
}
return gulp.src(`release/pui-${tagName}/**/*`, {base: 'release/'})
.pipe(plugins.zip(`pui.zip`))
.pipe(gulp.dest('.'));
});
gulp.task('release-add-release-notes', () => {
const tagName = process.env.TRAVIS_TAG;
if (!tagName) {
log('Skipping - because we did not cut a new release');
return;
}
return gulp.src('LATEST_CHANGES.md')
.pipe(map(async (latestChangesFile, callback) => {
log('Updating release notes...');
try {
await addReleaseNotesToTag(tagName, latestChangesFile.contents.toString());
callback();
}
catch(error) {
console.error(error);
callback(error);
}
}));
});
|
:new: Add Site info to Config
|
'use strict';
const path = require('path');
const cfenv = require('cfenv');
const env = cfenv.getAppEnv();
env.host = env.url.replace(`:${env.port}`, '');
module.exports = {
contentTypes: {
contentTypesHome: {
path: '/content',
title: 'Content Type ALL Landing Page',
desc: 'This is the content type ALL landing page.',
},
contentTypeDir: path.join(__dirname, '../content-types'),
},
knex: {
dialect: 'pg',
connection: {
host: 'localhost',
user: 'punchcard',
database: 'punchcard',
},
debug: false,
acquireConnectionTimeout: 1000,
},
site: {
name: 'Punchcard CMS',
},
env,
cookies: {
secure: false,
secret: process.env.COOKIE_SECRET || 'babka',
},
};
|
'use strict';
const path = require('path');
const cfenv = require('cfenv');
const env = cfenv.getAppEnv();
env.host = env.url.replace(`:${env.port}`, '');
module.exports = {
contentTypes: {
contentTypesHome: {
path: '/content',
title: 'Content Type ALL Landing Page',
desc: 'This is the content type ALL landing page.',
},
contentTypeDir: path.join(__dirname, '../content-types'),
contentTypeExt: 'yml',
viewsDir: path.join(__dirname, '../views/'),
formTemplateFile: '_content-type-form.html',
},
knex: {
dialect: 'pg',
connection: {
host: 'localhost',
user: 'punchcard',
database: 'punchcard',
},
debug: true,
acquireConnectionTimeout: 1000,
},
env,
cookies: {
secure: false,
secret: process.env.COOKIE_SECRET || 'babka',
},
};
|
Adjust example to correct API.
|
package org.wildfly.swarm.example.docker;
//import lombok.extern.slf4j.Slf4j;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.logging.LoggingFraction;
import org.wildfly.swarm.config.logging.Level;
//@Slf4j
public class SwarmMain {
public static void main(String[] args) throws Exception {
Container container = new Container();
Level logLevel = Level.INFO;
container.fraction(new LoggingFraction()
.formatter("PATTERN", "%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n")
.consoleHandler(logLevel, "PATTERN")
.rootLogger(logLevel, "CONSOLE"));
container.start();
JAXRSArchive jaxrsDeployment = ShrinkWrap.create( JAXRSArchive.class );
jaxrsDeployment.addClass(JaxRsApplication.class);
jaxrsDeployment.addResource(MyResource.class);
container.deploy(jaxrsDeployment);
}
}
|
package org.wildfly.swarm.example.docker;
//import lombok.extern.slf4j.Slf4j;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.logging.LoggingFraction;
//@Slf4j
public class SwarmMain {
public static void main(String[] args) throws Exception {
Container container = new Container();
String logLevel = "INFO";
container.fraction(new LoggingFraction()
.formatter("PATTERN", "%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n")
.consoleHandler(logLevel, "PATTERN")
.rootLogger(logLevel, "CONSOLE"));
container.start();
JAXRSArchive jaxrsDeployment = ShrinkWrap.create( JAXRSArchive.class );
jaxrsDeployment.addClass(JaxRsApplication.class);
jaxrsDeployment.addResource(MyResource.class);
container.deploy(jaxrsDeployment);
}
}
|
Remove jquery cookie from shim config.
|
requirejs.config({
baseUrl: 'assets/js',
paths: {
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
'bootstrap': '//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min',
'underscore': '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min',
'backbone': '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min',
'jquery-cookie': '//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
}
});
requirejs(['main']);
|
requirejs.config({
baseUrl: 'assets/js',
paths: {
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
'bootstrap': '//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min',
'underscore': '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min',
'backbone': '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min',
'jquery-cookie': '//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
},
shim: {
'jquery-cookie': {
deps: ['jquery'],
exports: 'jQuery.fn.cookie'
}
}
});
requirejs(['main']);
|
Use FAIL functions, not CATCH
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'form',
classNameBindings: [ 'isValid:valid:invalid' ],
cancel: 'cancel',
isValid: Ember.computed.alias('formModel.isValid'),
notify: 'notify',
save: 'save',
showButtons: true,
transitionTo: 'transitionTo',
actions: {
cancel: function () {
this.sendAction('cancel');
},
submit: function () {
this.set('formModel.showInputErrors', true);
if (!this.get('isValid')) {
// console.log('[ValidatedFormComponent] Not submitting invalid formModel.');
return false;
}
var self = this;
var deferred = Ember.RSVP.defer();
this.set('errors', false);
this.sendAction('save', deferred);
deferred.promise.fail(function (result) {
// console.log('[ValidatedFormComponent]', result);
if (result.unauthorized) self.sendAction('transitionTo', 'login.screen');
self.set('errors', result.errors || [ 'Oops! There was a problem.' ]);
});
},
notify: function (opts) {
this.sendAction('notify', opts);
}
}
});
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'form',
classNameBindings: [ 'isValid:valid:invalid' ],
cancel: 'cancel',
isValid: Ember.computed.alias('formModel.isValid'),
notify: 'notify',
save: 'save',
showButtons: true,
transitionTo: 'transitionTo',
actions: {
cancel: function () {
this.sendAction('cancel');
},
submit: function () {
this.set('formModel.showInputErrors', true);
if (!this.get('isValid')) {
// console.log('[ValidatedFormComponent] Not submitting invalid formModel.');
return false;
}
var self = this;
var deferred = Ember.RSVP.defer();
this.set('errors', false);
this.sendAction('save', deferred);
deferred.promise.catch(function (result) {
// console.log('[ValidatedFormComponent]', result);
if (result.unauthorized) self.sendAction('transitionTo', 'login.screen');
self.set('errors', result.errors || [ 'Oops! There was a problem.' ]);
});
},
notify: function (opts) {
this.sendAction('notify', opts);
}
}
});
|
Fix group toggle not showing
|
import Polymer from '../polymer';
import hass from '../util/home-assistant-js-instance';
import canToggle from '../util/can-toggle';
require('../components/ha-card');
require('../components/entity/ha-entity-toggle');
require('../state-summary/state-card-content');
const { moreInfoActions } = hass;
export default new Polymer({
is: 'ha-entities-card',
properties: {
states: {
type: Array,
},
groupEntity: {
type: Object,
},
},
computeTitle(states, groupEntity) {
return groupEntity ? groupEntity.entityDisplay :
states[0].domain.replace(/_/g, ' ');
},
entityTapped(ev) {
if (ev.target.classList.contains('paper-toggle-button') ||
ev.target.classList.contains('paper-icon-button')) {
return;
}
ev.stopPropagation();
const entityId = ev.model.item.entityId;
this.async(() => moreInfoActions.selectEntity(entityId), 1);
},
showGroupToggle(groupEntity, states) {
if (!groupEntity || !states || groupEntity.state !== 'on' && groupEntity.state !== 'off') {
return false;
}
// only show if we can toggle 2+ entities in group
return states.reduce((sum, state) => sum + canToggle(state.entityId), 0) > 1;
},
});
|
import Polymer from '../polymer';
import hass from '../util/home-assistant-js-instance';
import canToggle from '../util/can-toggle';
require('../components/ha-card');
require('../components/entity/ha-entity-toggle');
require('../state-summary/state-card-content');
const { moreInfoActions } = hass;
export default new Polymer({
is: 'ha-entities-card',
properties: {
states: {
type: Array,
},
groupEntity: {
type: Object,
},
},
computeTitle(states, groupEntity) {
return groupEntity ? groupEntity.entityDisplay :
states[0].domain.replace(/_/g, ' ');
},
entityTapped(ev) {
if (ev.target.classList.contains('paper-toggle-button') ||
ev.target.classList.contains('paper-icon-button')) {
return;
}
ev.stopPropagation();
const entityId = ev.model.item.entityId;
this.async(() => moreInfoActions.selectEntity(entityId), 1);
},
showGroupToggle(groupEntity, states) {
if (!groupEntity || !states || groupEntity.state !== 'on' && groupEntity.state !== 'off') {
return false;
}
// only show if we can toggle 2+ entities in group
return states.reduce((sum, state) => sum + canToggle(state.entityId)) > 1;
},
});
|
Use t.Errorf instead of t.Error(fmt.Sprintf
|
package geocoder
import (
"testing"
)
const (
city = "Seattle"
state = "WA"
postalCode = "98104"
seattleLat = 47.603561
seattleLng = -122.329437
)
func TestGeocode(t *testing.T) {
query := "Seattle WA"
lat, lng := Geocode(query)
if lat != seattleLat || lng != seattleLng {
t.Errorf("Expected %f, %f ~ Received %f, %f", seattleLat, seattleLng, lat, lng)
}
}
func TestReverseGeoCode(t *testing.T) {
address := ReverseGeocode(seattleLat, seattleLng)
if address.City != city || address.State != state || address.PostalCode != postalCode {
t.Errorf("Expected %s %s %s ~ Received %s %s %s",
city, state, postalCode, address.City, address.State, address.PostalCode)
}
}
|
package geocoder
import (
"fmt"
"testing"
)
const (
city = "Seattle"
state = "WA"
postalCode = "98104"
seattleLat = 47.603561
seattleLng = -122.329437
)
func TestGeocode(t *testing.T) {
query := "Seattle WA"
lat, lng := Geocode(query)
if lat != seattleLat || lng != seattleLng {
t.Error(fmt.Sprintf("Expected %f, %f ~ Received %f, %f", seattleLat, seattleLng, lat, lng))
}
}
func TestReverseGeoCode(t *testing.T) {
address := ReverseGeocode(seattleLat, seattleLng)
if address.City != city || address.State != state || address.PostalCode != postalCode {
t.Error(fmt.Sprintf("Expected %s %s %s ~ Received %s %s %s",
city, state, postalCode, address.City, address.State, address.PostalCode))
}
}
|
Add logging before storing to datastore.
|
package org.jboss.pnc.core.builder;
import org.jboss.logging.Logger;
import org.jboss.pnc.model.ProjectBuildResult;
import org.jboss.pnc.spi.builddriver.BuildJobConfiguration;
import org.jboss.pnc.spi.builddriver.BuildJobDetails;
import org.jboss.pnc.spi.datastore.Datastore;
import javax.inject.Inject;
/**
* Created by <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> on 2014-12-15.
*/
public class DatastoreAdapter {
private Datastore datastore;
private static final Logger log = Logger.getLogger(DatastoreAdapter.class);
@Inject
public DatastoreAdapter(Datastore datastore) {
this.datastore = datastore;
}
public void storeResult(BuildJobDetails buildDetails, BuildJobConfiguration buildJobConfiguration) {
ProjectBuildResult buildResult = new ProjectBuildResult();
buildResult.setBuildLog(buildDetails.getBuildLog());
buildResult.setStatus(buildDetails.getBuildStatus());
buildResult.setProjectBuildConfiguration(buildJobConfiguration.getProjectBuildConfiguration());
log.tracef("Storing results of %s to datastore.", buildDetails.getJobName());
datastore.storeCompletedBuild(buildResult);
}
}
|
package org.jboss.pnc.core.builder;
import org.jboss.pnc.model.ProjectBuildResult;
import org.jboss.pnc.spi.builddriver.BuildJobConfiguration;
import org.jboss.pnc.spi.builddriver.BuildJobDetails;
import org.jboss.pnc.spi.datastore.Datastore;
import javax.inject.Inject;
/**
* Created by <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> on 2014-12-15.
*/
public class DatastoreAdapter {
private Datastore datastore;
@Inject
public DatastoreAdapter(Datastore datastore) {
this.datastore = datastore;
}
public void storeResult(BuildJobDetails buildDetails, BuildJobConfiguration buildJobConfiguration) {
ProjectBuildResult buildResult = new ProjectBuildResult();
buildResult.setBuildLog(buildDetails.getBuildLog());
buildResult.setStatus(buildDetails.getBuildStatus());
buildResult.setProjectBuildConfiguration(buildJobConfiguration.getProjectBuildConfiguration());
datastore.storeCompletedBuild(buildResult);
}
}
|
Remove dependency on Alias definitions
|
<?php
namespace Rap2hpoutre\LaravelLogViewer;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
class LogViewerController extends Controller
{
public function index()
{
if (Input::get('l')) {
LaravelLogViewer::setFile(base64_decode(Input::get('l')));
}
if (Input::get('dl')) {
return Response::download(storage_path() . '/logs/' . base64_decode(Input::get('dl')));
} elseif (Input::has('del')) {
File::delete(storage_path() . '/logs/' . base64_decode(Input::get('del')));
return Redirect::to(Request::url());
}
$logs = LaravelLogViewer::all();
return View::make('laravel-log-viewer::log', [
'logs' => $logs,
'files' => LaravelLogViewer::getFiles(true),
'current_file' => LaravelLogViewer::getFileName()
]);
}
}
|
<?php
namespace Rap2hpoutre\LaravelLogViewer;
use Illuminate\Support\Facades\View;
class LogViewerController extends \Illuminate\Routing\Controller
{
public function index()
{
if (\Input::get('l')) {
LaravelLogViewer::setFile(base64_decode(\Input::get('l')));
}
if (\Input::get('dl')) {
return \Response::download(storage_path() . '/logs/' . base64_decode(\Input::get('dl')));
} elseif (\Input::has('del')) {
\File::delete(storage_path() . '/logs/' . base64_decode(\Input::get('del')));
return \Redirect::to(\Request::url());
}
$logs = LaravelLogViewer::all();
return View::make('laravel-log-viewer::log', [
'logs' => $logs,
'files' => LaravelLogViewer::getFiles(true),
'current_file' => LaravelLogViewer::getFileName()
]);
}
}
|
Change comment about Exceptions in execute
|
package ru.nixan.android.requestloaders;
import android.content.Context;
/**
* Created by nixan on 11/26/13.
*/
public interface IRequest {
/**
* Executes the request.
*/
public void execute(Context context);
/**
* Cancel the executing request
*/
public void cancel();
/**
* @return if the instance of this request class have already been executed
*/
public boolean wasExecuted();
/**
* Set the result of the request
*/
public void setException(Exception exception);
/**
* @return the exception that occured during excecution.
*/
public Exception getException();
/**
* @return if the request was succesfull
*/
public boolean isSuccesfull();
}
|
package ru.nixan.android.requestloaders;
import android.content.Context;
/**
* Created by nixan on 11/26/13.
*/
public interface IRequest {
/**
* Executes the request. In case of any error in implemented protocol or actual implementation
* of network stack please throw an exception.
*/
public void execute(Context context);
/**
* Cancel the executing request
*/
public void cancel();
/**
* @return if the instance of this request class have already been executed
*/
public boolean wasExecuted();
/**
* Set the result of the request
*/
public void setException(Exception exception);
/**
* @return the exception that occured during excecution.
*/
public Exception getException();
/**
* @return if the request was succesfull
*/
public boolean isSuccesfull();
}
|
DOC: Document the reason msvc requires SSE2 on 32 bit platforms.
|
import os
import distutils.msvccompiler
from distutils.msvccompiler import *
from .system_info import platform_bits
class MSVCCompiler(distutils.msvccompiler.MSVCCompiler):
def __init__(self, verbose=0, dry_run=0, force=0):
distutils.msvccompiler.MSVCCompiler.__init__(self, verbose, dry_run, force)
def initialize(self, plat_name=None):
environ_lib = os.getenv('lib')
environ_include = os.getenv('include')
distutils.msvccompiler.MSVCCompiler.initialize(self, plat_name)
if environ_lib is not None:
os.environ['lib'] = environ_lib + os.environ['lib']
if environ_include is not None:
os.environ['include'] = environ_include + os.environ['include']
if platform_bits == 32:
# msvc9 building for 32 bits requires SSE2 to work around a
# compiler bug.
self.compile_options += ['/arch:SSE2']
self.compile_options_debug += ['/arch:SSE2']
|
import os
import distutils.msvccompiler
from distutils.msvccompiler import *
from .system_info import platform_bits
class MSVCCompiler(distutils.msvccompiler.MSVCCompiler):
def __init__(self, verbose=0, dry_run=0, force=0):
distutils.msvccompiler.MSVCCompiler.__init__(self, verbose, dry_run, force)
def initialize(self, plat_name=None):
environ_lib = os.getenv('lib')
environ_include = os.getenv('include')
distutils.msvccompiler.MSVCCompiler.initialize(self, plat_name)
if environ_lib is not None:
os.environ['lib'] = environ_lib + os.environ['lib']
if environ_include is not None:
os.environ['include'] = environ_include + os.environ['include']
if platform_bits == 32:
self.compile_options += ['/arch:SSE2']
self.compile_options_debug += ['/arch:SSE2']
|
Allow replaceItems to be edited with options
Currently cannot change the default replaceItems setting
|
export default function makeDefaultState (servicePath, options) {
const { idField, autoRemove, paginate, enableEvents, preferUpdate, replaceItems } = options
const state = {
ids: [],
keyedById: {},
copiesById: {},
currentId: null,
copy: null,
idField,
servicePath,
autoRemove,
enableEvents,
preferUpdate,
replaceItems,
isFindPending: false,
isGetPending: false,
isCreatePending: false,
isUpdatePending: false,
isPatchPending: false,
isRemovePending: false,
errorOnFind: null,
errorOnGet: null,
errorOnCreate: null,
errorOnUpdate: null,
errorOnPatch: null,
errorOnRemove: null
}
if (paginate) {
state.pagination = {}
}
return state
}
|
export default function makeDefaultState (servicePath, options) {
const { idField, autoRemove, paginate, enableEvents, preferUpdate } = options
const state = {
ids: [],
keyedById: {},
copiesById: {},
currentId: null,
copy: null,
idField,
servicePath,
autoRemove,
enableEvents,
preferUpdate,
replaceItems: false,
isFindPending: false,
isGetPending: false,
isCreatePending: false,
isUpdatePending: false,
isPatchPending: false,
isRemovePending: false,
errorOnFind: null,
errorOnGet: null,
errorOnCreate: null,
errorOnUpdate: null,
errorOnPatch: null,
errorOnRemove: null
}
if (paginate) {
state.pagination = {}
}
return state
}
|
:bug: Fix a presence check of Symbol function
|
import padStart from './polyfill/padStart';
const THREE_MINUTES = 3 * 60 * 1000;
const privateDateProperty = typeof Symbol === 'function' ?
Symbol('privateDateProperty') : '_privateDateProperty';
function computeEorzeaDate(date) {
const eorzeaTime = new Date();
const unixTime = Math.floor(date.getTime() * 1440 / 70 - THREE_MINUTES);
eorzeaTime.setTime(unixTime);
return eorzeaTime;
}
export default class EorzeaTime {
constructor(date = new Date()) {
this[privateDateProperty] = computeEorzeaDate(date);
}
getHours() {
return this[privateDateProperty].getUTCHours();
}
getMinutes() {
return this[privateDateProperty].getUTCMinutes();
}
getSeconds() {
return this[privateDateProperty].getUTCSeconds();
}
toString() {
return [
padStart.call(this.getHours(), 2, 0),
padStart.call(this.getMinutes(), 2, 0),
padStart.call(this.getSeconds(), 2, 0)
].join(':');
}
toJSON() {
return toString();
}
}
|
import padStart from './polyfill/padStart';
const THREE_MINUTES = 3 * 60 * 1000;
const privateDateProperty = typeof Symbol !== 'function' ?
Symbol('privateDateProperty') : '_privateDateProperty';
function computeEorzeaDate(date) {
const eorzeaTime = new Date();
const unixTime = Math.floor(date.getTime() * 1440 / 70 - THREE_MINUTES);
eorzeaTime.setTime(unixTime);
return eorzeaTime;
}
export default class EorzeaTime {
constructor(date = new Date()) {
this[privateDateProperty] = computeEorzeaDate(date);
}
getHours() {
return this[privateDateProperty].getUTCHours();
}
getMinutes() {
return this[privateDateProperty].getUTCMinutes();
}
getSeconds() {
return this[privateDateProperty].getUTCSeconds();
}
toString() {
return [
padStart.call(this.getHours(), 2, 0),
padStart.call(this.getMinutes(), 2, 0),
padStart.call(this.getSeconds(), 2, 0)
].join(':');
}
toJSON() {
return toString();
}
}
|
Add custom launcher for karma
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
singleRun: false
});
};
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
|
Fix description in help text
|
package commands
import (
"fmt"
"github.com/codegangsta/cli"
"github.com/brooklyncentral/brooklyn-cli/api/application"
"github.com/brooklyncentral/brooklyn-cli/command_metadata"
"github.com/brooklyncentral/brooklyn-cli/net"
"github.com/brooklyncentral/brooklyn-cli/scope"
)
type Deploy struct {
network *net.Network
}
func NewDeploy(network *net.Network) (cmd *Deploy) {
cmd = new(Deploy)
cmd.network = network
return
}
func (cmd *Deploy) Metadata() command_metadata.CommandMetadata {
return command_metadata.CommandMetadata{
Name: "deploy",
Description: "Deploy a new brooklyn application from the supplied YAML",
Usage: "BROOKLYN_NAME [ SCOPE ] deploy FILEPATH",
Flags: []cli.Flag{},
}
}
func (cmd *Deploy) Run(scope scope.Scope, c *cli.Context) {
create := application.Create(cmd.network, c.Args().First())
fmt.Println(create)
}
|
package commands
import (
"fmt"
"github.com/codegangsta/cli"
"github.com/brooklyncentral/brooklyn-cli/api/application"
"github.com/brooklyncentral/brooklyn-cli/command_metadata"
"github.com/brooklyncentral/brooklyn-cli/net"
"github.com/brooklyncentral/brooklyn-cli/scope"
)
type Deploy struct {
network *net.Network
}
func NewDeploy(network *net.Network) (cmd *Deploy) {
cmd = new(Deploy)
cmd.network = network
return
}
func (cmd *Deploy) Metadata() command_metadata.CommandMetadata {
return command_metadata.CommandMetadata{
Name: "deploy",
Description: "Create a new brooklyn application from the supplied YAML",
Usage: "BROOKLYN_NAME [ SCOPE ] deploy FILEPATH",
Flags: []cli.Flag{},
}
}
func (cmd *Deploy) Run(scope scope.Scope, c *cli.Context) {
create := application.Create(cmd.network, c.Args().First())
fmt.Println(create)
}
|
Scale app to fit screen
|
package com.example.nickj.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.content.res.AssetManager;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
AssetManager am = getApplicationContext().getAssets();
String indexHTML = "<html><body>If you're seeing this you need an index.html</body></html>";
try {
InputStream is = am.open("index.html");
indexHTML = IOUtils.toString(is, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
webView.loadDataWithBaseURL("file:///android_asset/", indexHTML, "text/html", "UTF-8", null);
setContentView(webView);
}
}
|
package com.example.nickj.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.content.res.AssetManager;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
AssetManager am = getApplicationContext().getAssets();
String indexHTML = "<html><body>If you're seeing this you need an index.html</body></html>";
try {
InputStream is = am.open("index.html");
indexHTML = IOUtils.toString(is, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
webView.loadDataWithBaseURL("file:///android_asset/", indexHTML, "text/html", "UTF-8", null);
setContentView(webView);
}
}
|
Fix full reload on specific message.
|
const serverRouter = require('server-router')
const browserify = require('browserify')
const bankai = require('bankai')
const http = require('http')
const PORT = 8080
const server = http.createServer(createRouter())
server.listen(PORT, () => process.stdout.write(`listening on port ${PORT}\n`))
function createRouter () {
const router = serverRouter('/404')
const js = bankai.js(browserify, require.resolve('./client.js'))
router.on('/bundle.js', (req, res) => js(req, res).pipe(res))
router.on('/:inbox/bundle.js', (req, res) => js(req, res).pipe(res))
const html = bankai.html({ css: false })
router.on('/', (req, res) => html(req, res).pipe(res))
router.on('/:inbox', (req, res) => html(req, res).pipe(res))
router.on('/:inbox/:message_id', (req, res) => html(req, res).pipe(res))
router.on('/hi', (req, res) => res.end('{ "message": "hi back!" }'))
router.on('/404', (req, res) => {
res.statusCode = 404
res.end('{ "message": "the server is confused" }')
})
return router
}
|
const serverRouter = require('server-router')
const browserify = require('browserify')
const bankai = require('bankai')
const http = require('http')
const PORT = 8080
const server = http.createServer(createRouter())
server.listen(PORT, () => process.stdout.write(`listening on port ${PORT}\n`))
function createRouter () {
const router = serverRouter('/404')
const html = bankai.html({ css: false })
router.on('/', (req, res) => html(req, res).pipe(res))
router.on('/:inbox', (req, res) => html(req, res).pipe(res))
router.on('/:inbox/:message_id', (req, res) => html(req, res).pipe(res))
const js = bankai.js(browserify, require.resolve('./client.js'))
router.on('/bundle.js', (req, res) => js(req, res).pipe(res))
router.on('/hi', (req, res) => res.end('{ "message": "hi back!" }'))
router.on('/404', (req, res) => {
res.statusCode = 404
res.end('{ "message": "the server is confused" }')
})
return router
}
|
Delete the jobs in tearDown() in tests
|
#!/usr/bin/env python
import sys
import os
import unittest
from subprocess import Popen, PIPE
ROOT_DIR = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(ROOT_DIR)
from supercron import SuperCron
class RunTests(unittest.TestCase):
"""class that tests supercron for behavior correctness"""
def setUp(self):
pass
def tearDown(self):
SuperCron.delete_job("ls")
def get_crontab(self):
p = Popen(["crontab", "-l"], stdout=PIPE, stderr=PIPE)
crontab_out, crontab_err = p.communicate()
return crontab_out
def test_midnight(self):
entry1 = b"@daily ls # ls"
entry2 = b"0 0 * * * ls # ls"
SuperCron.add_job("ls", "ls", "midnight")
user_crontab = self.get_crontab()
self.assertTrue(entry1 in user_crontab or entry2 in user_crontab)
def test_every_x_minutes(self):
hour, minute = SuperCron.get_time_now()
entry = b"*/5 {} * * * ls # ls".format(hour)
SuperCron.add_job("ls", "ls", "once every 5 minutes")
user_crontab = self.get_crontab()
self.assertTrue(entry in user_crontab)
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env python
import sys
import os
import unittest
from subprocess import Popen, PIPE
ROOT_DIR = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(ROOT_DIR)
from supercron import SuperCron
class RunTests(unittest.TestCase):
"""class that tests supercron for behavior correctness"""
def setUp(self):
pass
def get_crontab(self):
p = Popen(["crontab", "-l"], stdout=PIPE)
crontab_out, crontab_err = p.communicate()
return crontab_out
def test_midnight(self):
entry1 = b"@daily ls # ls"
entry2 = b"0 0 * * * ls # ls"
SuperCron.add_job("ls", "ls", "midnight")
user_crontab = self.get_crontab()
self.assertTrue(entry1 in user_crontab or entry2 in user_crontab)
def test_every_x_minutes(self):
hour, minute = SuperCron.get_time_now()
entry = b"*/5 {} * * * ls # ls".format(hour)
SuperCron.add_job("ls", "ls", "once every 5 minutes")
user_crontab = self.get_crontab()
self.assertTrue(entry in user_crontab)
if __name__ == "__main__":
unittest.main()
|
Fix bug on unterminated multi-line comment
|
<?php
// Doctrine (db)
$app['db.options'] = array(
'driver' => 'pdo_pgsql',
'charset' => 'utf8',
'host' => 'ec2-54-83-57-86.compute-1.amazonaws.com',
'port' => '5432',
'dbname' => 'd70b123ck17v74',
'user' => 'yasrxhlztiwpnq',
'password' => 'YT5kh8cYoPq4e9Xa2i2cWWz7rs',
);
// define log level
$app['monolog.level'] = 'WARNING';
//A ENLEVER
// enable the debug mode
//$app['debug'] = true;
// define log level
//$app['monolog.level'] = 'INFO';
|
<?php
// Doctrine (db)
$app['db.options'] = array(
'driver' => 'pdo_pgsql',
'charset' => 'utf8',
'host' => 'ec2-54-83-57-86.compute-1.amazonaws.com',
'port' => '5432',
'dbname' => 'd70b123ck17v74',
'user' => 'yasrxhlztiwpnq',
'password' => 'YT5kh8cYoPq4e9Xa2i2cWWz7rs',
);
// define log level
$app['monolog.level'] = 'WARNING';
//A ENLEVER
// enable the debug mode
/*$app['debug'] = true;
// define log level
$app['monolog.level'] = 'INFO';
|
Disable New Relic's apdex metric on non-fetch_snippets views.
New Relic doesn't allow us to set different thresholds for different
pages across the site, so in order to get valuable metrics on the main
view for snippets, fetch_snippets, we need to disable apdex for the
admin interface and public snippets views, which don't need as close
monitoring.
|
from django.core.urlresolvers import resolve
from snippets.base.views import fetch_snippets
class FetchSnippetsMiddleware(object):
"""
If the incoming request is for the fetch_snippets view, execute the view
and return it before other middleware can run.
fetch_snippets is a very very basic view that doesn't need any of the
middleware that the rest of the site needs, such as the session or csrf
middlewares. To avoid unintended issues (such as headers we don't want
being added to the response) this middleware detects requests to that view
and executes the view early, bypassing the rest of the middleware.
Also disables New Relic's apdex for views that aren't the
fetch_snippets, as we only really care about the apdex for
fetch_snippets.
"""
def process_request(self, request):
result = resolve(request.path)
if result.func == fetch_snippets:
return fetch_snippets(request, *result.args, **result.kwargs)
else:
# Not fetch_snippets? Then no New Relic for you!
try:
import newrelic.agent
except ImportError:
pass
else:
newrelic.agent.suppress_apdex_metric()
|
from django.core.urlresolvers import resolve
from snippets.base.views import fetch_snippets
class FetchSnippetsMiddleware(object):
"""
If the incoming request is for the fetch_snippets view, execute the view
and return it before other middleware can run.
fetch_snippets is a very very basic view that doesn't need any of the
middleware that the rest of the site needs, such as the session or csrf
middlewares. To avoid unintended issues (such as headers we don't want
being added to the response) this middleware detects requests to that view
and executes the view early, bypassing the rest of the middleware.
"""
def process_request(self, request):
result = resolve(request.path)
if result.func == fetch_snippets:
return fetch_snippets(request, *result.args, **result.kwargs)
|
Add ability to "fix" texture
|
import {
RepeatWrapping,
UVMapping,
NearestFilter,
LinearMipMapLinearFilter,
TextureLoader,
Vector2
} from 'three';
const loader = new TextureLoader();
export class TextureModule {
static load(url) {
return new TextureModule({url}).texture;
}
textures = [];
constructor(...textures) {
textures.forEach(({
url,
type = 'map',
offset = new Vector2(0, 0),
repeat = new Vector2(1, 1),
wrap = RepeatWrapping,
mapping = UVMapping,
fix = tex => tex
}) => {
const texture = loader.load(url);
if (wrap.length > 0) {
texture.wrapS = wrap[0];
texture.wrapT = wrap[1];
} else
texture.wrapS = texture.wrapT = wrap;
texture.mapping = mapping;
texture.offset.copy(offset);
texture.repeat.copy(repeat);
texture.magFilter = NearestFilter;
texture.minFilter = LinearMipMapLinearFilter;
this.textures.push([type, fix(texture)]);
});
}
bridge = {
material(material, self) {
self.textures.forEach(texture => {
material[texture[0]] = texture[1];
});
return material;
}
}
}
|
import {
RepeatWrapping,
UVMapping,
NearestFilter,
LinearMipMapLinearFilter,
TextureLoader,
Vector2
} from 'three';
const loader = new TextureLoader();
export class TextureModule {
static load(url) {
return new TextureModule({url}).texture;
}
textures = [];
constructor(...textures) {
textures.forEach(({
url,
type = 'map',
offset = new Vector2(0, 0),
repeat = new Vector2(1, 1),
wrap = RepeatWrapping,
mapping = UVMapping
}) => {
const texture = loader.load(url);
if (wrap.length > 0) {
texture.wrapS = wrap[0];
texture.wrapT = wrap[1];
} else
texture.wrapS = texture.wrapT = wrap;
texture.mapping = mapping;
texture.offset.copy(offset);
texture.repeat.copy(repeat);
texture.magFilter = NearestFilter;
texture.minFilter = LinearMipMapLinearFilter;
this.textures.push([type, texture]);
});
}
bridge = {
material(material, self) {
self.textures.forEach(texture => {
material[texture[0]] = texture[1];
});
return material;
}
}
}
|
Exclude node_modules from vue loader
|
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist'
},
module: {
loaders: [
{
exclude: [/(node_modules)/],
test: /\.vue$/,
loader: 'vue-loader',
options: {
extractCss: true,
loaders: {
js: 'babel-loader'
}
}
}
]
},
plugins: [
new ExtractTextPlugin("style.css")
],
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
};
|
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist'
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
extractCss: true,
loaders: {
js: 'babel-loader'
}
}
}
]
},
plugins: [
new ExtractTextPlugin("style.css")
],
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
};
|
Add boto to list of installation dependencies
|
import os
from setuptools import setup
INSTALL_REQUIRES = ['python_cjson', 'requests >=1.0.3', 'boto >=2.20.1']
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "qds_sdk",
version = "1.0.9_beta",
author = "Qubole",
author_email = "dev@qubole.com",
description = ("Python SDK for coding to the Qubole Data Service API"),
keywords = "qubole sdk api",
url = "http://packages.python.org/qds_sdk",
packages=['qds_sdk'],
scripts=['bin/qds.py'],
install_requires=INSTALL_REQUIRES,
long_description="[Please visit the project page at https://github.com/qubole/qds-sdk-py]\n\n" + read('README')
)
|
import os
from setuptools import setup
INSTALL_REQUIRES = ['python_cjson', 'requests >=1.0.3']
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "qds_sdk",
version = "1.0.9_beta",
author = "Qubole",
author_email = "dev@qubole.com",
description = ("Python SDK for coding to the Qubole Data Service API"),
keywords = "qubole sdk api",
url = "http://packages.python.org/qds_sdk",
packages=['qds_sdk'],
scripts=['bin/qds.py'],
install_requires=INSTALL_REQUIRES,
long_description="[Please visit the project page at https://github.com/qubole/qds-sdk-py]\n\n" + read('README')
)
|
Remove not needed test from PageWrapper
|
import { shallow } from 'enzyme';
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import PageWrapper from './PageWrapper';
describe('pages/PageWrapper', () => {
const defaultProps = {
className: 'test-page',
title: 'Test title',
};
function getWrapper(extraProps) {
return shallow(
<PageWrapper {...defaultProps} {...extraProps}>
<h1>Rendered content</h1>
</PageWrapper>
);
}
test('renders Helmet title', () => {
const title = getWrapper().find('title');
expect(title.text()).toBe('Test title - Varaamo');
});
test('renders a div with the className given in props', () => {
const div = getWrapper().find(`.${defaultProps.className}`);
expect(div.length).toBe(1);
});
test('renders the page content', () => {
const content = getWrapper().find('h1');
expect(content).toHaveLength(1);
expect(content.text()).toBe('Rendered content');
});
test('renders a normal Grid', () => {
const gridWrapper = getWrapper().find(Grid);
expect(gridWrapper).toHaveLength(1);
});
});
|
import { shallow } from 'enzyme';
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import PageWrapper from './PageWrapper';
describe('pages/PageWrapper', () => {
const defaultProps = {
className: 'test-page',
title: 'Test title',
};
function getWrapper(extraProps) {
return shallow(
<PageWrapper {...defaultProps} {...extraProps}>
<h1>Rendered content</h1>
</PageWrapper>
);
}
test('renders Helmet title', () => {
const title = getWrapper().find('title');
expect(title.text()).toBe('Test title - Varaamo');
});
test('renders a div with the className given in props', () => {
const div = getWrapper().find(`.${defaultProps.className}`);
expect(div.length).toBe(1);
});
test('renders the page content', () => {
const content = getWrapper().find('h1');
expect(content).toHaveLength(1);
expect(content.text()).toBe('Rendered content');
});
test('renders a normal Grid', () => {
const gridWrapper = getWrapper().find(Grid);
expect(gridWrapper).toHaveLength(1);
});
test('renders a fluid Grid if fluid prop', () => {
const gridWrapper = getWrapper({ fluid: true }).find(Grid);
expect(gridWrapper).toHaveLength(1);
});
});
|
Fix a hard-coded version number
|
from distutils.core import setup # setuptools breaks
# Dynamically calculate the version based on knowledge.VERSION
version_tuple = __import__('rest_hooks').VERSION
version = '.'.join([str(v) for v in version_tuple])
setup(
name = 'django-rest-hooks',
description = 'A powerful mechanism for sending real time API notifications via a new subscription model.',
version = version,
author = 'Bryan Helmig',
author_email = 'bryan@zapier.com',
url = 'http://github.com/zapier/django-rest-hooks',
install_requires=['Django>=1.4','requests'],
packages=['rest_hooks'],
package_data={
'rest_hooks': [
'migrations/*.py'
]
},
classifiers = ['Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'],
)
|
from distutils.core import setup # setuptools breaks
# Dynamically calculate the version based on knowledge.VERSION
version_tuple = __import__('rest_hooks').VERSION
version = '1.0.4' #'.'.join([str(v) for v in version_tuple])
setup(
name = 'django-rest-hooks',
description = 'A powerful mechanism for sending real time API notifications via a new subscription model.',
version = version,
author = 'Bryan Helmig',
author_email = 'bryan@zapier.com',
url = 'http://github.com/zapier/django-rest-hooks',
install_requires=['Django>=1.4','requests'],
packages=['rest_hooks'],
package_data={
'rest_hooks': [
'migrations/*.py'
]
},
classifiers = ['Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'],
)
|
Set the content group weight to 90
|
<?php namespace Modules\Menu\Composers;
use Illuminate\Contracts\View\View;
use Maatwebsite\Sidebar\SidebarGroup;
use Maatwebsite\Sidebar\SidebarItem;
use Modules\Core\Composers\BaseSidebarViewComposer;
class SidebarViewComposer extends BaseSidebarViewComposer
{
public function compose(View $view)
{
$view->sidebar->group(trans('core::sidebar.content'), function (SidebarGroup $group) {
$group->weight = 90;
$group->addItem(trans('menu::menu.title'), function (SidebarItem $item) {
$item->weight = 3;
$item->icon = 'fa fa-bars';
$item->route('admin.menu.menu.index');
$item->authorize(
$this->auth->hasAccess('menu.menus.index')
);
});
});
}
}
|
<?php namespace Modules\Menu\Composers;
use Illuminate\Contracts\View\View;
use Maatwebsite\Sidebar\SidebarGroup;
use Maatwebsite\Sidebar\SidebarItem;
use Modules\Core\Composers\BaseSidebarViewComposer;
class SidebarViewComposer extends BaseSidebarViewComposer
{
public function compose(View $view)
{
$view->sidebar->group(trans('core::sidebar.content'), function (SidebarGroup $group) {
$group->addItem(trans('menu::menu.title'), function (SidebarItem $item) {
$item->weight = 3;
$item->icon = 'fa fa-bars';
$item->route('admin.menu.menu.index');
$item->authorize(
$this->auth->hasAccess('menu.menus.index')
);
});
});
}
}
|
Use regex to test date condition instead
|
#!/usr/bin/env node
"use strict";
const moment = require("moment");
const sugar = require("sugar");
const chalk = require("chalk");
const exec = require("child_process").exec;
// Throw a fatal error
const fatal = err => {
console.error(`fatal: ${err}`);
}
process.argv.splice(0, 2);
if (process.argv.length === 0) {
fatal("No date string given");
} else {
// Attempt to parse the date
let date = process.argv.join(" ");
let parsedDate = new sugar.Date.create(date);
console.log(parsedDate);
if (/Invalid Date/.test(parsedDate)) {
fatal("Could not parse \"" + date + "\" into a valid date");
} else {
// Date could be parsed, parse the date to git date format
let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ");
// Actually modify the dates
let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit";
exec(command, (err, stdout, stderr) => {
if (err) {
fatal("Could not change the previous commit");
} else {
console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n");
}
});
}
}
|
#!/usr/bin/env node
"use strict";
const moment = require("moment");
const sugar = require("sugar");
const chalk = require("chalk");
const exec = require("child_process").exec;
// Throw a fatal error
const fatal = err => {
console.error(`fatal: ${err}`);
}
process.argv.splice(0, 2);
if (process.argv.length > 0) {
// Attempt to parse the date
let date = process.argv.join(" ");
let parsedDate = new sugar.Date.create(date);
if (parsedDate != "Invalid Date") {
// Date could be parsed, parse the date to git date format
let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ");
// Actually modify the dates
let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit";
exec(command, (err, stdout, stderr) => {
if (err) {
fatal("Could not change the previous commit");
} else {
console.log("\nModified previous commit:\n AUTHOR_DATE " + chalk.grey(dateString) + "\n COMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n " + chalk.bgWhite.black(command) + "\n");
}
});
} else {
fatal("Could not parse \"" + date + "\" into a valid date");
}
} else {
fatal("No date string given");
}
|
Update required DB version to v43
|
package com.faforever.api.db;
import com.faforever.api.config.ApplicationProfile;
import org.springframework.context.annotation.Profile;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import javax.annotation.PostConstruct;
import java.util.Objects;
@Component
@Profile(ApplicationProfile.PRODUCTION)
public class SchemaVersionVerifier implements PriorityOrdered {
private static final String DB_COMPATIBILITY_VERSION = "43";
private final SchemaVersionRepository schemaVersionRepository;
public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository) {
this.schemaVersionRepository = schemaVersionRepository;
}
@PostConstruct
public void postConstruct() {
String maxVersion = schemaVersionRepository.findMaxVersion()
.orElseThrow(() -> new IllegalStateException("No database version is available"));
Assert.state(Objects.equals(DB_COMPATIBILITY_VERSION, maxVersion),
String.format("Database version is '%s' but this software requires '%s'", maxVersion, DB_COMPATIBILITY_VERSION));
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
|
package com.faforever.api.db;
import com.faforever.api.config.ApplicationProfile;
import org.springframework.context.annotation.Profile;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import javax.annotation.PostConstruct;
import java.util.Objects;
@Component
@Profile(ApplicationProfile.PRODUCTION)
public class SchemaVersionVerifier implements PriorityOrdered {
private static final String DB_COMPATIBILITY_VERSION = "35";
private final SchemaVersionRepository schemaVersionRepository;
public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository) {
this.schemaVersionRepository = schemaVersionRepository;
}
@PostConstruct
public void postConstruct() {
String maxVersion = schemaVersionRepository.findMaxVersion()
.orElseThrow(() -> new IllegalStateException("No database version is available"));
Assert.state(Objects.equals(DB_COMPATIBILITY_VERSION, maxVersion),
String.format("Database version is '%s' but this software requires '%s'", maxVersion, DB_COMPATIBILITY_VERSION));
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
|
Fix CLOUDSTACK-2520: Invoke parent constructor to set result state to
default true to avoid attachVolume error.
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cloudstack.storage.command;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.to.DiskTO;
public class AttachAnswer extends Answer {
private DiskTO disk;
public AttachAnswer() {
super(null);
}
public AttachAnswer(DiskTO disk) {
super(null);
this.setDisk(disk);
}
public AttachAnswer(String errMsg) {
super(null, false, errMsg);
}
public DiskTO getDisk() {
return disk;
}
public void setDisk(DiskTO disk) {
this.disk = disk;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cloudstack.storage.command;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.to.DiskTO;
public class AttachAnswer extends Answer {
private DiskTO disk;
public AttachAnswer() {
super(null);
}
public AttachAnswer(DiskTO disk) {
this.setDisk(disk);
}
public AttachAnswer(String errMsg) {
super(null, false, errMsg);
}
public DiskTO getDisk() {
return disk;
}
public void setDisk(DiskTO disk) {
this.disk = disk;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.