text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add SITE_ID to test settings setup for Django 1.3. | #!/usr/bin/env python
import os
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'selectable',
),
SITE_ID=1,
ROOT_URLCONF='selectable.tests.urls',
)
from django.test.utils import get_runner
def runtests(*test_args):
if not test_args:
test_args = ['selectable']
parent = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", )
sys.path.insert(0, parent)
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import os
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'selectable',
),
ROOT_URLCONF='selectable.tests.urls',
)
from django.test.utils import get_runner
def runtests(*test_args):
if not test_args:
test_args = ['selectable']
parent = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", )
sys.path.insert(0, parent)
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Remove import which does not seem to be used any more
It seems like since we don't need ti inject batching strategy, we would not need this import? | import IsomorphicRouter from 'isomorphic-relay-router';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Relay from 'react-relay';
import {match} from 'react-router';
import routes from './routes';
const GRAPHQL_URL = `http://localhost:8080/graphql`;
Relay.injectNetworkLayer(new Relay.DefaultNetworkLayer(GRAPHQL_URL));
export default (req, res, next) => {
match({routes, location: req.originalUrl}, (error, redirectLocation, renderProps) => {
if (error) {
next(error);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
IsomorphicRouter.prepareData(renderProps).then(render, next);
} else {
res.status(404).send('Not Found');
}
function render({data, props}) {
const reactOutput = ReactDOMServer.renderToString(
<IsomorphicRouter.RouterContext {...props} />
);
res.render(path.resolve(__dirname, '..', 'views', 'index.ejs'), {
preloadedData: JSON.stringify(data),
reactOutput
});
}
});
};
| import IsomorphicRouter from 'isomorphic-relay-router';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Relay from 'react-relay';
import RelayStoreData from 'react-relay/lib/RelayStoreData';
import {match} from 'react-router';
import routes from './routes';
const GRAPHQL_URL = `http://localhost:8080/graphql`;
Relay.injectNetworkLayer(new Relay.DefaultNetworkLayer(GRAPHQL_URL));
export default (req, res, next) => {
match({routes, location: req.originalUrl}, (error, redirectLocation, renderProps) => {
if (error) {
next(error);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
IsomorphicRouter.prepareData(renderProps).then(render, next);
} else {
res.status(404).send('Not Found');
}
function render({data, props}) {
const reactOutput = ReactDOMServer.renderToString(
<IsomorphicRouter.RouterContext {...props} />
);
res.render(path.resolve(__dirname, '..', 'views', 'index.ejs'), {
preloadedData: JSON.stringify(data),
reactOutput
});
}
});
};
|
Use more reliable JS source mapping technique | const path = require("path");
const merge = require("webpack-merge");
const webpack = require("webpack");
const common = require("./webpack.common.js");
const postCSSPlugins = [
require("postcss-easy-import")({ prefix: "_" }),
require("postcss-mixins"),
require("postcss-simple-vars"),
require("postcss-nested"),
require("postcss-color-function"),
require("postcss-hexrgba"),
require("autoprefixer")
];
module.exports = merge(common, {
entry: [
"webpack-dev-server/client?http://localhost:3000/",
"webpack/hot/only-dev-server"
],
mode: "development",
devtool: "eval-source-map",
watch: true,
devServer: {
headers: {
"Access-Control-Allow-Origin": "*"
},
hot: true,
port: 3000,
disableHostCheck: true,
overlay: true,
contentBase: path.join(__dirname, "../src")
},
plugins: [new webpack.HotModuleReplacementPlugin()],
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
url: false
}
},
{
loader: "postcss-loader",
options: {
plugins: postCSSPlugins
}
}
]
}
]
}
});
| const path = require("path");
const merge = require("webpack-merge");
const webpack = require("webpack");
const common = require("./webpack.common.js");
const postCSSPlugins = [
require("postcss-easy-import")({ prefix: "_" }),
require("postcss-mixins"),
require("postcss-simple-vars"),
require("postcss-nested"),
require("postcss-color-function"),
require("postcss-hexrgba"),
require("autoprefixer")
];
module.exports = merge(common, {
entry: [
"webpack-dev-server/client?http://localhost:3000/",
"webpack/hot/only-dev-server"
],
mode: "development",
devtool: "eval-cheap-module-source-map",
watch: true,
devServer: {
headers: {
"Access-Control-Allow-Origin": "*"
},
hot: true,
port: 3000,
disableHostCheck: true,
overlay: true,
contentBase: path.join(__dirname, "../src")
},
plugins: [new webpack.HotModuleReplacementPlugin()],
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
url: false
}
},
{
loader: "postcss-loader",
options: {
plugins: postCSSPlugins
}
}
]
}
]
}
});
|
Update classifiers through Python 3.6 | import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='[email protected]',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
| import codecs
import os
import re
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
def read(*parts):
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, *parts), 'r').read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
setup(
name='aiofiles',
version=find_version('aiofiles', '__init__.py'),
packages=find_packages(),
url='https://github.com/Tinche/aiofiles',
license='Apache 2.0',
author='Tin Tvrtkovic',
author_email='[email protected]',
description='File support for asyncio.',
long_description=readme,
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Filesystems",
],
extras_require={
':python_version == "3.3"': ['asyncio', 'singledispatch']
}
)
|
Use whatever is default open mode. | import logging
import json
import py
from fields import Namespace
from pytest_benchmark.plugin import BenchmarkSession
class MockSession(BenchmarkSession):
def __init__(self):
self.histogram = True
me = py.path.local(__file__)
self.storage = me.dirpath(me.purebasename)
self.benchmarks = []
self.sort = u"min"
self.compare = self.storage.join('0001_b692275e28a23b5d4aae70f453079ba593e60290_20150811_052350.json')
self.logger = logging.getLogger(__name__)
for bench_file in self.storage.listdir("[0-9][0-9][0-9][0-9]_*.json"):
with bench_file.open() as fh:
data = json.load(fh)
self.benchmarks.extend(
Namespace(
json=lambda: bench['stats'],
fullname=bench['fullname'],
**bench['stats']
)
for bench in data['benchmarks']
)
break
def test_rendering():
sess = MockSession()
sess.handle_histogram()
| import logging
import json
import py
from fields import Namespace
from pytest_benchmark.plugin import BenchmarkSession
class MockSession(BenchmarkSession):
def __init__(self):
self.histogram = True
me = py.path.local(__file__)
self.storage = me.dirpath(me.purebasename)
self.benchmarks = []
self.sort = u"min"
self.compare = self.storage.join('0001_b692275e28a23b5d4aae70f453079ba593e60290_20150811_052350.json')
self.logger = logging.getLogger(__name__)
for bench_file in self.storage.listdir("[0-9][0-9][0-9][0-9]_*.json"):
with bench_file.open('rb') as fh:
data = json.load(fh)
self.benchmarks.extend(
Namespace(
json=lambda: bench['stats'],
fullname=bench['fullname'],
**bench['stats']
)
for bench in data['benchmarks']
)
break
def test_rendering():
sess = MockSession()
sess.handle_histogram()
|
Remove use statements that are no longer needed | <?php
namespace App\Providers;
use App\Tag;
use App\Note;
use Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Validate photos for a maximum filesize
Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
if ($value[0] !== null) {
foreach ($value as $file) {
if ($file->getSize() > 5000000) {
return false;
}
}
}
return true;
});
//Add tags for notes
Note::created(function ($note) {
$tagsToAdd = [];
preg_match_all('/#([^\s<>]+)\b/', $note, $tags);
foreach ($tags[1] as $tag) {
$tag = Tag::normalizeTag($tag);
}
$tags = array_unique($tags[1]);
foreach ($tags as $tag) {
$tag = Tag::firstOrCreate(['tag' => $tag]);
$tagsToAdd[] = $tag->id;
}
if (count($tagsToAdd > 0)) {
$note->tags()->attach($tagsToAdd);
}
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
| <?php
namespace App\Providers;
use App\Tag;
use App\Note;
use Validator;
use App\WebMention;
use App\Observers\WebMentionObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Validate photos for a maximum filesize
Validator::extend('photosize', function ($attribute, $value, $parameters, $validator) {
if ($value[0] !== null) {
foreach ($value as $file) {
if ($file->getSize() > 5000000) {
return false;
}
}
}
return true;
});
//Add tags for notes
Note::created(function ($note) {
$tagsToAdd = [];
preg_match_all('/#([^\s<>]+)\b/', $note, $tags);
foreach ($tags[1] as $tag) {
$tag = Tag::normalizeTag($tag);
}
$tags = array_unique($tags[1]);
foreach ($tags as $tag) {
$tag = Tag::firstOrCreate(['tag' => $tag]);
$tagsToAdd[] = $tag->id;
}
if (count($tagsToAdd > 0)) {
$note->tags()->attach($tagsToAdd);
}
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
|
Fix variable + change event | let formId, formValidationFields;
window.addEventListener('load', function() {
let $_form = $('form#' + formId + '-form'),
$_formInputs = $_form.find(':input'),
_formHasCheckboxes = false;
$_formInputs.each(function () {
$(this).removeAttr('required minlength maxlength');
if ($(this).is(':checkbox')) {
$(this).addClass('hidden');
_formHasCheckboxes = true;
}
});
if (_formHasCheckboxes) {
$('.ui.checkbox').checkbox();
}
let _recaptchaElement = $_form + '-recaptcha-render',
_recaptcha_enabled = document.getElementById(_recaptchaElement);
if (_recaptcha_enabled !== null) {
grecaptcha.render(formId + '-recaptcha-render', {
size: 'invisible',
callback: function (token) {
document.getElementById(formId + '-form').submit();
}
});
}
let _form_validation = {
inline: true,
on: 'blur',
onSuccess: function (e, validation_fields) {
if (_recaptcha_enabled !== null) {
e.preventDefault();
grecaptcha.execute();
}
}
};
_form_validation.fields = formValidationFields;
$_form.form(_form_validation);
});
| let formId, formValidationFields;
window.addEventListener('DOMContentLoaded', function() {
let $_form = $('form#' + formId + '-form'),
$_formInputs = $_form.find(':input'),
_formHasCheckboxes = false;
$_formInputs.each(function () {
$(this).removeAttr('required minlength maxlength');
if ($(this).is(':checkbox')) {
$(this).addClass('hidden');
_formHasCheckboxes = true;
}
});
if (_formHasCheckboxes) {
$('.ui.checkbox').checkbox();
}
let _recaptchaElement = form + '-recaptcha-render',
_recaptcha_enabled = document.getElementById(_recaptchaElement);
if (_recaptcha_enabled !== null) {
grecaptcha.render(formId + '-recaptcha-render', {
size: 'invisible',
callback: function (token) {
document.getElementById(formId + '-form').submit();
}
});
}
let _form_validation = {
inline: true,
on: 'blur',
onSuccess: function (e, validation_fields) {
if (_recaptcha_enabled !== null) {
e.preventDefault();
grecaptcha.execute();
}
}
};
_form_validation.fields = formValidationFields;
$_form.form(_form_validation);
});
|
Change hdu[0] to hdu for optional indexing | """
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None, hdu=0):
"""
Read a SJI file and return a MapCube
..warning::
This function is a very early beta and is not stable. Further work is
on going to improve SunPy IRIS support.
Parameters
----------
filename: string
File to read
start:
Temporal axis index to create MapCube from
stop:
Temporal index to stop MapCube at
hdu:
Choose hdu index
Returns
-------
iris_cube: sunpy.map.MapCube
A map cube of the SJI sequence
"""
hdus = sunpy.io.read_file(filename)
#Get the time delta
time_range = sunpy.time.TimeRange(hdus[hdu][1]['STARTOBS'], hdus[hdu][1]['ENDOBS'])
splits = time_range.split(hdus[hdu][0].shape[0])
if not stop:
stop = len(splits)
headers = [hdus[hdu][1]]*(stop-start)
datas = hdus[hdu][0][start:stop]
#Make the cube:
iris_cube = sunpy.map.Map(zip(datas,headers),cube=True)
#Set the date/time
for i,m in enumerate(iris_cube):
m.meta['DATE-OBS'] = splits[i].center().isoformat()
return iris_cube
| """
Some very beta tools for IRIS
"""
import sunpy.io
import sunpy.time
import sunpy.map
__all__ = ['SJI_to_cube']
def SJI_to_cube(filename, start=0, stop=None):
"""
Read a SJI file and return a MapCube
..warning::
This function is a very early beta and is not stable. Further work is
on going to improve SunPy IRIS support.
Parameters
----------
filename: string
File to read
start:
Temporal axis index to create MapCube from
stop:
Temporal index to stop MapCube at
Returns
-------
iris_cube: sunpy.map.MapCube
A map cube of the SJI sequence
"""
hdus = sunpy.io.read_file(filename)
#Get the time delta
time_range = sunpy.time.TimeRange(hdus[0][1]['STARTOBS'], hdus[0][1]['ENDOBS'])
splits = time_range.split(hdus[0][0].shape[0])
if not stop:
stop = len(splits)
headers = [hdus[0][1]]*(stop-start)
datas = hdus[0][0][start:stop]
#Make the cube:
iris_cube = sunpy.map.Map(zip(datas,headers),cube=True)
#Set the date/time
for i,m in enumerate(iris_cube):
m.meta['DATE-OBS'] = splits[i].center().isoformat()
return iris_cube |
Fix np array issues again | import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, nparray_dtype=None, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
self.nparray_dtype = nparray_dtype
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
nparray_dtype = getattr(self, 'nparray_dtype', None)
if nparray_dtype:
transformed = np.array(transformed, dtype=nparray_dtype)
else:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
FORCE_NP_1D_ARRAY = False
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
if self.FORCE_NP_1D_ARRAY: transformed = np.array(transformed, dtype=np.object)
else: transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
|
Add new bucket list item | import React from 'react';
import Layout from '@theme/Layout';
function BucketList() {
return (
<Layout>
<div className="container padding-vert--lg">
<div className="row">
<div className="col col--8 col--offset-2 markdown">
<h1>Bucket List</h1>
<h3>TODO</h3>
<ul>
<li>Speak at a JSConf</li>
<li>Publish a book</li>
<li>Create an online course</li>
<li>Write a state management framework</li>
<li>
Invent a programming language and write its compiler (toy one)
</li>
<li>Write a module bundler</li>
<li>Become a Google Dev Expert</li>
<li>Buy a nice house</li>
</ul>
<h3>In Progress</h3>
<ul>
<li>Write a CSS framework</li>
<li>Write a static site generator</li>
</ul>
<h3>Done</h3>
<ul>
<li>Work at Facebook (2017, Nov)</li>
<li>Present at F8 (2019, Apr)</li>
</ul>
</div>
</div>
</div>
</Layout>
);
}
export default BucketList;
| import React from 'react';
import Layout from '@theme/Layout';
function BucketList() {
return (
<Layout>
<div className="container padding-vert--lg">
<div className="row">
<div className="col col--8 col--offset-2 markdown">
<h1>Bucket List</h1>
<h3>TODO</h3>
<ul>
<li>Speak at a JSConf</li>
<li>Publish a book</li>
<li>Create an online course</li>
<li>Write a state management framework</li>
<li>
Invent a programming language and write its compiler (toy one)
</li>
<li>Write a module bundler</li>
<li>Buy a nice house</li>
</ul>
<h3>In Progress</h3>
<ul>
<li>Write a CSS framework</li>
<li>Write a static site generator</li>
</ul>
<h3>Done</h3>
<ul>
<li>Work at Facebook (2017, Nov)</li>
<li>Present at F8 (2019, Apr)</li>
</ul>
</div>
</div>
</div>
</Layout>
);
}
export default BucketList;
|
Make psr test more verbose | <?php
namespace phpSmug\Tests;
/**
* @class
* Test properties of our codebase rather than the actual code.
*/
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testPSR()
{
// If we can't find the command-line tool, we mark the test as skipped
// so it shows as a warning to the developer rather than passing silently.
if (!file_exists('vendor/bin/php-cs-fixer')) {
$this->markTestSkipped(
'Needs linter to check PSR compliance'
);
}
// Let's check all PSR compliance for our code and tests.
// Add any other pass you want to test to this array.
foreach (array('lib/', 'examples/', 'test/') as $path) {
// Run linter in dry-run mode so it changes nothing.
exec(
escapeshellcmd('vendor/bin/php-cs-fixer fix -v --dry-run '.$_SERVER['PWD']."/$path"),
$output,
$return_var
);
// If we've got output, pop its first item ("Fixed all files...")
// and trim whitespace from the rest so the below makes sense.
if ($output) {
array_pop($output);
$output = array_map('trim', $output);
}
// Check shell return code: if nonzero, report the output as a failure.
$this->assertEquals(
0,
$return_var,
"PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
);
}
}
}
| <?php
namespace phpSmug\Tests;
/**
* @class
* Test properties of our codebase rather than the actual code.
*/
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testPSR()
{
// If we can't find the command-line tool, we mark the test as skipped
// so it shows as a warning to the developer rather than passing silently.
if (!file_exists('vendor/bin/php-cs-fixer')) {
$this->markTestSkipped(
'Needs linter to check PSR compliance'
);
}
// Let's check all PSR compliance for our code and tests.
// Add any other pass you want to test to this array.
foreach (array('lib/', 'examples/', 'test/') as $path) {
// Run linter in dry-run mode so it changes nothing.
exec(
escapeshellcmd('vendor/bin/php-cs-fixer fix --dry-run '.$_SERVER['PWD']."/$path"),
$output,
$return_var
);
// If we've got output, pop its first item ("Fixed all files...")
// and trim whitespace from the rest so the below makes sense.
if ($output) {
array_pop($output);
$output = array_map('trim', $output);
}
// Check shell return code: if nonzero, report the output as a failure.
$this->assertEquals(
0,
$return_var,
"PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
);
}
}
}
|
[DAT-12296] Remove redundant PATHSCHEMAS from where part of SQL statement looking for a view definition to make query return unique only results | package liquibase.sqlgenerator.core;
import liquibase.CatalogAndSchema;
import liquibase.database.Database;
import liquibase.database.core.AbstractDb2Database;
import liquibase.database.core.Db2zDatabase;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.GetViewDefinitionStatement;
public class GetViewDefinitionGeneratorDB2 extends GetViewDefinitionGenerator {
@Override
public int getPriority() {
return SqlGenerator.PRIORITY_DATABASE;
}
@Override
public boolean supports(GetViewDefinitionStatement statement, Database database) {
return database instanceof AbstractDb2Database;
}
@Override
public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
CatalogAndSchema schema = new CatalogAndSchema(statement.getCatalogName(), statement.getSchemaName()).customize(database);
if (database instanceof Db2zDatabase) {
return new Sql[] {
new UnparsedSql("select STATEMENT AS view_definition from SYSIBM.SYSVIEWS where NAME='" + statement.getViewName() + "' and CREATOR = '" + schema.getSchemaName() + "'")
};
}
return new Sql[] {
new UnparsedSql("select view_definition from SYSIBM.VIEWS where TABLE_NAME='" + statement.getViewName() + "' and TABLE_SCHEMA='" + schema.getSchemaName() + "'")
};
}
}
| package liquibase.sqlgenerator.core;
import liquibase.CatalogAndSchema;
import liquibase.database.Database;
import liquibase.database.core.AbstractDb2Database;
import liquibase.database.core.Db2zDatabase;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.GetViewDefinitionStatement;
public class GetViewDefinitionGeneratorDB2 extends GetViewDefinitionGenerator {
@Override
public int getPriority() {
return SqlGenerator.PRIORITY_DATABASE;
}
@Override
public boolean supports(GetViewDefinitionStatement statement, Database database) {
return database instanceof AbstractDb2Database;
}
@Override
public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
CatalogAndSchema schema = new CatalogAndSchema(statement.getCatalogName(), statement.getSchemaName()).customize(database);
if (database instanceof Db2zDatabase) {
return new Sql[] {
new UnparsedSql("select STATEMENT AS view_definition from SYSIBM.SYSVIEWS where NAME='" + statement.getViewName() + "' and (PATHSCHEMAS LIKE '%" + schema.getSchemaName() + "%' OR CREATOR = '" + schema.getSchemaName() + "')")
};
}
return new Sql[] {
new UnparsedSql("select view_definition from SYSIBM.VIEWS where TABLE_NAME='" + statement.getViewName() + "' and TABLE_SCHEMA='" + schema.getSchemaName() + "'")
};
}
}
|
feat(shop): Update admin order index page
Update admin order index page
see #369 | @extends('layouts.admin')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
List of orders
</div>
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Order At</th>
<th>User</th>
<th>Quantity</th>
<th>Total Price</th>
<th>Status</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
@foreach($orders as $order)
<tr>
<td>{{ $order->id }}</td>
<td>{{ $order->updated_at }}</td>
<td>{{ $order->user->first_name }} {{ $order->user->last_name }}</td>
<td>{{ $order->orderProducts->sum('quantity') }}</td>
<td>{{ $order->orderProducts->sum('price') }}</td>
<td>{{ $order->statusText() }}</td>
<td class="text-right">
<a href="{{ route('adminOrdersShow', ['id' => $order->id] ) }}"><button class="btn btn-xs btn-primary">Show</button></a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
@endsection
| @extends('layouts.admin')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
List of orders
</div>
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Order At</th>
<th>User</th>
<th>Quantity</th>
<th>Total Price</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
@foreach($orders as $order)
<tr>
<td>{{ $order->id }}</td>
<td>{{ $order->updated_at }}</td>
<td>{{ $order->user->first_name }} {{ $order->user->last_name }}</td>
<td>{{ $order->orderProducts->sum('quantity') }}</td>
<td>{{ $order->orderProducts->sum('price') }}</td>
<td class="text-right">
<a href="{{ route('adminOrdersShow', ['id' => $order->id] ) }}"><button class="btn btn-xs btn-primary">Show</button></a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
@endsection
|
Fix response for testing errors |
from werkzeug.exceptions import HTTPException
import sys
from six import reraise
class Handler(object):
"""
The Exception handler
"""
def __init__(self, app):
"""
Initiate
:param app: The application
:type app: Edmunds.Application
"""
self.app = app
self.dont_report = []
def report(self, exception):
"""
Report the exception
:param exception: The exception
:type exception: Exception
:return: Should report
"""
if exception.__class__ in self.dont_report:
return False
return True
def render(self, exception):
"""
Render the exception
:param exception: The exception
:type exception: Exception
:return: The response
"""
# Determine status code
status_code = 500
if isinstance(exception, HTTPException):
status_code = exception.code
is_error_code = status_code - (status_code % 100) == 500
if self.app.debug and is_error_code:
if sys.version_info < (3, 0):
exc_type, exc_value, tb = sys.exc_info()
if exc_value is exception:
reraise(exc_type, exc_value, tb)
raise exception
elif isinstance(exception, HTTPException):
return exception.get_response()
elif self.app.testing and is_error_code:
return '%s' % exception, status_code
else:
return str(status_code), status_code
|
from werkzeug.exceptions import HTTPException
import sys
from six import reraise
class Handler(object):
"""
The Exception handler
"""
def __init__(self, app):
"""
Initiate
:param app: The application
:type app: Edmunds.Application
"""
self.app = app
self.dont_report = []
def report(self, exception):
"""
Report the exception
:param exception: The exception
:type exception: Exception
:return: Should report
"""
if exception.__class__ in self.dont_report:
return False
return True
def render(self, exception):
"""
Render the exception
:param exception: The exception
:type exception: Exception
:return: The response
"""
# Determine status code
status_code = 500
if isinstance(exception, HTTPException):
status_code = exception.code
is_error_code = status_code - (status_code % 100) == 500
if self.app.debug and is_error_code:
if sys.version_info < (3, 0):
exc_type, exc_value, tb = sys.exc_info()
if exc_value is exception:
reraise(exc_type, exc_value, tb)
raise exception
elif isinstance(exception, HTTPException):
return exception.get_response()
elif self.app.testing and is_error_code:
return str(status_code), '%s' % exception
else:
return str(status_code), status_code
|
Add backward compatibility on constants init. | <?php
namespace FrosyaLabs\Lang;
/**
* Class used for formatting the month
*
* @author Nanang F. Rozi
* @since 1.0.2
*/
class MonthFormatter
{
const LONG_MONTH = [
'Januari',
'Februari',
'Maret',
'April',
'Mei',
'Juni',
'Juli',
'Agustus',
'September',
'Oktober',
'November',
'Desember'
];
const SHORT_MONTH = [
'Jan',
'Feb',
'Mar',
'Apr',
'Mei',
'Jun',
'Jul',
'Ags',
'Sep',
'Okt',
'Nov',
'Des'
];
/**
* Get long text representation of the numeric month
*
* @param string $month
* @return string
*/
public static function toText($month)
{
return MonthFormatter::LONG_MONTH[$month-1];
}
/**
* Get shorted text representation of the numeric month
*
* @param string $month
* @return string
*/
public static function toShortedText($month)
{
return MonthFormatter::SHORT_MONTH[$month-1];
}
}
| <?php
namespace FrosyaLabs\Lang;
/**
* Class used for formatting the month
*
* @author Nanang F. Rozi
* @since 1.0.2
*/
class MonthFormatter
{
private const LONG_MONTH = [
'Januari',
'Februari',
'Maret',
'April',
'Mei',
'Juni',
'Juli',
'Agustus',
'September',
'Oktober',
'November',
'Desember'
];
private const SHORT_MONTH = [
'Jan',
'Feb',
'Mar',
'Apr',
'Mei',
'Jun',
'Jul',
'Ags',
'Sep',
'Okt',
'Nov',
'Des'
];
/**
* Get long text representation of the numeric month
*
* @param string $month
* @return string
*/
public static function toText($month)
{
return MonthFormatter::LONG_MONTH[$month-1];
}
/**
* Get shorted text representation of the numeric month
*
* @param string $month
* @return string
*/
public static function toShortedText($month)
{
return MonthFormatter::SHORT_MONTH[$month-1];
}
}
|
Make it out of p tag for reg | @extends('theme/main')
@section('title')
Login - Researchew
@endsection
@section('content')
<div class="am-container">
<div class="am-u-sm-8 am-u-sm-centered">
@if(Session::has('message'))
<div class="am-alert am-alert-success" data-am-alert>{{ Session::get('message') }}</div>
@endif
<div class="am-panel am-panel-default">
<div class="am-panel-hd">Login</div>
<div class="am-panel-bd">
{{ Form::open(array('url'=>'user/auth', 'class'=>'am-form')) }}
<div class="am-form-group">
<label for="email">Email</label>
{{ Form::text('email', null, array('class'=>'', 'placeholder'=>'Please type in your account email')) }}
</div>
<div class="am-form-group">
<label for="password">Password</label>
{{ Form::password('password', array('class'=>'', 'placeholder'=>'Please type in your password')) }}
</div>
<button type="submit" class="am-btn am-btn-primary am-btn-block">Submit</button>
{{ Form::close() }}
</div>
</div>
</div>
</div>
@endsection
@section('script')
@endsection
| @extends('theme/main')
@section('title')
Login - Researchew
@endsection
@section('content')
<div class="am-container">
<div class="am-u-sm-8 am-u-sm-centered">
@if(Session::has('message'))
<div class="am-alert am-alert-success" data-am-alert>{{ Session::get('message') }}</div>
@endif
<div class="am-panel am-panel-default">
<div class="am-panel-hd">Login</div>
<div class="am-panel-bd">
{{ Form::open(array('url'=>'user/auth', 'class'=>'am-form')) }}
<div class="am-form-group">
<label for="email">Email</label>
{{ Form::text('email', null, array('class'=>'', 'placeholder'=>'Please type in your account email')) }}
</div>
<div class="am-form-group">
<label for="password">Password</label>
{{ Form::password('password', array('class'=>'', 'placeholder'=>'Please type in your password')) }}
</div>
<p><button type="submit" class="am-btn am-btn-primary am-btn-block">Submit</button></p>
{{ Form::close() }}
</div>
</div>
</div>
</div>
@endsection
@section('script')
@endsection
|
Fix flaky logout on FF 45 | """
End to end tests for Studio Login
"""
import os
from bok_choy.web_app_test import WebAppTest
from regression.pages.studio.studio_home import DashboardPageExtended
from regression.pages.studio.login_studio import StudioLogin
from regression.pages.studio.logout_studio import StudioLogout
class StudioUserLogin(WebAppTest):
"""
Test for logging in and out to Studio
"""
DEMO_COURSE_USER = os.environ.get('USER_LOGIN_EMAIL')
DEMO_COURSE_PASSWORD = os.environ.get('USER_LOGIN_PASSWORD')
def setUp(self):
"""
Initialize the page object
"""
super(StudioUserLogin, self).setUp()
self.studio_login_page = StudioLogin(self.browser)
self.studio_home_page = DashboardPageExtended(self.browser)
self.studio_logout_page = StudioLogout(self.browser)
def test_studio_login_logout(self):
"""
Verifies that user can login and logout successfully
"""
self.studio_login_page.visit()
self.studio_login_page.login(self.DEMO_COURSE_USER,
self.DEMO_COURSE_PASSWORD)
self.studio_home_page.wait_for_page()
self.studio_home_page.click_logout_button()
self.studio_logout_page.wait_for_page()
| """
End to end tests for Studio Login
"""
import os
from flaky import flaky
from bok_choy.web_app_test import WebAppTest
from regression.pages.studio.studio_home import DashboardPageExtended
from regression.pages.studio.login_studio import StudioLogin
from regression.pages.studio.logout_studio import StudioLogout
class StudioUserLogin(WebAppTest):
"""
Test for logging in and out to Studio
"""
DEMO_COURSE_USER = os.environ.get('USER_LOGIN_EMAIL')
DEMO_COURSE_PASSWORD = os.environ.get('USER_LOGIN_PASSWORD')
def setUp(self):
"""
Initialize the page object
"""
super(StudioUserLogin, self).setUp()
self.studio_login_page = StudioLogin(self.browser)
self.studio_home_page = DashboardPageExtended(self.browser)
self.studio_logout_page = StudioLogout(self.browser)
@flaky # TODO: See https://openedx.atlassian.net/browse/LT-65
def test_studio_login_logout(self):
"""
Verifies that user can login and logout successfully
"""
self.studio_login_page.visit()
self.studio_login_page.login(self.DEMO_COURSE_USER,
self.DEMO_COURSE_PASSWORD)
self.studio_home_page.wait_for_page()
self.studio_home_page.click_logout_button()
self.studio_logout_page.wait_for_page()
|
Use logging instead of print logs. | import logging
class Prioritize(object):
'''
Class which convert dependency relationship to priority level
'''
def __init__(self):
self._priorityLevel = {}
def getPrioritizeLevel(self, item):
if item in self._priorityLevel:
return self._priorityLevel[item]
return -1
def reset(self):
self._priorityLevel.clear()
@staticmethod
def _rmItemRelationship(relationship, item):
rmRelation = set([])
for (f, t) in relationship:
if t == item or f == item:
rmRelation.add((f, t))
relationship -= rmRelation
def convertFrom(self, dependRelations):
"""
Return true when convert is succeed.
The priority level is stored in _priorityLevel.
Input args:
dependRelations - Set of dependency relationship.
example: set([(A, B), (A, C)]) means A depends on B and C.
"""
self.reset()
curLev = 0
depent = dependRelations.copy()
todo = set([])
for (f, t) in depent:
todo.add(f)
todo.add(t)
while todo:
exclude = set([])
for (f, t) in depent:
exclude.add(f)
curLevItem = todo - exclude
if not curLevItem:
logging.warning("Dependency relationship error. Circular dependency exist.")
return False
for item in curLevItem:
Prioritize._rmItemRelationship(depent, item)
self._priorityLevel[item] = curLev
todo -= curLevItem
curLev = curLev + 1
return True
| class Prioritize(object):
'''
Class which convert dependency relationship to priority level
'''
def __init__(self):
self._priorityLevel = {}
def getPrioritizeLevel(self, item):
if item in self._priorityLevel:
return self._priorityLevel[item]
return -1
def reset(self):
self._priorityLevel.clear()
@staticmethod
def _rmItemRelationship(relationship, item):
rmRelation = set([])
for (f, t) in relationship:
if t == item or f == item:
rmRelation.add((f, t))
relationship -= rmRelation
def convertFrom(self, dependRelations):
"""
Return true when convert is succeed.
The priority level is stored in _priorityLevel.
Input args:
dependRelations - Set of dependency relationship.
example: set([(A, B), (A, C)]) means A depends on B and C.
"""
self.reset()
curLev = 0
depent = dependRelations.copy()
todo = set([])
for (f, t) in depent:
todo.add(f)
todo.add(t)
while todo:
exclude = set([])
for (f, t) in depent:
exclude.add(f)
curLevItem = todo - exclude
if not curLevItem:
print("ERROR: dependency relationship error. Circular dependency exist.")
return False
for item in curLevItem:
Prioritize._rmItemRelationship(depent, item)
self._priorityLevel[item] = curLev
todo -= curLevItem
curLev = curLev + 1
return True
|
Fix navigation ACL issue when db is not initialized | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$sm = $e->getApplication()->getServiceManager();
// Add ACL information to the Navigation view helper
$authorize = $sm->get('BjyAuthorize\Service\Authorize');
try {
\Zend\View\Helper\Navigation::setDefaultAcl($authorize->getAcl());
\Zend\View\Helper\Navigation::setDefaultRole($authorize->getIdentity());
} catch (\Doctrine\DBAL\DBALException $exception) {
// database tables not yet initialized
}
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$sm = $e->getApplication()->getServiceManager();
// Add ACL information to the Navigation view helper
$authorize = $sm->get('BjyAuthorize\Service\Authorize');
\Zend\View\Helper\Navigation::setDefaultAcl($authorize->getAcl());
\Zend\View\Helper\Navigation::setDefaultRole($authorize->getIdentity());
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
|
Add test for 1d array arguments for Wrapper | import numpy as np
from functools import partial
from elfi.wrapper import Wrapper
class Test_wrapper():
def test_echo_exec_arg(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper("1")
assert ret == 1
def test_echo_default_arg(self):
command = "echo 1"
wrapper = Wrapper(command, post=int)
ret = wrapper()
assert ret == 1
def test_echo_both_args(self):
command = "echo 1 {0}"
post = partial(np.fromstring, sep=" ")
wrapper = Wrapper(command, post=post)
ret = wrapper("2")
assert np.array_equal(ret, np.array([1,2]))
def test_echo_kwargs(self):
command = "echo {param}"
wrapper = Wrapper(command, post=int)
ret = wrapper(param="1")
assert ret == 1
def test_echo_args_and_kwargs(self):
command = "echo {param} {0}"
post = partial(np.fromstring, sep=" ")
wrapper = Wrapper(command, post=post)
ret = wrapper(2, param="1")
assert np.array_equal(ret, np.array([1,2]))
def test_echo_non_string_args(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper(1)
assert ret == 1
def test_echo_1d_array_args(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper(np.array([1]))
assert ret == 1
| import numpy as np
from functools import partial
from elfi.wrapper import Wrapper
class Test_wrapper():
def test_echo_exec_arg(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper("1")
assert ret == 1
def test_echo_default_arg(self):
command = "echo 1"
wrapper = Wrapper(command, post=int)
ret = wrapper()
assert ret == 1
def test_echo_both_args(self):
command = "echo 1 {0}"
post = partial(np.fromstring, sep=" ")
wrapper = Wrapper(command, post=post)
ret = wrapper("2")
assert np.array_equal(ret, np.array([1,2]))
def test_echo_kwargs(self):
command = "echo {param}"
wrapper = Wrapper(command, post=int)
ret = wrapper(param="1")
assert ret == 1
def test_echo_args_and_kwargs(self):
command = "echo {param} {0}"
post = partial(np.fromstring, sep=" ")
wrapper = Wrapper(command, post=post)
ret = wrapper(2, param="1")
assert np.array_equal(ret, np.array([1,2]))
def test_echo_non_string_args(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper(1)
assert ret == 1
|
Add data status to container view | <h1>Container: <?php echo $cont['NAME'] ?></h1>
<p class="help">This page shows the contents of the selected container. Samples can be added and edited by clicking the pencil icon, and removed by clicking the x</p>
<div class="form">
<ul>
<li>
<span class="label">Shipment</span>
<span><a href="/shipment/sid/<?php echo $cont['SHIPPINGID'] ?>"><?php echo $cont['SHIPMENT'] ?></a></span>
</li>
<li>
<span class="label">Dewar</span>
<span><?php echo $cont['DEWAR'] ?></span>
</li>
</ul>
</div>
<div class="table sample">
<table class="robot_actions samples">
<thead>
<tr>
<th>Location</th>
<th>Protein Acronym</th>
<th>Name</th>
<th>Spacegroup</th>
<th>Comment</th>
<th>Data</th>
<th> </th>
</tr>
</thead>
<tbody></tbody>
</table>
</div> | <h1>Container: <?php echo $cont['NAME'] ?></h1>
<p class="help">This page shows the contents of the selected container. Samples can be added and edited by clicking the pencil icon, and removed by clicking the x</p>
<div class="form">
<ul>
<li>
<span class="label">Shipment</span>
<span><a href="/shipment/sid/<?php echo $cont['SHIPPINGID'] ?>"><?php echo $cont['SHIPMENT'] ?></a></span>
</li>
<li>
<span class="label">Dewar</span>
<span><?php echo $cont['DEWAR'] ?></span>
</li>
</ul>
</div>
<div class="table sample">
<table class="robot_actions samples">
<thead>
<tr>
<th>Location</th>
<th>Protein Acronym</th>
<th>Name</th>
<th>Spacegroup</th>
<th>Comment</th>
<th> </th>
</tr>
</thead>
<tbody></tbody>
</table>
</div> |
Add actual hostname tag to datadog
The datadog daemon may run on different host so the host tag will be
incorrect (mainly on k8s deployment). | <?php
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Middleware;
use ChaseConey\LaravelDatadogHelper\Middleware\LaravelDatadogMiddleware;
use Datadog;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DatadogMetrics extends LaravelDatadogMiddleware
{
/**
* Logs the duration of a specific request through the application
*
* @param Request $request
* @param Response $response
* @param float $startTime
*/
protected static function logDuration(Request $request, Response $response, $startTime)
{
static $hostname;
if (!isset($hostname)) {
$hostname = gethostname();
if (!is_string($hostname)) {
$hostname = 'unknown';
}
}
$duration = microtime(true) - $startTime;
$tags = [
'action' => 'error_page',
'api' => $request->is('api/*') ? 'true' : 'false',
'controller' => 'error',
'namespace' => 'error',
'pod_name' => $hostname,
'section' => 'error',
'status_code' => $response->getStatusCode(),
'status_code_extra' => $request->attributes->get('status_code_extra'),
];
$tags = array_merge($tags, app('route-section')->getCurrent());
Datadog::timing(config('datadog-helper.prefix_web').'.request_time', $duration, 1, $tags);
}
}
| <?php
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Middleware;
use ChaseConey\LaravelDatadogHelper\Middleware\LaravelDatadogMiddleware;
use Datadog;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DatadogMetrics extends LaravelDatadogMiddleware
{
/**
* Logs the duration of a specific request through the application
*
* @param Request $request
* @param Response $response
* @param float $startTime
*/
protected static function logDuration(Request $request, Response $response, $startTime)
{
$duration = microtime(true) - $startTime;
$tags = [
'action' => 'error_page',
'api' => $request->is('api/*') ? 'true' : 'false',
'controller' => 'error',
'namespace' => 'error',
'section' => 'error',
'status_code' => $response->getStatusCode(),
'status_code_extra' => $request->attributes->get('status_code_extra'),
];
$tags = array_merge($tags, app('route-section')->getCurrent());
Datadog::timing(config('datadog-helper.prefix_web').'.request_time', $duration, 1, $tags);
}
}
|
Add CORS on service endpoint. | var express = require('express');
var cors = require('cors');
var situations = require('../controllers/situations');
var teleservices = require('../controllers/teleservices');
module.exports = function(api) {
api.route('/situations').post(situations.create);
var route = new express.Router({ mergeParams: true });
route.use(situations.validateAccess);
route.get('/', situations.show);
route.get('/openfisca-response', situations.openfiscaResponse);
route.get('/legacy-openfisca-request', situations.openfiscaRequestFromLegacy);
// Enable CORS for openfisca-tracer
route.options('/openfisca-request', cors());
route.get('/openfisca-request', cors({ origin: '*' }), situations.openfiscaRequest);
route.post('/openfisca-test', situations.openfiscaTest);
route.get('/openfisca-trace', situations.openfiscaTrace);
teleservices.names.forEach(function(name) {
route.get('/' + name,
teleservices.metadataResponseGenerator(teleservices[name])
);
});
api.options('/situations/via/:signedPayload', cors());
api.get('/situations/via/:signedPayload',
cors({ origin: '*' }),
teleservices.checkCredentials,
teleservices.attachPayloadSituation,
teleservices.verifyRequest,
teleservices.exportRepresentation);
api.use('/situations/:situationId', route);
/*
** Param injection
*/
api.param('situationId', situations.situation);
api.param('signedPayload', teleservices.decodePayload);
};
| var express = require('express');
var cors = require('cors');
var situations = require('../controllers/situations');
var teleservices = require('../controllers/teleservices');
module.exports = function(api) {
api.route('/situations').post(situations.create);
var route = new express.Router({ mergeParams: true });
route.use(situations.validateAccess);
route.get('/', situations.show);
route.get('/openfisca-response', situations.openfiscaResponse);
route.get('/legacy-openfisca-request', situations.openfiscaRequestFromLegacy);
// Enable CORS for openfisca-tracer
route.options('/openfisca-request', cors());
route.get('/openfisca-request', cors({ origin: '*' }), situations.openfiscaRequest);
route.post('/openfisca-test', situations.openfiscaTest);
route.get('/openfisca-trace', situations.openfiscaTrace);
teleservices.names.forEach(function(name) {
route.get('/' + name,
teleservices.metadataResponseGenerator(teleservices[name])
);
});
api.get('/situations/via/:signedPayload',
teleservices.checkCredentials,
teleservices.attachPayloadSituation,
teleservices.verifyRequest,
teleservices.exportRepresentation);
api.use('/situations/:situationId', route);
/*
** Param injection
*/
api.param('situationId', situations.situation);
api.param('signedPayload', teleservices.decodePayload);
};
|
Add logging statement for debugging Travis CI | import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
process.stdout.write(diff + '\n');
process.stdout.write(`Committing 'vinsonchuong/${dependencyName}'\n`);
await exec(
`git config user.email '[email protected]'`,
{cwd: dependencyPath}
);
await exec(
`git config user.name 'Vinson Chuong'`,
{cwd: dependencyPath}
);
await exec(
[
'git commit',
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
| import {exec} from 'node-promise-es6/child-process';
import fs from 'node-promise-es6/fs';
async function run() {
const {linkDependencies = {}} = await fs.readJson('package.json');
for (const dependencyName of Object.keys(linkDependencies)) {
const dependencyPath = linkDependencies[dependencyName];
const {stdout: diff} = await exec(
'git diff-index HEAD', {cwd: dependencyPath});
if (diff.trim().indexOf('package.json') === -1) { continue; }
process.stdout.write(`Committing 'vinsonchuong/${linkDependencies}'\n`);
await exec(
`git config user.email '[email protected]'`,
{cwd: dependencyPath}
);
await exec(
`git config user.name 'Vinson Chuong'`,
{cwd: dependencyPath}
);
await exec(
[
'git commit',
`-m 'Automatically update dependencies'`,
'package.json'
].join(' '),
{cwd: dependencyPath}
);
await exec(
[
'git push',
`https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`,
'master'
].join(' '),
{cwd: dependencyPath}
);
}
}
run().catch(e => {
process.stderr.write(`${e.stack}\n`);
process.exit(1);
});
|
Fix case of "nose" in tests_require. | import sys
from setuptools import setup, find_packages
extra_setup = {}
if sys.version_info >= (3,):
extra_setup['use_2to3'] = True
setup(
name='blessings',
version='1.4',
description='A thin, practical wrapper around terminal coloring, styling, and positioning',
long_description=open('README.rst').read(),
author='Erik Rose',
author_email='[email protected]',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
tests_require=['nose'],
url='https://github.com/erikrose/blessings',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Console :: Curses',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: User Interfaces',
'Topic :: Terminals'
],
keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'style', 'color', 'console'],
**extra_setup
)
| import sys
from setuptools import setup, find_packages
extra_setup = {}
if sys.version_info >= (3,):
extra_setup['use_2to3'] = True
setup(
name='blessings',
version='1.4',
description='A thin, practical wrapper around terminal coloring, styling, and positioning',
long_description=open('README.rst').read(),
author='Erik Rose',
author_email='[email protected]',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
tests_require=['Nose'],
url='https://github.com/erikrose/blessings',
include_package_data=True,
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Console :: Curses',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: User Interfaces',
'Topic :: Terminals'
],
keywords=['terminal', 'tty', 'curses', 'ncurses', 'formatting', 'style', 'color', 'console'],
**extra_setup
)
|
Update the regular express to be less strict.
And remove duplicate definition. | (
function () {
var isDebugging = false;
var re = /saas.hp(.*).com\//;
function isAgmSite(url){
return re.test(url);
}
function onCopyClicked(tab) {
if (!isAgmSite(tab.url)) {
console.log("Nothing to copy, since the URL does not look like AGM site, URL: " + tab.url);
if (!isDebugging){
return;
}
}
chrome.tabs.sendMessage(tab.id, { action: "copy" }, function (response) {
if (response && response.data) {
copyText(response.data);
}
});
}
// show page action for tabs that matches the condition.
chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) {
if (!isAgmSite(tab.url)) {
chrome.pageAction.hide(tabid);
if (!isDebugging)
{
return;
}
}
chrome.pageAction.show(tabid);
chrome.pageAction.onClicked.removeListener(onCopyClicked);
chrome.pageAction.onClicked.addListener(onCopyClicked);
});
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
document.execCommand('Copy');
input.remove();
};
})();
| (
function () {
var isDebugging = false;
var re = /saas.hp(.*).com\/agm/;
function isAgmSite(url){
return re.test(url);
}
function onCopyClicked(tab) {
var re = /saas.hp(.*).com\//;
if (!isAgmSite(tab.url)) {
console.log("Nothing to copy, since the URL does not look like AGM site, URL: " + tab.url);
if (!isDebugging){
return;
}
}
chrome.tabs.sendMessage(tab.id, { action: "copy" }, function (response) {
if (response && response.data) {
copyText(response.data);
}
});
}
// show page action for tabs that matches the condition.
chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) {
if (!isAgmSite(tab.url)) {
chrome.pageAction.hide(tabid);
if (!isDebugging)
{
return;
}
}
chrome.pageAction.show(tabid);
chrome.pageAction.onClicked.removeListener(onCopyClicked);
chrome.pageAction.onClicked.addListener(onCopyClicked);
});
function copyText(text) {
var input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();
document.execCommand('Copy');
input.remove();
};
})();
|
Optimize perf by replacing call_user_func with dynamic vars | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Iterator;
/**
* CustomFilterIterator filters files by applying anonymous functions.
*
* The anonymous function receives a \SplFileInfo and must return false
* to remove files.
*
* @author Fabien Potencier <[email protected]>
*/
class CustomFilterIterator extends \FilterIterator
{
private $filters = array();
/**
* @param \Iterator $iterator The Iterator to filter
* @param callable[] $filters An array of PHP callbacks
*
* @throws \InvalidArgumentException
*/
public function __construct(\Iterator $iterator, array $filters)
{
foreach ($filters as $filter) {
if (!\is_callable($filter)) {
throw new \InvalidArgumentException('Invalid PHP callback.');
}
}
$this->filters = $filters;
parent::__construct($iterator);
}
/**
* Filters the iterator values.
*
* @return bool true if the value should be kept, false otherwise
*/
public function accept()
{
$fileinfo = $this->current();
foreach ($this->filters as $filter) {
if (false === $filter($fileinfo)) {
return false;
}
}
return true;
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Iterator;
/**
* CustomFilterIterator filters files by applying anonymous functions.
*
* The anonymous function receives a \SplFileInfo and must return false
* to remove files.
*
* @author Fabien Potencier <[email protected]>
*/
class CustomFilterIterator extends \FilterIterator
{
private $filters = array();
/**
* @param \Iterator $iterator The Iterator to filter
* @param callable[] $filters An array of PHP callbacks
*
* @throws \InvalidArgumentException
*/
public function __construct(\Iterator $iterator, array $filters)
{
foreach ($filters as $filter) {
if (!\is_callable($filter)) {
throw new \InvalidArgumentException('Invalid PHP callback.');
}
}
$this->filters = $filters;
parent::__construct($iterator);
}
/**
* Filters the iterator values.
*
* @return bool true if the value should be kept, false otherwise
*/
public function accept()
{
$fileinfo = $this->current();
foreach ($this->filters as $filter) {
if (false === \call_user_func($filter, $fileinfo)) {
return false;
}
}
return true;
}
}
|
Disable stage "unit" test for Hibernate Reactive
See #14812
Signed-off-by: Yoann Rodière <[email protected]> | package io.quarkus.hibernate.reactive.singlepersistenceunit;
import static org.assertj.core.api.Assertions.assertThat;
import javax.enterprise.context.control.ActivateRequestContext;
import javax.inject.Inject;
import org.hibernate.reactive.stage.Stage;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
public class SinglePersistenceUnitCdiStageSessionTest {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(DefaultEntity.class)
.addAsResource("application.properties"));
@Inject
Stage.Session session;
@Test
@Disabled("#14812: We're getting a ContextNotActiveException for some (unknown) reason")
@ActivateRequestContext
public void test() {
DefaultEntity entity = new DefaultEntity("default");
DefaultEntity retrievedEntity = session.withTransaction(tx -> session.persist(entity))
.thenCompose($ -> session.withTransaction(tx -> session.clear().find(DefaultEntity.class, entity.getId())))
.toCompletableFuture().join();
assertThat(retrievedEntity)
.isNotSameAs(entity)
.returns(entity.getName(), DefaultEntity::getName);
}
}
| package io.quarkus.hibernate.reactive.singlepersistenceunit;
import static org.assertj.core.api.Assertions.assertThat;
import javax.enterprise.context.control.ActivateRequestContext;
import javax.inject.Inject;
import org.hibernate.reactive.stage.Stage;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
public class SinglePersistenceUnitCdiStageSessionTest {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(DefaultEntity.class)
.addAsResource("application.properties"));
@Inject
Stage.Session session;
@Test
@ActivateRequestContext
public void test() {
DefaultEntity entity = new DefaultEntity("default");
DefaultEntity retrievedEntity = session.withTransaction(tx -> session.persist(entity))
.thenCompose($ -> session.withTransaction(tx -> session.clear().find(DefaultEntity.class, entity.getId())))
.toCompletableFuture().join();
assertThat(retrievedEntity)
.isNotSameAs(entity)
.returns(entity.getName(), DefaultEntity::getName);
}
}
|
Update magic links for dweet and user links | import re
from django import template
register = template.Library()
def to_link(m):
text = m.group('text')
dweet_id = m.group('dweet_id')
username = m.group('username')
if username is None:
url = 'd/' + dweet_id
else:
url = 'u/' + username
result = '<a href="/{0}">{0}</a>'.format(url)
return text.replace(url, result)
@register.filter(is_safe=True)
def insert_magic_links(text):
return re.sub(
r'(?:^|(?<=\s))' # start of string or whitespace
r'/?' # optional /
r'(?P<text>' # capture original pattern
r'[^a-zA-Z\d]?d/(?P<dweet_id>\d+)[^a-zA-Z]?' # dweet reference
r'|' # or
r'[^a-zA-Z\d]?u/(?P<username>[\w.@+-]+)[^a-zA-Z\d]?)' # user reference
r'(?=$|\s)', # end of string or whitespace
to_link,
text
)
| import re
from django import template
register = template.Library()
def to_link(m):
text = m.group('text')
dweet_id = m.group('dweet_id')
username = m.group('username')
if username is None:
path = '/d/' + dweet_id # hardcode for speed!
# path = reverse('dweet_show', kwargs={'dweet_id': dweet_id})
else:
path = '/u/' + username # hardcode for speed!
# path = reverse('user_feed', kwargs={'url_username': username})
return '<a href="%s">%s</a>' % (path, text)
@register.filter(is_safe=True)
def insert_magic_links(text):
return re.sub(
r'(?:^|(?<=\s))' # start of string or whitespace
r'/?' # optional /
r'(?P<text>' # capture original pattern
r'd/(?P<dweet_id>\d+)' # dweet reference
r'|' # or
r'u/(?P<username>[\w.@+-]+))' # user reference
r'(?=$|\s)', # end of string or whitespace
to_link,
text
)
|
Revert 232670 "Fix script after r232641"
Needs to be out to speculatively revert r232641.
> Fix script after r232641
>
> BUG=314253
> [email protected]
>
> Review URL: https://codereview.chromium.org/49753004
[email protected]
Review URL: https://codereview.chromium.org/57293002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232677 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir, _ = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
| #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
Add test control for number of threads
Enable over saturated testing | package org.jctools.util;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
public class TestUtil {
public static final int CONCURRENT_TEST_DURATION = Integer.getInteger("org.jctools.concTestDurationMs", 500);
public static final int CONCURRENT_TEST_THREADS = Integer.getInteger("org.jctools.concTestThreads", Runtime.getRuntime().availableProcessors());
public static final int TEST_TIMEOUT = 30000;
private static final AtomicInteger threadIndex = new AtomicInteger();
public static void sleepQuietly(long timeMs) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(timeMs));
}
public static void startWaitJoin(AtomicBoolean stop, List<Thread> threads) throws InterruptedException
{
for (Thread t : threads) t.start();
Thread.sleep(CONCURRENT_TEST_DURATION);
stop.set(true);
for (Thread t : threads) t.join();
stop.set(false);
}
public static void threads(Runnable runnable, int count, List<Thread> threads)
{
if (count <= 0)
count = CONCURRENT_TEST_THREADS - 1;
for (int i = 0; i < count; i++)
{
Thread thread = new Thread(runnable);
thread.setName("JCTools test thread-" + threadIndex.getAndIncrement());
threads.add(thread);
}
}
public static final class Val
{
public int value;
}
}
| package org.jctools.util;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
public class TestUtil {
public static final int CONCURRENT_TEST_DURATION = Integer.getInteger("org.jctools.concTestDurationMs", 500);
public static final int TEST_TIMEOUT = 30000;
private static final AtomicInteger threadIndex = new AtomicInteger();
public static void sleepQuietly(long timeMs) {
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(timeMs));
}
public static void startWaitJoin(AtomicBoolean stop, List<Thread> threads) throws InterruptedException
{
for (Thread t : threads) t.start();
Thread.sleep(CONCURRENT_TEST_DURATION);
stop.set(true);
for (Thread t : threads) t.join();
stop.set(false);
}
public static void threads(Runnable runnable, int count, List<Thread> threads)
{
if (count <= 0)
count = Runtime.getRuntime().availableProcessors() - 1;
for (int i = 0; i < count; i++)
{
Thread thread = new Thread(runnable);
thread.setName("JCTools test thread-" + threadIndex.getAndIncrement());
threads.add(thread);
}
}
public static final class Val
{
public int value;
}
}
|
Create sections for htmlhead and scripts
Make it possible to inject additional files from other views | <!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html lang="en">
@section('htmlheader')
@include('layouts.partials.htmlheader')
@show
<!--
BODY TAG OPTIONS:
=================
Apply one or more of the following classes to get the
desired effect
|---------------------------------------------------------|
| SKINS | skin-blue |
| | skin-black |
| | skin-purple |
| | skin-yellow |
| | skin-red |
| | skin-green |
|---------------------------------------------------------|
|LAYOUT OPTIONS | fixed |
| | layout-boxed |
| | layout-top-nav |
| | sidebar-collapse |
| | sidebar-mini |
|---------------------------------------------------------|
-->
<body class="skin-blue sidebar-mini">
<div class="wrapper">
@include('layouts.partials.mainheader')
@include('layouts.partials.sidebar')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
@include('layouts.partials.contentheader')
<!-- Main content -->
<section class="content">
<!-- Your Page Content Here -->
@yield('main-content')
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
@include('layouts.partials.controlsidebar')
@include('layouts.partials.footer')
</div><!-- ./wrapper -->
@section('scripts')
@include('layouts.partials.scripts')
@show
</body>
</html>
| <!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html lang="en">
@include('layouts.partials.htmlheader')
<!--
BODY TAG OPTIONS:
=================
Apply one or more of the following classes to get the
desired effect
|---------------------------------------------------------|
| SKINS | skin-blue |
| | skin-black |
| | skin-purple |
| | skin-yellow |
| | skin-red |
| | skin-green |
|---------------------------------------------------------|
|LAYOUT OPTIONS | fixed |
| | layout-boxed |
| | layout-top-nav |
| | sidebar-collapse |
| | sidebar-mini |
|---------------------------------------------------------|
-->
<body class="skin-blue sidebar-mini">
<div class="wrapper">
@include('layouts.partials.mainheader')
@include('layouts.partials.sidebar')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
@include('layouts.partials.contentheader')
<!-- Main content -->
<section class="content">
<!-- Your Page Content Here -->
@yield('main-content')
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
@include('layouts.partials.controlsidebar')
@include('layouts.partials.footer')
</div><!-- ./wrapper -->
@include('layouts.partials.scripts')
</body>
</html> |
Fix ArrayOutOfBoundsException when relativizing path elements | package com.sourcegraph.javagraph;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathUtil {
public static final Path CWD = SystemUtils.getUserDir().toPath().toAbsolutePath().normalize();
public static String normalize(String path) {
if (SystemUtils.IS_OS_WINDOWS) {
return path.replace('\\', '/');
} else {
return path;
}
}
public static String relativizeCwd(String path) {
Path p = Paths.get(path).toAbsolutePath();
if (p.startsWith(CWD)) {
Path rel = CWD.relativize(p);
if (rel.toString().isEmpty()) {
return StringUtils.EMPTY;
}
return normalize(rel.normalize().toString());
} else {
// for example, Android projects may refer to a directory on other drive
return normalize(p.normalize().toString());
}
}
public static Path concat(Path parent, Path child) {
if (child.isAbsolute()) {
return child;
} else {
return parent.resolve(child);
}
}
public static File concat(File parent, File child) {
if (child.isAbsolute()) {
return child;
} else {
return new File(parent, child.getPath());
}
}
public static File concat(File parent, String child) {
return concat(parent, new File(child));
}
}
| package com.sourcegraph.javagraph;
import org.apache.commons.lang3.SystemUtils;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathUtil {
public static final Path CWD = SystemUtils.getUserDir().toPath().toAbsolutePath().normalize();
public static String normalize(String path) {
if (SystemUtils.IS_OS_WINDOWS) {
return path.replace('\\', '/');
} else {
return path;
}
}
public static String relativizeCwd(String path) {
Path p = Paths.get(path).toAbsolutePath();
if (p.startsWith(CWD)) {
return normalize(CWD.relativize(p).normalize().toString());
} else {
// for example, Android projects may refer to a directory on other drive
return normalize(p.normalize().toString());
}
}
public static Path concat(Path parent, Path child) {
if (child.isAbsolute()) {
return child;
} else {
return parent.resolve(child);
}
}
public static File concat(File parent, File child) {
if (child.isAbsolute()) {
return child;
} else {
return new File(parent, child.getPath());
}
}
public static File concat(File parent, String child) {
return concat(parent, new File(child));
}
}
|
Remove if(this.viewHeight){} since block is empty. | class MCShowSampleComponentController {
/*@ngInject*/
constructor($stateParams, samplesService, toast, $mdDialog) {
this.projectId = $stateParams.project_id;
this.samplesService = samplesService;
this.toast = toast;
this.$mdDialog = $mdDialog;
this.viewHeight = this.viewHeight ? this.viewHeight : "40vh";
}
$onInit() {
this.samplesService.getProjectSample(this.projectId, this.sampleId)
.then(
(sample) => this.sample = sample,
() => this.toast.error('Unable to retrieve sample')
)
}
showProcess(process) {
this.$mdDialog.show({
templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html',
controllerAs: '$ctrl',
controller: ShowProcessDialogController,
bindToController: true,
locals: {
process: process
}
});
}
}
class ShowProcessDialogController {
/*@ngInject*/
constructor($mdDialog) {
this.$mdDialog = $mdDialog;
}
done() {
this.$mdDialog.cancel();
}
}
angular.module('materialscommons').component('mcShowSample', {
templateUrl: 'app/global.components/mc-show-sample.html',
controller: MCShowSampleComponentController,
bindings: {
sampleId: '<',
viewHeight: '@'
}
});
| class MCShowSampleComponentController {
/*@ngInject*/
constructor($stateParams, samplesService, toast, $mdDialog) {
this.projectId = $stateParams.project_id;
this.samplesService = samplesService;
this.toast = toast;
this.$mdDialog = $mdDialog;
this.viewHeight = this.viewHeight ? this.viewHeight : "40vh";
}
$onInit() {
if (this.viewHeight) {
}
this.samplesService.getProjectSample(this.projectId, this.sampleId)
.then(
(sample) => this.sample = sample,
() => this.toast.error('Unable to retrieve sample')
)
}
showProcess(process) {
this.$mdDialog.show({
templateUrl: 'app/project/experiments/experiment/components/dataset/components/show-process-dialog.html',
controllerAs: '$ctrl',
controller: ShowProcessDialogController,
bindToController: true,
locals: {
process: process
}
});
}
}
class ShowProcessDialogController {
/*@ngInject*/
constructor($mdDialog) {
this.$mdDialog = $mdDialog;
}
done() {
this.$mdDialog.cancel();
}
}
angular.module('materialscommons').component('mcShowSample', {
templateUrl: 'app/global.components/mc-show-sample.html',
controller: MCShowSampleComponentController,
bindings: {
sampleId: '<',
viewHeight: '@'
}
});
|
Remove explicit inheritance from object | """
Hook wrapper "result" utilities.
"""
import sys
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError(
"wrap_controller at %r %s:%d %s"
% (co.co_name, co.co_filename, co.co_firstlineno, msg)
)
class HookCallError(Exception):
""" Hook was called wrongly. """
class _Result:
def __init__(self, result, excinfo):
self._result = result
self._excinfo = excinfo
@property
def excinfo(self):
return self._excinfo
@classmethod
def from_call(cls, func):
__tracebackhide__ = True
result = excinfo = None
try:
result = func()
except BaseException:
excinfo = sys.exc_info()
return cls(result, excinfo)
def force_result(self, result):
"""Force the result(s) to ``result``.
If the hook was marked as a ``firstresult`` a single value should
be set otherwise set a (modified) list of results. Any exceptions
found during invocation will be deleted.
"""
self._result = result
self._excinfo = None
def get_result(self):
"""Get the result(s) for this hook call.
If the hook was marked as a ``firstresult`` only a single value
will be returned otherwise a list of results.
"""
__tracebackhide__ = True
if self._excinfo is None:
return self._result
else:
ex = self._excinfo
raise ex[1].with_traceback(ex[2])
| """
Hook wrapper "result" utilities.
"""
import sys
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError(
"wrap_controller at %r %s:%d %s"
% (co.co_name, co.co_filename, co.co_firstlineno, msg)
)
class HookCallError(Exception):
""" Hook was called wrongly. """
class _Result(object):
def __init__(self, result, excinfo):
self._result = result
self._excinfo = excinfo
@property
def excinfo(self):
return self._excinfo
@classmethod
def from_call(cls, func):
__tracebackhide__ = True
result = excinfo = None
try:
result = func()
except BaseException:
excinfo = sys.exc_info()
return cls(result, excinfo)
def force_result(self, result):
"""Force the result(s) to ``result``.
If the hook was marked as a ``firstresult`` a single value should
be set otherwise set a (modified) list of results. Any exceptions
found during invocation will be deleted.
"""
self._result = result
self._excinfo = None
def get_result(self):
"""Get the result(s) for this hook call.
If the hook was marked as a ``firstresult`` only a single value
will be returned otherwise a list of results.
"""
__tracebackhide__ = True
if self._excinfo is None:
return self._result
else:
ex = self._excinfo
raise ex[1].with_traceback(ex[2])
|
Switch breadcrumb store to ConcurrentLinkedQueue to prevent concurrency issues | package com.bugsnag.android;
import android.support.annotation.NonNull;
import java.io.IOException;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
class Breadcrumbs implements JsonStream.Streamable {
private static class Breadcrumb {
private static final int MAX_MESSAGE_LENGTH = 140;
final String timestamp;
final String message;
Breadcrumb(@NonNull String message) {
this.timestamp = DateUtils.toISO8601(new Date());
this.message = message.substring(0, Math.min(message.length(), MAX_MESSAGE_LENGTH));
}
}
private static final int DEFAULT_MAX_SIZE = 20;
private final Queue<Breadcrumb> store = new ConcurrentLinkedQueue<>();
private int maxSize = DEFAULT_MAX_SIZE;
public void toStream(@NonNull JsonStream writer) throws IOException {
writer.beginArray();
for (Breadcrumb breadcrumb : store) {
writer.beginArray();
writer.value(breadcrumb.timestamp);
writer.value(breadcrumb.message);
writer.endArray();
}
writer.endArray();
}
void add(@NonNull String message) {
if (store.size() >= maxSize) {
// Remove oldest breadcrumb
store.poll();
}
store.add(new Breadcrumb(message));
}
void clear() {
store.clear();
}
void setSize(int size) {
if (size > store.size()) {
this.maxSize = size;
} else {
// Remove oldest breadcrumbs until reaching the required size
while (store.size() > size) {
store.poll();
}
}
}
}
| package com.bugsnag.android;
import android.support.annotation.NonNull;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
class Breadcrumbs implements JsonStream.Streamable {
private static class Breadcrumb {
private static final int MAX_MESSAGE_LENGTH = 140;
final String timestamp;
final String message;
Breadcrumb(@NonNull String message) {
this.timestamp = DateUtils.toISO8601(new Date());
this.message = message.substring(0, Math.min(message.length(), MAX_MESSAGE_LENGTH));
}
}
private static final int DEFAULT_MAX_SIZE = 20;
private final List<Breadcrumb> store = new LinkedList<Breadcrumb>();
private int maxSize = DEFAULT_MAX_SIZE;
public void toStream(@NonNull JsonStream writer) throws IOException {
writer.beginArray();
for (Breadcrumb breadcrumb : store) {
writer.beginArray();
writer.value(breadcrumb.timestamp);
writer.value(breadcrumb.message);
writer.endArray();
}
writer.endArray();
}
void add(@NonNull String message) {
if (store.size() >= maxSize) {
store.remove(0);
}
store.add(new Breadcrumb(message));
}
void clear() {
store.clear();
}
void setSize(int size) {
if (size > store.size()) {
this.maxSize = size;
} else {
store.subList(0, store.size() - size).clear();
}
}
}
|
Document year filter spec and only attempt to use it with 4 digit values | 'use strict';
angular.module('occupied.filters', ['occupied.services'])
/**
* Filter to insert adjusted/ filled-in values for {city}, {population|...}, {area|...}, {year|...}.
*
* Year must be a full 4-digit value.
* Population must be an integer with no commas.
* Area must be an int or float with no commas.
* Area will have unit (km^2) appended to the number.
*/
.filter('interpolate', ['$filter', 'basePopulation', 'baseArea', function($filter, basePopulation, baseArea) {
return function(text, city) {
text = text.replace(new RegExp('{city}', 'g'), city.name);
text = text.replace(new RegExp('\\{population\\|([0-9]+)\\}', 'g'), function(match, capture) {
return $filter('number')(parseInt(capture) * city.population / basePopulation, 0);
});
text = text.replace(new RegExp('\\{area\\|([0-9.]+)\\}', 'g'), function(match, capture) {
return $filter('number')(parseFloat(capture) * city.area / baseArea, 1) + ' km²';
});
text = text.replace(new RegExp('\\{year\\|([0-9]{4})\\}', 'g'), function(match, capture) {
return parseInt(capture) + (new Date()).getFullYear() - 1946;
});
return text;
};
}]);
| 'use strict';
angular.module('occupied.filters', ['occupied.services'])
/**
* Filter to insert adjusted/ filled-in values for {city}, {population|...}, {area|...}, {year|...}.
*
* Population must be an integer with no commas.
* Area must be an int or float with no commas.
* Area will have unit (km^2) appended to the number.
*/
.filter('interpolate', ['$filter', 'basePopulation', 'baseArea', function($filter, basePopulation, baseArea) {
return function(text, city) {
text = text.replace(new RegExp('{city}', 'g'), city.name);
text = text.replace(new RegExp('\\{population\\|([0-9]+)\\}', 'g'), function(match, capture) {
return $filter('number')(parseInt(capture) * city.population / basePopulation, 0);
});
text = text.replace(new RegExp('\\{area\\|([0-9.]+)\\}', 'g'), function(match, capture) {
return $filter('number')(parseFloat(capture) * city.area / baseArea, 1) + ' km²';
});
text = text.replace(new RegExp('\\{year\\|([0-9]+)\\}', 'g'), function(match, capture) {
return parseInt(capture) + (new Date()).getFullYear() - 1946;
});
return text;
};
}]);
|
Improve perfomance on large DOMs when container is not whole document. | (function(ns) {
var namespaces = [this];
var attachBehavior = function($element, behavior) {
var fn = namespaces;
behavior.replace(/([^.]+)/g, function(object) {
if(fn === namespaces) {
for(var nextFn, index = 0; index < fn.length; ++index) {
nextFn = fn[index][object];
if(nextFn) {
fn = nextFn;
break;
}
}
} else if(typeof fn === 'object') {
fn = fn[object];
}
});
if(typeof fn === 'function') {
return fn($element);
} else {
if (window.console && console.warn) {
console.warn("elementalJS: Unable to find behavior:", behavior);
}
}
};
ns.load = function(container) {
var $selector;
$selector = $('[data-behavior]', container)
if ($(container).data('behavior')) {
$selector = $selector.add(container);
}
$selector.each(function(index, element) {
var $element = $(element);
var behaviors = $element.data('behavior');
behaviors.replace(/([^ ]+)/g, function(behavior) {
attachBehavior($element, behavior);
});
});
};
ns.addNamespace = function(namespace) {
namespaces.push(namespace);
};
})(window.Elemental = {});
| (function(ns) {
var namespaces = [this];
var attachBehavior = function($element, behavior) {
var fn = namespaces;
behavior.replace(/([^.]+)/g, function(object) {
if(fn === namespaces) {
for(var nextFn, index = 0; index < fn.length; ++index) {
nextFn = fn[index][object];
if(nextFn) {
fn = nextFn;
break;
}
}
} else if(typeof fn === 'object') {
fn = fn[object];
}
});
if(typeof fn === 'function') {
return fn($element);
} else {
if (window.console && console.warn) {
console.warn("elementalJS: Unable to find behavior:", behavior);
}
}
};
ns.load = function(container) {
var $selector;
if (container === document) {
$selector = $('[data-behavior]');
}
else {
$selector = $(container).find("*").andSelf().filter("[data-behavior]");
}
$selector.each(function(index, element) {
var $element = $(element);
var behaviors = $element.data('behavior');
behaviors.replace(/([^ ]+)/g, function(behavior) {
attachBehavior($element, behavior);
});
});
};
ns.addNamespace = function(namespace) {
namespaces.push(namespace);
};
})(window.Elemental = {});
|
Remove impossible todo about loc status enum validation | const geom = require('./geom');
const time = require('./time');
const objectid = require('./objectid');
module.exports = {
type: 'object',
properties: {
_id: objectid,
createdAt: time,
creator: {
type: 'string',
},
deleted: {
type: 'boolean',
},
geom: geom,
name: {
type: 'string',
},
places: {
type: 'array',
items: {
type: 'string',
},
},
published: {
type: 'boolean',
},
status: {
type: 'string',
// values depend on configuration
},
text1: {
type: 'string',
},
text2: {
type: 'string',
},
thumbnail: {
anyOf: [
{
type: 'string',
},
{
type: 'null',
},
],
},
type: {
type: 'string',
},
// Latent
childLayer: {
type: 'integer',
},
isLayered: {
type: 'boolean',
},
layer: {
type: 'integer',
},
points: {
type: 'integer',
},
},
required: [
// _id
'createdAt',
'creator',
'deleted',
'geom',
'name',
'places',
'published',
'status',
'text1',
'text2',
'thumbnail',
'type',
// childLayer
// isLayered
// layer
// points
],
additionalProperties: false,
};
| const geom = require('./geom');
const time = require('./time');
const objectid = require('./objectid');
module.exports = {
type: 'object',
properties: {
_id: objectid,
createdAt: time,
creator: {
type: 'string',
},
deleted: {
type: 'boolean',
},
geom: geom,
name: {
type: 'string',
},
places: {
type: 'array',
items: {
type: 'string',
},
},
published: {
type: 'boolean',
},
status: {
type: 'string',
// TODO enum
},
text1: {
type: 'string',
},
text2: {
type: 'string',
},
thumbnail: {
anyOf: [
{
type: 'string',
},
{
type: 'null',
},
],
},
type: {
type: 'string',
},
// Latent
childLayer: {
type: 'integer',
},
isLayered: {
type: 'boolean',
},
layer: {
type: 'integer',
},
points: {
type: 'integer',
},
},
required: [
// _id
'createdAt',
'creator',
'deleted',
'geom',
'name',
'places',
'published',
'status',
'text1',
'text2',
'thumbnail',
'type',
// childLayer
// isLayered
// layer
// points
],
additionalProperties: false,
};
|
Remove the comment (line already fixed) | $(window).load(function () {
var Ector = require('ector');
ector = new Ector();
var previousResponseNodes = null;
var user = { username: "Guy"};
var msgtpl = $('#msgtpl').html();
var lastmsg = false;
$('#msgtpl').remove();
var message;
$('#send').on('click', function () {
var d = new Date();
var entry = $('#message').val();
message = {
user: user,
message: entry,
h: d.getHours(),
m: d.getMinutes()
};
$('#message').attr('value','');
$('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
ector.addEntry(entry);
ector.linkNodesToLastSentence(previousResponseNodes);
var response = ector.generateResponse();
// console.log('%s: %s', ector.name, response.sentence);
previousResponseNodes = response.nodes;
d = new Date();
message = {
user: {username: ector.name},
message: response.sentence,
h: d.getHours(),
m: d.getMinutes()
};
$('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
return false;
});
}); | $(window).load(function () {
var Ector = require('ector');
ector = new Ector();
var previousResponseNodes = null;
var user = { username: "Guy"};
var msgtpl = $('#msgtpl').html();
var lastmsg = false;
$('#msgtpl').remove();
var message;
$('#send').on('click', function () {
var d = new Date();
var entry = $('#message').val();
message = {
user: user,
message: entry,
h: d.getHours(),
m: d.getMinutes()
};
$('#message').attr('value',''); // FIXME
$('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
ector.addEntry(entry);
ector.linkNodesToLastSentence(previousResponseNodes);
var response = ector.generateResponse();
// console.log('%s: %s', ector.name, response.sentence);
previousResponseNodes = response.nodes;
d = new Date();
message = {
user: {username: ector.name},
message: response.sentence,
h: d.getHours(),
m: d.getMinutes()
};
$('#messages').append('<div class="message">' + Mustache.render(msgtpl, message) + '</div>');
$('#messages').animate({scrollTop : $('#messages').prop('scrollHeight')}, 500);
return false;
});
}); |
CRM-6121: Disable emails as a feature
- Removed unused service argument | <?php
namespace Oro\Bundle\SidebarBundle\Model;
use Doctrine\Common\Collections\ArrayCollection;
use Oro\Bundle\FeatureToggleBundle\Checker\FeatureChecker;
class WidgetDefinitionRegistry
{
const SIDEBAR_WIDGET_FEATURE_NAME = 'sidebar_widgets';
/**
* @var ArrayCollection
*/
protected $widgetDefinitions;
/**
* @param array $definitions
*/
public function __construct(array $definitions)
{
$this->widgetDefinitions = new ArrayCollection();
$this->setWidgetDefinitions($definitions);
}
/**
* @param array $definitions
*/
public function setWidgetDefinitions(array $definitions)
{
foreach ($definitions as $name => $definition) {
$this->widgetDefinitions->set($name, $definition);
}
}
/**
* @return ArrayCollection
*/
public function getWidgetDefinitions()
{
return $this->widgetDefinitions;
}
/**
* @param string $placement
* @return ArrayCollection
*/
public function getWidgetDefinitionsByPlacement($placement)
{
return $this->widgetDefinitions->filter(
function ($widgetDefinition) use ($placement) {
return $widgetDefinition['placement'] === $placement
|| $widgetDefinition['placement'] === 'both';
}
);
}
}
| <?php
namespace Oro\Bundle\SidebarBundle\Model;
use Doctrine\Common\Collections\ArrayCollection;
use Oro\Bundle\FeatureToggleBundle\Checker\FeatureChecker;
class WidgetDefinitionRegistry
{
const SIDEBAR_WIDGET_FEATURE_NAME = 'sidebar_widgets';
/**
* @var ArrayCollection
*/
protected $widgetDefinitions;
/**
* @param array $definitions
*/
public function __construct(array $definitions, FeatureChecker $featureChecker)
{
$this->featureChecker = $featureChecker;
$this->widgetDefinitions = new ArrayCollection();
$this->setWidgetDefinitions($definitions);
}
/**
* @param array $definitions
*/
public function setWidgetDefinitions(array $definitions)
{
foreach ($definitions as $name => $definition) {
$this->widgetDefinitions->set($name, $definition);
}
}
/**
* @return ArrayCollection
*/
public function getWidgetDefinitions()
{
return $this->widgetDefinitions;
}
/**
* @param string $placement
* @return ArrayCollection
*/
public function getWidgetDefinitionsByPlacement($placement)
{
return $this->widgetDefinitions->filter(
function ($widgetDefinition) use ($placement) {
return $widgetDefinition['placement'] === $placement
|| $widgetDefinition['placement'] === 'both';
}
);
}
}
|
Add prop-types as a peer dependency
This further reduces the bundle size to 8k | import path from 'path';
import UglifyJSPlugin from 'uglifyjs-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
const config = [
{
name: 'react-redux-spinner',
entry: [
'./src/nprogress.css',
'./src/index.js'
],
externals: {
react: 'react',
'react-dom': 'ReactDOM',
'prop-types': 'PropTypes'
},
output: {
path: path.join(__dirname, '..', 'dist'),
filename: 'react-redux-spinner.js',
library: 'react-redux-spinner',
libraryTarget: 'umd',
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.js$/,
include: [ __dirname ],
loader: 'babel-loader'
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: {
loader: 'css-loader',
options: {
minimize: true
}
}
})
}
]
},
plugins: [
new UglifyJSPlugin(),
new ExtractTextPlugin('react-redux-spinner.css')
]
}
];
module.exports = config;
| import path from 'path';
import UglifyJSPlugin from 'uglifyjs-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
const config = [
{
name: 'react-redux-spinner',
entry: [
'./src/nprogress.css',
'./src/index.js'
],
externals: {
react: 'react',
'react-dom': 'ReactDOM'
},
output: {
path: path.join(__dirname, '..', 'dist'),
filename: 'react-redux-spinner.js',
library: 'react-redux-spinner',
libraryTarget: 'umd',
publicPath: '/dist/'
},
module: {
rules: [
{
test: /\.js$/,
include: [ __dirname ],
loader: 'babel-loader'
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: {
loader: 'css-loader',
options: {
minimize: true
}
}
})
}
]
},
plugins: [
new UglifyJSPlugin(),
new ExtractTextPlugin('react-redux-spinner.css')
]
}
];
module.exports = config;
|
Exclude tests from installed packages
Fixes #453. | #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='django-mptt',
description='''Utilities for implementing Modified Preorder Tree Traversal
with your Django Models and working with trees of Model instances.''',
version=__import__('mptt').__version__,
author='Craig de Stigter',
author_email='[email protected]',
url='http://github.com/django-mptt/django-mptt',
license='MIT License',
packages=find_packages(exclude=['tests', 'tests.*']),
include_package_data=True,
install_requires=(
'Django>=1.8',
),
tests_require=(
'mock-django>=0.6.7',
'mock>=1.3',
),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
'Topic :: Utilities',
],
)
| #!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name='django-mptt',
description='''Utilities for implementing Modified Preorder Tree Traversal
with your Django Models and working with trees of Model instances.''',
version=__import__('mptt').__version__,
author='Craig de Stigter',
author_email='[email protected]',
url='http://github.com/django-mptt/django-mptt',
license='MIT License',
packages=find_packages(),
include_package_data=True,
install_requires=(
'Django>=1.8',
),
tests_require=(
'mock-django>=0.6.7',
'mock>=1.3',
),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
'Topic :: Utilities',
],
)
|
Set height and width for Sub Ebook Embed iframe | import m from 'mithril';
import h from '../h';
import userVM from '../vms/user-vm';
import projectVM from '../vms/project-vm';
import youtubeLightbox from '../c/youtube-lightbox';
const I18nScope = _.partial(h.i18nScope, 'projects.dashboard_start');
const projectEditStart = {
controller(args) {
},
view(ctrl, args) {
return m('.dashboard-header.min-height-70.u-text-center',
m('.w-container',
m('.u-marginbottom-40.w-row',
[
m('.w-col.w-col-8.w-col-push-2',
[
m('.fontsize-larger.fontweight-semibold.lineheight-looser.u-marginbottom-10',
I18n.t('title', I18nScope())
),
m('.fontsize-small.lineheight-loose.u-marginbottom-40',
I18n.t('description', I18nScope({ name: args.project().user.name || '' }))
),
m('.card.card-terciary.u-radius',
m(`iframe[allowfullscreen="true"][width="630"][height="383"][frameborder="0"][scrolling="no"][mozallowfullscreen="true"][webkitallowfullscreen="true"][src=${I18n.t('video_src', I18nScope())}]`)
)
]
)
]
)
)
);
}
};
export default projectEditStart;
| import m from 'mithril';
import h from '../h';
import userVM from '../vms/user-vm';
import projectVM from '../vms/project-vm';
import youtubeLightbox from '../c/youtube-lightbox';
const I18nScope = _.partial(h.i18nScope, 'projects.dashboard_start');
const projectEditStart = {
controller(args) {
},
view(ctrl, args) {
return m('.dashboard-header.min-height-70.u-text-center',
m('.w-container',
m('.u-marginbottom-40.w-row',
[
m('.w-col.w-col-8.w-col-push-2',
[
m('.fontsize-larger.fontweight-semibold.lineheight-looser.u-marginbottom-10',
I18n.t('title', I18nScope())
),
m('.fontsize-small.lineheight-loose.u-marginbottom-40',
I18n.t('description', I18nScope({ name: args.project().user.name || '' }))
),
m('.card.card-terciary.u-radius',
m(`iframe[allowfullscreen="true"][frameborder="0"][scrolling="no"][mozallowfullscreen="true"][webkitallowfullscreen="true"][src=${I18n.t('video_src', I18nScope())}]`)
)
]
)
]
)
)
);
}
};
export default projectEditStart;
|
Remove GDAL as a dependency | from setuptools import setup
setup(
name='centerline',
version='0.1',
description='Calculate the centerline of a polygon',
long_description='README.rst',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: GIS'
],
url='https://github.com/fitodic/centerline.git',
author='Filip Todic',
author_email='[email protected]',
license='MIT',
packages=['centerline'],
install_requires=[
'Fiona>=1.6.3'
'Shapely>=1.5.13',
'numpy>=1.10.4',
'scipy>=0.16.1',
],
extras_require={
'dev': [
'pypandoc',
'ipdb',
],
'test': [
'coverage',
'pytest',
'pytest-cov',
'pytest-sugar',
'pytest-runner',
'tox'
],
},
scripts=[
'bin/shp2centerline',
],
include_package_data=True,
zip_safe=False,
)
| from setuptools import setup
setup(
name='centerline',
version='0.1',
description='Calculate the centerline of a polygon',
long_description='README.rst',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: GIS'
],
url='https://github.com/fitodic/centerline.git',
author='Filip Todic',
author_email='[email protected]',
license='MIT',
packages=['centerline'],
install_requires=[
'GDAL>=1.9.2',
'Fiona>=1.6.3'
'Shapely>=1.5.13',
'numpy>=1.10.4',
'scipy>=0.16.1',
],
extras_require={
'dev': [
'pypandoc',
'ipdb',
],
'test': [
'coverage',
'pytest',
'pytest-cov',
'pytest-sugar',
'pytest-runner',
'tox'
],
},
scripts=[
'bin/shp2centerline',
],
include_package_data=True,
zip_safe=False,
)
|
Fix typos in French translation of the example | export const messages = {
post: {
name: 'Article',
all: 'Articles',
list: {
search: 'Recherche',
title: 'Titre',
published_at: 'Publié le',
commentable: 'Commentable',
views: 'Vues',
},
form: {
title: 'Titre',
published_at: 'Publié le',
teaser: 'Description',
body: 'Contenu',
average_note: 'Note moyenne',
allow_comments: 'Accepte les commentaires ?',
password: 'Mot de passe (si protégé)',
summary: 'Résumé',
miscellaneous: 'Extra',
nb_view: 'Nb de vues',
comments: 'Commentaires',
created_at: 'Créé le',
},
},
comment: {
name: 'Commentaire',
all: 'Commentaires',
form: {
body: 'Contenu',
created_at: 'Créé le',
author_name: 'Nom de l\'auteur',
},
},
author: {
name: 'Auteur',
list: {
name: 'Nom',
},
},
resources: {
comments: 'Commentaire |||| Commentaires'
}
};
export default messages;
| export const messages = {
post: {
name: 'Article',
all: 'Articles',
list: {
search: 'Recherche',
title: 'Titre',
published_at: 'Publié le',
commentable: 'Commentable',
views: 'Vues',
},
form: {
title: 'Titre',
published_at: 'Publié le',
teaser: 'Description',
body: 'Contenu',
average_note: 'Note moyenne',
allow_comments: 'Accepte les commentaires ?',
password: 'Mot de passe (si protégé)',
summary: 'Résumé',
miscellaneous: 'Extra',
nb_view: 'Nb de vues ?',
comments: 'Commentaires',
created_at: 'Créer le',
},
},
comment: {
name: 'Commentaire',
all: 'Commentaires',
form: {
body: 'Contenu',
created_at: 'Créer le',
author_name: 'Nom de l\'auteur',
},
},
author: {
name: 'Auteur',
list: {
name: 'Nom',
},
},
};
export default messages;
|
Install beautifulsoup4 with lxml parser | import subprocess
from codecs import open
from setuptools import setup, find_packages
from setuptools.command import develop, build_py
def readme():
with open("README.md", "r", "utf-8") as f:
return f.read()
class CustomDevelop(develop.develop, object):
"""
Class needed for "pip install -e ."
"""
def run(self):
subprocess.check_call("make", shell=True)
super(CustomDevelop, self).run()
class CustomBuildPy(build_py.build_py, object):
"""
Class needed for "pip install s2p"
"""
def run(self):
super(CustomBuildPy, self).run()
subprocess.check_call("make", shell=True)
subprocess.check_call("cp -r bin lib build/lib/", shell=True)
requirements = ['numpy',
'scipy',
'rasterio[s3,test]',
'utm',
'pyproj',
'beautifulsoup4[lxml]',
'requests']
setup(name="s2p",
version="1.0b6",
description="Satellite Stereo Pipeline.",
long_description=readme(),
long_description_content_type='text/markdown',
url='https://github.com/miss3d/s2p',
packages=['s2p'],
install_requires=requirements,
cmdclass={'develop': CustomDevelop,
'build_py': CustomBuildPy},
entry_points="""
[console_scripts]
s2p=s2p.cli:main
""")
| import subprocess
from codecs import open
from setuptools import setup, find_packages
from setuptools.command import develop, build_py
def readme():
with open("README.md", "r", "utf-8") as f:
return f.read()
class CustomDevelop(develop.develop, object):
"""
Class needed for "pip install -e ."
"""
def run(self):
subprocess.check_call("make", shell=True)
super(CustomDevelop, self).run()
class CustomBuildPy(build_py.build_py, object):
"""
Class needed for "pip install s2p"
"""
def run(self):
super(CustomBuildPy, self).run()
subprocess.check_call("make", shell=True)
subprocess.check_call("cp -r bin lib build/lib/", shell=True)
requirements = ['numpy',
'scipy',
'rasterio[s3,test]',
'utm',
'pyproj',
'bs4',
'requests']
setup(name="s2p",
version="1.0b6",
description="Satellite Stereo Pipeline.",
long_description=readme(),
long_description_content_type='text/markdown',
url='https://github.com/miss3d/s2p',
packages=['s2p'],
install_requires=requirements,
cmdclass={'develop': CustomDevelop,
'build_py': CustomBuildPy},
entry_points="""
[console_scripts]
s2p=s2p.cli:main
""")
|
Fix promises params and this references | 'use strict';
var request = require('request');
class CartoDBMapClient {
constructor(user, apiKey) {
this.user = user;
this.apiKey = apiKey;
this.baseURL = 'https://' + this.user + '.cartodb.com/';
}
createNamedMap(options) {
this.existsNamedMap(options.name).then(function() {
});
}
existsNamedMap(name) {
var $this = this;
var promise = new Promise(function(resolve, reject) {
request({
method: 'GET',
uri: $this.baseURL + 'tiles/template/' + name,
qs: {
'api_key': $this.apiKey,
},
json: {}
}, function(error, response, body) {
if(error) {
reject(error);
}
resolve({
exists: response.statusCode !== 404,
data: body
});
});
});
return promise;
}
getGroupID(name) {
var $this = this;
var promise = new Promise(function(resolve, reject) {
request({
method: 'POST',
uri: $this.baseURL + 'tiles/template/' + name,
qs: {
'api_key': $this.apiKey,
},
json: {}
}, function(error, response, body) {
if(error) {
reject(error);
}
resolve(body);
});
});
return promise;
}
}
module.exports = CartoDBMapClient;
| 'use strict';
var request = require('request');
class CartoDBMapClient {
constructor(user, apiKey) {
this.user = user;
this.apiKey = apiKey;
this.baseURL = 'https://' + this.user + '.cartodb.com/';
}
createNamedMap(options) {
this.existsNamedMap(options.name).then(function() {
});
}
existsNamedMap(name) {
var promise = new Promise(function(reject, resolve) {
request({
method: 'GET',
uri: this.baseURL + 'tiles/template/' + name,
qs: {
'api_key': this.apiKey,
},
json: {}
}, function(error, response, body) {
if(error) {
reject(error);
}
resolve({
notExists: response.status === 404,
exists: response.status === 200,
data: body
});
});
});
return promise;
}
getGroupID(name) {
var promise = new Promise(function(reject, resolve) {
request({
method: 'POST',
uri: this.baseURL + 'tiles/template/' + name,
qs: {
'api_key': this.apiKey,
},
json: {}
}, function(error, response, body) {
if(error) {
reject(error);
}
resolve(body);
});
});
return promise;
}
}
module.exports = CartoDBMapClient;
|
Allow codes for owned entities in the api models | package org.marsik.elshelves.api.entities;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.Setter;
import org.marsik.elshelves.ember.EmberModelName;
import org.marsik.elshelves.api.entities.idresolvers.CodeIdResolver;
import javax.validation.constraints.NotNull;
import java.util.UUID;
@Getter
@Setter
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", resolver = CodeIdResolver.class)
@JsonTypeName("code")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "_type",
visible = true,
defaultImpl = CodeApiModel.class)
public class CodeApiModel extends AbstractEntityApiModel {
public CodeApiModel(UUID id) {
super(id);
}
public CodeApiModel() {
}
public CodeApiModel(String uuid) {
super(uuid);
}
@NotNull
String type; // CODE_TYPE - EAN, QR, UPC...
@NotNull
String code; // CODE_VALUE
AbstractOwnedEntityApiModel reference;
UserApiModel belongsTo;
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| package org.marsik.elshelves.api.entities;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.Setter;
import org.marsik.elshelves.ember.EmberModelName;
import org.marsik.elshelves.api.entities.idresolvers.CodeIdResolver;
import javax.validation.constraints.NotNull;
import java.util.UUID;
@Getter
@Setter
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", resolver = CodeIdResolver.class)
@JsonTypeName("code")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "_type",
visible = true,
defaultImpl = CodeApiModel.class)
public class CodeApiModel extends AbstractEntityApiModel {
public CodeApiModel(UUID id) {
super(id);
}
public CodeApiModel() {
}
public CodeApiModel(String uuid) {
super(uuid);
}
@NotNull
String type; // CODE_TYPE - EAN, QR, UPC...
@NotNull
String code; // CODE_VALUE
AbstractNamedEntityApiModel reference;
UserApiModel belongsTo;
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
|
Use the correct path for the database file | async function sql( args ) {
/*
description("This will execute sql on the internal SQLite database")
base_component_id("systemFunctionAppSql")
load_once_from_file(true)
*/
var getSqlResults = new Promise(returnResult => {
var dbPath = path.join(userData, args.base_component_id + '.visi')
console.log("dbPath: " + JSON.stringify(dbPath,null,2))
var appDb = new sqlite3.Database(dbPath);
appDb.run("PRAGMA journal_mode=WAL;")
appDb.serialize(
function() {
appDb.run("begin exclusive transaction");
appDb.all(
args.sql
,
function(err, results)
{
console.log("Results: " + JSON.stringify(results,null,2))
appDb.run("commit");
appDb.run("PRAGMA wal_checkpoint;")
returnResult(results)
})
})
})
var res = await getSqlResults
return res
}
| async function sql( args ) {
/*
description("This will execute sql on the internal SQLite database")
base_component_id("systemFunctionAppSql")
load_once_from_file(true)
*/
var getSqlResults = new Promise(returnResult => {
var dbPath = path.join(userData, args.base_component_id + '.visi.db')
console.log("dbPath: " + JSON.stringify(dbPath,null,2))
var appDb = new sqlite3.Database(dbPath);
appDb.run("PRAGMA journal_mode=WAL;")
appDb.serialize(
function() {
appDb.run("begin exclusive transaction");
appDb.all(
args.sql
,
function(err, results)
{
console.log("Results: " + JSON.stringify(results,null,2))
appDb.run("commit");
appDb.run("PRAGMA wal_checkpoint;")
returnResult(results)
})
})
})
var res = await getSqlResults
return res
}
|
Fix stacktrace.js always used even if disabled
`$config['use_stacktrace_js']` is always defined, `$config['use_stacktrace_js']['enabled']` must be tested instead. | <?php
namespace Nelmio\JsLoggerBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class NelmioJsLoggerExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$levels = array_map(function ($level) {
return strtolower($level);
}, $config['allowed_levels']);
$container->setParameter('nelmio_js_logger.allowed_levels', $levels);
$container->setParameter('nelmio_js_logger.ignore_messages', $config['ignore_messages']);
$container->setParameter('nelmio_js_logger.ignore_url_prefixes', $config['ignore_url_prefixes']);
if ($config['use_stacktrace_js']['enabled']) {
$container->setParameter('nelmio_js_logger.stacktrace_js_path', $config['use_stacktrace_js']['path']);
} else {
$container->setParameter('nelmio_js_logger.stacktrace_js_path', null);
}
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
| <?php
namespace Nelmio\JsLoggerBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class NelmioJsLoggerExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$levels = array_map(function ($level) {
return strtolower($level);
}, $config['allowed_levels']);
$container->setParameter('nelmio_js_logger.allowed_levels', $levels);
$container->setParameter('nelmio_js_logger.ignore_messages', $config['ignore_messages']);
$container->setParameter('nelmio_js_logger.ignore_url_prefixes', $config['ignore_url_prefixes']);
if (isset($config['use_stacktrace_js'])) {
$container->setParameter('nelmio_js_logger.stacktrace_js_path', $config['use_stacktrace_js']['path']);
} else {
$container->setParameter('nelmio_js_logger.stacktrace_js_path', null);
}
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
|
Fix fetchAll yet again - getting sloppy here | <?php
class Model_Tag extends Model_Record
{
protected $_user;
protected function _getTable() { return 'tags'; }
protected function _getTableIdFieldname() { return 'tag_id'; }
protected function _getColumns()
{
return array('tag_text');
}
/**
* @var Model_LocalConfig
*/
protected $_localConfig;
public function __construct(Model_LocalConfig $config)
{
$this->_localConfig = $config;
}
public function getTagText() { return $this->get('tag_text'); }
public function fetchByPostId($postId)
{
$query = $this->_localConfig->database()->select()
->from($this->_getTable())
->joinLeft(
'post_tag',
"post_tag.post_id = $postId AND post_tag.tag_id = tags.tag_id",
array()
)
->where('post_tag.post_tag_id IS NOT NULL')
->order('tags.tag_text ASC');
$rows = $this->_localConfig->database()->fetchAll($query);
$models = array();
foreach ($rows as $row) {
$model = $this->_getContainer()->Tag()->setData($row);
$models[] = $model;
}
return $models;
}
public function fetchAll()
{
$rows = parent::fetchAll();
$models = array();
foreach ($rows as $row) {
$model = $this->_getContainer()->Tag()->setData($row);
$models[] = $model;
}
return $models;
}
} | <?php
class Model_Tag extends Model_Record
{
protected $_user;
protected function _getTable() { return 'tags'; }
protected function _getTableIdFieldname() { return 'tag_id'; }
protected function _getColumns()
{
return array('tag_text');
}
/**
* @var Model_LocalConfig
*/
protected $_localConfig;
public function __construct(Model_LocalConfig $config)
{
$this->_localConfig = $config;
}
public function getTagText() { return $this->get('tag_text'); }
public function fetchByPostId($postId)
{
$query = $this->_localConfig->database()->select()
->from($this->_getTable())
->joinLeft(
'post_tag',
"post_tag.post_id = $postId AND post_tag.tag_id = tags.tag_id",
array()
)
->where('post_tag.post_tag_id IS NOT NULL')
->order('tags.tag_text ASC');
$rows = $this->_localConfig->database()->fetchAll($query);
$models = array();
foreach ($rows as $row) {
$model = $this->_getContainer()->Tag()->setData($row);
$models[] = $model;
}
return $models;
}
public function fetchAll($postId)
{
$rows = parent::fetchAll();
$models = array();
foreach ($rows as $row) {
$model = $this->_getContainer()->Tag()->setData($row);
$models[] = $model;
}
return $models;
}
} |
Revert "dependency removed from bundle test"
This reverts commit 119a99ec1947f49803e913e0220a1edc633feb6e. | <?php
namespace Devhelp\PiwikBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class DevhelpPiwikBundleTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DevhelpPiwikBundle
*/
private $bundle;
/**
* @var ContainerBuilder
*/
private $container;
protected function setUp()
{
$this->container = new ContainerBuilder();
$this->bundle = new DevhelpPiwikBundle();
}
/**
* @test
*/
public function it_adds_compiler_passes_to_the_container()
{
$this->when_bundle_is_built();
$this->then_compiler_passes_are_added();
}
private function when_bundle_is_built()
{
$this->bundle->build($this->container);
}
private function then_compiler_passes_are_added()
{
$passes = $this->container->getCompiler()->getPassConfig()->getBeforeOptimizationPasses();
$classes = array_map(function ($pass) {
return get_class($pass);
}, $passes);
$expectedPassClasses = array(
'Devhelp\PiwikBundle\DependencyInjection\Compiler\AddPiwikClientDefinition',
'Devhelp\PiwikBundle\DependencyInjection\Compiler\InsertParamsServices'
);
$this->assertEquals($expectedPassClasses, $classes);
}
}
| <?php
namespace Devhelp\PiwikBundle;
class DevhelpPiwikBundleTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DevhelpPiwikBundle
*/
private $bundle;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $container;
protected function setUp()
{
$this->container = $this
->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
->disableOriginalConstructor()
->getMock();
$this->bundle = new DevhelpPiwikBundle();
}
/**
* @test
*/
public function it_adds_compiler_passes()
{
$this->it_adds_compiler_passes_to_the_container();
$this->when_bundle_is_built();
}
private function when_bundle_is_built()
{
$this->bundle->build($this->container);
}
private function it_adds_compiler_passes_to_the_container()
{
$this->container
->expects($this->at(0))
->method('addCompilerPass')
->with($this->callback(function ($object) {
return get_class($object) == 'Devhelp\PiwikBundle\DependencyInjection\Compiler\AddPiwikClientDefinition';
}));
$this->container
->expects($this->at(1))
->method('addCompilerPass')
->with($this->callback(function ($object) {
return get_class($object) == 'Devhelp\PiwikBundle\DependencyInjection\Compiler\InsertParamsServices';
}));
}
}
|
Add small test for crop parameter to pipe | import os
import pytest
import tempfile
import pandas
from skan import pipe
@pytest.fixture
def image_filename():
rundir = os.path.abspath(os.path.dirname(__file__))
datadir = os.path.join(rundir, 'data')
return os.path.join(datadir, 'retic.tif')
def test_pipe(image_filename):
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight')
assert type(data[0]) == pandas.DataFrame
assert data[0].shape[0] > 0
data2 = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight', crop_radius=75)[0]
assert data2.shape[0] < data[0].shape[0]
def test_pipe_figure(image_filename):
with tempfile.TemporaryDirectory() as tempdir:
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight',
save_skeleton='skeleton-plot-',
output_folder=tempdir)
expected_output = os.path.join(tempdir, 'skeleton-plot-' +
os.path.basename(image_filename)[:-4] +
'.png')
assert os.path.exists(expected_output)
assert type(data[0]) == pandas.DataFrame
assert data[0].shape[0] > 0
| import os
import pytest
import tempfile
import pandas
from skan import pipe
@pytest.fixture
def image_filename():
rundir = os.path.abspath(os.path.dirname(__file__))
datadir = os.path.join(rundir, 'data')
return os.path.join(datadir, 'retic.tif')
def test_pipe(image_filename):
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight')
assert type(data[0]) == pandas.DataFrame
assert data[0].shape[0] > 0
def test_pipe_figure(image_filename):
with tempfile.TemporaryDirectory() as tempdir:
data = pipe.process_images([image_filename], 'fei', 5e-8, 0.1, 0.075,
'Scan/PixelHeight',
save_skeleton='skeleton-plot-',
output_folder=tempdir)
expected_output = os.path.join(tempdir, 'skeleton-plot-' +
os.path.basename(image_filename)[:-4] +
'.png')
assert os.path.exists(expected_output)
assert type(data[0]) == pandas.DataFrame
assert data[0].shape[0] > 0
|
Fix fade of slickslider clashing with bootstrap 4 | /**
* global: jsFrontend
*/
(function ($) {
/**
* Create responsive media slider, which uses "slick" slider
*/
$.fn.mediaLibrarySlider = function () {
// loop for all sliders
return this.each(function () {
// define slider
var $slider = $(this)
// define show controls or not
var showControls = $slider.data('show-controls')
var showPager = $slider.data('show-pager')
// we have multiple items
var multipleItems = ($slider.find('div').length > 1)
// we only have one item, hide controls
if (!multipleItems) {
showControls = false
showPager = false
}
// init slick slider
$slider.find('.widget-body').show().slick({
arrows: showControls,
autoplay: multipleItems,
adaptiveHeight: true,
dots: showPager,
// fade: true, // this has side effects in bootstrap 4 because of the .fade class, if you enable this don't forget to add extra styling for this
lazyLoad: 'ondemand',
mobileFirst: true
})
})
}
})(jQuery)
/**
* MediaLibrary slider
*/
jsFrontend.mediaLibrarySlider = {
init: function () {
var $sliders = $('.widget-media-library-slider')
// when no items for slider found, stop here
if ($sliders.length === 0) {
return false
}
// init sliders
$sliders.mediaLibrarySlider()
}
}
$(jsFrontend.mediaLibrarySlider.init)
| /**
* global: jsFrontend
*/
(function ($) {
/**
* Create responsive media slider, which uses "slick" slider
*/
$.fn.mediaLibrarySlider = function () {
// loop for all sliders
return this.each(function () {
// define slider
var $slider = $(this)
// define show controls or not
var showControls = $slider.data('show-controls')
var showPager = $slider.data('show-pager')
// we have multiple items
var multipleItems = ($slider.find('div').length > 1)
// we only have one item, hide controls
if (!multipleItems) {
showControls = false
showPager = false
}
// init slick slider
$slider.find('.widget-body').show().slick({
arrows: showControls,
autoplay: multipleItems,
adaptiveHeight: true,
dots: showPager,
fade: true,
lazyLoad: 'ondemand',
mobileFirst: true
})
})
}
})(jQuery)
/**
* MediaLibrary slider
*/
jsFrontend.mediaLibrarySlider = {
init: function () {
var $sliders = $('.widget-media-library-slider')
// when no items for slider found, stop here
if ($sliders.length === 0) {
return false
}
// init sliders
$sliders.mediaLibrarySlider()
}
}
$(jsFrontend.mediaLibrarySlider.init)
|
Add full calendar for staff | <div id="sidebar">
<ul class="clearfix">
<li class="help"><a href="#">Help</a></li>
<li><a href="/">Upcoming Visits</a>
<?php if ($this->staff): ?>
<ul>
<li><a href="/dc">Calendar</a></li>
</ul>
<?php endif; ?>
</li>
<li><a href="/cell">Unit Cell Search</a>
<?php if ($this->staff): ?>
<ul>
<li><a href="/cell/batch">PDB vs Unit Cell</a></li>
</ul>
<?php endif; ?>
</li>
<li><a href="/proposal">Proposals</a></li>
<li>
<span class="current" title="Click to change the currently selected proposal"><?php echo $prop ?></span>
<?php if ($prop): ?>
<ul>
<li><a href="/proposal/visits">Visits</a></li>
<li><a href="/dc/proposal">Calendar</a></li>
<li><a href="/samples/proposal">Prepare Experiment</a></li>
<li><a href="/shipment">Shipments</a></li>
<li><a href="/sample">Samples</a></li>
<li><a href="/sample/proteins">Proteins</a></li>
<li><a href="/contact">Lab Contacts</a></li>
<li><a href="/vstat/proposal">Statistics</a></li>
</ul>
<?php endif; ?>
</li>
</ul>
<a class="pull">Menu</a>
</div> | <div id="sidebar">
<ul class="clearfix">
<li class="help"><a href="#">Help</a></li>
<li><a href="/">Upcoming Visits</a></li>
<li><a href="/cell">Unit Cell Search</a>
<?php if ($this->staff): ?>
<ul>
<li><a href="/cell/batch">PDB vs Unit Cell</a>
</ul>
<?php endif; ?>
</li>
<li><a href="/proposal">Proposals</a></li>
<li>
<span class="current" title="Click to change the currently selected proposal"><?php echo $prop ?></span>
<?php if ($prop): ?>
<ul>
<li><a href="/proposal/visits">Visits</a></li>
<li><a href="/dc/proposal">Calendar</a></li>
<li><a href="/samples/proposal">Prepare Experiment</a></li>
<li><a href="/shipment">Shipments</a></li>
<li><a href="/sample">Samples</a></li>
<li><a href="/sample/proteins">Proteins</a></li>
<li><a href="/contact">Lab Contacts</a></li>
<li><a href="/vstat/proposal">Statistics</a></li>
</ul>
<?php endif; ?>
</li>
</ul>
<a class="pull">Menu</a>
</div> |
Fix create dashboard not working | import React from 'react'
import Modal from 'app/components/modal'
import Flash from 'app/flash'
import i18n from 'app/utils/i18n'
import rpc from 'app/rpc'
class CreateDashboard extends React.Component{
handleCreateDashboard(){
const props = this.props
let name = this.refs.name.value
rpc.call("dashboard.create", {
project: props.project,
name: name
}).then( () => props.onClose() )
.catch( e => {
console.error(e)
Flash.error("Could not create the dashboard. Check the logs.")
})
}
render(){
const props = this.props
return (
<Modal>
<div className="ui top secondary serverboards menu">
<h3 className="ui header">Create new dashboard</h3>
</div>
<div className="ui text container with padding">
<div className="ui form">
<div className="ui field">
<label>{i18n("Dashboard name")}</label>
<input type="text" className="input" ref="name" placeholder={i18n("Monitoring, tools...")}/>
</div>
<button className="ui button yellow" onClick={this.handleCreateDashboard.bind(this)}>
{i18n("Create dashboard")}
</button>
</div>
</div>
</Modal>
)
}
}
export default CreateDashboard
| import React from 'react'
import Modal from 'app/components/modal'
import Flash from 'app/flash'
import i18n from 'app/utils/i18n'
import rpc from 'app/rpc'
class CreateDashboard extends React.Component{
handleCreateDashboard(){
const props = this.props
let name = this.refs.name.value
rpc.call("dashboard.create", {
project: props.project,
name: name
}).then( () => props.onClose() )
.catch( e => {
console.error(e)
Flash.error("Could not create the dashboard. Check the logs.")
})
}
render(){
const props = this.props
return (
<Modal>
<div className="ui top secondary serverboards menu">
<h3 className="ui header">Create new dashboard</h3>
</div>
<div className="ui text container with padding">
<div className="ui form">
<div className="ui field">
<label>{i18n("Dashboard name")}</label>
<input type="text" className="input" ref="name" placeholder={i18n("Monitoring, tools...")}/>
</div>
<button className="ui button yellow" onClick={this.handleCreateDashboard}>
{i18n("Create dashboard")}
</button>
</div>
</div>
</Modal>
)
}
}
export default CreateDashboard
|
Support in-addon and in-engine options | 'use strict';
module.exports = {
name: require('./package').name,
options: {
autoImport: {
webpack: {
module: {
rules: [
/* fixes issue with graphql-js's mjs entry */
/* see: https://github.com/graphql/graphql-js/issues/1272#issuecomment-393903706 */
{
test: /\.mjs$/,
include: /node_modules\/graphql/,
type: 'javascript/auto',
},
],
},
externals: {
react: 'react',
},
},
},
},
included(app) {
this._super.included.apply(this, arguments);
this.app = app;
},
getOptions() {
const hostOptions =
(this.parent && this.parent.options) ||
(this.app && this.app.options) ||
{};
return (
hostOptions.emberApolloClient || {
keepGraphqlFileExtension: true,
}
);
},
setupPreprocessorRegistry(type, registry) {
const options = this.getOptions();
if (type === 'parent') {
registry.add('js', {
name: require('./package').name,
ext: 'graphql',
toTree(tree) {
const GraphQLFilter = require('broccoli-graphql-filter');
return new GraphQLFilter(tree, {
keepExtension: options.keepGraphqlFileExtension,
});
},
});
}
},
};
| 'use strict';
module.exports = {
name: require('./package').name,
options: {
autoImport: {
webpack: {
module: {
rules: [
/* fixes issue with graphql-js's mjs entry */
/* see: https://github.com/graphql/graphql-js/issues/1272#issuecomment-393903706 */
{
test: /\.mjs$/,
include: /node_modules\/graphql/,
type: 'javascript/auto',
},
],
},
externals: {
react: 'react',
},
},
},
},
included(app) {
this._super.included.apply(this, arguments);
this.app = app;
},
getOptions() {
return (
(this.app && this.app.options.emberApolloClient) || {
keepGraphqlFileExtension: true,
}
);
},
setupPreprocessorRegistry(type, registry) {
let getOptions = this.getOptions.bind(this);
let options = getOptions();
if (type === 'parent') {
registry.add('js', {
name: require('./package').name,
ext: 'graphql',
toTree(tree) {
const GraphQLFilter = require('broccoli-graphql-filter');
return new GraphQLFilter(tree, {
keepExtension: options.keepGraphqlFileExtension,
});
},
});
}
},
};
|
Allow protocol to also be specified. | 'use strict';
var request = require('../request')
;
var token = {};
var Authenticatable = {
token: {
get: function () {
return token;
}
},
authenticate: {
value: function (user, password) {
if (!user) {
throw {
name: 'ArgumentError',
message: user + ' is not a valid username'
};
}
if (!password) {
throw {
name: 'ArgumentError',
message: password + ' is not a valid password'
};
}
console.log(this.auth)
console.log(this.host)
console.log(this.auth.port)
console.log(this.path)
return request({
method: 'post',
protocol: this.auth.protocol || 'https:',
host: this.auth.host || this.host,
port: this.auth.port || 9100,
path: this.path,
withCredentials: false,
headers: {
'content-type': 'application/json'
},
rejectUnauthorized: this.rejectUnauthorized,
auth: [user, password].join(':')
}).then(function (res) {
if (res.statusCode !== 201) {
throw {
name: 'APIError',
status: res.statusCode,
message: res.body.faultstring || res.body
};
}
token = res.body;
return res.body;
});
}
}
};
module.exports = Authenticatable;
| 'use strict';
var request = require('../request')
;
var token = {};
var Authenticatable = {
token: {
get: function () {
return token;
}
},
authenticate: {
value: function (user, password) {
if (!user) {
throw {
name: 'ArgumentError',
message: user + ' is not a valid username'
};
}
if (!password) {
throw {
name: 'ArgumentError',
message: password + ' is not a valid password'
};
}
return request({
method: 'post',
protocol: 'https:',
host: this.auth.host || this.host,
port: this.auth.port || 9100,
path: this.path,
withCredentials: false,
headers: {
'content-type': 'application/json'
},
rejectUnauthorized: this.rejectUnauthorized,
auth: [user, password].join(':')
}).then(function (res) {
if (res.statusCode !== 201) {
throw {
name: 'APIError',
status: res.statusCode,
message: res.body.faultstring || res.body
};
}
token = res.body;
return res.body;
});
}
}
};
module.exports = Authenticatable;
|
Fix to account for casing diffs between Mac OS X and Linux | from django.test import TestCase
from core import utils
class SlugifyOC(TestCase):
def test_oc_slugify(self):
lst = (
('test.this.value', 'test-this-value'),
('Plone.OpenComparison', 'plone-opencomparison'),
('Run from here', 'run-from-here'),
('Jump_the shark', 'jump_the-shark'),
)
for l in lst:
self.assertEquals(utils.oc_slugify(l[0]), l[1])
class GetPypiUrl(TestCase):
def test_get_pypi_url_success(self):
lst = (
('django', 'http://pypi.python.org/pypi/django'),
('Django Uni Form', 'http://pypi.python.org/pypi/django-uni-form'),
)
for l in lst:
self.assertEquals(utils.get_pypi_url(l[0].lower()), l[1].lower())
def test_get_pypi_url_fail(self):
lst = (
'ColdFusion is not here',
'php is not here'
)
for l in lst:
self.assertEquals(utils.get_pypi_url(l), None)
| from django.test import TestCase
from core import utils
class SlugifyOC(TestCase):
def test_oc_slugify(self):
lst = (
('test.this.value', 'test-this-value'),
('Plone.OpenComparison', 'plone-opencomparison'),
('Run from here', 'run-from-here'),
('Jump_the shark', 'jump_the-shark'),
)
for l in lst:
self.assertEquals(utils.oc_slugify(l[0]), l[1])
class GetPypiUrl(TestCase):
def test_get_pypi_url_success(self):
lst = (
('django', 'http://pypi.python.org/pypi/django'),
('Django Uni Form', 'http://pypi.python.org/pypi/django-uni-form'),
)
for l in lst:
self.assertEquals(utils.get_pypi_url(l[0]), l[1])
def test_get_pypi_url_fail(self):
lst = (
'ColdFusion is not here',
'php is not here'
)
for l in lst:
self.assertEquals(utils.get_pypi_url(l), None)
|
Use empty value with grid | <?php
declare(strict_types=1);
namespace Psi\Component\Grid\Filter;
use Psi\Component\Grid\FilterInterface;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Expression;
use Psi\Component\ObjectAgent\Query\Query;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class BooleanFilter implements FilterInterface
{
const CHOICE_ANY = 'any';
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('value', ChoiceType::class, [
'choices' => [
1 => 'yes',
0 => 'no',
],
'empty_value' => self::CHOICE_ANY
]);
}
/**
* {@inheritdoc}
*/
public function isApplicable(array $filterData): bool
{
return isset($filterData['value']);
}
/**
* {@inheritdoc}
*/
public function getExpression(string $fieldName, array $data): Expression
{
return Query::comparison(
Comparison::EQUALS,
$fieldName,
$data['value']
);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $options)
{
}
}
| <?php
declare(strict_types=1);
namespace Psi\Component\Grid\Filter;
use Psi\Component\Grid\FilterInterface;
use Psi\Component\ObjectAgent\Query\Comparison;
use Psi\Component\ObjectAgent\Query\Expression;
use Psi\Component\ObjectAgent\Query\Query;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class BooleanFilter implements FilterInterface
{
const CHOICE_ANY = 'any';
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('value', ChoiceType::class, [
'choices' => [
self::CHOICE_ANY => 'any',
1 => 'yes',
0 => 'no',
],
]);
}
/**
* {@inheritdoc}
*/
public function isApplicable(array $filterData): bool
{
return self::CHOICE_ANY !== $filterData['value'];
}
/**
* {@inheritdoc}
*/
public function getExpression(string $fieldName, array $data): Expression
{
return Query::comparison(
Comparison::EQUALS,
$fieldName,
$data['value']
);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $options)
{
}
}
|
Add README as long_description to package | from setuptools import setup
with open("README.md", 'r') as f:
long_description = f.read()
setup(name='fortdepend',
version='0.1.0',
description='Automatically generate Fortran dependencies',
long_description=long_description,
long_description_content_type="test/markdown",
author='Peter Hill',
author_email='[email protected]',
url='https://github.com/ZedThree/fort_depend.py/',
download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Fortran',
],
packages=['fortdepend'],
install_requires=[
'colorama >= 0.3.9',
'pcpp >= 1.1.0'
],
extras_require={
'tests': ['pytest >= 3.3.0'],
'docs': [
'sphinx >= 1.4',
'sphinx-argparse >= 0.2.3'
],
},
keywords=['build', 'dependencies', 'fortran'],
entry_points={
'console_scripts': [
'fortdepend = fortdepend.__main__:main',
],
},
)
| from setuptools import setup
setup(name='fortdepend',
version='0.1.0',
description='Automatically generate Fortran dependencies',
author='Peter Hill',
author_email='[email protected]',
url='https://github.com/ZedThree/fort_depend.py/',
download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Fortran',
],
packages=['fortdepend'],
install_requires=[
'colorama >= 0.3.9',
'pcpp >= 1.1.0'
],
extras_require={
'tests': ['pytest >= 3.3.0'],
'docs': [
'sphinx >= 1.4',
'sphinx-argparse >= 0.2.3'
],
},
keywords=['build', 'dependencies', 'fortran'],
entry_points={
'console_scripts': [
'fortdepend = fortdepend.__main__:main',
],
},
)
|
Verify job config is not deleted when scheduled job is deleted | <?php
namespace SimplyTestable\ApiBundle\Tests\Services\ScheduledJob\Delete;
use SimplyTestable\ApiBundle\Entity\ScheduledJob;
class SingleUserTest extends ServiceTest {
/**
* @var ScheduledJob
*/
private $scheduledJob;
public function setUp() {
parent::setUp();
$user = $this->createAndActivateUser('[email protected]');
$jobConfiguration = $this->createJobConfiguration([
'label' => 'foo',
'parameters' => 'parameters',
'type' => 'Full site',
'website' => 'http://example.com/',
'task_configuration' => [
'HTML validation' => []
],
], $user);
$this->scheduledJob = $this->getScheduledJobService()->create(
$jobConfiguration,
'* * * * *',
true
);
$this->getScheduledJobService()->delete($this->scheduledJob);
}
public function testCronJobIsDeleted() {
$this->assertNull($this->scheduledJob->getCronJob()->getId());
}
public function testScheduledJobIsDeleted() {
$this->assertNull($this->scheduledJob->getId());
}
public function testJobConfigurationIsNotDeleted() {
$this->assertNotNull($this->scheduledJob->getJobConfiguration()->getId());
}
} | <?php
namespace SimplyTestable\ApiBundle\Tests\Services\ScheduledJob\Delete;
use SimplyTestable\ApiBundle\Entity\ScheduledJob;
class SingleUserTest extends ServiceTest {
/**
* @var ScheduledJob
*/
private $scheduledJob;
public function setUp() {
parent::setUp();
$user = $this->createAndActivateUser('[email protected]');
$jobConfiguration = $this->createJobConfiguration([
'label' => 'foo',
'parameters' => 'parameters',
'type' => 'Full site',
'website' => 'http://example.com/',
'task_configuration' => [
'HTML validation' => []
],
], $user);
$this->scheduledJob = $this->getScheduledJobService()->create(
$jobConfiguration,
'* * * * *',
true
);
$this->getScheduledJobService()->delete($this->scheduledJob);
}
public function testCronJobIsDeleted() {
$this->assertNull($this->scheduledJob->getCronJob()->getId());
}
public function testScheduledJobIsDeleted() {
$this->assertNull($this->scheduledJob->getId());
}
} |
Use get_the_archive_title() for archive pages | <?php
$page_title = '';
$page_subtitle = '';
if (is_author()) :
$page_title = __('Content by:', 'keitaro');
elseif (is_search()):
global $wp_query;
$page_title = __('Search results:', 'keitaro') . ' ' . highlight(get_search_query());
$page_subtitle = __('Found', 'keitaro') . ' ' . highlight($wp_query->found_posts) . ' ' . __('search results', 'keitaro');
elseif (is_archive()) :
$page_title = get_the_archive_title();
endif;
if (!empty($page_title)) :
?>
<header class="page-header">
<div class="row">
<div class="col-md-8">
<?php if ($page_title): ?>
<h1 class="page-title"><?php echo $page_title; ?></h1>
<?php endif; ?>
<?php if ($page_subtitle): ?>
<p class="lead"><?php echo $page_subtitle; ?></p>
<?php
endif;
keitaro_posted_on();
if (is_author()) :
keitaro_author_box(get_the_author_meta('ID'));
endif;
?>
</div>
</div>
</header>
<?php
endif; | <?php
$page_title = '';
$page_subtitle = '';
if (is_author()) :
$page_title = __('Content by:', 'keitaro');
elseif (is_search()):
global $wp_query;
$page_title = __('Search results:', 'keitaro') . ' ' . highlight(get_search_query());
$page_subtitle = __('Found', 'keitaro') . ' ' . highlight($wp_query->found_posts) . ' ' . __('search results', 'keitaro');
elseif (is_archive()) :
$page_title = single_cat_title(__('Archive:', 'keitaro') . ' ', false);
endif;
if (!empty($page_title)) :
?>
<header class="page-header">
<div class="row">
<div class="col-md-8">
<?php if ($page_title): ?>
<h1 class="page-title"><?php echo $page_title; ?></h1>
<?php endif; ?>
<?php if ($page_subtitle): ?>
<p class="lead"><?php echo $page_subtitle; ?></p>
<?php
endif;
keitaro_posted_on();
if (is_author()) :
keitaro_author_box(get_the_author_meta('ID'));
endif;
?>
</div>
</div>
</header>
<?php
endif;
|
Refactor filter out none to method | import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
transposed_square = [''.join(row) for row in transposed_matrix]
return transposed_square
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
| import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
joined_matrix = [''.join([x for x in row if x is not None]) for row in transposed_matrix]
return joined_matrix
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
def encode(msg):
return CryptoSquare.encode(msg)
|
Add a shortcut method on node to add to frame | (function () {
"use strict";
var Frame = function (elem) {
if (typeof elem === 'string') {
elem = document.getElementById(elem);
}
var height = elem.scrollHeight;
var width = elem.scrollWidth;
var viewAngle = 45;
var aspect = width / (1.0 * height);
var near = 0.1;
var far = 10000;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
this.camera.position.z = 10;
this.scene.add(this.camera);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(width, height);
elem.appendChild(this.renderer.domElement);
};
window.Frame = Frame;
Frame.prototype.addNode = function (node) {
this.scene.add(node.mesh);
};
Frame.prototype.render = function () {
this.renderer.render(this.scene, this.camera);
};
var Node = function (x, y, z) {
var geometry = new THREE.SphereGeometry(1, 4, 4);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
this.mesh = new THREE.Mesh(geometry, material);
this.mesh.position = {x: x, y: y, z: z};
};
window.Node = Node;
Node.prototype.addTo = function (frame) {
frame.addNode(this);
};
}());
| (function () {
"use strict";
var Frame = function (elem) {
if (typeof elem === 'string') {
elem = document.getElementById(elem);
}
var height = elem.scrollHeight;
var width = elem.scrollWidth;
var viewAngle = 45;
var aspect = width / (1.0 * height);
var near = 0.1;
var far = 10000;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
this.camera.position.z = 10;
this.scene.add(this.camera);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(width, height);
elem.appendChild(this.renderer.domElement);
};
window.Frame = Frame;
Frame.prototype.addNode = function (node) {
this.scene.add(node.mesh);
};
Frame.prototype.render = function () {
this.renderer.render(this.scene, this.camera);
};
var Node = function (x, y, z) {
var geometry = new THREE.SphereGeometry(1, 4, 4);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00, wireframe: true});
this.mesh = new THREE.Mesh(geometry, material);
this.mesh.position = {x: x, y: y, z: z};
};
window.Node = Node;
}());
|
Fix example outside the admin | try:
from django.urls import reverse_lazy
except ImportError:
from django.core.urlresolvers import reverse_lazy
from django.forms import inlineformset_factory
from django.views import generic
from select2_many_to_many.forms import TForm
from select2_many_to_many.models import TModel
class UpdateView(generic.UpdateView):
model = TModel
form_class = TForm
template_name = 'select2_outside_admin.html'
success_url = reverse_lazy('select2_outside_admin')
formset_class = inlineformset_factory(
TModel,
TModel,
form=TForm,
extra=1,
fk_name='for_inline',
fields=('name', 'test')
)
def get_object(self):
return TModel.objects.first()
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid() and self.formset.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
result = super().form_valid(form)
self.formset.save()
return result
@property
def formset(self):
if '_formset' not in self.__dict__:
setattr(self, '_formset', self.formset_class(
self.request.POST if self.request.method == 'POST' else None,
instance=getattr(self, 'object', self.get_object()),
))
return self._formset
| try:
from django.urls import reverse_lazy
except ImportError:
from django.core.urlresolvers import reverse_lazy
from django.forms import inlineformset_factory
from django.views import generic
from select2_many_to_many.forms import TForm
from select2_many_to_many.models import TModel
class UpdateView(generic.UpdateView):
model = TModel
form_class = TForm
template_name = 'select2_outside_admin.html'
success_url = reverse_lazy('select2_outside_admin')
formset_class = inlineformset_factory(
TModel,
TModel,
form=TForm,
extra=1,
fk_name='for_inline',
fields=('name', 'test')
)
def get_object(self):
return TModel.objects.first()
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid() and self.formset.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
result = super().form_valid(form)
self.formset.save()
return result
@property
def formset(self):
if '_formset' not in self.__dict__:
setattr(self, '_formset', self.formset_class(
self.request.POST if self.request.method == 'POST' else None,
instance=getattr(self, 'object', self.get_object()),
))
return self._formset
|
Fix bug in changeling title fix - it used to remove some lines on the way... | import json
import logging
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_jsons, budget_jsons = inputs
for line in file(budget_jsons):
line = json.loads(line.strip())
budgets["%(year)s/%(code)s" % line] = line['title']
outfile = file(output,"w")
changed_num = 0
for line in file(changes_jsons):
line = json.loads(line.strip())
key = "%(year)s/%(budget_code)s" % line
title = budgets.get(key)
if title != None:
if title != line['budget_title']:
line['budget_title'] = title
changed_num += 1
else:
logging.error("Failed to find title for change with key %s" % key)
outfile.write(json.dumps(line,sort_keys=True)+"\n")
print "updated %d entries" % changed_num
| import json
import logging
if __name__ == "__main__":
input = sys.argv[1]
output = sys.argv[2]
processor = fix_changeline_budget_titles().process(input,output,[])
class fix_changeline_budget_titles(object):
def process(self,inputs,output):
out = []
budgets = {}
changes_jsons, budget_jsons = inputs
for line in file(budget_jsons):
line = json.loads(line.strip())
budgets["%(year)s/%(code)s" % line] = line['title']
outfile = file(output,"w")
changed_num = 0
for line in file(changes_jsons):
line = json.loads(line.strip())
key = "%(year)s/%(budget_code)s" % line
title = budgets.get(key)
if title != None:
if title != line['budget_title']:
line['budget_title'] = title
changed_num += 1
else:
logging.error("Failed to find title for change with key %s" % key)
raise Exception()
outfile.write(json.dumps(line,sort_keys=True)+"\n")
print "updated %d entries" % changed_num
|
Fix help message of --min_eval_frequency flag | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn(batch_inputs=True,
prepare_filename_queues=True,
distributed=False):
adder = FlagAdder()
for mode in [tf.contrib.learn.ModeKeys.TRAIN,
tf.contrib.learn.ModeKeys.EVAL]:
adder.add_flag("{}_steps".format(mode), type=int,
help="Maximum number of {} steps".format(mode))
adder.add_flag("min_eval_frequency", type=int, default=1,
help="Minimum evaluation frequency in number of train steps")
estimator = def_estimator(distributed)
def_train_input_fn = def_def_train_input_fn(batch_inputs,
prepare_filename_queues)
def_eval_input_fn = def_def_eval_input_fn(batch_inputs,
prepare_filename_queues)
def def_experiment_fn(model_fn, train_input_fn, eval_input_fn=None):
def experiment_fn(output_dir):
return tf.contrib.learn.Experiment(
estimator(model_fn, output_dir),
def_train_input_fn(train_input_fn),
def_eval_input_fn(eval_input_fn or train_input_fn),
**adder.flags)
return experiment_fn
return def_experiment_fn
| import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn(batch_inputs=True,
prepare_filename_queues=True,
distributed=False):
adder = FlagAdder()
for mode in [tf.contrib.learn.ModeKeys.TRAIN,
tf.contrib.learn.ModeKeys.EVAL]:
adder.add_flag("{}_steps".format(mode), type=int,
help="Maximum number of {} steps".format(mode))
adder.add_flag("min_eval_frequency", type=int, default=1,
help="Minimum evaluation frequency in number of model "
"savings")
estimator = def_estimator(distributed)
def_train_input_fn = def_def_train_input_fn(batch_inputs,
prepare_filename_queues)
def_eval_input_fn = def_def_eval_input_fn(batch_inputs,
prepare_filename_queues)
def def_experiment_fn(model_fn, train_input_fn, eval_input_fn=None):
def experiment_fn(output_dir):
return tf.contrib.learn.Experiment(
estimator(model_fn, output_dir),
def_train_input_fn(train_input_fn),
def_eval_input_fn(eval_input_fn or train_input_fn),
**adder.flags)
return experiment_fn
return def_experiment_fn
|
Make urlencode load properly in python 3. | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from .base import AuthenticationMixinBase
from . import GrantFailed
# We need to get urlencode from urllib.parse in Python 3, but fall back to
# urllib in Python 2
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
basestring
except NameError:
basestring = str
class AuthorizationCodeMixin(AuthenticationMixinBase):
"""Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, scope, redirect):
"""Get the url to direct a user to authenticate."""
url = self.API_ROOT + "/oauth/authorize?"
query = {
"response_type": "code",
"client_id": self.app_info[0]
}
if scope:
if not isinstance(scope, basestring):
scope = ' '.join(scope)
query['scope'] = scope
if redirect:
query['redirect_uri'] = redirect
return url + urlencode(query)
def exchange_code(self, code, redirect):
"""Perform the exchange step for the code from the redirected user."""
code, headers, resp = self.call_grant('/oauth/access_token',
{
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect
})
if not code == 200:
raise GrantFailed()
self.token = resp['access_token']
return self.token, resp['user'], resp['scope']
| #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
import urllib
from .base import AuthenticationMixinBase
from . import GrantFailed
try:
basestring
except NameError:
basestring = str
class AuthorizationCodeMixin(AuthenticationMixinBase):
"""Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, scope, redirect):
"""Get the url to direct a user to authenticate."""
url = self.API_ROOT + "/oauth/authorize?"
query = {
"response_type": "code",
"client_id": self.app_info[0]
}
if scope:
if not isinstance(scope, basestring):
scope = ' '.join(scope)
query['scope'] = scope
if redirect:
query['redirect_uri'] = redirect
return url + urllib.urlencode(query)
def exchange_code(self, code, redirect):
"""Perform the exchange step for the code from the redirected user."""
code, headers, resp = self.call_grant('/oauth/access_token',
{
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect
})
if not code == 200:
raise GrantFailed()
self.token = resp['access_token']
return self.token, resp['user'], resp['scope']
|
Handle app-name validation failures better. | from .command import Command
from ..api.errors import BadRequest
import logging
import sys
log = logging.getLogger(__name__)
class AppsCommand(Command):
"""
Manage Orchard apps.
Usage: apps COMMAND [ARGS...]
Commands:
ls List apps (default)
create Add a new app
rm Remove an app
"""
def parse(self, argv, global_options):
if len(argv) == 0:
argv = ['ls']
return super(AppsCommand, self).parse(argv, global_options)
def ls(self, options):
"""
List apps.
Usage: ls
"""
apps = self.api.apps
if apps:
for app in apps:
print app.name
else:
log.error("You don't have any apps yet. Run \"orchard apps create\" to create one.")
def create(self, options):
"""
Create a new app.
Usage: create NAME
"""
try:
app = self.api.apps.create({"name": options['NAME']})
except BadRequest as e:
name_errors = e.json.get('name', None)
if name_errors:
log.error("\n".join(name_errors))
else:
log.error(e.json)
sys.exit(1)
log.info("Created %s", app.name)
def rm(self, options):
"""
Remove an app.
Usage: rm NAME [NAME...]
"""
# TODO: handle unrecognised app name
for name in options['NAME']:
self.api.apps[name].delete()
log.info("Deleted %s", name)
| from .command import Command
from ..api.errors import BadRequest
import logging
import sys
log = logging.getLogger(__name__)
class AppsCommand(Command):
"""
Manage Orchard apps.
Usage: apps COMMAND [ARGS...]
Commands:
ls List apps (default)
create Add a new app
rm Remove an app
"""
def parse(self, argv, global_options):
if len(argv) == 0:
argv = ['ls']
return super(AppsCommand, self).parse(argv, global_options)
def ls(self, options):
"""
List apps.
Usage: ls
"""
apps = self.api.apps
if apps:
for app in apps:
print app.name
else:
log.error("You don't have any apps yet. Run \"orchard apps create\" to create one.")
def create(self, options):
"""
Create a new app.
Usage: create NAME
"""
# TODO: handle invalid or clashing app name
try:
app = self.api.apps.create({"name": options['NAME']})
except BadRequest as e:
log.error(e.json)
sys.exit(1)
log.info("Created %s", app.name)
def rm(self, options):
"""
Remove an app.
Usage: rm NAME [NAME...]
"""
# TODO: handle unrecognised app name
for name in options['NAME']:
self.api.apps[name].delete()
log.info("Deleted %s", name)
|
Use np.inf for max/min limit values | import random
import numpy as np
from ..player import Player
from ..utils import utility
class AlphaBeta(Player):
name = 'Alpha-Beta'
def __init__(self, eval_func=utility, max_depth=np.inf):
self._eval = eval_func
self._max_depth = max_depth
def __str__(self):
return self.name
def __repr__(self):
return self.name
def _ab(self, game, cur_depth, alpha, beta):
if game.is_over() or cur_depth == self._max_depth:
return None, self._eval(game, game.cur_player())
best_move = None
best_score = -np.inf
for move in game.legal_moves():
_, score = self._ab(game=game.copy().make_move(move),
cur_depth=cur_depth + 1,
alpha=-beta,
beta=-max(alpha, best_score))
score = -score
if score > best_score:
best_score = score
best_move = move
if best_score >= beta:
return best_move, best_score
return best_move, best_score
##########
# Player #
##########
def choose_move(self, game):
move, _ = self._ab(game, cur_depth=0, alpha=-np.inf, beta=np.inf)
return move
| import random
from ..player import Player
from ..utils import utility
class AlphaBeta(Player):
name = 'Alpha-Beta'
def __init__(self, eval_func=utility, max_depth=1000):
self._eval = eval_func
self._max_depth = max_depth
def __str__(self):
return self.name
def __repr__(self):
return self.name
def _ab(self, game, cur_depth, alpha, beta):
if game.is_over() or cur_depth == self._max_depth:
return None, self._eval(game, game.cur_player())
best_move = None
best_score = -100000000
for move in game.legal_moves():
_, score = self._ab(game=game.copy().make_move(move),
cur_depth=cur_depth + 1,
alpha=-beta,
beta=-max(alpha, best_score))
score = -score
if score > best_score:
best_score = score
best_move = move
if best_score >= beta:
return best_move, best_score
return best_move, best_score
##########
# Player #
##########
def choose_move(self, game):
move, _ = self._ab(game, cur_depth=0, alpha=-100000000, beta=100000000)
return move
|
Remove unnecessary table headers in tags page | import React, { Component, PropTypes } from 'react'
import { Table } from 'semantic-ui-react'
import TagTableRow from './TagTableRow'
const propTypes = {
dispatch: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
tagNames: PropTypes.array.isRequired,
tags: PropTypes.object.isRequired,
type: PropTypes.string.isRequired
}
class TagsTable extends Component {
render() {
const { dispatch, isAuthenticated, tags, tagNames, type } = this.props
const filteredTagNames = tagNames.filter(name => {
return tags[name].type === type
})
return (
<Table selectable unstackable compact>
<Table.Header>
<Table.Row>
<Table.HeaderCell colSpan={3}>
{type}
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{filteredTagNames.map((name, index) => (
<TagTableRow
key={index}
dispatch={dispatch}
isAuthenticated={isAuthenticated}
tag={tags[name]}
/>
))}
</Table.Body>
</Table>
)
}
}
TagsTable.propTypes = propTypes
export default TagsTable
| import React, { Component, PropTypes } from 'react'
import { Table } from 'semantic-ui-react'
import TagTableRow from './TagTableRow'
const propTypes = {
dispatch: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
tagNames: PropTypes.array.isRequired,
tags: PropTypes.object.isRequired,
type: PropTypes.string.isRequired
}
class TagsTable extends Component {
render() {
const { dispatch, isAuthenticated, tags, tagNames, type } = this.props
const filteredTagNames = tagNames.filter(name => {
return tags[name].type === type
})
return (
<Table selectable unstackable compact>
<Table.Header>
<Table.Row>
<Table.HeaderCell colSpan={3} textAlign="center">
{type}
</Table.HeaderCell>
</Table.Row>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Action</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{filteredTagNames.map((name, index) => (
<TagTableRow
key={index}
dispatch={dispatch}
isAuthenticated={isAuthenticated}
tag={tags[name]}
/>
))}
</Table.Body>
</Table>
)
}
}
TagsTable.propTypes = propTypes
export default TagsTable
|
Remove clean function of gulp default | var gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename'),
minifyCss = require('gulp-minify-css'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync').create();
gulp.task('dependencies', function() {
gulp.src('bower_components/normalize-css/normalize.css')
.pipe(rename('_normalize.scss'))
.pipe(gulp.dest('scss/libs'));
});
gulp.task('sass', function() {
gulp.src('scss/style.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 20 versions'],
cascade: false
}))
.pipe(gulp.dest('./css/'))
.pipe(minifyCss())
.pipe(rename('style.min.css'))
.pipe(gulp.dest('./css/'));
});
gulp.task('dist', function() {
gulp.src(['index.html'])
.pipe(gulp.dest('./'));
});
gulp.task('watch', function() {
browserSync.init({
server: "./"
});
gulp.watch('scss/**/*.scss', ['sass']).on('change', browserSync.reload);
gulp.watch('index.html', ['dist']).on('change', browserSync.reload);
gulp.watch('js/*.js', ['dist']).on('change', browserSync.reload);
});
gulp.task('default', ['dependencies', 'sass'], function() {
gulp.start('dist');
});
| var gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename'),
minifyCss = require('gulp-minify-css'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync').create();
gulp.task('dependencies', function() {
gulp.src('bower_components/normalize-css/normalize.css')
.pipe(rename('_normalize.scss'))
.pipe(gulp.dest('scss/libs'));
});
gulp.task('sass', function() {
gulp.src('scss/style.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 20 versions'],
cascade: false
}))
.pipe(gulp.dest('./css/'))
.pipe(minifyCss())
.pipe(rename('style.min.css'))
.pipe(gulp.dest('./css/'));
});
gulp.task('dist', function() {
gulp.src(['index.html'])
.pipe(gulp.dest('./'));
});
gulp.task('watch', function() {
browserSync.init({
server: "./"
});
gulp.watch('scss/**/*.scss', ['sass']).on('change', browserSync.reload);
gulp.watch('index.html', ['dist']).on('change', browserSync.reload);
gulp.watch('js/*.js', ['dist']).on('change', browserSync.reload);
});
gulp.task('default', ['clean', 'dependencies', 'sass'], function() {
gulp.start('dist');
});
|
Sort Gulp tasks in executing order | 'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var jsonlint = require("gulp-jsonlint");
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var plumber = require('gulp-plumber');
gulp.task('set-test-env', function(cb) {
process.env.NODE_ENV = 'test';
cb();
});
gulp.task('json', ['set-test-env'], function(cb) {
gulp.src(["**/*.json", "!./node_modules/**/*.json"])
.pipe(jsonlint())
.pipe(jsonlint.reporter());
cb();
});
gulp.task('static', function() {
gulp.src('source/*.js')
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('test', ['set-test-env'], function(cb) {
var mochaErr;
gulp.src('test/**/*.js')
.pipe(plumber())
.pipe(mocha({reporter: 'spec'}))
.on('error', function(err) {
mochaErr = err;
})
.pipe(istanbul.writeReports())
.on('end', function() {
cb(mochaErr);
});
});
gulp.task('default', ['set-test-env', 'json', 'static', 'test']);
| 'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var jsonlint = require("gulp-jsonlint");
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var plumber = require('gulp-plumber');
gulp.task('static', function() {
gulp.src('source/*.js')
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('json', ['set-test-env'], function(cb) {
gulp.src(["**/*.json", "!./node_modules/**/*.json"])
.pipe(jsonlint())
.pipe(jsonlint.reporter());
cb();
});
gulp.task('test', ['set-test-env'], function(cb) {
var mochaErr;
gulp.src('test/**/*.js')
.pipe(plumber())
.pipe(mocha({reporter: 'spec'}))
.on('error', function(err) {
mochaErr = err;
})
.pipe(istanbul.writeReports())
.on('end', function() {
cb(mochaErr);
});
});
gulp.task('set-test-env', function(cb) {
process.env.NODE_ENV = 'test';
cb();
});
gulp.task('default', ['set-test-env', 'json', 'static', 'test']);
|
Rename variable to javascriptExecutor in unit test | package com.saucelabs.common;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class SauceHelperTest {
private SauceHelper sauceHelper;
@Before
public void runBeforeEveryTest()
{
sauceHelper = new SauceHelper();
}
@Test
public void shouldReturnPassedForTrueResult()
{
assertStringsEqual("sauce:job-result=", true);
}
@Test
public void shouldReturnFailedForFalseResult()
{
assertStringsEqual("sauce:job-result=", false);
}
@Test
public void shouldReturnCorrectStringForTestName()
{
String testName = "MyTestName";
assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName));
}
@Test
public void shouldReturnSauceContextString()
{
String comment = "This is a comment";
assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment));
}
@Test
public void shouldRunExecuteStringMethodWithoutDefaultManagerSet()
{
JavaScriptInvokerManager javascriptExecutor = mock(JavaScriptInvokerManager.class);
JavaScriptInvokerFactory.setJavaScriptInvoker(javascriptExecutor);
sauceHelper.setTestStatus("pass");
verify(javascriptExecutor, times(1)).executeScript("sauce:job-result=pass");
}
private void assertStringsEqual(String s, boolean b) {
assertEquals(s + b, sauceHelper.getTestResultString(b));
}
}
| package com.saucelabs.common;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class SauceHelperTest {
private SauceHelper sauceHelper;
@Before
public void runBeforeEveryTest()
{
sauceHelper = new SauceHelper();
}
@Test
public void shouldReturnPassedForTrueResult()
{
assertStringsEqual("sauce:job-result=", true);
}
@Test
public void shouldReturnFailedForFalseResult()
{
assertStringsEqual("sauce:job-result=", false);
}
@Test
public void shouldReturnCorrectStringForTestName()
{
String testName = "MyTestName";
assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName));
}
@Test
public void shouldReturnSauceContextString()
{
String comment = "This is a comment";
assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment));
}
@Test
public void shouldRunExecuteStringMethodWithoutDefaultManagerSet()
{
JavaScriptInvokerManager mockCustomJsManager = mock(JavaScriptInvokerManager.class);
JavaScriptInvokerFactory.setJavaScriptInvoker(mockCustomJsManager);
sauceHelper.setTestStatus("pass");
verify(mockCustomJsManager, times(1)).executeScript("sauce:job-result=pass");
}
private void assertStringsEqual(String s, boolean b) {
assertEquals(s + b, sauceHelper.getTestResultString(b));
}
}
|
Call frame scripts immediately. This is just temporary for testing purposes. | function MovieClip() {
this.currentFrame = 0;
this.framesLoaded = 0;
this.totalFrames = 0;
this.trackAsMenu = false;
this.scenes = [];
this.currentScene = null;
this.currentLabel = null;
this.currentFrameLabel = null;
this.enabled = false;
this.isPlaying = false;
}
var p = MovieClip.prototype = new Sprite;
p.play = function () { notImplemented(); };
p.stop = function () { notImplemented(); };
p.nextFrame = function () { notImplemented(); };
p.prevFrame = function () { notImplemented(); };
p.gotoAndPlay = function (frame, scene) { notImplemented(); };
p.gotoAndStop = function (frame, scene) { notImplemented(); };
p.addFrameScript = function () {
arguments[1].call(this);
};
p.prevScene = function () { notImplemented(); };
p.nextScene = function () { notImplemented(); };
natives.MovieClipClass = function (scope, instance, baseClass) {
var c = new Class("MovieClip", MovieClip, Class.passthroughCallable(MovieClip));
c.baseClass = baseClass;
c.nativeMethods = p;
c.makeSimpleNativeAccessors("get", ["currentFrame",
"framesLoaded",
"totalFrames",
"trackAsMenu",
"scenes",
"currentScene",
"currentLabel",
"currentFrameLabel",
"enabled",
"isPlaying"]);
c.makeSimpleNativeAccessors("set", ["trackAsMenu", "enabled"]);
return c;
};
| function MovieClip() {
this.currentFrame = 0;
this.framesLoaded = 0;
this.totalFrames = 0;
this.trackAsMenu = false;
this.scenes = [];
this.currentScene = null;
this.currentLabel = null;
this.currentFrameLabel = null;
this.enabled = false;
this.isPlaying = false;
}
var p = MovieClip.prototype = new Sprite;
p.play = function () { notImplemented(); };
p.stop = function () { notImplemented(); };
p.nextFrame = function () { notImplemented(); };
p.prevFrame = function () { notImplemented(); };
p.gotoAndPlay = function (frame, scene) { notImplemented(); };
p.gotoAndStop = function (frame, scene) { notImplemented(); };
p.addFrameScript = function () { notImplemented(); };
p.prevScene = function () { notImplemented(); };
p.nextScene = function () { notImplemented(); };
natives.MovieClipClass = function (scope, instance, baseClass) {
var c = new Class("MovieClip", MovieClip, Class.passthroughCallable(MovieClip));
c.baseClass = baseClass;
c.nativeMethods = p;
c.makeSimpleNativeAccessors("get", ["currentFrame",
"framesLoaded",
"totalFrames",
"trackAsMenu",
"scenes",
"currentScene",
"currentLabel",
"currentFrameLabel",
"enabled",
"isPlaying"]);
c.makeSimpleNativeAccessors("set", ["trackAsMenu", "enabled"]);
return c;
};
|
Use get_or_create instead of catching exception | from django.core.management.base import BaseCommand
from utils.create_random_data import create_items, create_users, create_orders
from saleor.userprofile.models import User
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = r'saleor/static/placeholders/'
def add_arguments(self, parser):
parser.add_argument(
'--createsuperuser',
action='store_true',
dest='createsuperuser',
default=False,
help='Create admin account')
def handle(self, *args, **options):
for msg in create_items(self.placeholders_dir, 10):
self.stdout.write(msg)
for msg in create_users(10):
self.stdout.write(msg)
for msg in create_orders(20):
self.stdout.write(msg)
if options['createsuperuser']:
credentials = {'email': '[email protected]', 'password': 'admin'}
user, created = User.objects.get_or_create(
email=credentials['email'],
is_active=True, is_staff=True, is_superuser=True)
if created:
user.set_password(credentials['password'])
user.save()
self.stdout.write(
'Superuser - %(email)s/%(password)s' % credentials)
else:
self.stdout.write(
'Superuser already exists - %(email)s' % credentials)
| from django.core.management.base import BaseCommand
from django.db import IntegrityError
from utils.create_random_data import create_items, create_users, create_orders
from saleor.userprofile.models import User
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = r'saleor/static/placeholders/'
def add_arguments(self, parser):
parser.add_argument(
'--createsuperuser',
action='store_true',
dest='createsuperuser',
default=False,
help='Create admin account')
def handle(self, *args, **options):
for msg in create_items(self.placeholders_dir, 10):
self.stdout.write(msg)
for msg in create_users(10):
self.stdout.write(msg)
for msg in create_orders(20):
self.stdout.write(msg)
if options['createsuperuser']:
credentials = {'email': '[email protected]', 'password': 'admin'}
try:
User.objects.create_superuser(**credentials)
except IntegrityError:
self.stdout.write(
'Superuser already exists - %(email)s' % credentials)
else:
self.stdout.write(
'Superuser - %(email)s/%(password)s' % credentials)
|
Clean up how UI works | 'use strict';
var Q = require('q'),
scorer = require('./scorer'),
print = require('./board/print');
module.exports = {
play: function(board, player_x, player_o) {
var self = this;
return Q.promise(function(resolve) {
self
.get_play(board, player_x, player_o)
.then(function(choice) {
board.set(choice, scorer.turn(board));
if (scorer.is_over(board)) {
resolve();
} else {
resolve(self.play(board, player_x, player_o));
}
});
});
},
get_play: function(board, player_x, player_o) {
var current_player;
if (scorer.turn(board) === 'x') {
current_player = player_x;
} else {
current_player = player_o;
}
if (current_player.type === 'human') {
print.rows(board.horizontal_rows());
}
return current_player.play(board.empty_cells());
}
};
| 'use strict';
var Q = require('q'),
scorer = require('./scorer'),
print = require('./board/print');
module.exports = {
play: function(board, player_x, player_o) {
var self = this;
return Q.promise(function(resolve) {
self
.get_play(board, player_x, player_o)
.then(function(choice) {
board.set(choice, scorer.turn(board));
if (scorer.is_over(board)) {
resolve();
} else {
resolve(self.play(board, player_x, player_o));
}
});
});
},
get_play: function(board, player_x, player_o) {
var current_player;
print.rows(board.horizontal_rows()); // TODO this doesn't belong in get_play
if (scorer.turn(board) === 'x') {
current_player = player_x;
} else {
current_player = player_o;
}
return current_player.play(board.empty_cells());
}
};
|
CRM-2199: Create search handler for A/CI field autocomplete
-revert changes | <?php
namespace Oro\Bundle\MigrationBundle\Migration;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\MigrationBundle\Entity\DataFixture;
class UpdateDataFixturesFixture extends AbstractFixture
{
/**
* @var array
* key - class name
* value - current loaded version
*/
protected $dataFixturesClassNames;
/**
* Set a list of data fixtures to be updated
*
* @param array $classNames
*/
public function setDataFixtures($classNames)
{
$this->dataFixturesClassNames = $classNames;
}
/**
* @inheritdoc
*/
public function load(ObjectManager $manager)
{
if (!empty($this->dataFixturesClassNames)) {
$loadedAt = new \DateTime('now', new \DateTimeZone('UTC'));
foreach ($this->dataFixturesClassNames as $className => $version) {
$dataFixture = null;
if ($version !== null) {
$dataFixture = $manager
->getRepository('OroMigrationBundle:DataFixture')
->findOneBy(['className' => $className]);
}
if (!$dataFixture) {
$dataFixture = new DataFixture();
$dataFixture->setClassName($className);
}
$dataFixture
->setVersion($version)
->setLoadedAt($loadedAt);
$manager->persist($dataFixture);
}
$manager->flush();
}
}
}
| <?php
namespace Oro\Bundle\MigrationBundle\Migration;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\MigrationBundle\Entity\DataFixture;
class UpdateDataFixturesFixture extends AbstractFixture
{
/**
* @var array
* key - class name
* value - current loaded version
*/
protected $dataFixturesClassNames;
/**
* Set a list of data fixtures to be updated
*
* @param array $classNames
*/
public function setDataFixtures($classNames)
{
$this->dataFixturesClassNames = $classNames;
}
/**
* @inheritdoc
*/
public function load(ObjectManager $manager)
{return;
if (!empty($this->dataFixturesClassNames)) {
$loadedAt = new \DateTime('now', new \DateTimeZone('UTC'));
foreach ($this->dataFixturesClassNames as $className => $version) {
$dataFixture = null;
if ($version !== null) {
$dataFixture = $manager
->getRepository('OroMigrationBundle:DataFixture')
->findOneBy(['className' => $className]);
}
if (!$dataFixture) {
$dataFixture = new DataFixture();
$dataFixture->setClassName($className);
}
$dataFixture
->setVersion($version)
->setLoadedAt($loadedAt);
$manager->persist($dataFixture);
}
$manager->flush();
}
}
}
|
Add link to interest group info page | // @flow
import styles from './InterestGroup.css';
import React from 'react';
import InterestGroupComponent from './InterestGroup';
import Button from 'app/components/Button';
import { Content } from 'app/components/Content';
import { Link } from 'react-router';
import NavigationTab, { NavigationLink } from 'app/components/NavigationTab';
import type { InterestGroup } from 'app/models';
export type Props = {
interestGroups: Array<InterestGroup>,
loggedIn: boolean
};
const InterestGroupList = (props: Props) => {
const groups = props.interestGroups.map((group, key) => (
<InterestGroupComponent group={group} key={key} />
));
const showCreate = props.loggedIn;
return (
<Content>
<div className={styles.section}>
<div>
<NavigationTab title="Interessegrupper">
<NavigationLink to="">
<i className="fa fa-angle-left" /> Hjem
</NavigationLink>
</NavigationTab>
<p>
<Link to="/pages/info/39-praktisk-informasjon">Her</Link> finner du
all praktisk informasjon knyttet til våre interessegrupper.
</p>
{showCreate && (
<Link to="/interestgroups/create" className={styles.link}>
<Button>Lag ny interessegruppe</Button>
</Link>
)}
</div>
</div>
<div className="groups">{groups}</div>
</Content>
);
};
export default InterestGroupList;
| // @flow
import styles from './InterestGroup.css';
import React from 'react';
import InterestGroupComponent from './InterestGroup';
import Button from 'app/components/Button';
import { Content } from 'app/components/Content';
import { Link } from 'react-router';
import NavigationTab, { NavigationLink } from 'app/components/NavigationTab';
import type { InterestGroup } from 'app/models';
export type Props = {
interestGroups: Array<InterestGroup>,
loggedIn: boolean
};
const InterestGroupList = (props: Props) => {
const groups = props.interestGroups.map((group, key) => (
<InterestGroupComponent group={group} key={key} />
));
const showCreate = props.loggedIn;
return (
<Content>
<div className={styles.section}>
<div>
<NavigationTab title="Interessegrupper">
<NavigationLink to="">
<i className="fa fa-angle-left" /> Hjem
</NavigationLink>
</NavigationTab>
<p>
<strong>Her</strong> finner du all praktisk informasjon knyttet til
våre interessegrupper.
</p>
{showCreate && (
<Link to="/interestgroups/create" className={styles.link}>
<Button>Lag ny interessegruppe</Button>
</Link>
)}
</div>
</div>
<div className="groups">{groups}</div>
</Content>
);
};
export default InterestGroupList;
|
Allow use of Check-And-Set option and raise exception if status is 4xx or 5xx | import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if keys is not None:
params['keys'] = True
r = requests.get(url, params=params)
if r.status_code == 200:
return json.loads(r.text)
else:
r.raise_for_status()
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
def list(self, key=''):
return self._get(key, keys=True)
def set(self, key, value, cas=None):
params = dict()
if cas is not None:
params['cas'] = cas
r = requests.put(self._url + '/' + key, data=value, params=params)
if r.status_code == 200:
if re.match(r"true", r.text) is not None:
return True
elif re.match(r"false", r.text) is not None:
return False
else:
r.raise_for_status()
def delete(self, key, recurse=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
r = requests.delete(url, params=params)
r.raise_for_status()
| import json
import re
import requests
class KeyValue(object):
def __init__(self, url):
self._url = "%s/kv" % url
def _get(self, key, recurse=None, keys=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
if keys is not None:
params['keys'] = True
r = requests.get(url, params=params)
if r.status_code == 200:
return json.loads(r.text)
else:
return None
def get(self, key, recurse=None):
return self._get(key, recurse=recurse)
def list(self, key=''):
return self._get(key, keys=True)
def set(self, key, value):
r = requests.put(self._url + '/' + key, data=value)
if r.status_code == 200 and re.match(r"true", r.text) is not None:
return True
else:
return False
def delete(self, key, recurse=None):
url = self._url + '/' + key
params = dict()
if recurse is not None:
params['recurse'] = True
requests.delete(url, params=params)
|
Remove docblock injected by phpstorm | <?php
namespace PhpXmlRpc\Helper;
class Logger
{
protected static $instance = null;
/**
* This class is singleton, so that later we can move to DI patterns.
*
* @return Logger
*/
public static function instance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Echoes a debug message, taking care of escaping it when not in console mode.
* NB: if the encoding of the message is not known or wrong, and we are working in web mode, there is no guarantee
* of 100% accuracy, which kind of defeats the purpose of debugging
*
* @param string $message
* @param string $encoding
*/
public function debugMessage($message, $encoding=null)
{
// US-ASCII is a warning for PHP and a fatal for HHVM
if ($encoding == 'US-ASCII') {
$encoding = 'UTF-8';
}
if (PHP_SAPI != 'cli') {
$flags = ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE;
if ($encoding != null) {
print "<PRE>\n".htmlentities($message, $flags, $encoding)."\n</PRE>";
} else {
print "<PRE>\n".htmlentities($message, $flags)."\n</PRE>";
}
} else {
print "\n$message\n";
}
// let the user see this now in case there's a time out later...
flush();
}
} | <?php
/**
* Created by PhpStorm.
* User: gg
* Date: 12/04/2015
* Time: 12:11
*/
namespace PhpXmlRpc\Helper;
class Logger
{
protected static $instance = null;
/**
* This class is singleton, so that later we can move to DI patterns.
*
* @return Logger
*/
public static function instance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Echoes a debug message, taking care of escaping it when not in console mode.
* NB: if the encoding of the message is not known or wrong, and we are working in web mode, there is no guarantee
* of 100% accuracy, which kind of defeats the purpose of debugging
*
* @param string $message
* @param string $encoding
*/
public function debugMessage($message, $encoding=null)
{
// US-ASCII is a warning for PHP and a fatal for HHVM
if ($encoding == 'US-ASCII') {
$encoding = 'UTF-8';
}
if (PHP_SAPI != 'cli') {
$flags = ENT_COMPAT | ENT_HTML401 | ENT_SUBSTITUTE;
if ($encoding != null) {
print "<PRE>\n".htmlentities($message, $flags, $encoding)."\n</PRE>";
} else {
print "<PRE>\n".htmlentities($message, $flags)."\n</PRE>";
}
} else {
print "\n$message\n";
}
// let the user see this now in case there's a time out later...
flush();
}
} |
Change "Main Menu" button to an "Agree" button | function initScenes(Q) {
Q.scene("mainMenu", function(stage) {
stage.insert(new Q.UI.Button(
{
asset: "play_button.png",
x: Q.width / 2 - 55,
y: 500
},
function() {
Q.stageScene('game');
}));
stage.insert(new Q.HoverSprite({
asset: "title.png",
cx: 0,
cy: 0,
x: Q.width / 2 - 210,
y: 16,
}));
});
Q.scene('endGame',function(stage) {
var box = stage.insert(new Q.UI.Container({
x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.25)"
}));
var button = box.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC", label: "Agree" }))
var label = box.insert(new Q.UI.Text({x:10, y: -10 - button.p.h, label: stage.options.label }));
button.on("click",function() {
Q.clearStages();
Q.stageScene('mainMenu');
});
box.fit(20);
});
Q.scene("game",function(stage) {
Q.stageTMX('stage1.tmx', stage);
var player = stage.detect(function() { return this.p.team === 'players' });
stage.add('viewport').follow(player);
});
}
| function initScenes(Q) {
Q.scene("mainMenu", function(stage) {
stage.insert(new Q.UI.Button(
{
asset: "play_button.png",
x: Q.width / 2 - 55,
y: 500
},
function() {
Q.stageScene('game');
}));
stage.insert(new Q.HoverSprite({
asset: "title.png",
cx: 0,
cy: 0,
x: Q.width / 2 - 210,
y: 16,
}));
});
Q.scene('endGame',function(stage) {
var box = stage.insert(new Q.UI.Container({
x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.25)"
}));
var button = box.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC", label: "Main Menu" }))
var label = box.insert(new Q.UI.Text({x:10, y: -10 - button.p.h, label: stage.options.label }));
button.on("click",function() {
Q.clearStages();
Q.stageScene('mainMenu');
});
box.fit(20);
});
Q.scene("game",function(stage) {
Q.stageTMX('stage1.tmx', stage);
var player = stage.detect(function() { return this.p.team === 'players' });
stage.add('viewport').follow(player);
});
} |
Clean up language, center answer button. | @extends('layouts.app')
@section('content')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Trio {{ $trio->id }}
</div>
<div class="panel-body">
<ul>
<li>{{ $trio->sentence1 }}</li>
<li>{{ $trio->sentence2 }}</li>
<li>{{ $trio->sentence3 }}</li>
{{--<li>answer: {{ $trio->answer }}</li>--}}
</ul>
<form action="{{ action('SolveController@check', $trio->id) }}" class="form-horizontal" method="post" role="form">
{{ csrf_field() }}
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="answer">Answer</label>
<div class="col-md-4">
<input class="form-control input-md" id="answer" name="answer" placeholder="" value="" required="true" type="text">
</div>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-default" type="submit">Check</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
@endsection | @extends('layouts.app')
@section('content')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
Single trio {{ $trio->id }}
</div>
<div class="panel-body">
<ul>
<li>ID: {{ $trio->id }}</li>
<li>sentence1: {{ $trio->sentence1 }}</li>
<li>sentence2: {{ $trio->sentence2 }}</li>
<li>sentence3: {{ $trio->sentence3 }}</li>
{{--<li>answer: {{ $trio->answer }}</li>--}}
</ul>
<form action="{{ action('SolveController@check', $trio->id) }}" class="form-horizontal" method="post" role="form">
{{ csrf_field() }}
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="answer">Answer</label>
<div class="col-md-4">
<input class="form-control input-md" id="answer" name="answer" placeholder="" value="" required="true" type="text">
</div>
</div>
<div class="form-group">
<div class="col-md-2 col-md-offset-5">
<button class="btn btn-default" type="submit">Check</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
@endsection |
Update denon device mock to reflect mixer changes | import unittest
import os
from mopidy.mixers.denon import DenonMixer
class DenonMixerDeviceMock(object):
def __init__(self):
self._open = True
self.ret_val = bytes('MV00\r')
def write(self, x):
if x[2] != '?':
self.ret_val = bytes(x)
def read(self, x):
return self.ret_val
def isOpen(self):
return self._open
def open(self):
self._open = True
class DenonMixerTest(unittest.TestCase):
def setUp(self):
self.m = DenonMixer()
self.m._device = DenonMixerDeviceMock()
def test_volume_set_to_min(self):
self.m.volume = 0
self.assertEqual(self.m.volume, 0)
def test_volume_set_to_max(self):
self.m.volume = 100
self.assertEqual(self.m.volume, 99)
def test_volume_set_to_below_min_results_in_min(self):
self.m.volume = -10
self.assertEqual(self.m.volume, 0)
def test_volume_set_to_above_max_results_in_max(self):
self.m.volume = 110
self.assertEqual(self.m.volume, 99)
def test_reopen_device(self):
self.m._device._open = False
self.m.volume = 10
self.assertTrue(self.m._device._open)
| import unittest
import os
from mopidy.mixers.denon import DenonMixer
class DenonMixerDeviceMock(object):
def __init__(self):
self._open = True
self.ret_val = bytes('00')
def write(self, x):
pass
def read(self, x):
return self.ret_val
def isOpen(self):
return self._open
def open(self):
self._open = True
class DenonMixerTest(unittest.TestCase):
def setUp(self):
self.m = DenonMixer()
self.m._device = DenonMixerDeviceMock()
def test_volume_set_to_min(self):
self.m.volume = 0
self.assertEqual(self.m.volume, 0)
def test_volume_set_to_max(self):
self.m.volume = 100
self.assertEqual(self.m.volume, 99)
def test_volume_set_to_below_min_results_in_min(self):
self.m.volume = -10
self.assertEqual(self.m.volume, 0)
def test_volume_set_to_above_max_results_in_max(self):
self.m.volume = 110
self.assertEqual(self.m.volume, 99)
def test_reopen_device(self):
self.m._device._open = False
self.m.volume = 10
self.assertTrue(self.m._device._open)
|
Fix typo on the cleaning loop | module.exports = function(data, Bot, Config, Helpers) {
var value = Helpers.getCommandPart(data.message, '2', Config);
if(Config.admin.indexOf(data.userID) == -1) {
var message = '';
message += '@';
message += data.user;
message += ' ';
message += 'Vous n\'avez pas la permission d\'effectuer cette commande'
Bot.sendMessage({
'to': data.channelID,
'message': message
})
return;
}
if(typeof value !== 'undefined'){
switch(value){
case 'all' :
Bot.getMessages({
channel: data.channelID,
limit: 500000
}, function(messageArr) {
for(i=0; i < messageArr.length; i++){
Bot.deleteMessage({
channel: data.channelID,
messageID: messageArr[i].id
});
}
});
break;
default:
Bot.getMessages({
channel: data.channelID,
limit: parseInt(value)
}, function(messageArr) {
for (i = 0; i < messageArr.length; i++) {
Bot.deleteMessage({
channel: data.channelID,
messageID: messageArr[i].id
});
}
});
break;
}
}else{
Bot.sendMessage({
'to': data.userID,
'message': 'merci de spécifier un paramètre'
});
}
};
| module.exports = function(data, Bot, Config, Helpers) {
var value = Helpers.getCommandPart(data.message, '2', Config);
if(Config.admin.indexOf(data.userID) == -1) {
var message = '';
message += '@';
message += data.user;
message += ' ';
message += 'Vous n\'avez pas la permission d\'effectuer cette commande'
Bot.sendMessage({
'to': data.channelID,
'message': message
})
return;
}
if(typeof value !== 'undefined'){
switch(value){
case 'all' :
Bot.getMessages({
channel: data.channelID,
limit: 500000
}, function(messageArr) {
for(i=0; i = messageArr.length; i++){
Bot.deleteMessage({
channel: data.channelID,
messageID: messageArr[i].id
});
}
});
break;
default:
Bot.getMessages({
channel: data.channelID,
limit: parseInt(value)
}, function(messageArr) {
for (i = 0; i < messageArr.length; i++) {
Bot.deleteMessage({
channel: data.channelID,
messageID: messageArr[i].id
});
}
});
break;
}
}else{
Bot.sendMessage({
'to': data.userID,
'message': 'merci de spécifier un paramètre'
});
}
};
|
Handle case for error formatting where errors are a list of dictionaries (as you would see in bulk create). |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
def dict_error_formatting(errors, error):
for key, value in error.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'detail': reason, 'meta': {'field': key}})
else:
errors.append({'detail': value, 'meta': {'field': key}})
if response:
message = response.data
if isinstance(message, dict):
dict_error_formatting(errors, message)
elif isinstance(message, (list, tuple)):
for error in message:
if isinstance(error, (dict)):
dict_error_formatting(errors, error)
else:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'detail': reason, 'meta': {'field': key}})
else:
errors.append({'detail': value, 'meta': {'field': key}})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
Clean up the profiles activation action | <?php
namespace Frontend\Modules\Profiles\Actions;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Frontend\Core\Engine\Base\Block as FrontendBaseBlock;
use Frontend\Modules\Profiles\Engine\Authentication as FrontendProfilesAuthentication;
use Frontend\Modules\Profiles\Engine\Model as FrontendProfilesModel;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Activate extends FrontendBaseBlock
{
public function execute(): void
{
$this->loadTemplate();
$profileId = $this->getProfileId();
$this->activateProfile($profileId);
FrontendProfilesAuthentication::login($profileId);
$this->template->assign('activationSuccess', true);
}
private function activateProfile(int $profileId): void
{
FrontendProfilesModel::update($profileId, ['status' => 'active']);
FrontendProfilesModel::deleteSetting($profileId, 'activation_key');
}
private function getProfileId(): int
{
$profileId = FrontendProfilesModel::getIdBySetting('activation_key', $this->getActivationKey());
if ($profileId === null) {
throw new NotFoundHttpException();
}
return $profileId;
}
private function getActivationKey(): string
{
$activationKey = $this->url->getParameter(0);
if ($activationKey === null) {
throw new NotFoundHttpException();
}
return $activationKey;
}
}
| <?php
namespace Frontend\Modules\Profiles\Actions;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Frontend\Core\Engine\Base\Block as FrontendBaseBlock;
use Frontend\Core\Engine\Navigation as FrontendNavigation;
use Frontend\Modules\Profiles\Engine\Authentication as FrontendProfilesAuthentication;
use Frontend\Modules\Profiles\Engine\Model as FrontendProfilesModel;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* This is the activate-action.
*/
class Activate extends FrontendBaseBlock
{
public function execute(): void
{
// get activation key
$key = $this->url->getParameter(0);
// load template
$this->loadTemplate();
// do we have an activation key?
if (isset($key)) {
// get profile id
$profileId = FrontendProfilesModel::getIdBySetting('activation_key', $key);
// have id?
if ($profileId != null) {
// update status
FrontendProfilesModel::update($profileId, ['status' => 'active']);
// delete activation key
FrontendProfilesModel::deleteSetting($profileId, 'activation_key');
// login profile
FrontendProfilesAuthentication::login($profileId);
// show success message
$this->template->assign('activationSuccess', true);
} else {
// failure
throw new NotFoundHttpException();
}
} else {
throw new NotFoundHttpException();
}
}
}
|
Use only lowercase letters in the source link as well | """Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
| """Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1])
|
Return the assignment value instead of for DummyConfigResource.app's setter | var _ = require('lodash');
var resources = require('../dummy/resources');
var DummyResource = resources.DummyResource;
var DummyConfigResource = DummyResource.extend(function(self, name, store) {
/**class:DummyConfigResource(name)
Handles api requests to the config resource from :class:`DummyApi`.
:param string name:
The name of the resource. Should match the name given in api requests.
*/
DummyResource.call(self, name);
/**attribute:DummyConfigResource.store
An object containing sandbox's config data. Properties do not need to be
JSON-stringified, this is done when the config is retrieved using a
``'config.get'`` api request.
*/
self.store = store || {config: {}};
/**attribute:DummyConfigResource.app
A shortcut to DummyConfigResource.store.config (the app's config).
*/
Object.defineProperty(self, 'app', {
get: function() {
return self.store.config;
},
set: function(v) {
self.store.config = v;
return v;
}
});
self.handlers.get = function(cmd) {
var value = self.store[cmd.key];
if (_.isUndefined(value)) {
value = null;
}
return {
success: true,
value: JSON.stringify(value)
};
};
});
this.DummyConfigResource = DummyConfigResource;
| var _ = require('lodash');
var resources = require('../dummy/resources');
var DummyResource = resources.DummyResource;
var DummyConfigResource = DummyResource.extend(function(self, name, store) {
/**class:DummyConfigResource(name)
Handles api requests to the config resource from :class:`DummyApi`.
:param string name:
The name of the resource. Should match the name given in api requests.
*/
DummyResource.call(self, name);
/**attribute:DummyConfigResource.store
An object containing sandbox's config data. Properties do not need to be
JSON-stringified, this is done when the config is retrieved using a
``'config.get'`` api request.
*/
self.store = store || {config: {}};
/**attribute:DummyConfigResource.app
A shortcut to DummyConfigResource.store.config (the app's config).
*/
Object.defineProperty(self, 'app', {
get: function() {
return self.store.config;
},
set: function(v) {
self.store.config = v;
return self.store.config;
}
});
self.handlers.get = function(cmd) {
var value = self.store[cmd.key];
if (_.isUndefined(value)) {
value = null;
}
return {
success: true,
value: JSON.stringify(value)
};
};
});
this.DummyConfigResource = DummyConfigResource;
|
Move the init/event methods to the private scope | var Gificiency = (function() {
'use strict';
var searchField = $('.search'),
items = $('li'),
links = $('a');
var init = function() {
if ( getHash() ) {
search( getHash() );
}
events();
};
var events = function() {
searchField.on('keyup', function() {
search( $(this).val() );
});
items.on('mouseover', function() {
var elem = $(this).find('a'), image = elem.attr('href');
elem.parent().append( popup(image) );
}).on('mouseout', function() {
clearImages();
});
};
var search = function(filter) {
links.each(function() {
var elem = $(this);
if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
elem.hide();
} else {
elem.show();
}
});
};
var getHash = function() {
var filter;
if (window.location.hash != '') {
filter = window.location.hash.substring(1);
} else {
filter = false;
}
return filter;
};
var clearImages = function() {
$('img').each(function() {
$(this).remove();
});
};
var popup = function(image) {
return $('<img src="'+ image +'" />');
};
var Gificiency = {
init: init
};
return Gificiency;
})();
| var Gificiency = (function() {
'use strict';
var searchField = $('.search'),
items = $('li'),
links = $('a');
var search = function(filter) {
links.each(function() {
var elem = $(this);
if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
elem.hide();
} else {
elem.show();
}
});
};
var getHash = function() {
var filter;
if (window.location.hash != '') {
filter = window.location.hash.substring(1);
} else {
filter = false;
}
return filter;
};
var clearImages = function() {
$('img').each(function() {
$(this).remove();
});
};
var popup = function(image) {
return $('<img src="'+ image +'" />');
};
var init = function() {
if ( getHash() ) {
search( getHash() );
}
events();
};
var events = function() {
searchField.on('keyup', function() {
search( $(this).val() );
});
items.on('mouseover', function() {
var elem = $(this).find('a'), image = elem.attr('href');
elem.parent().append( popup(image) );
}).on('mouseout', function() {
clearImages();
});
};
var Gificiency = {
init: init,
events: events
};
return Gificiency;
})();
|
[model] Add ability to get ISO4217 info. add a request and action for that. Simply payment interface. | <?php
namespace Payum\AuthorizeNet\Aim\Action;
use Payum\Core\Action\ActionInterface;
use Payum\Core\Action\GatewayAwareAction;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Model\PaymentInterface;
use Payum\Core\Request\Convert;
use Payum\Core\Request\GetCurrency;
class ConvertPaymentAction extends GatewayAwareAction
{
/**
* {@inheritDoc}
*
* @param Convert $request
*/
public function execute($request)
{
RequestNotSupportedException::assertSupports($this, $request);
/** @var PaymentInterface $payment */
$payment = $request->getSource();
$this->gateway->execute($currency = new GetCurrency($payment->getCurrencyCode()));
$divisor = pow(10, $currency->getIso4217()->getExp());
$details = ArrayObject::ensureArrayObject($payment->getDetails());
$details['amount'] = $payment->getTotalAmount() / $divisor;
$details['invoice_num'] = $payment->getNumber();
$details['description'] = $payment->getDescription();
$details['email'] = $payment->getClientEmail();
$details['cust_id'] = $payment->getClientId();
$request->setResult((array) $details);
}
/**
* {@inheritDoc}
*/
public function supports($request)
{
return
$request instanceof Convert &&
$request->getSource() instanceof PaymentInterface &&
$request->getTo() == 'array'
;
}
}
| <?php
namespace Payum\AuthorizeNet\Aim\Action;
use Payum\Core\Action\ActionInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Model\PaymentInterface;
use Payum\Core\Request\Convert;
class ConvertPaymentAction implements ActionInterface
{
/**
* {@inheritDoc}
*
* @param Convert $request
*/
public function execute($request)
{
RequestNotSupportedException::assertSupports($this, $request);
/** @var PaymentInterface $payment */
$payment = $request->getSource();
$divisor = pow(10, $payment->getCurrencyDigitsAfterDecimalPoint());
$details = ArrayObject::ensureArrayObject($payment->getDetails());
$details['amount'] = $payment->getTotalAmount() / $divisor;
$details['invoice_num'] = $payment->getNumber();
$details['description'] = $payment->getDescription();
$details['email'] = $payment->getClientEmail();
$details['cust_id'] = $payment->getClientId();
$request->setResult((array) $details);
}
/**
* {@inheritDoc}
*/
public function supports($request)
{
return
$request instanceof Convert &&
$request->getSource() instanceof PaymentInterface &&
$request->getTo() == 'array'
;
}
}
|
FIX partner internal code compatibility with sign up | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
class partner(models.Model):
""""""
_inherit = 'res.partner'
internal_code = fields.Char(
'Internal Code',
copy=False,
)
# we let this to base nane search improoved
# def name_search(self, cr, uid, name, args=None,
# operator='ilike', context=None, limit=100):
# args = args or []
# res = []
# if name:
# recs = self.search(
# cr, uid, [('internal_code', operator, name)] + args,
# limit=limit, context=context)
# res = self.name_get(cr, uid, recs)
# res += super(partner, self).name_search(
# cr, uid,
# name=name, args=args, operator=operator, limit=limit)
# return res
@api.model
def create(self, vals):
if not vals.get('internal_code', False):
vals['internal_code'] = self.env[
'ir.sequence'].next_by_code('partner.internal.code') or '/'
return super(partner, self).create(vals)
_sql_constraints = {
('internal_code_uniq', 'unique(internal_code)',
'Internal Code mast be unique!')
}
| # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import fields, models, api
class partner(models.Model):
""""""
_inherit = 'res.partner'
internal_code = fields.Char(
'Internal Code')
# we let this to base nane search improoved
# def name_search(self, cr, uid, name, args=None,
# operator='ilike', context=None, limit=100):
# args = args or []
# res = []
# if name:
# recs = self.search(
# cr, uid, [('internal_code', operator, name)] + args,
# limit=limit, context=context)
# res = self.name_get(cr, uid, recs)
# res += super(partner, self).name_search(
# cr, uid,
# name=name, args=args, operator=operator, limit=limit)
# return res
@api.model
def create(self, vals):
if not vals.get('internal_code', False):
vals['internal_code'] = self.env[
'ir.sequence'].next_by_code('partner.internal.code') or '/'
return super(partner, self).create(vals)
_sql_constraints = {
('internal_code_uniq', 'unique(internal_code)',
'Internal Code mast be unique!')
}
|
Add css during search loading | $(function() {
function doSearch() {
var keywords = $('input[name="q"]').val().toLowerCase();
$.get("search.php", {q: keywords}, function(data) {
$('#count').text(data['count']);
$('#time').text(data['time']);
var html = '';
$.each(data['results'], function(k, v) {
html += '<strong><a href="' + v['url'] + '"><img class="favicon" width="16px" src="//logo.clearbit.com/' + v['domain'] + '?size=32" onError="this.onerror=null;this.src=\'/default_favicon.png\';"> ' + v['title'] + '</a></strong><br>' + v['description'] + '<br><span class="text-muted">' + v['url'] + '</span> <span class="text-muted hidden-sm-down"><br>[lang: ' + v['lang'] + '] [scores: ' + v['position_quality'] + ', ' + v['pagerank'] + ']</span><br><br>';
});
$('#results').css('opacity', '1');
if (html == '') {
$('#counters').hide();
$('#results').html('No result');
} else {
$('#counters').show();
$('#results').html(html);
}
}, 'json');
}
doSearch();
$('form').submit(function(e) {
var keywords = $('input[name="q"]').val().toLowerCase();
window.history.pushState(null, null, '/?q=' + keywords);
$('#results').css('opacity', '0.1');
doSearch();
return false;
})
});
| $(function() {
function doSearch() {
var keywords = $('input[name="q"]').val().toLowerCase();
$.get("search.php", {q: keywords}, function(data) {
$('#count').text(data['count']);
$('#time').text(data['time']);
var html = '';
$.each(data['results'], function(k, v) {
html += '<strong><a href="' + v['url'] + '"><img class="favicon" width="16px" src="//logo.clearbit.com/' + v['domain'] + '?size=32" onError="this.onerror=null;this.src=\'/default_favicon.png\';"> ' + v['title'] + '</a></strong><br>' + v['description'] + '<br><span class="text-muted">' + v['url'] + '</span> <span class="text-muted hidden-sm-down"><br>[lang: ' + v['lang'] + '] [scores: ' + v['position_quality'] + ', ' + v['pagerank'] + ']</span><br><br>';
});
if (html == '') {
$('#counters').hide();
$('#results').html('No result');
} else {
$('#counters').show();
$('#results').html(html);
}
}, 'json');
}
doSearch();
$('form').submit(function(e) {
var keywords = $('input[name="q"]').val().toLowerCase();
window.history.pushState(null, null, '/?q=' + keywords);
doSearch();
return false;
})
});
|
Fix user role filtered namespace | """
Copyright 2016 ElasticBox 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.
"""
def filter_namespaces(data, user, _message):
if user["role"] != "administrator":
if isinstance(data, list):
for item in data:
if "members" not in item or user["username"] not in item["members"]:
data.remove(item)
return data
else:
if "members" not in data or user["username"] not in data["members"]:
return None
return data
def filter_metrics(data, user, message):
if "body" in message and "name" in message["body"]:
if ("involvedObject" in data and
"name" in data["involvedObject"] and
data["involvedObject"]["name"] == message["body"]["name"]):
return data
else:
return None
else:
return data
return data
| """
Copyright 2016 ElasticBox 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.
"""
def filter_namespaces(data, user, _message):
if user["role"] != "administrator":
if isinstance(data, list):
for item in data:
if "members" not in item or user["username"] not in item["members"]:
data.remove(item)
return data
else:
if "members" not in data or user["username"] not in data["members"]:
return None
else:
return data
def filter_metrics(data, user, message):
if "body" in message and "name" in message["body"]:
if ("involvedObject" in data and
"name" in data["involvedObject"] and
data["involvedObject"]["name"] == message["body"]["name"]):
return data
else:
return None
else:
return data
return data
|
Add users to Project angular ressource | // -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <[email protected]>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';
var trexServices = angular.module('trex.services', ['ngResource']);
trexServices.factory('Conf', function($location) {
function getRootUrl() {
var rootUrl = $location.protocol() + '://' + $location.host();
if ($location.port())
rootUrl += ':' + $location.port();
return rootUrl;
};
return {
'apiBase': '/api/1',
'rootUrl': getRootUrl()
};
});
trexServices.factory('Project', ['$resource', 'Conf',
function($resource, Conf) {
return $resource(Conf.apiBase + '/projects/:projectId',
{projectId: '@id'},
{entries: {method: 'GET', isArray: true,
url: Conf.apiBase + '/projects/:projectId/entries',
params: {projectId: '@id'}
},
tags: {method: 'GET', isArray: true,
url: Conf.apiBase + '/projects/:projectId/tags',
params: {projectId: '@id'}
},
users: {method: 'GET', isArray: true,
url: Conf.apiBase + '/projects/:projectId/users',
params: {projectId: '@id'}
}
}
);
}
]);
trexServices.factory('Entry', ['$resource', 'Conf',
function($resource, Conf) {
return $resource(Conf.apiBase + '/entries/:entryId', {entryId: '@id'}, {
});
}
]);
| // -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <[email protected]>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';
var trexServices = angular.module('trex.services', ['ngResource']);
trexServices.factory('Conf', function($location) {
function getRootUrl() {
var rootUrl = $location.protocol() + '://' + $location.host();
if ($location.port())
rootUrl += ':' + $location.port();
return rootUrl;
};
return {
'apiBase': '/api/1',
'rootUrl': getRootUrl()
};
});
trexServices.factory('Project', ['$resource', 'Conf',
function($resource, Conf) {
return $resource(Conf.apiBase + '/projects/:projectId',
{projectId: '@id'},
{entries: {method: 'GET', isArray: true,
url: Conf.apiBase + '/projects/:projectId/entries',
params: {projectId: '@id'}
},
tags: {method: 'GET', isArray: true,
url: Conf.apiBase + '/projects/:projectId/tags',
params: {projectId: '@id'}
}
}
);
}
]);
trexServices.factory('Entry', ['$resource', 'Conf',
function($resource, Conf) {
return $resource(Conf.apiBase + '/entries/:entryId', {entryId: '@id'}, {
});
}
]);
|
Feature: Fix when there are multiple datetime pickers on same page | <style>
.datepicker input {
width: 40%;
}
.datepicker .btn {
border: 1px solid #dadada;
border-left: none;
font-size:1.125em;
padding: 0.7em 0.8em;
}
</style>
<div class="form-group" for="{{$name}}">
<span class="form-group-content">
<label for="" class="form-label">
{{ $label }}
</label>
<span class="form-field">
<p class="datepicker input-group" id="datepicker-{{ $name }}" data-wrap="true" data-clickOpens="false" data-enableTime="true">
<input value="
@if ($model->id && $model->{$name})
{{ date('Y-m-d H:i:s', strtotime($model->{$name})) }}
@elseif ($model->id)
{{ date('Y-m-d H:i:s') }}
@endif
"
name="{{ $name }}"
class="{{ ($required ? ' js-required':'') }}"
id="{{ $name }}"
autocorrect="off"
data-input><!--
--><a class="btn" data-toggle><i class="fa fa-calendar"></i></a><!--
--><a class="btn" data-clear><i class="fa fa-close"></i> </a>
</p>
</span>
</span>
</div>
| <style>
.datepicker input {
width: 40%;
}
.datepicker .btn {
border: 1px solid #dadada;
border-left: none;
font-size:1.125em;
padding: 0.7em 0.8em;
}
</style>
<div class="form-group" for="{{$name}}">
<span class="form-group-content">
<label for="" class="form-label">
{{ $label }}
</label>
<span class="form-field">
<p class="datepicker input-group" id="datepicker-{{ $name }}" data-wrap="true" data-clickOpens="false" data-enableTime="true" data-defaultDate="{{ date('H:i:s') }}" data-defaultHour="{{ date('H') }}" data-defaultMinute="{{ date('m') }}">
<input placeholder="{{ date('d-m-Y H:i') }}"
value="{{ $model->{$name} }}"
name="{{ $name }}"
class="{{ ($required ? ' js-required':'') }}"
id="{{ $name }}"
autocorrect="off"
data-input><!--
--><a class="btn" data-toggle><i class="fa fa-calendar"></i></a><!--
--><a class="btn" data-clear><i class="fa fa-close"></i> </a>
</p>
</span>
</span>
</div>
|
Add maps link to menu | <?php
namespace FoodFlow\WebBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function mainMenu(FactoryInterface $factory, array $options)
{
$menu = $factory->createItem('root');
$menu->addChild('Home', array('route' => 'ff_web_home'));
$menu->addChild('Map', array('route' => 'ff_maps_home'));
$menu->addChild('Contact', array('route' => 'ff_web_contact'));
$menu->addChild('Purpose', array('route' => 'ff_web_purpose'));
$context = $this->container->get('security.context');
if ($context->isGranted('ROLE_USER')) {
$this->addUserItems($menu, $context);
} else {
$this->addAnonymousItems($menu);
}
return $menu;
}
protected function adduserItems($menu, $context)
{
$menu->addChild('Profile', array('route' => 'fos_user_profile_show'));
$menu->addChild('Logout', array('route' => 'fos_user_security_logout'));
if ($context->isGranted('ROLE_ADMIN')) {
$menu->addChild('Admin', array('route' => 'ff_admin_home'));
}
}
protected function addAnonymousItems($menu)
{
$menu->addChild('Login', array('route' => 'fos_user_security_login'));
$menu->addChild('Register', array('route' => 'fos_user_registration_register'));
}
} | <?php
namespace FoodFlow\WebBundle\Menu;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
class Builder extends ContainerAware
{
public function mainMenu(FactoryInterface $factory, array $options)
{
$menu = $factory->createItem('root');
$menu->addChild('Home', array('route' => 'ff_web_home'));
$menu->addChild('Purpose', array('route' => 'ff_web_purpose'));
$menu->addChild('Contact', array('route' => 'ff_web_contact'));
$context = $this->container->get('security.context');
if ($context->isGranted('ROLE_USER')) {
$this->addUserItems($menu, $context);
} else {
$this->addAnonymousItems($menu);
}
return $menu;
}
protected function adduserItems($menu, $context)
{
$menu->addChild('Profile', array('route' => 'fos_user_profile_show'));
$menu->addChild('Logout', array('route' => 'fos_user_security_logout'));
if ($context->isGranted('ROLE_ADMIN')) {
$menu->addChild('Admin', array('route' => 'ff_admin_home'));
}
}
protected function addAnonymousItems($menu)
{
$menu->addChild('Login', array('route' => 'fos_user_security_login'));
$menu->addChild('Register', array('route' => 'fos_user_registration_register'));
}
} |
Add workaround for electron webview issue with disappearing cursors | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import ElectronWebView from 'react-electron-web-view';
import ServiceModel from '../../../models/Service';
@observer
class ServiceWebview extends Component {
static propTypes = {
service: PropTypes.instanceOf(ServiceModel).isRequired,
setWebviewReference: PropTypes.func.isRequired,
detachService: PropTypes.func.isRequired,
};
webview = null;
componentWillUnmount() {
const { service, detachService } = this.props;
detachService({ service });
}
refocusWebview = () => {
const { webview } = this;
if (!webview) return;
webview.view.blur();
webview.view.focus();
};
render() {
const {
service,
setWebviewReference,
} = this.props;
return (
<ElectronWebView
ref={(webview) => {
this.webview = webview;
webview.view.addEventListener('did-stop-loading', this.refocusWebview);
}}
autosize
src={service.url}
preload="./webview/recipe.js"
partition={`persist:service-${service.id}`}
onDidAttach={() => {
setWebviewReference({
serviceId: service.id,
webview: this.webview.view,
});
}}
onUpdateTargetUrl={this.updateTargetUrl}
useragent={service.userAgent}
disablewebsecurity={service.recipe.disablewebsecurity}
allowpopups
/>
);
}
}
export default ServiceWebview;
| import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import ElectronWebView from 'react-electron-web-view';
import ServiceModel from '../../../models/Service';
@observer
class ServiceWebview extends Component {
static propTypes = {
service: PropTypes.instanceOf(ServiceModel).isRequired,
setWebviewReference: PropTypes.func.isRequired,
detachService: PropTypes.func.isRequired,
};
webview = null;
componentWillUnmount() {
const { service, detachService } = this.props;
detachService({ service });
}
render() {
const {
service,
setWebviewReference,
} = this.props;
return (
<ElectronWebView
ref={(webview) => { this.webview = webview; }}
autosize
src={service.url}
preload="./webview/recipe.js"
partition={`persist:service-${service.id}`}
onDidAttach={() => {
setWebviewReference({
serviceId: service.id,
webview: this.webview.view,
});
}}
onUpdateTargetUrl={this.updateTargetUrl}
useragent={service.userAgent}
disablewebsecurity={service.recipe.disablewebsecurity}
allowpopups
/>
);
}
}
export default ServiceWebview;
|