text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Use class notation in config | <?php
return [
/*
|--------------------------------------------------------------------------
| Authorization Models
|--------------------------------------------------------------------------
*/
'models' => [
/*
* The class name of the permission model to be used.
*/
'permission' => Spatie\Permission\Models\Permission::class,
/*
* The class name of the role model to be used.
*/
'role' => Spatie\Permission\Models\Role::class,
/*
* The class name of the user model to be used.
*/
'user' => App\User::class,
],
/*
|--------------------------------------------------------------------------
| Authorization Tables
|--------------------------------------------------------------------------
*/
'tableNames' => [
/*
* The name of the "users" table to be used.
*/
'users' => 'users',
/*
* The name of the "roles" table to be used.
*/
'roles' => 'roles',
/*
* The name of the "permissions" table to be used.
*/
'permissions' => 'permissions',
/*
* The name of the "user_has_permissions" table to be used.
*/
'user_has_permissions' => 'user_has_permissions',
/*
* The name of the "user_has_roles" table to be used.
*/
'user_has_roles' => 'user_has_roles',
/*
* The name of the "role_has_permissions" table to be used.
*/
'role_has_permissions' => 'role_has_permissions',
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Authorization Models
|--------------------------------------------------------------------------
*/
'models' => [
/*
* The class name of the permission model to be used.
*/
'permission' => 'Spatie\Permission\Models\Permission',
/*
* The class name of the role model to be used.
*/
'role' => 'Spatie\Permission\Models\Role',
/*
* The class name of the user model to be used.
*/
'user' => 'App\User',
],
/*
|--------------------------------------------------------------------------
| Authorization Tables
|--------------------------------------------------------------------------
*/
'tableNames' => [
/*
* The name of the "users" table to be used.
*/
'users' => 'users',
/*
* The name of the "roles" table to be used.
*/
'roles' => 'roles',
/*
* The name of the "permissions" table to be used.
*/
'permissions' => 'permissions',
/*
* The name of the "user_has_permissions" table to be used.
*/
'user_has_permissions' => 'user_has_permissions',
/*
* The name of the "user_has_roles" table to be used.
*/
'user_has_roles' => 'user_has_roles',
/*
* The name of the "role_has_permissions" table to be used.
*/
'role_has_permissions' => 'role_has_permissions',
],
];
|
Use canonical form of Docker folder when building TAR files
In BuildImageCmdImpl#buildDockerFolderTar a canonical form of the source
files referenced in the Dockerfile is used. But the Docker folder is
passed in the given form to the CompressArchiveUtil.
CompressArchiveUtil#relativize creates absolute TAR archive entries if the
canonical form of the source files differs from the given form of the
Docker folder. As a result, the Docker deamon can not find the files
during the build. This can happen in case-insensitive file systems such as
Windows, for example.
As a solution, the canonical form of the Docker folder must be used. | package com.github.dockerjava.core;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import java.io.*;
public class CompressArchiveUtil {
public static File archiveTARFiles(File base, Iterable<File> files, String archiveNameWithOutExtension) throws IOException {
File tarFile = new File(FileUtils.getTempDirectoryPath(), archiveNameWithOutExtension + ".tar");
TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile));
try {
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
for (File file : files) {
TarArchiveEntry tarEntry = new TarArchiveEntry(file);
tarEntry.setName(relativize(base.getCanonicalFile(), file.getCanonicalFile()));
if (!file.isDirectory()) {
if (file.canExecute()) {
tarEntry.setMode(tarEntry.getMode() | 0755);
}
}
tos.putArchiveEntry(tarEntry);
if (!file.isDirectory()) {
FileUtils.copyFile(file, tos);
}
tos.closeArchiveEntry();
}
} finally {
tos.close();
}
return tarFile;
}
private static String relativize(File base, File absolute) {
String relative = base.toURI().relativize(absolute.toURI()).getPath();
return relative;
}
}
| package com.github.dockerjava.core;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import java.io.*;
public class CompressArchiveUtil {
public static File archiveTARFiles(File base, Iterable<File> files, String archiveNameWithOutExtension) throws IOException {
File tarFile = new File(FileUtils.getTempDirectoryPath(), archiveNameWithOutExtension + ".tar");
TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile));
try {
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
for (File file : files) {
TarArchiveEntry tarEntry = new TarArchiveEntry(file);
tarEntry.setName(relativize(base, file));
if (!file.isDirectory()) {
if (file.canExecute()) {
tarEntry.setMode(tarEntry.getMode() | 0755);
}
}
tos.putArchiveEntry(tarEntry);
if (!file.isDirectory()) {
FileUtils.copyFile(file, tos);
}
tos.closeArchiveEntry();
}
} finally {
tos.close();
}
return tarFile;
}
private static String relativize(File base, File absolute) {
String relative = base.toURI().relativize(absolute.toURI()).getPath();
return relative;
}
}
|
Refactor the timing decorator to be less confusing
Also means that we don't have to ignore a flake8 error. | from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
def record_timing():
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
try:
resp = f(*args, **kwargs)
except NewsletterException:
record_timing()
raise
record_timing()
return resp
return wrapped
return decorator
| from functools import wraps
from time import time
from django_statsd.clients import statsd
class UnauthorizedException(Exception):
"""Failure to log into the email server."""
pass
class NewsletterException(Exception):
"""Error when trying to talk to the the email server."""
def __init__(self, msg=None, error_code=None, status_code=None):
self.error_code = error_code
self.status_code = status_code
super(NewsletterException, self).__init__(msg)
class NewsletterNoResultsException(NewsletterException):
"""
No results were returned from the mail server (but the request
didn't report any errors)
"""
pass
def get_timer_decorator(prefix):
"""
Decorator for timing and counting requests to the API
"""
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
starttime = time()
e = None
try:
resp = f(*args, **kwargs)
except NewsletterException as e: # noqa
pass
except Exception:
raise
totaltime = int((time() - starttime) * 1000)
statsd.timing(prefix + '.timing', totaltime)
statsd.timing(prefix + '.{}.timing'.format(f.__name__), totaltime)
statsd.incr(prefix + '.count')
statsd.incr(prefix + '.{}.count'.format(f.__name__))
if e:
raise
else:
return resp
return wrapped
return decorator
|
Move gin-config to install_requires to fix build.
PiperOrigin-RevId: 258563598 | """Install Mesh TensorFlow."""
from setuptools import find_packages
from setuptools import setup
setup(
name='mesh-tensorflow',
version='0.0.5',
description='Mesh TensorFlow',
author='Google Inc.',
author_email='[email protected]',
url='http://github.com/tensorflow/mesh',
license='Apache 2.0',
packages=find_packages(),
package_data={},
scripts=[],
install_requires=[
'future',
'gin-config',
'six',
],
extras_require={
'auto_mtf': ['ortools>=7.0.6546'],
'tensorflow': ['tensorflow>=1.9.0'],
'tensorflow_gpu': ['tensorflow-gpu>=1.9.0'],
'tests': [
'absl-py',
'pytest',
'ortools>=7.0.6546',
'tensor2tensor>=1.9.0', # TODO(trandustin): rm dependence
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning',
)
| """Install Mesh TensorFlow."""
from setuptools import find_packages
from setuptools import setup
setup(
name='mesh-tensorflow',
version='0.0.5',
description='Mesh TensorFlow',
author='Google Inc.',
author_email='[email protected]',
url='http://github.com/tensorflow/mesh',
license='Apache 2.0',
packages=find_packages(),
package_data={},
scripts=[],
install_requires=[
'future',
'six',
],
extras_require={
'auto_mtf': ['ortools>=7.0.6546'],
'gin-config': ['gin-config>=0.2.0'],
'tensorflow': ['tensorflow>=1.9.0'],
'tensorflow_gpu': ['tensorflow-gpu>=1.9.0'],
'tests': [
'absl-py',
'pytest',
'ortools>=7.0.6546',
'tensor2tensor>=1.9.0', # TODO(trandustin): rm dependence
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning',
)
|
Use font awesome user and search iscons | /**
* @module SOCIAL
*/
var SOCIAL = (function (SOCIAL) {
/**
* @property breadcrumbs
* @type {{content: string, title: string, isValid: isValid, href: string}[]}
*
* Data structure that defines the sub-level tabs for
* our plugin, used by the navbar controller to show
* or hide tabs based on some criteria
*/
SOCIAL.breadcrumbs = [
{
content: '<i class="icon-user"></i> User',
title: "Search info about a Twitter User",
isValid: function () { return true; },
href: "#/social/user"
},
{
content: '<i class="icon-search"></i> Tweets',
title: "Search Tweets based on keywords",
isValid: function () { return true; },
href: "#/social/tweets"
}
];
/**
* @function NavBarController
*
* @param $scope
*
* The controller for this plugin's navigation bar
*
*/
SOCIAL.NavBarController = function ($scope) {
$scope.breadcrumbs = SOCIAL.breadcrumbs;
$scope.isValid = function(link) {
return true;
};
};
return SOCIAL;
}(SOCIAL || { }));
| /**
* @module SOCIAL
*/
var SOCIAL = (function (SOCIAL) {
/**
* @property breadcrumbs
* @type {{content: string, title: string, isValid: isValid, href: string}[]}
*
* Data structure that defines the sub-level tabs for
* our plugin, used by the navbar controller to show
* or hide tabs based on some criteria
*/
SOCIAL.breadcrumbs = [
{
content: '<i class="icon-comments"></i> User',
title: "Search info about a User",
isValid: function () { return true; },
href: "#/social/user"
},
{
content: '<i class="icon-cogs"></i> Tweets',
title: "Search Tweets",
isValid: function () { return true; },
href: "#/social/tweets"
}
];
/**
* @function NavBarController
*
* @param $scope
*
* The controller for this plugin's navigation bar
*
*/
SOCIAL.NavBarController = function ($scope) {
$scope.breadcrumbs = SOCIAL.breadcrumbs;
$scope.isValid = function(link) {
return true;
};
};
return SOCIAL;
}(SOCIAL || { }));
|
Implement method injection to fetch the query. | <?php
namespace Yajra\CMS\DataTables;
use Yajra\Acl\Models\Role;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Services\DataTable;
class RolesDataTable extends DataTable
{
/**
* @return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns(trans('cms::role.dataTable.columns'))
->minifiedAjax()
->parameters(trans('cms::role.dataTable.parameters'));
}
/**
* @return string
*/
protected function filename()
{
return trans('cms::role.dataTable.filename');
}
/**
* Build DataTable api response.
*
* @param \Yajra\Acl\Models\Role $role
* @return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable(Role $role)
{
$model = $role->newQuery()->withCount('users')->withCount('permissions');
return (new EloquentDataTable($model))
->editColumn('system', function (Role $role) {
return dt_check($role->system);
})
->addColumn('users', function (Role $role) {
return view('administrator.roles.datatables.users', compact('role'));
})
->addColumn('permissions', function (Role $role) {
return view('administrator.roles.datatables.permissions', compact('role'));
})
->addColumn('action', 'administrator.roles.datatables.action')
->rawColumns(['system', 'users', 'permissions', 'action']);
}
}
| <?php
namespace Yajra\CMS\DataTables;
use Yajra\Acl\Models\Role;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Services\DataTable;
class RolesDataTable extends DataTable
{
/**
* @return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns(trans('cms::role.dataTable.columns'))
->minifiedAjax()
->parameters(trans('cms::role.dataTable.parameters'));
}
/**
* @return string
*/
protected function filename()
{
return trans('cms::role.dataTable.filename');
}
/**
* Build DataTable api response.
*
* @return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable()
{
return (new EloquentDataTable($this->query()))
->editColumn('system', function (Role $role) {
return dt_check($role->system);
})
->addColumn('users', function (Role $role) {
return view('administrator.roles.datatables.users', compact('role'));
})
->addColumn('permissions', function (Role $role) {
return view('administrator.roles.datatables.permissions', compact('role'));
})
->addColumn('action', 'administrator.roles.datatables.action')
->rawColumns(['system', 'users', 'permissions', 'action']);
}
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
public function query()
{
return $this->applyScopes(Role::query()->withCount('users')->withCount('permissions'));
}
}
|
Add comment to Pillow requirement to indicate that 2.0.0 is needed for Mac users. | #/usr/bin/env python
import os
from setuptools import setup, find_packages
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
version = '2.6.dev0'
setup(
name="django-photologue",
version=version,
description="Powerful image management for the Django web framework.",
author="Justin Driscoll, Marcos Daniel Petry, Richard Barran",
author_email="[email protected], [email protected]",
url="https://github.com/jdriscoll/django-photologue",
packages=find_packages(),
package_data={
'photologue': [
'res/*.jpg',
'locale/*/LC_MESSAGES/*',
'templates/photologue/*.html',
'templates/photologue/tags/*.html',
]
},
zip_safe=False,
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'],
install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum.
'South>=0.7.5', # Might work with earlier versions, but not tested.
'Pillow>=2.0.0', # Might work with earlier versions, but not tested. YMMV. Note that 2.0.0 needed for Mac users.
],
)
| #/usr/bin/env python
import os
from setuptools import setup, find_packages
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
version = '2.6.dev0'
setup(
name="django-photologue",
version=version,
description="Powerful image management for the Django web framework.",
author="Justin Driscoll, Marcos Daniel Petry, Richard Barran",
author_email="[email protected], [email protected]",
url="https://github.com/jdriscoll/django-photologue",
packages=find_packages(),
package_data={
'photologue': [
'res/*.jpg',
'locale/*/LC_MESSAGES/*',
'templates/photologue/*.html',
'templates/photologue/tags/*.html',
]
},
zip_safe=False,
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'],
install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum.
'South>=0.7.5', # Might work with earlier versions, but not tested.
'Pillow>=2.0.0', # Might work with earlier versions, but not tested.
],
)
|
Fix assignment issue in coallatz | '''
Module for running arbitrairy tests
'''
import time
def echo(text):
'''
Return a string - used for testing the connection
CLI Example:
salt '*' test.echo 'foo bar baz quo qux'
'''
print 'Echo got called!'
return text
def ping():
'''
Just used to make sure the minion is up and responding
Return True
CLI Example:
salt '*' test.ping
'''
return True
def fib(num):
'''
Return a fibonachi sequence up to the passed number, and the time it took
to compute in seconds. Used for performance tests
CLI Example:
salt '*' test.fib 3
'''
start = time.time()
a, b = 0, 1
ret = [0]
while b < num:
ret.append(b)
a, b = b, a + b
return ret, time.time() - start
def collatz(start):
'''
Execute the collatz conjecture from the passed starting number, returns
the sequence and the time it took to compute. Used for performance tests.
CLI Example:
salt '*' test.collatz 3
'''
begin = time.time()
steps = []
while start != 1:
steps.append(start)
if start > 1:
if start % 2 == 0:
start = start / 2
else:
start = start * 3 + 1
return steps, time.time() - begin
| '''
Module for running arbitrairy tests
'''
import time
def echo(text):
'''
Return a string - used for testing the connection
CLI Example:
salt '*' test.echo 'foo bar baz quo qux'
'''
print 'Echo got called!'
return text
def ping():
'''
Just used to make sure the minion is up and responding
Return True
CLI Example:
salt '*' test.ping
'''
return True
def fib(num):
'''
Return a fibonachi sequence up to the passed number, and the time it took
to compute in seconds. Used for performance tests
CLI Example:
salt '*' test.fib 3
'''
start = time.time()
a, b = 0, 1
ret = [0]
while b < num:
ret.append(b)
a, b = b, a + b
return ret, time.time() - start
def collatz(start):
'''
Execute the collatz conjecture from the passed starting number, returns
the sequence and the time it took to compute. Used for performance tests.
CLI Example:
salt '*' test.collatz 3
'''
start = time.time()
steps = []
while start != 1:
steps.append(start)
if start > 1:
if start % 2 == 0:
start = start / 2
else:
start = start * 3 + 1
return steps, time.time() - start
|
Remove os.scandir usage (not in python 3.4) | import uuid
import os
from audio_pipeline.util.AudioFileFactory import AudioFileFactory
from audio_pipeline.util import Exceptions
mbid_directory = "Ready To Filewalk"
picard_directory = "Picard Me!"
cache_limit = 30
cancel = -1
checked = 1
unchecked = 0
def has_mbid(track):
"""
Check whether or not the given track has an MBID.
"""
if track.mbid.value:
try:
id = uuid.UUID(track.mbid.value)
good = True
except ValueError as e:
good = False
else:
good = False
return good
def is_release(directory):
track = False
# we'll set this to a DBPOWERAMP config later
#if InputPatterns.release_pattern.match(d):
for f in os.listdir(directory):
file_path = os.path.join(directory, f)
if os.path.isfile(file_path):
try:
track = AudioFileFactory.get(file_path)
except IOError:
track = False
continue
except Exceptions.UnsupportedFiletypeError:
track = False
continue
break
return track
| import uuid
import os
from audio_pipeline.util.AudioFileFactory import AudioFileFactory
from audio_pipeline.util import Exceptions
mbid_directory = "Ready To Filewalk"
picard_directory = "Picard Me!"
cache_limit = 30
cancel = -1
checked = 1
unchecked = 0
def has_mbid(track):
"""
Check whether or not the given track has an MBID.
"""
if track.mbid.value:
try:
id = uuid.UUID(track.mbid.value)
good = True
except ValueError as e:
good = False
else:
good = False
return good
def is_release(directory):
d = os.path.split(directory)[1]
track = False
# we'll set this to a DBPOWERAMP config later
#if InputPatterns.release_pattern.match(d):
for f in os.scandir(directory):
if f.is_file:
file_name = f.name
try:
track = AudioFileFactory.get(f.path)
except IOError:
track = False
continue
except Exceptions.UnsupportedFiletypeError:
track = False
continue
break
return track
|
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: '@'
}
});
|
Restructure format for videos table | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('provider');
$table->string('original_id');
$table->string('custom_id');
$table->string('author');
$table->integer('duration')->default(0);
$table->integer('views')->default(0);
$table->integer('likes')->default(0);
$table->integer('dislikes')->default(0);
$table->text('data');
// Determine whether a video has a DMCA claim
$table->boolean('dmca_claim')->default(false);
$table->softDeletes();
$table->timestamps();
$table->index(['original_id', 'author', 'duration', 'views', 'likes', 'dislikes']);
$table->unique(['original_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('videos');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('provider');
$table->string('original_id');
$table->string('original_url');
$table->string('custom_id');
$table->string('slug')->nullable();
// json encoded video data as returned from API
$table->json('data');
// Determine whether a video has a DMCA claim
$table->boolean('dmca_claim')->default(false);
$table->softDeletes();
$table->timestamps();
$table->unique(['original_id', 'original_url', 'custom_id']);
$table->index(['original_id', 'custom_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('videos');
}
}
|
Add root path to url | <?php
namespace Simox;
class Url extends SimoxServiceBase
{
private $_root_path;
/**
* Base uri is prepended to all resources (css, images, links..)
*/
private $_base_uri;
public function __construct()
{
$this->_base_uri = "/";
$this->_root_path = realpath(__DIR__ . "/../../../../");
}
public function getRootPath()
{
return $this->_root_path;
}
/**
* Sets the base uri
*
* @param string $base_uri
*/
public function setBaseUri( $base_uri )
{
/**
* If there is no prepending slash, add it
*/
if ( $base_uri[0] !== "/" )
{
$base_uri = "/" . $base_uri;
}
/**
* If there is no appending slash, add it
*/
if ($base_uri[strlen($base_uri)-1] !== "/")
{
$base_uri = $base_uri . "/";
}
$this->_base_uri = $base_uri;
}
/**
* Returns the base uri
*
* @return string
*/
public function getBaseUri()
{
return $this->_base_uri;
}
/**
* Appends a given path to the base uri
*
* @param string $path
* @return string
*/
public function get( $path )
{
return $this->getBaseUri() . $path;
}
}
| <?php
namespace Simox;
class Url extends SimoxServiceBase
{
/**
* Base uri is prepended to all resources (css, images, links..)
*/
private $_base_uri;
public function __construct()
{
$this->_base_uri = "/";
}
/**
* Sets the base uri
*
* @param string $base_uri
*/
public function setBaseUri( $base_uri )
{
/**
* If there is no prepending slash, add it
*/
if ( $base_uri[0] !== "/" )
{
$base_uri = "/" . $base_uri;
}
/**
* If there is no appending slash, add it
*/
if ($base_uri[strlen($base_uri)-1] !== "/")
{
$base_uri = $base_uri . "/";
}
$this->_base_uri = $base_uri;
}
/**
* Returns the base uri
*
* @return string
*/
public function getBaseUri()
{
return $this->_base_uri;
}
/**
* Appends a given path to the base uri
*
* @param string $path
* @return string
*/
public function get( $path )
{
return $this->getBaseUri() . $path;
}
public function getRootPath()
{
return "../";
}
}
|
Fix dab command failing on users with multiple words in their name
Closes #22 | package com.nincraft.ninbot.command;
import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
public class DabCommand extends AbstractCommand {
public DabCommand() {
length = 3;
name = "dab";
description = "Adds all dab emojis to the last message of the user named";
}
@Override
public void executeCommand(MessageReceivedEvent event) {
val content = event.getMessage().getContent();
if (isCommandLengthCorrect(content)) {
val channel = event.getChannel();
val dabUser = content.substring(12).replaceFirst("@", "");
int count = 0;
int maxDab = 10;
for (Message message : channel.getIterableHistory()) {
if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) {
dabOnMessage(message);
break;
}
if (count >= maxDab) {
MessageUtils.reactUnsuccessfulResponse(event.getMessage());
break;
}
count++;
}
} else {
MessageUtils.reactUnsuccessfulResponse(event.getMessage());
}
}
private void dabOnMessage(Message message) {
val guild = message.getGuild();
for (val emote : guild.getEmotes()) {
if (emote.getName().contains("dab")) {
MessageUtils.addReaction(message, emote);
}
}
}
@Override
boolean isCommandLengthCorrect(String content) {
return content.split(" ").length >= length;
}
}
| package com.nincraft.ninbot.command;
import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
public class DabCommand extends AbstractCommand {
public DabCommand() {
length = 3;
name = "dab";
description = "Adds all dab emojis to the last message of the user named";
}
@Override
public void executeCommand(MessageReceivedEvent event) {
val content = event.getMessage().getContent();
if (isCommandLengthCorrect(content)) {
val channel = event.getChannel();
val dabUser = content.split(" ")[2].replaceFirst("@", "");
int count = 0;
int maxDab = 10;
for (Message message : channel.getIterableHistory()) {
if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) {
dabOnMessage(message);
break;
}
if (count >= maxDab) {
MessageUtils.reactUnsuccessfulResponse(event.getMessage());
break;
}
count++;
}
} else {
MessageUtils.reactUnsuccessfulResponse(event.getMessage());
}
}
private void dabOnMessage(Message message) {
val guild = message.getGuild();
for (val emote : guild.getEmotes()) {
if (emote.getName().contains("dab")) {
MessageUtils.addReaction(message, emote);
}
}
}
}
|
Fix typo in RevisionUpgrade command. | <?php
namespace Sofa\Revisionable\Laravel;
use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Illuminate\Filesystem\Filesystem;
class RevisionsUpgradeCommand extends Command
{
/** @var string */
protected $name = 'revisions:upgrade-5.3';
/** @var string */
protected $description = 'Create a migration upgrading to v5.3';
/** @var \Illuminate\Filesystem\Filesystem */
protected $files;
/** @var \Illuminate\Foundation\Composer */
protected $composer;
/**
* @param \Illuminate\Filesystem\Filesystem $files
* @param \Illuminate\Foundation\Composer $composer
*/
public function __construct(Filesystem $files, Composer $composer)
{
parent::__construct();
$this->files = $files;
$this->composer = $composer;
}
/**
* Execute the console command.
*/
public function fire()
{
$path = $this->createBaseMigration();
$this->files->put($path, $this->files->get(__DIR__.'/../migrations/upgrade-5.3.stub'));
$this->info('Revisions upgrade migration created successfully!');
$this->composer->dumpAutoloads();
}
/**
* Create a base migration file for the table.
*
* @return string
*/
protected function createBaseMigration()
{
$name = 'add_morph_relation_to_revisions';
$path = $this->laravel->databasePath().'/migrations';
return $this->laravel['migration.creator']->create($name, $path);
}
}
| <?php
namespace Sofa\Revisionable\Laravel;
use Illuminate\Console\Command;
use Illuminate\Support\Composer;
use Illuminate\Filesystem\Filesystem;
class RevisionsUpgradeCommand extends Command
{
/** @var string */
protected $name = 'revisions:upgrade-5.3';
/** @var string */
protected $description = 'Create a migration upgrading to v5.3';
/** @var \Illuminate\Filesystem\Filesystem */
protected $files;
/** @var \Illuminate\Foundation\Composer */
protected $composer;
/**
* @param \Illuminate\Filesystem\Filesystem $files
* @param \Illuminate\Foundation\Composer $composer
*/
public function __construct(Filesystem $files, Composer $composer)
{
parent::__construct();
$this->files = $files;
$this->composer = $composer;
}
/**
* Execute the console command.
*/
public function fire()
{
$path = $this->createBaseMigration();
$this->files->put($path, $this->files->get(__DIR__.'/../migrations/upgrade-5.3stub'));
$this->info('Revisions upgrade migration created successfully!');
$this->composer->dumpAutoloads();
}
/**
* Create a base migration file for the table.
*
* @return string
*/
protected function createBaseMigration()
{
$name = 'add_morph_relation_to_revisions';
$path = $this->laravel->databasePath().'/migrations';
return $this->laravel['migration.creator']->create($name, $path);
}
}
|
Add missing dependency for backend | <?php
class Kwc_Advanced_GoogleMap_Component extends Kwc_Advanced_GoogleMapView_Component
{
public static function getSettings()
{
$ret = array_merge(parent::getSettings(), array(
'componentName' => trlKwfStatic('Google Maps'),
'ownModel' => 'Kwc_Advanced_GoogleMap_Model',
'default' => array(
'zoom' => 8,
'height' => 300
),
));
$ret['componentCategory'] = 'special';
$ret['generators']['child']['component']['text'] = 'Kwc_Basic_Text_Component';
$ret['placeholder']['noCoordinates'] = trlKwfStatic('coordinates not entered');
$ret['assetsAdmin']['dep'][] = 'KwfGoogleMapField';
return $ret;
}
protected function _getOptions()
{
$row = $this->_getRow();
$fields = array('coordinates', 'zoom', 'width', 'height', 'zoom_properties',
'scale', 'satelite', 'overview', 'routing', 'map_type', 'scrollwheel');
foreach ($fields as $f) {
$ret[$f] = $row->$f;
}
if (!isset($ret['coordinates'])) $ret['coordinates'] = '';
return $ret;
}
}
| <?php
class Kwc_Advanced_GoogleMap_Component extends Kwc_Advanced_GoogleMapView_Component
{
public static function getSettings()
{
$ret = array_merge(parent::getSettings(), array(
'componentName' => trlKwfStatic('Google Maps'),
'ownModel' => 'Kwc_Advanced_GoogleMap_Model',
'default' => array(
'zoom' => 8,
'height' => 300
),
));
$ret['componentCategory'] = 'special';
$ret['generators']['child']['component']['text'] = 'Kwc_Basic_Text_Component';
$ret['placeholder']['noCoordinates'] = trlKwfStatic('coordinates not entered');
return $ret;
}
protected function _getOptions()
{
$row = $this->_getRow();
$fields = array('coordinates', 'zoom', 'width', 'height', 'zoom_properties',
'scale', 'satelite', 'overview', 'routing', 'map_type', 'scrollwheel');
foreach ($fields as $f) {
$ret[$f] = $row->$f;
}
if (!isset($ret['coordinates'])) $ret['coordinates'] = '';
return $ret;
}
}
|
Use relative path for db REST API access | 'use strict';
/* Controllers */
var recordControllers = angular.module('myApp.recordControllers', []);
recordControllers.controller('recordCtrl', ['$scope', '$http', '_',
function($scope, $http, _) {
// Initialize
$scope.distance = '25m';
$scope.style = '自由形';
$scope.submit = function() {
let config = {
params: {}
};
if ($scope.name && $scope.name.length > 0) {
config.params.name = $scope.name;
}
if ($scope.distance != '指定なし') {
config.params.distance = $scope.distance;
}
if ($scope.style != '指定なし') {
config.params.style = $scope.style;
}
if ($scope.name) {
$http.get('/db', config)
.success(function(data) {
data = _.uniq(data).sort(function(a, b) {
if (a.year && b.year && a.year !== b.year) {
return a.year - b.year;
} else if (a.month && b.month && a.month !== b.month) {
return a.month - b.month;
} else if (a.day && b.day && a.day !== b.day) {
return a.day - b.day;
}
return 0;
});
$scope.records = data;
});
}
};
}
]);
| 'use strict';
/* Controllers */
var recordControllers = angular.module('myApp.recordControllers', []);
recordControllers.controller('recordCtrl', ['$scope', '$http', '_',
function($scope, $http, _) {
// Initialize
$scope.distance = '25m';
$scope.style = '自由形';
$scope.submit = function() {
let config = {
params: {}
};
if ($scope.name && $scope.name.length > 0) {
config.params.name = $scope.name;
}
if ($scope.distance != '指定なし') {
config.params.distance = $scope.distance;
}
if ($scope.style != '指定なし') {
config.params.style = $scope.style;
}
if ($scope.name) {
$http.get('http://localhost:3000/db', config)
.success(function(data) {
data = _.uniq(data).sort(function(a, b) {
if (a.year && b.year && a.year !== b.year) {
return a.year - b.year;
} else if (a.month && b.month && a.month !== b.month) {
return a.month - b.month;
} else if (a.day && b.day && a.day !== b.day) {
return a.day - b.day;
}
return 0;
});
$scope.records = data;
});
}
};
}
]);
|
Load relationships and remove data formatting | <?php
namespace App\Repositories;
use App\Models\Schedule;
use App\Repositories\Contracts\ScheduleRepositoryInterface;
class ScheduleRepository extends Repository implements ScheduleRepositoryInterface
{
public function __construct(Schedule $model)
{
$this->model = $model;
}
public function getLatestSchedules()
{
$today = date('Y-m-d');
return $this->model->with('departure_station', 'arrival_station', 'train', 'operator')
->where('departure_date', '>=', $today)
->orWhere('arrival_date', '>=', $today)
->get();
}
public function getSchedule($id)
{
$schedule = $this->find($id);
$schedule->load('departure_station', 'arrival_station', 'train', 'operator');
return $schedule;
}
public function search($departure, $arrival)
{
$query = $this->model->with('departure_station', 'arrival_station', 'train', 'operator');
if ($departure) {
$query = $query->where('departure_station_id', $departure);
}
if ($arrival) {
$query = $query->where('arrival_station_id', $arrival);
}
$results = $query->get();
return ! $results->isEmpty() ? $results : [];
}
}
| <?php
namespace App\Repositories;
use App\Models\Schedule;
use App\Repositories\Contracts\ScheduleRepositoryInterface;
class ScheduleRepository extends Repository implements ScheduleRepositoryInterface
{
public function __construct(Schedule $model)
{
$this->model = $model;
}
public function getLatestSchedules()
{
$today = date('Y-m-d');
return $this->model->with('departure_station', 'arrival_station', 'train', 'operator')
->where('departure_date', '>=', $today)
->orWhere('arrival_date', '>=', $today)
->get();
}
public function getSchedule($id)
{
$schedule = $this->find($id);
$schedule->load('departure_station', 'arrival_station', 'train', 'operator');
return $schedule;
}
public function search($departure, $arrival)
{
$query = $this->model;
if ($departure) {
$query = $query->where('departure_station_id', $departure);
}
if ($arrival) {
$query = $query->where('arrival_station_id', $arrival);
}
$results = $query->get();
return $this->getFormattedData($results);
}
}
|
Fix 500 error when no ID parameter is passed | import json
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, Http404
from django.views.generic.detail import BaseDetailView
from .models import Marker
class MarkerDetailView(BaseDetailView):
"""
Simple view for fetching marker details.
"""
# TODO: support different object types. Perhaps through django-polymorphic?
model = Marker
pk_url_kwarg = 'id'
def get_object(self, queryset=None):
"""
Returns the object the view is displaying.
"""
if queryset is None:
queryset = self.get_queryset()
# Take a GET parameter instead of URLConf variable.
try:
pk = long(self.request.GET[self.pk_url_kwarg])
except (KeyError, ValueError):
raise Http404("Invalid Parameters")
queryset = queryset.filter(pk=pk)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except ObjectDoesNotExist as e:
raise Http404(e)
return obj
def render_to_response(self, context):
return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8')
def get_json_data(self, context):
"""
Generate the JSON data to send back to the client.
:rtype: dict
"""
return self.object.to_dict(detailed=True)
| import json
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, Http404, HttpResponseBadRequest
from django.views.generic.detail import BaseDetailView
from .models import Marker
class MarkerDetailView(BaseDetailView):
"""
Simple view for fetching marker details.
"""
# TODO: support different object types. Perhaps through django-polymorphic?
model = Marker
pk_url_kwarg = 'id'
def get_object(self, queryset=None):
"""
Returns the object the view is displaying.
"""
if queryset is None:
queryset = self.get_queryset()
# Take a GET parameter instead of URLConf variable.
try:
pk = long(self.request.GET[self.pk_url_kwarg])
except (KeyError, ValueError):
return HttpResponseBadRequest("Invalid Parameters")
queryset = queryset.filter(pk=pk)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except ObjectDoesNotExist as e:
raise Http404(e)
return obj
def render_to_response(self, context):
return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8')
def get_json_data(self, context):
"""
Generate the JSON data to send back to the client.
:rtype: dict
"""
return self.object.to_dict(detailed=True)
|
Set blocked attribute when account is created | /** facebook.js
* @file: /config/passport/facebook.js
* @description: Handles passport authentication for Facebook strategy
* @parameters: Object(config)
* @exports: Facebook authentication for Passport
*/
var FacebookStrategy = require('passport-facebook').Strategy
module.exports = function(resources) {
return new FacebookStrategy({
clientID: resources.config.facebook.app_id,
clientSecret: resources.config.facebook.app_secret,
callbackURL: resources.config.facebook.callback,
profileFields: ['id', 'name', 'displayName', 'picture.type(large)'],
}, function (access_token, refresh_token, profile, done) {
var usersdb = resources.collections.users
usersdb.findAndModify({
auth: {
facebook: profile.id
}
},
[
['_id','asc'] // sort order
], {
$setOnInsert: {
auth: {
facebook: profile.id
},
name: {
display_name: profile.displayName,
first: profile.name.givenName
},
info: {
website: null,
description: null,
blocked: false
},
fb_photo: (profile.photos) ? profile.photos[0].value : '/unknown_user.png',
active_photo: 'facebook',
}
}, {
new: true,
upsert: true
}, function (error, result) {
done(error, {
id: result.value._id,
display_name: result.value.name.display_name,
fb_photo: result.value.photo,
active_photo: 'facebook'
})
})
})
} | /** facebook.js
* @file: /config/passport/facebook.js
* @description: Handles passport authentication for Facebook strategy
* @parameters: Object(config)
* @exports: Facebook authentication for Passport
*/
var FacebookStrategy = require('passport-facebook').Strategy
module.exports = function(resources) {
return new FacebookStrategy({
clientID: resources.config.facebook.app_id,
clientSecret: resources.config.facebook.app_secret,
callbackURL: resources.config.facebook.callback,
profileFields: ['id', 'name', 'displayName', 'picture.type(large)'],
}, function (access_token, refresh_token, profile, done) {
var usersdb = resources.collections.users
usersdb.findAndModify({
auth: {
facebook: profile.id
}
},
[
['_id','asc'] // sort order
], {
$setOnInsert: {
auth: {
facebook: profile.id
},
name: {
display_name: profile.displayName,
first: profile.name.givenName
},
info: {
website: null,
description: null,
},
fb_photo: (profile.photos) ? profile.photos[0].value : '/unknown_user.png',
active_photo: 'facebook'
}
}, {
new: true,
upsert: true
}, function (error, result) {
done(error, {
id: result.value._id,
display_name: result.value.name.display_name,
fb_photo: result.value.photo,
active_photo: 'facebook'
})
})
})
} |
Update git command that will support old version of git also | <?php
if (! function_exists('create_hooks_dir')) {
/**
* Create hook directory if not exists.
*
* @param string $dir
* @param int $mode
* @param bool $recursive
*
* @return void
*/
function create_hooks_dir($dir, $mode = 0700, $recursive = true)
{
if (! is_dir("{$dir}/hooks")) {
mkdir("{$dir}/hooks", $mode, $recursive);
}
}
}
if (! function_exists('is_windows')) {
/**
* Determine whether the current environment is Windows based.
*
* @return bool
*/
function is_windows()
{
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
}
if (! function_exists('global_hook_dir')) {
/**
* Gets the global directory set for git hooks
*/
function global_hook_dir()
{
return trim(shell_exec('git config --global core.hooksPath'));
}
}
if (! function_exists('absolute_git_dir')) {
/**
* Resolve absolute git dir which will serve as the default git dir
* if one is not provided by the user.
*/
function absolute_git_dir()
{
return trim(shell_exec('git rev-parse --git-dir'));
}
}
| <?php
if (! function_exists('create_hooks_dir')) {
/**
* Create hook directory if not exists.
*
* @param string $dir
* @param int $mode
* @param bool $recursive
*
* @return void
*/
function create_hooks_dir($dir, $mode = 0700, $recursive = true)
{
if (! is_dir("{$dir}/hooks")) {
mkdir("{$dir}/hooks", $mode, $recursive);
}
}
}
if (! function_exists('is_windows')) {
/**
* Determine whether the current environment is Windows based.
*
* @return bool
*/
function is_windows()
{
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
}
if (! function_exists('global_hook_dir')) {
/**
* Gets the global directory set for git hooks
*/
function global_hook_dir()
{
return trim(shell_exec('git config --global core.hooksPath'));
}
}
if (! function_exists('absolute_git_dir')) {
/**
* Resolve absolute git dir which will serve as the default git dir
* if one is not provided by the user.
*/
function absolute_git_dir()
{
return trim(shell_exec('git rev-parse --absolute-git-dir'));
}
}
|
Install mock package when not in stdlib | #!/usr/bin/env python
from distutils.core import setup
from clusterjob import __version__
try:
# In Python >3.3, 'mock' is part of the standard library
import unittest.mock
mock_package = []
except ImportError:
# In other versions, it has be to be installed as an exernal package
mock_package = ['mock', ]
setup(name='clusterjob',
version=__version__,
description='Manage traditional HPC cluster workflows in Python',
author='Michael Goerz',
author_email='[email protected]',
url='https://github.com/goerz/clusterjob',
license='GPL',
extras_require={'dev': ['pytest', 'pytest-capturelog', 'sphinx',
'sphinx-autobuild', 'sphinx_rtd_theme',
'coverage', 'pytest-cov'] + mock_package},
packages=['clusterjob', 'clusterjob.backends'],
scripts=[],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Topic :: Scientific/Engineering',
'Topic :: System :: Clustering',
'Topic :: Utilities',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
]
)
| #!/usr/bin/env python
from distutils.core import setup
from clusterjob import __version__
setup(name='clusterjob',
version=__version__,
description='Manage traditional HPC cluster workflows in Python',
author='Michael Goerz',
author_email='[email protected]',
url='https://github.com/goerz/clusterjob',
license='GPL',
extras_require={'dev': ['pytest', 'pytest-capturelog', 'sphinx',
'sphinx-autobuild', 'sphinx_rtd_theme',
'coverage', 'pytest-cov']},
packages=['clusterjob', 'clusterjob.backends'],
scripts=[],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Topic :: Scientific/Engineering',
'Topic :: System :: Clustering',
'Topic :: Utilities',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
]
)
|
Make isStandalone() compatible with webkit1
In webkit1 implementation, we don't use 'activity' as a protocol. | define(function () {
'use strict';
var env = {};
env.getEnvironment = function (callback) {
// FIXME: we assume this code runs on the same thread as the
// javascript executed from sugar-toolkit-gtk3 (python)
if (env.isStandalone()) {
setTimeout(function () {
callback(null, {});
}, 0);
} else {
var environmentCallback = function () {
callback(null, window.top.sugar.environment);
};
if (window.top.sugar) {
setTimeout(function () {
environmentCallback();
}, 0);
} else {
window.top.sugar = {};
window.top.sugar.onEnvironmentSet = function () {
environmentCallback();
};
}
}
};
env.getObjectId = function (callback) {
env.getEnvironment(function (error, environment) {
callback(environment.objectId);
});
};
env.getURLScheme = function () {
return window.location.protocol;
};
env.isStandalone = function () {
var webActivityURLScheme = "activity:";
var currentURLScheme = env.getURLScheme();
// the control of hostname !== '0.0.0.0' is used
// for compatibility with F18 and webkit1
return currentURLScheme !== webActivityURLScheme &&
window.location.hostname !== '0.0.0.0';
};
return env;
});
| define(function () {
'use strict';
var env = {};
env.getEnvironment = function (callback) {
// FIXME: we assume this code runs on the same thread as the
// javascript executed from sugar-toolkit-gtk3 (python)
if (env.isStandalone()) {
setTimeout(function () {
callback(null, {});
}, 0);
} else {
var environmentCallback = function () {
callback(null, window.top.sugar.environment);
};
if (window.top.sugar) {
setTimeout(function () {
environmentCallback();
}, 0);
} else {
window.top.sugar = {};
window.top.sugar.onEnvironmentSet = function () {
environmentCallback();
};
}
}
};
env.getObjectId = function (callback) {
env.getEnvironment(function (error, environment) {
callback(environment.objectId);
});
};
env.getURLScheme = function () {
return window.location.protocol;
};
env.isStandalone = function () {
var webActivityURLScheme = "activity:";
var currentURLScheme = env.getURLScheme();
return currentURLScheme !== webActivityURLScheme;
};
return env;
});
|
Remove `files` key from BrowserSync config, to prevent double reload | let argv = require('yargs').argv;
let bin = require('./bin');
let command = require('node-cmd');
let AfterWebpack = require('on-build-webpack');
let BrowserSync = require('browser-sync');
let BrowserSyncPlugin = require('browser-sync-webpack-plugin');
let Watch = require('webpack-watch');
let browserSyncInstance;
let env = argv.e || argv.env || 'local';
let port = argv.p || argv.port || 3000;
module.exports = {
jigsaw: new AfterWebpack(() => {
command.get(bin.path() + ' build ' + env, (error, stdout, stderr) => {
console.log(error ? stderr : stdout);
if (browserSyncInstance) {
browserSyncInstance.reload();
}
});
}),
watch: function(paths) {
return new Watch({
options: { ignoreInitial: true },
paths: paths,
})
},
browserSync: function(proxy) {
return new BrowserSyncPlugin({
notify: false,
port: port,
proxy: proxy,
server: proxy ? null : { baseDir: 'build_' + env + '/' },
},
{
reload: false,
callback: function() {
browserSyncInstance = BrowserSync.get('bs-webpack-plugin');
},
})
},
};
| let argv = require('yargs').argv;
let bin = require('./bin');
let command = require('node-cmd');
let AfterWebpack = require('on-build-webpack');
let BrowserSync = require('browser-sync');
let BrowserSyncPlugin = require('browser-sync-webpack-plugin');
let Watch = require('webpack-watch');
let browserSyncInstance;
let env = argv.e || argv.env || 'local';
let port = argv.p || argv.port || 3000;
module.exports = {
jigsaw: new AfterWebpack(() => {
command.get(bin.path() + ' build ' + env, (error, stdout, stderr) => {
console.log(error ? stderr : stdout);
if (browserSyncInstance) {
browserSyncInstance.reload();
}
});
}),
watch: function(paths) {
return new Watch({
options: { ignoreInitial: true },
paths: paths,
})
},
browserSync: function(proxy) {
return new BrowserSyncPlugin({
files: [ 'build_' + env + '/**/*' ],
notify: false,
port: port,
proxy: proxy,
server: proxy ? null : { baseDir: 'build_' + env + '/' },
},
{
reload: false,
callback: function() {
browserSyncInstance = BrowserSync.get('bs-webpack-plugin');
},
})
},
};
|
Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS | import os
from celery.loaders.base import BaseLoader
DEFAULT_CONFIG_MODULE = "celeryconfig"
DEFAULT_SETTINGS = {
"DEBUG": False,
"DATABASE_ENGINE": "sqlite3",
"DATABASE_NAME": "celery.sqlite",
"INSTALLED_APPS": ("celery", ),
}
def wanted_module_item(item):
is_private = item.startswith("_")
return not is_private
class Loader(BaseLoader):
"""The default loader.
See the FAQ for example usage.
"""
def read_configuration(self):
"""Read configuration from ``celeryconfig.py`` and configure
celery and Django so it can be used by regular Python."""
config = dict(DEFAULT_SETTINGS)
configname = os.environ.get("CELERY_CONFIG_MODULE",
DEFAULT_CONFIG_MODULE)
celeryconfig = __import__(configname, {}, {}, [''])
import celeryconfig
usercfg = dict((key, getattr(celeryconfig, key))
for key in dir(celeryconfig)
if wanted_module_item(key))
config.update(usercfg)
from django.conf import settings
if not settings.configured:
settings.configure()
for config_key, config_value in usercfg.items():
setattr(settings, config_key, config_value)
return settings
def on_worker_init(self):
"""Imports modules at worker init so tasks can be registered
and used by the worked.
The list of modules to import is taken from the ``CELERY_IMPORTS``
setting in ``celeryconf.py``.
"""
imports = getattr(self.conf, "CELERY_IMPORTS", [])
for module in imports:
__import__(module, [], [], [''])
| from celery.loaders.base import BaseLoader
DEFAULT_SETTINGS = {
"DEBUG": False,
"DATABASE_ENGINE": "sqlite3",
"DATABASE_NAME": "celery.sqlite",
"INSTALLED_APPS": ("celery", ),
}
def wanted_module_item(item):
is_private = item.startswith("_")
return not is_private
class Loader(BaseLoader):
"""The default loader.
See the FAQ for example usage.
"""
def read_configuration(self):
"""Read configuration from ``celeryconf.py`` and configure
celery and Django so it can be used by regular Python."""
config = dict(DEFAULT_SETTINGS)
import celeryconfig
usercfg = dict((key, getattr(celeryconfig, key))
for key in dir(celeryconfig)
if wanted_module_item(key))
config.update(usercfg)
from django.conf import settings
if not settings.configured:
settings.configure()
for config_key, config_value in usercfg.items():
setattr(settings, config_key, config_value)
return settings
def on_worker_init(self):
"""Imports modules at worker init so tasks can be registered
and used by the worked.
The list of modules to import is taken from the ``CELERY_IMPORTS``
setting in ``celeryconf.py``.
"""
imports = getattr(self.conf, "CELERY_IMPORTS", [])
for module in imports:
__import__(module, [], [], [''])
|
Fix behavior on create new version
- Was not redirecting to the correct state | (function() {'use strict';
angular.module('ag-admin').controller(
'ApiVersionController',
function($scope, $timeout, $state, $stateParams, flash, ApiRepository) {
ApiRepository.getApi($stateParams.apiName, $stateParams.version).then(function (api) {
$scope.api = api;
$scope.currentVersion = api.version;
$scope.defaultApiVersion = api.default_version;
});
$scope.createNewApiVersion = function () {
ApiRepository.createNewVersion($scope.api.name).then(function (data) {
flash.success = 'A new version of this API was created';
$timeout(function () {
$state.go('ag.api.version', {apiName: $scope.api.name, version: data.version});
}, 500);
});
};
$scope.setDefaultApiVersion = function () {
flash.info = 'Setting the default API version to ' + $scope.defaultApiVersion;
ApiRepository.setDefaultApiVersion($scope.api.name, $scope.defaultApiVersion).then(function (data) {
flash.success = 'Default API version updated';
$scope.defaultApiVersion = data.version;
});
};
$scope.changeVersion = function () {
$timeout(function () {
$state.go($state.$current, {version: $scope.currentVersion});
}, 500);
};
}
);
})();
| (function() {'use strict';
angular.module('ag-admin').controller(
'ApiVersionController',
function($scope, $timeout, $state, $stateParams, flash, ApiRepository) {
ApiRepository.getApi($stateParams.apiName, $stateParams.version).then(function (api) {
$scope.api = api;
$scope.currentVersion = api.version;
$scope.defaultApiVersion = api.default_version;
});
$scope.createNewApiVersion = function () {
ApiRepository.createNewVersion($scope.api.name).then(function (data) {
flash.success = 'A new version of this API was created';
$timeout(function () {
$state.go('ag.api', {apiName: $scope.api.name, version: data.version});
}, 500);
});
};
$scope.setDefaultApiVersion = function () {
flash.info = 'Setting the default API version to ' + $scope.defaultApiVersion;
ApiRepository.setDefaultApiVersion($scope.api.name, $scope.defaultApiVersion).then(function (data) {
flash.success = 'Default API version updated';
$scope.defaultApiVersion = data.version;
});
};
$scope.changeVersion = function () {
$timeout(function () {
$state.go($state.$current, {version: $scope.currentVersion});
}, 500);
};
}
);
})();
|
Bump version number to 0.0.2 | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
version='0.0.2',
description='Swagger UI blueprint for Flask',
long_description=long_description,
url='https://github.com/sveint/flask-swagger-ui',
author='Svein Tore Koksrud Seljebotn',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='flask swagger',
packages=['flask_swagger_ui'],
package_data={
'flask_swagger_ui': [
'README.md',
'templates/*.html',
'dist/VERSION',
'dist/LICENSE',
'dist/README.md',
'dist/*.html',
'dist/*.js',
'dist/*/*.js',
'dist/*/*.css',
'dist/*/*.gif',
'dist/*/*.png',
'dist/*/*.ico',
'dist/*/*.ttf',
],
}
)
| from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='flask-swagger-ui',
version='0.0.1a',
description='Swagger UI blueprint for Flask',
long_description=long_description,
url='https://github.com/sveint/flask-swagger-ui',
author='Svein Tore Koksrud Seljebotn',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='flask swagger',
packages=['flask_swagger_ui'],
package_data={
'flask_swagger_ui': [
'README.md',
'templates/*.html',
'dist/VERSION',
'dist/LICENSE',
'dist/README.md',
'dist/*.html',
'dist/*.js',
'dist/*/*.js',
'dist/*/*.css',
'dist/*/*.gif',
'dist/*/*.png',
'dist/*/*.ico',
'dist/*/*.ttf',
],
}
)
|
Fix display tests in navbar
prev $this->data[] is overwritten QuestionEdit by controller | <?php
namespace Egzaminer\Question;
use Egzaminer\Admin\Dashboard as Controller;
class QuestionAdd extends Controller
{
public function addAction($testId)
{
$this->testId = $testId;
$this->data['question'] = [
'content' => '',
'correct' => '',
];
$this->data['answers'] = [
['content' => '', 'id' => '1'],
['content' => '', 'id' => '2'],
['content' => '', 'id' => '3'],
['content' => '', 'id' => '4'],
];
if (isset($_POST['submit'])) {
$model = new QuestionAddModel();
if ($id = $model->add($testId, $_POST)) {
$_SESSION['valid'] = true;
header('Location: '.$this->dir().'/admin/test/edit/'.$testId.'/question/edit/'.$id);
exit;
} else {
$this->data['invalid'] = true;
}
}
$this->render('admin-question', 'Dodawanie pytania');
}
}
| <?php
namespace Egzaminer\Question;
use Egzaminer\Admin\Dashboard as Controller;
class QuestionAdd extends Controller
{
public function addAction($testId)
{
$this->testId = $testId;
$this->data = [
'question' => [
'content' => '',
'correct' => '',
],
'answers' => [
['content' => '', 'id' => '1'],
['content' => '', 'id' => '2'],
['content' => '', 'id' => '3'],
['content' => '', 'id' => '4'],
],
];
if (isset($_POST['submit'])) {
$model = new QuestionAddModel();
if ($id = $model->add($testId, $_POST)) {
$_SESSION['valid'] = true;
header('Location: '.$this->dir().'/admin/test/edit/'.$testId.'/question/edit/'.$id);
exit;
} else {
$this->data['invalid'] = true;
}
}
$this->render('admin-question', 'Dodawanie pytania');
}
}
|
Set overflow:hidden to hide default windows scrollbars on drawer | import React from 'react';
import Drawer from 'material-ui/Drawer';
import DrawerMenuItems from '../../containers/drawer-menu-items';
import * as ImagesHelper from '../../../util/images';
export default class DrawerNavigation extends React.Component {
componentDidMount() {
// iubenda Privacy Policy
(function(w, d) {
var loader = function() {
var s = d.createElement("script"),
tag = d.getElementsByTagName("script")[0];
s.src = "//cdn.iubenda.com/iubenda.js";
tag.parentNode.insertBefore(s, tag);
};
if (w.addEventListener) {
w.addEventListener("load", loader, false);
} else if (w.attachEvent) {
w.attachEvent("onload", loader);
} else {
w.onload = loader;
}
})(window, document);
}
render() {
return (
<Drawer docked={ false } width={ 250 } open={ this.props.isOpen } onRequestChange={ isOpen => this.props.setDrawerOpen(isOpen) } containerStyle={{'overflow': 'hidden'}}>
<DrawerMenuItems closeDrawer={ this.props.closeDrawer } />
<div className="iubenda-button">
<a href="//www.iubenda.com/privacy-policy/7885534" className="iubenda-white iubenda-embed" title="Privacy Policy">Privacy Policy</a>
</div>
</Drawer>
);
}
};
DrawerNavigation.propTypes = {
isOpen: React.PropTypes.bool.isRequired,
closeDrawer: React.PropTypes.func,
};
| import React from 'react';
import Drawer from 'material-ui/Drawer';
import DrawerMenuItems from '../../containers/drawer-menu-items';
import * as ImagesHelper from '../../../util/images';
export default class DrawerNavigation extends React.Component {
componentDidMount() {
// iubenda Privacy Policy
(function(w, d) {
var loader = function() {
var s = d.createElement("script"),
tag = d.getElementsByTagName("script")[0];
s.src = "//cdn.iubenda.com/iubenda.js";
tag.parentNode.insertBefore(s, tag);
};
if (w.addEventListener) {
w.addEventListener("load", loader, false);
} else if (w.attachEvent) {
w.attachEvent("onload", loader);
} else {
w.onload = loader;
}
})(window, document);
}
render() {
return (
<Drawer docked={ false } width={ 250 } open={ this.props.isOpen } onRequestChange={ isOpen => this.props.setDrawerOpen(isOpen) }>
<DrawerMenuItems closeDrawer={ this.props.closeDrawer } />
<div className="iubenda-button">
<a href="//www.iubenda.com/privacy-policy/7885534" className="iubenda-white iubenda-embed" title="Privacy Policy">Privacy Policy</a>
</div>
</Drawer>
);
}
};
DrawerNavigation.propTypes = {
isOpen: React.PropTypes.bool.isRequired,
closeDrawer: React.PropTypes.func,
};
|
Fix Gulp watch for theme files
Rebuild when a theme file is modified | /*!
* gulpfile
*/
// Load plugins
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var rename = require('gulp-rename');
var jade = require('gulp-jade');
var inline = require('gulp-inline-css');
// Paths
var sourcePath = 'src';
var paths = {
emails: sourcePath + '/emails/**/*.jade',
styles: sourcePath + '/themes/**/*.styl'
};
// Styles
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(stylus({
compress: true
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest(sourcePath + '/themes'));
});
// Templates
gulp.task('emails', ['styles'], function() {
return gulp.src(paths.emails)
.pipe(jade({
pretty: true
}))
.pipe(inline({
applyStyleTags: false,
removeStyleTags: false
}))
.pipe(gulp.dest('dist'));
});
// Watch
gulp.task('watch', function() {
gulp.watch(sourcePath + '/**/*.jade', ['emails']);
gulp.watch(sourcePath + '/themes/**/*.styl', ['emails']);
});
gulp.task('default', ['watch', 'emails']);
| /*!
* gulpfile
*/
// Load plugins
var gulp = require('gulp');
var stylus = require('gulp-stylus');
var rename = require('gulp-rename');
var jade = require('gulp-jade');
var inline = require('gulp-inline-css');
// Paths
var sourcePath = 'src';
var paths = {
emails: sourcePath + '/emails/**/*.jade',
styles: sourcePath + '/themes/**/*.styl'
};
// Styles
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(stylus({
compress: true
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest(sourcePath + '/themes'));
});
// Templates
gulp.task('emails', ['styles'], function() {
return gulp.src(paths.emails)
.pipe(jade({
pretty: true
}))
.pipe(inline({
applyStyleTags: false,
removeStyleTags: false
}))
.pipe(gulp.dest('dist'));
});
// Watch
gulp.task('watch', function() {
gulp.watch(sourcePath + '/emails/**/*.jade', ['emails']);
gulp.watch(sourcePath + '/themes/**/*.styl', ['styles']);
});
gulp.task('default', ['watch', 'emails']);
|
Fix Elastica_Log param. Remove Elastica_Client here | <?php
require_once dirname(__FILE__) . '/../../bootstrap.php';
class Elastica_LogTest extends Elastica_Test
{
public function testSetLogConfigPath()
{
$logPath = '/tmp/php.log';
$client = new Elastica_Client(array('log' => $logPath));
$this->assertEquals($logPath, $client->getConfig('log'));
}
public function testSetLogConfigEnable()
{
$client = new Elastica_Client(array('log' => true));
$this->assertTrue($client->getConfig('log'));
}
public function testEmptyLogConfig()
{
$client = new Elastica_Client();
$this->assertEmpty($client->getConfig('log'));
}
public function testGetLastMessage()
{
$log = new Elastica_Log('/tmp/php.log');
$message = 'hello world';
$log->log($message);
$this->assertEquals($message, $log->getLastMessage());
}
public function testGetLastMessage2()
{
$client = new Elastica_Client(array('log' => true));
$log = new Elastica_Log($client);
// Set log path temp path as otherwise test fails with output
$errorLog = ini_get('error_log');
ini_set('error_log', sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php.log');
$message = 'hello world';
$log->log($message);
ini_set('error_log', $errorLog);
$this->assertEquals($message, $log->getLastMessage());
}
}
| <?php
require_once dirname(__FILE__) . '/../../bootstrap.php';
class Elastica_LogTest extends Elastica_Test
{
public function testSetLogConfigPath()
{
$logPath = '/tmp/php.log';
$client = new Elastica_Client(array('log' => $logPath));
$this->assertEquals($logPath, $client->getConfig('log'));
}
public function testSetLogConfigEnable()
{
$client = new Elastica_Client(array('log' => true));
$this->assertTrue($client->getConfig('log'));
}
public function testEmptyLogConfig()
{
$client = new Elastica_Client();
$this->assertEmpty($client->getConfig('log'));
}
public function testGetLastMessage()
{
$client = new Elastica_Client(array('log' => '/tmp/php.log'));
$log = new Elastica_Log($client);
$message = 'hello world';
$log->log($message);
$this->assertEquals($message, $log->getLastMessage());
}
public function testGetLastMessage2()
{
$client = new Elastica_Client(array('log' => true));
$log = new Elastica_Log($client);
// Set log path temp path as otherwise test fails with output
$errorLog = ini_get('error_log');
ini_set('error_log', sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'php.log');
$message = 'hello world';
$log->log($message);
ini_set('error_log', $errorLog);
$this->assertEquals($message, $log->getLastMessage());
}
}
|
Fix wrong template usage in error pages | package li.l1t.tingo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* Controls displaying of error messages.
*
* @author <a href="http://xxyy.github.io/">xxyy</a>
* @since 7.4.16
*/
@Controller
public class TingoErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
@Autowired
private ErrorAttributes errorAttributes;
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String errorHtml(HttpServletRequest request, Model model) {
Object errCodeObj = request.getAttribute("javax.servlet.error.status_code");
int errorCode = errCodeObj == null ? 0 : (int) errCodeObj;
model.addAttribute("errorCode", errCodeObj);
model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception"));
switch(errorCode) {
case 401:
return "error/401";
case 0:
default:
return "error/generic";
}
}
}
| package li.l1t.tingo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* Controls displaying of error messages.
*
* @author <a href="http://xxyy.github.io/">xxyy</a>
* @since 7.4.16
*/
@Controller
public class TingoErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
@Autowired
private ErrorAttributes errorAttributes;
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String errorHtml(HttpServletRequest request, Model model) {
Object errCodeObj = request.getAttribute("javax.servlet.error.status_code");
int errorCode = errCodeObj == null ? 0 : (int) errCodeObj;
model.addAttribute("errorCode", errCodeObj);
model.addAttribute("errorType", request.getAttribute("javax.servlet.error.exception"));
switch(errorCode) {
case 401:
return "error/401.html";
case 0:
default:
return "error/generic.html";
}
}
}
|
Install yarn.lock in target project | const Generator = require('yeoman-generator')
const humps = require('humps')
module.exports = class ReactZeal extends Generator {
prompting() {
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your project name',
default: kabob(this.appname)
}
]).then(function(answers) {
this.appName = kabob(answers.name)
}.bind(this))
}
writing() {
this.fs.copyTpl(
this.templatePath('package.json'),
this.destinationPath('package.json'),
{ appName: this.appName }
)
this.fs.copy(this.templatePath('client'), this.destinationPath('client'))
this.fs.copy(
this.templatePath('.eslintrc.json'),
this.destinationPath('.eslintrc.json')
)
this.fs.copy(
this.templatePath('.sass-lint.yml'),
this.destinationPath('.sass-lint.yml')
)
this.fs.copy(
this.templatePath('yarn.lock'),
this.destinationPath('yarn.lock')
)
this._mergeGitIgnore()
}
_mergeGitIgnore() {
const template = this.fs.read(this.templatePath('gitignore'))
const existing = this.fs.read(this.destinationPath('.gitignore'), {
defaults: ''
})
this.fs.write(
this.destinationPath('.gitignore'),
existing + '\n\n' + template
)
}
}
function kabob(string) {
return humps.decamelize(humps.camelize(string), { separator: '-' })
}
| const Generator = require('yeoman-generator')
const humps = require('humps')
module.exports = class ReactZeal extends Generator {
prompting() {
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your project name',
default: kabob(this.appname)
}
]).then(function(answers) {
this.appName = kabob(answers.name)
}.bind(this))
}
writing() {
this.fs.copyTpl(
this.templatePath('package.json'),
this.destinationPath('package.json'),
{ appName: this.appName }
)
this.fs.copy(this.templatePath('client'), this.destinationPath('client'))
this.fs.copy(
this.templatePath('.eslintrc.json'),
this.destinationPath('.eslintrc.json')
)
this.fs.copy(
this.templatePath('.sass-lint.yml'),
this.destinationPath('.sass-lint.yml')
)
this._mergeGitIgnore()
}
_mergeGitIgnore() {
const template = this.fs.read(this.templatePath('gitignore'))
const existing = this.fs.read(this.destinationPath('.gitignore'), {
defaults: ''
})
this.fs.write(
this.destinationPath('.gitignore'),
existing + '\n\n' + template
)
}
}
function kabob(string) {
return humps.decamelize(humps.camelize(string), { separator: '-' })
}
|
Move logic out of the loop. | <?php
namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;
final class Linear implements Gradient
{
/** @var int */
private $power;
/**
* @param int $power
*/
public function __construct($power = 2)
{
$this->power = $power;
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return float
*/
public function cost(array $coefficients, array $features, $outcome)
{
return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power);
}
/**
* @param array $coefficients
* @param array $features
* @return float
*/
private function predicted(array $coefficients, array $features)
{
return array_sum(array_map(function ($coefficient, $feature) {
return $coefficient * $feature;
}, $coefficients, $features));
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return array
*/
public function gradient(array $coefficients, array $features, $outcome)
{
$gradient = [];
$iterationConstant = $this->power * pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power - 1);
foreach ($features as $feature) {
$gradient[] = $iterationConstant * $feature;
}
return $gradient;
}
}
| <?php
namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;
final class Linear implements Gradient
{
/** @var int */
private $power;
/**
* @param int $power
*/
public function __construct($power = 2)
{
$this->power = $power;
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return float
*/
public function cost(array $coefficients, array $features, $outcome)
{
return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power);
}
/**
* @param array $coefficients
* @param array $features
* @return float
*/
private function predicted(array $coefficients, array $features)
{
return array_sum(array_map(function ($coefficient, $feature) {
return $coefficient * $feature;
}, $coefficients, $features));
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return array
*/
public function gradient(array $coefficients, array $features, $outcome)
{
$gradient = [];
$predicted = $this->predicted($coefficients, $features);
foreach ($features as $feature) {
$gradient[] = $this->power * pow(abs($predicted - $outcome), $this->power - 1) * $feature;
}
return $gradient;
}
}
|
Add built-in interceptors via configration | JARS.internal('InternalBootstrapper', function(InternalsManager) {
'use strict';
var getInternal = InternalsManager.get,
InternalBootstrapper;
/**
* @namespace
*
* @memberof JARS.internals
*/
InternalBootstrapper = {
bootstrap: function() {
var SourceManager = getInternal('SourceManager'),
System = getInternal('System'),
Loader = getInternal('Loader'),
ConfigsManager = getInternal('ConfigsManager');
Loader.getRootModule().$export();
Loader.registerModule('System', ['Logger', 'Modules']).$export(function systemFactory() {
// TODO maybe calling the internal factory for System is the better option
// to isolate System on a per context basis but right now this is enough
/**
* @global
* @module System
* @see JARS.internals.System
*/
return System;
});
ConfigsManager.update({
modules: [{
basePath: SourceManager.BASE_PATH,
cache: true,
minified: false,
timeout: 5
}, {
restrict: 'System.*',
basePath: SourceManager.INTERNALS_PATH
}],
interceptors: [
getInternal('PluginInterceptor'),
getInternal('PartialModuleInterceptor')
]
});
}
};
return InternalBootstrapper;
});
| JARS.internal('InternalBootstrapper', function(InternalsManager) {
'use strict';
var getInternal = InternalsManager.get,
InternalBootstrapper;
/**
* @namespace
*
* @memberof JARS.internals
*/
InternalBootstrapper = {
bootstrap: function() {
var SourceManager = getInternal('SourceManager'),
System = getInternal('System'),
Loader = getInternal('Loader'),
ConfigsManager = getInternal('ConfigsManager'),
InterceptionManager = getInternal('InterceptionManager');
InterceptionManager.addInterceptor(getInternal('PluginInterceptor'));
InterceptionManager.addInterceptor(getInternal('PartialModuleInterceptor'));
Loader.getRootModule().$export();
Loader.registerModule('System', ['Logger', 'Modules']).$export(function systemFactory() {
// TODO maybe calling the internal factory for System is the better option
// to isolate System on a per context basis but right now this is enough
/**
* @global
* @module System
* @see JARS.internals.System
*/
return System;
});
ConfigsManager.update({
modules: [{
basePath: SourceManager.BASE_PATH,
cache: true,
minified: false,
timeout: 5
}, {
restrict: 'System.*',
basePath: SourceManager.INTERNALS_PATH
}]
});
}
};
return InternalBootstrapper;
});
|
Add documentation to BaseCaller and BaseOptimizer class | """
This module provides an abstract base class for implementing optimizer
"""
from __future__ import division, print_function, with_statement
from abc import abstractmethod, ABCMeta # Abstract Base Class
class BaseOptimizer(object):
"""
Abstract base class for objects optimizing objective functions.
"""
__metaclass__ = ABCMeta
@abstractmethod
def optimize(self, function, param_spec, return_spec):
"""
:param function: Objective function
:param param_spec: Parameters specification for `function`
:param return_spec: Return value specification for `function`
"""
# TODO: Include invoker property
class BaseCaller(object):
"""Abstract base class for objects calling
:meth:`orges.invoker.base.BaseInvoker.invoke` (and being called back by it).
"""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
self._invoker = None
@property
@abstractmethod
def invoker(self):
"The invoker that is used by this caller."
return self._invoker
@invoker.setter
@abstractmethod
def invoker(self, invoker):
self._invoker = invoker
@abstractmethod
def on_result(self, result, fargs, *vargs, **kwargs):
"""
Called when :meth:`orges.invoker.base.BaseInvoker.invoke` was
successful.
:param result: Return value of the objective function
:param fargs: Arguments the objective function was applied to
"""
pass
@abstractmethod
def on_error(self, error, fargs, *vargs, **kwargs):
"""
Called when :meth:`orges.invoker.base.BaseInvoker.invoke` was *not*
successful.
:param error: Error that occured
:param fargs: Arguments the objective function was applied to
"""
pass
| """
Abstract optimizer defining the API of optimizer implementations.
"""
from __future__ import division, print_function, with_statement
from abc import abstractmethod, ABCMeta # Abstract Base Class
class BaseOptimizer(object):
"""
Abstract optimizer, a systematic way to call a function with arguments.
"""
__metaclass__ = ABCMeta
@abstractmethod
def optimize(self, function, param_spec, return_spec):
"""
:param function:
:param param_spec: Parameter specification for the given function.
:param return_spec: Return value specification for the given function.
"""
class BaseCaller(object):
"""Abstract caller handling calls to a given invoker."""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
self._invoker = None
@property
@abstractmethod
def invoker(self):
return self._invoker
@invoker.setter
@abstractmethod
def invoker(self, invoker):
self._invoker = invoker
@abstractmethod
def on_result(self, result, fargs, *vargs, **kwargs):
'''
Handles a result.
:param return_value: Return value of the given arguments.
:param fargs: The arguments given to a function.
'''
pass
@abstractmethod
def on_error(self, error, fargs, *vargs, **kwargs):
'''
Handles an error.
:param fargs: The arguments given to a function.
'''
pass
|
Fix SAM checker to for better coverage | """Functions for checking files"""
import os
import stat
import mimetypes
from .checker import is_link
from .config import CONFIG
def is_fastq(fi):
"""Check whether a given file is a fastq file."""
path = fi['path']
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return 'PROB_FILE_IS_FASTQ'
def sam_should_compress(fi):
"""Check if a *.SAM file should be compressed or deleted"""
path = fi['path']
name, ext = os.path.splitext(path)
if ext == '.sam':
if os.path.isfile('.'.join((name, 'bam'))):
return 'PROB_SAM_AND_BAM_EXIST'
else:
return 'PROB_SAM_SHOULD_COMPRESS'
elif ext == '.bam':
if os.path.isfile('.'.join((name, 'sam'))):
return 'PROB_SAM_SHOULD_COMPRESS'
def is_large_plaintext(fi):
"""Detect if a file plaintext and >100MB"""
guess = mimetypes.guess_type(fi['path'])
mod_days = fi['lastmod'] / (24 * 60 * 60) # Days since last modification
large = CONFIG.get('checks', 'largesize',
fallback=100000000) # Default to 100MB
old = CONFIG.get('checks', 'oldage',
fallback=30) # Default to one month
if guess == 'text/plain' and fi['size'] > large and mod_days >= old:
return 'PROB_OLD_LARGE_PLAINTEXT'
| """Functions for checking files"""
import os
import stat
import mimetypes
from .checker import is_link
from .config import CONFIG
def is_fastq(fi):
"""Check whether a given file is a fastq file."""
path = fi['path']
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return 'PROB_FILE_IS_FASTQ'
def sam_should_compress(fi):
"""Check if a *.SAM file should be compressed or deleted"""
path = fi['path']
name, ext = os.path.splitext(path)
if ext == '.sam':
if os.path.isfile('.'.join((name, 'bam'))):
return 'PROB_SAM_AND_BAM_EXIST'
else:
return 'PROB_SAM_SHOULD_COMPRESS'
def is_large_plaintext(fi):
"""Detect if a file plaintext and >100MB"""
guess = mimetypes.guess_type(fi['path'])
mod_days = fi['lastmod'] / (24 * 60 * 60) # Days since last modification
large = CONFIG.get('checks', 'largesize',
fallback=100000000) # Default to 100MB
old = CONFIG.get('checks', 'oldage',
fallback=30) # Default to one month
if guess == 'text/plain' and fi['size'] > large and mod_days >= old:
return 'PROB_OLD_LARGE_PLAINTEXT'
|
Clean up formatting. Assign function name to comparePasswords | /* eslint new-cap: 0 */
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Q = require('q');
const SALT_WORK_FACTOR = 10;
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
salt: String,
textViewText: {
type: Array,
default: [],
},
speechViewText: {
type: Array,
default: [],
},
speechViewSecondsElapsed: Number,
});
UserSchema.methods.comparePasswords = function comparePasswords(candidatePassword) {
const savedPassword = this.password;
return Q.Promise((resolve, reject) => {
bcrypt.compare(candidatePassword, savedPassword, (err, matched) => {
if (err) {
reject(err);
} else {
resolve(matched);
}
});
});
};
UserSchema.pre('save', function presaveCallback(next) {
const user = this;
return bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
if (err) {
return next(err);
}
return bcrypt.hash(user.password, salt, null, (err2, hash) => {
if (err2) {
return next(err2);
}
user.password = hash;
user.salt = salt;
return next();
});
});
});
module.exports = mongoose.model('User', UserSchema);
| /* eslint new-cap: 0 */
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Q = require('q');
const SALT_WORK_FACTOR = 10;
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
salt: String,
textViewText: {
type: Array,
default: [],
},
speechViewText: {
type: Array,
default: [],
},
speechViewSecondsElapsed: Number,
});
UserSchema.methods.comparePasswords = function (candidatePassword) {
const savedPassword = this.password;
return Q.Promise((resolve, reject) => {
bcrypt.compare(candidatePassword, savedPassword, (err, matched) => {
if (err) {
reject(err);
} else {
resolve(matched);
}
});
});
};
UserSchema.pre('save', function presaveCallback(next) {
const user = this;
return bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
if (err) {
return next(err);
}
return bcrypt.hash(user.password, salt, null, (err2, hash) => {
if (err2) {
return next(err2);
}
user.password = hash;
user.salt = salt;
return next();
});
});
});
module.exports = mongoose.model('User', UserSchema);
|
Add date at the end | # -*- coding: utf-8 -*-
import json
from collections import defaultdict
from datetime import datetime
from unidecode import unidecode
from .items import Subject
from .spiders.cagr import SEMESTER
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
def classes(item: Subject):
for klass in item['classes']:
yield [klass['id'], item['hours'], klass['vacancy'], klass['occupied'],
klass['special'], klass['remaining'], klass['lacking'],
klass['raw_timetable'], klass['teachers']]
del klass['raw_timetable']
class LegacyPipeline(object):
data = defaultdict(list)
time_format = '{}.{}-{} / {}'
def process_item(self, item: Subject, spider):
norm = unidecode(item['name']).upper()
subject = [item['id'], norm, item['name'], list(classes(item))]
self.data[item['campus']].append(subject)
return item
def close_spider(self, spider):
self.data['DATA'] = datetime.now().strftime('%d/%m/%y - %H:%M')
with open('{}.json'.format(SEMESTER), 'w') as fp:
json.dump(self.data, fp, ensure_ascii=False, separators=(',', ':',))
| # -*- coding: utf-8 -*-
import json
from collections import defaultdict
from datetime import datetime
from unidecode import unidecode
from .items import Subject
from .spiders.cagr import SEMESTER
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
def classes(item: Subject):
for klass in item['classes']:
yield [klass['id'], item['hours'], klass['vacancy'], klass['occupied'],
klass['special'], klass['remaining'], klass['lacking'],
klass['raw_timetable'], klass['teachers']]
del klass['raw_timetable']
class LegacyPipeline(object):
data = defaultdict(list)
time_format = '{}.{}-{} / {}'
def open_spider(self, spider):
self.data['DATA'] = datetime.now().strftime('%d/%m/%y - %H:%M')
def process_item(self, item: Subject, spider):
norm = unidecode(item['name']).upper()
subject = [item['id'], norm, item['name'], list(classes(item))]
self.data[item['campus']].append(subject)
return item
def close_spider(self, spider):
with open('{}.json'.format(SEMESTER), 'w') as fp:
json.dump(self.data, fp, ensure_ascii=False, separators=(',', ':',))
|
Use dominate to render comments as well. | from flask import current_app
from dominate import tags
from visitor import Visitor
class BaseRenderer(Visitor):
def visit_object(self, node):
if current_app.debug:
return tags.comment(
'no implementation in {} to render {}'.format(
self.__class__.__name__, node.__class__.__name__,
))
return ''
class SimpleRenderer(BaseRenderer):
def visit_Link(self, node):
return tags.a(node.title, title=node.title, **node.attribs)
def visit_Navbar(self, node):
cont = tags.nav(_class='navbar')
for item in node.items:
cont.add(tags.li(self.visit(item)))
return cont
def visit_View(self, node):
kwargs = {}
if node.active:
kwargs['_class'] = 'active'
return tags.a(node.title,
href=node.get_url(),
title=node.title,
**kwargs)
def visit_Subgroup(self, node):
group = tags.ul()
for item in node.items:
group.add(tags.li(self.visit(item)))
return group
def visit_Separator(self, node):
return tags.span(_class='separator')
def visit_Label(self, node):
return tags.span(node.title, _class='nav-label')
| from flask import current_app
from dominate import tags
from visitor import Visitor
class BaseRenderer(Visitor):
def visit_object(self, node):
if current_app.debug:
return '<!-- no implementation in {} to render {} -->'.format(
self.__class__.__name__, node.__class__.__name__,
)
return ''
class SimpleRenderer(BaseRenderer):
def visit_Link(self, node):
return tags.a(node.title, title=node.title, **node.attribs)
def visit_Navbar(self, node):
cont = tags.nav(_class='navbar')
for item in node.items:
cont.add(tags.li(self.visit(item)))
return cont
def visit_View(self, node):
kwargs = {}
if node.active:
kwargs['_class'] = 'active'
return tags.a(node.title,
href=node.get_url(),
title=node.title,
**kwargs)
def visit_Subgroup(self, node):
group = tags.ul()
for item in node.items:
group.add(tags.li(self.visit(item)))
return group
def visit_Separator(self, node):
return tags.span(_class='separator')
def visit_Label(self, node):
return tags.span(node.title, _class='nav-label')
|
Fix syntax error, filter row log | var RSVP = require('rsvp'),
utils = require('./lib'),
GoogleSpreadsheet = require("google-spreadsheet"),
config = require('./config.js'),
doc = new GoogleSpreadsheet(config['google_spreadsheet_key']),
process = require('process');
RSVP.hash({
currentItems: utils.getWishlistFromAmazon(config['amazon_wishlist_id']),
previousItems: utils.getPreviousWishlist(),
spreadsheetAuthenticated: utils.authenticateServiceAccount(doc, {
private_key: config['google_private_key'],
client_email: config['google_client_email']
})
})
.then(function(wishlist){
var itemsAdded = utils.getDifference(wishlist.previousItems, wishlist.currentItems);
console.log(`Found ${itemsAdded.length} new items.`);
console.log(itemsAdded.map(function(item) { image: item.image, title: item.title, link: item.link } ));
rowAddPromises = itemsAdded.map(function(rowObj){
return utils.addRowsToDriveSpreadsheet(doc, 1, {
Image: '=IMAGE("' + rowObj.picture + '")',
Title: '=HYPERLINK("' + rowObj.link + '", "' + rowObj.name + '")'
});
});
rowAddPromises.push(utils.savePreviousWishlist(wishlist.currentItems));
return RSVP.all(rowAddPromises);
}, function(err){
console.log(err);
process.exit();
})
.then(function(){
console.log('Success adding rows to spreadsheet!');
}, function(err){
console.log(err.stack || err.message || err);
process.exit();
});
| var RSVP = require('rsvp'),
utils = require('./lib'),
GoogleSpreadsheet = require("google-spreadsheet"),
config = require('./config.js'),
doc = new GoogleSpreadsheet(config['google_spreadsheet_key']),
process = require('process');
RSVP.hash({
currentItems: utils.getWishlistFromAmazon(config['amazon_wishlist_id']),
previousItems: utils.getPreviousWishlist(),
spreadsheetAuthenticated: utils.authenticateServiceAccount(doc, {
private_key: config['google_private_key'],
client_email: config['google_client_email']
})
})
.then(function(wishlist){
var itemsAdded = utils.getDifference(wishlist.previousItems, wishlist.currentItems);
console.log(`Found ${itemsAdded.length} new items.`);
console.log(itemsAdded);
rowAddPromises = rowValues.map(function(rowObj){
return utils.addRowsToDriveSpreadsheet(doc, 1, {
Image: '=IMAGE("' + rowObj.picture + '")',
Title: '=HYPERLINK("' + rowObj.link + '", "' + rowObj.name + '")'
});
});
rowAddPromises.push(utils.savePreviousWishlist(wishlist.currentItems));
return RSVP.all(rowAddPromises);
}, function(err){
console.log(err);
process.exit();
})
.then(function(){
console.log('Success adding rows to spreadsheet!');
}, function(err){
console.log(err.stack || err.message || err);
process.exit();
});
|
Fix NPE when saving smart lock | package com.firebase.ui.auth.provider;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.LayoutRes;
import com.firebase.ui.auth.R;
import com.firebase.ui.auth.ResultCodes;
import com.firebase.ui.auth.ui.BaseHelper;
import com.firebase.ui.auth.ui.email.RegisterEmailActivity;
import com.google.firebase.auth.EmailAuthProvider;
public class EmailProvider implements Provider {
private static final int RC_EMAIL_FLOW = 2;
private Activity mActivity;
private BaseHelper mHelper;
public EmailProvider(Activity activity, BaseHelper helper) {
mActivity = activity;
mHelper = helper;
}
@Override
public String getName(Context context) {
return context.getString(R.string.provider_name_email);
}
@Override
public String getProviderId() {
return EmailAuthProvider.PROVIDER_ID;
}
@Override
@LayoutRes
public int getButtonLayout() {
return R.layout.provider_button_email;
}
@Override
public void startLogin(Activity activity) {
activity.startActivityForResult(
RegisterEmailActivity.createIntent(activity, mHelper.getFlowParams()),
RC_EMAIL_FLOW);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_EMAIL_FLOW && resultCode == ResultCodes.OK) {
mHelper.finishActivity(mActivity, ResultCodes.OK, data);
}
}
}
| package com.firebase.ui.auth.provider;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.LayoutRes;
import com.firebase.ui.auth.R;
import com.firebase.ui.auth.ResultCodes;
import com.firebase.ui.auth.ui.BaseHelper;
import com.firebase.ui.auth.ui.email.RegisterEmailActivity;
import com.google.firebase.auth.EmailAuthProvider;
public class EmailProvider implements Provider {
private static final int RC_EMAIL_FLOW = 2;
private Activity mActivity;
private BaseHelper mHelper;
public EmailProvider(Activity activity, BaseHelper helper) {
mActivity = activity;
mHelper = helper;
}
@Override
public String getName(Context context) {
return context.getString(R.string.provider_name_email);
}
@Override
public String getProviderId() {
return EmailAuthProvider.PROVIDER_ID;
}
@Override
@LayoutRes
public int getButtonLayout() {
return R.layout.provider_button_email;
}
@Override
public void startLogin(Activity activity) {
activity.startActivityForResult(
RegisterEmailActivity.createIntent(activity, mHelper.getFlowParams()),
RC_EMAIL_FLOW);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == ResultCodes.OK) {
mHelper.finishActivity(mActivity, ResultCodes.OK, data);
}
}
}
|
Use more reliable time threshold for SSL reload. | <?php
declare(strict_types=1);
namespace App\Sync\Task;
use App\Doctrine\ReloadableEntityManagerInterface;
use App\Entity\Repository\SettingsRepository;
use App\Radio\Adapters;
use App\Radio\CertificateLocator;
use Psr\Log\LoggerInterface;
class ReloadFrontendAfterSslChangeTask extends AbstractTask
{
public function __construct(
protected Adapters $adapters,
protected SettingsRepository $settingsRepo,
ReloadableEntityManagerInterface $em,
LoggerInterface $logger
) {
parent::__construct($em, $logger);
}
public function run(bool $force = false): void
{
$threshold = $this->settingsRepo->readSettings()->getSyncLongLastRun();
$certs = CertificateLocator::findCertificate();
$pathsToCheck = [
$certs->getCertPath(),
$certs->getKeyPath(),
];
$certsUpdated = false;
foreach ($pathsToCheck as $path) {
if (filemtime($path) > $threshold) {
$certsUpdated = true;
break;
}
}
if ($certsUpdated) {
$this->logger->info('SSL certificates have updated; hot-reloading stations that support it.');
foreach ($this->iterateStations() as $station) {
$frontend = $this->adapters->getFrontendAdapter($station);
if ($frontend->supportsReload()) {
$frontend->reload($station);
}
}
} else {
$this->logger->info('SSL certificates have not updated.');
}
}
}
| <?php
declare(strict_types=1);
namespace App\Sync\Task;
use App\Doctrine\ReloadableEntityManagerInterface;
use App\Radio\Adapters;
use App\Radio\CertificateLocator;
use Psr\Log\LoggerInterface;
class ReloadFrontendAfterSslChangeTask extends AbstractTask
{
public function __construct(
protected Adapters $adapters,
ReloadableEntityManagerInterface $em,
LoggerInterface $logger
) {
parent::__construct($em, $logger);
}
public function run(bool $force = false): void
{
$threshold = time() - 60 * 60; // An hour ago
$certs = CertificateLocator::findCertificate();
$pathsToCheck = [
$certs->getCertPath(),
$certs->getKeyPath(),
];
$certsUpdated = false;
foreach ($pathsToCheck as $path) {
if (filemtime($path) > $threshold) {
$certsUpdated = true;
break;
}
}
if ($certsUpdated) {
$this->logger->info('SSL certificates have updated; hot-reloading stations that support it.');
foreach ($this->iterateStations() as $station) {
$frontend = $this->adapters->getFrontendAdapter($station);
if ($frontend->supportsReload()) {
$frontend->reload($station);
}
}
} else {
$this->logger->info('SSL certificates have not updated.');
}
}
}
|
Save the scroll position more often | function rememberScrollPosition() {
function rememberScrollPositionForElement(element) {
var id = element.getAttribute('id');
var scrollTimer;
element.onscroll = function (e) {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () {
localStorage.setItem(id + ' scrollTop', element.scrollTop);
localStorage.setItem(id + ' scrollLeft', element.scrollLeft);
}, 300);
};
}
function retrieveScrollPositionForElement(element) {
var id = element.getAttribute('id');
var scrollTop = localStorage.getItem(id + ' scrollTop');
var scrollLeft = localStorage.getItem(id + ' scrollLeft');
if (typeof scrollTop === 'string') {
element.scrollTop = parseInt(scrollTop, 10);
element.scrollLeft = parseInt(scrollLeft, 10);
}
}
var elements = document.querySelectorAll('.js-remember-scroll-position');
for (var i = 0; i < elements.length; i += 1) {
try {
var element = elements[i];
retrieveScrollPositionForElement(element);
rememberScrollPositionForElement(element);
} catch (e) {
// ignore
}
}
}
rememberScrollPosition();
| function rememberScrollPosition() {
function rememberScrollPositionForElement(element) {
var id = element.getAttribute('id');
var scrollTimer;
element.onscroll = function (e) {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(function () {
localStorage.setItem(id + ' scrollTop', element.scrollTop);
localStorage.setItem(id + ' scrollLeft', element.scrollLeft);
}, 1000);
};
}
function retrieveScrollPositionForElement(element) {
var id = element.getAttribute('id');
var scrollTop = localStorage.getItem(id + ' scrollTop');
var scrollLeft = localStorage.getItem(id + ' scrollLeft');
if (typeof scrollTop === 'string') {
element.scrollTop = parseInt(scrollTop, 10);
element.scrollLeft = parseInt(scrollLeft, 10);
}
}
var elements = document.querySelectorAll('.js-remember-scroll-position');
for (var i = 0; i < elements.length; i += 1) {
try {
var element = elements[i];
retrieveScrollPositionForElement(element);
rememberScrollPositionForElement(element);
} catch (e) {
// ignore
}
}
}
rememberScrollPosition();
|
Add graphitesend dependency for graphiteservice output. | from setuptools import setup, find_packages
setup(
name='braubuddy',
version='0.3.0',
author='James Stewart',
author_email='[email protected]',
description='An extensile thermostat framework',
long_description=open('README.rst').read(),
license='LICENSE.txt',
packages=find_packages(),
url='http://braubuddy.org/',
include_package_data=True,
entry_points={
'console_scripts': [
'braubuddy = braubuddy.runserver:main',
]
},
install_requires=[
'pyserial>=2.0',
'tosr0x>=0.2.0',
'temperusb>=1.2.0',
'ds18b20>=0.01.03',
'cherrypy>=3.2.2',
'pyxdg>=0.25',
'jinja2>=2.7.0',
'mock>=1.0,<2.0',
'alabaster>=0.6.0',
'graphitesend>0.3.4,<0.4',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
| from setuptools import setup, find_packages
setup(
name='braubuddy',
version='0.3.0',
author='James Stewart',
author_email='[email protected]',
description='An extensile thermostat framework',
long_description=open('README.rst').read(),
license='LICENSE.txt',
packages=find_packages(),
url='http://braubuddy.org/',
include_package_data=True,
entry_points={
'console_scripts': [
'braubuddy = braubuddy.runserver:main',
]
},
install_requires=[
'pyserial>=2.0',
'tosr0x>=0.2.0',
'temperusb>=1.2.0',
'ds18b20>=0.01.03',
'cherrypy>=3.2.2',
'pyxdg>=0.25',
'jinja2>=2.7.0',
'mock>=1.0,<2.0',
'alabaster>=0.6.0',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
Add CommandResponse class to use instead of (out, err) tuple | # -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
class CommandResponse(object):
def __init__(self, process):
self.process = process
self.out, self.err = process.communicate()
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return CommandResponse(p)
def kill(session):
r = command("kill-session -t {}".format(session))
if "session not found" in r.err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in r.err:
raise ServerConnectionError()
def list():
r = command("ls")
if "failed to connect to server" in r.err:
raise ServerConnectionError()
return r.out
def create(session):
r = command("new -s {}".format(session))
if "duplicate session" in r.err:
raise SessionExists(session)
def attach(session):
r = command("attach-session -t {}".format(session))
if "no sessions" in r.err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
| # -*- coding: utf-8 -*-
import subprocess
class SessionExists(Exception):
description = "Session already exists."
pass
class ServerConnectionError(Exception):
description = "tmux server is not currently running."
pass
class SessionDoesNotExist(Exception):
description = "Session does not exist."
pass
def command(command):
p = subprocess.Popen("tmux " + command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
return p.communicate()
def kill(session):
out, err = command("kill-session -t {}".format(session))
if "session not found" in err:
raise SessionDoesNotExist(session)
if "failed to connect to server" in err:
raise ServerConnectionError()
def list():
out, err = command("ls")
if "failed to connect to server" in err:
raise ServerConnectionError()
return out
def create(session):
out, err = command("new -s {}".format(session))
if "duplicate session" in err:
raise SessionExists(session)
def attach(session):
out, err = command("attach-session -t {}".format(session))
if "no sessions" in err:
raise SessionDoesNotExist(session)
def create_or_attach(session):
try:
create(session)
except SessionExists:
attach(session)
|
Fix LoginSerializer to support custom username fields of custom user models | from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
User.USERNAME_FIELD, 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length(User.USERNAME_FIELD), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(
username=attrs['username'], password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
raise serializers.ValidationError(
'Can not log in as inactive user')
elif user.is_staff and overridable(
'OSCARAPI_BLOCK_ADMIN_API_ACCESS', True):
raise serializers.ValidationError(
'Staff users can not log in via the rest api')
# set instance to the user so we can use this in the view
self.instance = user
return attrs
| from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers
from oscarapi.utils import overridable
User = get_user_model()
def field_length(fieldname):
field = next(
field for field in User._meta.fields if field.name == fieldname)
return field.max_length
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = overridable('OSCARAPI_USER_FIELDS', (
'username', 'id', 'date_joined',))
class LoginSerializer(serializers.Serializer):
username = serializers.CharField(
max_length=field_length('username'), required=True)
password = serializers.CharField(
max_length=field_length('password'), required=True)
def validate(self, attrs):
user = authenticate(username=attrs['username'],
password=attrs['password'])
if user is None:
raise serializers.ValidationError('invalid login')
elif not user.is_active:
raise serializers.ValidationError(
'Can not log in as inactive user')
elif user.is_staff and overridable(
'OSCARAPI_BLOCK_ADMIN_API_ACCESS', True):
raise serializers.ValidationError(
'Staff users can not log in via the rest api')
# set instance to the user so we can use this in the view
self.instance = user
return attrs
|
Allow query parameters in font source urls | // noinspection JSUnresolvedVariable
module.exports = {
cache: false,
debug: false,
module: {
loaders: [
{
// This is a custom property.
name: 'jsx',
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
},
exclude: /node_modules/,
},
{test: /\.json$/, loader: 'json-loader'},
{test: /\.png$/, loader: 'url-loader?prefix=img/&limit=5000'},
{test: /\.jpg$/, loader: 'url-loader?prefix=img/&limit=5000'},
{test: /\.gif$/, loader: 'url-loader?prefix=img/&limit=5000'},
{ test: /\.woff2?(\?.*)?$/, loader: 'url-loader?prefix=font/&limit=5000' },
{ test: /\.(eot|ttf|svg)(\?.*)?$/, loader: 'file-loader?prefix=font/' },
],
noParse: /\.min\.js/,
},
eslint: {
eslint: {
configFile: '.eslintrc',
},
},
resolve: {
extensions: ['', '.js', '.json', '.jsx'],
modulesDirectories: [
'node_modules',
'app/components',
],
},
node: {
__dirname: true,
fs: 'empty',
},
};
| // noinspection JSUnresolvedVariable
module.exports = {
cache: false,
debug: false,
module: {
loaders: [
{
// This is a custom property.
name: 'jsx',
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
},
exclude: /node_modules/,
},
{test: /\.json$/, loader: 'json-loader'},
{test: /\.png$/, loader: 'url-loader?prefix=img/&limit=5000'},
{test: /\.jpg$/, loader: 'url-loader?prefix=img/&limit=5000'},
{test: /\.gif$/, loader: 'url-loader?prefix=img/&limit=5000'},
{test: /\.woff2?$/, loader: 'url-loader?prefix=font/&limit=5000'},
{test: /\.eot$/, loader: 'file-loader?prefix=font/'},
{test: /\.ttf$/, loader: 'file-loader?prefix=font/'},
{test: /\.svg$/, loader: 'file-loader?prefix=font/'},
],
noParse: /\.min\.js/,
},
eslint: {
eslint: {
configFile: '.eslintrc',
},
},
resolve: {
extensions: ['', '.js', '.json', '.jsx'],
modulesDirectories: [
'node_modules',
'app/components',
],
},
node: {
__dirname: true,
fs: 'empty',
},
};
|
Add placeholder for secret key | # -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
DEBUG = False
TESTING = False
APP_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
SECRET_KEY = str(os.environ.get('SECRET_KEY'))
# Local Settings
"""MONGODB_DB = os.environ.get('WHERENO_DB', 'whereno')
MONGODB_HOST = os.environ.get('WHERENO_HOST', 'localhost')
MONGODB_PORT = os.environ.get('WHERENO_PORT', 27017)
MONGODB_USERNAME = os.environ.get('WHERENO_USERNAME', 'whereno')
MONGODB_PASSWORD = os.environ.get('WHERENO_PASSWORD', 'whereno')"""
# Cloud Settings
MONGODB_DB = str(os.environ.get('MONGODB_DB'))
MONGODB_HOST = str(os.environ.get('MONGODB_HOST'))
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
DEBUG = False
TESTING = False
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
TESTING = True
CACHE_TYPE = 'simple'
BCRYPT_LOG_ROUNDS = 4
class TestConfig(Config):
"""Test configuration."""
TESTING = True
DEBUG = True
BCRYPT_LOG_ROUNDS = 4
| # -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
DEBUG = False
TESTING = False
APP_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
# Local Settings
"""MONGODB_DB = os.environ.get('WHERENO_DB', 'whereno')
MONGODB_HOST = os.environ.get('WHERENO_HOST', 'localhost')
MONGODB_PORT = os.environ.get('WHERENO_PORT', 27017)
MONGODB_USERNAME = os.environ.get('WHERENO_USERNAME', 'whereno')
MONGODB_PASSWORD = os.environ.get('WHERENO_PASSWORD', 'whereno')"""
# Cloud Settings
MONGODB_DB = str(os.environ.get('MONGODB_DB'))
print(MONGODB_DB)
MONGODB_HOST = str(os.environ.get('MONGODB_HOST'))
print(MONGODB_HOST)
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
DEBUG = False
TESTING = False
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
TESTING = True
CACHE_TYPE = 'simple'
BCRYPT_LOG_ROUNDS = 4
class TestConfig(Config):
"""Test configuration."""
TESTING = True
DEBUG = True
BCRYPT_LOG_ROUNDS = 4
|
Remove console logging from figuring out graphjs. | import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement() {
Chart.defaults.global.responsive = true;
Chart.defaults.global.legend.display =false
},
didRender() {
let data = this.get('data');
let toGraph = {
labels: [],
datasets: [{
data: []
}]
}
data.forEach(item => {
toGraph.labels.push(item.get('name'));
toGraph.datasets[0].data.push(item.get('value'));
});
let options = {
type: 'bar',
data: toGraph,
options: {
scales: {
yAxes: [
{
ticks: {beginAtZero: true}
}
]
}
}
}
let ctx = this.$().children(".bar-chart").first();//.getContext('2d');
let statsChart = new Chart(ctx, options);
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement() {
Chart.defaults.global.responsive = true;
Chart.defaults.global.legend.display =false
},
didRender() {
let data = this.get('data');
let toGraph = {
labels: [],
datasets: [{
data: []
}]
}
data.forEach(item => {
toGraph.labels.push(item.get('name'));
toGraph.datasets[0].data.push(item.get('value'));
});
let options = {
type: 'bar',
data: toGraph,
options: {
scales: {
yAxes: [
{
ticks: {beginAtZero: true}
}
]
}
}
}
console.log(this.elementId);
let ctx = this.$().children(".bar-chart").first();//.getContext('2d');
let statsChart = new Chart(ctx, options);
}
});
|
Fix up settings for upstream Girder change | from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource, RestException
from girder.constants import AccessType, TokenScope
from girder.models.setting import Setting
from .constants import Features, Deployment, Branding
class Configuration(Resource):
def __init__(self):
super(Configuration, self).__init__()
self.resourceName = 'configuration'
self.route('GET', (), self.get)
@access.public
@autoDescribeRoute(
Description('Get the deployment configuration.')
)
def get(self):
notebooks = Setting().get(Features.NOTEBOOKS)
if notebooks is None:
notebooks = True
site = Setting().get(Deployment.SITE)
if site is None:
site = ''
return {
'features': {
'notebooks': notebooks
},
'deployment': {
'site': site
},
'branding': {
'license': Setting().get(Branding.LICENSE),
'privacy': Setting().get(Branding.PRIVACY),
'headerLogoFileId': Setting().get(Branding.HEADER_LOGO_ID),
'footerLogoFileId': Setting().get(Branding.FOOTER_LOGO_ID),
'footerLogoUrl': Setting().get(Branding.FOOTER_LOGO_URL),
'faviconFileId': Setting().get(Branding.FAVICON_ID)
}
}
| from girder.api import access
from girder.api.describe import Description, autoDescribeRoute
from girder.api.rest import Resource, RestException
from girder.constants import AccessType, TokenScope
from girder.models.setting import Setting
from .constants import Features, Deployment, Branding
class Configuration(Resource):
def __init__(self):
super(Configuration, self).__init__()
self.resourceName = 'configuration'
self.route('GET', (), self.get)
@access.public
@autoDescribeRoute(
Description('Get the deployment configuration.')
)
def get(self):
return {
'features': {
'notebooks': Setting().get(Features.NOTEBOOKS, True)
},
'deployment': {
'site': Setting().get(Deployment.SITE, '')
},
'branding': {
'license': Setting().get(Branding.LICENSE),
'privacy': Setting().get(Branding.PRIVACY),
'headerLogoFileId': Setting().get(Branding.HEADER_LOGO_ID),
'footerLogoFileId': Setting().get(Branding.FOOTER_LOGO_ID),
'footerLogoUrl': Setting().get(Branding.FOOTER_LOGO_URL),
'faviconFileId': Setting().get(Branding.FAVICON_ID)
}
}
|
Correct some comments in command producer | <?php
/*
* (c) Jérémy Marodon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Th3Mouk\RxTraining\Commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Th3Mouk\RxTraining\Commands\Styles\SuccessTrait;
use Th3Mouk\RxTraining\Producers\PizzaOrderingProducer;
class ProduceCommand extends Command
{
use SuccessTrait;
protected function configure()
{
$this
// the name of the command
->setName('produce')
// the short description of the command
->setDescription('Generate some dumb pizza ordering.')
// number of pizza ordering
->addOption(
'orders',
null,
InputOption::VALUE_REQUIRED,
'How many pizza orders do you want?',
20
);
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->getFormatter()->setStyle('leaf', $this->getSuccessStyle());
$orders = $input->getOption('orders');
$pizza_producer = new PizzaOrderingProducer($output, $orders);
$pizza_producer->produce();
}
}
| <?php
/*
* (c) Jérémy Marodon <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Th3Mouk\RxTraining\Commands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Th3Mouk\RxTraining\Commands\Styles\SuccessTrait;
use Th3Mouk\RxTraining\Producers\PizzaOrderingProducer;
class ProduceCommand extends Command
{
use SuccessTrait;
protected function configure()
{
$this
// the name of the command (the part after "bin/console")
->setName('produce')
// the short description shown while running "php bin/console list"
->setDescription('Generate some dumb pizza ordering.')
// number of pizza ordering
->addOption(
'orders',
null,
InputOption::VALUE_REQUIRED,
'How many pizza orders do you want?',
20
);
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->getFormatter()->setStyle('leaf', $this->getSuccessStyle());
$orders = $input->getOption('orders');
$pizza_producer = new PizzaOrderingProducer($output, $orders);
$pizza_producer->produce();
}
}
|
Use inspect.getdoc() instead of plain __doc__ | """
Interface for all launch-control-tool commands
"""
import inspect
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
Base class for all command line tool sub-commands.
"""
def __init__(self, parser, args):
"""
Prepare instance for executing commands.
This method is called immediately after all arguments are parsed
and results are available. This gives subclasses a chance to
configure themselves.
The default implementation does not do anything.
"""
pass
def invoke(self, args):
"""
Invoke command action.
"""
raise NotImplemented()
@classmethod
def get_name(cls):
"""
Return the name of this command.
The default implementation strips any leading underscores
and replaces all other underscores with dashes.
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return inspect.getdoc(cls)
@classmethod
def register_arguments(cls, parser):
"""
Register arguments if required.
Subclasses can override this to add any arguments that will be
exposed to the command line interface.
"""
pass
| """
Interface for all launch-control-tool commands
"""
from launch_control.utils.registry import RegistryBase
class Command(RegistryBase):
"""
Base class for all command line tool sub-commands.
"""
def __init__(self, parser, args):
"""
Prepare instance for executing commands.
This method is called immediately after all arguments are parsed
and results are available. This gives subclasses a chance to
configure themselves.
The default implementation does not do anything.
"""
pass
def invoke(self, args):
"""
Invoke command action.
"""
raise NotImplemented()
@classmethod
def get_name(cls):
"""
Return the name of this command.
The default implementation strips any leading underscores
and replaces all other underscores with dashes.
"""
return cls.__name__.lstrip("_").replace("_", "-")
@classmethod
def get_help(cls):
"""
Return the help message of this command
"""
return cls.__doc__
@classmethod
def register_arguments(cls, parser):
"""
Register arguments if required.
Subclasses can override this to add any arguments that will be
exposed to the command line interface.
"""
pass
|
Make test case valid MiniJava. | /**
* Tests some evaluation order / side effects with && and ||.
*
* @author Elvis Stansvik <[email protected]>
*/
//EXT:BDJ
//EXT:IWE
class SideEffects {
public static void main(String[] args) {
IncredibleMachine m;
m = new IncredibleMachine();
System.out.println(m.run()); // Should print 329.
}
}
class IncredibleMachine {
int result;
public int run() {
result = 2;
if (this.a(3, false) && this.a(5, true) /* r = 2 + 3 */
|| (this.m(7, false) || this.s(11, true) && this.m(13, false)) /* r = ((2 + 3) * 7 - 11) * 13 */
|| this.a(17, true) || this.m(19, true)) /* r = ((2 + 3) * 7 - 11) * 13 + 17 = 329 */
result = result;
return result;
}
public boolean m(int value, boolean ret) {
result = result * value;
return ret;
}
public boolean a(int value, boolean ret) {
result = result + value;
return ret;
}
public boolean s(int value, boolean ret) {
result = result - value;
return ret;
}
}
| /**
* Tests some evaluation order / side effects with && and ||.
*
* @author Elvis Stansvik <[email protected]>
*/
//EXT:BDJ
class SideEffects {
public static void main(String[] args) {
IncredibleMachine m;
m = new IncredibleMachine();
System.out.println(m.run()); // Should print 329.
}
}
class IncredibleMachine {
int result;
public int run() {
result = 2;
if (a(3, false) && a(5, true) /* r = 2 + 3 */
|| (m(7, false) || s(11, true) && m(13, false)) /* r = ((2 + 3) * 7 - 11) * 13 */
|| a(17, true) || m(19, true)) /* r = ((2 + 3) * 7 - 11) * 13 + 17 = 329 */
result = result;
else
result = 42;
return result;
}
public boolean m(int value, boolean ret) {
result = result * value;
return ret;
}
public boolean a(int value, boolean ret) {
result = result + value;
return ret;
}
public boolean s(int value, boolean ret) {
result = result - value;
return ret;
}
}
|
Fix other SyntaxError: invalid syntax
Fix
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/tmp/pip-7dj0aup6-build/setup.py", line 19
classifiers=[
^
SyntaxError: invalid syntax | #!/usr/bin/env python
from distutils.core import setup
setup(
name='wagtail_embed_videos',
version='0.0.5',
description='Embed Videos for Wagtail CMS.',
long_description=README,
author='Diogo Marques',
author_email='[email protected]',
maintainer='Diogo Marques',
maintainer_email='[email protected]',
url='https://github.com/infoportugal/wagtail-embedvideos',
packages=['wagtail_embed_videos', 'wagtail_embed_videos.views'],
package_data={'wagtail_embed_videos': ['static/wagtail_embed_videos/js/*.js']},
requires=['django(>=1.7)', 'wagtail(>=1.0)', 'django-embed-video(>=1.0)'],
install_requires=['wagtail', 'django-embed-video'],
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Wagtail CMS',
'License :: OSI Approved :: BSD License'],
license='New BSD',
)
| #!/usr/bin/env python
from distutils.core import setup
setup(
name='wagtail_embed_videos',
version='0.0.5',
description='Embed Videos for Wagtail CMS.',
long_description=README,
author='Diogo Marques',
author_email='[email protected]',
maintainer='Diogo Marques',
maintainer_email='[email protected]',
url='https://github.com/infoportugal/wagtail-embedvideos',
packages=['wagtail_embed_videos', 'wagtail_embed_videos.views'],
package_data={'wagtail_embed_videos': ['static/wagtail_embed_videos/js/*.js']},
requires=['django(>=1.7)', 'wagtail(>=1.0)', 'django-embed-video(>=1.0)'],
install_requires=['wagtail', 'django-embed-video']
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Wagtail CMS',
'License :: OSI Approved :: BSD License'],
license='New BSD',
)
|
Add missing attribute declaration (was made dynamically) | <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Service / SearchImage
*/
namespace PH7\Framework\Service\SearchImage;
defined('PH7') or exit('Restricted access');
class Url
{
/** @var string */
private $sUrl;
/**
* @param string $sUrl
*
* @throws InvalidUrlException
*/
public function __construct($sUrl)
{
if (!$this->isValid($sUrl)) {
throw new InvalidUrlException(sprintf('%s is an invalid URL', $sUrl));
}
$this->sUrl = $sUrl;
}
/**
* @return string
*/
public function getValue()
{
return $this->sUrl;
}
/**
* @param $sUrl
*
* @return bool
*/
private function isValid($sUrl)
{
return filter_var($sUrl, FILTER_VALIDATE_URL) !== false && strlen($sUrl) <= $this->getMaxImageLength();
}
/**
* Images length are longer. It multiples the regular URL length by 2.
*
* @return int
*/
private function getMaxImageLength()
{
return PH7_MAX_URL_LENGTH * 2;
}
}
| <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2017-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Framework / Service / SearchImage
*/
namespace PH7\Framework\Service\SearchImage;
defined('PH7') or exit('Restricted access');
class Url
{
/**
* @param string $sUrl
*
* @throws InvalidUrlException
*/
public function __construct($sUrl)
{
if (!$this->isValid($sUrl)) {
throw new InvalidUrlException(sprintf('%s is an invalid URL', $sUrl));
}
$this->sUrl = $sUrl;
}
/**
* @return string
*/
public function getValue()
{
return $this->sUrl;
}
/**
* @param $sUrl
*
* @return bool
*/
private function isValid($sUrl)
{
return filter_var($sUrl, FILTER_VALIDATE_URL) !== false && strlen($sUrl) <= $this->getMaxImageLength();
}
/**
* Images length are longer. It multiples the regular URL length by 2.
*
* @return int
*/
private function getMaxImageLength()
{
return PH7_MAX_URL_LENGTH * 2;
}
}
|
Allow Lady-In-Waiting to only target cards that can be duped (owned and controlled) | const DrawCard = require('../../../drawcard.js');
class LadyInWaiting extends DrawCard {
setupCardAbilities() {
this.playAction({
title: 'Marshal as dupe',
condition: () => this.canMarshalAsDupe(),
handler: () => {
this.game.promptForSelect(this.controller, {
activePromptTitle: 'Select a Lady character',
cardCondition: card => card.location === 'play area' && card.getType() === 'character' && card.hasTrait('Lady') &&
card.controller === this.controller && card.owner === this.controller,
onSelect: (player, card) => this.marshalAsDupe(card)
});
}
});
}
canMarshalAsDupe() {
return (
this.game.currentPhase === 'marshal' &&
this.canBeMarshaled() &&
this.controller.isCardInPlayableLocation(this, 'marshal') &&
this.controller.anyCardsInPlay(card => card.getType() === 'character' && card.hasTrait('Lady'))
);
}
marshalAsDupe(card) {
this.controller.removeCardFromPile(this);
card.addDuplicate(this);
this.game.addMessage('{0} places {1} on {2} as a duplicate', this.controller, this, card);
return true;
}
}
LadyInWaiting.code = '02023';
module.exports = LadyInWaiting;
| const DrawCard = require('../../../drawcard.js');
class LadyInWaiting extends DrawCard {
setupCardAbilities() {
this.playAction({
title: 'Marshal as dupe',
condition: () => this.canMarshalAsDupe(),
handler: () => {
this.game.promptForSelect(this.controller, {
activePromptTitle: 'Select a Lady character',
cardCondition: card => card.location === 'play area' && card.getType() === 'character' && card.hasTrait('Lady'),
onSelect: (player, card) => this.marshalAsDupe(card)
});
}
});
}
canMarshalAsDupe() {
return (
this.game.currentPhase === 'marshal' &&
this.canBeMarshaled() &&
this.controller.isCardInPlayableLocation(this, 'marshal') &&
this.controller.anyCardsInPlay(card => card.getType() === 'character' && card.hasTrait('Lady'))
);
}
marshalAsDupe(card) {
this.controller.removeCardFromPile(this);
card.addDuplicate(this);
this.game.addMessage('{0} places {1} on {2} as a duplicate', this.controller, this, card);
return true;
}
}
LadyInWaiting.code = '02023';
module.exports = LadyInWaiting;
|
Remove old dependency to kit from euth frontend | """Adhocracy frontend customization package."""
import os
import version
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = ['adhocracy_frontend',
'adhocracy_euth',
]
test_requires = ['adhocracy_frontend[test]',
'adhocracy_euth[test]',
]
debug_requires = ['adhocracy_frontend[debug]',
'adhocracy_euth[debug]',
]
setup(name='euth',
version=version.get_git_version(),
description='Adhocracy meta package for backend/frontend customization.',
long_description=README + '\n\n' + CHANGES,
classifiers=["Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons adhocracy',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=requires,
extras_require={'test': test_requires,
'debug': debug_requires},
entry_points="""\
[paste.app_factory]
main = euth:main
""",
)
| """Adhocracy frontend customization package."""
import os
import version
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = ['adhocracy_frontend',
'adhocracy_kit',
]
test_requires = ['adhocracy_frontend[test]',
'adhocracy_kit[test]',
]
debug_requires = ['adhocracy_frontend[debug]',
'adhocracy_kit[debug]',
]
setup(name='euth',
version=version.get_git_version(),
description='Adhocracy meta package for backend/frontend customization.',
long_description=README + '\n\n' + CHANGES,
classifiers=["Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='',
author_email='',
url='',
keywords='web pyramid pylons adhocracy',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=requires,
extras_require={'test': test_requires,
'debug': debug_requires},
entry_points="""\
[paste.app_factory]
main = euth:main
""",
)
|
Use six instead of sys.version_info | import six
from .log import log_input, log_output
def open(*args, **kwargs):
"""Built-in open replacement that logs input and output
Workaround for issue #44. Patching `__builtins__['open']` is complicated,
because many libraries use standard open internally, while we only want to
log inputs and outputs that are opened explicitly by the user.
The user can either use `recipy.open` (only requires `import recipy` at the
top of the script), or add `from recipy import open` and just use `open`.
If python 2 is used, and an `encoding` parameter is passed to this
function, `codecs` is used to open the file with proper encoding.
"""
if six.PY3:
mode = kwargs['mode']
f = __builtins__['open'](*args, **kwargs)
else:
try:
mode = args[1]
except:
mode = 'r'
if 'encoding' in kwargs.keys():
import codecs
f = codecs.open(*args, **kwargs)
else:
f = __builtins__['open'](*args, **kwargs)
# open file for reading?
for c in 'r+':
if c in mode:
log_input(args[0], 'recipy.open')
# open file for writing?
for c in 'wax+':
if c in mode:
log_output(args[0], 'recipy.open')
return(f)
| import sys
from .log import log_input, log_output
def open(*args, **kwargs):
"""Built-in open replacement that logs input and output
Workaround for issue #44. Patching `__builtins__['open']` is complicated,
because many libraries use standard open internally, while we only want to
log inputs and outputs that are opened explicitly by the user.
The user can either use `recipy.open` (only requires `import recipy` at the
top of the script), or add `from recipy import open` and just use `open`.
If python 2 is used, and an `encoding` parameter is passed to this
function, `codecs` is used to open the file with proper encoding.
"""
if 'mode' in kwargs.keys():
mode = kwargs['mode'] # Python 3
else:
try:
mode = args[1] # Python 2
except:
mode = 'r' # Default (in Python 2)
# open file for reading?
for c in 'r+':
if c in mode:
log_input(args[0], 'recipy.open')
# open file for writing?
for c in 'wax+':
if c in mode:
log_output(args[0], 'recipy.open')
if sys.version_info[0] == 2:
if 'encoding' in kwargs.keys():
import codecs
f = codecs.open(*args, **kwargs)
else:
f = __builtins__['open'](*args, **kwargs)
else:
f = __builtins__['open'](*args, **kwargs)
return(f)
|
Remove cwd from file name. | const fs = require('fs');
const parseInput = (input, config) => new Promise((resolve, reject) => {
let parser = () => null;
if (!config.parser) {
parser = require('doxdox-parser-dox');
}
fs.stat(input, (err, stats) => {
if (err) {
return reject(err);
}
if (stats.isFile()) {
fs.readFile(input, 'utf8', (err, data) => {
if (err) {
return reject(err);
}
return resolve({
'name': input.replace(process.cwd(), ''),
'methods': parser(data, {'file': input})
});
});
}
return false;
});
});
const parseInputs = (inputs, config) => new Promise(resolve => {
let layout = () => null;
if (!config.layout || config.layout === 'markdown') {
layout = require('doxdox-plugin-markdown');
}
if (inputs.length) {
Promise.all(inputs.map(input => parseInput(input, config)))
.then(files => layout(Object.assign({
files
}, config)))
.then(resolve);
}
});
module.exports = {
parseInputs
};
| const fs = require('fs');
const parseInput = (input, config) => new Promise((resolve, reject) => {
let parser = () => null;
if (!config.parser) {
parser = require('doxdox-parser-dox');
}
fs.stat(input, (err, stats) => {
if (err) {
return reject(err);
}
if (stats.isFile()) {
fs.readFile(input, 'utf8', (err, data) => {
if (err) {
return reject(err);
}
return resolve({
'contents': data,
'file': input,
'methods': parser(data, {'file': input})
});
});
}
return false;
});
});
const parseInputs = (inputs, config) => new Promise(resolve => {
let layout = () => null;
if (!config.layout || config.layout === 'markdown') {
layout = require('doxdox-plugin-markdown');
}
if (inputs.length) {
Promise.all(inputs.map(input => parseInput(input, config)))
.then(files => layout(Object.assign({
files
}, config)))
.then(resolve);
}
});
module.exports = {
parseInputs
};
|
Fix edit user route param
Signed-off-by: Christoph Wurst <[email protected]> | @extends('settings/settings')
@section('settings_content')
<h1>Benutzer</h1>
@if (Auth::user()->isAdmin())
<a class="btn btn-default"
type="button"
href="{!! route('settings.users/create') !!}">
<span class="glyphicon glyphicon-plus"></span>
Benutzer hinzufügen
</a>
@endif
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Benutzername</th>
<th>Administrator</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
@foreach ($users as $u)
<tr>
<td>
{!! link_to_route('settings.user/show', $u->username, array('user' => $u->username)) !!}
</td>
<td>
@if ($u->isAdmin())
<span class="glyphicon glyphicon-ok"></span>
@else
-
@endif
</td>
<td>
{!! link_to_route('settings.users/edit', 'bearbeiten',
array('user' => $u)) !!}
@if($u->username != Auth::user()->username)
| {!! link_to_route('settings.users/delete', 'löschen', array('user' => $u->username)) !!}
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- /.table-responsive -->
@stop
| @extends('settings/settings')
@section('settings_content')
<h1>Benutzer</h1>
@if (Auth::user()->isAdmin())
<a class="btn btn-default"
type="button"
href="{!! route('settings.users/create') !!}">
<span class="glyphicon glyphicon-plus"></span>
Benutzer hinzufügen
</a>
@endif
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Benutzername</th>
<th>Administrator</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
@foreach ($users as $u)
<tr>
<td>
{!! link_to_route('settings.user/show', $u->username, array('user' => $u->username)) !!}
</td>
<td>
@if ($u->isAdmin())
<span class="glyphicon glyphicon-ok"></span>
@else
-
@endif
</td>
<td>
{!! link_to_route('settings.users/edit', 'bearbeiten',
array('username' => $u->username)) !!}
@if($u->username != Auth::user()->username)
| {!! link_to_route('settings.users/delete', 'löschen', array('user' => $u->username)) !!}
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- /.table-responsive -->
@stop |
Add cancel button to earnings' edit view | @extends('layout')
@section('body')
<div class="wrapper my-3">
<h2>{{ __('actions.edit') }} {{ __('general.earning') }}</h2>
<div class="box mt-3">
<form method="POST" action="/earnings/{{ $earning->id }}" autocomplete="off">
{{ method_field('PATCH') }}
{{ csrf_field() }}
<div class="box__section">
<div class="input input--small">
<label>Date</label>
<DatePicker></DatePicker>
@include('partials.validation_error', ['payload' => 'date'])
</div>
<div class="input input--small">
<label>Description</label>
<input type="text" name="description" value="{{ $earning->description }}" />
@include('partials.validation_error', ['payload' => 'description'])
</div>
<div class="input input--small mb-0">
<label>Amount</label>
<input type="text" name="amount" value="{{ $earning->amount }}" />
@include('partials.validation_error', ['payload' => 'amount'])
</div>
</div>
<div class="box__section box__section--highlight row row--right">
<div class="row__column row__column--compact row__column--middle">
<a href="/earnings">{{ __('actions.cancel') }}</a>
</div>
<div class="row__column row__column--compact ml-2">
<button class="button">@lang('actions.save')</button>
</div>
</div>
</form>
</div>
</div>
@endsection
| @extends('layout')
@section('body')
<div class="wrapper my-3">
<h2>{{ __('actions.edit') }} {{ __('general.earning') }}</h2>
<div class="box mt-3">
<form method="POST" action="/earnings/{{ $earning->id }}" autocomplete="off">
{{ method_field('PATCH') }}
{{ csrf_field() }}
<div class="box__section">
<div class="input input--small">
<label>Date</label>
<DatePicker></DatePicker>
@include('partials.validation_error', ['payload' => 'date'])
</div>
<div class="input input--small">
<label>Description</label>
<input type="text" name="description" value="{{ $earning->description }}" />
@include('partials.validation_error', ['payload' => 'description'])
</div>
<div class="input input--small mb-0">
<label>Amount</label>
<input type="text" name="amount" value="{{ $earning->amount }}" />
@include('partials.validation_error', ['payload' => 'amount'])
</div>
</div>
<div class="box__section box__section--highlight text-right">
<button class="button">@lang('actions.save')</button>
</div>
</form>
</div>
</div>
@endsection
|
Add a link to the import-subscribers page in the sidebar | import React from 'react';
import SideLink from '../common/SideLink';
import { Link } from 'react-router';
const Sidebar = (props) => { // eslint-disable-line no-unused-vars
return (
<aside className="main-sidebar">
<section className="sidebar">
<div className="user-panel">
<div className="pull-left image"><img className="img-circle" src="https://placeholdit.imgix.net/~text?txtsize=15&txt=160%C3%97160&w=160&h=160" alt="User Image" /></div>
<div className="pull-left info">
<p>Test user</p>
<a> Online</a></div>
</div>
<ul className="sidebar-menu">
<li className="header">OPTIONS</li>
<SideLink to="/">Home</SideLink>
<SideLink to="/settings">Settings</SideLink>
<li className="treeview"><a href="#"> Subscribers </a>
<ul className="treeview-menu">
<li><Link to="/add-email">Add email</Link></li>
<li><Link to="/import-subscribers">Import</Link></li>
</ul>
</li>
</ul>
</section>
</aside>
);
};
export default Sidebar;
| import React from 'react';
import SideLink from '../common/SideLink';
import { Link } from 'react-router';
const Sidebar = (props) => { // eslint-disable-line no-unused-vars
return (
<aside className="main-sidebar">
<section className="sidebar">
<div className="user-panel">
<div className="pull-left image"><img className="img-circle" src="https://placeholdit.imgix.net/~text?txtsize=15&txt=160%C3%97160&w=160&h=160" alt="User Image" /></div>
<div className="pull-left info">
<p>Test user</p>
<a> Online</a></div>
</div>
<ul className="sidebar-menu">
<li className="header">OPTIONS</li>
<SideLink to="/">Home</SideLink>
<SideLink to="/settings">Settings</SideLink>
<li className="treeview"><a href="#"> Subscribers </a>
<ul className="treeview-menu">
<li><Link to="/add-email">Add email</Link></li>
<li><a href="#">Link in level 2</a></li>
</ul>
</li>
</ul>
</section>
</aside>
);
};
export default Sidebar;
|
Remove "recursive symlink detected" UserWarning | import os
from pathlib import Path
from typing import Iterable, Iterator, List, Set
from isort.settings import Config
def find(
paths: Iterable[str], config: Config, skipped: List[str], broken: List[str]
) -> Iterator[str]:
"""Fines and provides an iterator for all Python source files defined in paths."""
visited_dirs: Set[Path] = set()
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(
path, topdown=True, followlinks=config.follow_links
):
base_path = Path(dirpath)
for dirname in list(dirnames):
full_path = base_path / dirname
resolved_path = full_path.resolve()
if config.is_skipped(full_path):
skipped.append(dirname)
dirnames.remove(dirname)
else:
if resolved_path in visited_dirs: # pragma: no cover
dirnames.remove(dirname)
visited_dirs.add(resolved_path)
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if config.is_supported_filetype(filepath):
if config.is_skipped(Path(os.path.abspath(filepath))):
skipped.append(filename)
else:
yield filepath
elif not os.path.exists(path):
broken.append(path)
else:
yield path
| import os
from pathlib import Path
from typing import Iterable, Iterator, List, Set
from warnings import warn
from isort.settings import Config
def find(
paths: Iterable[str], config: Config, skipped: List[str], broken: List[str]
) -> Iterator[str]:
"""Fines and provides an iterator for all Python source files defined in paths."""
visited_dirs: Set[Path] = set()
for path in paths:
if os.path.isdir(path):
for dirpath, dirnames, filenames in os.walk(
path, topdown=True, followlinks=config.follow_links
):
base_path = Path(dirpath)
for dirname in list(dirnames):
full_path = base_path / dirname
resolved_path = full_path.resolve()
if config.is_skipped(full_path):
skipped.append(dirname)
dirnames.remove(dirname)
else:
if resolved_path in visited_dirs: # pragma: no cover
if not config.quiet:
warn(f"Likely recursive symlink detected to {resolved_path}")
dirnames.remove(dirname)
visited_dirs.add(resolved_path)
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if config.is_supported_filetype(filepath):
if config.is_skipped(Path(os.path.abspath(filepath))):
skipped.append(filename)
else:
yield filepath
elif not os.path.exists(path):
broken.append(path)
else:
yield path
|
Fix metric expression test name. | from datetime import datetime
import json
import unittest
from pypercube.cube import Cube
from pypercube.cube import Query
from pypercube.metric import Metric
from pypercube.expression import EventExpression
from pypercube.expression import Sum
from tests import MockResponse
from tests import mock_get
class TestMetricExpressions(unittest.TestCase):
def setUp(self):
self.c = Cube('unittest')
def test_no_matching_metrics(self):
mock_response = MockResponse(ok=True, status_code='200',
content="[]", json=[])
Query.get = mock_get(mock_response)
event = EventExpression('test')
metric = Sum(event)
response = self.c.get_metric(metric, limit=10)
self.assertEqual(len(response), 0)
def test_single_matching_metric(self):
timestamp = datetime.utcnow()
expected_content = '[{"time":"' + timestamp.isoformat() + '", '\
'"value":100}]'
mock_response = MockResponse(ok=True, status_code='200',
content=expected_content, json=json.loads(expected_content))
Query.get = mock_get(mock_response)
event = EventExpression('test')
metric = Sum(event)
response = self.c.get_metric(metric, limit=1)
self.assertEqual(len(response), 1)
self.assertTrue(isinstance(response[0], Metric))
self.assertEqual(response[0].time, timestamp)
self.assertEqual(response[0].value, 100)
| from datetime import datetime
import json
import unittest
from pypercube.cube import Cube
from pypercube.cube import Query
from pypercube.metric import Metric
from pypercube.expression import EventExpression
from pypercube.expression import Sum
from tests import MockResponse
from tests import mock_get
class TestEventExpressions(unittest.TestCase):
def setUp(self):
self.c = Cube('unittest')
def test_no_matching_metrics(self):
mock_response = MockResponse(ok=True, status_code='200',
content="[]", json=[])
Query.get = mock_get(mock_response)
event = EventExpression('test')
metric = Sum(event)
response = self.c.get_metric(metric, limit=10)
self.assertEqual(len(response), 0)
def test_single_matching_metric(self):
timestamp = datetime.utcnow()
expected_content = '[{"time":"' + timestamp.isoformat() + '", '\
'"value":100}]'
mock_response = MockResponse(ok=True, status_code='200',
content=expected_content, json=json.loads(expected_content))
Query.get = mock_get(mock_response)
event = EventExpression('test')
metric = Sum(event)
response = self.c.get_metric(metric, limit=1)
self.assertEqual(len(response), 1)
self.assertTrue(isinstance(response[0], Metric))
self.assertEqual(response[0].time, timestamp)
self.assertEqual(response[0].value, 100)
|
Migrate from deprecated imp to importlib | """
automatically maintains the latest git tag + revision info in a python file
"""
import importlib
import os
import subprocess
def get_project_version(version_file):
version_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), version_file)
try:
module = importlib.load_module(version_file)
file_ver = module.__version__
except: # pylint: disable=bare-except
file_ver = None
try:
proc = subprocess.Popen(["git", "describe", "--always"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, _ = proc.communicate()
if stdout:
git_ver = stdout.splitlines()[0].strip().decode("utf-8")
if git_ver and ((git_ver != file_ver) or not file_ver):
open(version_file, "w").write("__version__ = '%s'\n" % git_ver)
return git_ver
except OSError:
pass
if not file_ver:
raise Exception("version not available from git or from file %r"
% version_file)
return file_ver
if __name__ == "__main__":
import sys
get_project_version(sys.argv[1])
| """
automatically maintains the latest git tag + revision info in a python file
"""
import imp
import os
import subprocess
def get_project_version(version_file):
version_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), version_file)
try:
module = imp.load_source("verfile", version_file)
file_ver = module.__version__
except: # pylint: disable=bare-except
file_ver = None
try:
proc = subprocess.Popen(["git", "describe", "--always"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, _ = proc.communicate()
if stdout:
git_ver = stdout.splitlines()[0].strip().decode("utf-8")
if git_ver and ((git_ver != file_ver) or not file_ver):
open(version_file, "w").write("__version__ = '%s'\n" % git_ver)
return git_ver
except OSError:
pass
if not file_ver:
raise Exception("version not available from git or from file %r"
% version_file)
return file_ver
if __name__ == "__main__":
import sys
get_project_version(sys.argv[1])
|
Change logging default true => false; accept nulls for logging and obfuscate_client_ip | <?php
namespace OwsProxy3\CoreBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Christian Wygoda
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ows_proxy3_core');
$rootNode
->canBeUnset()->addDefaultsIfNotSet()
->children()
->booleanNode('logging')
->defaultFalse()
->treatNullLike(false)
->end()
->booleanNode('obfuscate_client_ip')
->defaultTrue()
->treatNullLike(true)
->end()
->arrayNode("proxy")
->canBeUnset()
->addDefaultsIfNotSet()
->children()
->scalarNode('host')->defaultNull()->end()
->scalarNode('port')->defaultNull()->end()
->scalarNode('connecttimeout')->defaultNull()->end()
->scalarNode('timeout')->defaultNull()->end()
->scalarNode('user')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()
->scalarNode('checkssl')->defaultNull()->end()
->arrayNode("noproxy")
->prototype('scalar')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace OwsProxy3\CoreBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Christian Wygoda
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ows_proxy3_core');
$rootNode
->children()
->scalarNode('logging')
->defaultTrue()
->end()
->scalarNode('obfuscate_client_ip')
->defaultTrue()
->end()
->arrayNode("proxy")
->canBeUnset()
->addDefaultsIfNotSet()
->children()
->scalarNode('host')->defaultNull()->end()
->scalarNode('port')->defaultNull()->end()
->scalarNode('connecttimeout')->defaultNull()->end()
->scalarNode('timeout')->defaultNull()->end()
->scalarNode('user')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()
->scalarNode('checkssl')->defaultNull()->end()
->arrayNode("noproxy")
->prototype('scalar')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
|
Fix e.keypress being called when it does not exist | function add_quicksearch(input, result_div, url) {
input.closest('form').submit(function() {
result_div.load(url, {quicksearch: input.val()});
return false;
});
}
function add_tablesorter(table) {
var table = $(table);
var headers = {};
headers[table.find('th').length - 1] = { sorter: false};
table.tablesorter({
widgets: ['zebra'],
headers: headers
});
}
function initForms() {
// Removes 'Hold down' helptext.
$('.helptext:contains(' + 'Hold down "Control"' + ')').remove();
// Form stuff.
$('.cancel').click(function() {
var $this = $(this);
$('#' + $this.attr('data-formId')).slideUp('fast', 'easeOutExpo');
});
$('.submit').click(function() {
$(this).closest('form').submit();
});
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).closest('form').submit();
}
});
$('.submit-on-change').change(function() {
this.form.submit();
});
}
function slideUp($e) {
$e.slideUp(200, 'easeOutExpo');
}
function slideDown($e) {
$e.slideDown(500, 'easeOutExpo');
}
$(document).ready(function() {
initForms();
});
| function add_quicksearch(input, result_div, url) {
input.closest('form').submit(function() {
result_div.load(url, {quicksearch: input.val()});
return false;
});
}
function add_tablesorter(table) {
var table = $(table);
var headers = {};
headers[table.find('th').length - 1] = { sorter: false};
table.tablesorter({
widgets: ['zebra'],
headers: headers
});
}
function initForms() {
// Removes 'Hold down' helptext.
$('.helptext:contains(' + 'Hold down "Control"' + ')').remove();
// Form stuff.
$('.cancel').click(function() {
var $this = $(this);
$('#' + $this.attr('data-formId')).slideUp('fast', 'easeOutExpo');
});
$('.submit').click(function() {
$(this).closest('form').submit();
});
$('input').keypress(function(e) {
if (e.keypress == 13) {
$(this).closest('form').submit();
}
});
$('.submit-on-change').change(function() {
this.form.submit();
});
}
function slideUp($e) {
$e.slideUp(200, 'easeOutExpo');
}
function slideDown($e) {
$e.slideDown(500, 'easeOutExpo');
}
$(document).ready(function() {
initForms();
});
|
Correct link in backend not logged | <td class="header_menu">
<div class="menu_top">
<table>
<tr>
<td rowspan="2" style="height:90px"> </td>
</tr>
<tr>
<td>
<ul class="menu_link">
<li><?php echo link_to(__('Our collections'),$sf_context->getConfiguration()->generatePublicUrl('homepage'));?></li>
<li><?php echo link_to(__('Search'),$sf_context->getConfiguration()->generatePublicUrl('homepage').'search/search');?></li>
<li><?php echo link_to(__('Take a tour'),$sf_context->getConfiguration()->generatePublicUrl('tour'));?></li>
<li><?php echo link_to(__('Contacts'),$sf_context->getConfiguration()->generatePublicUrl('contact'));?></li>
<li><?php echo link_to(__('About'),$sf_context->getConfiguration()->generatePublicUrl('about'));?></li>
</ul>
</td>
</tr>
<tr>
<td class="lang_picker">
<ul style="">
<li><?php echo link_to('En','account/lang?lang=en');?></li>
<li class="sep">|<li>
<li><?php echo link_to('Fr','account/lang?lang=fr');?></li>
<li class="sep">|<li>
<li><?php echo link_to('Nl','account/lang?lang=nl');?></li>
</ul>
</td>
</tr>
</table>
<div class="blue_line"></div>
</div>
</td>
| <td class="header_menu">
<div class="menu_top">
<table>
<tr>
<td rowspan="2" style="height:90px"> </td>
</tr>
<tr>
<td>
<ul class="menu_link">
<li><?php echo link_to(__('Our collections'),$sf_context->getConfiguration()->generatePublicUrl('homepage'));?></li>
<li><?php echo link_to(__('Search'),$sf_context->getConfiguration()->generatePublicUrl('homepage').'search/search');?></li>
<li><?php echo link_to(__('Take a tour'),$sf_context->getConfiguration()->generatePublicUrl('homepage'));?></li>
<li><?php echo link_to(__('Contacts'),$sf_context->getConfiguration()->generatePublicUrl('homepage'));?></li>
<li><?php echo link_to(__('Links'),$sf_context->getConfiguration()->generatePublicUrl('homepage'));?></li>
</ul>
</td>
</tr>
<tr>
<td class="lang_picker">
<ul style="">
<li><?php echo link_to('En','account/lang?lang=en');?></li>
<li class="sep">|<li>
<li><?php echo link_to('Fr','account/lang?lang=fr');?></li>
<li class="sep">|<li>
<li><?php echo link_to('Nl','account/lang?lang=nl');?></li>
</ul>
</td>
</tr>
</table>
<div class="blue_line"></div>
</div>
</td>
|
Add classifiers of Python 3.6 3.7 | from setuptools import setup
import urlfetch
import re
import os
import sys
setup(
name="urlfetch",
version=urlfetch.__version__,
author=re.sub(r'\s+<.*', r'', urlfetch.__author__),
author_email=re.sub(r'(^.*<)|(>.*$)', r'', urlfetch.__author__),
url=urlfetch.__url__,
description="An easy to use HTTP client",
long_description=open('README.rst').read(),
license="BSD",
keywords="httpclient urlfetch",
py_modules=['urlfetch'],
data_files=[('', ['urlfetch.useragents.list'])],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: POSIX :: Linux',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite='tests.testall',
tests_require=['bottle', 'gunicorn'],
)
| from setuptools import setup
import urlfetch
import re
import os
import sys
setup(
name="urlfetch",
version=urlfetch.__version__,
author=re.sub(r'\s+<.*', r'', urlfetch.__author__),
author_email=re.sub(r'(^.*<)|(>.*$)', r'', urlfetch.__author__),
url=urlfetch.__url__,
description="An easy to use HTTP client",
long_description=open('README.rst').read(),
license="BSD",
keywords="httpclient urlfetch",
py_modules=['urlfetch'],
data_files=[('', ['urlfetch.useragents.list'])],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: POSIX :: Linux',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite='tests.testall',
tests_require=['bottle', 'gunicorn'],
)
|
Cut the message buffer down before forwarding | package blue.mesh;
import android.util.Log;
public class ReadWriteThread extends Thread {
private final RouterObject router;
private final Connection connection;
private static final String TAG = "ReadWriteThread";
protected ReadWriteThread(RouterObject a_router, Connection a_connection){
Log.d(TAG, "RWTHREAD CONNECTED!");
router = a_router;
connection = a_connection;
}
public void run() {
byte[] buffer = new byte[Constants.MAX_MESSAGE_LEN];
// Keep listening to the InputStream while connected
while (true) {
if (this.isInterrupted()) {
break;
}
int bytes = connection.read( buffer );
if( bytes > 0 ){
Log.d(TAG, "Got something");
}
if( bytes > 0 && buffer != null ){
Log.d(TAG, buffer.toString());
byte[] returnBuffer = new byte[bytes];
for( int i = 0; i < bytes; i++ ){
returnBuffer[i] = buffer[i];
}
router.route(returnBuffer, Constants.SRC_OTHER);
}
}
disconnect();
return;
}
private int disconnect(){
// On exit close the in and out sockets and the Bluetooth socket
router.notifyDisconnected(connection.getID(), this);
connection.close();
Log.d(TAG, "ReadWriteThread returned");
return Constants.SUCCESS;
}
protected int write(byte[] buffer) {
Log.d(TAG, "Writing bytes: " + buffer.toString() );
connection.write( buffer );
return Constants.SUCCESS;
}
}
| package blue.mesh;
import android.util.Log;
public class ReadWriteThread extends Thread {
private final RouterObject router;
private final Connection connection;
private static final String TAG = "ReadWriteThread";
protected ReadWriteThread(RouterObject a_router, Connection a_connection){
Log.d(TAG, "RWTHREAD CONNECTED!");
router = a_router;
connection = a_connection;
}
public void run() {
byte[] buffer = null;
// Keep listening to the InputStream while connected
while (true) {
if (this.isInterrupted()) {
break;
}
int bytes = connection.read( buffer );
if( bytes > 0 ){
router.route(buffer, Constants.SRC_OTHER);
}
}
disconnect();
return;
}
private int disconnect(){
// On exit close the in and out sockets and the Bluetooth socket
router.notifyDisconnected(connection.getID(), this);
connection.close();
Log.d(TAG, "ReadWriteThread returned");
return Constants.SUCCESS;
}
protected int write(byte[] buffer) {
Log.d(TAG, "Writing bytes");
connection.write( buffer );
return Constants.SUCCESS;
}
}
|
Add some commented-out code to hide the text label of rich text elements | /* global django, CKEDITOR */
(function($) {
// Activate and deactivate the CKEDITOR because it does not like
// getting dragged or its underlying ID changed.
// The 'data-processed' attribute is set for compatibility with
// django-ckeditor.
$(document).on(
'content-editor:activate',
function(event, $row, formsetName) {
$row.find('textarea[data-type=ckeditortype]').each(function() {
if (this.getAttribute('data-processed') != '1') {
this.setAttribute('data-processed', '1')
$($(this).data('external-plugin-resources')).each(function(){
CKEDITOR.plugins.addExternal(this[0], this[1], this[2]);
});
CKEDITOR.replace(this.id, $(this).data('config'));
}
});
}
).on(
'content-editor:deactivate',
function(event, $row, formsetName) {
$row.find('textarea[data-type=ckeditortype]').each(function() {
try {
CKEDITOR.instances[this.id] && CKEDITOR.instances[this.id].destroy();
this.setAttribute('data-processed', '0')
} catch(err) {}
});
}
);
// Move CKEditor up a bit to hide the text label.
// var style = document.createElement('style');
// style.textContent = '.order-machine .django-ckeditor-widget { margin: -30px 0 0 -1px; }';
// document.head.appendChild(style);
})(django.jQuery);
| /* global django, CKEDITOR */
(function($) {
// Activate and deactivate the CKEDITOR because it does not like
// getting dragged or its underlying ID changed.
// The 'data-processed' attribute is set for compatibility with
// django-ckeditor.
$(document).on(
'content-editor:activate',
function(event, $row, formsetName) {
$row.find('textarea[data-type=ckeditortype]').each(function() {
if (this.getAttribute('data-processed') != '1') {
this.setAttribute('data-processed', '1')
$($(this).data('external-plugin-resources')).each(function(){
CKEDITOR.plugins.addExternal(this[0], this[1], this[2]);
});
CKEDITOR.replace(this.id, $(this).data('config'));
}
});
}
).on(
'content-editor:deactivate',
function(event, $row, formsetName) {
$row.find('textarea[data-type=ckeditortype]').each(function() {
try {
CKEDITOR.instances[this.id] && CKEDITOR.instances[this.id].destroy();
this.setAttribute('data-processed', '0')
} catch(err) {}
});
}
);
})(django.jQuery);
|
Make cache headers sentitive to urls | (function (angular) {
"use strict";
angular.module("mfl.gis.interceptor", [])
.factory("mfl.gis.interceptor.headers", [function () {
var cache_headers = {};
var request_fxn = function(config) {
var headers = cache_headers[config.url];
if (_.isUndefined(headers)) {
console.log("cache miss : ", config.url);
return config;
}
console.log("cache hit : ", config.url);
if (headers.etag_header) {
config.headers.ETag = headers.etag_header;
config.headers["If-None-Match"] = headers.etag_header;
}
if (headers.last_modified_header) {
config.headers["If-Modified-Since"] = headers.last_modified_header;
}
return config;
};
var response_fxn = function(response) {
var etag = response.headers("ETag");
var last_modified = response.headers("Last-Modified");
var headers = {};
if (etag) {
headers.etag_header = etag;
}
if (last_modified) {
headers.last_modified_header = last_modified;
}
cache_headers[response.config.url] = headers;
return response;
};
return {
"request" : request_fxn,
"response": response_fxn
};
}]);
})(angular);
| (function (angular) {
"use strict";
angular.module("mfl.gis.interceptor", [])
.factory("mfl.gis.interceptor.headers", [function () {
var etag_header = null;
var last_modified_header = null;
return {
"request" : function(config) {
if (etag_header) {
config.headers.ETag = etag_header;
config.headers["If-None-Match"] = etag_header;
}
if (last_modified_header) {
config.headers["If-Modified-Since"] = last_modified_header;
}
return config;
},
"response": function(response) {
var etag = response.headers("ETag");
var last_modified = response.headers("Last-Modified");
if (etag) {
etag_header = etag;
}
if (last_modified) {
last_modified_header = last_modified;
}
return response;
}
};
}]);
})(angular);
|
Fix width and height properties in url() method | <?php
namespace Uploadify\Casts;
use Uploadify\Casts\Cast as BaseCast;
class ImageCast extends BaseCast
{
/**
* Get full url to file
*
* @param int|array $width
* @param int $height
* @param array $options
* @return string
*/
public function url($width = null, $height = null, array $options = [])
{
if (is_array($width)) {
$options = $width;
} elseif ($width) {
$options['w'] = $width;
}
if ($height) {
$options['h'] = $height;
}
if (! empty($options)) {
return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
}
return $this->getStorage()->url($this->path().'/'.$this->name());
}
/**
* Prepare and convert options from array to string
*
* @param array $options
*/
protected function prepareOptions(array $options = [])
{
$string = implode(',', array_map(
function ($value, $key) {
return $key.'_'.$value;
},
$options,
array_keys($options)
));
$from = ['width', 'height'];
$to = ['w', 'h'];
return str_replace($from, $to, $string);
}
}
| <?php
namespace Uploadify\Casts;
use Uploadify\Casts\Cast as BaseCast;
class ImageCast extends BaseCast
{
/**
* Get full url to file
*
* @param int|array $width
* @param int $height
* @param array $options
* @return string
*/
public function url($width = null, $height = null, array $options = [])
{
if (is_array($width)) {
$options = $width;
}
if (empty($options)) {
if ($width) {
$options['w'] = $width;
}
if ($height) {
$options['h'] = $height;
}
}
if (! empty($options)) {
return $this->getStorage()->url($this->path().'/'.$this->prepareOptions($options).'/'.$this->name());
}
return $this->getStorage()->url($this->path().'/'.$this->name());
}
/**
* Prepare and convert options from array to string
*
* @param array $options
*/
protected function prepareOptions(array $options = [])
{
$string = implode(',', array_map(
function ($value, $key) {
return $key.'_'.$value;
},
$options,
array_keys($options)
));
$from = ['width', 'height'];
$to = ['w', 'h'];
return str_replace($from, $to, $string);
}
}
|
Remove a ton of metaclass complexity
If I'd read the jinja2 documentation, I'd have seen that dotted notation
is equivalent to subscript notation, which means metaclasses and
generated classes aren't necessary. At all.
Note-to-self for the future: RTFM. | import argparse
import jinja2
import os
import yaml
from debug.debug import dprint
def load_templates(template_dir=os.path.join(os.getcwd(), 'template')):
loader = jinja2.FileSystemLoader(template_dir)
environment = jinja2.environment.Environment(loader=loader)
return environment
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generates multiple resume outputs from a singular YAML-formatted source")
parser.add_argument('source_file', help="yaml-formatted containing the desired resume sections")
args = parser.parse_args()
environment = load_templates()
dprint("found templates {}".format(environment.list_templates()))
with open('resume.txt', 'w') as output:
with open(args.source_file, 'r') as source_file:
raw = yaml.load(source_file)
for section, value in zip(raw.keys(), raw.values()):
try:
# Wow this is gross. refactor a _ton_
template = environment.get_template(os.path.join('plain_text',section+os.path.extsep+'txt'))
dprint("found template {}".format(template))
metaargs = dict()
metaargs[section] = value
output.write(template.render(metaargs))
except (jinja2.TemplateNotFound):
print("Source section '{}' found in source file, but no template exists".format(section))
| import argparse
import jinja2
import os
import types
import yaml
from debug.debug import dprint
def load_templates(template_dir=os.path.join(os.getcwd(), 'template')):
loader = jinja2.FileSystemLoader(template_dir)
environment = jinja2.environment.Environment(loader=loader)
return environment
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generates multiple resume outputs from a singular YAML-formatted source")
parser.add_argument('source_file', help="yaml-formatted containing the desired resume sections")
args = parser.parse_args()
environment = load_templates()
dprint("found templates {}".format(environment.list_templates()))
with open('resume.txt', 'w') as output:
with open(args.source_file, 'r') as source_file:
raw = yaml.load(source_file)
for section, value in zip(raw.keys(), raw.values()):
try:
# Wow this is gross. refactor a _ton_
template = environment.get_template(os.path.join('plain_text',section+os.path.extsep+'txt'))
dprint("found template {}".format(template))
metatype = types.new_class(section)
dprint("created metatype {}".format(metatype))
metaobject = metatype()
metaobject.__dict__ = value
dprint("metaobject = {}".format(str(metaobject)))
dprint("metaobject = {}".format(metaobject.__dict__))
metaargs = dict()
metaargs[section] = metaobject
output.write(template.render(metaargs))
except (jinja2.TemplateNotFound):
print("Source section '{}' found in source file, but no template exists".format(section))
|
Revert "Enabled a custom mapping"
This reverts commit ca094beb7e2effd0b38faeba1dd95b2437ffb443. | <?php
namespace Xidea\Bundle\BaseBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle,
Symfony\Component\DependencyInjection\ContainerBuilder;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
abstract class AbstractBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$this->addRegisterMappingsPass($container, $this->getName());
}
/**
* @param ContainerBuilder $container
*/
protected function addRegisterMappingsPass(ContainerBuilder $container, $bundleName)
{
$mappings = $this->getModelMappings();
if(!empty($mappings)) {
$container->addCompilerPass(DoctrineOrmMappingsPass::createYamlMappingDriver(
$mappings,
array(),
false,
array($bundleName => $this->getModelNamespace())
));
}
}
protected function getModelNamespace()
{
return 'Xidea\Component\Base\Model';
}
protected function getModelMappings()
{
return array(
sprintf($this->getConfigPath().'/%s', $this->getDoctrineMappingDirectory()) => $this->getModelNamespace()
);
}
protected function getDoctrineMappingDirectory()
{
return 'doctrine/model';
}
protected function getConfigPath()
{
return sprintf(
'%s/Resources/config',
$this->getPath()
);
}
}
| <?php
namespace Xidea\Bundle\BaseBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle,
Symfony\Component\DependencyInjection\ContainerBuilder;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
abstract class AbstractBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$this->addRegisterMappingsPass($container, $this->getName());
}
/**
* @param ContainerBuilder $container
*/
protected function addRegisterMappingsPass(ContainerBuilder $container, $bundleName)
{
$mappings = $this->getModelMappings();
if(!empty($mappings)) {
$container->addCompilerPass(DoctrineOrmMappingsPass::createYamlMappingDriver(
$mappings,
array(),
true,
array($bundleName => $this->getModelNamespace())
));
}
}
protected function getModelNamespace()
{
return 'Xidea\Component\Base\Model';
}
protected function getModelMappings()
{
return array(
sprintf($this->getConfigPath().'/%s', $this->getDoctrineMappingDirectory()) => $this->getModelNamespace()
);
}
protected function getDoctrineMappingDirectory()
{
return 'doctrine/model';
}
protected function getConfigPath()
{
return sprintf(
'%s/Resources/config',
$this->getPath()
);
}
}
|
Make sure to support new linter | // @flow
import pushUniqueVariable from '../helpers/pushUniqueVariable'
type Context = {
[number]: Array<VariableName>,
}
function getVariablesInContext(context: Context, column: number) {
return Object.keys(context)
.filter(key => Number(key) <= column)
// $FlowFixMe
.map(key => context[key])
.reduce((flattenArray, array) => flattenArray.concat(array), [])
}
export default class State {
variables: VariableList
context: Context
constructor() {
// Array of variable Nodes
this.variables = []
// Map of variable names
this.context = {}
}
getVariables() {
return this.variables
}
addVariables(column: number, variables: VariableList) {
const contextVars = getVariablesInContext(this.context, column)
variables
.filter(variable => contextVars.indexOf(variable.value) === -1)
.forEach((variable) => {
this.variables = [...this.variables, variable]
})
}
addToContext(column: number, variables: Array<VariableName>) {
if (variables.length > 0) {
if (this.context[column]) {
this.context[column] = pushUniqueVariable(this.context[column], variables)
} else {
this.context[column] = variables
}
}
}
clearContext(column: number) {
Object.keys(this.context)
.filter(key => Number(key) > column)
.forEach((key) => {
// $FlowFixMe
this.context[key] = []
})
}
}
| // @flow
import pushUniqueVariable from '../helpers/pushUniqueVariable'
type Context = {
[number]: Array<VariableName>,
}
function getVariablesInContext(context: Context, column: number) {
return Object.keys(context)
.filter(key => Number(key) <= column)
// $FlowFixMe
.map(key => context[key])
.reduce((flattenArray, array) => flattenArray.concat(array), [])
}
export default class State {
variables: VariableList
context: Context
constructor() {
// Array of variable Nodes
this.variables = []
// Map of variable names
this.context = {}
}
getVariables() {
return this.variables
}
addVariables(column: number, variables: VariableList) {
const contextVars = getVariablesInContext(this.context, column)
variables
.filter(variable => contextVars.indexOf(variable.value) === -1)
.forEach((variable) => {
this.variables = [...this.variables, variable]
})
}
addToContext(column: number, variables: Array<VariableName>) {
if (variables.length > 0) {
if (this.context[column]) {
this.context[column] = pushUniqueVariable(this.context[column], variables)
} else {
this.context[column] = variables
}
}
}
clearContext(column: number) {
Object.keys(this.context)
.filter(key => Number(key) > column)
.forEach((key) => {
// $FlowFixMe
this.context[key] = []
})
}
}
|
Use print_verbose for conditional printing. | # ome - Object Message Expressions
# Copyright (c) 2015-2016 Luke McCarthy <[email protected]>. All rights reserved.
import sys
from .command import command_args
from .error import OmeError
from .terminal import stderr
def print_verbose(*args, **kwargs):
if command_args.verbose:
print(*args, **kwargs)
def main():
stderr.reset()
try:
from . import compiler
target = compiler.get_target(command_args.target)
build_options = compiler.BuildOptions(target)
backend = compiler.get_backend(target, command_args.backend)
print_verbose('ome: using target {}'.format(target.name))
print_verbose('ome: using backend {} {}'.format(backend.name, backend.version))
for filename in command_args.filename:
print_verbose('ome: compiling {}'.format(filename))
if command_args.print_code:
print(compiler.compile_file(filename, target).decode(target.encoding))
else:
build_options.make_executable(filename, backend)
except OmeError as error:
error.write_ansi(stderr)
stderr.reset()
sys.exit(1)
if __name__ == '__main__':
if sys.version_info[0] < 3:
sys.exit('ome: error: please use python 3.x')
main()
| # ome - Object Message Expressions
# Copyright (c) 2015-2016 Luke McCarthy <[email protected]>. All rights reserved.
import sys
from .command import command_args
from .error import OmeError
from .terminal import stderr
def main():
stderr.reset()
try:
from . import compiler
target = compiler.get_target(command_args.target)
build_options = compiler.BuildOptions(target)
backend = compiler.get_backend(target, command_args.backend)
if command_args.verbose:
print('ome: using target {}'.format(target.name))
print('ome: using backend {} {}'.format(backend.name, backend.version))
for filename in command_args.filename:
if command_args.verbose:
print('ome: compiling {}'.format(filename))
if command_args.print_code:
print(compiler.compile_file(filename, target).decode(target.encoding))
else:
build_options.make_executable(filename, backend)
except OmeError as error:
error.write_ansi(stderr)
stderr.reset()
sys.exit(1)
if __name__ == '__main__':
if sys.version_info[0] < 3:
sys.exit('ome: error: please use python 3.x')
main()
|
Add individual curated set lookup | "use strict";
var querystring = require("querystring");
var SdkException = require("./sdkexception.js");
var WebHelper = require("./webhelper.js");
var GettyApiRequest = require("./baseclasses/gettyApiRequest.js");
const _ids = new WeakMap();
const _fields = new WeakMap();
class Events extends GettyApiRequest {
constructor(credentials, hostName) {
super(credentials,hostName);
this.setId = null;
this.page = 0;
this.pageSize = 0;
}
withSetId(setId) {
this.setId = setId;
return this;
}
withPage(page) {
this.page = page;
return this;
}
withPageSize(pageSize) {
this.pageSize = pageSize;
return this;
}
execute(next) {
var path = "/v3/sets";
if (this.setId) {
path += "/" + this.setId;
}
else {
var params = {};
if (this.page > 0) {
params.page = this.page;
}
if (this.pageSize > 0) {
params.page_size = this.pageSize;
}
path += "?";
path += querystring.stringify(params);
}
var webHelper = new WebHelper(this.credentials, this.hostName);
webHelper.get(path, function (err, response) {
if (err) {
next(err, null);
} else {
next(null, response);
}
});
}
}
module.exports = Events; | "use strict";
var querystring = require("querystring");
var SdkException = require("./sdkexception.js");
var WebHelper = require("./webhelper.js");
var GettyApiRequest = require("./baseclasses/gettyApiRequest.js");
const _ids = new WeakMap();
const _fields = new WeakMap();
class Events extends GettyApiRequest {
constructor(credentials, hostName) {
super(credentials,hostName);
this.page = 0;
this.pageSize = 0;
}
withPage(page) {
this.page = page;
return this;
}
withPageSize(pageSize) {
this.pageSize = pageSize;
return this;
}
execute(next) {
var path = "/v3/sets";
var params = {};
if (this.page > 0) {
params.page = this.page;
}
if (this.pageSize > 0) {
params.page_size = this.pageSize;
}
path += "?";
path += querystring.stringify(params);
var webHelper = new WebHelper(this.credentials, this.hostName);
webHelper.get(path, function (err, response) {
if (err) {
next(err, null);
} else {
next(null, response);
}
});
}
}
module.exports = Events; |
Use "style" property in package.json
This seems to be a prevailing standard already (http://stackoverflow.com/questions/32037150/style-field-in-package-json) so use that instead of https://xkcd.com/927/ | var findup = require('findup'),
path = require('path');
var local = require('./local');
function find(dir, file, callback) {
var name = file.split('/')[0],
modulePath = './node_modules/' + name + '/package.json';
findup(dir, modulePath, function (err, moduleDir) {
if (err) { return callback(err); }
var root = path.dirname(path.resolve(moduleDir, modulePath));
var location;
// if import is just a module name
if (file.split('/').length === 0) {
var json = require(path.resolve(moduleDir, modulePath));
// look for "style" declaration in package.json
if (json.style) {
location = json.style;
// otherwise assume ./styles.scss
} else {
location = './styles';
}
// if a full path is provided
} else {
location = path.join('../', file);
}
callback(null, path.resolve(root, location));
});
}
function importer(url, file, done) {
local(url, file, function (err, isLocal) {
if (err || isLocal) {
done({
file: url
});
} else {
find(path.dirname(file), url, function (err, location) {
if (err) {
done({
file: url
});
} else {
done({
file: location
});
};
});
}
})
}
module.exports = importer;
| var findup = require('findup'),
path = require('path');
var local = require('./local');
function find(dir, file, callback) {
var name = file.split('/')[0],
modulePath = './node_modules/' + name + '/package.json';
findup(dir, modulePath, function (err, moduleDir) {
if (err) { return callback(err); }
var root = path.dirname(path.resolve(moduleDir, modulePath));
var location;
// if import is just a module name
if (file.split('/').length === 0) {
var json = require(path.resolve(moduleDir, modulePath));
// look for styles declaration in package.json
if (json.styles) {
location = json.styles;
// otherwise assume ./styles.scss
} else {
location = './styles';
}
// if a full path is provided
} else {
location = path.join('../', file);
}
callback(null, path.resolve(root, location));
});
}
function importer(url, file, done) {
local(url, file, function (err, isLocal) {
if (err || isLocal) {
done({
file: url
});
} else {
find(path.dirname(file), url, function (err, location) {
if (err) {
done({
file: url
});
} else {
done({
file: location
});
};
});
}
})
}
module.exports = importer;
|
Call go test for src/ only | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), // the package file to use
qunit: { // internal task or name of a plugin (like "qunit")
all: ['js/tests/*.html']
},
watch: {
files: [
'js/tests/*.js',
'js/tests/*.html',
'tmpl/*.html',
'js/*.js',
'src/*.go'
],
tasks: ['qunit', 'shell:buildGo', 'shell:testGo']
},
shell: {
buildGo: {
command: 'go build -o rtfblog src/*.go',
options: {
stdout: true,
stderr: true
}
},
testGo: {
command: 'go test ./src/...',
options: {
stdout: true,
stderr: true
}
}
}
});
// load up your plugins
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');
// register one or more task lists (you should ALWAYS have a "default" task list)
grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), // the package file to use
qunit: { // internal task or name of a plugin (like "qunit")
all: ['js/tests/*.html']
},
watch: {
files: [
'js/tests/*.js',
'js/tests/*.html',
'tmpl/*.html',
'js/*.js',
'src/*.go'
],
tasks: ['qunit', 'shell:buildGo', 'shell:testGo']
},
shell: {
buildGo: {
command: 'go build -o rtfblog src/*.go',
options: {
stdout: true,
stderr: true
}
},
testGo: {
command: 'go test ./...',
options: {
stdout: true,
stderr: true
}
}
}
});
// load up your plugins
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');
// register one or more task lists (you should ALWAYS have a "default" task list)
grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']);
};
|
Use appropriate order of classes | # -*- coding: utf-8 -*-
from adminsortable.admin import SortableAdmin
from cms.admin.placeholderadmin import PlaceholderAdmin
from django.contrib import admin
from distutils.version import LooseVersion
from hvad.admin import TranslatableAdmin
import cms
from . import models
from aldryn_faq.forms import CategoryForm
class CategoryAdmin(TranslatableAdmin):
list_display = ['__unicode__', 'all_translations']
form = CategoryForm
def get_fieldsets(self, request, obj=None):
fieldsets = [
(None, {'fields': ['name', 'slug']}),
]
return fieldsets
class QuestionAdmin(SortableAdmin, PlaceholderAdmin):
render_placeholder_language_tabs = False
list_display = ['title', 'language', 'category', 'is_top']
def get_fieldsets(self, request, obj=None):
fieldsets = [
(None, {
'fields': ['title', 'language', 'category', 'answer_text', 'is_top']
})
]
# show placeholder field if not CMS 3.0
if LooseVersion(cms.__version__) < LooseVersion('3.0'):
fieldsets.append(
('Answer', {
'classes': ['plugin-holder', 'plugin-holder-nopage'],
'fields': ['answer']
}))
return fieldsets
admin.site.register(models.Question, QuestionAdmin)
admin.site.register(models.Category, CategoryAdmin)
| # -*- coding: utf-8 -*-
from adminsortable.admin import SortableAdmin
from cms.admin.placeholderadmin import PlaceholderAdmin
from django.contrib import admin
from distutils.version import LooseVersion
from hvad.admin import TranslatableAdmin
import cms
from . import models
from aldryn_faq.forms import CategoryForm
class CategoryAdmin(TranslatableAdmin):
list_display = ['__unicode__', 'all_translations']
form = CategoryForm
def get_fieldsets(self, request, obj=None):
fieldsets = [
(None, {'fields': ['name', 'slug']}),
]
return fieldsets
class QuestionAdmin(PlaceholderAdmin, SortableAdmin):
render_placeholder_language_tabs = False
list_display = ['title', 'language', 'category', 'is_top']
def get_fieldsets(self, request, obj=None):
fieldsets = [
(None, {
'fields': ['title', 'language', 'category', 'answer_text', 'is_top']
})
]
# show placeholder field if not CMS 3.0
if LooseVersion(cms.__version__) < LooseVersion('3.0'):
fieldsets.append(
('Answer', {
'classes': ['plugin-holder', 'plugin-holder-nopage'],
'fields': ['answer']
}))
return fieldsets
admin.site.register(models.Question, QuestionAdmin)
admin.site.register(models.Category, CategoryAdmin)
|
Document that python 3.10 is supported and update version number. | from setuptools import setup # type: ignore[import]
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="objname",
version="0.12.0",
packages=["objname"],
package_data={
"objname": ["__init__.py", "py.typed", "_module.py",
"test_objname.py"],
},
zip_safe=False,
author="Alan Cristhian Ruiz",
author_email="[email protected]",
description="A library with a base class that "
"stores the assigned name of an object.",
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development',
'Topic :: Software Development :: Object Brokering',
'Typing :: Typed'
],
license="MIT",
keywords="data structure debug",
url="https://github.com/AlanCristhian/objname",
)
| from setuptools import setup # type: ignore[import]
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="objname",
version="0.11.0",
packages=["objname"],
package_data={
"objname": ["__init__.py", "py.typed", "_module.py",
"test_objname.py"],
},
zip_safe=False,
author="Alan Cristhian Ruiz",
author_email="[email protected]",
description="A library with a base class that "
"stores the assigned name of an object.",
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development',
'Topic :: Software Development :: Object Brokering',
'Typing :: Typed'
],
license="MIT",
keywords="data structure debug",
url="https://github.com/AlanCristhian/objname",
)
|
Fix pytest path to root of package
Instead of the package init file. | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
__all__ = ['__version__']
# We first need to detect if we're being called as part of the skmisc
# setup procedure itself in a reliable manner.
try:
__SKMISC_SETUP__
except NameError:
__SKMISC_SETUP__ = False
if __SKMISC_SETUP__:
import sys as _sys
_sys.stderr.write('Running from skmisc source directory.\n')
del _sys
else:
try:
from skmisc.__config__ import show as show_config # noqa: F401
except ImportError as err:
msg = """Error importing skmisc: you cannot import skmisc while
being in skmisc source directory; please exit the skmisc source
tree first, and relaunch your python intepreter."""
raise ImportError('\n\n'.join([err.message, msg]))
__all__.append('show_config')
def test(args=None, plugins=None):
"""
Run tests
"""
# The doctests are not run when called from an installed
# package since the pytest.ini is not included in the
# package.
import os
try:
import pytest
except ImportError:
msg = "To run the tests, you must install pytest"
raise ImportError(msg)
path = os.path.dirname(os.path.realpath(__file__))
if args is None:
args = [path]
else:
args.append(path)
return pytest.main(args=args, plugins=plugins)
| from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
__all__ = ['__version__']
# We first need to detect if we're being called as part of the skmisc
# setup procedure itself in a reliable manner.
try:
__SKMISC_SETUP__
except NameError:
__SKMISC_SETUP__ = False
if __SKMISC_SETUP__:
import sys as _sys
_sys.stderr.write('Running from skmisc source directory.\n')
del _sys
else:
from skmisc.__config__ import show as show_config # noqa: F401
# try:
# from skmisc.__config__ import show as show_config # noqa: F401
# except ImportError:
# msg = """Error importing skmisc: you cannot import skmisc while
# being in skmisc source directory; please exit the skmisc source
# tree first, and relaunch your python intepreter."""
# raise ImportError(msg)
__all__.append('show_config')
def test(args=None, plugins=None):
"""
Run tests
"""
# The doctests are not run when called from an installed
# package since the pytest.ini is not included in the
# package.
import os
try:
import pytest
except ImportError:
msg = "To run the tests, you must install pytest"
raise ImportError(msg)
path = os.path.realpath(__file__)
if args is None:
args = [path]
else:
args.append(path)
return pytest.main(args=args, plugins=plugins)
|
Add select2 to long filters as well |
$(function() {
$('select').each(function() {
var $select = $(this)
if ($select.find('option').length < 7) return;
if ($select.is('[multiple]')) {
$select.siblings('.help-inline').addClass('hide')
}
$select.select2({
width: $select.width()
})
})
})
function dismissAddAnotherPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
// django.utils.html.escape.
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName == 'SELECT') {
var o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
$(elem).trigger('change')
} else if (elemName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
|
$(function() {
$('.change-form select').each(function() {
var $select = $(this)
if ($select.is('[multiple]')) {
$select.siblings('.help-inline').addClass('hide')
}
$select.select2({
width: $select.width()
})
})
})
function dismissAddAnotherPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
// django.utils.html.escape.
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName == 'SELECT') {
var o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
$(elem).trigger('change')
} else if (elemName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
|
Add user's names to review | import React, { Component } from 'react';
class Review extends Component {
constructor(props) {
super(props);
this.renderReviews = this.renderReviews.bind(this);
}
renderReviews() {
const { reviews } = this.props;
if (!reviews.length) {
return (
<div className = "row center">
<p> No Reviews yet.</p>
</div>
);
}
return reviews.map((review, index) => (
<div className="card-panel grey lighten-5" key = { index }>
<h6><i className="material-icons prefix">account_circle</i>{ `${review.userReviews.firstName} ${review.userReviews.lastName}` }
<span className="right"> { review.createdAt.split('T')[0] } </span> </h6>
<span className="bold">
{ review.review }
</span>
</div>
));
}
render() {
return (
<div>
<h5 className="header center-align book-header">Reviews</h5>
<div className="card-panel">
{ this.renderReviews() };
</div>
</div>
);
}
}
export default Review;
| import React, { Component } from 'react';
class Review extends Component {
constructor(props) {
super(props);
this.renderReviews = this.renderReviews.bind(this);
}
renderReviews() {
const { reviews } = this.props;
if (!reviews.length) {
return (
<div className = "row center">
<p className="flow-text"> No Reviews yet.</p>
</div>
);
}
return reviews.map((review, index) => (
<div className="card-panel grey lighten-5" key = { index }>
<h6><i className="material-icons prefix">account_circle</i>{ review.userId }
<span className="right"> { review.createdAt.split('T')[0] } </span> </h6>
<span className="bold">
{ review.review }
</span>
</div>
));
}
render() {
return (
<div>
<h5 className="header center-align book-header">Reviews</h5>
<div className="card-panel">
{ this.renderReviews() };
</div>
</div>
);
}
}
export default Review;
|
Fix create action for key value pair | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'reactor': "http://%s:9102" % st2host,
'datastore': "http://%s:9103" % st2host
}
try:
client = Client(st2_endpoints)
except Exception as e:
return e
if action == 'get':
kvp = client.keys.get_by_name(key)
if not kvp:
raise Exception('Key error with %s.' % key)
return kvp.value
else:
instance = client.keys.get_by_name(key) or KeyValuePair()
instance.id = key
instance.name = key
instance.value = value
kvp = client.keys.update(instance) if action in ['create', 'update'] else None
if action == 'delete':
return kvp
else:
return kvp.serialize()
| from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'reactor': "http://%s:9102" % st2host,
'datastore': "http://%s:9103" % st2host
}
try:
client = Client(st2_endpoints)
except Exception as e:
return e
if action == 'get':
kvp = client.keys.get_by_name(key)
if not kvp:
raise Exception('Key error with %s.' % key)
return kvp.value
else:
instance = KeyValuePair()
instance.id = client.keys.get_by_name(key).name
instance.name = key
instance.value = value
try:
kvstore = getattr(client.keys, action)
kvp = kvstore(instance)
except Exception as e:
raise
if action == 'delete':
return kvp
else:
return kvp.serialize()
|
Fix bug in ParticleSorter initialization | from hoomd.operation import _Tuner
from hoomd.parameterdicts import ParameterDict
from hoomd.typeconverter import OnlyType
from hoomd.trigger import Trigger
from hoomd import _hoomd
from math import log2, ceil
def to_power_of_two(value):
return int(2. ** ceil(log2(value)))
def natural_number(value):
try:
if value < 1:
raise ValueError("Expected positive integer.")
else:
return value
except TypeError:
raise ValueError("Expected positive integer.")
class ParticleSorter(_Tuner):
def __init__(self, trigger=200, grid=None):
self._param_dict = ParameterDict(
trigger=Trigger,
grid=OnlyType(int,
postprocess=lambda x: int(to_power_of_two(x)),
preprocess=natural_number,
allow_none=True)
)
self.trigger = trigger
self.grid = grid
def attach(self, simulation):
if simulation.device.mode == 'gpu':
cpp_cls = getattr(_hoomd, 'SFCPackTunerGPU')
else:
cpp_cls = getattr(_hoomd, 'SFCPackTuner')
self._cpp_obj = cpp_cls(simulation.state._cpp_sys_def, self.trigger)
super().attach(simulation)
| from hoomd.operation import _Tuner
from hoomd.parameterdicts import ParameterDict
from hoomd.typeconverter import OnlyType
from hoomd.trigger import Trigger
from hoomd import _hoomd
from math import log2, ceil
def to_power_of_two(value):
return int(2. ** ceil(log2(value)))
def natural_number(value):
try:
if value < 1:
raise ValueError("Expected positive integer.")
else:
return value
except TypeError:
raise ValueError("Expected positive integer.")
class ParticleSorter(_Tuner):
def __init__(self, trigger=200, grid=None):
self._param_dict = ParameterDict(
trigger=Trigger,
grid=OnlyType(int,
postprocess=lambda x: int(to_power_of_two(x)),
preprocess=natural_number,
allow_none=True)
)
self.trigger = trigger
self.grid = None
def attach(self, simulation):
if simulation.device.mode == 'gpu':
cpp_cls = getattr(_hoomd, 'SFCPackTunerGPU')
else:
cpp_cls = getattr(_hoomd, 'SFCPackTuner')
self._cpp_obj = cpp_cls(simulation.state._cpp_sys_def, self.trigger)
super().attach(simulation)
|
Test that nodes contain the methods we use | chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var observer = new MutationObserver(function (mutations) {
mutations.forEach(handleMutationEvents);
});
// configuration of the observer:
var config = {
attributes: true,
characterData: true,
childList: true,
subtree: true
};
observer.observe(document, config);
var handleMutationEvents = function handleMutationEvents(mutation) {
Array.prototype.forEach.call(mutation.addedNodes, styleLabelsInNode);
styleLabelsInNode(mutation.target);
}
var styleLabelsInNode = function styleLabelsInNode(node) {
if (nodeIsElement(node)) {
styleLabels(findLabelsInNode(node));
}
}
var nodeIsElement = function nodeIsElement(node) {
return (typeof node.querySelectorAll !== 'undefined');
}
var findLabelsInNode = function findLabelsInNode(node) {
return node.querySelectorAll('a.label');
}
var styleLabels = function styleLabels(labels) {
Array.prototype.forEach.call(labels, function(label) {
if (isLabelEligible(label.textContent)) {
label.classList.add('blocked');
} else {
label.classList.remove('blocked');
}
});
}
}
}, 10);
});
| chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var observer = new MutationObserver(function (mutations) {
mutations.forEach(handleMutationEvents);
});
// configuration of the observer:
var config = {
attributes: true,
characterData: true,
childList: true,
subtree: true
};
observer.observe(document, config);
var handleMutationEvents = function handleMutationEvents(mutation) {
Array.prototype.forEach.call(mutation.addedNodes, styleLabelsInNode);
styleLabelsInNode(mutation.target);
}
var styleLabelsInNode = function styleLabelsInNode(node) {
if (nodeIsElement(node)) {
styleLabels(findLabelsInNode(node));
}
}
var nodeIsElement = function nodeIsElement(node) {
return (typeof node.getElementsByClassName !== 'undefined');
}
var findLabelsInNode = function findLabelsInNode(node) {
return node.querySelectorAll('a.label');
}
var styleLabels = function styleLabels(labels) {
Array.prototype.forEach.call(labels, function(label) {
if (isLabelEligible(label.textContent)) {
label.classList.add('blocked');
} else {
label.classList.remove('blocked');
}
});
}
}
}, 10);
});
|
Adhocracy-service: Change API to get single external static page | import requests
from pylons import config
class RESTAPI(object):
"""Helper to work with the adhocarcy_service rest api
(adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone).
"""
session = requests.Session()
def __init__(self):
self.api_token = config.get('adhocracy_service.rest_api_token', '')
self.api_address = config.get('adhocracy_service.rest_api_address', '')
self.headers = {"X-API-Token": self.api_token}
def staticpages_get(self, languages):
request = requests.Request("GET",
url='%s%s' % (
self.api_address,
"staticpages",
),
params={
'lang': languages,
},
headers=self.headers)
return self.session.send(request.prepare())
def staticpage_get(self, path, languages):
request = requests.Request("GET",
url='%s%s' % (
self.api_address,
'staticpages/single',
),
params={
'path': path,
'lang': languages,
},
headers=self.headers)
return self.session.send(request.prepare())
| import requests
from pylons import config
class RESTAPI(object):
"""Helper to work with the adhocarcy_service rest api
(adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone).
"""
session = requests.Session()
def __init__(self):
self.api_token = config.get('adhocracy_service.rest_api_token', '')
self.api_address = config.get('adhocracy_service.rest_api_address', '')
self.headers = {"X-API-Token": self.api_token}
def staticpages_get(self, languages):
request = requests.Request("GET",
url='%s%s' % (
self.api_address,
"staticpages",
),
params={
'lang': languages,
},
headers=self.headers)
return self.session.send(request.prepare())
def staticpage_get(self, path, languages):
request = requests.Request("GET",
url='%s%s/%s' % (
self.api_address,
"staticpages",
path,
),
params={
'lang': languages,
},
headers=self.headers)
return self.session.send(request.prepare())
|
Fix inability to edit or delete external links
Former-commit-id: 6e002af2f8605aaf35a0f8b2121c22a05716c082 | <?php
namespace Concrete\Controller\Backend\UserInterface;
use Exception;
use Page as ConcretePage;
use Permissions;
abstract class Page extends \Concrete\Controller\Backend\UserInterface
{
/** @var ConcretePage A page object */
protected $page;
public function __construct()
{
parent::__construct();
$request = $this->request;
$cID = $request->query->get('cID');
if ($cID) {
$page = ConcretePage::getByID($cID);
$this->setPageObject($page);
$request->setCurrentPage($this->page);
}
}
public function setPageObject(ConcretePage $c)
{
$this->page = $c;
$this->permissions = new Permissions($this->page);
$this->set('c', $this->page);
$this->set('cp', $this->permissions);
}
public function getViewObject()
{
if ($this->permissions->canViewPage()) {
return parent::getViewObject();
}
throw new Exception(t('Access Denied'));
}
public function action()
{
if ($this->page->getCollectionPointerOriginalID()) {
$cID = $this->page->getCollectionPointerOriginalID();
} else {
$cID = $this->page->getCollectionID();
}
$url = call_user_func_array('parent::action', func_get_args());
$url .= '&cID=' . $cID;
return $url;
}
}
| <?php
namespace Concrete\Controller\Backend\UserInterface;
use Exception;
use Page as ConcretePage;
use Permissions;
abstract class Page extends \Concrete\Controller\Backend\UserInterface
{
/** @var ConcretePage A page object */
protected $page;
public function __construct()
{
parent::__construct();
$request = $this->request;
$cID = $request->query->get('cID');
if ($cID) {
$page = ConcretePage::getByID($cID);
$this->setPageObject($page);
$request->setCurrentPage($this->page);
}
}
public function setPageObject(ConcretePage $c)
{
$this->page = $c;
$this->permissions = new Permissions($this->page);
$this->set('c', $this->page);
$this->set('cp', $this->permissions);
}
public function getViewObject()
{
if ($this->permissions->canViewPage()) {
return parent::getViewObject();
}
throw new Exception(t('Access Denied'));
}
public function action()
{
if ($this->page->isAlias()) {
$cID = $this->page->getCollectionPointerOriginalID();
} else {
$cID = $this->page->getCollectionID();
}
$url = call_user_func_array('parent::action', func_get_args());
$url .= '&cID=' . $cID;
return $url;
}
}
|
Add model transformer for json field | <?php
namespace Furniture\ProductBundle\Form\Type\PdpIntellectual;
use Furniture\CommonBundle\Form\DataTransformer\ObjectToStringTransformer;
use Furniture\ProductBundle\Entity\PdpIntellectualRoot;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PdpIntellectualRootType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => PdpIntellectualRoot::class
]);
}
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', 'text', [
'label' => 'Product',
'disabled' => true
])
->add('name', 'text', [
'label' => 'Name'
])
->add('graphJson', 'textarea', [
'read_only' => true,
]);
$builder->get('graphJson')
->addModelTransformer(new CallbackTransformer(
function ($array) {
return !empty($array) ? json_encode($array) : '';
},
function ($json) {
return json_decode($json, true);
}
));
$builder->get('product')->addModelTransformer(new ObjectToStringTransformer());
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'pdp_intellectual_root';
}
}
| <?php
namespace Furniture\ProductBundle\Form\Type\PdpIntellectual;
use Furniture\CommonBundle\Form\DataTransformer\ObjectToStringTransformer;
use Furniture\ProductBundle\Entity\PdpIntellectualRoot;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PdpIntellectualRootType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => PdpIntellectualRoot::class
]);
}
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', 'text', [
'label' => 'Product',
'disabled' => true
])
->add('name', 'text', [
'label' => 'Name'
])
->add('graphJson', 'textarea', [
'read_only' => true,
]);
$builder->get('product')->addModelTransformer(new ObjectToStringTransformer());
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'pdp_intellectual_root';
}
}
|
Add method to construct Capsule set from Iterable. | package mb.nabl2.util;
import java.util.Map.Entry;
import org.metaborg.util.functions.Function2;
import io.usethesource.capsule.Map;
import io.usethesource.capsule.Set;
public final class CapsuleUtil {
private CapsuleUtil() {
}
public static <K, V> void replace(Map.Transient<K, V> map, Function2<K, V, V> mapper) {
for(Entry<K, V> entry : map.entrySet()) {
final K key = entry.getKey();
final V val = mapper.apply(key, entry.getValue());
if(val != null) {
map.__put(key, val);
} else {
map.__remove(key);
}
}
}
public static <K, V> Map.Immutable<K, V> replace(Map.Immutable<K, V> map, Function2<K, V, V> mapper) {
final Map.Transient<K, V> newMap = Map.Transient.of();
for(Entry<K, V> entry : map.entrySet()) {
final K key = entry.getKey();
final V val = mapper.apply(key, entry.getValue());
if(val != null) {
newMap.__put(key, val);
}
}
return newMap.freeze();
}
@SuppressWarnings("unchecked") public static <V> Set.Immutable<V> toSet(Iterable<? extends V> values) {
if(values instanceof Set.Immutable) {
return (Set.Immutable<V>) values;
}
Set.Transient<V> set = Set.Transient.of();
for(V value : values) {
set.__insert(value);
}
return set.freeze();
}
} | package mb.nabl2.util;
import java.util.Map.Entry;
import org.metaborg.util.functions.Function2;
import io.usethesource.capsule.Map;
public final class CapsuleUtil {
private CapsuleUtil() {
}
public static <K, V> void replace(Map.Transient<K, V> map, Function2<K, V, V> mapper) {
for(Entry<K, V> entry : map.entrySet()) {
final K key = entry.getKey();
final V val = mapper.apply(key, entry.getValue());
if(val != null) {
map.__put(key, val);
} else {
map.__remove(key);
}
}
}
public static <K, V> Map.Immutable<K, V> replace(Map.Immutable<K, V> map, Function2<K, V, V> mapper) {
final Map.Transient<K, V> newMap = Map.Transient.of();
for(Entry<K, V> entry : map.entrySet()) {
final K key = entry.getKey();
final V val = mapper.apply(key, entry.getValue());
if(val != null) {
newMap.__put(key, val);
}
}
return newMap.freeze();
}
} |
Use io.open to support Python 2 | import io
from setuptools import setup, find_packages # pylint: disable=no-name-in-module,import-error
def dependencies(file):
with open(file) as f:
return f.read().splitlines()
with io.open("README.md", encoding='utf-8') as infile:
long_description = infile.read()
setup(
name='halo',
packages=find_packages(exclude=('tests', 'examples')),
version='0.0.23',
license='MIT',
description='Beautiful terminal spinners in Python',
long_description=long_description,
long_description_content_type="text/markdown",
author='Manraj Singh',
author_email='[email protected]',
url='https://github.com/manrajgrover/halo',
keywords=[
"console",
"loading",
"indicator",
"progress",
"cli",
"spinner",
"spinners",
"terminal",
"term",
"busy",
"wait",
"idle"
],
install_requires=dependencies('requirements.txt'),
tests_require=dependencies('requirements-dev.txt'),
include_package_data=True,
extras_require={
'ipython': [
'IPython==5.7.0',
'ipywidgets==7.1.0',
]
}
)
| from setuptools import setup, find_packages # pylint: disable=no-name-in-module,import-error
def dependencies(file):
with open(file) as f:
return f.read().splitlines()
with open("README.md", encoding='utf-8') as infile:
long_description = infile.read()
setup(
name='halo',
packages=find_packages(exclude=('tests', 'examples')),
version='0.0.23',
license='MIT',
description='Beautiful terminal spinners in Python',
long_description=long_description,
long_description_content_type="text/markdown",
author='Manraj Singh',
author_email='[email protected]',
url='https://github.com/manrajgrover/halo',
keywords=[
"console",
"loading",
"indicator",
"progress",
"cli",
"spinner",
"spinners",
"terminal",
"term",
"busy",
"wait",
"idle"
],
install_requires=dependencies('requirements.txt'),
tests_require=dependencies('requirements-dev.txt'),
include_package_data=True,
extras_require={
'ipython': [
'IPython==5.7.0',
'ipywidgets==7.1.0',
]
}
)
|
Deploy a single listener for UDP as port reuse is not supported. | package com.codingchili.router;
import com.codingchili.router.configuration.ListenerSettings;
import com.codingchili.router.configuration.RouterContext;
import com.codingchili.router.controller.RouterHandler;
import com.codingchili.router.controller.transport.*;
import io.vertx.core.*;
import com.codingchili.core.protocol.ClusterNode;
/**
* @author Robin Duda
* root game server, deploys realmName servers.
*/
public class Service extends ClusterNode {
private RouterContext context;
public Service(RouterContext context) {
this.context = context;
}
@Override
public void init(Vertx vertx, Context context) {
super.init(vertx, context);
if (context == null) {
this.context = new RouterContext(vertx);
}
}
@Override
public void start(Future<Void> start) {
for (ListenerSettings listener : context.transports()) {
RouterHandler<RouterContext> handler = new RouterHandler<>(context);
for (int i = 0; i < settings.getHandlers(); i++) {
boolean singleHandlerOnly = false;
Future<String> future = Future.future();
switch (listener.getType()) {
case UDP:
context.deploy(new UdpListener(handler), future);
singleHandlerOnly = true;
break;
case TCP:
context.deploy(new TcpListener(handler));
break;
case WEBSOCKET:
context.deploy(new WebsocketListener(handler));
break;
case REST:
context.deploy(new RestListener(handler));
break;
}
if (singleHandlerOnly) {
break;
}
}
}
start.complete();
}
}
| package com.codingchili.router;
import com.codingchili.router.configuration.ListenerSettings;
import com.codingchili.router.configuration.RouterContext;
import com.codingchili.router.controller.RouterHandler;
import com.codingchili.router.controller.transport.*;
import io.vertx.core.*;
import com.codingchili.core.protocol.ClusterNode;
/**
* @author Robin Duda
* root game server, deploys realmName servers.
*/
public class Service extends ClusterNode {
private RouterContext context;
public Service(RouterContext context) {
this.context = context;
}
@Override
public void init(Vertx vertx, Context context) {
super.init(vertx, context);
if (context == null) {
this.context = new RouterContext(vertx);
}
}
@Override
public void start(Future<Void> start) {
for (int i = 0; i < settings.getHandlers(); i++) {
for (ListenerSettings listener : context.transports()) {
RouterHandler<RouterContext> handler = new RouterHandler<>(context);
switch (listener.getType()) {
case UDP:
context.deploy(new UdpListener(handler));
break;
case TCP:
context.deploy(new TcpListener(handler));
break;
case WEBSOCKET:
context.deploy(new WebsocketListener(handler));
break;
case REST:
context.deploy(new RestListener(handler));
break;
}
}
}
start.complete();
}
}
|
Revert "E arruma o alinhamento do texto"
This reverts commit a7cb58ef323df97de537bb7cf0571c5ed26e113c. | import os
import datetime
import time
import picamera
from PIL import Image, ImageStat, ImageFont, ImageDraw
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.rotation = 180
time.sleep(2) # camera warm-up time
for filename in camera.capture_continuous('images/img_{timestamp:%Y%m%d%H%M%S}.png'):
image = Image.open(filename)
stat = ImageStat.Stat(image)
r, g, b, _ = stat.mean
if r < 50 and g < 50 and b < 50:
print('[!] Lights must be powered off, sleeping...')
try:
os.unlink(filename)
except:
pass
time.sleep(60 * 5)
else:
annotate_text = datetime.datetime.now().strftime('%H:%M:%S @ %d/%m/%Y')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('/usr/share/fonts/truetype/roboto/Roboto-Regular.ttf', 24)
draw.text((10, 730), annotate_text, (255, 255, 0), font=font)
image.save(filename)
print('[!] Taken: {}'.format(filename))
time.sleep(60 / 2)
image.close()
| import os
import datetime
import time
import picamera
from PIL import Image, ImageStat, ImageFont, ImageDraw
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.rotation = 180
time.sleep(2) # camera warm-up time
for filename in camera.capture_continuous('images/img_{timestamp:%Y%m%d%H%M%S}.png'):
image = Image.open(filename)
stat = ImageStat.Stat(image)
r, g, b, _ = stat.mean
if r < 50 and g < 50 and b < 50:
print('[!] Lights must be powered off, sleeping...')
try:
os.unlink(filename)
except:
pass
time.sleep(60 * 5)
else:
annotate_text = datetime.datetime.now().strftime('%H:%M:%S @ %d/%m/%Y')
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('/usr/share/fonts/truetype/roboto/Roboto-Regular.ttf', 24)
draw.text((10, 700), annotate_text, (255, 255, 0), font=font)
image.save(filename)
print('[!] Taken: {}'.format(filename))
time.sleep(60 / 2)
image.close()
|
Fix deadlock in remote debugger (PY-18546) | import sys
def __getfilesystemencoding():
'''
Note: there's a copy of this method in interpreterInfo.py
'''
try:
ret = sys.getfilesystemencoding()
if not ret:
raise RuntimeError('Unable to get encoding.')
return ret
except:
try:
#Handle Jython
from java.lang import System # @UnresolvedImport
env = System.getProperty("os.name").lower()
if env.find('win') != -1:
return 'ISO-8859-1' #mbcs does not work on Jython, so, use a (hopefully) suitable replacement
return 'utf-8'
except:
pass
#Only available from 2.3 onwards.
if sys.platform == 'win32':
return 'mbcs'
return 'utf-8'
def getfilesystemencoding():
try:
ret = __getfilesystemencoding()
#Check if the encoding is actually there to be used!
if hasattr('', 'encode'):
''.encode(ret)
if hasattr('', 'decode'):
''.decode(ret)
return ret
except:
return 'utf-8'
| def __getfilesystemencoding():
'''
Note: there's a copy of this method in interpreterInfo.py
'''
import sys
try:
ret = sys.getfilesystemencoding()
if not ret:
raise RuntimeError('Unable to get encoding.')
return ret
except:
try:
#Handle Jython
from java.lang import System # @UnresolvedImport
env = System.getProperty("os.name").lower()
if env.find('win') != -1:
return 'ISO-8859-1' #mbcs does not work on Jython, so, use a (hopefully) suitable replacement
return 'utf-8'
except:
pass
#Only available from 2.3 onwards.
if sys.platform == 'win32':
return 'mbcs'
return 'utf-8'
def getfilesystemencoding():
try:
ret = __getfilesystemencoding()
#Check if the encoding is actually there to be used!
if hasattr('', 'encode'):
''.encode(ret)
if hasattr('', 'decode'):
''.decode(ret)
return ret
except:
return 'utf-8'
|
Add constituent lookup tab, shorten tab labels | import React from 'react';
import Relay from 'react-relay';
import {Styles} from 'material-ui';
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider';
import TopNav from './TopNav';
import {BernieTheme} from './styles/bernie-theme';
import {BernieColors} from './styles/bernie-css';
class AdminDashboard extends React.Component {
tabs = [
{
value: '/admin/call-assignments',
label: 'Calls'
},
{
value: '/admin/constituent-lookup',
label: 'People'
},
{
value: '/admin/events',
label: 'Events'
}
];
render() {
return (
<MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}>
<div>
<TopNav
barColor={BernieColors.blue}
tabColor={BernieColors.lightBlue}
selectedTabColor={Styles.Colors.white}
title="Ground Control Admin"
logoColors={{
primary: Styles.Colors.white,
swoosh: BernieColors.gray
}}
tabs={this.tabs}
history={this.props.history}
location={this.props.location}
/>
{this.props.children}
</div>
</MuiThemeProvider>
)
}
}
// We only do this to auth protect this component. Otherwise it is unnecessary.
export default Relay.createContainer(AdminDashboard, {
fragments: {
listContainer: () => Relay.QL`
fragment on ListContainer {
id
}
`
}
}) | import React from 'react';
import Relay from 'react-relay';
import {Styles} from 'material-ui';
import MuiThemeProvider from 'material-ui/lib/MuiThemeProvider';
import TopNav from './TopNav';
import {BernieTheme} from './styles/bernie-theme';
import {BernieColors} from './styles/bernie-css';
class AdminDashboard extends React.Component {
tabs = [
{
value: '/admin/call-assignments',
label: 'Call Assignments'
},
{
value: '/admin/events',
label: 'Events'
}
];
render() {
return (
<MuiThemeProvider muiTheme={Styles.getMuiTheme(BernieTheme)}>
<div>
<TopNav
barColor={BernieColors.blue}
tabColor={BernieColors.lightBlue}
selectedTabColor={Styles.Colors.white}
title="Ground Control Admin"
logoColors={{
primary: Styles.Colors.white,
swoosh: BernieColors.gray
}}
tabs={this.tabs}
history={this.props.history}
location={this.props.location}
/>
{this.props.children}
</div>
</MuiThemeProvider>
)
}
}
// We only do this to auth protect this component. Otherwise it is unnecessary.
export default Relay.createContainer(AdminDashboard, {
fragments: {
listContainer: () => Relay.QL`
fragment on ListContainer {
id
}
`
}
}) |
Make initial scene fadein slower. | define(function(require){
var TimeLine = require("timeline");
var renderer = new THREE.WebGLRenderer( {antialias: true, alpha:true} );
renderer.shadowMapEnabled = true;
var scene;
var timeSource;
return {
init:function(){
renderer.autoClear = false;
$(window).resize(resizeViewPort);
document.body.appendChild( renderer.domElement );
$("canvas").hide();
resizeViewPort();
},
setTimeSource: function(argTimeSource){
timeSource = argTimeSource;
},
start: function() {
$("canvas").fadeIn(3000);
function render() {
scene = TimeLine.getScene();
if(!scene){
requestAnimationFrame(render);
return;
}
scene.render(timeSource.getTime());
requestAnimationFrame(render);
renderer.render(scene.scene, scene.camera);
}
render();
},
renderer: renderer
};
function resizeViewPort() {
var width = window.innerWidth;
var height = width * (9 / 16);
var position = (window.innerHeight - height) / 2;
renderer.setSize(width, height);
$("canvas").css("margin-top", position + "px");
}
}); | define(function(require){
var TimeLine = require("timeline");
var renderer = new THREE.WebGLRenderer( {antialias: true, alpha:true} );
renderer.shadowMapEnabled = true;
var scene;
var timeSource;
return {
init:function(){
renderer.autoClear = false;
$(window).resize(resizeViewPort);
document.body.appendChild( renderer.domElement );
$(renderer.domElement).hide();
resizeViewPort();
},
setTimeSource: function(argTimeSource){
timeSource = argTimeSource;
},
start: function() {
$(renderer.domElement).fadeIn(1000);
function render() {
scene = TimeLine.getScene();
if(!scene){
requestAnimationFrame(render);
return;
}
scene.render(timeSource.getTime());
requestAnimationFrame(render);
renderer.render(scene.scene, scene.camera);
}
render();
},
renderer: renderer
};
function resizeViewPort() {
var width = window.innerWidth;
var height = width * (9 / 16);
var position = (window.innerHeight - height) / 2;
renderer.setSize(width, height);
$("canvas").css("margin-top", position + "px");
}
}); |
Use dev env while building for production
This yields better errors. | 'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
'NODE_ENV': 'dev'
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
};
| 'use strict';
var fs = require('fs');
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
var corePath = path.join(parent, 'components');
var common = {
corePath: corePath,
parent: parent,
resolve: {
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'assets': path.join(cwd, 'assets'),
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': corePath
},
extensions: [
'',
'.js',
'.jsx',
'.json'
],
modulesDirectories: [
path.join(cwd, 'node_modules'),
'node_modules'
]
},
resolveLoader: {
modulesDirectories: [
path.join(parent, 'node_modules'),
'node_modules'
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(config.buildDev)),
'process.env': {
'NODE_ENV': JSON.stringify(config.buildDev ? 'dev' : 'production')
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
resolve(merge(common, siteConfig));
});
};
|
Increase service worker cache version | 'use strict';
var CACHE_NAME = 'offline-issues-cache-v2';
var urlsToCache = [
'./',
'css/bootstrap.css',
'css/app.css',
'js/lodash.js',
'js/jquery-2.2.4.js',
'js/bootstrap.js',
'js/github.bundle.min.js',
'js/pouchdb-5.4.5.js',
'js/pouchdb.all-dbs.js',
'js/moment.min.js',
'js/markdown.js',
'js/commentWorker.js',
'js/app.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
return cacheName !== CACHE_NAME;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
})
);
}); | 'use strict';
var CACHE_NAME = 'offline-issues-cache-v1';
var urlsToCache = [
'./',
'css/bootstrap.css',
'css/app.css',
'js/lodash.js',
'js/jquery-2.2.4.js',
'js/bootstrap.js',
'js/github.bundle.min.js',
'js/pouchdb-5.4.5.js',
'js/pouchdb.all-dbs.js',
'js/moment.min.js',
'js/markdown.js',
'js/commentWorker.js',
'js/app.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
return cacheName !== CACHE_NAME;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
})
);
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.