text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Make use of the filter (syntactic sugar) for | angular.module('cheatsheet')
.service('csfUserSettings', [
'$meteorSubscribe', '$meteorObject', '$q', '$timeout', '$rootScope',
function($meteorSubscribe, $meteorObject, $q, $timeout, $rootScope) {
var me = this;
var deferred = $q.defer();
var userSettings = {
instance: null
};
me.UserSettingsPromise = deferred.promise;
subscription = Meteor.subscribe('user-settings');
Tracker.autorun(function() {
if( Meteor.userId() && subscription.ready() ) {
// Wrap the following inside $timeout since it contains reactive sources which should not trigger this autorun
$timeout(function() {
if(userSettings.instance) {
userSettings.instance.stop();
}
$rootScope.$apply(function() {
userSettings.instance = $meteorObject(UserSettings, {userId: Meteor.userId()}, false);
deferred.resolve( userSettings );
});
});
}
});
}
]);
| angular.module('cheatsheet')
.service('csfUserSettings', [
'$meteorSubscribe', '$meteorObject', '$q', '$timeout', '$rootScope',
function($meteorSubscribe, $meteorObject, $q, $timeout, $rootScope) {
var me = this;
var deferred = $q.defer();
var userSettings = {
instance: null
};
me.UserSettingsPromise = deferred.promise;
subscription = Meteor.subscribe('user-settings');
Tracker.autorun(function() {
if( Meteor.userId() && subscription.ready() ) {
var userSettingsId = UserSettings.findOne({userId: Meteor.userId()}, {fields: {_id:true}})._id;
// Wrap the following inside $timeout since it contains reactive sources which should not trigger this autorun
$timeout(function() {
if(userSettings.instance) {
userSettings.instance.stop();
}
$rootScope.$apply(function() {
userSettings.instance = $meteorObject(UserSettings, userSettingsId, false);
deferred.resolve( userSettings );
});
});
}
});
}
]);
|
Add colors to peer graph | package nl.tudelft.ti2306.blockchain;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import nl.tudelft.ti2306.blockchain.datastructure.PeerGraph;
public class PeerGraphToViz implements Runnable {
private PeerGraph graph;
private String output;
public PeerGraphToViz(PeerGraph graph, String output) {
this.graph = graph;
this.output = output;
}
@Override
public void run() {
try (PrintWriter out = new PrintWriter(new File(output))) {
out.println("graph peergraph {");
out.println("ratio=expand;");
out.println("node[width=.40,height=.40, label=\"\"]");
out.println("edge[arrowsize=\"0.3\"]");
for (int i = 0; i < graph.getNodes().size(); i++) {
double hue = i / (double) graph.getNodes().size();
out.println(i + " [label=" + i + " style=filled fillcolor=\"" + hue + " 1.0 1.0\"]");
for (int j = 0; j < graph.getEdges(i).size(); j++) {
int k = graph.getEdges(i).get(j);
if (i > k) continue;
out.println(i + "--" + k + " [color=black]");
}
}
out.println("}");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
| package nl.tudelft.ti2306.blockchain;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import nl.tudelft.ti2306.blockchain.datastructure.PeerGraph;
public class PeerGraphToViz implements Runnable {
private PeerGraph graph;
private String output;
public PeerGraphToViz(PeerGraph graph, String output) {
this.graph = graph;
this.output = output;
}
@Override
public void run() {
try (PrintWriter out = new PrintWriter(new File(output))) {
out.println("graph peergraph {");
out.println("ratio=expand;");
out.println("node[width=.40,height=.40, label=\"\"]");
out.println("edge[arrowsize=\"0.3\"]");
for (int i = 0; i < graph.getNodes().size(); i++) {
out.println(i + " [label=" + i + " style=filled fillcolor=red]");
for (int j = 0; j < graph.getEdges(i).size(); j++) {
int k = graph.getEdges(i).get(j);
if (i > k) continue;
out.println(i + "--" + k + " [color=black]");
}
}
out.println("}");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
|
Exclude ids from filter search | /**
* Client class that talks to bugzilla
*/
const BZ_DOMAIN = "https://bugzilla.mozilla.org";
const REST_BUG = "/rest/bug";
export default {
getBugs: function(bugIds) {
if (!Array.isArray(bugIds)) {
bugIds = [bugIds];
}
let url = BZ_DOMAIN + REST_BUG + "?id=" + bugIds.join(",");
return this._fetchFromUrl(url);
},
searchBugs: function(filter, excludeIds) {
if(!filter) {
return Promise.resolve([]);
}
if (!Array.isArray(excludeIds)) {
excludeIds = [excludeIds];
}
let url = BZ_DOMAIN + REST_BUG + "?quicksearch=" + encodeURIComponent(filter)
+ "&bug_id=" + excludeIds.join(",") + "&bug_id_type=nowords";
return this._fetchFromUrl(url);
},
_fetchFromUrl: function(url) {
return new Promise(function(resolve, reject) {
let req = new XMLHttpRequest();
req.open('GET', url);
req.setRequestHeader("Content-type", "application/json");
req.setRequestHeader("Accept", "application/json");
req.onload = function() {
if (req.status == 200) {
try {
resolve(JSON.parse(req.response).bugs);
} catch (e) {
console.log("Failed to parse the request bugs");
reject(Error(e));
}
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
}
| /**
* Client class that talks to bugzilla
*/
const BZ_DOMAIN = "https://bugzilla.mozilla.org";
const REST_BUG = "/rest/bug";
export default {
getBugs: function(bugIds) {
if (!Array.isArray(bugIds)) {
bugIds = [bugIds];
}
let url = BZ_DOMAIN + REST_BUG + "?id=" + bugIds.join(",");
return this._fetchFromUrl(url);
},
searchBugs: function(filter) {
if(!filter) {
return Promise.resolve([]);
}
return this._fetchFromUrl(this._filterToUrl(filter));
},
_filterToUrl: function (filter) {
return BZ_DOMAIN + REST_BUG + "?quicksearch=" + encodeURIComponent(filter);
},
_fetchFromUrl: function(url) {
return new Promise(function(resolve, reject) {
let req = new XMLHttpRequest();
req.open('GET', url);
req.setRequestHeader("Content-type", "application/json");
req.setRequestHeader("Accept", "application/json");
req.onload = function() {
if (req.status == 200) {
try {
resolve(JSON.parse(req.response).bugs);
} catch (e) {
console.log("Failed to parse the request bugs");
reject(Error(e));
}
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
}
|
Fix bug when modifying the startFrame of a layer
Two events were sent to the server at once, which triggered a double
simultaneous write of layers.json.
This mostly resulted in the endFrame update overwriting the startFrame
update, and sometimes even an extra `]` at the end of the file for some
mysterious reason. | 'use strict';
angular.module('nin')
.controller('BottomCtrl', function ($scope, $interval, socket) {
var linesContainer = null;
$scope.onBottomScroll = function(event) {
linesContainer = event.target;
$scope.bottomScrollOffset = event.target.scrollLeft;
};
$scope.musicLayerClick = function($event) {
$scope.demo.jumpToFrame($event.offsetX);
};
$scope.layerLabelClick = function(layer) {
$scope.$parent.$parent.inspectedLayer = $scope.inspectedLayer == layer
? null
: layer;
};
$scope.dragResizeLayer = function(event, ui, layer) {
if (ui.position.left != layer.startFrame) {
socket.sendEvent('set', {
id: layer.position,
field: 'startFrame',
value: ui.position.left
});
} else {
socket.sendEvent('set', {
id: layer.position,
field: 'endFrame',
value: ui.position.left + ui.size.width
});
}
};
$interval(function(){
$scope.hideMarker = false;
if(!linesContainer) {
return;
}
if(linesContainer.scrollLeft > $scope.currentFrame ||
$scope.currentFrame >= linesContainer.scrollLeft + $(linesContainer).width()) {
$scope.hideMarker = true;
} else {
$scope.hideMarker = false;
}
}, 1000 / 60);
});
| 'use strict';
angular.module('nin')
.controller('BottomCtrl', function ($scope, $interval, socket) {
var linesContainer = null;
$scope.onBottomScroll = function(event) {
linesContainer = event.target;
$scope.bottomScrollOffset = event.target.scrollLeft;
};
$scope.musicLayerClick = function($event) {
$scope.demo.jumpToFrame($event.offsetX);
};
$scope.layerLabelClick = function(layer) {
$scope.$parent.$parent.inspectedLayer = $scope.inspectedLayer == layer
? null
: layer;
};
$scope.dragResizeLayer = function(event, ui, layer) {
console.log(event, ui, layer);
socket.sendEvent('set', {
id: layer.position,
field: 'startFrame',
value: ui.position.left
});
socket.sendEvent('set', {
id: layer.position,
field: 'endFrame',
value: ui.position.left + ui.size.width
});
};
$interval(function(){
$scope.hideMarker = false;
if(!linesContainer) {
return;
}
if(linesContainer.scrollLeft > $scope.currentFrame ||
$scope.currentFrame >= linesContainer.scrollLeft + $(linesContainer).width()) {
$scope.hideMarker = true;
} else {
$scope.hideMarker = false;
}
}, 1000 / 60);
});
|
Add active class to current breadcrumb | <?php namespace Coreplex\Crumbs\Renderers;
use Coreplex\Crumbs\Contracts\Renderer as Contract;
use Coreplex\Crumbs\Contracts\Container;
class Basic implements Contract {
/**
* Render the breadcrumbs from the container
*
* @return string
*/
public function render(Container $container)
{
$rendered = '';
if ($container->count() > 0) {
$rendered .= '<ul>';
foreach ($container->getCrumbs() as $crumb) {
$rendered .= $crumb->isCurrent() ? '<li class="active">' : '<li>';
if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
$rendered .= '<a href="' . $crumb->getUrl() . '">';
}
$rendered .= $crumb->hasLabel() ? $crumb->getLabel() : $crumb->getUrl();
if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
$rendered .= '</a>';
}
$rendered .= '</li>';
}
$rendered .= '</ul>';
}
return $rendered;
}
} | <?php namespace Coreplex\Crumbs\Renderers;
use Coreplex\Crumbs\Contracts\Renderer as Contract;
use Coreplex\Crumbs\Contracts\Container;
class Basic implements Contract {
/**
* Render the breadcrumbs from the container
*
* @return string
*/
public function render(Container $container)
{
$rendered = '';
if ($container->count() > 0) {
$rendered .= '<ul>';
foreach ($container->getCrumbs() as $crumb) {
$rendered .= '<li>';
if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
$rendered .= '<a href="' . $crumb->getUrl() . '">';
}
$rendered .= $crumb->hasLabel() ? $crumb->getLabel() : $crumb->getUrl();
if ( ! $crumb->isCurrent() && $crumb->hasUrl()) {
$rendered .= '</a>';
}
$rendered .= '</li>';
}
$rendered .= '</ul>';
}
return $rendered;
}
} |
Increase python compatibility version and bump to v1.2.0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
long_description = """
Django URL routing system DRYed.
"""
requirements = [
'django>=1.9',
'six',
]
test_requirements = [
'mock',
'coveralls'
]
setup(
name='urljects',
version='1.10.4',
description="Django URLS DRYed.",
long_description=long_description,
author="Visgean Skeloru",
author_email='[email protected]',
url='https://github.com/visgean/urljects',
packages=[
'urljects',
],
package_dir={'urljects': 'urljects'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='urljects',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
long_description = """
Django URL routing system DRYed.
"""
requirements = [
'django>=1.8',
'six',
]
test_requirements = [
'mock',
'coveralls'
]
setup(
name='urljects',
version='1.10.4',
description="Django URLS DRYed.",
long_description=long_description,
author="Visgean Skeloru",
author_email='[email protected]',
url='https://github.com/visgean/urljects',
packages=[
'urljects',
],
package_dir={'urljects': 'urljects'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='urljects',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=test_requirements
)
|
Remove --ip=* from ipcontroller command | """
IPython.parallel utilities.
"""
import os
import subprocess
import time
import uuid
class LocalCluster(object):
"""
Start an IPython.parallel cluster on localhost.
Parameters
----------
n_engines : int
Number of engines to initialize.
"""
def __init__(self, n_engines):
self.n_engines = n_engines
# placeholders
self.cluster_id = None
self.controller = None
self.engines = []
self.output = None
# initialize the cluster
self.start()
def __del__(self):
"""
Shut down the cluster.
"""
self.stop()
def start(self):
"""
Start the cluster by running ipcontroller and ipengine.
"""
self.cluster_id = uuid.uuid4()
output = open(os.devnull)
self.controller = subprocess.Popen(
['ipcontroller', '--cluster-id={}'.format(self.cluster_id),
'--log-level=ERROR'])
time.sleep(1) # wait for controller to initialize
for i in xrange(self.n_engines):
engine = subprocess.Popen(
['ipengine', '--cluster-id={}'.format(self.cluster_id),
'--log-level=ERROR'])
self.engines.append(engine)
self.output = output
time.sleep(10) # wait for engines to initialize
def stop(self):
"""
Shut down the cluster.
"""
for engine in self.engines:
engine.terminate()
self.controller.terminate()
self.output.close()
| """
IPython.parallel utilities.
"""
import os
import subprocess
import time
import uuid
class LocalCluster(object):
"""
Start an IPython.parallel cluster on localhost.
Parameters
----------
n_engines : int
Number of engines to initialize.
"""
def __init__(self, n_engines):
self.n_engines = n_engines
# placeholders
self.cluster_id = None
self.controller = None
self.engines = []
self.output = None
# initialize the cluster
self.start()
def __del__(self):
"""
Shut down the cluster.
"""
self.stop()
def start(self):
"""
Start the cluster by running ipcontroller and ipengine.
"""
self.cluster_id = uuid.uuid4()
output = open(os.devnull)
self.controller = subprocess.Popen(
['ipcontroller', '--ip=*',
'--cluster-id={}'.format(self.cluster_id),
'--log-level=ERROR'])
time.sleep(1) # wait for controller to initialize
for i in xrange(self.n_engines):
engine = subprocess.Popen(
['ipengine', '--cluster-id={}'.format(self.cluster_id),
'--log-level=ERROR'])
self.engines.append(engine)
self.output = output
time.sleep(10) # wait for engines to initialize
def stop(self):
"""
Shut down the cluster.
"""
for engine in self.engines:
engine.terminate()
self.controller.terminate()
self.output.close()
|
Fix relative animation of list values | from kivy.animation import Animation
class RelativeAnimation(Animation):
"""Class that extends the Kivy Animation base class to add relative animation
property target values that are calculated when the animation starts."""
def _initialize(self, widget):
"""Initializes the animation and calculates the property target value
based on the current value plus the desired delta.
Notes: Do not call the base class _initialize method as this override
completely replaces the base class method."""
d = self._widgets[widget.uid] = {
'widget': widget,
'properties': {},
'time': None}
# get current values and calculate target values
p = d['properties']
for key, value in self._animated_properties.items():
original_value = getattr(widget, key)
if isinstance(original_value, (tuple, list)):
original_value = original_value[:]
target_value = [x + y for x, y in zip(original_value, value)]
elif isinstance(original_value, dict):
original_value = original_value.copy()
target_value = value
else:
target_value = original_value + value
p[key] = (original_value, target_value)
# install clock
self._clock_install()
| from kivy.animation import Animation
class RelativeAnimation(Animation):
"""Class that extends the Kivy Animation base class to add relative animation
property target values that are calculated when the animation starts."""
def _initialize(self, widget):
"""Initializes the animation and calculates the property target value
based on the current value plus the desired delta.
Notes: Do not call the base class _initialize method as this override
completely replaces the base class method."""
d = self._widgets[widget.uid] = {
'widget': widget,
'properties': {},
'time': None}
# get current values and calculate target values
p = d['properties']
for key, value in self._animated_properties.items():
original_value = getattr(widget, key)
if isinstance(original_value, (tuple, list)):
original_value = original_value[:]
target_value = map(lambda x, y: x + y, original_value, value)
elif isinstance(original_value, dict):
original_value = original_value.copy()
target_value = value
else:
target_value = original_value + value
p[key] = (original_value, target_value)
# install clock
self._clock_install()
|
Fix tests on Python 2 | # -*- coding: utf-8; -*-
import re
from jenkins_autojobs import main
def test_filter_jobs():
class Job:
def __init__(self, name):
self.name = name
class jenkins:
@staticmethod
def view_jobs(x):
return {
'v1': [Job('scratch-one'), Job('scratch-two')],
'v2': [Job('release-one'), Job('maintenance-three')]
}[x]
names = ['feature-one', 'feature-two', 'release-one', 'release-two']
jenkins.jobs = [Job(i) for i in names]
filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)}
#-------------------------------------------------------------------------
assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'}
res = filter_jobs(by_name_regex=[re.compile('feature-')])
assert res == {'feature-one', 'feature-two'}
res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')])
assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'}
#-------------------------------------------------------------------------
res = filter_jobs(by_views=['v1'])
assert res == {'scratch-one', 'scratch-two'}
res = filter_jobs(by_views=['v1', 'v2'])
assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'}
| # -*- coding: utf-8; -*-
import re
from jenkins_autojobs import main
def test_filter_jobs():
class Job:
def __init__(self, name):
self.name = name
class jenkins:
pass
names = ['feature-one', 'feature-two', 'release-one', 'release-two']
jenkins.jobs = [Job(i) for i in names]
filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)}
#-------------------------------------------------------------------------
assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'}
res = filter_jobs(by_name_regex=[re.compile('feature-')])
assert res == {'feature-one', 'feature-two'}
res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')])
assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'}
#-------------------------------------------------------------------------
view_jobs = {
'v1': [Job('scratch-one'), Job('scratch-two')],
'v2': [Job('release-one'), Job('maintenance-three')]
}
jenkins.view_jobs = lambda x: view_jobs[x]
res = filter_jobs(by_views=['v1'])
assert res == {'scratch-one', 'scratch-two'}
res = filter_jobs(by_views=['v1', 'v2'])
assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'}
|
Add $query to log output on caught graphql request errors | <?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a GraphQL query using the client and return the data result.
*
* @param $query String
* @param $variables Array
* @return array|null
*/
public function query($query, $variables)
{
// Use try/catch to avoid any GraphQL related errors breaking the application.
try {
$response = $this->client->query($query, $variables);
} catch (\Exception $exception) {
Log::error(
'GraphQL request failed. Query: '.$query
.' Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
);
return null;
}
return $response ? $response->getData() : null;
}
/**
* Query for a CampaignWebsite by campaignId field.
*
* @param $campaignId String
* @return array|null
*/
public function getCampaignWebsiteByCampaignId($campaignId)
{
$query = '
query GetCampaignWebsiteByCampaignId($campaignId: String!) {
campaignWebsiteByCampaignId(campaignId: $campaignId) {
title
slug
}
}';
$variables = [
'campaignId' => $campaignId,
];
return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
}
}
| <?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a GraphQL query using the client and return the data result.
*
* @param $query String
* @param $variables Array
* @return array|null
*/
public function query($query, $variables)
{
// Use try/catch to avoid any GraphQL related errors breaking the application.
try {
$response = $this->client->query($query, $variables);
} catch (\Exception $exception) {
Log::error(
'GraphQL request failed. Variables: '.json_encode($variables).' Exception: '.$exception->getMessage()
);
return null;
}
return $response ? $response->getData() : null;
}
/**
* Query for a CampaignWebsite by campaignId field.
*
* @param $campaignId String
* @return array|null
*/
public function getCampaignWebsiteByCampaignId($campaignId)
{
$query = '
query GetCampaignWebsiteByCampaignId($campaignId: String!) {
campaignWebsiteByCampaignId(campaignId: $campaignId) {
title
slug
}
}';
$variables = [
'campaignId' => $campaignId,
];
return $this->query($query, $variables, 'campaignWebsiteByCampaignId');
}
}
|
Add a default date format | <?php
$db_core = require(__DIR__ . '/db_core.php');
$db_bank = require(__DIR__ . '/db_bank.php');
$db_openerp = require(__DIR__ . '/db_openerp.php');
Yii::setAlias('@base', dirname(dirname(__DIR__)));
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'extensions' => require(__DIR__ . '/../../vendor/yiisoft/extensions.php'),
'language' => 'fi',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'db_core' => $db_core,
'db_bank' => $db_bank,
'db' => $db_openerp,
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => true,
],
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@base/messages',
'sourceLanguage' => 'en',
],
],
],
'formatter' => [
'dateFormat' => 'd.m.Y',
]
],
];
| <?php
$db_core = require(__DIR__ . '/db_core.php');
$db_bank = require(__DIR__ . '/db_bank.php');
$db_openerp = require(__DIR__ . '/db_openerp.php');
Yii::setAlias('@base', dirname(dirname(__DIR__)));
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'extensions' => require(__DIR__ . '/../../vendor/yiisoft/extensions.php'),
'language' => 'fi',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'db_core' => $db_core,
'db_bank' => $db_bank,
'db' => $db_openerp,
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => true,
],
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@base/messages',
'sourceLanguage' => 'en',
],
],
],
],
];
|
Use normal link for download
Or the frontend will shortcut and not find it | // @flow
import { List, ListItem } from "material-ui/List";
import Subheader from "material-ui/Subheader";
import * as React from "react";
import { createFragmentContainer, graphql } from "react-relay";
import GroupscoreListGroupscore from "./__generated__/GroupscoreList_groupscore.graphql";
type Props = {
groupscore: GroupscoreListGroupscore,
};
class GroupscoreList extends React.Component<Props> {
render() {
const { groupscore } = this.props;
return (
<List>
<Subheader>{groupscore.name}</Subheader>
{groupscore.files.edges.map((edge) => {
const file = edge.node;
return (
<ListItem
disabled
primaryText={
<a download href={file.path}>
{file.filename}
</a>
}
/>
);
})}
</List>
);
}
}
export default createFragmentContainer(GroupscoreList, {
groupscore: graphql`
fragment GroupscoreList_groupscore on Groupscore {
id
name
files {
edges {
node {
id
filename
path
}
}
}
}
`,
});
| // @flow
import Link from "found/lib/Link";
import { List, ListItem } from "material-ui/List";
import Subheader from "material-ui/Subheader";
import * as React from "react";
import { createFragmentContainer, graphql } from "react-relay";
import GroupscoreListGroupscore from "./__generated__/GroupscoreList_groupscore.graphql";
type Props = {
groupscore: GroupscoreListGroupscore,
};
class GroupscoreList extends React.Component<Props> {
render() {
const { groupscore } = this.props;
return (
<List>
<Subheader>{groupscore.name}</Subheader>
{groupscore.files.edges.map((edge) => {
const file = edge.node;
return (
<ListItem
disabled
primaryText={<Link to={file.path}>{file.filename}</Link>}
/>
);
})}
</List>
);
}
}
export default createFragmentContainer(GroupscoreList, {
groupscore: graphql`
fragment GroupscoreList_groupscore on Groupscore {
id
name
files {
edges {
node {
id
filename
path
}
}
}
}
`,
});
|
Add BitBar metadata, working app | #!/usr/bin/env /usr/local/bin/node
const bitbar = require('bitbar');
const request = require('superagent');
const moment = require('moment');
var busStop = 18610;
var busAPIKey = 'TEST';
var busAPI = `http://api.pugetsound.onebusaway.org/api/where/arrivals-and-departures-for-stop/1_${busStop}.json?key=${busAPIKey}`;
var busInfo = {};
request
.get(busAPI)
.end(function(err, res) {
var response = JSON.parse(res.text);
bitbar([
{
color: bitbar.darkMode ? 'white' : 'red',
dropdown: false
},
bitbar.sep,
{
text: 'Unicorns',
color: '#ff79d7',
submenu: [
{
text: ':tv: Video',
href: 'https://www.youtube.com/watch?v=9auOCbH5Ns4'
},
{
text: ':book: Wiki',
href: 'https://en.wikipedia.org/wiki/Unicorn'
}
]
},
bitbar.sep,
'Ponies'
]);
}); | #!/usr/bin/env /usr/local/bin/node
const bitbar = require('bitbar');
const request = require('superagent');
const moment = require('moment');
var busStop = 18610;
var busAPIKey = 'TEST';
var busAPI = `http://api.pugetsound.onebusaway.org/api/where/arrivals-and-departures-for-stop/1_${busStop}.json?key=${busAPIKey}`;
var busInfo = {};
request
.get(busAPI)
.end(function(err, res) {
var response = JSON.parse(res.text);
console.log(response);
var currentTime = response.currentTime;
bitbar([
{
text: currentTime,
color: bitbar.darkMode ? 'white' : 'red',
dropdown: false
},
bitbar.sep,
{
text: 'Unicorns',
color: '#ff79d7',
submenu: [
{
text: ':tv: Video',
href: 'https://www.youtube.com/watch?v=9auOCbH5Ns4'
},
{
text: ':book: Wiki',
href: 'https://en.wikipedia.org/wiki/Unicorn'
}
]
},
bitbar.sep,
'Ponies'
]);
}); |
Support facets in the url that don't exist yet
For example, the page first loads with a domain=Vivaldi facet
in the URL. But there is no such domain, because domains are
not loaded for another .1 second. So the facet is in the URL
but not the search bar. With this fix, when domains are
loaded and the facet JSON is updated, the code that
regenerates the facets also rereads from the URL.
This is a revision of my little hack in bootstrap_magic_search.js
to handle options coming in late. It actually feels less
like a hack now, and more like something you might want
to pull in and use. | angular.module('MagicSearch', ['ui.bootstrap'])
.directive('magicOverrides', function() {
return {
restrict: 'A',
controller: function($scope) {
// showMenu and hideMenu depend on foundation's dropdown. They need
// to be modified to work with another dropdown implemenation.
// For bootstrap, they are not needed at all.
$scope.showMenu = function() {
$scope.isMenuOpen = true;
};
$scope.hideMenu = function() {
$scope.isMenuOpen = false;
};
$scope.isMenuOpen = false;
// remove the following when magic_search.js handles changing the facets/options
$scope.$watch('facets_json', function(newVal, oldVal) {
if (newVal === oldVal) {
return;
}
$scope.currentSearch = [];
$scope.initSearch();
});
}
};
}); | angular.module('MagicSearch', ['ui.bootstrap'])
.directive('magicOverrides', function() {
return {
restrict: 'A',
controller: function($scope) {
// showMenu and hideMenu depend on foundation's dropdown. They need
// to be modified to work with another dropdown implemenation.
// For bootstrap, they are not needed at all.
$scope.showMenu = function() {
$scope.isMenuOpen = true;
};
$scope.hideMenu = function() {
$scope.isMenuOpen = false;
};
$scope.isMenuOpen = false;
// remove the following when magic_search.js handles changing the facets/options
$scope.$watch('facets_json', function(newVal, oldVal) {
if (newVal === oldVal) {
return;
}
$scope.facetsJson = $scope.facets_json.replace(/__apos__/g, "\'").replace(/__dquote__/g, '\\"').replace(/__bslash__/g, "\\");
$scope.facetsObj = JSON.parse($scope.facetsJson);
$scope.resetState();
});
}
};
}); |
Rename create_dirs method to makedirs in line with os.path method | # -*- coding: utf-8 -*-
"""
file: model_files.py
Graph model classes for working with files
"""
import os
import logging
from lie_graph.graph_mixin import NodeEdgeToolsBaseClass
class FilePath(NodeEdgeToolsBaseClass):
@property
def exists(self):
path = self.get()
if path:
return os.path.exists(path)
return False
@property
def iswritable(self):
return os.access(self.get(), os.W_OK)
def set(self, key, value=None, absolute=True):
if key == self.node_value_tag and absolute:
value = os.path.abspath(value)
self.nodes[self.nid][key] = value
def makedirs(self):
"""
Recursively create the directory structure of the path
:return: Absolute path to working directory
:rtype: :py:str
"""
path = self.get()
if self.exists and self.iswritable:
logging.info('Directory exists and writable: {0}'.format(path))
return path
try:
os.makedirs(path, 0755)
except Exception:
logging.error('Unable to create project directory: {0}'.format(path))
return path
| # -*- coding: utf-8 -*-
"""
file: model_files.py
Graph model classes for working with files
"""
import os
import logging
from lie_graph.graph_mixin import NodeEdgeToolsBaseClass
class FilePath(NodeEdgeToolsBaseClass):
@property
def exists(self):
path = self.get()
if path:
return os.path.exists(path)
return False
@property
def iswritable(self):
return os.access(self.get(), os.W_OK)
def set(self, key, value=None, absolute=True):
if key == self.node_value_tag and absolute:
value = os.path.abspath(value)
self.nodes[self.nid][key] = value
def create_dirs(self):
"""
Create directories of the stored path
:return: Absolute path to working directory
:rtype: :py:str
"""
path = self.get()
if self.exists and self.iswritable:
logging.info('Directory exists and writable: {0}'.format(path))
return path
try:
os.makedirs(path, 0755)
except Exception:
logging.error('Unable to create project directory: {0}'.format(path))
return path
|
Remove old data retrieval, replace error condition | (function(env) {
env.ddg_spice_meta_cpan = function(api_result) {
"use strict";
if ( !api_result || api_result.hits.hits.length < 1 ) {
return DDH.failed('meta_cpan');
}
Spice.add({
id: "meta_cpan",
name: "Software",
data: {
title: module_name,
subtitle: api_result.abstract,
record_data: api_result,
record_keys: ['author','version','description']
},
meta: {
sourceName: "MetaCPAN",
sourceUrl: 'https://metacpan.org/' + link
},
templates: {
group: 'list',
options: {
content: 'record',
moreAt: true
}
}
});
};
}(this));
| (function(env) {
env.ddg_spice_meta_cpan = function(api_result) {
"use strict";
if (!(api_result && api_result.author && api_result.version)) {
return Spice.failed('meta_cpan');
}
var script = $('[src*="/js/spice/meta_cpan/"]')[0],
source = $(script).attr("src"),
query = decodeURIComponent(source.match(/meta_cpan\/([^\/]+)/)[1]),
link = "search?q=" + encodeURIComponent(query),
module_name = api_result.name;
if (api_result.module && api_result.module.length > 0) {
module_name = api_result.module[0].name;
if (api_result.module[0].associated_pod) {
link = "module/" + api_result.module[0].associated_pod;
}
}
Spice.add({
id: "meta_cpan",
name: "Software",
data: {
title: module_name,
subtitle: api_result.abstract,
record_data: api_result,
record_keys: ['author','version','description']
},
meta: {
sourceName: "MetaCPAN",
sourceUrl: 'https://metacpan.org/' + link
},
templates: {
group: 'list',
options: {
content: 'record',
moreAt: true
}
}
});
};
}(this));
|
Move token handling from tag function to CSSAssetTagNode | from __future__ import absolute_import
from django.template import Node, Library, TemplateSyntaxError
from gears.assets import build_asset
from ..settings import environment, GEARS_URL, GEARS_DEBUG
register = Library()
class CSSAssetTagNode(Node):
template = u'<link rel="stylesheet" href="%s%%s">' % GEARS_URL
def __init__(self, logical_path, debug):
self.logical_path = logical_path
self.debug = debug
@classmethod
def handle_token(cls, parser, token):
bits = token.split_contents()
if len(bits) not in (2, 3):
msg = '%r tag takes one argument: the logical path to the public asset'
raise TemplateSyntaxError(msg % bits[0])
debug = (len(bits) == 3)
if debug and bits[2] != 'debug':
msg = "Second (optional) argument to %r tag must be 'debug'"
raise TemplateSyntaxError(msg % bits[0])
logical_path = parser.compile_filter(bits[1])
return cls(logical_path, debug)
def render(self, context):
logical_path = self.logical_path.resolve(context)
if self.debug or GEARS_DEBUG:
asset = build_asset(environment, logical_path)
paths = (('%s?body=1' % r.attributes.logical_path) for r in asset.requirements)
else:
paths = (logical_path,)
return '\n'.join((self.template % path) for path in paths)
@register.tag
def css_asset_tag(parser, token):
return CSSAssetTagNode.handle_token(parser, token)
| from __future__ import absolute_import
from django.template import Node, Library, TemplateSyntaxError
from gears.assets import build_asset
from ..settings import environment, GEARS_URL, GEARS_DEBUG
register = Library()
class CSSAssetTagNode(Node):
template = u'<link rel="stylesheet" href="%s%%s">' % GEARS_URL
def __init__(self, logical_path, debug):
self.logical_path = logical_path
self.debug = debug
def render(self, context):
logical_path = self.logical_path.resolve(context)
if self.debug or GEARS_DEBUG:
asset = build_asset(environment, logical_path)
paths = (('%s?body=1' % r.attributes.logical_path) for r in asset.requirements)
else:
paths = (logical_path,)
return '\n'.join((self.template % path) for path in paths)
@register.tag
def css_asset_tag(parser, token):
bits = token.split_contents()
if len(bits) not in (2, 3):
raise TemplateSyntaxError("'css_asset_tag' tag takes one argument:"
" the logical path to the public asset")
debug = (len(bits) == 3)
if debug and bits[2] != 'debug':
raise TemplateSyntaxError("Second (optional) argument to"
" 'css_asset_tag' tag must be 'debug'")
logical_path = parser.compile_filter(bits[1])
return CSSAssetTagNode(logical_path, debug)
|
Make wand plugin cleanup after itself.
If you disabled the wand plugin, the currently outlined element would
stay outlined. This change fixes that. | /**
* Allows users to see what screen readers would see.
*/
let $ = require("jquery");
let Plugin = require("../base");
require("./style.less");
class A11yTextWand extends Plugin {
getTitle() {
return "Screen Reader Wand";
}
getDescription() {
return "Hover over elements to view them as a screen reader would";
}
run() {
// HACK(jordan): We provide a fake summary to force the info panel to
// render.
this.summary(" ");
this.panel.render();
$(document).on("mousemove.wand", function(e) {
let element = document.elementFromPoint(e.clientX, e.clientY);
let textAlternative = $.axs.properties.findTextAlternatives(
element, {});
$(".tota11y-outlined").removeClass("tota11y-outlined");
$(element).addClass("tota11y-outlined");
if (!textAlternative) {
$(".tota11y-info-section.active").html(
<i className="tota11y-nothingness">
No text visible to a screen reader
</i>
);
} else {
$(".tota11y-info-section.active").text(textAlternative);
}
});
}
cleanup() {
$(".tota11y-outlined").removeClass("tota11y-outlined");
$(document).off("mousemove.wand");
}
}
module.exports = A11yTextWand;
| /**
* Allows users to see what screen readers would see.
*/
let $ = require("jquery");
let Plugin = require("../base");
require("./style.less");
class A11yTextWand extends Plugin {
getTitle() {
return "Screen Reader Wand";
}
getDescription() {
return "Hover over elements to view them as a screen reader would";
}
run() {
// HACK(jordan): We provide a fake summary to force the info panel to
// render.
this.summary(" ");
this.panel.render();
$(document).on("mousemove.wand", function(e) {
let element = document.elementFromPoint(e.clientX, e.clientY);
let textAlternative = $.axs.properties.findTextAlternatives(
element, {});
$(".tota11y-outlined").removeClass("tota11y-outlined");
$(element).addClass("tota11y-outlined");
if (!textAlternative) {
$(".tota11y-info-section.active").html(
<i className="tota11y-nothingness">
No text visible to a screen reader
</i>
);
} else {
$(".tota11y-info-section.active").text(textAlternative);
}
});
}
cleanup() {
$(document).off("mousemove.wand");
}
}
module.exports = A11yTextWand;
|
Remove custom icon and name, this should be set from slack webhook configuration page | <?php
namespace MathieuImbert\Slack\Logger;
class SlackRequest
{
private $webhookUrl;
/**
* SlackRequest constructor.
* @param string $webhookUrl
*/
public function __construct($webhookUrl)
{
$this->webhookUrl = $webhookUrl;
}
public function post($text)
{
/*
switch ($level) {
case 'success':
case 'good':
$color = 'good';
break;
case 'warning':
$color = 'warning';
break;
case 'error':
case 'danger':
case 'critical':
$color = 'danger';
break;
case 'info':
$color = '#3aa3e3';
break;
default:
$color = "#cccccc";
}
*/
$payload = [
"text" => $text
];
$client = new \GuzzleHttp\Client();
$client->post($this->webhookUrl, ['json' => $payload]);
}
} | <?php
namespace MathieuImbert\Slack\Logger;
class SlackRequest
{
private $webhookUrl;
/**
* SlackRequest constructor.
* @param string $webhookUrl
*/
public function __construct($webhookUrl)
{
$this->webhookUrl = $webhookUrl;
}
public function post($text)
{
/*
switch ($level) {
case 'success':
case 'good':
$color = 'good';
break;
case 'warning':
$color = 'warning';
break;
case 'error':
case 'danger':
case 'critical':
$color = 'danger';
break;
case 'info':
$color = '#3aa3e3';
break;
default:
$color = "#cccccc";
}
*/
$payload = [
"username" => "Flow Bot",
"icon_emoji" => ":robot_face:",
"text" => $text
];
$client = new \GuzzleHttp\Client();
$client->post($this->webhookUrl, ['json' => $payload]);
}
} |
Rename method name (stop -> pause) | /*global MusicPlayer, Vue */
(function (global, undefined) {
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var musicPlayer = new MusicPlayer();
var hasSource = false;
var isPlay = false;
new Vue({
el: '#app',
data: {
names: [],
sources: []
},
methods: {
loadMusic: function (event) {
var that = this;
var files = event.target.files;
[].forEach.call(files, function (file) {
musicPlayer.loadMusic(file, function (src) {
return that.$data.sources.push(src);
});
if (!musicPlayer.isMusicFile) {
return;
}
that.$data.names.push(file.name);
});
},
toggle: function (event) {
var elm = event.currentTarget;
var index = this.$data.names.indexOf(elm.textContent);
var audioElms = document.getElementsByTagName('audio'),
audioE = audioElms[index];
if (!hasSource) {
musicPlayer.createSource(audioE);
hasSource = true;
}
if (!isPlay) {
musicPlayer.play(audioE);
isPlay = true;
return;
}
musicPlayer.pause(audioE);
isPlay = false;
}
}
});
}, false);
})(this.self, void 0);
| /*global MusicPlayer, Vue */
(function (global, undefined) {
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var musicPlayer = new MusicPlayer();
var hasSource = false;
var isPlay = false;
new Vue({
el: '#app',
data: {
names: [],
sources: []
},
methods: {
loadMusic: function (event) {
var that = this;
var files = event.target.files;
[].forEach.call(files, function (file) {
musicPlayer.loadMusic(file, function (src) {
return that.$data.sources.push(src);
});
if (!musicPlayer.isMusicFile) {
return;
}
that.$data.names.push(file.name);
});
},
toggle: function (event) {
var elm = event.currentTarget;
var index = this.$data.names.indexOf(elm.textContent);
var audioElms = document.getElementsByTagName('audio'),
audioE = audioElms[index];
if (!hasSource) {
musicPlayer.createSource(audioE);
hasSource = true;
}
if (!isPlay) {
musicPlayer.play(audioE);
isPlay = true;
return;
}
musicPlayer.stop(audioE);
isPlay = false;
}
}
});
}, false);
})(this.self, void 0);
|
Change accoring to PR comments. moving code inside if block | <?php
namespace Omise\Payment\Block\Checkout\Onepage\Success;
class PaynowAdditionalInformation extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
array $data = []
) {
$this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data);
}
/**
* Adding PayNow Payment Information
*
* @return string
*/
protected function _toHtml()
{
$paymentData = $this->_checkoutSession->getLastRealOrder()->getPayment()->getData();
if (isset($paymentData['additional_information']['payment_type']) || $paymentData['additional_information']['payment_type'] === 'paynow') {
$orderCurrency = $this->_checkoutSession->getLastRealOrder()->getOrderCurrency()->getCurrencyCode();
$this->addData([
'paynow_qrcode' => $paymentData['additional_information']['qr_code_encoded'],
'order_amount' => number_format($paymentData['amount_ordered'], 2) .' '.$orderCurrency
]);
}
return parent::_toHtml();
}
}
| <?php
namespace Omise\Payment\Block\Checkout\Onepage\Success;
class PaynowAdditionalInformation extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
array $data = []
) {
$this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data);
}
/**
* Adding PayNow Payment Information
*
* @return string
*/
protected function _toHtml()
{
$paymentData = $this->_checkoutSession->getLastRealOrder()->getPayment()->getData();
if (!isset($paymentData['additional_information']['payment_type']) || $paymentData['additional_information']['payment_type'] !== 'paynow') {
return;
}
$orderCurrency = $this->_checkoutSession->getLastRealOrder()->getOrderCurrency()->getCurrencyCode();
$this->addData([
'paynow_qrcode' => $paymentData['additional_information']['qr_code_encoded'],
'order_amount' => number_format($paymentData['amount_ordered'], 2) .' '.$orderCurrency
]);
return parent::_toHtml();
}
}
|
Increment version for multichannel splitting | __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.19.0',
author='James Robert',
author_email='[email protected]',
description='Manipulate audio with an simple and easy high level interface',
license='MIT',
keywords='audio sound high-level',
url='http://pydub.com',
packages=['pydub'],
long_description=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'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',
'Operating System :: OS Independent',
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Sound/Audio :: Analysis",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Sound/Audio :: Editors",
"Topic :: Multimedia :: Sound/Audio :: Mixers",
"Topic :: Software Development :: Libraries",
'Topic :: Utilities',
]
)
| __doc__ = """
Manipulate audio with an simple and easy high level interface.
See the README file for details, usage info, and a list of gotchas.
"""
from setuptools import setup
setup(
name='pydub',
version='0.18.0',
author='James Robert',
author_email='[email protected]',
description='Manipulate audio with an simple and easy high level interface',
license='MIT',
keywords='audio sound high-level',
url='http://pydub.com',
packages=['pydub'],
long_description=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'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',
'Operating System :: OS Independent',
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Sound/Audio :: Analysis",
"Topic :: Multimedia :: Sound/Audio :: Conversion",
"Topic :: Multimedia :: Sound/Audio :: Editors",
"Topic :: Multimedia :: Sound/Audio :: Mixers",
"Topic :: Software Development :: Libraries",
'Topic :: Utilities',
]
)
|
Change installation path for nipap-passwd
This really is a "admin tool" and so we put it in /usr/sbin instead!
Fixes #196 | #!/usr/bin/env python
from distutils.core import setup
import nipap
long_desc = open('README.rst').read()
short_desc = long_desc.split('\n')[0].split(' - ')[1].strip()
setup(
name = 'nipap',
version = nipap.__version__,
description = short_desc,
long_description = long_desc,
author = nipap.__author__,
author_email = nipap.__author_email__,
license = nipap.__license__,
url = nipap.__url__,
packages = ['nipap'],
keywords = ['nipap'],
requires = ['twisted', 'ldap', 'sqlite3', 'IPy', 'psycopg2'],
data_files = [
('/etc/nipap/', ['local_auth.db', 'nipap.conf']),
('/usr/sbin/', ['nipapd', 'nipap-passwd']),
('/usr/share/nipap/sql/', [
'sql/functions.plsql',
'sql/ip_net.plsql'
])
],
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Telecommunications Industry',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware'
]
)
| #!/usr/bin/env python
from distutils.core import setup
import nipap
long_desc = open('README.rst').read()
short_desc = long_desc.split('\n')[0].split(' - ')[1].strip()
setup(
name = 'nipap',
version = nipap.__version__,
description = short_desc,
long_description = long_desc,
author = nipap.__author__,
author_email = nipap.__author_email__,
license = nipap.__license__,
url = nipap.__url__,
packages = ['nipap'],
keywords = ['nipap'],
requires = ['twisted', 'ldap', 'sqlite3', 'IPy', 'psycopg2'],
data_files = [
('/etc/nipap/', ['local_auth.db', 'nipap.conf']),
('/usr/bin/', ['nipap-passwd']),
('/usr/sbin/', ['nipapd']),
('/usr/share/nipap/sql/', [
'sql/functions.plsql',
'sql/ip_net.plsql'
])
],
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Telecommunications Industry',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.6',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware'
]
)
|
Fix problem with missing semicolon
The minified source was dealing with it, we need to deal with it only
for the non-minified variant. | import { terser } from 'rollup-plugin-terser'
import filesize from 'rollup-plugin-filesize'
import license from 'rollup-plugin-license'
export default [
{
input: 'src/js.cookie.mjs',
output: [
// config for <script type="module">
{
dir: 'dist',
entryFileNames: '[name].mjs',
format: 'esm'
},
// config for <script nomodule>
{
dir: 'dist',
name: 'Cookies',
entryFileNames: '[name].js',
format: 'umd',
noConflict: true,
banner: ';'
}
]
},
{
input: 'src/js.cookie.mjs',
output: [
// config for <script type="module">
{
dir: 'dist',
entryFileNames: '[name].min.mjs',
format: 'esm'
},
// config for <script nomodule>
{
dir: 'dist',
name: 'Cookies',
entryFileNames: '[name].min.js',
format: 'umd',
noConflict: true
}
],
plugins: [
terser(),
license({
banner: {
content:
'/*! <%= pkg.name %> v<%= pkg.version %> | <%= pkg.license %> */',
commentStyle: 'none'
}
}),
filesize()
]
}
]
| import { terser } from 'rollup-plugin-terser'
import filesize from 'rollup-plugin-filesize'
import license from 'rollup-plugin-license'
export default [
{
input: 'src/js.cookie.mjs',
output: [
// config for <script type="module">
{
dir: 'dist',
entryFileNames: '[name].mjs',
format: 'esm'
},
// config for <script nomodule>
{
dir: 'dist',
name: 'Cookies',
entryFileNames: '[name].js',
format: 'umd',
noConflict: true
}
]
},
{
input: 'src/js.cookie.mjs',
output: [
// config for <script type="module">
{
dir: 'dist',
entryFileNames: '[name].min.mjs',
format: 'esm'
},
// config for <script nomodule>
{
dir: 'dist',
name: 'Cookies',
entryFileNames: '[name].min.js',
format: 'umd',
noConflict: true
}
],
plugins: [
terser(),
license({
banner: {
content:
'/*! <%= pkg.name %> v<%= pkg.version %> | <%= pkg.license %> */',
commentStyle: 'none'
}
}),
filesize()
]
}
]
|
Add user agent so we don't get bounced by sites requiring it (e.g. SoundCloud) | 'use strict';
var request = require( 'request' ),
cheerio = require( 'cheerio' ),
urlChecker = {
bot : false,
setup : function( bot ){
var _this = this,
channel;
_this.bot = bot;
for( channel in _this.bot.opt.channels ){
if( _this.bot.opt.channels.hasOwnProperty( channel ) ){
bot.addListener( 'message' + this.bot.opt.channels[ channel ], _this.handleMessage );
}
}
},
handleMessage : function( from, text, message ){
var url,
urlRegex = /(https?:\/\/[^\s]+)/g,
options = {
headers: {
'User-Agent': 'request'
}
};
url = text.match( urlRegex );
if( url !== null ){
options.url = url[ 0 ];
request( options, function( error, response, html ){
var $ = cheerio.load( html ),
pageTitle;
if( error ){
console.log( error );
}
pageTitle = $( 'title' ).text();
urlChecker.sendMessage( message.args[ 0 ], pageTitle );
});
}
},
sendMessage : function( channel, message ){
this.bot.say( channel, message.trim() );
}
};
module.exports = urlChecker;
| 'use strict';
var request = require( 'request' ),
cheerio = require( 'cheerio' ),
urlChecker = {
bot : false,
setup : function( bot ){
var _this = this,
channel;
_this.bot = bot;
for( channel in _this.bot.opt.channels ){
if( _this.bot.opt.channels.hasOwnProperty( channel ) ){
bot.addListener( 'message' + this.bot.opt.channels[ channel ], _this.handleMessage );
}
}
},
handleMessage : function( from, text, message ){
var url,
urlRegex = /(https?:\/\/[^\s]+)/g;
url = text.match( urlRegex );
if( url !== null ){
request( url[ 0 ], function( error, response, html ){
var $ = cheerio.load( html ),
pageTitle;
if( error ){
console.log( error );
}
pageTitle = $( 'title' ).text();
urlChecker.sendMessage( message.args[ 0 ], pageTitle );
});
}
},
sendMessage : function( channel, message ){
this.bot.say( channel, message.trim() );
}
};
module.exports = urlChecker;
|
Allow negative values, only mask -9999 | import numpy
def import_climate_data(filepath, monthnr):
ncols = 720
nrows = 360
digits = 5
with open(filepath, 'r') as filein:
lines = filein.readlines()
line_n = 0
grid_size = 0.50
xmin = 0.25
xmax = 360.25
ymin = -89.75
ymax = 90.25
lonrange = numpy.arange(xmin, xmax, grid_size)
latrange = numpy.arange(ymin, ymax, grid_size)
Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0])))
print(len(lonrange))
print(len(latrange))
i = 0
rown = 0
for line in lines:
line_n += 1
if line_n < 3: # skip header
continue
if rown < (monthnr-1)*nrows or rown >= monthnr*nrows: # read one month
rown += 1
continue
value = ''
counter = 1
j = 0
for char in line:
value += char
if counter % digits == 0:
value = float(value)
if value == -9999:
value = numpy.nan
Z[i][j] = value
value = ''
j += 1
counter += 1
i += 1
rown += 1
return latrange, lonrange, Z | import numpy
def import_climate_data(filepath, monthnr):
ncols = 720
nrows = 360
digits = 5
with open(filepath, 'r') as filein:
lines = filein.readlines()
line_n = 0
grid_size = 0.50
xmin = 0.25
xmax = 360.25
ymin = -89.75
ymax = 90.25
lonrange = numpy.arange(xmin, xmax, grid_size)
latrange = numpy.arange(ymin, ymax, grid_size)
Z = numpy.zeros((int(latrange.shape[0]), int(lonrange.shape[0])))
print(len(lonrange))
print(len(latrange))
i = 0
rown = 0
for line in lines:
line_n += 1
if line_n < 3: # skip header
continue
if rown < (monthnr-1)*nrows or rown >= monthnr*nrows: # read one month
rown += 1
continue
value = ''
counter = 1
j = 0
for char in line:
value += char
if counter % digits == 0:
value = float(value)
if value < 0:
value = numpy.nan
Z[i][j] = value
value = ''
j += 1
counter += 1
i += 1
rown += 1
return latrange, lonrange, Z |
[BJA-271]
Add synchronized keyword to prevent concurrency issues in lazy parsing | package org.bouncycastle.asn1;
import java.io.IOException;
import java.util.Enumeration;
public class LazyDERSequence
extends DERSequence
{
private byte[] encoded;
private boolean parsed = false;
private int size = -1;
LazyDERSequence(
byte[] encoded)
throws IOException
{
this.encoded = encoded;
}
private void parse()
{
Enumeration en = new LazyDERConstructionEnumeration(encoded);
while (en.hasMoreElements())
{
addObject((DEREncodable)en.nextElement());
}
parsed = true;
}
public synchronized DEREncodable getObjectAt(int index)
{
if (!parsed)
{
parse();
}
return super.getObjectAt(index);
}
public synchronized Enumeration getObjects()
{
if (parsed)
{
return super.getObjects();
}
return new LazyDERConstructionEnumeration(encoded);
}
public int size()
{
if (size < 0)
{
Enumeration en = new LazyDERConstructionEnumeration(encoded);
size = 0;
while (en.hasMoreElements())
{
en.nextElement();
size++;
}
}
return size;
}
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(SEQUENCE | CONSTRUCTED, encoded);
}
}
| package org.bouncycastle.asn1;
import java.io.IOException;
import java.util.Enumeration;
public class LazyDERSequence
extends DERSequence
{
private byte[] encoded;
private boolean parsed = false;
private int size = -1;
LazyDERSequence(
byte[] encoded)
throws IOException
{
this.encoded = encoded;
}
private void parse()
{
Enumeration en = new LazyDERConstructionEnumeration(encoded);
while (en.hasMoreElements())
{
addObject((DEREncodable)en.nextElement());
}
parsed = true;
}
public DEREncodable getObjectAt(int index)
{
if (!parsed)
{
parse();
}
return super.getObjectAt(index);
}
public Enumeration getObjects()
{
if (parsed)
{
return super.getObjects();
}
return new LazyDERConstructionEnumeration(encoded);
}
public int size()
{
if (size < 0)
{
Enumeration en = new LazyDERConstructionEnumeration(encoded);
size = 0;
while (en.hasMoreElements())
{
en.nextElement();
size++;
}
}
return size;
}
void encode(
DEROutputStream out)
throws IOException
{
out.writeEncoded(SEQUENCE | CONSTRUCTED, encoded);
}
}
|
Cache: Add initial implementation of the bulk updates | import copy
import vim
from taskwiki.task import VimwikiTask
class TaskCache(object):
"""
A cache that holds all the tasks in the given file and prevents
multiple redundant taskwarrior calls.
"""
def __init__(self, tw):
self.uuid_cache = dict()
self.cache = dict()
self.tw = tw
def __getitem__(self, key):
task = self.cache.get(key)
if task is None:
task = VimwikiTask(vim.current.buffer[key], key, self.tw, self)
self.cache[key] = task
if task.uuid:
self.uuid_cache[task.uuid] = task
return task
def __iter__(self):
iterated_cache = copy.copy(self.cache)
while iterated_cache.keys():
for key in list(iterated_cache.keys()):
task = iterated_cache[key]
if all([t.line_number not in iterated_cache.keys()
for t in task.add_dependencies]):
del iterated_cache[key]
yield task
def reset(self):
self.cache = dict()
self.uuid_cache = dict()
def update_tasks(self):
# Select all tasks in the files that have UUIDs
uuids = [t.uuid for t in self.cache.values() if t.uuid]
# Get them out of TaskWarrior at once
tasks = self.tw.filter(uuid=','.join(tasks))
# Update each task in the cache
for task in tasks:
self.uuid_cache[task['uuid']].task = task
| import copy
import vim
from taskwiki.task import VimwikiTask
class TaskCache(object):
"""
A cache that holds all the tasks in the given file and prevents
multiple redundant taskwarrior calls.
"""
def __init__(self, tw):
self.uuid_cache = dict()
self.cache = dict()
self.tw = tw
def __getitem__(self, key):
task = self.cache.get(key)
if task is None:
task = VimwikiTask(vim.current.buffer[key], key, self.tw, self)
self.cache[key] = task
if task.uuid:
self.uuid_cache[task.uuid] = task
return task
def __iter__(self):
iterated_cache = copy.copy(self.cache)
while iterated_cache.keys():
for key in list(iterated_cache.keys()):
task = iterated_cache[key]
if all([t.line_number not in iterated_cache.keys()
for t in task.add_dependencies]):
del iterated_cache[key]
yield task
def reset(self):
self.cache = dict()
# def update_tasks(self):
# tasks = [t
|
ENH: Add test that fails *if* 'all' is not working | from nose.tools import assert_in, assert_equal
from bluesky.run_engine import RunEngine
from bluesky.examples import *
from nose.tools import raises
RE = None
def setup():
global RE
RE = RunEngine()
def exception_raiser(doc):
raise Exception("Hey look it's an exception that better not kill the "
"scan!!")
def test_main_thread_callback_exceptions():
RE(stepscan(motor, det), subs={'start': exception_raiser,
'stop': exception_raiser,
'event': exception_raiser,
'descriptor': exception_raiser,
'all': exception_raiser},
beamline_id='testing', owner='tester')
def test_all():
c = CallbackCounter()
RE(stepscan(motor, det), subs={'all': c})
assert_equal(c.value, 10 + 1 + 2) # events, descriptor, start and stop
c = CallbackCounter()
token = RE.subscribe('all', c)
RE(stepscan(motor, det))
RE.unsubscribe(token)
assert_equal(c.value, 10 + 1 + 2)
@raises(Exception)
def _raising_callbacks_helper(stream_name, callback):
RE(stepscan(motor, det), subs={stream_name: callback},
beamline_id='testing', owner='tester')
def test_callback_execution():
# make main thread exceptions end the scan
RE.dispatcher.cb_registry.halt_on_exception = True
cb = exception_raiser
for stream in ['all', 'start', 'event', 'stop', 'descriptor']:
yield _raising_callbacks_helper, stream, cb
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
| from nose.tools import assert_in, assert_equal
from bluesky.run_engine import RunEngine
from bluesky.examples import *
RE = None
def setup():
global RE
RE = RunEngine()
def test_main_thread_callback_exceptions():
def callbacker(doc):
raise Exception("Hey look it's an exception that better not kill the "
"scan!!")
RE(stepscan(motor, det), subs={'start': callbacker,
'stop': callbacker,
'event': callbacker,
'descriptor': callbacker,
'all': callbacker},
beamline_id='testing', owner='tester')
def test_all():
c = CallbackCounter()
RE(stepscan(motor, det), subs={'all': c})
assert_equal(c.value, 10 + 1 + 2) # events, descriptor, start and stop
c = CallbackCounter()
token = RE.subscribe('all', c)
RE(stepscan(motor, det))
RE.unsubscribe(token)
assert_equal(c.value, 10 + 1 + 2)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
|
Throw RuntimeException is scandir returns false. | <?php
/**
* Utility class that works with deleting files and directories.
*/
class DeleteUtils {
/**
* Delete all files and directories within the root directory.
*
* @param String The absolute path to the root directory.
*/
public static function rm_dir($path) {
foreach(self::serialize_dir($path) as $item) {
$absolute_path = $path . DIRECTORY_SEPARATOR . $item;
if(is_dir($absolute_path) && !self::is_empty($absolute_path)) {
self::rm_dir($absolute_path);
rmdir($absolute_path);
} else if(is_dir($absolute_path)) {
rmdir($absolute_path);
} else {
unlink($absolute_path);
}
}
}
/**
* Checks to see if a directory is empty
*
* @param String The absolute path to a directory.
*
* @return true or false if the directory is empty or not
*/
public static function is_empty($dir) {
return count(self::serialize_dir($dir)) === 0;
}
/**
* Removes . and .. from the array returned from scandir.
*
* @param String The absolute path to a directory.
*
* @return an array from scandir without . and ..
*
* @exception throws a runtime exception when scandir returns false
*/
public static function serialize_dir($dir) {
if(scandir($dir) === false) {
throw new \RuntimeException("Scandir returned false, either $dir was not a directory or an I/O error occurred.");
}
return array_diff(scandir($dir), array('.', '..'));
}
}
DeleteUtils::rm_dir('C:\\temp');
?> | <?php
/**
* Utility class that works with deleting files and directories.
*/
class DeleteUtils {
/**
* Delete all files and directories within the root directory.
*
* @param String The absolute path to the root directory.
*/
public static function rm_dir($path) {
foreach(self::serialize_dir($path) as $item) {
$absolute_path = $path . DIRECTORY_SEPARATOR . $item;
if(is_dir($absolute_path) && !self::is_empty($absolute_path)) {
self::rm_dir($absolute_path);
rmdir($absolute_path);
} else if(is_dir($absolute_path)) {
rmdir($absolute_path);
} else {
unlink($absolute_path);
}
}
}
/**
* Checks to see if a directory is empty
*
* @param String The absolute path to a directory.
*
* @return true or false if the directory is empty or not
*/
public static function is_empty($dir) {
return count(self::serialize_dir($dir)) === 0;
}
/**
* Removes . and .. from the array returned from scandir.
*
* @param String The absolute path to a directory.
*
* @return an array from scandir without . and ..
*/
public static function serialize_dir($dir) {
return array_diff(scandir($dir), array('.', '..'));
}
}
?> |
Drop data on server relaunch | /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
connection: 'mongodbServer',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
migrate: 'drop'
};
| /**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
connection: 'mongodbServer',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
migrate: 'alter'
};
|
Add reset on rotation support in log processor. | import re
import snmpy
class log_processor(snmpy.plugin):
def create(self):
for k, v in sorted(self.conf['objects'].items()):
extra = {
'count': re.compile(v['count']),
'reset': re.compile(v['reset']) if 'reset' in v else None,
'start': int(v['start']) if 'start' in v else 0,
'rotate': bool(v['rotate']) if 'rotate' in v else False
}
self.data['1.%s' % k] = 'string', v['label']
self.data['2.%s' % k] = 'integer', extra['start'], extra
self.tail()
@snmpy.plugin.task
def tail(self):
for line in snmpy.plugin.tail(self.conf['file_name'], True):
if line is True:
for item in self.data['2.0':]:
if self.data[item:'rotate'] and line is True:
self.data[item] = self.data[item:'start']
continue
for item in self.data['2.0':]:
count = self.data[item:'count'].search(line)
if count:
self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1)
break
if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line):
self.data[item] = self.data[item:'start']
break
| import re
import snmpy
class log_processor(snmpy.plugin):
def create(self):
for k, v in sorted(self.conf['objects'].items()):
extra = {
'count': re.compile(v['count']),
'reset': re.compile(v['reset']) if 'reset' in v else None,
'start': int(v['start']) if 'start' in v else 0,
}
self.data['1.%s' % k] = 'string', v['label']
self.data['2.%s' % k] = 'integer', extra['start'], extra
self.tail()
@snmpy.plugin.task
def tail(self):
for line in snmpy.plugin.tail(self.conf['file_name']):
for item in self.data['2.0':]:
count = self.data[item:'count'].search(line)
if count:
self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1)
break
if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line):
self.data[item] = self.data[item:'start']
break
|
Initialize doctrine models when storage is doctrine | <?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class StorageCompilerPass
* @package Tbbc\MoneyBundle\DependencyInjection\Compiler
*/
class StorageCompilerPass implements CompilerPassInterface
{
/**
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$storage = $container->getParameter('tbbc_money.pair.storage');
//Determine if DoctrineBundle is defined
if ('doctrine' === $storage) {
if (!isset($bundles['DoctrineBundle'])) {
throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
}
//Add doctrine schema mappings
$modelDir = realpath(__DIR__.'/../../Resources/config/doctrine/ratios');
$path = DoctrineOrmMappingsPass::createXmlMappingDriver(array(
$modelDir => 'Tbbc\MoneyBundle\Entity',
));
$path->process($container);
$storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
new Reference('doctrine.orm.entity_manager'),
$container->getParameter('tbbc_money.reference_currency'),
));
$container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
$container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
}
}
}
| <?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class StorageCompilerPass
* @package Tbbc\MoneyBundle\DependencyInjection\Compiler
*/
class StorageCompilerPass implements CompilerPassInterface
{
/**
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$storage = $container->getParameter('tbbc_money.pair.storage');
//Determine if DoctrineBundle is defined
if ('doctrine' === $storage) {
if (!isset($bundles['DoctrineBundle'])) {
throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
}
$storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
new Reference('doctrine.orm.entity_manager'),
$container->getParameter('tbbc_money.reference_currency'),
));
$container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
$container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
}
}
}
|
Change wording to use response | import requests, json
from resources.urls import FACEBOOK_MESSAGES_POST_URL
class HttpClient():
"""
Client which excutes the call to
facebook's messenger api
"""
def submit_request(self, path, method, payload, completion):
assert len(path) > 0
path = self.get_api_url(path)
headers = self.get_headers()
if method == 'GET':
response = requests.get(path, headers=headers)
if response.status_code is not 200:
error = self.get_error_from_request(response)
completion(None, error)
else:
json_ = self.get_json(response.text)
completion(json_, None)
elif method == 'POST':
re
def get_error_from_response(self, response):
return {
'error': self.get_json(response.text)
}
def get_json(self, string):
return json.loads(string)
def get_api_url(self, path):
return FACEBOOK_MESSAGES_POST_URL + path
def get_headers(self):
return {}
| import requests, json
from resources.urls import FACEBOOK_MESSAGES_POST_URL
class HttpClient():
"""
Client which excutes the call to
facebook's messenger api
"""
def submit_request(self, path, method, payload, completion):
assert len(path) > 0
path = self.get_api_url(path)
headers = self.get_headers()
if method == 'GET':
request = requests.get(path, headers=headers)
if request.status_code is not 200:
error = self.get_error_from_request(request)
completion(None, error)
else:
json_ = self.get_json(request.text)
completion(json_, None)
elif method == 'POST':
raise NotImplementedError
def get_error_from_request(self, request):
return {
'error': self.get_json(request.text)
}
def get_json(self, string):
return json.loads(string)
def get_api_url(self, path):
return FACEBOOK_MESSAGES_POST_URL + path
def get_headers(self):
return {}
|
Support no context with tLog | <?php
/**
* @license MIT
* @copyright 2017 Tim Gunter
*/
namespace Kaecyra\AppCommon\Log\Tagged;
/**
* Tagged log trait
*
* @author Tim Gunter <[email protected]>
* @package app-common
*/
trait TaggedLogTrait {
/**
* Log tag
* @var string|Callable
*/
protected $logTag = null;
/**
* Log tagged message
*
* @param string $level
* @param string $message
* @param array $context
*/
public function tLog(string $level, string $message, array $context = []) {
$logtag = $this->getLogTag();
if (is_array($message) || is_object($message)) {
$message = print_r($message, true);
}
$this->log($level, "[{$logtag}] ".$message, $context);
}
/**
* Get log tag
*
* @return string
*/
protected function getLogTag() {
return is_callable($this->logTag) ? $this->logTag() : $this->logTag;
}
/**
* Set log tag
*
* @param string|Callable $logTag
*/
public function setLogTag($logTag) {
$this->logTag = $logTag;
}
/**
* Set default logtag callback
*
*
*/
public function setDefaultLogCallback() {
$this->setLogTag(function(){
return (new \ReflectionClass($this))->getShortName();
});
}
} | <?php
/**
* @license MIT
* @copyright 2017 Tim Gunter
*/
namespace Kaecyra\AppCommon\Log\Tagged;
/**
* Tagged log trait
*
* @author Tim Gunter <[email protected]>
* @package app-common
*/
trait TaggedLogTrait {
/**
* Log tag
* @var string|Callable
*/
protected $logTag = null;
/**
* Log tagged message
*
* @param string $level
* @param string $message
* @param array $context
*/
public function tLog(string $level, string $message, array $context) {
$logtag = $this->getLogTag();
if (is_array($message) || is_object($message)) {
$message = print_r($message, true);
}
$this->log($level, "[{$logtag}] ".$message, $context);
}
/**
* Get log tag
*
* @return string
*/
protected function getLogTag() {
return is_callable($this->logTag) ? $this->logtag() : $this->logTag;
}
/**
* Set log tag
*
* @param string|Callable $logTag
*/
public function setLogTag($logTag) {
$this->logTag = $logTag;
}
/**
* Set default logtag callback
*
*
*/
public function setDefaultLogCallback() {
$this->setLogTag(function(){
return (new \ReflectionClass($this))->getShortName();
});
}
} |
Add initialProgress property to make start from the given value | var React = require('react-native');
var {
Animated,
Easing,
StyleSheet,
View
} = React;
var styles = StyleSheet.create({
background: {
backgroundColor: '#bbbbbb',
height: 5,
overflow: 'hidden'
},
fill: {
backgroundColor: '#3b5998',
height: 5
}
});
var ProgressBar = React.createClass({
getDefaultProps() {
return {
style: styles,
easing: Easing.inOut(Easing.ease),
easingDuration: 500
};
},
getInitialState() {
return {
progress: new Animated.Value(this.props.initialProgress || 0)
};
},
componentDidUpdate(prevProps, prevState) {
if (this.props.progress >= 0 && this.props.progress != prevProps.progress) {
this.update();
}
},
render() {
var fillWidth = this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [0 * this.props.style.width, 1 * this.props.style.width],
});
return (
<View style={[styles.background, this.props.backgroundStyle, this.props.style]}>
<Animated.View style={[styles.fill, this.props.fillStyle, { width: fillWidth }]}/>
</View>
);
},
update() {
Animated.timing(this.state.progress, {
easing: this.props.easing,
duration: this.props.easingDuration,
toValue: this.props.progress
}).start();
}
});
module.exports = ProgressBar;
| var React = require('react-native');
var {
Animated,
Easing,
StyleSheet,
View
} = React;
var styles = StyleSheet.create({
background: {
backgroundColor: '#bbbbbb',
height: 5,
overflow: 'hidden'
},
fill: {
backgroundColor: '#3b5998',
height: 5
}
});
var ProgressBar = React.createClass({
getDefaultProps() {
return {
style: styles,
easing: Easing.inOut(Easing.ease),
easingDuration: 500
};
},
getInitialState() {
return {
progress: new Animated.Value(0)
};
},
componentDidUpdate(prevProps, prevState) {
if (this.props.progress >= 0 && this.props.progress != prevProps.progress) {
this.update();
}
},
render() {
var fillWidth = this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [0 * this.props.style.width, 1 * this.props.style.width],
});
return (
<View style={[styles.background, this.props.backgroundStyle, this.props.style]}>
<Animated.View style={[styles.fill, this.props.fillStyle, { width: fillWidth }]}/>
</View>
);
},
update() {
Animated.timing(this.state.progress, {
easing: this.props.easing,
duration: this.props.easingDuration,
toValue: this.props.progress
}).start();
}
});
module.exports = ProgressBar;
|
Convert FlowToolsLog to a class | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles ([email protected])
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
class FlowToolsLog(object):
def __init__(self, file_path):
self._file_path = file_path
def __iter__(self):
self._parser = self._reader()
return self
def __next__(self):
return next(self._parser)
def next(self):
"""
next method included for compatibility with Python 2
"""
return self.__next__()
def _reader(self):
with io.open(self._file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(
self._file_path
)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
| # flowtools_wrapper.py
# Copyright 2014 Bo Bayles ([email protected])
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
def FlowToolsLog(file_path):
with io.open(file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(file_path)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
|
Remove reset method for database class | <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace acd;
/**
* Description of database
*
* @author Acidvertigo
*/
class Database
{
/** @var object|null **/
private static $conn = null;
/** @var array $db **/
private $db = array();
private function __construct() {}
private function __clone() {}
private function __wakeup() {}
/**
* Connects to the database
* @param \acd\Registry $registry
* @return null|object
*/
public static function connect(Registry $registry)
{
// One connection through whole application
if (null == self::$conn) {
try {
// Load the database connection parameters from the Registry
$db = $registry->get('config')['database'];
// Starts connection
self::$conn = new \PDO("mysql:host=".$db['HOST'].";dbname=".$db['NAME'], $db['USERNAME'], $db['PASSWORD']);
} catch (\PDOException $e) {
echo $e->getMessage();
}
}
return self::$conn;
}
/**
* Close database connection
*/
public static function disconnect()
{
self::$conn = null;
}
}
| <?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace acd;
/**
* Description of database
*
* @author Acidvertigo
*/
class Database
{
/** @var object|null **/
private static $conn = null;
/** @var array $db **/
private $db = array();
private function __construct() {}
private function __clone() {}
private function __wakeup() {}
/**
* Connects to the database
* @param \acd\Registry $registry
* @return null|object
*/
public static function connect(Registry $registry)
{
// One connection through whole application
if (null == self::$conn) {
try {
// Load the database connection parameters from the Registry
$db = $registry->get('config')['database'];
// Starts connection
self::$conn = new \PDO("mysql:host=".$db['HOST'].";dbname=".$db['NAME'], $db['USERNAME'], $db['PASSWORD']);
} catch (\PDOException $e) {
echo $e->getMessage();
}
}
return self::$conn;
}
/**
* Close database connection
*/
public static function disconnect()
{
self::$conn = null;
}
public static function reset() {
self::$conn = null;
}
}
|
Remove reference to deprecated TicketDB class | <?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('class.TicketAdminPage.php');
$page = new TicketAdminPage('Burning Flipside - Tickets');
$page->add_js(JS_DATATABLE, false);
$page->add_css(CSS_DATATABLE);
$page->add_js_from_src('js/sold_tickets.js');
$page->body .= '
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Sold Tickets</h1>
</div>
</div>
<div class="row">
<table class="table" id="tickets">
<thead>
<tr>
<th>Short Code</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
';
$page->print_page();
// vim: set tabstop=4 shiftwidth=4 expandtab:
?>
| <?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('class.TicketAdminPage.php');
require_once('class.FlipsideTicketDB.php');
$page = new TicketAdminPage('Burning Flipside - Tickets');
$page->add_js(JS_DATATABLE);
$page->add_css(CSS_DATATABLE);
$page->add_js_from_src('js/sold_tickets.js');
$page->body .= '
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Sold Tickets</h1>
</div>
</div>
<div class="row">
<table class="table" id="tickets">
<thead>
<tr>
<th>Short Code</th>
<th>First Name</th>
<th>Last Name</th>
<th>Type</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
';
$page->print_page();
// vim: set tabstop=4 shiftwidth=4 expandtab:
?>
|
Attach prefix path resolver at end of chain of aggregate resolver | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mvc\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver as ViewResolver;
class ViewResolverFactory implements FactoryInterface
{
/**
* Create the aggregate view resolver
*
* Creates a Zend\View\Resolver\AggregateResolver and attaches the template
* map resolver and path stack resolver
*
* @param ServiceLocatorInterface $serviceLocator
* @return ViewResolver\AggregateResolver
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$resolver = new ViewResolver\AggregateResolver();
$mapResolver = $serviceLocator->get('ViewTemplateMapResolver');
$pathResolver = $serviceLocator->get('ViewTemplatePathStack');
$prefixPathStackResolver = $serviceLocator->get('ViewPrefixPathStackResolver');
$resolver
->attach($mapResolver)
->attach($pathResolver)
->attach($prefixPathStackResolver)
->attach(new ViewResolver\RelativeFallbackResolver($mapResolver))
->attach(new ViewResolver\RelativeFallbackResolver($pathResolver))
->attach(new ViewResolver\RelativeFallbackResolver($prefixPathStackResolver));
return $resolver;
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mvc\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Resolver as ViewResolver;
class ViewResolverFactory implements FactoryInterface
{
/**
* Create the aggregate view resolver
*
* Creates a Zend\View\Resolver\AggregateResolver and attaches the template
* map resolver and path stack resolver
*
* @param ServiceLocatorInterface $serviceLocator
* @return ViewResolver\AggregateResolver
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$resolver = new ViewResolver\AggregateResolver();
<<<<<<< HEAD
$mapResolver = $serviceLocator->get('ViewTemplateMapResolver');
$pathResolver = $serviceLocator->get('ViewTemplatePathStack');
$resolver->attach($mapResolver)
->attach($pathResolver)
->attach(new ViewResolver\RelativeFallbackResolver($mapResolver))
->attach(new ViewResolver\RelativeFallbackResolver($pathResolver))
;
=======
$resolver->attach($serviceLocator->get('ViewPrefixPathStackResolver'));
$resolver->attach($serviceLocator->get('ViewTemplateMapResolver'));
$resolver->attach($serviceLocator->get('ViewTemplatePathStack'));
>>>>>>> Create PrefixPathStackResolver
return $resolver;
}
}
|
Fix for fatal error with renamned DispatchesCommands trait | <?php namespace Laravel\Lumen\Routing;
use Illuminate\Http\Request;
abstract class Controller
{
use DispatchesJobs, ValidatesRequests;
/**
* The middleware defined on the controller.
*
* @var array
*/
protected $middleware = [];
/**
* Define a middleware on the controller.
*
* @param string $middleware
* @param array $options
* @return void
*/
public function middleware($middleware, array $options = array())
{
$this->middleware[$middleware] = $options;
}
/**
* Get the middleware for a given method.
*
* @param Request $request
* @param string $method
* @return array
*/
public function getMiddlewareForMethod(Request $request, $method)
{
$middleware = [];
foreach ($this->middleware as $name => $options) {
if (isset($options['only']) && ! in_array($method, (array) $options['only'])) {
continue;
}
if (isset($options['except']) && in_array($method, (array) $options['except'])) {
continue;
}
$middleware[] = $name;
}
return $middleware;
}
}
| <?php namespace Laravel\Lumen\Routing;
use Illuminate\Http\Request;
abstract class Controller
{
use DispatchesCommands, ValidatesRequests;
/**
* The middleware defined on the controller.
*
* @var array
*/
protected $middleware = [];
/**
* Define a middleware on the controller.
*
* @param string $middleware
* @param array $options
* @return void
*/
public function middleware($middleware, array $options = array())
{
$this->middleware[$middleware] = $options;
}
/**
* Get the middleware for a given method.
*
* @param Request $request
* @param string $method
* @return array
*/
public function getMiddlewareForMethod(Request $request, $method)
{
$middleware = [];
foreach ($this->middleware as $name => $options) {
if (isset($options['only']) && ! in_array($method, (array) $options['only'])) {
continue;
}
if (isset($options['except']) && in_array($method, (array) $options['except'])) {
continue;
}
$middleware[] = $name;
}
return $middleware;
}
}
|
Replace .bind with @bind decorator | import { h, Component } from 'preact'
import { bind } from './util'
export default class extends Component {
constructor() {
super()
this.state.show = false
}
linkState(key) {
return e => this.setState({
[key]: e.target.value
})
}
@bind
toggleShow() {
this.setState({
show: !this.state.show
})
}
clearState() {
this.setState({
appName: '',
username: '',
password: '',
show: false
})
}
@bind
handleSubmit(e) {
e.preventDefault()
this.props.add(this.state.appName, this.state.username, this.state.password)
this.clearState()
}
render(_, { show, appName, username, password }) {
return (
<section>
<div style={{display: show ? 'block' : 'none'}}>
<form onSubmit={this.handleSubmit}>
<input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} />
<input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} />
<input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} />
<button type='submit'>Save</button>
</form>
</div>
<button onClick={this.toggleShow}>Add new app</button>
</section>
)
}
}
| import { h, Component } from 'preact'
export default class extends Component {
constructor() {
super()
this.state.show = false
}
linkState(key) {
return e => this.setState({
[key]: e.target.value
})
}
toggleShow() {
this.setState({
show: !this.state.show
})
}
clearState() {
this.setState({
appName: '',
username: '',
password: '',
show: false
})
}
handleSubmit(e) {
e.preventDefault()
this.props.add(this.state.appName, this.state.username, this.state.password)
this.clearState()
}
render(_, { show, appName, username, password }) {
return (
<section>
<div style={{display: show ? 'block' : 'none'}}>
<form onSubmit={this.handleSubmit.bind(this)}>
<input name='appName' placeholder='Enter app name' value={appName} onInput={this.linkState('appName')} />
<input name='username' placeholder='Enter app username' value={username} onInput={this.linkState('username')} />
<input name='password' placeholder='Enter app password' value={password} onInput={this.linkState('password')} />
<button type='submit'>Save</button>
</form>
</div>
<button onClick={this.toggleShow.bind(this)}>Add new app</button>
</section>
)
}
}
|
[Fields] Fix du min et du max | <?php
namespace Gregwar\DSD\Fields;
/**
* Nombre
*
* @author Grégoire Passault <[email protected]>
*/
class NumberField extends Field
{
/**
* Valeur minimum
*/
private $min = null;
/**
* Valeur maximum
*/
private $max = null;
public function __construct()
{
$this->type = 'text';
}
public function push($name, $value)
{
switch ($name) {
case 'min':
$this->min = $value;
return;
case 'max':
$this->max = $value;
return;
}
parent::push($name, $value);
}
public function check()
{
if ($this->optional && !$this->value)
return;
$err=parent::check();
if ($err)
return $err;
if ($this->multiple && is_array($this->value))
return;
if (!is_numeric($this->value)) {
return 'Le champ '.$this->printName().' doit être un nombre';
}
if ($this->min !== null) {
if ($this->value < $this->min)
return 'Le champ '.$this->printName().' doit être au moins égal à '.$this->min;
}
if ($this->max !== null) {
if ($this->value > $this->max) {
return 'Le champ '.$this->printName().' ne doit pas dépasser '.$this->max;
}
}
}
}
| <?php
namespace Gregwar\DSD\Fields;
/**
* Nombre
*
* @author Grégoire Passault <[email protected]>
*/
class NumberField extends Field
{
/**
* Valeur minimum
*/
private $min = null;
/**
* Valeur maximum
*/
private $max = null;
public function __construct()
{
$this->type = 'text';
}
public function push($name, $value)
{
switch ($name) {
case 'min':
$this->min = $value;
break;
case 'max':
$this->max = $value;
break;
}
parent::push($name, $value);
}
public function check()
{
if ($this->optional && !$this->value)
return;
$err=parent::check();
if ($err)
return $err;
if ($this->multiple && is_array($this->value))
return;
if (!is_numeric($this->value)) {
return 'Le champ '.$this->printName().' doit être un nombre';
}
if ($this->min !== null) {
if ($this->value < $this->min)
return 'Le champ '.$this->printName().' doit être au moins égal à '.$this->min;
}
if ($this->max !== null) {
if ($this->value > $this->max) {
return 'Le champ '.$this->printName().' ne doit pas dépasser '.$this->max;
}
}
}
}
|
Fix a typo bug referencing headers | const responseFromObject = (mockResponse, response) => {
// statusCode
if (mockResponse.statusCode) {
response.statusCode = mockResponse.statusCode
}
// statusMessage
if (mockResponse.statusMessage) {
response.statusMessage = mockResponse.statusMessage
}
// headers
if (mockResponse.headers) {
Object.keys(mockResponse.headers).map((name) => (
[name, mockResponse.headers[name]]
)).forEach(([name, value]) => response.setHeader(name, value));
}
// trailers
if (mockResponse.trailers) {
// get all trailer keys and set the trailer header
response.setHeader('Trailer', Object.keys(mockResponse.trailers).join(', '));
}
// body
// TODO: consider automatically setting the Content-type header if it isn't
// already set
// if (mockResponse.body && typeof mockResponse.body.pipe === 'function') {
// mockResponse.body.pipe(response);
// } else {
// }
response.write(
((b) => {
if (
typeof b === 'string' ||
b instanceof Buffer
) {
return b;
}
return JSON.stringify(b, null, 2);
})(mockResponse.body)
);
// trailers - again
if (mockResponse.trailers) {
// add the actual trailers
response.addTrailers(mockResponse.trailers);
}
response.end();
};
module.exports = responseFromObject;
| const responseFromObject = (mockResponse, response) => {
// statusCode
if (mockResponse.statusCode) {
response.statusCode = mockResponse.statusCode
}
// statusMessage
if (mockResponse.statusMessage) {
response.statusMessage = mockResponse.statusMessage
}
// headers
if (mockResponse.headers) {
Object.keys(mockResponse.header).map((name) => (
[name, mockResponse.headers[name]]
)).forEach(([name, value]) => response.setHeader(name, value));
}
// trailers
if (mockResponse.trailers) {
// get all trailer keys and set the trailer header
response.setHeader('Trailer', Object.keys(mockResponse.trailers).join(', '));
}
// body
// TODO: consider automatically setting the Content-type header if it isn't
// already set
// if (mockResponse.body && typeof mockResponse.body.pipe === 'function') {
// mockResponse.body.pipe(response);
// } else {
// }
response.write(
((b) => {
if (
typeof b === 'string' ||
b instanceof Buffer
) {
return b;
}
return JSON.stringify(b, null, 2);
})(mockResponse.body)
);
// trailers - again
if (mockResponse.trailers) {
// add the actual trailers
response.addTrailers(mockResponse.trailers);
}
response.end();
};
module.exports = responseFromObject;
|
Replace \Criteria with \ModelCriteria, as in the pagination subscriber | <?php
namespace Knp\Component\Pager\Event\Subscriber\Sortable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
class PropelQuerySubscriber implements EventSubscriberInterface
{
public function items(ItemsEvent $event)
{
$query = $event->target;
if ($query instanceof \ModelCriteria) {
if (isset($_GET[$event->options['sortFieldParameterName']])) {
$direction = strtolower($_GET[$event->options['sortDirectionParameterName']]) === 'asc' ? 'asc' : 'desc';
$part = $_GET[$event->options['sortFieldParameterName']];
if (isset($event->options['sortFieldWhitelist'])) {
if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) {
throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist");
}
}
$query->orderBy($part, $direction);
}
}
}
public static function getSubscribedEvents()
{
return array(
'knp_pager.items' => array('items', 1)
);
}
}
| <?php
namespace Knp\Component\Pager\Event\Subscriber\Sortable;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
class PropelQuerySubscriber implements EventSubscriberInterface
{
public function items(ItemsEvent $event)
{
$query = $event->target;
if ($query instanceof \Criteria) {
if (isset($_GET[$event->options['sortFieldParameterName']])) {
$direction = strtolower($_GET[$event->options['sortDirectionParameterName']]) === 'asc' ? 'asc' : 'desc';
$part = $_GET[$event->options['sortFieldParameterName']];
if (isset($event->options['sortFieldWhitelist'])) {
if (!in_array($_GET[$event->options['sortFieldParameterName']], $event->options['sortFieldWhitelist'])) {
throw new \UnexpectedValueException("Cannot sort by: [{$_GET[$event->options['sortFieldParameterName']]}] this field is not in whitelist");
}
}
$query->orderBy($part, $direction);
}
}
}
public static function getSubscribedEvents()
{
return array(
'knp_pager.items' => array('items', 1)
);
}
}
|
Update troposphere & awacs to latest releases | import os
from setuptools import setup, find_packages
import glob
VERSION = "0.6.3"
src_dir = os.path.dirname(__file__)
install_requires = [
"troposphere>=1.8.0",
"boto3>=1.3.1",
"botocore>=1.4.38",
"PyYAML>=3.11",
"awacs>=0.6.0",
"colorama==0.3.7",
]
tests_require = [
"nose>=1.0",
"mock==1.0.1",
"stacker_blueprints",
"moto",
"testfixtures",
]
def read(filename):
full_path = os.path.join(src_dir, filename)
with open(full_path) as fd:
return fd.read()
if __name__ == "__main__":
setup(
name="stacker",
version=VERSION,
author="Michael Barrett",
author_email="[email protected]",
license="New BSD license",
url="https://github.com/remind101/stacker",
description="Opinionated AWS CloudFormation Stack manager",
long_description=read("README.rst"),
packages=find_packages(),
scripts=glob.glob(os.path.join(src_dir, "scripts", "*")),
install_requires=install_requires,
tests_require=tests_require,
test_suite="nose.collector",
)
| import os
from setuptools import setup, find_packages
import glob
VERSION = "0.6.3"
src_dir = os.path.dirname(__file__)
install_requires = [
"troposphere>=1.2.2",
"boto3>=1.3.1",
"botocore>=1.4.38",
"PyYAML>=3.11",
"awacs>=0.5.3",
"colorama==0.3.7",
]
tests_require = [
"nose>=1.0",
"mock==1.0.1",
"stacker_blueprints",
"moto",
"testfixtures",
]
def read(filename):
full_path = os.path.join(src_dir, filename)
with open(full_path) as fd:
return fd.read()
if __name__ == "__main__":
setup(
name="stacker",
version=VERSION,
author="Michael Barrett",
author_email="[email protected]",
license="New BSD license",
url="https://github.com/remind101/stacker",
description="Opinionated AWS CloudFormation Stack manager",
long_description=read("README.rst"),
packages=find_packages(),
scripts=glob.glob(os.path.join(src_dir, "scripts", "*")),
install_requires=install_requires,
tests_require=tests_require,
test_suite="nose.collector",
)
|
Set timeout of five minutes | 'use strict';
const mocha = require('mocha');
const BaseWorker = require('./BaseWorker');
const EventsBus = require('../libs/EventsBus');
const Util = require('../libs/Util');
class MochaWorker extends BaseWorker {
constructor(scenario) {
super(scenario);
this._mocha = new mocha();
}
setup(done) {
this._mocha.addFile(this.scenario.options.entrypoint);
this._mocha.reporter('json');
this._mocha.timeout(300000);
super.setup(done);
}
run(done) {
super.run(() => {
let output = '';
process.stdout.write = (chunk) => {
output += chunk;
};
let runner = this._mocha.run((failures) => {
this.scenario.data = Util.deepExtend(this.scenario.data, Data);
done(JSON.parse(output));
});
runner.on('test', (test) => {
EventsBus.emit('worker:test', {
name: this.name,
data: test.title
});
});
// runner.on('test end', (test) => {
// EventsBus.emit('worker:testend', {);
// });
runner.on('pass', (test) => {
EventsBus.emit('worker:pass', {
name: this.name,
data: test.title
});
});
runner.on('fail', (test) => {
EventsBus.emit('worker:fail', {
name: this.name,
data: test.title
});
});
})
}
}
module.exports = MochaWorker;
| 'use strict';
const mocha = require('mocha');
const BaseWorker = require('./BaseWorker');
const EventsBus = require('../libs/EventsBus');
const Util = require('../libs/Util');
class MochaWorker extends BaseWorker {
constructor(scenario) {
super(scenario);
this._mocha = new mocha();
}
setup(done) {
this._mocha.addFile(this.scenario.options.entrypoint);
this._mocha.reporter('json');
this._mocha.timeout(0);
super.setup(done);
}
run(done) {
super.run(() => {
let output = '';
process.stdout.write = (chunk) => {
output += chunk;
};
let runner = this._mocha.run((failures) => {
this.scenario.data = Util.deepExtend(this.scenario.data, Data);
done(JSON.parse(output));
});
runner.on('test', (test) => {
EventsBus.emit('worker:test', {
name: this.name,
data: test.title
});
});
// runner.on('test end', (test) => {
// EventsBus.emit('worker:testend', {);
// });
runner.on('pass', (test) => {
EventsBus.emit('worker:pass', {
name: this.name,
data: test.title
});
});
runner.on('fail', (test) => {
EventsBus.emit('worker:fail', {
name: this.name,
data: test.title
});
});
})
}
}
module.exports = MochaWorker; |
Add conflict to dyncss to ensure correct less rendering | <?php
/***************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
***************************************************************/
$EM_CONF[$_EXTKEY] = array (
'title' => 'Bootstrap Package',
'description' => 'Boostrap Package delivers a full configured frontend for TYPO3 CMS 6.2, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'shy' => 0,
'version' => '6.2.5-dev',
'dependencies' => '',
'conflicts' => '',
'priority' => 'top',
'loadOrder' => '',
'module' => '',
'state' => 'beta',
'uploadfolder' => 0,
'createDirs' => '',
'modify_tables' => 'tt_content',
'clearcacheonload' => 1,
'lockType' => '',
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'CGLcompliance' => NULL,
'CGLcompliance_note' => NULL,
'constraints' => array(
'depends' => array(
'typo3' => '6.2.0-6.3.99',
'css_styled_content' => '6.2.0-6.3.99',
'realurl' => '1.12.8-1.12.99',
),
'conflicts' => array(
'fluidpages' => '*',
'dyncss' => '*',
),
'suggests' => array()
),
); | <?php
/***************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
***************************************************************/
$EM_CONF[$_EXTKEY] = array (
'title' => 'Bootstrap Package',
'description' => 'Boostrap Package delivers a full configured frontend for TYPO3 CMS 6.2, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'shy' => 0,
'version' => '6.2.5-dev',
'dependencies' => '',
'conflicts' => '',
'priority' => 'top',
'loadOrder' => '',
'module' => '',
'state' => 'beta',
'uploadfolder' => 0,
'createDirs' => '',
'modify_tables' => 'tt_content',
'clearcacheonload' => 1,
'lockType' => '',
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'CGLcompliance' => NULL,
'CGLcompliance_note' => NULL,
'constraints' => array(
'depends' => array(
'typo3' => '6.2.0-6.3.99',
'css_styled_content' => '6.2.0-6.3.99',
'realurl' => '1.12.8-1.12.99',
),
'conflicts' => array(
'fluidpages' => '*',
),
'suggests' => array()
),
); |
Add description of LetBindings and LetBinding, which were missing from document | /**
* Abstract Syntax Tree.
*
* <pre>
* Group ::= Abbreviation* Definition*
*
* Definition ::= Test | FourPhaseTest | Table
*
* Test ::= Assertion*
*
* Assertion ::= Proposition* Fixture
*
* Proposition ::= QuotedExpr Predicate
*
* Predicate ::= IsPredicate | IsNotPredicate | ThrowsPredicate
*
* IsPredicate ::= Matcher
* IsNotPredicate ::= Matcher
* ThrowsPredicate ::= Matcher
*
* Matcher ::= EqualToMatcher
* | InstanceOfMatcher
* | InstanceSuchThatMatcher
* | NullValueMatcher
*
* EqualToMatcher ::= QuotedExpr
* InstanceOfMatcher ::= ClassType
* InstanceSuchThatMatcher ::= ClassType Proposition+
*
* Expr ::= QuotedExpr | StubExpr
*
* StubExpr ::= ClassType StubBehavior*
*
* StubBehavior ::= MethodPattern Expr
*
* MethodPattern ::= Type*
*
* Type ::= NonArrayType
* NonArrayType ::= PrimitiveType | ClassType
* PrimitiveType ::= Kind
*
* Fixture ::= | TableRef | Bindings
*
* TableRef ::= Ident+ TableType
*
* TableType :: INLINE | CSV | TSV | EXCEL
*
* Bindings ::= Binding*
* Binding ::= Ident Expr
*
* FourPhaseTest ::= Phase? Phase? VerifyPhase Phase?
*
* Phase ::= LetBindings? Execution?
* VerifyPhase ::= Assertion+
*
* LetBindings ::= LetBinding+
* LetBinding ::= Expr
*
* Execution ::= QuotedExpr*
*
* Table ::= Ident* Row*
*
* Row ::= Expr*
* </pre>
*
*/
package yokohama.unit.ast; | /**
* Abstract Syntax Tree.
*
* <pre>
* Group ::= Abbreviation* Definition*
*
* Definition ::= Test | FourPhaseTest | Table
*
* Test ::= Assertion*
*
* Assertion ::= Proposition* Fixture
*
* Proposition ::= QuotedExpr Predicate
*
* Predicate ::= IsPredicate | IsNotPredicate | ThrowsPredicate
*
* IsPredicate ::= Matcher
* IsNotPredicate ::= Matcher
* ThrowsPredicate ::= Matcher
*
* Matcher ::= EqualToMatcher
* | InstanceOfMatcher
* | InstanceSuchThatMatcher
* | NullValueMatcher
*
* EqualToMatcher ::= QuotedExpr
* InstanceOfMatcher ::= ClassType
* InstanceSuchThatMatcher ::= ClassType Proposition+
*
* Expr ::= QuotedExpr | StubExpr
*
* StubExpr ::= ClassType StubBehavior*
*
* StubBehavior ::= MethodPattern Expr
*
* MethodPattern ::= Type*
*
* Type ::= NonArrayType
* NonArrayType ::= PrimitiveType | ClassType
* PrimitiveType ::= Kind
*
* Fixture ::= | TableRef | Bindings
*
* TableRef ::= Ident+ TableType
*
* TableType :: INLINE | CSV | TSV | EXCEL
*
* Bindings ::= Binding*
* Binding ::= Ident Expr
*
* FourPhaseTest ::= Phase? Phase? VerifyPhase Phase?
*
* Phase ::= LetBindings? Execution?
* VerifyPhase ::= Assertion+
*
* Execution ::= QuotedExpr*
*
* Table ::= Ident* Row*
*
* Row ::= Expr*
* </pre>
*
*/
package yokohama.unit.ast; |
Disable and run and help commands; don't read settings. | import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run') # 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
ENABLE_PRESETS = False
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
if ENABLE_PRESETS:
parser.add_argument('--presets',
help='Filename for presets',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
presets = ENABLE_PRESETS and PresetLibrary(
os.path.expanduser(args.presets), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, presets) or 0)
| import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run', 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
parser.add_argument('--settings',
help='Filename for settings',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
settings = PresetLibrary(os.path.expanduser(args.settings), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, settings) or 0)
|
Remove python 3 syntax for python 2 compatibility | from django.contrib.auth.models import AnonymousUser
from django.db.models.base import ModelBase
from django.test import TestCase
from rest_framework.test import APIRequestFactory, force_authenticate
from . import factories
class AbstractModelTestCase(TestCase):
"""
Base class for tests of model mixins. To use, subclass and specify
the mixin class variable. A model using the mixin will be made
available in self.model.
From http://michael.mior.ca/2012/01/14/unit-testing-django-model-mixins/
via http://stackoverflow.com/a/9678200/400691, modified as we don't need an
object in the database.
"""
def setUp(self):
# Create a dummy model which extends the mixin
self.model = ModelBase(
'__TestModel__' + self.mixin.__name__,
(self.mixin,),
{'__module__': self.mixin.__module__},
)
class APIRequestTestCase(TestCase):
user_factory = factories.UserFactory
def create_request(self, method='get', url='/', user=None, auth=True, **kwargs):
if not user:
if auth:
user = self.user_factory.create()
else:
user = AnonymousUser()
kwargs['format'] = 'json'
request = getattr(APIRequestFactory(), method)(url, **kwargs)
request.user = user
if auth:
force_authenticate(request, user)
if 'data' in kwargs:
request.DATA = kwargs['data']
return request
| from django.contrib.auth.models import AnonymousUser
from django.db.models.base import ModelBase
from django.test import TestCase
from rest_framework.test import APIRequestFactory, force_authenticate
from . import factories
class AbstractModelTestCase(TestCase):
"""
Base class for tests of model mixins. To use, subclass and specify
the mixin class variable. A model using the mixin will be made
available in self.model.
From http://michael.mior.ca/2012/01/14/unit-testing-django-model-mixins/
via http://stackoverflow.com/a/9678200/400691, modified as we don't need an
object in the database.
"""
def setUp(self):
# Create a dummy model which extends the mixin
self.model = ModelBase(
'__TestModel__' + self.mixin.__name__,
(self.mixin,),
{'__module__': self.mixin.__module__},
)
class APIRequestTestCase(TestCase):
user_factory = factories.UserFactory
def create_request(self, method='get', *, url='/', user=None, auth=True, **kwargs):
if not user:
if auth:
user = self.user_factory.create()
else:
user = AnonymousUser()
kwargs['format'] = 'json'
request = getattr(APIRequestFactory(), method)(url, **kwargs)
request.user = user
if auth:
force_authenticate(request, user)
if 'data' in kwargs:
request.DATA = kwargs['data']
return request
|
Delete margin-right class from nav | import React, { Component } from 'react'
import { Link, IndexLink } from 'react-router'
export class Nav extends Component {
constructor(props) {
super(props)
}
render() {
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav navbar-format">
<li className="navbar-links"><Link activeClassName="nav-active" to="/journal">Journal</Link></li>
<li className="navbar-links"><Link activeClassName="nav-active" to="/dashboard">Dashboard</Link></li>
</ul>
<div className="navbar-header custom-header">
<IndexLink to="/" className="navbar-brand">Journey</IndexLink>
</div>
<ul className="nav navbar-nav navbar-right second navbar-format">
<li className="navbar-links"><Link activeClassName="nav-active" to="/profile">Profile</Link></li>
<li className="navbar-links"><Link activeClassName="nav-active" to="/signin">Sign In</Link></li>
</ul>
</div>
</div>
</nav>
)
}
} | import React, { Component } from 'react'
import { Link, IndexLink } from 'react-router'
export class Nav extends Component {
constructor(props) {
super(props)
}
render() {
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav navbar-format">
<li className="navbar-links"><Link activeClassName="nav-active" to="/journal">Journal</Link></li>
<li className="navbar-links"><Link activeClassName="nav-active" to="/dashboard">Dashboard</Link></li>
</ul>
<div className="navbar-header custom-header">
<IndexLink to="/" className="navbar-brand">Journey</IndexLink>
</div>
<ul className="nav navbar-nav navbar-right second navbar-format margin-right">
<li className="navbar-links"><Link activeClassName="nav-active" to="/profile">Profile</Link></li>
<li className="navbar-links"><Link activeClassName="nav-active" to="/signin">Sign In</Link></li>
</ul>
</div>
</div>
</nav>
)
}
} |
Add route to own profile | var winston = require('winston');
var path = require('path');
global.APP_NAME = "proxtop";
global.PROXER_BASE_URL = "https://proxer.me";
global.INDEX_LOCATION = __dirname + "../../index.html";
global.PROXER_PATHS = {
ROOT: '/',
LOGIN: '/component/user/?task=user.login',
WATCHLIST: '/ucp?s=reminder',
OWN_PROFILE: '/user'
};
try {
global.APP_DIR = path.join(require("app").getPath("appData"), APP_NAME);
} catch(e) {
global.APP_DIR = path.join(__dirname, '..', '..', APP_NAME);
}
var logPath = path.join(APP_DIR, "app.log");
console.log("Setting logfile to " + logPath);
global.LOG = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'silly',
timestamp: function() {
return new Date();
},
formatter: function(options) {
return '[' + options.level.toLowerCase() + '][' + options.timestamp() + '] ' +
(undefined !== options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' )
}
}),
new (winston.transports.File)({
filename: logPath
})
]
});
| var winston = require('winston');
var path = require('path');
global.APP_NAME = "proxtop";
global.PROXER_BASE_URL = "https://proxer.me";
global.INDEX_LOCATION = __dirname + "../../index.html";
global.PROXER_PATHS = {
ROOT: '/',
LOGIN: '/component/user/?task=user.login',
WATCHLIST: '/ucp?s=reminder'
};
try {
global.APP_DIR = path.join(require("app").getPath("appData"), APP_NAME);
} catch(e) {
global.APP_DIR = path.join(__dirname, '..', '..', APP_NAME);
}
var logPath = path.join(APP_DIR, "app.log");
console.log("Setting logfile to " + logPath);
global.LOG = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'silly',
timestamp: function() {
return new Date();
},
formatter: function(options) {
return '[' + options.level.toLowerCase() + '][' + options.timestamp() + '] ' +
(undefined !== options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' )
}
}),
new (winston.transports.File)({
filename: logPath
})
]
});
|
Split up the tests for AuthorizationToken | from django.test import TestCase
from django.contrib.auth.models import User
from doac.models import AuthorizationToken, Client, RefreshToken, Scope
class TestAuthorizationTokenModel(TestCase):
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclient.save()
self.scope = Scope(short_name="test", full_name="Test Scope", description="Scope for testing")
self.scope.save()
self.user = User(username="test", password="test", email="[email protected]")
self.user.save()
self.token = AuthorizationToken(client=self.oclient, user=self.user)
self.token.save()
self.token.scope = [self.scope]
self.token.save()
def test_unicode(self):
self.assertEqual(unicode(self.token), self.token.token)
def test_generate_refresh_token_creates(self):
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsInstance(rt, RefreshToken)
def test_generate_refresh_token_no_create_twice(self):
self.token.generate_refresh_token()
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
def test_generate_refresh_token_never_creates_twice(self):
self.token.generate_refresh_token()
self.token.is_active = True
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
| from django.test import TestCase
from django.contrib.auth.models import User
from doac.models import AuthorizationToken, Client, RefreshToken, Scope
class TestAuthorizationTokenModel(TestCase):
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclient.save()
self.scope = Scope(short_name="test", full_name="Test Scope", description="Scope for testing")
self.scope.save()
self.user = User(username="test", password="test", email="[email protected]")
self.user.save()
self.token = AuthorizationToken(client=self.oclient, user=self.user)
self.token.save()
self.token.scope = [self.scope]
self.token.save()
def test_unicode(self):
self.assertEqual(unicode(self.token), self.token.token)
def test_generate_refresh_token(self):
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsInstance(rt, RefreshToken)
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
self.token.is_active = True
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
|
Use absolute path for config file so it works with apps like Hazel | from os import path
from ConfigParser import ConfigParser
import requests
import sys
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
return None
config_file = '%s/config.ini' % path.dirname(path.dirname(path.abspath(__file__)))
if not path.exists(config_file):
return None
config = ConfigParser()
config.read(config_file)
if('MapQuest' not in config.sections()):
return None
key = config.get('MapQuest', 'key')
try:
r = requests.get('https://open.mapquestapi.com/nominatim/v1/reverse.php?key=%s&lat=%s&lon=%s&format=json' % (key, lat, lon))
return r.json()
except requests.exceptions.RequestException as e:
print e
return None
except ValueError as e:
print r.text
print e
return None
def place_name(lat, lon):
geolocation_info = reverse_lookup(lat, lon)
if(geolocation_info is not None):
if('address' in geolocation_info):
address = geolocation_info['address']
if('city' in address):
return address['city']
elif('state' in address):
return address['state']
elif('country' in address):
return address['country']
return None
| from os import path
from ConfigParser import ConfigParser
import requests
import sys
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
return None
if not path.exists('./config.ini'):
return None
config = ConfigParser()
config.read('./config.ini')
if('MapQuest' not in config.sections()):
return None
key = config.get('MapQuest', 'key')
try:
r = requests.get('https://open.mapquestapi.com/nominatim/v1/reverse.php?key=%s&lat=%s&lon=%s&format=json' % (key, lat, lon))
return r.json()
except requests.exceptions.RequestException as e:
print e
return None
except ValueError as e:
print r.text
print e
return None
def place_name(lat, lon):
geolocation_info = reverse_lookup(lat, lon)
if(geolocation_info is not None):
if('address' in geolocation_info):
address = geolocation_info['address']
if('city' in address):
return address['city']
elif('state' in address):
return address['state']
elif('country' in address):
return address['country']
return None
|
Check for parent filterable fields as well as local filterable fields | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, Link
class UserSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'fullname',
'given_name',
'middle_name',
'family_name',
'id'
])
id = ser.CharField(read_only=True, source='_id')
fullname = ser.CharField()
given_name = ser.CharField()
middle_name = ser.CharField(source='middle_names')
family_name = ser.CharField()
suffix = ser.CharField()
date_registered = ser.DateTimeField(read_only=True)
gravatar_url = ser.CharField()
employment_institutions = ser.ListField(source='jobs')
educational_institutions = ser.ListField(source='schools')
social_accounts = ser.DictField(source='social')
links = LinksField({
'html': 'absolute_url',
'nodes': {
'relation': Link('users:user-nodes', kwargs={'pk': '<pk>'})
}
})
class Meta:
type_ = 'users'
def absolute_url(self, obj):
return obj.absolute_url
def update(self, instance, validated_data):
# TODO
pass
class ContributorSerializer(UserSerializer):
local_filterable = frozenset(['bibliographic'])
filterable_fields = frozenset.union(UserSerializer.filterable_fields, local_filterable)
bibliographic = ser.SerializerMethodField()
def get_bibliographic(self, obj):
node = self.context['view'].get_node()
return obj._id in node.visible_contributor_ids
| from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, Link
class UserSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'fullname',
'given_name',
'middle_name',
'family_name',
'id'
])
id = ser.CharField(read_only=True, source='_id')
fullname = ser.CharField()
given_name = ser.CharField()
middle_name = ser.CharField(source='middle_names')
family_name = ser.CharField()
suffix = ser.CharField()
date_registered = ser.DateTimeField(read_only=True)
gravatar_url = ser.CharField()
employment_institutions = ser.ListField(source='jobs')
educational_institutions = ser.ListField(source='schools')
social_accounts = ser.DictField(source='social')
links = LinksField({
'html': 'absolute_url',
'nodes': {
'relation': Link('users:user-nodes', kwargs={'pk': '<pk>'})
}
})
class Meta:
type_ = 'users'
def absolute_url(self, obj):
return obj.absolute_url
def update(self, instance, validated_data):
# TODO
pass
class ContributorSerializer(UserSerializer):
filterable_fields = frozenset(['bibliographic'])
bibliographic = ser.SerializerMethodField()
def get_bibliographic(self, obj):
node = self.context['view'].get_node()
return obj._id in node.visible_contributor_ids
|
Add TODOs on how to expose non-playable tracks | from __future__ import unicode_literals
from mopidy import models
import spotify
def to_track(sp_track):
if not sp_track.is_loaded:
return # TODO Return placeholder "[loading]" track?
if sp_track.error != spotify.ErrorType.OK:
return # TODO Return placeholder "[error]" track?
if sp_track.availability != spotify.TrackAvailability.AVAILABLE:
return # TODO Return placeholder "[unavailable]" track?
# TODO artists
# TODO album
# TODO date from album
# TODO bitrate
return models.Track(
uri=sp_track.link.uri,
name=sp_track.name,
length=sp_track.duration,
track_no=sp_track.index)
def to_playlist(sp_playlist, folders=None, username=None):
if not isinstance(sp_playlist, spotify.Playlist):
return
if not sp_playlist.is_loaded:
return # TODO Return placeholder "[loading]" playlist?
name = sp_playlist.name
if name is None:
name = 'Starred'
# TODO Reverse order of tracks in starred playlists?
if folders is not None:
name = '/'.join(folders + [name])
if username is not None and sp_playlist.owner.canonical_name != username:
name = '%s by %s' % (name, sp_playlist.owner.canonical_name)
tracks = [to_track(sp_track) for sp_track in sp_playlist.tracks]
tracks = filter(None, tracks)
return models.Playlist(
uri=sp_playlist.link.uri,
name=name,
tracks=tracks)
| from __future__ import unicode_literals
from mopidy import models
import spotify
def to_track(sp_track):
if not sp_track.is_loaded:
return
if sp_track.error != spotify.ErrorType.OK:
return
if sp_track.availability != spotify.TrackAvailability.AVAILABLE:
return
# TODO artists
# TODO album
# TODO date from album
# TODO bitrate
return models.Track(
uri=sp_track.link.uri,
name=sp_track.name,
length=sp_track.duration,
track_no=sp_track.index)
def to_playlist(sp_playlist, folders=None, username=None):
if not isinstance(sp_playlist, spotify.Playlist):
return
if not sp_playlist.is_loaded:
return
name = sp_playlist.name
if name is None:
name = 'Starred'
# TODO Reverse order of tracks in starred playlists?
if folders is not None:
name = '/'.join(folders + [name])
if username is not None and sp_playlist.owner.canonical_name != username:
name = '%s by %s' % (name, sp_playlist.owner.canonical_name)
tracks = [to_track(sp_track) for sp_track in sp_playlist.tracks]
tracks = filter(None, tracks)
return models.Playlist(
uri=sp_playlist.link.uri,
name=name,
tracks=tracks)
|
Use cluster length of 3 |
import random
__metaclass__ = type
class Generator:
def __init__(self, data):
if isinstance(data, str):
data = data.split('\n')
self.clusters = []
for item in data:
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
for i in range(len(name) - 2):
self.clusters.append((name[i:i+3], info))
def generate(self, length=5):
length -= 3 # Account for initial cluster and cluster length of 3
valid = False
while not valid:
valid = True
clusters = [random.choice(self.clusters)[0]]
for i in range(length):
random.shuffle(self.clusters)
valid = False
for c in self.clusters:
if c[0][0] == clusters[-1][2]:
valid = True
clusters.append(c[0])
break
if not valid:
break
if clusters[-2] == clusters[-1]:
# Don't allow triple letters
valid = False
break
return (clusters[0][0] + ''.join([c[1:] for c in clusters]))[:length+3]
|
import random
__metaclass__ = type
class Generator:
def __init__(self, data):
if isinstance(data, str):
data = data.split('\n')
self.clusters = []
for item in data:
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
for i in range(len(name) - 1):
self.clusters.append((name[i:i+2], info))
def generate(self, length=5):
length -= 2 # Account for initial cluster and cluster length of 2
valid = False
while not valid:
valid = True
clusters = [random.choice(self.clusters)[0]]
for i in range(length):
random.shuffle(self.clusters)
valid = False
for c in self.clusters:
if c[0][0] == clusters[-1][1]:
valid = True
clusters.append(c[0])
break
if not valid:
break
if clusters[-2] == clusters[-1]:
# Don't allow triple letters
valid = False
break
return clusters[0][0] + ''.join([c[1] for c in clusters])
|
Check if App is running in console :bug: | <?php namespace JarydKrish\ErrorLogger;
use App;
use Backend;
use BackendAuth;
use Illuminate\Foundation\AliasLoader;
use System\Classes\PluginBase;
/**
* ErrorLogger Plugin Information File
*/
class Plugin extends PluginBase
{
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Sentry error logger',
'description' => 'Handles errors. Horrible, horrible errors.',
'author' => 'Jaryd Krishnan',
'icon' => 'icon-bug'
];
}
/**
* Boot method, called right before the request route.
*
* @return array
*/
public function boot()
{
if (!App::runningInConsole()) {
$this->setSentryHandler();
}
}
public function setSentryHandler()
{
// Register the service provider
App::register(\Sentry\SentryLaravel\SentryLaravelServiceProvider::class);
// Add the alias
AliasLoader::getInstance()->alias('Sentry', \Sentry\SentryLaravel\SentryFacade::class);
// On error, capture the exception and send to Sentry
App::error(function($exception) {
$sentry = App::make('sentry');
if (BackendAuth::check()) {
$user = BackendAuth::getUser();
$sentry->user_context([
'email' => $user->email,
'id' => $user->id,
'login' => $user->login
]);
}
$sentry->captureException($exception);
});
}
}
| <?php namespace JarydKrish\ErrorLogger;
use App;
use Backend;
use BackendAuth;
use Illuminate\Foundation\AliasLoader;
use System\Classes\PluginBase;
/**
* ErrorLogger Plugin Information File
*/
class Plugin extends PluginBase
{
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'Sentry error logger',
'description' => 'Handles errors. Horrible, horrible errors.',
'author' => 'Jaryd Krishnan',
'icon' => 'icon-bug'
];
}
/**
* Boot method, called right before the request route.
*
* @return array
*/
public function boot()
{
$this->setSentryHandler();
}
public function setSentryHandler()
{
// Register the service provider
App::register(\Sentry\SentryLaravel\SentryLaravelServiceProvider::class);
// Add the alias
AliasLoader::getInstance()->alias('Sentry', \Sentry\SentryLaravel\SentryFacade::class);
// On error, capture the exception and send to Sentry
App::error(function($exception) {
$sentry = App::make('sentry');
if (BackendAuth::check()) {
$user = BackendAuth::getUser();
$sentry->user_context([
'email' => $user->email,
'id' => $user->id,
'login' => $user->login
]);
}
$sentry->captureException($exception);
});
}
}
|
Improve printing of signature and version | #!/usr/bin/env python
#
# Copyright (c) 2017 Ralf Horstmann <[email protected]>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
parse daum ergo bike epp/eup files
"""
from __future__ import print_function
import sys
import eppformat as epp
if __name__ == "__main__":
if (len(sys.argv) > 1):
p = epp.epp_file.parse_stream(open(sys.argv[1], "rb"))
print("signature =", p.signature)
print("version =", p.version)
print(p.header)
if (len(sys.argv) > 2):
limit=int(sys.argv[2])
else:
limit=None
for v in p.data[:limit]:
print(v)
else:
print("usage: eppread <file> [limit]")
sys.exit(1);
| #!/usr/bin/env python
#
# Copyright (c) 2017 Ralf Horstmann <[email protected]>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
parse daum ergo bike epp/eup files
"""
import sys
import eppformat as epp
if __name__ == "__main__":
if (len(sys.argv) > 1):
p = epp.epp_file.parse_stream(open(sys.argv[1], "rb"))
print("signature =", p.signature)
print("version =", p.version)
print(p.header)
if (len(sys.argv) > 2):
limit=int(sys.argv[2])
else:
limit=None
for v in p.data[:limit]:
print(v)
else:
print("usage: eppread <file> [limit]")
sys.exit(1);
|
Fix navbar outside html tags | @extends('main')
@section('head')
<style>
.row
{
margin-top: 5%;
}
#meme
{
display: block;
margin-left: auto;
margin-right: auto;
}
#progress
{
margin-top: 1%;
}
</style>
@endsection
@section('content')
@include('topmemesnav')
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="jumbotron">
@foreach($memes as $meme)
<div class="page-header">
<h1>
{{ $i++ }}: {{ $meme->name }} <small><small>{{ $meme->description }}</small></small>
</h1>
</div>
<div class="">
<img id="meme" class="img-responsive img-thumbnail" title="{{ $meme->name }}" src="{{ '/images/'.$meme->filename }}">
<div class="panel-footer text-center">
<p>Głosów: {{ $meme->codes()->whereNotNull('vote')->count()}}</p>
<p>Procent "Spoko": {{ round($meme->codes()->where('vote', '=', '1')->count() / $meme->codes()->whereNotNull('vote')->count() * 100, 2)}}%</p>
</div>
</div>
@endforeach
</div>
</div>
</div>
@endsection | @extends('main')
@section('head')
<style>
.row
{
margin-top: 5%;
}
#meme
{
display: block;
margin-left: auto;
margin-right: auto;
}
#progress
{
margin-top: 1%;
}
</style>
@endsection
@include('topmemesnav')
@section('content')
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="jumbotron">
@foreach($memes as $meme)
<div class="page-header">
<h1>
{{ $i++ }}: {{ $meme->name }} <small><small>{{ $meme->description }}</small></small>
</h1>
</div>
<div class="">
<img id="meme" class="img-responsive img-thumbnail" title="{{ $meme->name }}" src="{{ '/images/'.$meme->filename }}">
<div class="panel-footer text-center">
<p>Głosów: {{ $meme->codes()->whereNotNull('vote')->count()}}</p>
<p>Procent "Spoko": {{ round($meme->codes()->where('vote', '=', '1')->count() / $meme->codes()->whereNotNull('vote')->count() * 100, 2)}}%</p>
</div>
</div>
@endforeach
</div>
</div>
</div>
@endsection |
Fix padding error in sample app view data | <?php
class ViewData
{
/**
* @var int $time
*/
private $time;
/**
* @var float $distance
*/
private $distance;
const SPEED_PRECISION = 2;
public function __construct()
{
$this->time = $_POST['time'];
$this->distance = $_POST['distance'];
}
/**
* @return int
*/
public function getTime()
{
return $this->time;
}
/**
* @return float
*/
public function getDistance()
{
return $this->distance;
}
/**
* @return bool
*/
public function hasSentData()
{
return isset($this->time) && isset($this->distance);
}
/**
* @return string
*/
public function getAveragePace()
{
return $this->decimalToMinuteString($this->time / $this->distance);
}
/**
* @return string
*/
public function getAverageSpeed()
{
return round($this->distance / ($this->time / 60), self::SPEED_PRECISION);
}
/**
* @param float $timeAsDecimal
* @return string
*/
private function decimalToMinuteString(float $timeAsDecimal)
{
$whole = floor($timeAsDecimal);
$decimal = $timeAsDecimal - $whole;
$roundedMinutes = round($decimal * 60, 0);
$minutes = str_pad($roundedMinutes, 2, "0", STR_PAD_LEFT);
return "{$whole}:{$minutes}";
}
}
| <?php
class ViewData
{
/**
* @var int $time
*/
private $time;
/**
* @var float $distance
*/
private $distance;
const SPEED_PRECISION = 2;
public function __construct()
{
$this->time = $_POST['time'];
$this->distance = $_POST['distance'];
}
/**
* @return int
*/
public function getTime()
{
return $this->time;
}
/**
* @return float
*/
public function getDistance()
{
return $this->distance;
}
/**
* @return bool
*/
public function hasSentData()
{
return isset($this->time) && isset($this->distance);
}
/**
* @return string
*/
public function getAveragePace()
{
return $this->decimalToMinuteString($this->time / $this->distance);
}
/**
* @return string
*/
public function getAverageSpeed()
{
return round($this->distance / ($this->time / 60), self::SPEED_PRECISION);
}
/**
* @param float $timeAsDecimal
* @return string
*/
private function decimalToMinuteString(float $timeAsDecimal)
{
$whole = floor($timeAsDecimal);
$decimal = $timeAsDecimal - $whole;
$roundedMinutes = round($decimal * 60, 0);
$minutes = str_pad($roundedMinutes, 2, "0");
return "{$whole}:{$minutes}";
}
}
|
Fix a bug launching a posix executable | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
import os
import subprocess
def launch_executable(executable, args, cwd, env=None):
"""
Launches an executable with optional arguments
:param executable:
A unicode string of an executable
:param args:
A list of unicode strings to pass as arguments to the executable
:param cwd:
A unicode string of the working directory to open the executable to
:param env:
A dict of unicode strings for a custom environmental variables to set
"""
subprocess_args = [executable]
if args is not None:
subprocess_args.extend(args)
if sys.version_info >= (3,):
subprocess_env = dict(os.environ)
else:
subprocess_env = {}
for key, value in os.environ.items():
subprocess_env[key.decode('utf-8', 'replace')] = value.decode('utf-8', 'replace')
if env:
for key, value in env.items():
subprocess_env[key] = value
if sys.version_info < (3,):
encoded_args = []
for arg in subprocess_args:
encoded_args.append(arg.encode('utf-8'))
subprocess_args = encoded_args
encoded_env = {}
for key, value in subprocess_env.items():
encoded_env[key.encode('utf-8')] = value.encode('utf-8')
subprocess_env = encoded_env
cwd = cwd.encode('utf-8')
subprocess.Popen(subprocess_args, env=subprocess_env, cwd=cwd)
| # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
import os
import subprocess
def launch_executable(executable, args, cwd, env=None):
"""
Launches an executable with optional arguments
:param executable:
A unicode string of an executable
:param args:
A list of unicode strings to pass as arguments to the executable
:param cwd:
A unicode string of the working directory to open the executable to
:param env:
A dict of unicode strings for a custom environmental variables to set
"""
subprocess_args = [executable]
subprocess_args.extend(args)
if sys.version_info >= (3,):
subprocess_env = dict(os.environ)
else:
subprocess_env = {}
for key, value in os.environ.items():
subprocess_env[key.decode('utf-8', 'replace')] = value.decode('utf-8', 'replace')
if env:
for key, value in env.items():
subprocess_env[key] = value
if sys.version_info < (3,):
encoded_args = []
for arg in subprocess_args:
encoded_args.append(arg.encode('utf-8'))
subprocess_args = encoded_args
encoded_env = {}
for key, value in subprocess_env.items():
encoded_env[key.encode('utf-8')] = value.encode('utf-8')
subprocess_env = encoded_env
cwd = cwd.encode('utf-8')
subprocess.Popen(subprocess_args, env=subprocess_env, cwd=cwd)
|
Correct which to not through...
...this was the whole point of it. | var spawn = require('child_process').spawn;
var _which = require('which');
function which (prog) {
try {
return _which.sync(prog);
} catch (err) {
if (err.message === 'not found: ' + prog) {
return null;
} else {
throw err;
}
}
}
module.exports.transformer = childProcTransformer;
module.exports.transform = childProcTransform;
function childProcTransformer(prog, transformer) {
var cmd = which(prog);
if (!cmd) return noopTransformer;
return subTransformer;
function subTransformer(options) {
options.cmd = cmd;
return transformer(options);
}
}
function childProcTransform(argv, stream, callback) {
var child = spawn(argv[0], argv.slice(1));
if (stream) {
stream.pipe(child.stdin);
}
child.on('exit', exited);
child.on('error', passError);
child.stdin.on('error', passError);
function exited(code) {
if (code !== 0) {
console.error(
'child exited abnormally (code %j): %s',
code, argv.join(' ') // TODO: quote better
);
}
}
function passError(err) {
if (err.errno !== 'EPIPE') {
child.stdout.emit('error', err);
}
}
callback(null, child.stdout);
}
function noopTransformer() {
return noopTransform;
}
function noopTransform(info, stream, callback) {
callback(null);
}
| var spawn = require('child_process').spawn;
var which = require('which');
module.exports.transformer = childProcTransformer;
module.exports.transform = childProcTransform;
function childProcTransformer(prog, transformer) {
var cmd = which.sync(prog);
if (!cmd) return noopTransformer;
return subTransformer;
function subTransformer(options) {
options.cmd = cmd;
return transformer(options);
}
}
function childProcTransform(argv, stream, callback) {
var child = spawn(argv[0], argv.slice(1));
if (stream) {
stream.pipe(child.stdin);
}
child.on('exit', exited);
child.on('error', passError);
child.stdin.on('error', passError);
function exited(code) {
if (code !== 0) {
console.error(
'child exited abnormally (code %j): %s',
code, argv.join(' ') // TODO: quote better
);
}
}
function passError(err) {
if (err.errno !== 'EPIPE') {
child.stdout.emit('error', err);
}
}
callback(null, child.stdout);
}
function noopTransformer() {
return noopTransform;
}
function noopTransform(info, stream, callback) {
callback(null);
}
|
Add link to club name | <h1>打卡紀錄</h1>
<ul class="list-group">
@forelse($records as $record)
<li class="list-group-item">
<div>
<h4>{{ link_to_route('clubs.show', $record->club->name, $record->club) }}
{!! $record->club->clubType->tag ?? '' !!}
@if(!$record->club->is_counted)
<span class='badge badge-default'>不列入集點</span>
@endif
</h4>
<small>
{{ $record->created_at }}
({{ (new \Carbon\Carbon($record->created_at))->diffForHumans() }})
</small>
</div>
</li>
@empty
<li class="list-group-item">
<div>
尚無打卡紀錄,快去打卡吧
</div>
</li>
@endforelse
</ul>
| <h1>打卡紀錄</h1>
<ul class="list-group">
@forelse($records as $record)
<li class="list-group-item">
<div>
<h4>{{ $record->club->name }}
{!! $record->club->clubType->tag ?? '' !!}
@if(!$record->club->is_counted)
<span class='badge badge-default'>不列入集點</span>
@endif
</h4>
<small>
{{ $record->created_at }}
({{ (new \Carbon\Carbon($record->created_at))->diffForHumans() }})
</small>
</div>
</li>
@empty
<li class="list-group-item">
<div>
尚無打卡紀錄,快去打卡吧
</div>
</li>
@endforelse
</ul>
|
Revert "Make tick thicker to facilitate hovering"
This reverts commit a90e6f1f92888e0904bd50d67993ab23ccec1a38. | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
scale: {useRawDomain: false},
mark: {
tickThickness: 2
}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
mark: {
tickThickness: 2
}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
|
Increase sleep value to 2s | <?php
namespace RabbitMQBundle\Tests\Controller;
use AppBundle\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;
class RabbitMQControllerTest extends WebTestCase
{
protected $entityManager;
public function __construct()
{
self::bootKernel(array('environment' => 'test', 'debug' => 'true'));
$this->entityManager = self::$kernel->getContainer()->get('doctrine')->getManager();
}
public function testRabbitMQ()
{
$client = static::createClient();
$post = new Post();
$post->setTitle('Lorem ipsum dolor');
$post->setSlug('Lorem-ipsum-dolor');
$post->setSummary('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
$post->setContent('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
$post->setAuthorEmail('[email protected]');
$this->entityManager->persist($post);
$this->entityManager->flush();
$client->request('POST', '/post/generate_pdf/' . $post->getId());
$this->assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
$pdfName = json_decode($client->getResponse()->getContent(), true)['pdfName'];
$this->entityManager->remove($post);
$this->entityManager->flush();
$pdfPath = self::$kernel->getRootDir() . '/../web/downloads/pdf/' . $pdfName . '.pdf';
sleep(2);
$this->assertTrue(file_exists($pdfPath));
unlink($pdfPath);
}
}
| <?php
namespace RabbitMQBundle\Tests\Controller;
use AppBundle\Entity\Post;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;
class RabbitMQControllerTest extends WebTestCase
{
protected $entityManager;
public function __construct()
{
self::bootKernel(array('environment' => 'test', 'debug' => 'true'));
$this->entityManager = self::$kernel->getContainer()->get('doctrine')->getManager();
}
public function testRabbitMQ()
{
$client = static::createClient();
$post = new Post();
$post->setTitle('Lorem ipsum dolor');
$post->setSlug('Lorem-ipsum-dolor');
$post->setSummary('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
$post->setContent('Lorem ipsum dolor sit amet consectetur adipiscing elit Urna nisl sollicitudin');
$post->setAuthorEmail('[email protected]');
$this->entityManager->persist($post);
$this->entityManager->flush();
$client->request('POST', '/post/generate_pdf/' . $post->getId());
$this->assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
$pdfName = json_decode($client->getResponse()->getContent(), true)['pdfName'];
$this->entityManager->remove($post);
$this->entityManager->flush();
$pdfPath = self::$kernel->getRootDir() . '/../web/downloads/pdf/' . $pdfName . '.pdf';
sleep(1);
$this->assertTrue(file_exists($pdfPath));
unlink($pdfPath);
}
}
|
Use dict comprehension instead of dict([...]) | 'Accounts'
from __future__ import unicode_literals
from .... import ProResource, RelatedResourceMixin
import six
import sys
class Account(RelatedResourceMixin, ProResource):
'Abstraction of Accounts resource in duedil v3 pro api'
attribute_names = [
'uri',
'date',
'type'
]
account_classes = {
'financial': 'pro.company.accounts.financial.AccountDetailsFinancial',
'gaap': 'pro.company.accounts.gaap.AccountDetailsGAAP',
'ifrs': 'pro.company.accounts.ifrs.AccountDetailsIFRS',
'insurance': 'pro.company.accounts.insurance.AccountDetailsInsurance',
'statutory': 'pro.company.accounts.statutory.AccountDetailsStatutory',
}
full_endpoint = True
def __iter__(self):
return iter({i: getattr(self, i) for i in self.attribute_names})
@property
def path(self):
return self.uri.split('/', 5)[-1].rsplit('/', 1)[0]
@property
def details(self):
resource = self.account_classes[self.type]
if isinstance(resource, six.string_types):
module, resource = resource.rsplit('.', 1)
resource = getattr(sys.modules['duedil.resources.{0!s}'.format(module)], resource)
resource_obj = self.load_related('details', resource, self.full_endpoint)
resource_obj.path = '{0}'.format(self.path)
resource_obj.loaded = True
return resource_obj
| 'Accounts'
from __future__ import unicode_literals
from .... import ProResource, RelatedResourceMixin
import six
import sys
class Account(RelatedResourceMixin, ProResource):
'Abstraction of Accounts resource in duedil v3 pro api'
attribute_names = [
'uri',
'date',
'type'
]
account_classes = {
'financial': 'pro.company.accounts.financial.AccountDetailsFinancial',
'gaap': 'pro.company.accounts.gaap.AccountDetailsGAAP',
'ifrs': 'pro.company.accounts.ifrs.AccountDetailsIFRS',
'insurance': 'pro.company.accounts.insurance.AccountDetailsInsurance',
'statutory': 'pro.company.accounts.statutory.AccountDetailsStatutory',
}
full_endpoint = True
def __iter__(self):
return iter(dict([(i,getattr(self, i)) for i in self.attribute_names]))
@property
def path(self):
return self.uri.split('/', 5)[-1].rsplit('/', 1)[0]
@property
def details(self):
resource = self.account_classes[self.type]
if isinstance(resource, six.string_types):
module, resource = resource.rsplit('.', 1)
resource = getattr(sys.modules['duedil.resources.{0!s}'.format(module)], resource)
resource_obj = self.load_related('details', resource, self.full_endpoint)
resource_obj.path = '{0}'.format(self.path)
resource_obj.loaded = True
return resource_obj
|
Allow custom endpoint in persona.verifier. | <?php
namespace Mozilla\Persona\Provider\Laravel;
use Auth;
use Illuminate\Auth\Guard;
use Illuminate\Support\ServiceProvider;
use Mozilla\Persona\Identity;
use Mozilla\Persona\Verifier;
use Request;
class PersonaServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('mozilla/persona');
Auth::extend(
'persona',
function () {
return new Guard(new PersonaUserProvider, $this->app->make('session'));
}
);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(
'persona.verifier',
function ($app, $endpoint) {
$audience = sprintf('%s://%s:%u', Request::getScheme(), Request::getHost(), Request::getPort());
return (empty($endpoint)) ? new Verifier($audience) : new Verifier($audience, $endpoint);
}
);
$this->app->bind(
'persona.identity',
function ($app, $assertion) {
return new Identity($assertion);
}
);
$this->app->bind(
'persona.user',
function ($app, $attributes) {
return new PersonaUser($attributes);
}
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('persona.verifier', 'persona.identity', 'persona.user');
}
}
| <?php
namespace Mozilla\Persona\Provider\Laravel;
use Auth;
use Illuminate\Auth\Guard;
use Illuminate\Support\ServiceProvider;
use Mozilla\Persona\Identity;
use Mozilla\Persona\Verifier;
use Request;
class PersonaServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('mozilla/persona');
Auth::extend(
'persona',
function () {
return new Guard(new PersonaUserProvider, $this->app->make('session'));
}
);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(
'persona.verifier',
function ($app) {
$audience = sprintf('%s://%s:%u', Request::getScheme(), Request::getHost(), Request::getPort());
return new Verifier($audience);
}
);
$this->app->bind(
'persona.identity',
function ($app, $assertion) {
return new Identity($assertion);
}
);
$this->app->bind(
'persona.user',
function ($app, $attributes) {
return new PersonaUser($attributes);
}
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('persona.verifier', 'persona.identity');
}
}
|
Add argparse as a dependency | import os
from setuptools import setup
import mando
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fobj:
readme = fobj.read()
setup(name='mando',
version=mando.__version__,
author='Michele Lacchia',
author_email='[email protected]',
url='https://mando.readthedocs.org/',
download_url='https://pypi.python.org/mando/',
license='MIT',
description='Create Python CLI apps with little to no effort at all!',
platforms='any',
long_description=readme,
packages=['mando', 'mando.tests'],
test_suite='mando.tests',
install_requires=['argparse'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'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.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
]
)
| import os
from setuptools import setup
import mando
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fobj:
readme = fobj.read()
setup(name='mando',
version=mando.__version__,
author='Michele Lacchia',
author_email='[email protected]',
url='https://mando.readthedocs.org/',
download_url='https://pypi.python.org/mando/',
license='MIT',
description='Create Python CLI apps with little to no effort at all!',
platforms='any',
long_description=readme,
packages=['mando', 'mando.tests'],
test_suite='mando.tests',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'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.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
]
)
|
Remove back authorization for snippets | package org.crunchytorch.coddy.snippet.api;
import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity;
import org.crunchytorch.coddy.snippet.service.SnippetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Component
@Path("/snippet")
public class Snippet {
@Autowired
private SnippetService snippetService;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<SnippetEntity> getSnippets(@DefaultValue("0") @QueryParam("from") final int from,
@DefaultValue("10") @QueryParam("size") final int size) {
return snippetService.getEntity(from, size);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("{id}")
public SnippetEntity getSnippet(@PathParam("id") String id) {
return snippetService.getSnippet(id);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void create(SnippetEntity snippet) {
snippetService.create(snippet);
}
}
| package org.crunchytorch.coddy.snippet.api;
import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity;
import org.crunchytorch.coddy.snippet.service.SnippetService;
import org.crunchytorch.coddy.user.filter.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Component
@AuthorizationFilter
@Path("/snippet")
public class Snippet {
@Autowired
private SnippetService snippetService;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<SnippetEntity> getSnippets(@DefaultValue("0") @QueryParam("from") final int from,
@DefaultValue("10") @QueryParam("size") final int size) {
return snippetService.getEntity(from, size);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("{id}")
public SnippetEntity getSnippet(@PathParam("id") String id) {
return snippetService.getSnippet(id);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void create(SnippetEntity snippet) {
snippetService.create(snippet);
}
}
|
Allow signal handlers to be disabled to run in subthread | import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
| import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
Add learning test for sinon sandbox. |
define(
[
'chai',
'sinon',
'jquery'
],
function(chai, undefined, undefined) {
var assert = chai.assert;
// Assertions
var assertCleanXHR = function() {
assert.isNotFunction(
XMLHttpRequest.restore,
'XMLHttpRequest lacks method `restore`.'
);
};
var assertModifiedXHR = function() {
assert.throws(
assertCleanXHR,
Error, null,
'Sinon server modifies XHR.'
);
};
// Tests
describe('sinon', function() {
it('should be an object', function() {
assert.isObject(sinon, 'Check sinon object.');
});
describe('fakeServer', function() {
var server;
beforeEach(function() {
server = sinon.fakeServer.create();
});
afterEach(function() {
if (server.restore) server.restore();
});
it('should create a server object', function() {
assert.isObject(server, 'Check server object.');
});
it('should respond to requests', function(done) {
server.respondWith('Some response text.');
var success = function() {
done();
};
var error = function() {
throw new Error("Failed Ajax request.");
};
$.ajax('/fake-url.json', {
success: success,
error: error
});
server.respond();
});
});
describe('Sandbox', function() {
it('should not affect XHR when unused', function() {
assertCleanXHR();
});
it('should allow usage of server', sinon.test(function() {
var server = sinon.fakeServer.create();
assertModifiedXHR();
}));
it('should clean up server in previous test', function() {
assertCleanXHR();
});
});
});
});
|
define(
[
'chai',
'sinon',
'jquery'
],
function(chai, undefined, undefined) {
var assert = chai.assert;
describe('sinon', function() {
it('should be an object', function() {
assert.isObject(sinon, 'Check sinon object.');
});
describe('fakeServer', function() {
var server;
beforeEach(function() {
server = sinon.fakeServer.create();
});
afterEach(function() {
if (server.restore) server.restore();
});
it('should create a server object', function() {
assert.isObject(server, 'Check server object.');
});
it('should respond to requests', function(done) {
server.respondWith('Some response text.');
var success = function() {
done();
};
var error = function() {
throw new Error("Failed Ajax request.");
};
$.ajax('/fake-url.json', {
success: success,
error: error
});
server.respond();
});
});
});
});
|
FIX only pass S52 test | from expects import expect, equal
from primestg.report import Report
with description('Report S52 example'):
with before.all:
self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048'
self.report = {}
with open(self.data_filename) as data_file:
self.report = Report(data_file)
with it('generates expected results for a value of the first line of '
'first remote terminal unit'):
expected_first_value = dict(
ae=0.0,
bc='00',
ai=8717.0,
r1=43.0,
r2=0.0,
r3=0.0,
r4=142.0,
timestamp='2020-09-14 01:00:00',
rt_unit_name='MRTR000000822522',
name='MRTL000006609121',
magn=1
)
rt_unit = list(self.report.rt_units)[0]
line = list(rt_unit.lines)[0]
values = line.values
first_value_first_line = {}
for x in values:
if x['timestamp'] == expected_first_value['timestamp']:
first_value_first_line = x
expect(first_value_first_line)\
.to(equal(expected_first_value))
| from expects import expect, equal
from primestg.report import Report
with fdescription('Report S52 example'):
with before.all:
self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048'
self.report = {}
with open(self.data_filename) as data_file:
self.report = Report(data_file)
with it('generates expected results for a value of the first line of '
'first remote terminal unit'):
expected_first_value = dict(
ae=0.0,
bc='00',
ai=8717.0,
r1=43.0,
r2=0.0,
r3=0.0,
r4=142.0,
timestamp='2020-09-14 01:00:00',
rt_unit_name='MRTR000000822522',
name='MRTL000006609121',
magn=1
)
rt_unit = list(self.report.rt_units)[0]
line = list(rt_unit.lines)[0]
values = line.values
first_value_first_line = {}
for x in values:
if x['timestamp'] == expected_first_value['timestamp']:
first_value_first_line = x
expect(first_value_first_line)\
.to(equal(expected_first_value))
|
Add tests for login oauth links | # coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if are links to oauth/oauth2 providers
providers = app.config['OAUTH_CREDENTIALS'].keys()
for provider in providers:
assert 'href="/login/{}'.format(provider) in resp.data
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data
def test_login_providers(self):
# test if links to the ouauth/oauth2 providers
providers = app.config['OAUTH_CREDENTIALS'].keys()
for provider in providers:
resp = self.app.get('/login/{}'.format(provider))
assert resp.status_code == 200
# test if unauthorized provider returns 404
resp = self.app.get('/login/anything_else')
assert resp.status_code == 404
| # coding: utf-8
from findaconf import app, db
from findaconf.tests.config import set_app, unset_app
from unittest import TestCase
class TestSiteRoutes(TestCase):
def setUp(self):
self.app = set_app(app, db)
def tearDown(self):
unset_app(db)
# test routes from blueprint/site.py
def test_index(self):
resp = self.app.get('/')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_find(self):
resp = self.app.get('/find', data={'query': 'sociology',
'month': 'February',
'year': 2015,
'region': 'Europe',
'location': 'University of Essex'})
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
def test_login(self):
# test if login page exists
resp = self.app.get('/login')
assert resp.status_code == 200
assert resp.mimetype == 'text/html'
# test if is there a link to login in the home page
resp = self.app.get('/')
assert 'href="/login"' in resp.data |
Replace bind with fat arrow syntax | import request from 'superagent';
import { Promise } from 'bluebird';
import { isValidToken } from './jwt';
export default class TokenClient {
constructor(config) {
this.user = config.user;
this.password = config.password;
this.routes = config.routes;
this.token = config.token;
}
getValidToken() {
return new Promise(this.tokenPromiseHandler.bind(this));
}
tokenPromiseHandler(resolve, reject) {
if (isValidToken(this.token)) {
resolve(this.token);
} else {
this.requestToken(this.user, this.password, (err, token) => {
if (err) {
reject(err);
} else {
this.token = token;
resolve(this.token);
}
});
}
}
requestToken(user, pass, callback) {
request.post(this.routes.token)
.send({
'user' : user,
'password' : pass
})
.end(function(err, result) {
if (err) {
callback(err);
} else if (!isValidToken(result.body.token)) {
if (result.serverError) {
callback('Server error: '+ result.status );
} else {
callback('Server returned invalid JWT token');
}
} else {
callback(null, result.body.token);
}
});
}
}
| import request from 'superagent';
import { Promise } from 'bluebird';
import { isValidToken } from './jwt';
export default class TokenClient {
constructor(config) {
this.user = config.user;
this.password = config.password;
this.routes = config.routes;
this.token = config.token;
}
getValidToken() {
return new Promise(this.tokenPromiseHandler.bind(this));
}
tokenPromiseHandler(resolve, reject) {
if (isValidToken(this.token)) {
resolve(this.token);
} else {
this.requestToken(this.user, this.password, function(err, token) {
if (err) {
reject(err);
} else {
this.token = token;
resolve(this.token);
}
}.bind(this));
}
}
requestToken(user, pass, callback) {
request.post(this.routes.token)
.send({
'user' : user,
'password' : pass
})
.end(function(err, result) {
if (err) {
callback(err);
} else if (!isValidToken(result.body.token)) {
if (result.serverError) {
callback('Server error: '+ result.status );
} else {
callback('Server returned invalid JWT token');
}
} else {
callback(null, result.body.token);
}
});
}
}
|
Remove leading whitespace in constructor arg | <?php
namespace Avalanche\Bundle\ImagineBundle\Imagine\Filter;
use Avalanche\Bundle\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Filter\FilterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FilterManager
{
private $filters;
private $loaders;
private $services;
public function __construct(array $filters = array())
{
$this->filters = $filters;
$this->loaders = array();
$this->services = array();
}
public function addLoader($name, LoaderInterface $loader)
{
$this->loaders[$name] = $loader;
}
public function get($filter)
{
if (!isset($this->filters[$filter])) {
throw new InvalidArgumentException(sprintf(
'Could not find image filter "%s"', $filter
));
}
$options = $this->filters[$filter];
if (!isset($options['type'])) {
throw new InvalidArgumentException(sprintf(
'Filter type for "%s" image filter must be specified', $filter
));
}
if (!isset($this->loaders[$options['type']])) {
throw new InvalidArgumentException(sprintf(
'Could not find loader for "%s" filter type', $options['type']
));
}
if (!isset($options['options'])) {
throw new InvalidArgumentException(sprintf(
'Options for filter type "%s" must be specified', $filter
));
}
return $this->loaders[$options['type']]->load($options['options']);
}
}
| <?php
namespace Avalanche\Bundle\ImagineBundle\Imagine\Filter;
use Avalanche\Bundle\ImagineBundle\Imagine\Filter\Loader\LoaderInterface;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Filter\FilterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FilterManager
{
private $filters;
private $loaders;
private $services;
public function __construct( array $filters = array())
{
$this->filters = $filters;
$this->loaders = array();
$this->services = array();
}
public function addLoader($name, LoaderInterface $loader)
{
$this->loaders[$name] = $loader;
}
public function get($filter)
{
if (!isset($this->filters[$filter])) {
throw new InvalidArgumentException(sprintf(
'Could not find image filter "%s"', $filter
));
}
$options = $this->filters[$filter];
if (!isset($options['type'])) {
throw new InvalidArgumentException(sprintf(
'Filter type for "%s" image filter must be specified', $filter
));
}
if (!isset($this->loaders[$options['type']])) {
throw new InvalidArgumentException(sprintf(
'Could not find loader for "%s" filter type', $options['type']
));
}
if (!isset($options['options'])) {
throw new InvalidArgumentException(sprintf(
'Options for filter type "%s" must be specified', $filter
));
}
return $this->loaders[$options['type']]->load($options['options']);
}
}
|
Convert to flags=value for future compatibility | import re
from mitmproxy import exceptions
from mitmproxy import filt
class Replace:
def __init__(self):
self.lst = []
def configure(self, options, updated):
"""
.replacements is a list of tuples (fpat, rex, s):
fpatt: a string specifying a filter pattern.
rex: a regular expression, as bytes.
s: the replacement string, as bytes
"""
lst = []
for fpatt, rex, s in options.replacements:
cpatt = filt.parse(fpatt)
if not cpatt:
raise exceptions.OptionsError(
"Invalid filter pattern: %s" % fpatt
)
try:
re.compile(rex)
except re.error as e:
raise exceptions.OptionsError(
"Invalid regular expression: %s - %s" % (rex, str(e))
)
lst.append((rex, s, cpatt))
self.lst = lst
def execute(self, f):
for rex, s, cpatt in self.lst:
if cpatt(f):
if f.response:
f.response.replace(rex, s, flags=re.DOTALL)
else:
f.request.replace(rex, s, flags=re.DOTALL)
def request(self, flow):
if not flow.reply.has_message:
self.execute(flow)
def response(self, flow):
if not flow.reply.has_message:
self.execute(flow)
| import re
from mitmproxy import exceptions
from mitmproxy import filt
class Replace:
def __init__(self):
self.lst = []
def configure(self, options, updated):
"""
.replacements is a list of tuples (fpat, rex, s):
fpatt: a string specifying a filter pattern.
rex: a regular expression, as bytes.
s: the replacement string, as bytes
"""
lst = []
for fpatt, rex, s in options.replacements:
cpatt = filt.parse(fpatt)
if not cpatt:
raise exceptions.OptionsError(
"Invalid filter pattern: %s" % fpatt
)
try:
re.compile(rex)
except re.error as e:
raise exceptions.OptionsError(
"Invalid regular expression: %s - %s" % (rex, str(e))
)
lst.append((rex, s, cpatt))
self.lst = lst
def execute(self, f):
for rex, s, cpatt in self.lst:
if cpatt(f):
if f.response:
f.response.replace(rex, s, re.DOTALL)
else:
f.request.replace(rex, s, re.DOTALL)
def request(self, flow):
if not flow.reply.has_message:
self.execute(flow)
def response(self, flow):
if not flow.reply.has_message:
self.execute(flow)
|
Remove whitespace before and after link text | <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Utilities\ThemeMods;
use GrottoPress\Jentil\Jentil;
class Colophon extends AbstractThemeMod
{
/**
* @var ThemeMods
*/
private $themeMods;
public function __construct(ThemeMods $theme_mods)
{
$this->themeMods = $theme_mods;
$this->id = \apply_filters('jentil_colophon_mod_id', 'colophon');
$this->default = $this->default();
}
public function get(): string
{
return $this->themeMods->utilities->shortTags->replace(parent::get());
}
private function default(): string
{
return \apply_filters(
'jentil_colophon_mod_default',
\sprintf(
\esc_html__(
'© %1$s %2$s. Built with %3$s on %4$s',
'jentil'
),
'<span itemprop="copyrightYear">{{this_year}}</span>',
'<a class="blog-name" itemprop="url" href="{{site_url}}">'.
'<span itemprop="copyrightHolder">{{site_name}}</span>'.
'</a>',
'<em><a itemprop="url" rel="nofollow" href="'.Jentil::URI.'">'.
Jentil::NAME.
'</a></em>',
'<a itemprop="url" rel="nofollow" href="https://wordpress.org">WordPress</a>.'
)
);
}
}
| <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Utilities\ThemeMods;
use GrottoPress\Jentil\Jentil;
class Colophon extends AbstractThemeMod
{
/**
* @var ThemeMods
*/
private $themeMods;
public function __construct(ThemeMods $theme_mods)
{
$this->themeMods = $theme_mods;
$this->id = \apply_filters('jentil_colophon_mod_id', 'colophon');
$this->default = $this->default();
}
public function get(): string
{
return $this->themeMods->utilities->shortTags->replace(parent::get());
}
private function default(): string
{
return \apply_filters(
'jentil_colophon_mod_default',
\sprintf(
\esc_html__(
'© %1$s %2$s. Built with %3$s on %4$s',
'jentil'
),
'<span itemprop="copyrightYear">{{this_year}}</span>',
'<a class="blog-name" itemprop="url" href="{{site_url}}">
<span itemprop="copyrightHolder">{{site_name}}</span>
</a>',
'<em><a itemprop="url" rel="nofollow" href="'.Jentil::URI.'">'.
Jentil::NAME.
'</a></em>',
'<a itemprop="url" rel="nofollow" href="https://wordpress.org">WordPress</a>.'
)
);
}
}
|
Add req.files to params object | 'use strict';
var passport = require('passport'),
nconf = require('nconf'),
utils = require('../lib/utils'),
geboSchema = require('../schemata/gebo'),
agentSchema = require('../schemata/agent'),
extend = require('extend'),
q = require('q');
module.exports = function(email) {
// Turn the email into a mongo-friend database name
var dbName = utils.ensureDbName(email);
/**
* Receive a request for consideration
*/
exports.request = [
passport.authenticate('bearer', { session: false }),
function(req, res) {
// There might be files attached to the request
var params = req.body;
extend(true, params, req.files);
console.log('request');
console.log(req.body);
console.log(req.user);
console.log(req.authInfo);
console.log('params');
console.log(params);
var action = require('../config/action')(dbName);
//action[req.body.action](req.user, req.body).
action[req.body.action](req.user, params).
then(function(data) {
res.send(data);
}).
catch(function(err) {
console.log(err);
res.send(404, err);
});
}
];
return exports;
};
| 'use strict';
var passport = require('passport'),
nconf = require('nconf'),
utils = require('../lib/utils'),
geboSchema = require('../schemata/gebo'),
agentSchema = require('../schemata/agent'),
q = require('q');
module.exports = function(email) {
// Turn the email into a mongo-friend database name
var dbName = utils.ensureDbName(email);
/**
* Receive a request for consideration
*/
exports.request = [
passport.authenticate('bearer', { session: false }),
function(req, res) {
console.log('request');
console.log(req.body);
console.log(req.user);
console.log(req.authInfo);
var action = require('../config/action')(dbName);
// Convert email address to mongo-friendly DB
// and collection strings
req.user.dbName = utils.getMongoDbName(req.user.dbName);
req.user.collectionName = utils.getMongoCollectionName(req.user.collectionName);
action[req.body.action](req.user, req.body).
then(function(data) {
res.send(data);
}).
catch(function(err) {
console.log(err);
res.send(404, err);
});
}
];
return exports;
};
|
Remove prop mapper from auth wrapper | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import hoistStatics from 'hoist-non-react-statics'
import isEmpty from 'lodash.isempty'
const defaults = {
AuthenticatingComponent: () => null, // dont render anything while authenticating
FailureComponent: undefined,
wrapperDisplayName: 'AuthWrapper',
predicate: x => !isEmpty(x)
}
export default (args) => {
const { AuthenticatingComponent, FailureComponent, wrapperDisplayName, predicate } = {
...defaults,
...args
}
// Wraps the component that needs the auth enforcement
function wrapComponent(DecoratedComponent) {
const displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'
class UserAuthWrapper extends Component {
static displayName = `${wrapperDisplayName}(${displayName})`;
static propTypes = {
authData: PropTypes.any,
isAuthenticating: PropTypes.bool
};
static defaultProps = {
isAuthenticating: false
}
render() {
const { authData, isAuthenticating } = this.props
if (predicate(authData)) {
return <DecoratedComponent {...this.props} />
} else if(isAuthenticating) {
return <AuthenticatingComponent {...this.props} />
} else {
return FailureComponent ? <FailureComponent {...this.props} /> : null
}
}
}
return hoistStatics(UserAuthWrapper, DecoratedComponent)
}
return wrapComponent
}
| import React, { Component } from 'react'
import PropTypes from 'prop-types'
import hoistStatics from 'hoist-non-react-statics'
import isEmpty from 'lodash.isempty'
const defaults = {
AuthenticatingComponent: () => null, // dont render anything while authenticating
FailureComponent: undefined,
wrapperDisplayName: 'AuthWrapper',
predicate: x => !isEmpty(x),
propMapper: props => props
}
export default (args) => {
const { AuthenticatingComponent, FailureComponent, wrapperDisplayName, predicate, propMapper } = {
...defaults,
...args
}
// Wraps the component that needs the auth enforcement
function wrapComponent(DecoratedComponent) {
const displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'
class UserAuthWrapper extends Component {
static displayName = `${wrapperDisplayName}(${displayName})`;
static propTypes = {
authData: PropTypes.any,
isAuthenticating: PropTypes.bool
};
static defaultProps = {
isAuthenticating: false
}
render() {
// Allow everything but the replace aciton creator to be passed down
// Includes route props from React-Router and authData
const { authData, isAuthenticating } = this.props
if (predicate(authData)) {
return <DecoratedComponent {...propMapper(this.props)} />
} else if(isAuthenticating) {
return <AuthenticatingComponent {...propMapper(this.props)} />
} else {
return FailureComponent ? <FailureComponent {...propMapper(this.props)} /> : null
}
}
}
return hoistStatics(UserAuthWrapper, DecoratedComponent)
}
return wrapComponent
}
|
Make phantom reporter a plain old object | /* globals window,alert,jasmine */
'use strict';
(function () {
var sendMessage = function sendMessage () {
var args = [].slice.call(arguments);
/* eslint-disable */
if (window._phantom) {
alert(JSON.stringify(args));
}
/* eslint-enable */
},
PhantomReporter = {
jasmineStarted: function () {
sendMessage('jasmine.started');
},
jasmineDone: function () {
sendMessage('jasmine.done');
},
suiteStarted: function (suiteMetadata) {
sendMessage('jasmine.suiteStarted', suiteMetadata);
},
suiteDone: function (suiteMetadata) {
sendMessage('jasmine.suiteDone', suiteMetadata);
},
specStarted: function (specMetadata) {
sendMessage('jasmine.specStarted', specMetadata);
},
specDone: function (specMetadata) {
sendMessage('jasmine.specDone', specMetadata);
}
};
jasmine.getEnv().addReporter(PhantomReporter);
}());
| /* globals window,alert,jasmine */
'use strict';
(function () {
var sendMessage = function sendMessage () {
var args = [].slice.call(arguments);
/* eslint-disable */
if (window._phantom) {
alert(JSON.stringify(args));
}
/* eslint-enable */
},
PhantomReporter = function () {
this.started = false;
this.finished = false;
this.suites = [];
this.results = {};
};
PhantomReporter.prototype.jasmineStarted = function () {
this.started = true;
sendMessage('jasmine.started');
};
PhantomReporter.prototype.jasmineDone = function () {
this.finished = true;
sendMessage('jasmine.done');
};
PhantomReporter.prototype.suiteStarted = function (suiteMetadata) {
sendMessage('jasmine.suiteStarted', suiteMetadata);
};
PhantomReporter.prototype.suiteDone = function (suiteMetadata) {
sendMessage('jasmine.suiteDone', suiteMetadata);
};
PhantomReporter.prototype.specStarted = function (specMetadata) {
sendMessage('jasmine.specStarted', specMetadata);
};
PhantomReporter.prototype.specDone = function (specMetadata) {
sendMessage('jasmine.specDone', specMetadata);
};
jasmine.getEnv().addReporter(new PhantomReporter());
}());
|
Add log level to configuration | /* eslint key-spacing:0 spaced-comment:0 */
const path = require('path');
const ip = require('ip');
const projectBase = path.resolve(__dirname, '..');
/************************************************
/* Default configuration
*************************************************/
module.exports = {
env : process.env.NODE_ENV || 'development',
log : {
level : 'debug'
},
/*************************************************
/* Project Structure
*************************************************/
structure : {
client : path.join(projectBase, 'app'),
build : path.join(projectBase, 'build'),
server : path.join(projectBase, 'server'),
config : path.join(projectBase, 'config'),
test : path.join(projectBase, 'tests')
},
/*************************************************
/* Server configuration
*************************************************/
server : {
host : ip.address(), // use string 'localhost' to prevent exposure on local network
port : process.env.PORT || 3000
},
/*************************************************
/* Compiler configuration
*************************************************/
compiler : {
babel : {
cache_directory : true,
plugins : ['transform-runtime'],
presets : ['es2015', 'react', 'stage-0']
},
devtool : 'source-map',
hash_type : 'hash',
fail_on_warning : false,
quiet : false,
public_path : '/',
stats : {
chunks : false,
chunkModules : false,
colors : true
}
},
/*************************************************
/* Build configuration
*************************************************/
build : {},
/*************************************************
/* Test configuration
*************************************************/
test : {}
};
| /* eslint key-spacing:0 spaced-comment:0 */
const path = require('path');
const ip = require('ip');
const projectBase = path.resolve(__dirname, '..');
/************************************************
/* Default configuration
*************************************************/
module.exports = {
env : process.env.NODE_ENV || 'development',
/*************************************************
/* Project Structure
*************************************************/
structure : {
client : path.join(projectBase, 'app'),
build : path.join(projectBase, 'build'),
server : path.join(projectBase, 'server'),
config : path.join(projectBase, 'config'),
test : path.join(projectBase, 'tests')
},
/*************************************************
/* Server configuration
*************************************************/
server : {
host : ip.address(), // use string 'localhost' to prevent exposure on local network
port : process.env.PORT || 3000
},
/*************************************************
/* Compiler configuration
*************************************************/
compiler : {
babel : {
cache_directory : true,
plugins : ['transform-runtime'],
presets : ['es2015', 'react', 'stage-0']
},
devtool : 'source-map',
hash_type : 'hash',
fail_on_warning : false,
quiet : false,
public_path : '/',
stats : {
chunks : false,
chunkModules : false,
colors : true
}
},
/*************************************************
/* Build configuration
*************************************************/
build : {},
/*************************************************
/* Test configuration
*************************************************/
test : {}
};
|
Change google storage endpoint to us https | import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
const googleStorageEndpoint = `https://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;
class MeshPage extends Component {
render() {
return (
<div>
<h2>
Mesh Example
</h2>
<Akkad>
<Scene>
<ArcRotateCamera
initialPosition={[0, 0, 100]}
target={[0, 0, 0]}
/>
<HemisphericLight />
<Mesh
path={googleStorageEndpoint}
fileName={'skull.babylon'}
>
<Position vector={[0, 0, 0]}/>
<Rotate
axis={[0, 1.2, 0]}
amount={60}
space="LOCAL"
/>
</Mesh>
</Scene>
</Akkad>
</div>
);
}
}
export default MeshPage;
| import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
const googleStorageEndpoint = `http://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;
class MeshPage extends Component {
render() {
return (
<div>
<h2>
Mesh Example
</h2>
<Akkad>
<Scene>
<ArcRotateCamera
initialPosition={[0, 0, 100]}
target={[0, 0, 0]}
/>
<HemisphericLight />
<Mesh
path={googleStorageEndpoint}
fileName={'skull.babylon'}
>
<Position vector={[0, 0, 0]}/>
<Rotate
axis={[0, 1.2, 0]}
amount={60}
space="LOCAL"
/>
</Mesh>
</Scene>
</Akkad>
</div>
);
}
}
export default MeshPage;
|
Revert "tests: Use exports syntax directly"
This reverts commit 5c2697713268ad03612e93d1c0b285a9b7f9986e. | import sinon from 'sinon';
import config from '../config.default.json';
import DataStoreHolder from '../lib/data-store-holder';
import getGithubClient from './_github-client';
const getIssue = (content = 'lorem ipsum') => {
//TODO should use an actual issue instance instead with a no-op github client.
const labels = new Set();
return {
content,
addLabel: sinon.spy((label) => labels.add(label)),
hasLabel: sinon.spy((label) => labels.has(label)),
removeLabel: sinon.spy((label) => labels.delete(label)),
comment: sinon.spy()
};
};
const getConfig = () => config[0];
const getDataStoreHolder = () => {
const Dsh = class extends DataStoreHolder {
constructor() {
super();
this.updateSpy = sinon.stub();
}
async update() {
this.updateSpy();
return super.update();
}
};
return new Dsh();
};
const getIssueData = () => ({
id: 0,
number: 1,
owner: "test",
repo: "foo",
content: 'lorem ipsum',
updated_at: new Date().toString(),
assignee: null,
labels: [],
title: 'bar',
state: true
});
export {
getIssue,
getConfig,
getDataStoreHolder,
getGithubClient,
getIssueData
};
| import sinon from 'sinon';
import config from '../config.default.json';
import DataStoreHolder from '../lib/data-store-holder';
export { getGithubClient } from './_github-client';
const getIssue = (content = 'lorem ipsum') => {
//TODO should use an actual issue instance instead with a no-op github client.
const labels = new Set();
return {
content,
addLabel: sinon.spy((label) => labels.add(label)),
hasLabel: sinon.spy((label) => labels.has(label)),
removeLabel: sinon.spy((label) => labels.delete(label)),
comment: sinon.spy()
};
};
const getConfig = () => config[0];
const getDataStoreHolder = () => {
const Dsh = class extends DataStoreHolder {
constructor() {
super();
this.updateSpy = sinon.stub();
}
async update() {
this.updateSpy();
return super.update();
}
};
return new Dsh();
};
const getIssueData = () => ({
id: 0,
number: 1,
owner: "test",
repo: "foo",
content: 'lorem ipsum',
updated_at: new Date().toString(),
assignee: null,
labels: [],
title: 'bar',
state: true
});
export {
getIssue,
getConfig,
getDataStoreHolder,
getIssueData
};
|
Use self for php 5.3 | <?php
namespace Mockery\Generator;
class DefinedTargetClass
{
private $rfc;
public function __construct(\ReflectionClass $rfc)
{
$this->rfc = $rfc;
}
public static function factory($name)
{
return new self(new \ReflectionClass($name));
}
public function getName()
{
return $this->rfc->getName();
}
public function isAbstract()
{
return $this->rfc->isAbstract();
}
public function isFinal()
{
return $this->rfc->isFinal();
}
public function getMethods()
{
return array_map(function ($method) {
return new Method($method);
}, $this->rfc->getMethods());
}
public function getInterfaces()
{
return array_map(function ($interface) {
return new self($interface);
}, $this->rfc->getInterfaces());
}
public function __toString()
{
return $this->getName();
}
public function getNamespaceName()
{
return $this->rfc->getNamespaceName();
}
public function inNamespace()
{
return $this->rfc->inNamespace();
}
public function getShortName()
{
return $this->rfc->getShortName();
}
}
| <?php
namespace Mockery\Generator;
class DefinedTargetClass
{
private $rfc;
public function __construct(\ReflectionClass $rfc)
{
$this->rfc = $rfc;
}
public static function factory($name)
{
return new static(new \ReflectionClass($name));
}
public function getName()
{
return $this->rfc->getName();
}
public function isAbstract()
{
return $this->rfc->isAbstract();
}
public function isFinal()
{
return $this->rfc->isFinal();
}
public function getMethods()
{
return array_map(function ($method) {
return new Method($method);
}, $this->rfc->getMethods());
}
public function getInterfaces()
{
return array_map(function ($interface) {
return new static($interface);
}, $this->rfc->getInterfaces());
}
public function __toString()
{
return $this->getName();
}
public function getNamespaceName()
{
return $this->rfc->getNamespaceName();
}
public function inNamespace()
{
return $this->rfc->inNamespace();
}
public function getShortName()
{
return $this->rfc->getShortName();
}
}
|
Use fat arrow syntax for callbacks. | {
angular.module('marvelousnote.notesForm')
.controller('NotesFormController', NotesFormController);
NotesFormController.$inject = ['$state', 'Flash', 'NotesService'];
function NotesFormController($state, Flash, NotesService) {
const vm = this;
vm.note = NotesService.find($state.params.noteId);
vm.clearForm = clearForm;
vm.save = save;
vm.destroy = destroy;
//////////////////////////
function clearForm() {
vm.note = { title: '', body_html: '' };
}
function save() {
if (vm.note._id) {
NotesService.update(vm.note)
.then(
res => {
vm.note = angular.copy(res.data.note);
Flash.create('success', res.data.message);
$state.go('notes.form', { noteId: vm.note._id });
},
() => Flash.create('danger', 'Oops! Something went wrong.')
);
}
else {
NotesService.create(vm.note)
.then(
res => {
vm.note = res.data.note;
Flash.create('success', res.data.message);
},
() => Flash.create('danger', 'Oops! Something went wrong.')
);
}
}
function destroy() {
NotesService.destroy(vm.note)
.then(
() => vm.clearForm()
);
}
}
}
| {
angular.module('marvelousnote.notesForm')
.controller('NotesFormController', NotesFormController);
NotesFormController.$inject = ['$state', 'Flash', 'NotesService'];
function NotesFormController($state, Flash, NotesService) {
const vm = this;
vm.note = NotesService.find($state.params.noteId);
vm.clearForm = clearForm;
vm.save = save;
vm.destroy = destroy;
//////////////////////////
function clearForm() {
vm.note = { title: '', body_html: '' };
}
function save() {
if (vm.note._id) {
NotesService.update(vm.note)
.then(
function(res) {
vm.note = angular.copy(res.data.note);
Flash.create('success', res.data.message);
$state.go('notes.form', { noteId: vm.note._id });
},
function() {
Flash.create('danger', 'Oops! Something went wrong.');
});
}
else {
NotesService.create(vm.note)
.then(
function(res) {
vm.note = res.data.note;
Flash.create('success', res.data.message);
},
function() {
Flash.create('danger', 'Oops! Something went wrong.');
});
}
}
function destroy() {
NotesService.destroy(vm.note)
.then(function() {
vm.clearForm();
});
}
}
}
|
Update openfisca-core requirement from <32.0,>=27.0 to >=27.0,<33.0
Updates the requirements on [openfisca-core](https://github.com/openfisca/openfisca-core) to permit the latest version.
- [Release notes](https://github.com/openfisca/openfisca-core/releases)
- [Changelog](https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md)
- [Commits](https://github.com/openfisca/openfisca-core/compare/27.0.0...32.1.0)
Signed-off-by: dependabot[bot] <[email protected]> | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.4",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >=27.0,<33.0",
],
extras_require = {
"dev": [
"autopep8 ==1.4.4",
"flake8 >=3.5.0,<3.8.0",
"flake8-print",
"pycodestyle >=2.3.0,<2.6.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.4",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >=27.0,<32.0",
],
extras_require = {
"dev": [
"autopep8 ==1.4.4",
"flake8 >=3.5.0,<3.8.0",
"flake8-print",
"pycodestyle >=2.3.0,<2.6.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
|
Return empty string if result output is disabled | import jinja2
import six
import os
from st2actions.runners.pythonrunner import Action
from st2client.client import Client
class FormatResultAction(Action):
def __init__(self, config):
super(FormatResultAction, self).__init__(config)
api_url = os.environ.get('ST2_ACTION_API_URL', None)
token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
self.client = Client(api_url=api_url, token=token)
self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True)
self.jinja.tests['in'] = lambda item, list: item in list
path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(path, 'templates/default.j2'), 'r') as f:
self.default_template = f.read()
def run(self, execution):
context = {
'six': six,
'execution': execution
}
template = self.default_template
alias_id = execution['context'].get('action_alias_ref', {}).get('id', None)
if alias_id:
alias = self.client.managers['ActionAlias'].get_by_id(alias_id)
context.update({
'alias': alias
})
result = getattr(alias, 'result', None)
if result:
if not result.get('enabled', True):
return ""
if 'format' in alias.result:
template = alias.result['format']
return self.jinja.from_string(template).render(context)
| import jinja2
import six
import os
from st2actions.runners.pythonrunner import Action
from st2client.client import Client
class FormatResultAction(Action):
def __init__(self, config):
super(FormatResultAction, self).__init__(config)
api_url = os.environ.get('ST2_ACTION_API_URL', None)
token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
self.client = Client(api_url=api_url, token=token)
self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True)
self.jinja.tests['in'] = lambda item, list: item in list
path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(path, 'templates/default.j2'), 'r') as f:
self.default_template = f.read()
def run(self, execution):
context = {
'six': six,
'execution': execution
}
template = self.default_template
alias_id = execution['context'].get('action_alias_ref', {}).get('id', None)
if alias_id:
alias = self.client.managers['ActionAlias'].get_by_id(alias_id)
context.update({
'alias': alias
})
result = getattr(alias, 'result', None)
if result:
enabled = result.get('enabled', True)
if enabled and 'format' in alias.result:
template = alias.result['format']
return self.jinja.from_string(template).render(context)
|
Fix importError for Yaafe and Aubio | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from . import api
from . import core
from . import decoder
from . import analyzer
from . import grapher
from . import encoder
__version__ = '0.5.5'
__all__ = ['api', 'core', 'decoder', 'analyzer', 'grapher', 'encoder']
def _discover_modules():
import sys
import pkgutil
import importlib
#pkg_path = os.path.abspath()
#__import__(pkg)
proc_modules = ['decoder', 'analyzer', 'encoder', 'grapher']
for module in proc_modules:
pkg = '.'.join([__name__, module])
importlib.import_module(pkg)
package = sys.modules[pkg]
prefix = pkg + "."
for importer, modname, ispkg in pkgutil.walk_packages(package.__path__,
prefix):
try:
importlib.import_module(modname)
#__import__(modname)
except ImportError as e:
if e.message.count('yaafelib'):
print 'No Yaafe'
elif e.message.count('aubio'):
print 'No Aubio'
else:
raise e
_discover_modules()
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from . import api
from . import core
from . import decoder
from . import analyzer
from . import grapher
from . import encoder
__version__ = '0.5.5'
__all__ = ['api', 'core', 'decoder', 'analyzer', 'grapher', 'encoder']
def _discover_modules():
import sys
import pkgutil
import importlib
#pkg_path = os.path.abspath()
#__import__(pkg)
proc_modules = ['decoder', 'analyzer', 'encoder', 'grapher']
for module in proc_modules:
pkg = '.'.join([__name__, module])
importlib.import_module(pkg)
package = sys.modules[pkg]
prefix = pkg + "."
for importer, modname, ispkg in pkgutil.walk_packages(package.__path__,
prefix):
try:
importlib.import_module(modname)
#__import__(modname)
except ImportError as e:
if e.message.find('yaafelib'):
print 'No Yaafe'
elif e.message.find('aubio'):
print 'No aubio'
else:
raise e
_discover_modules()
|
Fix problem in as_json and as_jsonp | import json
from functools import wraps
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def as_json(func):
def decorator(request, *ar, **kw):
output = func(request, *ar, **kw)
return HttpResponse(json.dumps(output), 'application/json')
return decorator
def as_jsonp(functionCallKey='callback'):
def decorator(func):
def wrapper(request, *ar, **kw):
output = func(request, *ar, **kw)
return HttpResponse(
"%s(%s)" % (request.GET.get(functionCallKey, functionCallKey),
json.dumps(output)),
'application/json'
)
return wrapper
return decorator
def as_html(template_path):
"""
Decorator with the same functionality as render_to_response has, but uses
decorator syntax.
"""
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
output = func(request, *args, **kwargs)
if not isinstance(output, dict):
return output
return render_to_response(
template_path,
output,
context_instance=RequestContext(request)
)
return wrapper
return decorator
| import json
from functools import wraps
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def as_json(func):
def decorator(request, *ar, **kw):
output = func(request, *ar, **kw)
if not isinstance(output, dict):
return output
return HttpResponse(json.dumps(output), 'application/json')
return decorator
def as_jsonp(functionCallKey='callback'):
def decorator(func):
def wrapper(request, *ar, **kw):
output = func(request, *ar, **kw)
if not isinstance(output, dict):
return output
return HttpResponse(
"%s(%s)" % (request.GET.get(functionCallKey),
json.dumps(output)),
'application/json'
)
return wrapper
return decorator
def as_html(template_path):
"""
Decorator with the same functionality as render_to_response has, but uses
decorator syntax.
"""
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
output = func(request, *args, **kwargs)
if not isinstance(output, dict):
return output
return render_to_response(
template_path,
output,
context_instance=RequestContext(request)
)
return wrapper
return decorator
|
Update the Japanese example test | # Japanese Language Test
from seleniumbase.translate.japanese import セレニウムテストケース # noqa
class 私のテストクラス(セレニウムテストケース):
def test_例1(self):
self.を開く("https://ja.wikipedia.org/wiki/")
self.テキストを確認する("ウィキペディア")
self.要素を確認する('[title*="ウィキペディアへようこそ"]')
self.JS入力('input[name="search"]', "アニメ")
self.クリックして("#searchform button")
self.テキストを確認する("アニメ", "#firstHeading")
self.JS入力('input[name="search"]', "寿司")
self.クリックして("#searchform button")
self.テキストを確認する("寿司", "#firstHeading")
self.要素を確認する('img[alt="握り寿司"]')
self.JS入力("#searchInput", "レゴランド・ジャパン")
self.クリックして("#searchform button")
self.要素を確認する('img[alt*="LEGOLAND JAPAN"]')
self.リンクテキストを確認する("名古屋城")
self.リンクテキストをクリックします("テーマパーク")
self.テキストを確認する("テーマパーク", "#firstHeading")
| # Japanese Language Test
from seleniumbase.translate.japanese import セレニウムテストケース # noqa
class 私のテストクラス(セレニウムテストケース):
def test_例1(self):
self.を開く("https://ja.wikipedia.org/wiki/")
self.テキストを確認する("ウィキペディア")
self.要素を確認する('[title*="メインページに移動する"]')
self.JS入力('input[name="search"]', "アニメ")
self.クリックして("#searchform button")
self.テキストを確認する("アニメ", "#firstHeading")
self.JS入力('input[name="search"]', "寿司")
self.クリックして("#searchform button")
self.テキストを確認する("寿司", "#firstHeading")
self.要素を確認する('img[alt="握り寿司"]')
self.JS入力("#searchInput", "レゴランド・ジャパン")
self.クリックして("#searchform button")
self.要素を確認する('img[alt*="LEGOLAND JAPAN"]')
self.リンクテキストを確認する("名古屋城")
self.リンクテキストをクリックします("テーマパーク")
self.テキストを確認する("テーマパーク", "#firstHeading")
|
Revert back Admin controller user ACL to ON | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/
public function indexAction()
{
// if user is not logged in, redirect to login page
$securityContext = $this->container->get('security.authorization_checker');
if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('fos_user_security_login');
}
// Load the data for the current user into an object
$user = $this->getUser();
// continue only if user has Admin access, else redirect to Home
if ($user->getEmail() !== '[email protected]') {
return $this->redirectToRoute('home');
}
// Get an instance of the Entity Manager
$em = $this->getDoctrine()->getManager();
$tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
->findOneById(12);
$dataUpdatesManager = $this->get('app.data_updates.manager');
$dataUpdatesManager->setEntityManager($em);
$dataUpdatesManager->updateTeamsByTournament($tournament);
// $dataUpdatesManager->updateFixtures();
return $this->redirectToRoute('home');
}
}
| <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/
public function indexAction()
{
// if user is not logged in, redirect to login page
$securityContext = $this->container->get('security.authorization_checker');
if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('fos_user_security_login');
}
// Load the data for the current user into an object
$user = $this->getUser();
// continue only if user has Admin access, else redirect to Home
// if ($user->getEmail() !== '[email protected]') {
// return $this->redirectToRoute('home');
// }
// Get an instance of the Entity Manager
$em = $this->getDoctrine()->getManager();
$tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
->findOneById(12);
$dataUpdatesManager = $this->get('app.data_updates.manager');
$dataUpdatesManager->setEntityManager($em);
$dataUpdatesManager->updateTeamsByTournament($tournament);
// $dataUpdatesManager->updateFixtures();
return $this->redirectToRoute('home');
}
}
|
Fix up a couple of minor issues | # -*- coding: utf-8 -*-
"""Implementation of pep257 integration with Flake8.
pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
import pep8
import pep257
__version__ = '0.2.2'
class pep257Checker(object):
"""Flake8 needs a class to check python file."""
name = 'flake8-docstrings'
version = __version__ + ', pep257: {0}'.format(pep257.__version__)
STDIN_NAMES = set(['stdin', '-', '(none)', None])
def __init__(self, tree, filename='(none)', builtins=None):
"""Placeholder."""
self.tree = tree
self.filename = filename
self.source = self.load_source()
self.checker = pep257.PEP257Checker()
def run(self):
"""Use directly check() api from pep257."""
for error in self.checker.check_source(self.source, self.filename):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
# NOTE(sigmavirus24): Fixes GitLab#3
message = '%s %s' % (error.code, error.short_desc)
yield (error.line, 0, message, type(self))
def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pep8.stdin_get_value()
else:
with io.open(self.filename, encoding='utf-8') as fd:
self.source = fd.read()
| # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
import pep8
import pep257
__version__ = '0.2.2'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
STDIN_NAMES = set(['stdin', '-', '(none)', None])
def __init__(self, tree, filename='(none)', builtins=None):
self.tree = tree
self.filename = filename
self.source = self.load_source()
self.checker = pep257.PEP257Checker()
def run(self):
"""Use directly check() api from pep257."""
for error in self.checker.check_source(self.source, self.filename):
# Ignore AllError, Environment error.
if isinstance(error, pep257.Error):
# NOTE(sigmavirus24): Fixes GitLab#3
message = '%s %s' % (error.code, error.short_desc)
yield (error.line, 0, message, type(self))
def load_source(self):
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pep8.stdin_get_value()
else:
with io.open(self.filename, encoding='utf-8') as fd:
self.source = fd.read()
|
Stop propagating click to parents | /* global define */
define([
'jquery',
'views/reply-form-view'
], function ($, ReplyFormView) {
'use strict';
var ReplyableView = {
renderReplyBox: function (event) {
event.preventDefault();
event.stopPropagation();
this.clickedReplyButton = $(event.currentTarget);
if (!this.$(this.replyForm).length) {
this.renderReplyForm();
}
},
renderReplyForm: function () {
if (!this.previouslyRendered) {
this.renderNewForm();
} else {
this.replyFormRendered();
}
},
renderNewForm: function () {
this.replyForm = new ReplyFormView({
post: this.post,
user: this.user,
parentView: this,
parentId: this.parentId()
});
this.replyForm.render();
$(this.clickedReplyButton).after(this.replyForm.el);
this.previouslyRendered = true;
},
parentId: function () {
return 0;
},
replyFormCancelled: function () {
$(this.clickedReplyButton).fadeIn('fast');
},
replyFormRendered: function () {
$(this.clickedReplyButton).fadeOut('fast', function () {
$(this.replyForm.el).slideDown('slow');
}.bind(this));
},
replyFormDestroyed: function () {
$(this.clickedReplyButton).fadeIn('fast');
$(this.replyForm.el).remove();
this.replyForm = null;
},
};
return ReplyableView;
});
| /* global define */
define([
'jquery',
'views/reply-form-view'
], function ($, ReplyFormView) {
'use strict';
var ReplyableView = {
renderReplyBox: function (event) {
event.preventDefault();
this.clickedReplyButton = $(event.currentTarget);
if (!this.$(this.replyForm).length) {
this.renderReplyForm();
}
},
renderReplyForm: function () {
if (!this.previouslyRendered) {
this.renderNewForm();
} else {
this.replyFormRendered();
}
},
renderNewForm: function () {
this.replyForm = new ReplyFormView({
post: this.post,
user: this.user,
parentView: this,
parentId: this.parentId()
});
this.replyForm.render();
$(this.clickedReplyButton).after(this.replyForm.el);
this.previouslyRendered = true;
},
parentId: function () {
return 0;
},
replyFormCancelled: function () {
$(this.clickedReplyButton).fadeIn('fast');
},
replyFormRendered: function () {
$(this.clickedReplyButton).fadeOut('fast', function () {
$(this.replyForm.el).slideDown('slow');
}.bind(this));
},
replyFormDestroyed: function () {
$(this.clickedReplyButton).fadeIn('fast');
$(this.replyForm.el).remove();
this.replyForm = null;
},
};
return ReplyableView;
});
|
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['localeurl']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['localeurl']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Change deprecated options_list to add_arguments | from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser):
parser.add_argument('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode')
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
| from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
option_list = BaseCommand.option_list + (
make_option('--verbose',
action='store_true',
dest='verbose',
default=False,
help='verbose mode'
),
)
def handle(self, *args, **options):
verbosity = int(options.get('verbosity', 0))
if options['verbose']:
warnings.warn('The `--verbose` option is being deprecated and it will be removed in the next release. Use `--verbosity` instead.', PendingDeprecationWarning)
verbosity = 1
if verbosity == 0:
# avoids allocating the results
recommends_precompute()
else:
self.stdout.write("\nCalculation Started.\n")
start_time = datetime.now()
results = recommends_precompute()
end_time = datetime.now()
if verbosity > 1:
for r in results:
self.stdout.write(
"%d similarities and %d recommendations saved.\n"
% (r['similar_count'], r['recommend_count']))
rd = dateutil.relativedelta.relativedelta(end_time, start_time)
self.stdout.write(
"Calculation finished in %d years, %d months, %d days, %d hours, %d minutes and %d seconds\n"
% (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds))
|
Print all scsslint errors before existing. | var path = require('path');
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
function scssLintExists() {
return shelljs.which('scss-lint');
}
module.exports = function(gulp, options) {
var scssLintPath = path.resolve(__dirname, 'scss-lint.yml');
var esLintPath = path.resolve(__dirname, 'eslintrc');
var customEslint = options.customEslintPath ?
require(options.customEslintPath) : {};
gulp.task('scsslint', function() {
if (options.scsslint) {
if (scssLintExists()) {
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
})).pipe(scsslint.failReporter());
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.');
}
}
});
gulp.task('jslint', function() {
var eslintRules = merge({
configFile: esLintPath
}, customEslint);
return gulp.src(options.jsAssets || [])
.pipe(eslint(eslintRules))
.pipe(eslint.formatEach())
.pipe(eslint.failOnError());
});
};
| var path = require('path');
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
function failLintBuild() {
process.exit(1);
}
function scssLintExists() {
return shelljs.which('scss-lint');
}
module.exports = function(gulp, options) {
var scssLintPath = path.resolve(__dirname, 'scss-lint.yml');
var esLintPath = path.resolve(__dirname, 'eslintrc');
var customEslint = options.customEslintPath ?
require(options.customEslintPath) : {};
gulp.task('scsslint', function() {
if (options.scsslint) {
if (scssLintExists()) {
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
})).pipe(scsslint.failReporter()).on('error', failLintBuild);
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.');
}
}
});
gulp.task('jslint', function() {
var eslintRules = merge({
configFile: esLintPath
}, customEslint);
return gulp.src(options.jsAssets || [])
.pipe(eslint(eslintRules))
.pipe(eslint.formatEach())
.pipe(eslint.failOnError());
});
};
|
Revert to puppeteer (keeping chromium install for dependencies) | // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
process.env.CHROME_BIN = require('puppeteer').executablePath()
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: [
// '--disable-translate',
// '--headless',
// '--disable-gpu',
// '--disable-extensions',
'--no-sandbox',
// '--disable-setuid-sandbox',
// '--remote-debugging-port=9222'
]
}
},
singleRun: true
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
process.env.CHROME_BIN = require('puppeteer').executablePath()
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
// browsers: ['ChromeHeadlessNoSandbox'],
// customLaunchers: {
// ChromeHeadlessNoSandbox: {
// base: 'Chrome',
// flags: [
// '--disable-translate',
// '--headless',
// '--disable-gpu',
// '--disable-extensions',
// '--no-sandbox',
// '--disable-setuid-sandbox',
// '--remote-debugging-port=9222']
// }
//},
singleRun: true
});
};
|
Change test case user info | import datetime
import tmdbsimple as tmdb
from django.contrib.auth.models import User
from django.test import TestCase
from .models import Movie
class MovieTestCase(TestCase):
def setUp(self):
User.objects.create(username="movie_test_case", password="pass", email="movie@test_case.tld",
first_name="Movie", last_name="TestCase")
def test_can_create_movie(self):
"""Can movies be created in the database?"""
movie_data = tmdb.Movies(550).info()
m = Movie.objects.create(tmdb_id=movie_data["id"], score=10, submitter=User.objects.first(),
title=movie_data["title"], tagline=movie_data["tagline"],
overview=movie_data["overview"],
release_date=datetime.datetime.strptime(movie_data["release_date"], "%Y-%m-%d"),
budget=movie_data["budget"], vote_average=movie_data["vote_average"],
vote_count=movie_data["vote_count"], original_language=movie_data["original_language"])
m.save()
def test_can_create_movie_from_id(self):
"""Does Movie.add_from_id work?"""
Movie.add_from_id(550, User.objects.first())
| import datetime
from django.contrib.auth.models import User
from django.test import TestCase
import tmdbsimple as tmdb
from .models import Movie
class MovieTestCase(TestCase):
def setUp(self):
User.objects.create(username="test_user", password="pass", email="[email protected]", first_name="Test",
last_name="User")
def test_can_create_movie(self):
"""Can movies be created in the database?"""
movie_data = tmdb.Movies(550).info()
m = Movie.objects.create(tmdb_id=movie_data["id"], score=10, submitter=User.objects.first(),
title=movie_data["title"], tagline=movie_data["tagline"],
overview=movie_data["overview"],
release_date=datetime.datetime.strptime(movie_data["release_date"], "%Y-%m-%d"),
budget=movie_data["budget"], vote_average=movie_data["vote_average"],
vote_count=movie_data["vote_count"], original_language=movie_data["original_language"])
m.save()
def test_can_create_movie_from_id(self):
"""Does Movie.add_from_id work?"""
Movie.add_from_id(550, User.objects.first())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.