text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix for not-markdown texts on .md pages | <?php
/**
* DokuWiki Plugin markdownextra (Action Component)
*
* @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
* @author Andreas Gohr <[email protected]>
*/
// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once DOKU_PLUGIN.'action.php';
class action_plugin_markdownextra extends DokuWiki_Action_Plugin {
function register(&$controller) {
$controller->register_hook('PARSER_WIKITEXT_PREPROCESS',
'BEFORE', $this, 'handle_parser_wikitext_preprocess');
}
function handle_parser_wikitext_preprocess(&$event, $param) {
global $ID;
global $TEXT;
if(substr($ID,-3) != '.md' || $event->data != $TEXT) return true;
if ($this->getConf('frontmatter')){
if (preg_match('/^---\s*\n(.*?\n?)^---\s*$\n?(.+)/sm',$event->data, $match)){
$event->data = sprintf("%s<markdown>\n%s\n</markdown>", $match[1], $match[2]);
}else{
$event->data = "<markdown>\n".$event->data."\n</markdown>";
}
}else{
$event->data = "<markdown>\n".$event->data."\n</markdown>";
}
}
}
| <?php
/**
* DokuWiki Plugin markdownextra (Action Component)
*
* @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
* @author Andreas Gohr <[email protected]>
*/
// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once DOKU_PLUGIN.'action.php';
class action_plugin_markdownextra extends DokuWiki_Action_Plugin {
function register(&$controller) {
$controller->register_hook('PARSER_WIKITEXT_PREPROCESS',
'BEFORE', $this, 'handle_parser_wikitext_preprocess');
}
function handle_parser_wikitext_preprocess(&$event, $param) {
global $ID;
if(substr($ID,-3) != '.md') return true;
if ($this->getConf('frontmatter')){
if (preg_match('/^---\s*\n(.*?\n?)^---\s*$\n?(.+)/sm',$event->data, $match)){
$event->data = sprintf("%s<markdown>\n%s\n</markdown>", $match[1], $match[2]);
}else{
$event->data = "<markdown>\n".$event->data."\n</markdown>";
}
}else{
$event->data = "<markdown>\n".$event->data."\n</markdown>";
}
}
} |
Add possibility to configure the action CHANGELOG update | <?php
namespace Liip\RMT\Action;
use Liip\RMT\Changelog\ChangelogManager;
use Liip\RMT\Context;
/**
* Update the changelog file
*/
class ChangelogUpdateAction extends BaseAction
{
protected $options;
public function __construct($options)
{
$this->options = array_merge(array(
'dump-commits' => false,
'format' => 'simple',
'file' => 'CHANGELOG'
), $options);
}
public function execute()
{
if ($this->options['dump-commits'] == true) {
$extraLines = Context::get('vcs')->getAllModificationsSince(
Context::get('version-persister')->getCurrentVersionTag(),
false
);
$this->options['extra-lines'] = $extraLines;
unset($this->options['dump-commits']);
}
$manager = new ChangelogManager($this->options['file'], $this->options['format']);
$manager->update(
Context::getParam('new-version'),
Context::get('information-collector')->getValueFor('comment'),
array_merge(
array('type' => Context::get('information-collector')->getValueFor('type', null)),
$this->options
)
);
$this->confirmSuccess();
}
public function getInformationRequests()
{
return array('comment');
}
}
| <?php
namespace Liip\RMT\Action;
use Liip\RMT\Changelog\ChangelogManager;
use Liip\RMT\Context;
/**
* Update the changelog file
*/
class ChangelogUpdateAction extends BaseAction
{
protected $options;
public function __construct($options)
{
$this->options = $options;
}
public function execute()
{
if (isset($this->options['dump-commits']) && $this->options['dump-commits']===true) {
$extraLines = Context::get('vcs')->getAllModificationsSince(
Context::get('version-persister')->getCurrentVersionTag(),
false
);
$this->options['extra-lines'] = $extraLines;
unset($this->options['dump-commits']);
}
$manager = new ChangelogManager('CHANGELOG', 'semantic');
$manager->update(
Context::getParam('new-version'),
Context::get('information-collector')->getValueFor('comment'),
array_merge(
array('type' => Context::get('information-collector')->getValueFor('type', null)),
$this->options
)
);
$this->confirmSuccess();
}
public function getInformationRequests()
{
return array('comment');
}
}
|
Update the RB.APIToken resource to use a defaults function
This change updates the `RB.APIToken` resource to use the new
`defaults` function that all other resources are using.
Testing Done:
Ran JS tests.
Reviewed at https://reviews.reviewboard.org/r/7394/ | RB.APIToken = RB.BaseResource.extend({
defaults: function() {
return _.defaults({
tokenValue: null,
note: null,
policy: {},
userName: null
}, RB.BaseResource.prototype.defaults());
},
rspNamespace: 'api_token',
url: function() {
var url = SITE_ROOT + (this.get('localSitePrefix') || '') +
'api/users/' + this.get('userName') + '/api-tokens/';
if (!this.isNew()) {
url += this.id + '/';
}
return url;
},
toJSON: function() {
return {
note: this.get('note'),
policy: JSON.stringify(this.get('policy'))
};
},
parseResourceData: function(rsp) {
return {
tokenValue: rsp.token,
note: rsp.note,
policy: rsp.policy
};
}
}, {
defaultPolicies: {
readWrite: {},
readOnly: {
resources: {
'*': {
allow: ['GET', 'HEAD', 'OPTIONS'],
block: ['*']
}
}
},
custom: {
resources: {
'*': {
allow: ['*'],
block: []
}
}
}
}
});
| RB.APIToken = RB.BaseResource.extend({
defaults: _.defaults({
tokenValue: null,
note: null,
policy: {},
userName: null
}, RB.BaseResource.prototype.defaults),
rspNamespace: 'api_token',
url: function() {
var url = SITE_ROOT + (this.get('localSitePrefix') || '') +
'api/users/' + this.get('userName') + '/api-tokens/';
if (!this.isNew()) {
url += this.id + '/';
}
return url;
},
toJSON: function() {
return {
note: this.get('note'),
policy: JSON.stringify(this.get('policy'))
};
},
parseResourceData: function(rsp) {
return {
tokenValue: rsp.token,
note: rsp.note,
policy: rsp.policy
};
}
}, {
defaultPolicies: {
readWrite: {},
readOnly: {
resources: {
'*': {
allow: ['GET', 'HEAD', 'OPTIONS'],
block: ['*']
}
}
},
custom: {
resources: {
'*': {
allow: ['*'],
block: []
}
}
}
}
});
|
Change repository URL to point to OpenPrinting's organisation | #!/usr/bin/env python
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
class sdist(_sdist):
def run(self):
try:
import sys
sys.path.append("contrib")
import git2changes
print('generating CHANGES.txt')
with open('CHANGES.txt', 'w+') as f:
git2changes.run(f)
except ImportError:
pass
_sdist.run(self)
setup(
name='pyppd',
version='1.0.2',
author='Vitor Baptista',
author_email='[email protected]',
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='https://github.com/OpenPrinting/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
open('ISSUES', 'rb').read().decode('UTF-8'),
cmdclass={'sdist': sdist},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'Operating System :: POSIX',
'License :: OSI Approved :: MIT License',
'Topic :: Printing',
],
)
| #!/usr/bin/env python
from distutils.core import setup
from distutils.command.sdist import sdist as _sdist
class sdist(_sdist):
def run(self):
try:
import sys
sys.path.append("contrib")
import git2changes
print('generating CHANGES.txt')
with open('CHANGES.txt', 'w+') as f:
git2changes.run(f)
except ImportError:
pass
_sdist.run(self)
setup(
name='pyppd',
version='1.0.2',
author='Vitor Baptista',
author_email='[email protected]',
packages=['pyppd'],
package_data={'pyppd': ['*.in']},
scripts=['bin/pyppd'],
url='http://github.com/vitorbaptista/pyppd/',
license='MIT',
description='A CUPS PostScript Printer Driver\'s compressor and generator',
long_description=open('README', 'rb').read().decode('UTF-8') + "\n" +
open('ISSUES', 'rb').read().decode('UTF-8'),
cmdclass={'sdist': sdist},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: System Administrators',
'Operating System :: POSIX',
'License :: OSI Approved :: MIT License',
'Topic :: Printing',
],
)
|
Improve url in the test. | /*global describe, beforeEach, module, inject, it, expect*/
/*jslint nomen: true*/
describe('Post module', function () {
"use strict";
beforeEach(module('post'));
var PostManager, Post, $httpBackend, $rootScope;
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get("$httpBackend");
$rootScope = $injector.get("$rootScope");
Post = $injector.get("Post");
PostManager = $injector.get("PostManager");
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingRequest();
$httpBackend.verifyNoOutstandingExpectation();
});
describe("PostManager", function (done) {
it('should be initialized and expose list of functions', function () {
expect(PostManager.getPosts).toBeDefined();
});
it('should fetch list of posts from API', function () {
var postsMock = [new Post({title: "Titile 1", body: "Body 1"})];
// http expectations
$httpBackend.expectGET("data/posts.json").respond(200, postsMock);
PostManager.getPosts()
.then(function (data) {
expect(data).toEqual(postsMock);
})
.finally(done);
$httpBackend.flush();
});
});
});
| /*global describe, beforeEach, module, inject, it, expect*/
/*jslint nomen: true*/
describe('Post module', function () {
"use strict";
beforeEach(module('post'));
var PostManager, Post, $httpBackend, $rootScope;
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get("$httpBackend");
$rootScope = $injector.get("$rootScope");
Post = $injector.get("Post");
PostManager = $injector.get("PostManager");
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingRequest();
$httpBackend.verifyNoOutstandingExpectation();
});
describe("PostManager", function (done) {
it('should be initialized and expose list of functions', function () {
expect(PostManager.getPosts).toBeDefined();
});
it('should fetch list of posts from API', function () {
var postsMock = [new Post({title: "Titile 1", body: "Body 1"})];
// http expectations
$httpBackend.expectGET(/data\/posts/).respond(200, postsMock);
PostManager.getPosts()
.then(function (data) {
expect(data).toEqual(postsMock);
})
.finally(done);
$httpBackend.flush();
});
});
});
|
Refactor Dusk Breadcrumbs test to be more efficient | <?php
namespace Tests\Browser;
use App\Models\User;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class BreadcrumbsTest extends DuskTestCase
{
public function testBreadcrumbsForPagesThatDoNotRequiredAuthentication(): void
{
$breadcrumbs = $this->guestPagesBreadcrumbs();
$this->browse(function (Browser $browser) use ($breadcrumbs) {
foreach ($breadcrumbs as $url => $crumbs) {
$browser->visit($url)
->assertSeeIn('.breadcrumb', strtoupper(implode("\n", $crumbs)));
}
});
}
public function guestPagesBreadcrumbs(): array
{
return [
'/' => ['Home'],
'/login' => ['Home', 'Login'],
'/register' => ['Home', 'Register'],
'/password/reset' => ['Home', 'Forgotten password'],
];
}
public function testBreadcrumbsForPagesThatRequiredAuthentication(): void
{
$breadcrumbs = $this->authPagesBreadcrumbs();
$this->browse(function (Browser $browser) use ($breadcrumbs) {
$browser->loginAs(factory(User::class)->create());
foreach ($breadcrumbs as $url => $crumbs) {
$browser->visit($url)
->assertSeeIn('.breadcrumb', strtoupper(implode("\n", $crumbs)));
}
});
}
public function authPagesBreadcrumbs(): array
{
return [
'/dashboard' => ['Home', 'Dashboard'],
];
}
}
| <?php
namespace Tests\Browser;
use App\Models\User;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class BreadcrumbsTest extends DuskTestCase
{
/**
* @dataProvider guestPagesBreadcrumbs
*/
public function testBreadcrumbsForPagesThatDoNotRequiredAuthentication(string $url, array $crumbs): void
{
$this->browse(function (Browser $browser) use ($url, $crumbs) {
$browser->visit($url)
->assertSeeIn('.breadcrumb', strtoupper(implode("\n", $crumbs)));
});
}
public function guestPagesBreadcrumbs(): array
{
return [
'Homepage' => ['/', ['Home']],
'Login' => ['/login', ['Home', 'Login']],
'Register' => ['/register', ['Home', 'Register']],
'Forgotten password' => ['/password/reset', ['Home', 'Forgotten password']],
];
}
/**
* @dataProvider authPagesBreadcrumbs
*/
public function testBreadcrumbsForPagesThatRequiredAuthentication(string $url, array $crumbs): void
{
$this->browse(function (Browser $browser) use ($url, $crumbs) {
$browser->loginAs(factory(User::class)->create())
->visit($url)
->assertSeeIn('.breadcrumb', strtoupper(implode("\n", $crumbs)));
});
}
public function authPagesBreadcrumbs(): array
{
return [
'Dashboard' => ['/dashboard', ['Home', 'Dashboard']],
];
}
}
|
Fix logical error in FAB scroll behaviour
FAB was not re-drawing on scroll up in recycler view. | package com.bookbase.bookbase.fragments.behaviour;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
public class FABScrollBehaviour extends FloatingActionButton.Behavior{
public FABScrollBehaviour(Context context, AttributeSet attrs){
super();
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child,
View directTargetChild,
View target,
int nestedScrollAxes){
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout,
child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child,
View target,
int dxConsumed,
int dyConsumed,
int dxUnconsumed,
int dyUnconsumed){
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if(dyConsumed > 0 && child.getVisibility() == View.VISIBLE){
child.hide();
} else if(dyConsumed < 0 && child.getVisibility() != View.VISIBLE){
child.show();
}
}
}
| package com.bookbase.bookbase.fragments.behaviour;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
public class FABScrollBehaviour extends FloatingActionButton.Behavior{
public FABScrollBehaviour(Context context, AttributeSet attrs){
super();
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child,
View directTargetChild,
View target,
int nestedScrollAxes){
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout,
child, directTargetChild, target, nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout,
FloatingActionButton child,
View target,
int dxConsumed,
int dyConsumed,
int dxUnconsumed,
int dyUnconsumed){
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if(dyConsumed > 0 && child.getVisibility() == View.VISIBLE){
child.hide();
} else if(dyConsumed > 0 && child.getVisibility() == View.VISIBLE){
child.show();
}
}
}
|
Use the new mechanism for the callback functions | /**
* @constructor
* @param {string} baseURL - URL for the Open PHACTS API
* @param {string} appID - Application ID for the application being used. Created by https://dev.openphacts.org
* @param {string} appKey - Application Key for the application ID.
* @license [MIT]{@link http://opensource.org/licenses/MIT}
* @author Ian Dunlop
* @author Egon Willighagen
*/
Openphacts.DataSources = function DataSources(baseURL, appID, appKey) {
this.baseURL = baseURL;
this.appID = appID;
this.appKey = appKey;
}
Openphacts.DataSources.prototype.getSources = function(callback) {
var sourcesQuery = $.ajax({
url: this.baseURL + '/sources',
dataType: 'json',
cache: true,
data: {
_format: "json",
app_id: this.appID,
app_key: this.appKey
}
}).done(function(response, status, request){
callback.call(this, true, request.status, response.result);
}).fail(function(response, status, statusText){
callback.call(this, false, response.status);
});
}
| /**
* @constructor
* @param {string} baseURL - URL for the Open PHACTS API
* @param {string} appID - Application ID for the application being used. Created by https://dev.openphacts.org
* @param {string} appKey - Application Key for the application ID.
* @license [MIT]{@link http://opensource.org/licenses/MIT}
* @author Ian Dunlop
* @author Egon Willighagen
*/
Openphacts.DataSources = function DataSources(baseURL, appID, appKey) {
this.baseURL = baseURL;
this.appID = appID;
this.appKey = appKey;
}
Openphacts.DataSources.prototype.getSources = function(callback) {
var sourcesQuery = $.ajax({
url: this.baseURL + '/sources',
dataType: 'json',
cache: true,
data: {
_format: "json",
app_id: this.appID,
app_key: this.appKey
},
success: function(response, status, request) {
callback.call(this, true, request.status, response.result.primaryTopic);
},
error: function(request, status, error) {
callback.call(this, false, request.status);
}
});
}
|
Return current user as promise (saas-185) | 'use strict';
(function() {
angular.module('ncsaas')
.service('usersService', ['RawUser', 'RawKey', usersService]);
function usersService(RawUser, RawKey) {
/*jshint validthis: true */
var vm = this;
vm.getCurrentUser = getCurrentUser;
vm.getCurrentUserWithKeys = getCurrentUserWithKeys;
vm.getUser = getUser;
vm.getRawUserList = getRawUserList;
function getCurrentUser() {
return RawUser.getCurrent().$promise;
}
function getCurrentUserWithKeys() {
return RawUser.getCurrent(initKeys);
function initKeys(user) {
/*jshint camelcase: false */
user.keys = RawKey.query({user_uuid: user.uuid});
}
}
function getRawUserList() {
return RawUser.query();
}
function getUser(uuid) {
return RawUser.get({userUUID: uuid});
}
}
})();
(function() {
angular.module('ncsaas')
.factory('RawUser', ['ENV', '$resource', RawUser]);
function RawUser(ENV, $resource) {
return $resource(ENV.apiEndpoint + 'api/users/:userUUID/', {userUUID:'@uuid'},
{
getCurrent: {
method: 'GET',
transformResponse: function(data) {return angular.fromJson(data)[0];},
params: {current:''}
}
}
);
}
})();
| 'use strict';
(function() {
angular.module('ncsaas')
.service('usersService', ['RawUser', 'RawKey', usersService]);
function usersService(RawUser, RawKey) {
/*jshint validthis: true */
var vm = this;
vm.getCurrentUser = getCurrentUser;
vm.getCurrentUserWithKeys = getCurrentUserWithKeys;
vm.getUser = getUser;
vm.getRawUserList = getRawUserList;
function getCurrentUser() {
return RawUser.getCurrent();
}
function getCurrentUserWithKeys() {
return RawUser.getCurrent(initKeys);
function initKeys(user) {
/*jshint camelcase: false */
user.keys = RawKey.query({user_uuid: user.uuid});
}
}
function getRawUserList() {
return RawUser.query();
}
function getUser(uuid) {
return RawUser.get({userUUID: uuid});
}
}
})();
(function() {
angular.module('ncsaas')
.factory('RawUser', ['ENV', '$resource', RawUser]);
function RawUser(ENV, $resource) {
return $resource(ENV.apiEndpoint + 'api/users/:userUUID/', {userUUID:'@uuid'},
{
getCurrent: {
method: 'GET',
transformResponse: function(data) {return angular.fromJson(data)[0];},
params: {current:''}
}
}
);
}
})();
|
Delete Loki database and persistent storage on logout. | /**
* Copyright 2015, Government of Canada.
* All rights reserved.
*
* This source code is licensed under the MIT license.
*
* @providesModule User
*/
var Cookie = require('react-cookie');
var Events = require('./Events');
/**
* An object that manages all user authentication and the user profile.
*
* @constructor
*/
var User = function () {
this.name = null;
this.events = new Events(['change', 'logout'], this);
this.load = function (data) {
// Update the username, token, and reset properties with the authorized values.
_.assign(this, _.omit(data, '_id'));
this.name = data._id;
Cookie.save('token', data.token);
this.emit('change');
};
this.authorize = function (data) {
this.load(data);
dispatcher.sync();
};
this.deauthorize = function (data) {
dispatcher.db.loki.deleteDatabase({}, function () {
location.hash = 'home/welcome';
this.name = null;
_.forIn(dispatcher.db, function (collection) {
collection.documents = [];
collection.synced = false;
});
this.emit('logout', data);
}.bind(this));
}.bind(this);
this.logout = function () {
dispatcher.send({
collectionName: 'users',
methodName: 'logout',
data: {
token: this.token
}
}, this.deauthorize);
};
};
module.exports = User; | /**
* Copyright 2015, Government of Canada.
* All rights reserved.
*
* This source code is licensed under the MIT license.
*
* @providesModule User
*/
var Cookie = require('react-cookie');
var Events = require('./Events');
/**
* An object that manages all user authentication and the user profile.
*
* @constructor
*/
var User = function () {
this.name = null;
this.events = new Events(['change', 'logout'], this);
this.load = function (data) {
// Update the username, token, and reset properties with the authorized values.
_.assign(this, _.omit(data, '_id'));
this.name = data._id;
Cookie.save('token', data.token);
this.emit('change');
};
this.authorize = function (data) {
this.load(data);
dispatcher.sync();
};
this.deauthorize = function (data) {
dispatcher.storage.deleteDatabase(function () {
location.hash = 'home/welcome';
this.name = null;
_.forIn(dispatcher.db, function (collection) {
collection.documents = [];
collection.synced = false;
});
this.emit('logout', data);
}.bind(this));
}.bind(this);
this.logout = function () {
dispatcher.send({
collectionName: 'users',
methodName: 'logout',
data: {
token: this.token
}
}, this.deauthorize);
};
};
module.exports = User; |
Remove the unnecessary dot that matches everything | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
/**
* Takes a string and returns the string with public URLs removed.
* It doesn't remove the URLs like `chrome://..` because they are internal URLs
* and they shouldn't be removed.
*/
export function removeURLs(
string: string,
removeExtensions: boolean = true
): string {
const regExpExtension = removeExtensions ? '|moz-extension' : '';
const regExp = new RegExp(
'((?:https?|ftp' + regExpExtension + ')://)[^\\s/$.?#][^\\s)]*',
// ^ ^ ^
// | | matches any characters except
// | | whitespaces and ) character.
// | | Other characters are allowed now
// | matches any characters except whitespaces
// | and / $ . ? # characters because this is
// | start of the URL
// Matches http, https, ftp and optionally moz-extension protocols
'gi'
);
return string.replace(regExp, '$1<URL>');
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
/**
* Takes a string and returns the string with public URLs removed.
* It doesn't remove the URLs like `chrome://..` because they are internal URLs
* and they shouldn't be removed.
*/
export function removeURLs(
string: string,
removeExtensions: boolean = true
): string {
const regExpExtension = removeExtensions ? '|moz-extension' : '';
const regExp = new RegExp(
'((?:https?|ftp' + regExpExtension + ')://)[^\\s/$.?#].[^\\s)]*',
// ^ ^ ^
// | | matches any characters except
// | | whitespaces and ) character.
// | | Other characters are allowed now
// | matches any characters except whitespaces
// | and / $ . ? # characters because this is
// | start of the URL
// Matches http, https, ftp and optionally moz-extension protocols
'gi'
);
return string.replace(regExp, '$1<URL>');
}
|
Revert unintend change. Fixes bug. | # A context carrying the loaded configuration.
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import config
class ConfigContext(object):
def __init__(self, config):
self._config = config
self._cloud_workstations = {}
self._volumes = {}
self._build_indexes()
# Only support GCE for now
assert config.provider == 'GCE'
ComputeEngine = get_driver(Provider.GCE)
self._driver = ComputeEngine('', '', project=self._config.project)
def _build_indexes(self):
for cws in self._config.cloud_workstations:
self._cloud_workstations[cws.name] = cws
for v in cws.volumes:
self._volumes[(cws.name, v.name)] = v
def driver(self):
return self._driver
def get_cws(self, cws_name):
return self._cloud_workstations[cws_name]
def get_volume(self, cws_name, volume_name):
return self._volumes[(cws_name, volume_name)]
def get_volumes(self, cws_name):
# Returned volumes order is non-deterministic. This will have
# to do for now.
volumes = []
for (name, _), v in self._volumes.iteritems():
if name == cws_name:
volumes.append(v)
return volumes
| # A context carrying the loaded configuration.
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
import config
class ConfigContext(object):
def __init__(self, config):
self._config = config
self._cloud_workstations = {}
self._volumes_by_cws = {}
self._build_indexes()
# Only support GCE for now
assert config.provider == 'GCE'
ComputeEngine = get_driver(Provider.GCE)
self._driver = ComputeEngine('', '', project=self._config.project)
def _build_indexes(self):
for cws in self._config.cloud_workstations:
self._cloud_workstations[cws.name] = cws
for v in cws.volumes:
self._volumes[(cws.name, v.name)] = v
def driver(self):
return self._driver
def get_cws(self, cws_name):
return self._cloud_workstations[cws_name]
def get_volume(self, cws_name, volume_name):
return self._volumes[(cws_name, volume_name)]
def get_volumes(self, cws_name):
# Returned volumes order is non-deterministic. This will have
# to do for now.
volumes = []
for (name, _), v in self._volumes.iteritems():
if name == cws_name:
volumes.append(v)
return volumes
|
Fix issue with brackets in generated queries. | (function () {
'use strict';
define(
[
'lodash',
'jquery'
],
function (_, $) {
return function (baseUrl, ajaxOptions, noCache, logErrors) {
var queryString;
queryString = function (parameters) {
return _.map(parameters.children, function (child) {
return child.hasOwnProperty('children') ?
'(' + queryString(child) + ')' :
'(' + child.key + ':' + child.value + ')';
})
.join(' ' + parameters.operator + ' ');
};
return function (parameters, callback) {
$.ajax(_.merge({}, ajaxOptions, {
url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''),
success: function (result) {
if (!result.ok) {
return callback(new Error('Invalid response received from server'));
}
delete result.ok;
callback(undefined, _.values(result));
},
error: function (jqXHR, textStatus, err) {
if (logErrors && console && typeof console.error === 'function') {
console.error(jqXHR, textStatus, err);
}
callback(err || 'An unknown error occurred');
}
}));
};
};
}
);
}());
| (function () {
'use strict';
define(
[
'lodash',
'jquery'
],
function (_, $) {
return function (baseUrl, ajaxOptions, noCache, logErrors) {
var queryString;
queryString = function (parameters) {
return '(' + _.map(parameters.children, function (child) {
return child.hasOwnProperty('children') ?
queryString(child) :
'(' + child.key + ':' + child.value + ')';
})
.join(' ' + parameters.operator + ' ') + ')';
};
return function (parameters, callback) {
$.ajax(_.merge({}, ajaxOptions, {
url: baseUrl + '?q=' + queryString(parameters || {}) + (noCache ? '&noCache=1' : ''),
success: function (result) {
if (!result.ok) {
return callback(new Error('Invalid response received from server'));
}
delete result.ok;
callback(undefined, _.values(result));
},
error: function (jqXHR, textStatus, err) {
if (logErrors && console && typeof console.error === 'function') {
console.error(jqXHR, textStatus, err);
}
callback(err || 'An unknown error occurred');
}
}));
};
};
}
);
}());
|
Remove python prefix from name | from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='[email protected]',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| from __future__ import unicode_literals
import re
from setuptools import setup, find_packages
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
name='Python-Tunigo',
version=get_version('tunigo/__init__.py'),
url='https://github.com/trygveaa/python-tunigo',
license='Apache License, Version 2.0',
author='Trygve Aaberge',
author_email='[email protected]',
description='Python API for the browse feature of Spotify',
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests', 'tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'requests >= 2.0.0',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
|
Update defaultSetting with defaut rosbridge address
Hi,
Currently no address are provide as default, so the page stop loading and we cannot configure where the WS server (rosbridge) is .
By using location.hostname as address we provide webserver addresse as default (usualy the same as ws server) and port 9090 is rosbridge default port ! | angular.module('roscc')
.controller('SettingsController', function($scope, localStorageService) {
$scope.add = function() {
$scope.settings.push( JSON.parse(JSON.stringify(defaultSetting)) ); // Clone object
$scope.selectedSettingIndex = String($scope.settings.length - 1);
};
$scope.remove = function() {
$scope.settings.splice($scope.selectedSettingIndex, 1);
$scope.selectedSettingIndex = '0';
if (!$scope.settings.length) {
$scope.add();
}
};
$scope.selectedSettingIndex = localStorageService.get('selectedSettingIndex');
$scope.settings = JSON.parse(localStorageService.get('settings'));
var defaultSetting = {
name: 'New Setting',
address: location.hostname,
port: 9090,
log: '/rosout', imagePreview: { port: 0, quality: 70, width: 640, height: 480 },
battery: true,
batteryTopic: ''
};
if (!$scope.settings) {
$scope.settings = [defaultSetting];
}
if (!$scope.selectedSettingIndex || $scope.selectedSettingIndex > $scope.settings.length) {
$scope.selectedSettingIndex = '0';
}
$scope.$watch('selectedSettingIndex', function() {
localStorageService.set('selectedSettingIndex', $scope.selectedSettingIndex);
});
$scope.$watch('settings', function() {
localStorageService.set('settings', JSON.stringify($scope.settings));
}, true);
});
| angular.module('roscc')
.controller('SettingsController', function($scope, localStorageService) {
$scope.add = function() {
$scope.settings.push( JSON.parse(JSON.stringify(defaultSetting)) ); // Clone object
$scope.selectedSettingIndex = String($scope.settings.length - 1);
};
$scope.remove = function() {
$scope.settings.splice($scope.selectedSettingIndex, 1);
$scope.selectedSettingIndex = '0';
if (!$scope.settings.length) {
$scope.add();
}
};
$scope.selectedSettingIndex = localStorageService.get('selectedSettingIndex');
$scope.settings = JSON.parse(localStorageService.get('settings'));
var defaultSetting = {
name: 'New Setting',
address: '',
port: '',
log: '/rosout', imagePreview: { port: 0, quality: 70, width: 640, height: 480 },
battery: true,
batteryTopic: ''
};
if (!$scope.settings) {
$scope.settings = [defaultSetting];
}
if (!$scope.selectedSettingIndex || $scope.selectedSettingIndex > $scope.settings.length) {
$scope.selectedSettingIndex = '0';
}
$scope.$watch('selectedSettingIndex', function() {
localStorageService.set('selectedSettingIndex', $scope.selectedSettingIndex);
});
$scope.$watch('settings', function() {
localStorageService.set('settings', JSON.stringify($scope.settings));
}, true);
});
|
Check for vendor returned by API call in my-rep directive. This prevents tray from showing if there is no vendor! | angular
.module('app')
.directive("myRep", ['$location', 'authService', 'vendorService', '$document',
function($location, authService, vendorService, $document) {
return {
replace: true,
templateUrl: 'app/templates/directives/myRep.html',
link: function(scope, element, attrs, ctrl) {
// get current user
var user = authService.getCurrentUser();
// only show this to vendorReps
if(!user || user.role !== 'vendorRep') return;
// user might not have a vendor
if(!user.vendorId) return;
// gets the vendor
vendorService.getSalesRep(user.vendorId).then(function(response) {
// save to local scope
scope.salesRep = response;
if(!scope.salesRep._id) return;
// set class on body
angular.element($document[0].body).addClass('has-rep-tray');
});
}
};
}
]); | angular
.module('app')
.directive("myRep", ['$location', 'authService', 'vendorService', '$document',
function($location, authService, vendorService, $document) {
return {
replace: true,
templateUrl: 'app/templates/directives/myRep.html',
link: function(scope, element, attrs, ctrl) {
// get current user
var user = authService.getCurrentUser();
// only show this to vendorReps
if(!user || user.role !== 'vendorRep') return;
// user might not have a vendor
if(!user.vendorId) return;
// gets the vendor
vendorService.getSalesRep(user.vendorId).then(function(response) {
// save to local scope
scope.salesRep = response;
// set class on body
angular.element($document[0].body).addClass('has-rep-tray');
});
}
};
}
]); |
Make runner stop when player last action is to end | package wumpus;
import java.util.Iterator;
import java.util.NoSuchElementException;
import wumpus.Environment.Result;
import wumpus.Environment.Action;
/**
* The iteration of plays that the player can take until reaches its end.
*/
public class Runner implements Iterable<Player>, Iterator<Player> {
private final World world;
private int iterations = 0;
private int maxIterations;
/**
* The runner constructor.
* @param world The world instance.
*/
public Runner(World world) {
this.world = world;
this.maxIterations = world.getMaxSteps();
}
/**
* Returns the iterator that can be user in a loop.
* @return Itself
*/
public Iterator<Player> iterator() {
return this;
}
/**
* Check if the game has ended.
* @return
*/
public boolean hasNext() {
Player player = world.getPlayer();
return iterations < maxIterations && world.getResult() != Result.WIN &&
player.isAlive() && player.getLastAction() != Action.END;
}
/**
* Get player instance to calculate the next iteration.
* @return The current player instance
*/
public Player next() {
if (!hasNext()) throw new NoSuchElementException();
iterations++;
return world.getPlayer();
}
/**
* Operation not supported, throws an error.
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
| package wumpus;
import java.util.Iterator;
import java.util.NoSuchElementException;
import wumpus.Environment.Result;
/**
* The iteration of plays that the player can take until reaches its end.
*/
public class Runner implements Iterable<Player>, Iterator<Player> {
private final World world;
private int iterations = 0;
private int maxIterations;
/**
* The runner constructor.
* @param world The world instance.
*/
public Runner(World world) {
this.world = world;
this.maxIterations = world.getMaxSteps();
}
/**
* Returns the iterator that can be user in a loop.
* @return Itself
*/
public Iterator<Player> iterator() {
return this;
}
/**
* Check if the game has ended.
* @return
*/
public boolean hasNext() {
Player player = world.getPlayer();
return iterations < maxIterations &&
player.isAlive() && world.getResult() != Result.WIN;
}
/**
* Get player instance to calculate the next iteration.
* @return The current player instance
*/
public Player next() {
if (!hasNext()) throw new NoSuchElementException();
iterations++;
return world.getPlayer();
}
/**
* Operation not supported, throws an error.
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
|
Use Numpy dtype when creating Numpy array
(as opposed to the Numba dtype) | import numpy as np
from numba import from_dtype, cuda
from numba import unittest_support as unittest
class TestAlignment(unittest.TestCase):
def test_record_alignment(self):
rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True)
rec = from_dtype(rec_dtype)
@cuda.jit((rec[:],))
def foo(a):
i = cuda.grid(1)
a[i].a = a[i].b
a_recarray = np.recarray(3, dtype=rec_dtype)
for i in range(a_recarray.size):
a_rec = a_recarray[i]
a_rec.a = 0
a_rec.b = (i + 1) * 123
foo[1, 3](a_recarray)
self.assertTrue(np.all(a_recarray.a == a_recarray.b))
def test_record_alignment_error(self):
rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')])
rec = from_dtype(rec_dtype)
with self.assertRaises(Exception) as raises:
@cuda.jit((rec[:],))
def foo(a):
i = cuda.grid(1)
a[i].a = a[i].b
self.assertTrue('type float64 is not aligned' in str(raises.exception))
if __name__ == '__main__':
unittest.main()
| import numpy as np
from numba import from_dtype, cuda
from numba import unittest_support as unittest
class TestAlignment(unittest.TestCase):
def test_record_alignment(self):
rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True)
rec = from_dtype(rec_dtype)
@cuda.jit((rec[:],))
def foo(a):
i = cuda.grid(1)
a[i].a = a[i].b
a_recarray = np.recarray(3, dtype=rec)
for i in range(a_recarray.size):
a_rec = a_recarray[i]
a_rec.a = 0
a_rec.b = (i + 1) * 123
foo[1, 3](a_recarray)
self.assertTrue(np.all(a_recarray.a == a_recarray.b))
def test_record_alignment_error(self):
rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')])
rec = from_dtype(rec_dtype)
with self.assertRaises(Exception) as raises:
@cuda.jit((rec[:],))
def foo(a):
i = cuda.grid(1)
a[i].a = a[i].b
self.assertTrue('type float64 is not aligned' in str(raises.exception))
if __name__ == '__main__':
unittest.main()
|
Add machine name to heap dump file name | /**
* Created by ronyadgar on 29/11/2015.
*/
var heapdump = require('heapdump');
var logger = require('./logger/logger')(module);
var fs = require('fs');
var config = require('./../common/Configuration');
var path = require('path');
var hostname = require('../common/utils/hostname');
module.exports = (function(){
var timeInterval = config.get('heapDumpParams').timeInterval || '9000000';
var windowSize = config.get('heapDumpParams').windowSize || '3';
var rootFolderPath = config.get('rootFolderPath');
var enabled = config.get('heapDumpParams').enabled;
var listOfHeapDumpFiles = [];
if (enabled) {
setInterval(function () {
var filename = Date.now() + '.heapsnapshot';
heapdump.writeSnapshot(path.join(rootFolderPath, hostname + "_" + filename), function (err, filename) {
if (err) {
logger.error("Failed to write snapshot in " + filename + ": " + err);
}
else {
if (listOfHeapDumpFiles.length === windowSize) {
var fileToDelete = listOfHeapDumpFiles.shift();
fs.unlink(fileToDelete, function (err) {
if (err) {
logger.error("Failed to delete " + fileToDelete + ": " + err);
}
else {
logger.info("Successfully deleted " + fileToDelete);
}
});
}
listOfHeapDumpFiles.push(filename);
logger.info("Successfully wrote snapshot to " + filename);
}
});
}, timeInterval);
}
})(); | /**
* Created by ronyadgar on 29/11/2015.
*/
var heapdump = require('heapdump');
var logger = require('./logger/logger')(module);
var fs = require('fs');
var config = require('./../common/Configuration');
var path = require('path');
module.exports = (function(){
var timeInterval = config.get('heapDumpParams').timeInterval || '9000000';
var windowSize = config.get('heapDumpParams').windowSize || '3';
var rootFolderPath = config.get('rootFolderPath');
var enabled = config.get('heapDumpParams').enabled;
var listOfHeapDumpFiles = [];
if (enabled) {
setInterval(function () {
var filename = Date.now() + '.heapsnapshot';
heapdump.writeSnapshot(path.join(rootFolderPath, filename), function (err, filename) {
if (err) {
logger.error("Failed to write snapshot in " + filename + ": " + err);
}
else {
if (listOfHeapDumpFiles.length === windowSize) {
var fileToDelete = listOfHeapDumpFiles.shift();
fs.unlink(fileToDelete, function (err) {
if (err) {
logger.error("Failed to delete " + fileToDelete + ": " + err);
}
else {
logger.info("Successfully deleted " + fileToDelete);
}
});
}
listOfHeapDumpFiles.push(filename);
logger.info("Successfully wrote snapshot to " + filename);
}
});
}, timeInterval);
}
})(); |
Clarify what the happens in argument analysis | module.exports = class Call {
constructor(callee, args) {
this.callee = callee;
this.args = args;
}
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
this.checkNumberOfArguments(this.callee.referent);
this.checkArgumentNamesAndPositionalRules(this.callee.referent);
}
checkNumberOfArguments(callee) {
const numArgs = this.args.length;
const numRequiredParams = callee.requiredParameterNames.size;
const numParams = callee.allParameterNames.size;
if (numArgs < numRequiredParams) {
// We have to at least cover all the required parameters
throw new Error(`Expected at least ${numRequiredParams} arguments but called with ${numArgs}`);
}
if (numArgs > numParams) {
// We can't pass more arguments than the total number of parameters
throw new Error(`Expected at most ${numParams} arguments but called with ${numArgs}`);
}
}
checkArgumentNamesAndPositionalRules(callee) {
let keywordArgumentSeen = false;
this.args.forEach((arg) => {
if (arg.id) {
// This is a keyword argument, record that fact and check that it's okay
keywordArgumentSeen = true;
if (!callee.allParameterNames.has(arg.id)) {
throw new Error(`Function does not have a parameter called ${arg.id}`);
}
} else if (keywordArgumentSeen) {
// This is a positional argument, but a prior one was a keyword one
throw new Error('Positional argument in call after keyword argument');
}
});
}
};
| module.exports = class Call {
constructor(callee, args) {
this.callee = callee;
this.args = args;
}
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
this.checkNumberOfArguments(this.callee.referent);
this.checkArgumentNamesAndPositionalRules(this.callee.referent);
}
checkNumberOfArguments(callee) {
const numArgs = this.args.length;
const numRequiredParams = callee.requiredParameterNames.size;
const numParams = callee.allParameterNames.size;
if (numArgs < numRequiredParams) {
throw new Error(`Expected at least ${numRequiredParams} arguments but called with ${numArgs}`);
}
if (numArgs > numParams) {
throw new Error(`Expected at most ${numParams} arguments but called with ${numArgs}`);
}
}
checkArgumentNamesAndPositionalRules(callee) {
let keywordArgumentSeen = false;
this.args.forEach((arg) => {
if (arg.id) {
// This is a keyword argument, record that fact and check that it's okay
keywordArgumentSeen = true;
if (!callee.allParameterNames.has(arg.id)) {
throw new Error(`Function does not have a parameter called ${arg.id}`);
}
} else if (keywordArgumentSeen) {
// This is a positional argument, but a prior one was a keyword one
throw new Error('Positional argument in call after keyword argument');
}
});
}
};
|
Add check for redeclared symbols. | package pt.up.fe.comp.utils;
import java.util.Stack;
public class SymbolTable<T> {
public SymbolTable(boolean lazy) {
_lazy = lazy;
beginScope();
}
public void beginScope() {
_scopes.add(new Scope<T>(_lazy));
}
public void endScope() {
// do not delete "global" scope
if (_scopes.size() > 1)
_scopes.pop();
}
public void setLazy(boolean value) {
_lazy = value;
for (Scope<T> scp : _scopes) {
scp.setLazy(value);
}
}
public void addSymbol(String name, Class type, Producer<T> init) {
if (!contains(name))
_scopes.peek().addSymbol(name, type, init);
else throw new Error(name + " is already declared.");
}
public boolean contains(String name) {
return get(name) != null;
}
public T get(String name) {
T value;
for (Scope<T> scp : _scopes) {
value = scp.getSymbol(name);
if (value != null) return value;
}
return null;
}
public Class getType(String name) {
Class type;
for (Scope<T> scp : _scopes) {
type = scp.getSymbolType(name);
if (type != null) return type;
}
return null;
}
private Stack<Scope<T>> _scopes = new Stack<>();
private boolean _lazy;
}
| package pt.up.fe.comp.utils;
import java.util.Stack;
public class SymbolTable<T> {
public SymbolTable(boolean lazy) {
_lazy = lazy;
beginScope();
}
public void beginScope() {
_scopes.add(new Scope<T>(_lazy));
}
public void endScope() {
// do not delete "global" scope
if (_scopes.size() > 1)
_scopes.pop();
}
public void setLazy(boolean value) {
_lazy = value;
for (Scope<T> scp : _scopes) {
scp.setLazy(value);
}
}
public void addSymbol(String name, Class type, Producer<T> init) {
_scopes.peek().addSymbol(name, type, init);
}
public boolean contains(String name) {
return get(name) != null;
}
public T get(String name) {
T value;
for (Scope<T> scp : _scopes) {
value = scp.getSymbol(name);
if (value != null) return value;
}
return null;
}
public Class getType(String name) {
Class type;
for (Scope<T> scp : _scopes) {
type = scp.getSymbolType(name);
if (type != null) return type;
}
return null;
}
private Stack<Scope<T>> _scopes = new Stack<>();
private boolean _lazy;
}
|
Fix issue with create_superuser method on UserManager | from django.utils import timezone
from django.contrib.auth.models import BaseUserManager
from model_utils.managers import InheritanceQuerySet
from .conf import settings
class UserManager(BaseUserManager):
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
users_auto_activate = not settings.USERS_VERIFY_EMAIL
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
is_active = extra_fields.pop('is_active', users_auto_activate)
user = self.model(email=email, is_staff=is_staff, is_active=is_active,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
is_staff = extra_fields.pop('is_staff', False)
return self._create_user(email, password, is_staff, False,
**extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True,
is_active=True, **extra_fields)
class UserInheritanceManager(UserManager):
def get_queryset(self):
return InheritanceQuerySet(self.model).select_subclasses()
| from django.utils import timezone
from django.contrib.auth.models import BaseUserManager
from model_utils.managers import InheritanceQuerySet
from .conf import settings
class UserManager(BaseUserManager):
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
users_auto_activate = not settings.USERS_VERIFY_EMAIL
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
is_active = extra_fields.pop('is_active', users_auto_activate)
user = self.model(email=email, is_staff=is_staff, is_active=is_active,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
is_staff = extra_fields.pop('is_staff', False)
return self._create_user(email, password, is_staff, False,
**extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True,
**extra_fields)
class UserInheritanceManager(UserManager):
def get_queryset(self):
return InheritanceQuerySet(self.model).select_subclasses()
|
Remove unneeded TEST_RUN_EDIT permission from default new user role. | from django.core.management.base import BaseCommand, CommandError
from ...api import admin
from ...models import Company, CompanyList
from ....users.models import Role, RoleList, PermissionList
DEFAULT_NEW_USER_ROLE_PERMISSIONS = set([
"PERMISSION_COMPANY_INFO_VIEW",
"PERMISSION_PRODUCT_VIEW",
"PERMISSION_TEST_CASE_VIEW",
"PERMISSION_TEST_CASE_EDIT",
"PERMISSION_TEST_CYCLE_VIEW",
"PERMISSION_TEST_RUN_VIEW",
"PERMISSION_TEST_RUN_ASSIGNMENT_EXECUTE",
"PERMISSION_ENVIRONMENT_VIEW",
])
class Command(BaseCommand):
help = ("Create a company resource and associated default new user role "
"with appropriate tester permissions.")
args = '"Company Name"'
def handle(self, *args, **options):
if not args:
raise CommandError("Company name is required.")
name = " ".join(args)
# @@@ U.S. is country ID 239, un-hardcode this
company = Company(name=name, country=239)
CompanyList.get(auth=admin).post(company)
role = Role(name="%s Tester" % name, company=company)
RoleList.get(auth=admin).post(role)
permissions = [p for p in PermissionList.get(auth=admin)
if p.permissionCode in DEFAULT_NEW_USER_ROLE_PERMISSIONS]
role.permissions = permissions
print "Created company id %s and role id %s." % (company.id, role.id)
| from django.core.management.base import BaseCommand, CommandError
from ...api import admin
from ...models import Company, CompanyList
from ....users.models import Role, RoleList, PermissionList
DEFAULT_NEW_USER_ROLE_PERMISSIONS = set([
"PERMISSION_COMPANY_INFO_VIEW",
"PERMISSION_PRODUCT_VIEW",
"PERMISSION_TEST_CASE_VIEW",
"PERMISSION_TEST_CASE_EDIT",
"PERMISSION_TEST_CYCLE_VIEW",
"PERMISSION_TEST_RUN_VIEW",
"PERMISSION_TEST_RUN_EDIT",
"PERMISSION_TEST_RUN_ASSIGNMENT_EXECUTE",
"PERMISSION_ENVIRONMENT_VIEW",
])
class Command(BaseCommand):
help = ("Create a company resource and associated default new user role "
"with appropriate tester permissions.")
args = '"Company Name"'
def handle(self, *args, **options):
if not args:
raise CommandError("Company name is required.")
name = " ".join(args)
# @@@ U.S. is country ID 239, un-hardcode this
company = Company(name=name, country=239)
CompanyList.get(auth=admin).post(company)
role = Role(name="%s Tester" % name, company=company)
RoleList.get(auth=admin).post(role)
permissions = [p for p in PermissionList.get(auth=admin)
if p.permissionCode in DEFAULT_NEW_USER_ROLE_PERMISSIONS]
role.permissions = permissions
print "Created company id %s and role id %s." % (company.id, role.id)
|
Add red color on dislikes | import React, { Component } from 'react';
import { Link } from 'react-router';
import Avatar from '../widgets/Avatar';
import './LikesList.scss';
export default class LikesList extends Component {
constructor(props) {
super(props);
this.state = {
show: 10,
};
}
handleShowMore() {
this.setState({
show: this.state.show + 10,
});
}
render() {
const { activeVotes } = this.props;
const hasMore = activeVotes.length > this.state.show;
return (
<div className="LikesList">
{
activeVotes.slice(0, this.state.show).map(vote =>
<div className="LikesList__item" key={vote.voter}>
<Avatar xs username={vote.voter} />
{ ' ' }
<Link to={`/@${vote.voter}`}>
@{vote.voter}
</Link>
{ ' ' }
{vote.percent < 0
? <span className="text-danger">Disliked</span>
: 'Liked'
}
</div>
)
}
{ hasMore &&
<a
className="LikesList__showMore"
tabIndex="0"
onClick={() => this.handleShowMore()}
>
See More Likes
</a>
}
</div>
);
}
}
| import React, { Component } from 'react';
import { Link } from 'react-router';
import Avatar from '../widgets/Avatar';
import './LikesList.scss';
export default class LikesList extends Component {
constructor(props) {
super(props);
this.state = {
show: 10,
};
}
handleShowMore() {
this.setState({
show: this.state.show + 10,
});
}
render() {
const { activeVotes } = this.props;
const hasMore = activeVotes.length > this.state.show;
return (
<div className="LikesList">
{
activeVotes.slice(0, this.state.show).map(vote =>
<div className="LikesList__item" key={vote.voter}>
<Avatar xs username={vote.voter} />
{ ' ' }
<Link to={`/@${vote.voter}`}>
@{vote.voter}
</Link>
{ ' ' }
{vote.percent < 0
? 'Disliked'
: 'Liked'
}
</div>
)
}
{ hasMore &&
<a
className="LikesList__showMore"
tabIndex="0"
onClick={() => this.handleShowMore()}
>
See More Likes
</a>
}
</div>
);
}
}
|
Update list command to display table | <?php namespace NZTim\Queue\Commands;
use Illuminate\Console\Command;
use NZTim\Queue\QueuedJob\QueuedJob;
use NZTim\Queue\QueueManager;
class ListCommand extends Command
{
protected $signature = 'queuemgr:list {days=7}';
protected $description = 'Lists recent jobs within the specified number of days';
/** @var QueueManager */
protected $queueManager;
public function __construct(QueueManager $queueManager)
{
parent::__construct();
$this->queueManager = $queueManager;
}
public function handle()
{
$days = $this->argument('days');
$entries = $this->queueManager->recent($days);
$jobs = [];
foreach($entries as $entry) {
/** @var QueuedJob $entry */
$job['Created'] = $entry->created_at->format('Y-m-d - H:i');
$job['ID'] = "ID:{$entry->getId()}";
$job['Class'] = get_class($entry->getJob());
$job['Status'] = is_null($entry->deleted_at) ? "Incomplete" : "Complete";
$job['Status'] .= " ({$entry->attempts})";
if ($entry->attempts == 0) {
$job['Status'] = "Failed!!!";
}
$jobs[] = $job;
}
if (count($jobs)) {
$this->table(array_keys($jobs[0]), $jobs);
} else {
$this->info('No jobs found');
}
}
}
| <?php namespace NZTim\Queue\Commands;
use Illuminate\Console\Command;
use NZTim\Queue\QueueManager;
class ListCommand extends Command
{
protected $signature = 'queuemgr:list {days=7}';
protected $description = 'Lists recent jobs within the specified number of days';
/** @var QueueManager */
protected $queueManager;
public function __construct(QueueManager $queueManager)
{
parent::__construct();
$this->queueManager = $queueManager;
}
public function handle()
{
$days = $this->argument('days');
$entries = $this->queueManager->recent($days);
foreach($entries as $entry) {
$message = $entry->created_at->format('Y-m-d @ H:i') . ' | ';
$message .= "ID:{$entry->getId()} | ";
$message .= get_class($entry->getJob()) . ' | ';
$status = "Complete";
$method = "info";
if (is_null($entry->deleted_at)) {
$status = "Incomplete";
$method = "error";
}
$status .= " ({$entry->attempts})";
if ($entry->attempts == 0) {
$status = "Failed!";
$method = 'error';
}
$message .= $status;
$this->$method($message);
}
}
}
|
Refactor adding temp to permutations | """Leetcode 46. Permutations
Medium
URL: https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
"""
class Solution(object):
def _backtrack(self, permutations, temps, nums):
if len(temps) == len(nums):
# One of permutations is completed.
permutations.append(temps[:])
return None
for i in range(len(nums)):
# Constraint: If num i was used, skip it; otherwise add it to temps.
if nums[i] in temps:
continue
temps.append(nums[i])
# Apply DFS by recursion with backtracking.
self._backtrack(permutations, temps, nums)
temps.pop()
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
Time complexity: O(n!).
Space complexity: O(n).
"""
permutations = []
self._backtrack(permutations, [], nums)
return permutations
def main():
nums = [1, 2, 3]
print Solution().permute(nums)
if __name__ == '__main__':
main()
| """Leetcode 46. Permutations
Medium
URL: https://leetcode.com/problems/permutations/
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
"""
class Solution(object):
def _backtrack(self, permutations, temps, nums):
if len(temps) == len(nums):
# One of permutations is completed.
permutations.append(temps[:])
else:
for i in range(len(nums)):
# If num i was used, skip it; otherwise add it to temps.
if nums[i] in temps:
continue
temps.append(nums[i])
# Apply DFS by recursion with backtracking.
self._backtrack(permutations, temps, nums)
temps.pop()
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
Time complexity: O(n!).
Space complexity: O(n).
"""
permutations = []
self._backtrack(permutations, [], nums)
return permutations
def main():
nums = [1, 2, 3]
print Solution().permute(nums)
if __name__ == '__main__':
main()
|
Increase the version to 0.2
An backward incompatible change was introduced by removing the package
names metadata from the inventory core.
If necessary, it is hereby advised to provide the metadata in other ways
supported by ansible, such as variables defined on role or playbook
level. | # coding: utf-8
# Author: Milan Kubik
from setuptools import setup, find_packages
with open('README.md') as f:
long_description = f.read()
setup(
name='ipaqe-dyndir',
version='0.2.0',
description='Ansible dynamic inventory for FreeIPA',
long_description=long_description,
keywords='freeipa tests ansible',
license='MIT',
author='Milan Kubik',
author_email='[email protected]',
url='https://github.com/apophys/ipaqe-dyndir',
classifiers=[
'Development Status :: 3 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(exclude=['tests']),
install_requires=['PyYAML'],
entry_points={
'console_scripts': [
'ipaqe-dyndir = ipaqe_dyndir.__main__:main'
],
'org.freeipa.dyndir.plugins': [
'updates-testing = ipaqe_dyndir.builtin.repos:UpdatesTestingRepositoryPlugin',
'copr = ipaqe_dyndir.builtin.repos:COPRPlugin'
]
}
)
| # coding: utf-8
# Author: Milan Kubik
from setuptools import setup, find_packages
with open('README.md') as f:
long_description = f.read()
setup(
name='ipaqe-dyndir',
version='0.1.4',
description='Ansible dynamic inventory for FreeIPA',
long_description=long_description,
keywords='freeipa tests ansible',
license='MIT',
author='Milan Kubik',
author_email='[email protected]',
url='https://github.com/apophys/ipaqe-dyndir',
classifiers=[
'Development Status :: 3 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(exclude=['tests']),
install_requires=['PyYAML'],
entry_points={
'console_scripts': [
'ipaqe-dyndir = ipaqe_dyndir.__main__:main'
],
'org.freeipa.dyndir.plugins': [
'updates-testing = ipaqe_dyndir.builtin.repos:UpdatesTestingRepositoryPlugin',
'copr = ipaqe_dyndir.builtin.repos:COPRPlugin'
]
}
)
|
Remove a bit of django boilerplate | from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': '[email protected]'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, '[email protected]')
self.visit('/')
BROWSER.fill('email', '[email protected]')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, '[email protected]')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', '[email protected]')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
| """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': '[email protected]'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, '[email protected]')
self.visit('/')
BROWSER.fill('email', '[email protected]')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, '[email protected]')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', '[email protected]')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
|
Add mergeApiHeaders and mergeApiBody method.
Signed-off-by: crynobone <[email protected]> | <?php
namespace Katsana\Sdk;
use GuzzleHttp\Psr7\Uri;
use Laravie\Codex\Request as BaseRequest;
abstract class Request extends BaseRequest
{
/**
* Get API Header.
*
* @return array
*/
protected function getApiHeaders()
{
$headers = [
'Accept' => "application/vnd.KATSANA.{$this->getVersion()}+json",
];
if (! is_null($accessToken = $this->client->getAccessToken())) {
$headers['Authorization'] = "Bearer {$accessToken}";
}
return $headers;
}
/**
* Get API Body.
*
* @return array
*/
protected function getApiBody()
{
return [];
}
/**
* Merge API Headers.
*
* @param array $headers
*
* @return array
*/
protected function mergeApiHeaders(array $headers = [])
{
return array_merge($this->getApiHeaders(), $headers);
}
/**
* Merge API Body.
*
* @param array $headers
*
* @return array
*/
protected function mergeApiBody(array $body = [])
{
return array_merge($this->getApiBody(), $body);
}
/**
* Get URI Endpoint.
*
* @param string $endpoint
*
* @return \GuzzleHttp\Psr7\Uri
*/
protected function getUriEndpoint($endpoint)
{
$query['client_id'] = $this->client->getClientId();
$query['client_secret'] = $this->client->getClientSecret();
$endpoint .= '?'.http_build_query($query, null, '&');
return new Uri(sprintf('%s/%s', $this->client->getApiEndpoint(), $endpoint));
}
}
| <?php
namespace Katsana\Sdk;
use GuzzleHttp\Psr7\Uri;
use Laravie\Codex\Request as BaseRequest;
abstract class Request extends BaseRequest
{
/**
* Get API Header.
*
* @return array
*/
protected function getApiHeaders()
{
$headers = [
'Accept' => "application/vnd.KATSANA.{$this->getVersion()}+json",
];
if (! is_null($accessToken = $this->client->getAccessToken())) {
$headers['Authorization'] = "Bearer {$accessToken}";
}
return $headers;
}
/**
* Get API Body.
*
* @return array
*/
protected function getApiBody()
{
return [];
}
/**
* Get URI Endpoint.
*
* @param string $endpoint
*
* @return \GuzzleHttp\Psr7\Uri
*/
protected function getUriEndpoint($endpoint)
{
$query['client_id'] = $this->client->getClientId();
$query['client_secret'] = $this->client->getClientSecret();
$endpoint .= '?'.http_build_query($query, null, '&');
return new Uri(sprintf('%s/%s', $this->client->getApiEndpoint(), $endpoint));
}
}
|
Fix @csutter's sloppy code style | define([ "jquery", "lib/utils/viewport_helper" ], function($, isInViewport) {
"use strict";
var HeroParallax,
_pageYOffset,
started = false,
speed = 15,
els;
HeroParallax = function( args ) {
this.$els = args.els || $(".js-bg-parallax");
$(window).bind("scroll", $.proxy(this._onScroll, this));
};
HeroParallax.prototype._updateBg = function( i, el ) {
var $el = $(el);
if (isInViewport(el)) {
var percent = 30 + ((($el.offset().top - _pageYOffset) * speed) / $el.height());
$el.css("backgroundPosition", "center " + percent + "%");
}
};
HeroParallax.prototype._update = function() {
window.lp.supports.requestAnimationFrame($.proxy(this._update, this));
$.each(this.$els, $.proxy(this._updateBg, this));
};
HeroParallax.prototype._startrAF = function() {
if (!started){
window.lp.supports.requestAnimationFrame($.proxy(this._update, this));
started = true;
}
};
HeroParallax.prototype._onScroll = function() {
_pageYOffset = window.pageYOffset;
this._startrAF();
};
if ( window.lp.supports.requestAnimationFrame ){
els = $(".js-bg-parallax");
if (els.length) {
new HeroParallax({
els: els
});
}
}
return HeroParallax;
});
| define([ "jquery", "lib/utils/viewport_helper" ], function($, isInViewport) {
"use strict";
var HeroParallax,
_pageYOffset,
started = false,
speed = 15,
els;
HeroParallax = function( args ) {
this.$els = args.els || $(".js-bg-parallax");
$(window).bind("scroll", $.proxy(this._onScroll, this));
};
HeroParallax.prototype._updateBg = function( i, el ) {
var $el = $(el);
if (isInViewport(el)) {
var percent = 30 + ((($el.offset().top - _pageYOffset) * speed) / $el.height());
$el.css("backgroundPosition", "center " + percent + "%");
}
};
HeroParallax.prototype._update = function() {
window.lp.supports.requestAnimationFrame($.proxy(this._update, this));
$.each(this.$els, $.proxy(this._updateBg, this));
};
HeroParallax.prototype._startrAF = function() {
if (!started){
window.lp.supports.requestAnimationFrame($.proxy(this._update, this));
started = true;
}
};
HeroParallax.prototype._onScroll = function() {
_pageYOffset = window.pageYOffset;
this._startrAF();
};
if ( window.lp.supports.requestAnimationFrame ){
els = $(".js-bg-parallax");
if (els.length) {
new HeroParallax({
els: els
});
}
}
return HeroParallax;
});
|
Reorder ENV urls redis providers. | import os
from django.conf import settings
SESSION_REDIS_HOST = getattr(
settings,
'SESSION_REDIS_HOST',
'127.0.0.1'
)
SESSION_REDIS_PORT = getattr(
settings,
'SESSION_REDIS_PORT',
6379
)
SESSION_REDIS_DB = getattr(
settings,
'SESSION_REDIS_DB',
0
)
SESSION_REDIS_PREFIX = getattr(
settings,
'SESSION_REDIS_PREFIX',
'django_sessions'
)
SESSION_REDIS_PASSWORD = getattr(
settings,
'SESSION_REDIS_PASSWORD',
None
)
SESSION_REDIS_UNIX_DOMAIN_SOCKET_PATH = getattr(
settings,
'SESSION_REDIS_UNIX_DOMAIN_SOCKET_PATH',
None
)
SESSION_REDIS_URL = getattr(
settings,
'SESSION_REDIS_URL',
None
)
SESSION_REDIS_CONNECTION_POOL = getattr(
settings,
'SESSION_REDIS_CONNECTION_POOL',
None
)
if SESSION_REDIS_URL is None:
# redis clouds ENV variables
SESSION_REDIS_ENV_URLS = getattr(
settings,
'SESSION_REDIS_ENV_URLS', (
'REDISCLOUD_URL'
'REDISTOGO_URL',
'OPENREDIS_URL',
'REDISGREEN_URL',
'MYREDIS_URL',
)
)
for url in SESSION_REDIS_ENV_URLS:
redis_env_url = os.environ.get(url)
if redis_env_url:
SESSION_REDIS_URL = redis_env_url
break
| import os
from django.conf import settings
SESSION_REDIS_HOST = getattr(
settings,
'SESSION_REDIS_HOST',
'127.0.0.1'
)
SESSION_REDIS_PORT = getattr(
settings,
'SESSION_REDIS_PORT',
6379
)
SESSION_REDIS_DB = getattr(
settings,
'SESSION_REDIS_DB',
0
)
SESSION_REDIS_PREFIX = getattr(
settings,
'SESSION_REDIS_PREFIX',
'django_sessions'
)
SESSION_REDIS_PASSWORD = getattr(
settings,
'SESSION_REDIS_PASSWORD',
None
)
SESSION_REDIS_UNIX_DOMAIN_SOCKET_PATH = getattr(
settings,
'SESSION_REDIS_UNIX_DOMAIN_SOCKET_PATH',
None
)
SESSION_REDIS_URL = getattr(
settings,
'SESSION_REDIS_URL',
None
)
SESSION_REDIS_CONNECTION_POOL = getattr(
settings,
'SESSION_REDIS_CONNECTION_POOL',
None
)
if SESSION_REDIS_URL is None:
# redis clouds ENV variables
SESSION_REDIS_ENV_URLS = getattr(
settings,
'SESSION_REDIS_ENV_URLS', (
'REDISTOGO_URL',
'OPENREDIS_URL',
'REDISGREEN_URL',
'MYREDIS_URL',
'REDISCLOUD_URL'
)
)
for url in SESSION_REDIS_ENV_URLS:
redis_env_url = os.environ.get(url)
if redis_env_url:
SESSION_REDIS_URL = redis_env_url
break
|
Reduce los sprites SVG a 32x32 | var gulp = require('gulp'),
gulpif = require('gulp-if'),
imagemin = require('gulp-imagemin'),
livereload = require('gulp-livereload'),
newer = require('gulp-newer'),
svgSprite = require('gulp-svg-sprite'),
CONFIG = require('../config.js')
gulp.task('svg-individual', function(cb) {
return gulp.src('./source/svg/*.svg')
.pipe(newer(CONFIG.dir.assets + 'svg'))
.pipe(imagemin())
.pipe(gulp.dest(CONFIG.dir.assets + 'svg/'))
.pipe(gulpif(CONFIG.noEsBuild, livereload()))
})
gulp.task('svg-sprite', function(cb) {
var options = {
shape: {
dimension: {
maxWidth: 32,
maxHeight: 32
},
id: {
whitespace: '_',
},
},
svg: {
namespaceClassnames: false,
},
mode: {
symbol: {
dest: '',
prefix: '',
bust: false,
sprite: 'sprite.svg'
}
}
}
return gulp.src('./source/svg/sprite/*.svg')
.pipe(newer(CONFIG.dir.assets + 'svg/sprite.svg'))
.pipe(svgSprite(options))
.pipe(gulp.dest(CONFIG.dir.assets + 'svg/'))
.pipe(gulpif(CONFIG.noEsBuild, livereload()))
})
gulp.task('svg', ['svg-individual', 'svg-sprite'])
| var gulp = require('gulp'),
gulpif = require('gulp-if'),
imagemin = require('gulp-imagemin'),
livereload = require('gulp-livereload'),
newer = require('gulp-newer'),
svgSprite = require('gulp-svg-sprite'),
CONFIG = require('../config.js')
gulp.task('svg-individual', function(cb) {
return gulp.src('./source/svg/*.svg')
.pipe(newer(CONFIG.dir.assets + 'svg'))
.pipe(imagemin())
.pipe(gulp.dest(CONFIG.dir.assets + 'svg/'))
.pipe(gulpif(CONFIG.noEsBuild, livereload()))
})
gulp.task('svg-sprite', function(cb) {
var options = {
shape: {
dimension: {
maxWidth: 100,
maxHeight: 100
},
id: {
whitespace: '_',
},
},
svg: {
namespaceClassnames: false,
},
mode: {
symbol: {
dest: '',
prefix: '',
bust: false,
sprite: 'sprite.svg'
}
}
}
return gulp.src('./source/svg/sprite/*.svg')
.pipe(newer(CONFIG.dir.assets + 'svg/sprite.svg'))
.pipe(svgSprite(options))
.pipe(gulp.dest(CONFIG.dir.assets + 'svg/'))
.pipe(gulpif(CONFIG.noEsBuild, livereload()))
})
gulp.task('svg', ['svg-individual', 'svg-sprite'])
|
Fix put to the torch and allow it to use saves | const DrawCard = require('../../../drawcard.js');
class PutToTheTorch extends DrawCard {
canPlay(player, card) {
if(player !== this.controller || this !== card) {
return false;
}
var currentChallenge = this.game.currentChallenge;
if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attackingPlayer !== this.controller || currentChallenge.strengthDifference < 5 ||
currentChallenge.challengeType !== 'military') {
return false;
}
return true;
}
play(player) {
if(this.controller !== player) {
return;
}
this.game.promptForSelect(player, {
activePromptTitle: 'Select a location to discard',
waitingPromptTitle: 'Waiting for opponent to use ' + this.name,
cardCondition: card => card.inPlay && card.controller !== player && card.getType() === 'location',
onSelect: (p, card) => this.onCardSelected(p, card)
});
}
onCardSelected(player, card) {
card.controller.discardCard(card);
this.game.addMessage('{0} uses {1} to discard {2}', player, this, card);
return true;
}
}
PutToTheTorch.code = '01042';
module.exports = PutToTheTorch;
| const DrawCard = require('../../../drawcard.js');
class PutToTheTorch extends DrawCard {
canPlay(player, card) {
if(player !== this.controller || this !== card) {
return false;
}
var currentChallenge = this.game.currentChallenge;
if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attacker !== this.controller || currentChallenge.strengthDifference < 5 ||
currentChallenge.challengeType !== 'military') {
return false;
}
return true;
}
play(player) {
if(this.controller !== player) {
return;
}
this.game.promptForSelect(player, {
activePromptTitle: 'Select a location to discard',
waitingPromptTitle: 'Waiting for opponent to use ' + this.name,
cardCondition: card => card.inPlay && card.controller !== player && card.getType() === 'location',
onSelect: (p, card) => this.onCardSelected(p, card)
});
}
onCardSelected(player, card) {
card.controller.moveCard(card, 'discard pile');
this.game.addMessage('{0} uses {1} to discard {2}', player, this, card);
return true;
}
}
PutToTheTorch.code = '01042';
module.exports = PutToTheTorch;
|
Add apikey to get_report api | from threading import Semaphore
from os.path import basename
from rate import ratelimiter
import requests
class VirusTotal():
def __init__(self, apikey, limit=4, every=60):
self.semaphore = threading.Semaphore(limit)
self.apikey = apikey
self.every = every
def scan(self, path):
with ratelimiter(self.semaphore, self.every):
with open(path, 'rb') as f:
params = {'apikey': self.apikey}
files = {'file': (basename(path), f)}
url = 'https://www.virustotal.com/vtapi/v2/file/scan'
res = requests.post(url, files=files, params=params)
return res.json()['resource']
def get_report(self, resource):
with ratelimiter(self.semaphore, self.every):
params = {'apikey': self.apikey, 'resource': resource}
url = 'https://www.virustotal.com/vtapi/v2/file/report'
return requests.get(url, params=params).json()
def get_num_detected(self, resource):
report = self.get_report(resource)
return sum(scan['detected'] for av, scan in report['scans'].items())
def get_percent_detected(self, resource):
report = self.get_report(resource)
return (sum(scan['detected'] for av, scan in report['scans'].items()) /
float(report['scans']))
| from threading import Semaphore
from os.path import basename
from rate import ratelimiter
import requests
class VirusTotal():
def __init__(self, apikey, limit=4, every=60):
self.semaphore = Semaphore(limit)
self.apikey = apikey
self.every = every
def scan(self, path):
with ratelimiter(self.semaphore, self.every):
with open(path, 'rb') as f:
params = {'apikey': self.apikey}
files = {'file': (basename(path), f)}
url = 'https://www.virustotal.com/vtapi/v2/file/scan'
res = requests.post(url, files=files, params=params)
return res.json()['resource']
def get_report(self, resource):
with ratelimiter(self.semaphore, self.every):
params = {'apikey': apikey, 'resource': resource}
url = 'https://www.virustotal.com/vtapi/v2/file/report'
return requests.get(url, params=params).json()
def get_num_detected(self, resource):
report = self.get_report(resource)
return sum(scan['detected'] for av, scan in report['scans'].items())
def get_percent_detected(self, resource):
report = self.get_report(resource)
return (sum(scan['detected'] for av, scan in report['scans'].items()) /
float(report['scans']))
|
Implement versioned crawling and remapping. | package no.uio.ifi.trackfind.backend.services;
import org.apache.commons.collections4.CollectionUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Service for maintaining versioning of indices. Currently backed by Git.
*
* @author Dmytro Titov
*/
@Service
public class VersioningService {
private Git git;
/**
* Commit everything.
*
* @param operation Operation to commit.
* @param repositoryName Name of changed repo to use in commit message.
* @throws GitAPIException In case of Git error.
*/
public void commitAllChanges(Operation operation, String repositoryName) throws GitAPIException {
git.add().addFilepattern(".").call();
git.commit().setAll(true).setMessage(operation.name() + ": " + repositoryName).call();
}
/**
* Tag current revision (HEAD, hopefully).
*
* @param repositoryName Name of changed repo to use in tag name.
* @throws GitAPIException In case of Git error.
*/
public void tag(String repositoryName) throws GitAPIException {
List<Ref> tags = git.tagList().call();
git.tag().setName(CollectionUtils.size(tags) + "." + repositoryName).call();
}
public enum Operation {
CRAWLING, REMAPPING
}
@Autowired
public void setGit(Git git) {
this.git = git;
}
}
| package no.uio.ifi.trackfind.backend.services;
import org.apache.commons.collections4.CollectionUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class VersioningService {
private Git git;
/**
* Commit everything.
*
* @param operation Operation to commit.
* @param repositoryName Name of changed repo to use in commit message.
* @throws GitAPIException In case of Git error.
*/
public void commitAllChanges(Operation operation, String repositoryName) throws GitAPIException {
git.add().addFilepattern(".").call();
git.commit().setAll(true).setMessage(operation.name() + ": " + repositoryName).call();
}
/**
* Tag current revision (HEAD, hopefully).
*
* @param repositoryName Name of changed repo to use in tag name.
* @throws GitAPIException In case of Git error.
*/
public void tag(String repositoryName) throws GitAPIException {
List<Ref> tags = git.tagList().call();
git.tag().setName(CollectionUtils.size(tags) + "." + repositoryName).call();
}
public enum Operation {
CRAWLING, REMAPPING
}
@Autowired
public void setGit(Git git) {
this.git = git;
}
}
|
Add additional logging to init game | /* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope, accounts) {
$scope.availableAccounts = accounts.availableAccounts;
$scope.selectedAccount = accounts.defaultAccount;
$scope.startcolor = 'white';
$scope.username = null;
$scope.etherbet = 0;
$scope.isSelectedAccount = function (account) {
return $scope.selectedAccount === account;
};
function initializeGame() {
$rootScope.$broadcast('message', 'Your game is being created, please wait a moment...',
'loading', 'startgame');
try {
console.log('Trying to init game', $scope.username, $scope.startcolor === 'white',
{
from: $scope.selectedAccount,
value: web3.toWei($scope.etherbet, 'ether')
});
Chess.initGame($scope.username, $scope.startcolor === 'white',
{
from: $scope.selectedAccount,
value: web3.toWei($scope.etherbet, 'ether')
});
}
catch(e) {
$rootScope.$broadcast('message', 'Could not initialize the game', 'loading', 'startgame');
}
}
$scope.selectOrCreateAccount = function($event) {
$event.preventDefault();
accounts.requestAccount(function(e, address) {
$scope.selectedAccount = address;
});
};
$scope.initializeGame = function (form) {
if(form.$valid) {
initializeGame();
}
};
$scope.getBalance = accounts.getBalance;
});
| /* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope, accounts) {
$scope.availableAccounts = accounts.availableAccounts;
$scope.selectedAccount = accounts.defaultAccount;
$scope.startcolor = 'white';
$scope.username = null;
$scope.etherbet = 0;
$scope.isSelectedAccount = function (account) {
return $scope.selectedAccount === account;
};
function initializeGame() {
$rootScope.$broadcast('message', 'Your game is being created, please wait a moment...',
'loading', 'startgame');
try {
Chess.initGame($scope.username, $scope.startcolor === 'white',
{
from: $scope.selectedAccount,
value: web3.toWei($scope.etherbet, 'ether')
});
}
catch(e) {
$rootScope.$broadcast('message', 'Could not initialize the game', 'loading', 'startgame');
}
}
$scope.selectOrCreateAccount = function($event) {
$event.preventDefault();
accounts.requestAccount(function(e, address) {
$scope.selectedAccount = address;
});
};
$scope.initializeGame = function (form) {
if(form.$valid) {
initializeGame();
}
};
$scope.getBalance = accounts.getBalance;
});
|
Test self request without authentication | from uuid import uuid4
from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
self.create_build(self.project)
path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex)
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert len(data) == 0
author = Author(email=self.default_user.email, name='Foo Bar')
db.session.add(author)
build = self.create_build(self.project, author=author)
path = '/api/0/authors/{0}/builds/'.format(author.id.hex)
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert len(data) == 1
assert data[0]['id'] == build.id.hex
path = '/api/0/authors/me/builds/'
resp = self.client.get(path)
assert resp.status_code == 401
self.login(self.default_user)
path = '/api/0/authors/me/builds/'
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert len(data) == 1
assert data[0]['id'] == build.id.hex
| from uuid import uuid4
from changes.config import db
from changes.models import Author
from changes.testutils import APITestCase
class AuthorBuildListTest(APITestCase):
def test_simple(self):
fake_author_id = uuid4()
self.create_build(self.project)
path = '/api/0/authors/{0}/builds/'.format(fake_author_id.hex)
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert len(data) == 0
author = Author(email=self.default_user.email, name='Foo Bar')
db.session.add(author)
build = self.create_build(self.project, author=author)
path = '/api/0/authors/{0}/builds/'.format(author.id.hex)
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert len(data) == 1
assert data[0]['id'] == build.id.hex
self.login(self.default_user)
path = '/api/0/authors/me/builds/'
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert len(data) == 1
assert data[0]['id'] == build.id.hex
|
Improve floating button item label styles | 'use strict'
import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import colors from '../../assets/styles/variables/colors'
import { spacing, sizing } from '../../assets/styles/variables/utils'
class FloatingButtonItemLabel extends Component {
classes() {
return {
'default': {
wrap: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
top: '0px',
bottom: '0px',
right: '0px',
},
label: {
backgroundColor: '#87878A',
borderRadius: '3px',
padding: '4px',
color: colors.bgDark,
whiteSpace: 'nowrap',
fontSize: '14px',
boxShadow: `0px 1px 0px 0px ${colors.bgDark}`,
transition: `background-color 0.2s ease-in-out`,
},
},
hover: {
label: {
backgroundColor: '#C3C3C5',
},
},
}
}
render() {
return (
<div is="wrap">
<span is="label">{ this.props.label }</span>
</div>
)
}
}
export default ReactCSS(FloatingButtonItemLabel)
| 'use strict'
import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import colors from '../../assets/styles/variables/colors'
import { spacing, sizing } from '../../assets/styles/variables/utils'
class FloatingButtonItemLabel extends Component {
classes() {
return {
'default': {
wrap: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
top: '0px',
bottom: '0px',
right: '0px'
},
label: {
backgroundColor: 'rgba(255,255,255,0.4)',
borderRadius: '3px',
padding: '4px',
color: colors.bgDark,
whiteSpace: 'nowrap',
fontSize: '14px',
boxShadow: `0px 1px 0px 0px ${colors.bgDark}`,
transition: `background-color 0.2s ease-in-out`,
},
},
hover: {
label: {
backgroundColor: 'rgba(255,255,255,0.7)',
},
},
}
}
render() {
return (
<div is="wrap">
<span is="label">{ this.props.label }</span>
</div>
)
}
}
export default ReactCSS(FloatingButtonItemLabel)
|
Add from parameter in handleNewMessage | import React, { Component } from 'react';
import ChatMessages from './ChatMessages';
import ChatFooter from './ChatFooter';
import connector from '../connection/connector';
import * as config from '../connection/config';
class Chatbody extends Component {
constructor(props) {
super(props);
this.state = {
partner: {
gender: 'female',
university: 'University of Athens, Greece'
},
me: {
gender: 'undefined',
university: 'National Technical University of Athens, Greece'
},
messages: [
{from: 'partner', timestamp: new Date(), content: 'hi, how are you?',},
{from: 'me', timestamp: new Date(), content: 'Fine, you?',},
]
};
}
handleNewMessage = (message, from) => {
if (from === undefined) {
from = 'me';
}
let newMessages = this.state.messages;
let newMessage = {
content: message,
timestamp: new Date(),
from: from
};
newMessages.push(newMessage);
this.setState({messages: newMessages});
//TODO: Message request to backend
}
render() {
return (
<div className="Chatbox">
<ChatMessages messages={this.state.messages} partner={this.state.partner} me={this.state.me} />
<ChatFooter handleNewMessage={this.handleNewMessage} />
</div>
);
}
}
export default Chatbody;
| import React, { Component } from 'react';
import ChatMessages from './ChatMessages';
import ChatFooter from './ChatFooter';
class Chatbody extends Component {
constructor(props) {
super(props);
this.state = {
partner: {
gender: 'female',
university: 'University of Athens, Greece'
},
me: {
gender: 'undefined',
university: 'National Technical University of Athens, Greece'
},
messages: [
{from: 'partner', timestamp: new Date(), content: 'hi, how are you?',},
{from: 'me', timestamp: new Date(), content: 'Fine, you?',},
]
};
}
handleNewMessage = (message) => {
let newMessages = this.state.messages;
let newMessage = {
content: message,
timestamp: new Date(),
from: 'me'
};
newMessages.push(newMessage);
this.setState({messages: newMessages});
//TODO: Message request to backend
}
render() {
return (
<div className="Chatbox">
<ChatMessages messages={this.state.messages} partner={this.state.partner} me={this.state.me} />
<ChatFooter handleNewMessage={this.handleNewMessage} />
</div>
);
}
}
export default Chatbody;
|
Update para esconder o botão de cadastrar uma vez que o usuário fizer o logon. | <?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'Trinket';
?>
<div class="site-index">
<div class="jumbotron">
<div id="logo"><?php echo "<img src=\"image/logo.jpg\">"; ?></div>
<h1>Bem vindo a Trinket</h1>
<p class="lead">Um site feito para trocas de forma rápida, segura e inteligente.</p>
<?php if (Yii::$app->user->isGuest) { ?>
<p>
<?= Html::a('Cadastre-se', ['usuario/create'], ['class' => 'btn btn-lg btn-primary']) ?>
</p>
<?php } ?>
</div>
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2></h2>
<p></p>
</div>
<div class="col-lg-4">
<h2></h2>
<p></p>
</div>
<div class="col-lg-4">
<h2></h2>
<p>
</p>
</div>
</div>
</div>
</div>
| <?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'Trinket';
?>
<div class="site-index">
<div class="jumbotron">
<div id="logo"><?php echo "<img src=\"image/logo.jpg\">"; ?></div>
<h1>Bem vindo a Trinket</h1>
<p class="lead">Um site feito para trocas de forma rápida, segura e inteligente.</p>
ola l
<p>
<?= Html::a('Cadastre-se', ['usuario/create'], ['class' => 'btn btn-lg btn-primary']) ?>
</p>
</div>
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2></h2>
<p></p>
</div>
<div class="col-lg-4">
<h2></h2>
<p></p>
</div>
<div class="col-lg-4">
<h2></h2>
<p>
</p>
</div>
</div>
</div>
</div>
|
Add an isActiveWhen on the dashbaord sidebar class | <?php namespace Modules\Dashboard\Sidebar;
use Maatwebsite\Sidebar\Group;
use Maatwebsite\Sidebar\Item;
use Maatwebsite\Sidebar\Menu;
use Modules\Core\Contracts\Authentication;
class SidebarExtender implements \Maatwebsite\Sidebar\SidebarExtender
{
/**
* @var Authentication
*/
protected $auth;
/**
* @param Authentication $auth
*
* @internal param Guard $guard
*/
public function __construct(Authentication $auth)
{
$this->auth = $auth;
}
/**
* @param Menu $menu
*
* @return Menu
*/
public function extendWith(Menu $menu)
{
$menu->group(trans('dashboard::dashboard.name'), function (Group $group) {
$group->weight(0);
$group->hideHeading();
$group->item(trans('dashboard::dashboard.name'), function (Item $item) {
$item->icon('fa fa-dashboard');
$item->route('dashboard.index');
$item->isActiveWhen(route('dashboard.index', null, false));
$item->authorize(
$this->auth->hasAccess('dashboard.index')
);
});
});
return $menu;
}
}
| <?php namespace Modules\Dashboard\Sidebar;
use Maatwebsite\Sidebar\Group;
use Maatwebsite\Sidebar\Item;
use Maatwebsite\Sidebar\Menu;
use Modules\Core\Contracts\Authentication;
class SidebarExtender implements \Maatwebsite\Sidebar\SidebarExtender
{
/**
* @var Authentication
*/
protected $auth;
/**
* @param Authentication $auth
*
* @internal param Guard $guard
*/
public function __construct(Authentication $auth)
{
$this->auth = $auth;
}
/**
* @param Menu $menu
*
* @return Menu
*/
public function extendWith(Menu $menu)
{
$menu->group(trans('dashboard::dashboard.name'), function (Group $group) {
$group->weight(0);
$group->hideHeading();
$group->item(trans('dashboard::dashboard.name'), function (Item $item) {
$item->icon('fa fa-dashboard');
$item->route('dashboard.index');
$item->authorize(
$this->auth->hasAccess('dashboard.index')
);
});
});
return $menu;
}
}
|
Fix argument in cron job | const CronJob = require('cron').CronJob;
const Database = require('./database.js');
const database = Object.create(Database).init();
const MillisecondsInOneDay = 24*60*60*1000;
const Days = 1;
module.exports = function() {
new CronJob('0 * * * *', function() {
console.log('cleaning up old groups');
database.getAllGroups(function(err, groups) {
if (err) {
return;
}
var current = Date.now();
groups.forEach(function(group) {
var lastMessage = group.messages.length > 0 ? group.messages[group.messages.length-1] : null;
// if there is a message, check the time since last message
// if there are no messages, check the group creation time
var targetTime;
if (lastMessage != null) {
targetTime = current - lastMessage.timestamp;
} else {
targetTime = current - group.timestamp;
}
if (targetTime > MillisecondsInOneDay) {
(function(group) {
database.deleteGroupById(group.id, function(err, res) {
if (err) {
return;
}
console.log('removed group', group)
});
})(group); // closure over group
}
});
});
}, null, true, 'America/Chicago');
};
| const CronJob = require('cron').CronJob;
const Database = require('./database.js');
const database = Object.create(Database).init();
const MillisecondsInOneDay = 24*60*60*1000;
const Days = 1;
module.exports = function() {
new CronJob('0 * * * *', function() {
console.log('cleaning up old groups');
database.getAllGroups(function(err, groups) {
if (err) {
return;
}
var current = Date.now();
groups.forEach(function(group) {
var lastMessage = group.messages.length > 0 ? group.messages[group.messages.length-1] : null;
// if there is a message, check the time since last message
// if there are no messages, check the group creation time
var targetTime;
if (lastMessage != null) {
targetTime = current - lastMessage.timestamp;
} else {
targetTime = current - group.timestamp;
}
if (targetTime > MillisecondsInOneDay) {
(function(group) {
database.deleteGroupById({id: group.id}, function(err, res) {
if (err) {
return;
}
console.log('removed group', group)
});
})(group); // closure over group
}
});
});
}, null, true, 'America/Chicago');
};
|
Fix python 3 compat. BREAKS python 2.x | import os
import json
from jsonschema import Draft4Validator
def validate_mapping(mapping):
""" Validate a mapping configuration file against the relevant schema. """
file_path = os.path.join(os.path.dirname(__file__),
'schemas', 'mapping.json')
with open(file_path, 'r') as fh:
validator = Draft4Validator(json.load(fh))
validator.validate(mapping)
return mapping
class RefScoped(object):
""" Objects which have a JSON schema-style scope. """
def __init__(self, resolver, scoped, scope=None, parent=None, name=None):
self.resolver = resolver
self._scoped = scoped
self._scope = scope or ''
self.name = name
self.parent = parent
@property
def id(self):
return self._scoped.get('id')
@property
def path(self):
if self.id is not None:
return self.id
if self.parent:
path = self.parent.path
if self.name:
if '#' not in path:
return path + '#/' + self.name
else:
return path + '/' + self.name
return path
@property
def scope(self):
if self.id:
return self.id
if self.parent:
return self.parent.scope
return self._scope
| import os
import json
from jsonschema import Draft4Validator
def validate_mapping(mapping):
""" Validate a mapping configuration file against the relevant schema. """
file_path = os.path.join(os.path.dirname(__file__),
'schemas', 'mapping.json')
with open(file_path, 'rb') as fh:
validator = Draft4Validator(json.load(fh))
validator.validate(mapping)
return mapping
class RefScoped(object):
""" Objects which have a JSON schema-style scope. """
def __init__(self, resolver, scoped, scope=None, parent=None, name=None):
self.resolver = resolver
self._scoped = scoped
self._scope = scope or ''
self.name = name
self.parent = parent
@property
def id(self):
return self._scoped.get('id')
@property
def path(self):
if self.id is not None:
return self.id
if self.parent:
path = self.parent.path
if self.name:
if '#' not in path:
return path + '#/' + self.name
else:
return path + '/' + self.name
return path
@property
def scope(self):
if self.id:
return self.id
if self.parent:
return self.parent.scope
return self._scope
|
Make NamedStruct instance names less confusing
Ideally we'd want to make the name the same as the instance name,
but I'm not sure if it's possible without introducing an additional
constructor argument. | import string
import struct
from collections import namedtuple
class NamedStruct(struct.Struct):
def __init__(self, fields, order='', size=0):
self.values = namedtuple("NamedStruct", ' '.join(k for k, _ in fields))
format = order + ''.join([v for _, v in fields])
if size:
format += "%dx" % (size - struct.calcsize(format))
super().__init__(format)
def pack(self, *args, **kwargs):
return super().pack(*self.values(*args, **kwargs))
def unpack(self, data):
return self.values._make(super().unpack(data))
# does not handle:
# - bytes
# - escapes in bytes
def sourcable_dump(dict_):
value_esc = {
"\\": r"\\",
"'": r"'\''",
}
value_trans = str.maketrans(value_esc)
for k, v in dict_.items():
k = str(k).lstrip("0123456789")
k = ''.join([c if c in string.ascii_letters + string.digits + '_' else '_' for c in k])
v = str(v).translate(value_trans)
if k:
print("%s='%s'" % (k, v))
def pretty_dump(dict_):
items = dict_.items()
maxlen = max([len(k) for k, _ in items])
for k, v in items:
print(("{:%d} {}" % maxlen).format(k, v))
dump = pretty_dump
| import string
import struct
from collections import namedtuple
class NamedStruct(struct.Struct):
def __init__(self, fields, order='', size=0):
self.values = namedtuple("header", ' '.join(k for k, _ in fields))
format = order + ''.join([v for _, v in fields])
if size:
format += "%dx" % (size - struct.calcsize(format))
super().__init__(format)
def pack(self, *args, **kwargs):
return super().pack(*self.values(*args, **kwargs))
def unpack(self, data):
return self.values._make(super().unpack(data))
# does not handle:
# - bytes
# - escapes in bytes
def sourcable_dump(dict_):
value_esc = {
"\\": r"\\",
"'": r"'\''",
}
value_trans = str.maketrans(value_esc)
for k, v in dict_.items():
k = str(k).lstrip("0123456789")
k = ''.join([c if c in string.ascii_letters + string.digits + '_' else '_' for c in k])
v = str(v).translate(value_trans)
if k:
print("%s='%s'" % (k, v))
def pretty_dump(dict_):
items = dict_.items()
maxlen = max([len(k) for k, _ in items])
for k, v in items:
print(("{:%d} {}" % maxlen).format(k, v))
dump = pretty_dump
|
Use correct auth failure message
Signed-off-by: snipe <[email protected]> | <?php
namespace App\Http\Livewire;
use Livewire\Component;
class LoginForm extends Component
{
public $username = '';
public $password = '';
public $can_submit = false;
/**
* Set the validation rules for login
*
* @author A. Ginaotto <[email protected]>
* @version v6.0
* @return Array
*/
public function rules()
{
return [
'username' => 'required|string|max:255',
'password' => 'required',
];
}
/**
* Perform the validation
*
* @author A. Ginaotto <[email protected]>
* @version v6.0
*/
public function updated($fields)
{
$this->validateOnly($fields);
if (!is_null($fields) && !empty($fields)) {
$this->can_submit = true;
} else {
$this->can_submit = false;
}
}
/**
* Actually do the login thing
*
* @todo fix missing LDAP stuff maybe?
* @author A. Ginaotto <[email protected]>
* @version v6.0
*/
public function submitForm()
{
$validatedData = $this->validate();
if (\Auth::attempt(
[
'username' => $this->username,
'password' => $this->password
]
))
{
redirect()->route('dashboard');
} else {
session()->flash('error', trans('auth/message.account_not_found'));
}
}
}
| <?php
namespace App\Http\Livewire;
use Livewire\Component;
class LoginForm extends Component
{
public $username = '';
public $password = '';
public $can_submit = false;
/**
* Set the validation rules for login
*
* @author A. Ginaotto <[email protected]>
* @version v6.0
* @return Array
*/
public function rules()
{
return [
'username' => 'required|string|max:255',
'password' => 'required',
];
}
/**
* Perform the validation
*
* @author A. Ginaotto <[email protected]>
* @version v6.0
*/
public function updated($fields)
{
$this->validateOnly($fields);
if (!is_null($fields) && !empty($fields)) {
$this->can_submit = true;
} else {
$this->can_submit = false;
}
}
/**
* Actually do the login thing
*
* @todo fix missing LDAP stuff maybe?
* @author A. Ginaotto <[email protected]>
* @version v6.0
*/
public function submitForm()
{
$validatedData = $this->validate();
if (\Auth::attempt(array('username' => $this->username, 'password' => $this->password))){
redirect()->route('dashboard');
} else {
session()->flash('error', 'email and password are wrong.');
}
}
}
|
Add the WordPress i18n as a filter to twig | <?php
namespace jvwp;
use FlorianWolters\Component\Util\Singleton\SingletonTrait;
class Templates
{
use SingletonTrait;
private $twigLoader;
private $twigEnvironment;
function __construct ()
{
$this->twigLoader = new \Twig_Loader_Filesystem(array());
$this->twigEnvironment = new \Twig_Environment($this->twigLoader);
self::extendTwig($this->twigEnvironment);
}
/**
* Adds the WP-specific filters and functions to the twig environment
* @param \Twig_Environment $twig_Environment
*/
private static function extendTwig (\Twig_Environment $twig_Environment)
{
$twig_Environment->addFilter('__', new \Twig_SimpleFilter('__', function ($text, $domain = 'default') {
return __($text, $domain);
}));
}
/**
* Adds a path where templates are stored.
*
* @param string $path A path where to look for templates
* @param string $namespace The namespace to associate the path with
*
* @throws \Twig_Error_Loader
*/
public static function addPath ($path, $namespace = \Twig_Loader_Filesystem::MAIN_NAMESPACE)
{
$twigLoader = self::getInstance()->twigLoader;
/* @var $twigLoader \Twig_Loader_Filesystem */
$twigLoader->addPath($path, $namespace);
}
/**
* Gets the template with the given name.
*
* @param string $name
*
* @return \Twig_Template
*/
public static function getTemplate ($name)
{
return self::getInstance()->getTwigEnvironment()->loadTemplate($name);
}
/**
* @return \Twig_Environment;
*/
public function getTwigEnvironment ()
{
return $this->twigEnvironment;
}
} | <?php
namespace jvwp;
use FlorianWolters\Component\Util\Singleton\SingletonTrait;
class Templates
{
use SingletonTrait;
private $twigLoader;
private $twigEnvironment;
function __construct ()
{
$this->twigLoader = new \Twig_Loader_Filesystem(array());
$this->twigEnvironment = new \Twig_Environment($this->twigLoader);
}
/**
* Adds a path where templates are stored.
*
* @param string $path A path where to look for templates
* @param string $namespace The namespace to associate the path with
*
* @throws \Twig_Error_Loader
*/
public static function addPath ($path, $namespace = \Twig_Loader_Filesystem::MAIN_NAMESPACE)
{
$twigLoader = self::getInstance()->twigLoader;
/* @var $twigLoader \Twig_Loader_Filesystem */
$twigLoader->addPath($path, $namespace);
}
/**
* Gets the template with the given name.
*
* @param string $name
*
* @return \Twig_Template
*/
public static function getTemplate ($name)
{
return self::getInstance()->getTwigEnvironment()->loadTemplate($name);
}
/**
* @return \Twig_Environment;
*/
public function getTwigEnvironment ()
{
return $this->twigEnvironment;
}
} |
Fix support in IE 11
Remove usage of => and `` comments that break backwards compatibility with IE | Selectize.define('tag_limit', function (options) {
const self = this
options.tagLimit = options.tagLimit
this.onBlur = (function (e) {
const original = self.onBlur
return function (e) {
original.apply(this, e);
if (!e)
return
const $control = this.$control
const $items = $control.find('.item')
const limit = options.tagLimit
if (limit === undefined || $items.length <= limit)
return
$items.toArray().forEach(function(item, index) {
if (index < limit)
return
$(item).hide()
});
$control.append('<span><b>' + ($items.length - limit) + '</b></span>')
};
})()
this.onFocus = (function (e) {
const original = self.onFocus
return function (e) {
original.apply(this, e);
if (!e)
return
const $control = this.$control
const $items = $control.find('.item')
$items.show()
$control.find('span').remove()
};
})()
});
| Selectize.define('tag_limit', function (options) {
const self = this
options.tagLimit = options.tagLimit
this.onBlur = (function (e) {
const original = self.onBlur
return function (e) {
original.apply(this, e);
if (!e)
return
const $control = this.$control
const $items = $control.find('.item')
const limit = options.tagLimit
if (limit === undefined || $items.length <= limit)
return
$items.toArray().forEach((item, index) => {
if (index < limit)
return
$(item).hide()
});
$control.append(`<span><b>+${$items.length - limit}</b></span>`)
};
})()
this.onFocus = (function (e) {
const original = self.onFocus
return function (e) {
original.apply(this, e);
if (!e)
return
const $control = this.$control
const $items = $control.find('.item')
$items.show()
$control.find('span').remove()
};
})()
}); |
Add docblock to help IDE | <?php
/*************************************************************************************
* Copyright (C) 2014 by Alejandro Fiestas Olivares <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Affero General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
namespace AFiestas\ProtectFont;
interface iPrinter
{
/**
* @return void
*/
public function printFont($path);
} | <?php
/*************************************************************************************
* Copyright (C) 2014 by Alejandro Fiestas Olivares <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Affero General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
namespace AFiestas\ProtectFont;
interface iPrinter
{
public function printFont($path);
} |
Add sanity checks for temperature readings | # coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
bathroom_temperature = round(data["data"]["bathroom_temperature"], 1)
bathroom_humidity = round(data["data"]["bathroom_humidity"], 1)
corridor_temperature = round(data["data"]["corridor_temperature"], 1)
corridor_humidity = round(data["data"]["corridor_humidity"], 1)
if bathroom_temperature < 1 or bathroom_temperature > 60:
bathroom_temperature = None
if corridor_temperature < 1 or corridor_temperature > 60:
corridor_temperature = None
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": bathroom_temperature,
"bathroom_humidity": bathroom_humidity,
"corridor_temperature": corridor_temperature,
"corridor_humidity": corridor_humidity,
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
| # coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
Use the Titanic example data set | import unittest
import json
import great_expectations as ge
from great_expectations import render
class TestPageRenderers(unittest.TestCase):
def test_import(self):
from great_expectations import render
def test_prescriptive_expectation_renderer(self):
results = render.render(
renderer_class=render.PrescriptiveExpectationPageRenderer,
expectations=json.load(open('tests/test_fixtures/rendering_fixtures/expectation_suite_3.json'))["expectations"],
)
assert results != None
# with open('./test.html', 'w') as f:
# f.write(results)
def test_descriptive_evr_renderer(self):
R = render.DescriptiveEvrPageRenderer(
json.load(open('tests/test_fixtures/rendering_fixtures/evr_suite_3.json'))["results"],
)
rendered_page = R.render()
assert rendered_page != None
# with open('./test.html', 'w') as f:
# f.write(rendered_page)
def test_full_oobe_flow(sefl):
df = ge.read_csv("examples/data/Titanic.csv")
df.autoinspect(ge.dataset.autoinspect.pseudo_pandas_profiling)
evrs = df.validate()["results"]
R = render.DescriptiveEvrPageRenderer(evrs)
rendered_page = R.render()
assert rendered_page != None
# with open('./test.html', 'w') as f:
# f.write(rendered_page) | import unittest
import json
import great_expectations as ge
from great_expectations import render
class TestPageRenderers(unittest.TestCase):
def test_import(self):
from great_expectations import render
def test_prescriptive_expectation_renderer(self):
results = render.render(
renderer_class=render.PrescriptiveExpectationPageRenderer,
expectations=json.load(open('tests/test_fixtures/rendering_fixtures/expectation_suite_3.json'))["expectations"],
)
assert results != None
# with open('./test.html', 'w') as f:
# f.write(results)
def test_descriptive_evr_renderer(self):
R = render.DescriptiveEvrPageRenderer(
json.load(open('tests/test_fixtures/rendering_fixtures/evr_suite_3.json'))["results"],
)
rendered_page = R.render()
assert rendered_page != None
# with open('./test.html', 'w') as f:
# f.write(rendered_page)
def test_full_oobe_flow(sefl):
df = ge.read_csv("/Users/abe/Documents/superconductive/data/Sacramentorealestatetransactions.csv")
df.autoinspect(ge.dataset.autoinspect.pseudo_pandas_profiling)
evrs = df.validate()["results"]
R = render.DescriptiveEvrPageRenderer(evrs)
rendered_page = R.render()
assert rendered_page != None
# with open('./test.html', 'w') as f:
# f.write(rendered_page) |
Disable the offline plugin for Gatsby | module.exports = {
siteMetadata: {
title: `Neon Tsunami`,
author: `Dwight Watson`,
description: `A blog on Laravel & Rails.`,
siteUrl: `https://www.neontsunami.com`,
social: {
twitter: `DwightConrad`,
},
},
plugins: [
`gatsby-plugin-postcss`,
{
resolve: `gatsby-plugin-purgecss`,
options: {
tailwind: true,
ignore: ['github.css']
}
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown`,
path: `${__dirname}/src/markdown`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
`gatsby-remark-prismjs`,
],
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: 'UA-23727271-4',
},
},
`gatsby-plugin-feed`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Neon Tsunami`,
short_name: `Neon Tsunami`,
start_url: `/`,
background_color: `#ffffff`,
theme_color: `#4299e1`,
display: `minimal-ui`,
icon: `src/images/tsunami.png`,
},
},
// `gatsby-plugin-offline`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-netlify`,
],
}
| module.exports = {
siteMetadata: {
title: `Neon Tsunami`,
author: `Dwight Watson`,
description: `A blog on Laravel & Rails.`,
siteUrl: `https://www.neontsunami.com`,
social: {
twitter: `DwightConrad`,
},
},
plugins: [
`gatsby-plugin-postcss`,
{
resolve: `gatsby-plugin-purgecss`,
options: {
tailwind: true,
ignore: ['github.css']
}
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `markdown`,
path: `${__dirname}/src/markdown`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
`gatsby-remark-prismjs`,
],
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-google-analytics`,
options: {
trackingId: 'UA-23727271-4',
},
},
`gatsby-plugin-feed`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `Neon Tsunami`,
short_name: `Neon Tsunami`,
start_url: `/`,
background_color: `#ffffff`,
theme_color: `#4299e1`,
display: `minimal-ui`,
icon: `src/images/tsunami.png`,
},
},
`gatsby-plugin-offline`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-netlify`,
],
}
|
Move ngModal to body to allow to breakout relative positioning |
angular.module('ngModal', [])
/**
* ng-modal Directive
*
* Loads the picker modal.
* All modal content should be placed within this directive. E.g.;
* <ng-modal>modal content</ng-modal>
*/
.directive('ngModal', ['$sce', function($sce) {
function link(scope, element, attrs) {
var setupCloseButton, setupStyle;
setupStyle = function() {
scope.dialogStyle = {};
if (attrs.width) {
scope.dialogStyle['width'] = attrs.width;
}
if (attrs.height) {
return scope.dialogStyle['height'] = attrs.height;
}
};
scope.hidePicker = function() {
return scope.show = false;
};
scope.$watch('show', function(newVal, oldVal) {
if (newVal && !oldVal) {
document.getElementsByTagName("body")[0].style.overflow = "hidden";
} else {
document.getElementsByTagName("body")[0].style.overflow = "";
}
if ((!newVal && oldVal) && (scope.onClose != null)) {
return scope.onClose();
}
});
scope.closeButtonHtml = $sce.trustAsHtml("<span class='ng-modal-close-x'>X</span>");
angular.element(document.body).append(element);
return setupStyle();
}
return {
restrict: 'E',
scope: {
show: '=',
onClose: '&?'
},
replace: true,
transclude: true,
link: link,
templateUrl: "/bundles/opifermedia/app/modal/modal.html"
};
}])
;
|
angular.module('ngModal', [])
/**
* ng-modal Directive
*
* Loads the picker modal.
* All modal content should be placed within this directive. E.g.;
* <ng-modal>modal content</ng-modal>
*/
.directive('ngModal', ['$sce', function($sce) {
function link(scope, element, attrs) {
var setupCloseButton, setupStyle;
setupStyle = function() {
scope.dialogStyle = {};
if (attrs.width) {
scope.dialogStyle['width'] = attrs.width;
}
if (attrs.height) {
return scope.dialogStyle['height'] = attrs.height;
}
};
scope.hidePicker = function() {
return scope.show = false;
};
scope.$watch('show', function(newVal, oldVal) {
if (newVal && !oldVal) {
document.getElementsByTagName("body")[0].style.overflow = "hidden";
} else {
document.getElementsByTagName("body")[0].style.overflow = "";
}
if ((!newVal && oldVal) && (scope.onClose != null)) {
return scope.onClose();
}
});
scope.closeButtonHtml = $sce.trustAsHtml("<span class='ng-modal-close-x'>X</span>");
return setupStyle();
}
return {
restrict: 'E',
scope: {
show: '=',
onClose: '&?'
},
replace: true,
transclude: true,
link: link,
templateUrl: "/bundles/opifermedia/app/modal/modal.html"
};
}])
;
|
Clean up transpose helper method | import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
return [''.join(row) for row in transposed_matrix]
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
transposed_matrix = list(itertools.zip_longest(*matrix))
return [[val for val in row if val is not None] for row in transposed_matrix] # Remove None's
def encode(msg):
return CryptoSquare.encode(msg)
| import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
return [''.join(row) for row in transposed_matrix]
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
|
[Process] Add default xampp path to the list of possible paths to check | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process;
/**
* An executable finder specifically designed for the PHP executable.
*
* @author Fabien Potencier <[email protected]>
* @author Johannes M. Schmitt <[email protected]>
*/
class PhpExecutableFinder
{
private $executableFinder;
public function __construct()
{
$this->executableFinder = new ExecutableFinder();
}
/**
* Finds The PHP executable.
*
* @return string|false The PHP executable path or false if it cannot be found
*/
public function find()
{
// PHP_BINARY return the current sapi executable
if (defined('PHP_BINARY') && PHP_BINARY && ('cli' === PHP_SAPI)) {
return PHP_BINARY;
}
if ($php = getenv('PHP_PATH')) {
if (!is_executable($php)) {
return false;
}
return $php;
}
if ($php = getenv('PHP_PEAR_PHP_BIN')) {
if (is_executable($php)) {
return $php;
}
}
$dirs = array(PHP_BINDIR);
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$dirs[] = 'C:\xampp\php\\';
}
return $this->executableFinder->find('php', false, $dirs);
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process;
/**
* An executable finder specifically designed for the PHP executable.
*
* @author Fabien Potencier <[email protected]>
* @author Johannes M. Schmitt <[email protected]>
*/
class PhpExecutableFinder
{
private $executableFinder;
public function __construct()
{
$this->executableFinder = new ExecutableFinder();
}
/**
* Finds The PHP executable.
*
* @return string|false The PHP executable path or false if it cannot be found
*/
public function find()
{
// PHP_BINARY return the current sapi executable
if (defined('PHP_BINARY') && PHP_BINARY && ('cli' === PHP_SAPI)) {
return PHP_BINARY;
}
if ($php = getenv('PHP_PATH')) {
if (!is_executable($php)) {
return false;
}
return $php;
}
if ($php = getenv('PHP_PEAR_PHP_BIN')) {
if (is_executable($php)) {
return $php;
}
}
$dirs = array(PHP_BINDIR);
return $this->executableFinder->find('php', false, $dirs);
}
}
|
Move '$theme' injection in partial method | <?php
namespace Bloge\Renderers;
use Bloge\NotFoundException;
/**
* Basic renderer
*
* This renderer renders raw PHP templates
*
* @package bloge
*/
class PHP implements IRenderer
{
/**
* @var string $path
*/
protected $path;
/**
* @var array $data
*/
protected $data = [];
/**
* @param string $path
*/
public function __construct($path)
{
$this->path = chop($path, '/');
}
/**
* @param string $view
* @param array $data
* @return string
*/
public function partial($view, array $data = [])
{
$data['theme'] = $this;
$view = \Bloge\removeExtension($view);
$path = "{$this->path}/$view.php";
if (!file_exists($path)) {
throw new NotFoundException($view);
}
return \Bloge\render($path, array_merge($this->data, $data));
}
/**
* @{inheritDoc}
*/
public function render(array $data = [])
{
$this->data = $data;
$layout = isset($data['layout'])
? $data['layout']
: 'layout';
return $this->partial($layout, $data);
}
} | <?php
namespace Bloge\Renderers;
use Bloge\NotFoundException;
/**
* Basic renderer
*
* This renderer renders raw PHP templates
*
* @package bloge
*/
class PHP implements IRenderer
{
/**
* @var string $path
*/
protected $path;
/**
* @var array $data
*/
protected $data = [];
/**
* @param string $path
*/
public function __construct($path)
{
$this->path = chop($path, '/');
}
/**
* @param string $view
* @param array $data
* @return string
*/
public function partial($view, array $data = [])
{
$view = \Bloge\removeExtension($view);
$path = "{$this->path}/$view.php";
if (!file_exists($path)) {
throw new NotFoundException($view);
}
return \Bloge\render($path, array_merge($this->data, $data));
}
/**
* @{inheritDoc}
*/
public function render(array $data = [])
{
$layout = isset($data['layout'])
? $data['layout']
: 'layout.php';
$data['theme'] = $this;
$this->data = $data;
return $this->partial($layout, $data);
}
} |
Fix an import path to work for case sensitive OSes | define(['backbone', 'marionette', 'app/modules/Activity/d3/graph', 'text!templates/devTools/activity/graph.html'
], function(Backbone, Marionette, Graph, tpl) {
var ActivityGraph = Backbone.Marionette.ItemView.extend({
template: tpl,
tagName: "div",
className: 'activity-graph',
defaults: {
activityCollection: undefined
},
onShow: function() {
this.showSlider();
},
showSlider: function() {
var formattedData = this.formatData(this.options.activityCollection);
Graph.displaySlider(
formattedData.data,
formattedData.startX,
formattedData.endX,
formattedData.maxDepth
);
},
formatData: function(data) {
var rectHeight = 20,
startX = Infinity,
endX = -Infinity,
maxDepth = 0;
_.each(data, function(activity) {
activity = activity.attributes;
startX = activity.startTime < startX ? activity.startTime : startX;
endX = activity.endTime > endX ? activity.endTime : endX;
maxDepth = activity.depth > maxDepth ? activity.depth : maxDepth;
activity.position = {
"dx": activity.endTime - activity.startTime,
"dy": rectHeight,
"x": activity.startTime,
"y": rectHeight * activity.depth - 20
};
});
return {
data: data,
startX: startX,
endX: endX,
maxDepth: maxDepth
};
}
});
return ActivityGraph;
});
| define(['backbone', 'marionette', 'app/modules/activity/d3/graph', 'text!templates/devTools/activity/graph.html'
], function(Backbone, Marionette, Graph, tpl) {
var ActivityGraph = Backbone.Marionette.ItemView.extend({
template: tpl,
tagName: "div",
className: 'activity-graph',
defaults: {
activityCollection: undefined
},
onShow: function() {
this.showSlider();
},
showSlider: function() {
var formattedData = this.formatData(this.options.activityCollection);
Graph.displaySlider(
formattedData.data,
formattedData.startX,
formattedData.endX,
formattedData.maxDepth
);
},
formatData: function(data) {
var rectHeight = 20,
startX = Infinity,
endX = -Infinity,
maxDepth = 0;
_.each(data, function(activity) {
activity = activity.attributes;
startX = activity.startTime < startX ? activity.startTime : startX;
endX = activity.endTime > endX ? activity.endTime : endX;
maxDepth = activity.depth > maxDepth ? activity.depth : maxDepth;
activity.position = {
"dx": activity.endTime - activity.startTime,
"dy": rectHeight,
"x": activity.startTime,
"y": rectHeight * activity.depth - 20
};
});
return {
data: data,
startX: startX,
endX: endX,
maxDepth: maxDepth
};
}
});
return ActivityGraph;
});
|
Allow to redefine scope via metadata | "use strict";
var marked = require('meta-marked');
var jsxTransform = require('react-tools').transform;
var runtime = require.resolve('./runtime');
function compile(src, opts) {
var compiled = marked(src);
var meta = compiled.meta || {};
var component = meta.component ?
'require(' + JSON.stringify(meta.component) + ')' :
opts.component ?
'require(' + JSON.stringify(opts.component) + ')' :
'_runtime.Reactdown'
var scope = meta.scope ?
'require(' + JSON.stringify(meta.scope) + ')' :
opts.scope ?
'require(' + JSON.stringify(opts.scope) + ')' :
'{}';
delete meta.component;
var code = [
'/** @jsx React.DOM */',
'var React = require("react");',
'',
'var _runtime = require(' + JSON.stringify(runtime) + ');',
'var _Wrapper = _runtime.Wrapper;',
'var _Component = ' + component + ';',
'',
'_runtime.mergeInto(global, ' + scope + ');',
'',
'var _markup = <_Wrapper>' + compiled.html + '</_Wrapper>;',
'',
'module.exports = function create(props) {',
' props = _runtime.merge(exports.meta, props);',
' return _Component.apply(_Component, [props].concat(_markup));',
'};',
'module.exports.meta = ' + JSON.stringify(meta) + ';'
].join('\n');
code = jsxTransform(code);
return {code: code, meta: meta};
}
module.exports = compile;
| "use strict";
var marked = require('meta-marked');
var jsxTransform = require('react-tools').transform;
var runtime = require.resolve('./runtime');
function compile(src, opts) {
var compiled = marked(src);
var meta = compiled.meta || {};
var component = meta.component ?
'require("' + meta.component + '")' :
opts.component ?
'require("' + opts.component + '")' :
'_runtime.Reactdown'
var scope = opts.scope ?
'require(' + JSON.stringify(opts.scope) + ')' :
'{}';
delete meta.component;
var code = [
'/** @jsx React.DOM */',
'var React = require("react");',
'',
'var _runtime = require(' + JSON.stringify(runtime) + ');',
'var _Wrapper = _runtime.Wrapper;',
'var _Component = ' + component + ';',
'',
'_runtime.mergeInto(global, ' + scope + ');',
'',
'var _markup = <_Wrapper>' + compiled.html + '</_Wrapper>;',
'',
'module.exports = function create(props) {',
' props = _runtime.merge(exports.meta, props);',
' return _Component.apply(_Component, [props].concat(_markup));',
'};',
'module.exports.meta = ' + JSON.stringify(meta) + ';'
].join('\n');
code = jsxTransform(code);
return {code: code, meta: meta};
}
module.exports = compile;
|
Fix encoding detection in python (shebang line was not parsed anymore) | """
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager
class PyFileManager(FileManager):
"""
Extends file manager to override detect_encoding. With python, we can
detect encoding by reading the two first lines of a file and extracting its
encoding tag.
"""
def detect_encoding(self, path):
"""
For the implementation of encoding definitions in Python, look at:
- http://www.python.org/dev/peps/pep-0263/
.. note:: code taken and adapted from
```jedi.common.source_to_unicode.detect_encoding```
"""
with open(path, 'rb') as file:
source = file.read()
# take care of line encodings (not in jedi)
source = source.replace(b'\r', b'')
source_str = str(source).replace('\\n', '\n')
byte_mark = ast.literal_eval(r"b'\xef\xbb\xbf'")
if source.startswith(byte_mark):
# UTF-8 byte-order mark
return 'utf-8'
first_two_lines = re.match(r'(?:[^\n]*\n){0,2}', source_str).group(0)
possible_encoding = re.search(r"coding[=:]\s*([-\w.]+)",
first_two_lines)
if possible_encoding:
return possible_encoding.group(1)
def open(self, path, encoding=None, use_cached_encoding=True):
if encoding is None:
encoding = self.detect_encoding(path)
super().open(path, encoding=encoding,
use_cached_encoding=use_cached_encoding)
| """
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager
class PyFileManager(FileManager):
"""
Extends file manager to override detect_encoding. With python, we can
detect encoding by reading the two first lines of a file and extracting its
encoding tag.
"""
def detect_encoding(self, path):
"""
For the implementation of encoding definitions in Python, look at:
- http://www.python.org/dev/peps/pep-0263/
.. note:: code taken and adapted from
```jedi.common.source_to_unicode.detect_encoding```
"""
with open(path, 'rb') as file:
source = file.read()
# take care of line encodings (not in jedi)
source = source.replace(b'\r', b'')
source_str = str(source).replace('\\n', '\n')
byte_mark = ast.literal_eval(r"b'\xef\xbb\xbf'")
if source.startswith(byte_mark):
# UTF-8 byte-order mark
return 'utf-8'
first_two_lines = re.match(r'(?:[^\n]*\n){0,2}', source_str).group(0)
possible_encoding = re.search(r"coding[=:]\s*([-\w.]+)",
first_two_lines)
if possible_encoding:
return possible_encoding.group(1)
else:
return super().detect_encoding(path)
|
Remove last called information from the profile page | <div class="pagehead">
<div class="{{ Auth::user()->getFluidLayout() }}">
<div class="row">
<div class="col-xs-12">
@include ('partials.notification')
<div class="people-profile-information">
@if ($contact->has_avatar == 'true')
<img src="{{ $contact->getAvatarURL(110) }}" width="87">
@else
@if (count($contact->getInitials()) == 1)
<div class="avatar one-letter" style="background-color: {{ $contact->getAvatarColor() }};">
{{ $contact->getInitials() }}
</div>
@else
<div class="avatar" style="background-color: {{ $contact->getAvatarColor() }};">
{{ $contact->getInitials() }}
</div>
@endif
@endif
<h2>
{{ $contact->getCompleteName() }}
</h2>
<ul class="horizontal profile-detail-summary">
{{-- Last activity information --}}
<li>
@if (is_null($contact->getLastActivityDate(Auth::user()->timezone)))
{{ trans('people.last_activity_date_empty') }}
@else
{{ trans('people.last_activity_date', ['date' => $contact->getLastActivityDate(Auth::user()->timezone)]) }}
@endif
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
| <div class="pagehead">
<div class="{{ Auth::user()->getFluidLayout() }}">
<div class="row">
<div class="col-xs-12">
@include ('partials.notification')
<div class="people-profile-information">
@if ($contact->has_avatar == 'true')
<img src="{{ $contact->getAvatarURL(110) }}" width="87">
@else
@if (count($contact->getInitials()) == 1)
<div class="avatar one-letter" style="background-color: {{ $contact->getAvatarColor() }};">
{{ $contact->getInitials() }}
</div>
@else
<div class="avatar" style="background-color: {{ $contact->getAvatarColor() }};">
{{ $contact->getInitials() }}
</div>
@endif
@endif
<h2>
{{ $contact->getCompleteName() }}
</h2>
<ul class="horizontal profile-detail-summary">
{{-- Last called information --}}
<li>
@if (is_null($contact->getLastCalled(Auth::user()->timezone)))
{{ trans('people.last_called_empty') }}
@else
{{ trans('people.last_called', ['date' => $contact->getLastCalled(Auth::user()->timezone)]) }}
@endif
</li>
{{-- Last activity information --}}
<li>
@if (is_null($contact->getLastActivityDate(Auth::user()->timezone)))
{{ trans('people.last_activity_date_empty') }}
@else
{{ trans('people.last_activity_date', ['date' => $contact->getLastActivityDate(Auth::user()->timezone)]) }}
@endif
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
|
Add server folder copy to build | const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: '[name].css', // '[name].[contenthash].css'
// disable: process.env.NODE_ENV === 'development'
});
module.exports = {
entry: {
app: './build/app',
worker: './build/worker'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.(css|scss)$/,
use: extractSass.extract({
use: [{
loader: 'css-loader'
}, {
loader: 'sass-loader'
}],
// use style-loader in development
fallback: 'style-loader'
})
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000
}
},
]
},
plugins: [
extractSass,
// new webpack.ProvidePlugin({
// $: 'jquery',
// jQuery: 'jquery'
// }),
new CopyWebpackPlugin([
{ from: 'server' /*, to: 'server'*/ },
])
],
};
| const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: '[name].css', // '[name].[contenthash].css'
// disable: process.env.NODE_ENV === 'development'
});
module.exports = {
entry: {
app: './build/app',
worker: './build/worker'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.(css|scss)$/,
use: extractSass.extract({
use: [{
loader: 'css-loader'
}, {
loader: 'sass-loader'
}],
// use style-loader in development
fallback: 'style-loader'
})
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000
}
},
]
},
plugins: [
extractSass,
// new webpack.ProvidePlugin({
// $: 'jquery',
// jQuery: 'jquery'
// }),
],
};
|
Remove default null property sets. | <?php
namespace Adldap\Connections;
class DetailedError
{
/**
* The error code from ldap_errno.
*
* @var int|null
*/
protected $errorCode;
/**
* The error message from ldap_error.
*
* @var string|null
*/
protected $errorMessage;
/**
* The diagnostic message when retrieved after an ldap_error.
*
* @var string|null
*/
protected $diagnosticMessage;
/**
* Constructor.
*
* @param int $errorCode
* @param string $errorMessage
* @param string $diagnosticMessage
*/
public function __construct($errorCode, $errorMessage, $diagnosticMessage)
{
$this->errorCode = $errorCode;
$this->errorMessage = $errorMessage;
$this->diagnosticMessage = $diagnosticMessage;
}
/**
* Returns the LDAP error code.
*
* @return int
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* Returns the LDAP error message.
*
* @return string
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* Returns the LDAP diagnostic message.
*
* @return string
*/
public function getDiagnosticMessage()
{
return $this->diagnosticMessage;
}
}
| <?php
namespace Adldap\Connections;
class DetailedError
{
/**
* The error code from ldap_errno.
*
* @var int
*/
protected $errorCode = null;
/**
* The error message from ldap_error.
*
* @var string
*/
protected $errorMessage = null;
/**
* The diagnostic message when retrieved after an ldap_error.
*
* @var string
*/
protected $diagnosticMessage = null;
/**
* Constructor.
*
* @param int $errorCode
* @param string $errorMessage
* @param string $diagnosticMessage
*/
public function __construct($errorCode, $errorMessage, $diagnosticMessage)
{
$this->errorCode = $errorCode;
$this->errorMessage = $errorMessage;
$this->diagnosticMessage = $diagnosticMessage;
}
/**
* Returns the LDAP error code.
*
* @return int
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* Returns the LDAP error message.
*
* @return string
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* Returns the LDAP diagnostic message.
*
* @return string
*/
public function getDiagnosticMessage()
{
return $this->diagnosticMessage;
}
}
|
Build a common mixin method. | var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var debug = require('debug')('carcass:Index');
var descriptor = Object.getOwnPropertyDescriptor;
var properties = Object.getOwnPropertyNames;
var defineProp = Object.defineProperty;
module.exports = function(obj) {
// Register every file in a dir plus a namespace.
obj.register = function(dir, namespace) {
namespace || (namespace = 'plugins');
// TODO: validate namespace.
obj[namespace] || (obj[namespace] = {});
// .
dir = path.join(dir, namespace);
fs.readdirSync(dir).forEach(function(filename) {
if (!/\.js$/.test(filename)) return;
var name = path.basename(filename, '.js');
function load() {
var component = require(path.join(dir, name));
component.title || (component.title = name);
return component;
}
obj[namespace].__defineGetter__(name, load);
});
};
// Add some helpers to a target object.
obj.mixable = function(target) {
if (!_.isObject(target)) return;
// I organize my mixins into plugins. Each a plugin is a factory
// function. Once invoked, the factory will return the mixin function,
// and the mixin function can be used to modify an object directly.
target.plugin = function(namespace, title, options) {
var factory = obj[namespace][title];
if (factory) {
factory(options)(this);
}
return this;
};
// The common mixin, simply merge properties.
target.mixin = function(source) {
var self = this;
properties(source).forEach(function(key) {
defineProp(self, key, descriptor(source, key));
});
return this;
};
_.bindAll(target, 'plugin', 'mixin');
};
};
| var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var debug = require('debug')('carcass:Index');
module.exports = function(obj) {
// Register every file in a dir plus a namespace.
obj.register = function(dir, namespace) {
namespace || (namespace = 'plugins');
// TODO: validate namespace.
obj[namespace] || (obj[namespace] = {});
// .
dir = path.join(dir, namespace);
fs.readdirSync(dir).forEach(function(filename) {
if (!/\.js$/.test(filename)) return;
var name = path.basename(filename, '.js');
function load() {
var component = require(path.join(dir, name));
component.title || (component.title = name);
return component;
}
obj[namespace].__defineGetter__(name, load);
});
};
// A method that can make something ...
// TODO: rename to plugin, and build a real mixin.
obj.mixable = function(target) {
target.plugin = function(namespace, title, options) {
var factory = obj[namespace][title];
if (factory) {
factory(options)(this);
}
return this;
};
_.bindAll(target, 'plugin');
};
};
|
Rename encode/decode parameterization in test | from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
dcconss_strategies_conss = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets, frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals, lambda x: x)]
example_input = [1]
@given(one_of(*[strategy_fn(integers()).map(dccons)
for dccons, strategy_fn, _ in dcconss_strategies_conss]))
@examples(*[dccons(cons(example_input))
for dccons, _, cons in dcconss_strategies_conss])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
| from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
conss_to_strategies = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets,
frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals,
lambda x: x)]
example_input = [1]
@given(one_of(*[strategy_fn(integers()).map(cons)
for cons, strategy_fn, _ in conss_to_strategies]))
@examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
|
Split preparating of context into separate method when rendering pages | <?php
declare(strict_types=1);
namespace MattyG\BBStatic\Content\Page;
use MattyG\BBStatic\BBCode\NeedsBBCodeRendererTrait;
use MattyG\BBStatic\Util\Vendor\NeedsTemplateEngineTrait;
use Symfony\Component\Filesystem\NeedsFilesystemTrait;
class PageRenderer
{
use NeedsBBCodeRendererTrait;
use NeedsFilesystemTrait;
use NeedsTemplateEngineTrait;
/**
* @param Page $page
* @return string The filename of the rendered page.
*/
final public function render(Page $page) : string
{
$pageType = $page->getPageType();
$renderedContent = $this->bbcodeRenderer->build($page->getContentFilename());
$template = $this->templateEngine->loadTemplate($pageType);
$context = array_merge($this->prepareContext($page), array("content" => $renderedContent));
$renderedPage = $template->render($context);
$outFilename = $page->getOutputFolder() . DIRECTORY_SEPARATOR . "index.html";
$this->filesystem->dumpFile($outFilename, $renderedPage);
return $outFilename;
}
/**
* @param Page $page
* @return array
*/
protected function prepareContext(Page $page) : array
{
return array(
"title" => $page->getTitle(),
"author" => $page->getAuthor(),
"date_posted" => $page->getDatePosted(),
"date_updated" => $page->getDateUpdated(),
"vars" => $page->getTemplateVariables(),
);
}
}
| <?php
declare(strict_types=1);
namespace MattyG\BBStatic\Content\Page;
use MattyG\BBStatic\BBCode\NeedsBBCodeRendererTrait;
use MattyG\BBStatic\Util\Vendor\NeedsTemplateEngineTrait;
use Symfony\Component\Filesystem\NeedsFilesystemTrait;
final class PageRenderer
{
use NeedsBBCodeRendererTrait;
use NeedsFilesystemTrait;
use NeedsTemplateEngineTrait;
/**
* @param Page $page
* @return string The filename of the rendered page.
*/
public function render(Page $page) : string
{
$pageType = $page->getPageType();
$contentFilename = $page->getContentFilename();
$convertedContent = $this->bbcodeRenderer->build($contentFilename);
$template = $this->templateEngine->loadTemplate($pageType);
$context = array(
"title" => $page->getTitle(),
"author" => $page->getAuthor(),
"date_posted" => $page->getDatePosted(),
"date_updated" => $page->getDateUpdated(),
"content" => $convertedContent,
"vars" => $page->getTemplateVariables(),
);
$renderedContent = $template->render($context);
$outFilename = $page->getOutputFolder() . DIRECTORY_SEPARATOR . "index.html";
$this->filesystem->dumpFile($outFilename, $renderedContent);
return $outFilename;
}
}
|
Clean up cookie lookup in TTRAuth | from requests.auth import AuthBase
import requests
import json
from exceptions import raise_on_error
class TTRAuth(AuthBase):
def __init__(self, user, password):
self.user = user
self.password = password
def response_hook(self, r, **kwargs):
j = json.loads(r.content)
if int(j['status']) == 0:
return r
sid = None
if 'ttrss_api_sid' in r.cookies:
sid = r.cookies['ttrss_api_sid']
r.request.headers['Cookie'] = 'ttrss_api_sid={0}'.format(sid)
else:
sid = r.request.headers['Cookie'].split('=')[1]
res = requests.post(r.request.url, json.dumps({
'sid': sid,
'op': 'login',
'user': self.user,
'password': self.password
}))
raise_on_error(res)
r.request.deregister_hook('response', self.response_hook)
_r = requests.Session().send(r.request)
_r.cookies = r.cookies
raise_on_error(_r)
return _r
def __call__(self, r):
r.register_hook('response', self.response_hook)
return r
| from requests.auth import AuthBase
import requests
import json
from exceptions import raise_on_error
class TTRAuth(AuthBase):
def __init__(self, user, password):
self.user = user
self.password = password
def response_hook(self, r, **kwargs):
j = json.loads(r.content)
if int(j['status']) == 0:
return r
sid = None
if r.headers['set-cookie']:
sid = r.headers['set-cookie'].split(';')[0].split('=')[1]
r.request.headers['Cookie'] = 'ttrss_api_sid={0}'.format(sid)
else:
sid = r.request.headers['Cookie'].split('=')[1]
res = requests.post(r.request.url, json.dumps({
'sid': sid,
'op': 'login',
'user': self.user,
'password': self.password
}))
raise_on_error(res)
r.request.deregister_hook('response', self.response_hook)
_r = requests.Session().send(r.request)
_r.cookies = r.cookies
raise_on_error(_r)
return _r
def __call__(self, r):
r.register_hook('response', self.response_hook)
return r
|
Fix call to HTTP404 now it is a function. | #! /usr/bin/env python
"""
Aragog Router Decorator
-----------------------
Convert any function into a WSGI endpoint with a simple decorator.
"""
from aragog.wsgi import get_url
from aragog.routing.client_error import HTTP404
class Router(object):
"""
Router holds the mapping of routes to callables.
"""
def __init__(self):
"""
Instance level route mapping
"""
self.mapping = {}
def __call__(self, environ, start_response):
"""
Get a WSGI request, and pass it on to the correct callable.
"""
routing = self.mapping.get(get_url(environ), HTTP404)
return routing(environ, start_response)
def add_route(self, url, func):
"""
Adds a route to the mapping
"""
if url not in self.mapping:
self.mapping[url] = func
else:
raise KeyError("Route already exists: {}".format(url))
def route(self, uri):
"""
Route a request to a function
:param: uri
:param_type: string
"""
def app_wrapper(f):
self.add_route(uri, f)
return f
return app_wrapper
| #! /usr/bin/env python
"""
Aragog Router Decorator
-----------------------
Convert any function into a WSGI endpoint with a simple decorator.
"""
from aragog.wsgi import get_url
from aragog.routing.client_error import HTTP404
class Router(object):
"""
Router holds the mapping of routes to callables.
"""
def __init__(self):
"""
Instance level route mapping
"""
self.mapping = {}
def __call__(self, environ, start_response):
"""
Get a WSGI request, and pass it on to the correct callable.
"""
routing = self.mapping.get(get_url(environ), HTTP404())
return routing(environ, start_response)
def add_route(self, url, func):
"""
Adds a route to the mapping
"""
if url not in self.mapping:
self.mapping[url] = func
else:
raise KeyError("Route already exists: {}".format(url))
def route(self, uri):
"""
Route a request to a function
:param: uri
:param_type: string
"""
def app_wrapper(f):
self.add_route(uri, f)
return f
return app_wrapper
|
Fix char counter when init one more time | var locastyle = locastyle || {};
locastyle.charCounter = (function() {
'use strict';
function updateCounter(index, count) {
$('.ls-number-counter-'+index).text(count);
}
function countText() {
$('[data-ls-module="charCounter"]').each(function(index, field) {
$('.ls-number-counter-' + index).parent().remove();
var limit = $(field).attr('maxlength');
var html = '<p class="ls-help-inline"><small><strong ' +
'class="ls-char-count ls-number-counter-' + index + '">' + limit +
'</strong> caracteres restantes</small></p>';
var prefixGroup = $(field).closest('.ls-prefix-group');
$(field).data().maxlength = limit;
if (prefixGroup.length) {
prefixGroup.after(html);
} else {
$(field).after(html);
}
$(field).keyup(function() {
var count = $(this).val().length;
var limit = $(this).data().maxlength;
if(count > limit) {
$(this).val($(this).val().substring(0, limit));
updateCounter(index, 0);
} else {
updateCounter(index, limit - count);
}
});
$(field).trigger('keyup');
});
}
function init() {
countText();
}
return {
init: init
};
}());
| var locastyle = locastyle || {};
locastyle.charCounter = (function() {
'use strict';
function updateCounter(index, count) {
$('.ls-number-counter-'+index).text(count);
}
function countText() {
$('[data-ls-module="charCounter"]').each(function(index, field) {
var limit = $(field).attr('maxlength');
var html = '<p class="ls-help-inline"><small><strong ' +
'class="ls-char-count ls-number-counter-' + index + '">' + limit +
'</strong> caracteres restantes</small></p>';
var prefixGroup = $(field).closest('.ls-prefix-group');
$(field).removeAttr('maxlength').data().maxlength = limit;
if (prefixGroup.length) {
prefixGroup.after(html);
} else {
$(field).after(html);
}
$(field).keyup(function() {
var count = $(this).val().length;
var limit = $(this).data().maxlength;
if(count > limit) {
$(this).val($(this).val().substring(0, limit));
updateCounter(index, 0);
} else {
updateCounter(index, limit - count);
}
});
$(field).trigger('keyup');
});
}
function init() {
countText();
}
return {
init: init
};
}());
|
Correct column name in migration | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateForumTableCategories extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('forum_categories', function (Blueprint $table)
{
$table->renameColumn('parent_category', 'category_id');
$table->renameColumn('subtitle', 'description');
});
Schema::table('forum_categories', function (Blueprint $table)
{
$table->integer('category_id')->default(0)->change();
$table->string('description')->nullable()->change();
$table->integer('weight')->default(0)->change();
$table->boolean('enable_threads')->default(0);
$table->boolean('private')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('forum_categories', function (Blueprint $table)
{
$table->renameColumn('category_id', 'parent_category');
$table->dropColumn(['created_at', 'updated_at', 'enable_threads', 'private']);
$table->renameColumn('description', 'subtitle');
});
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class UpdateForumTableCategories extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('forum_categories', function (Blueprint $table)
{
$table->renameColumn('parent_category', 'category_id');
$table->renameColumn('subtitle', 'description');
});
Schema::table('forum_categories', function (Blueprint $table)
{
$table->integer('category_id')->default(0)->change();
$table->string('subtitle')->nullable()->change();
$table->integer('weight')->default(0)->change();
$table->boolean('enable_threads')->default(0);
$table->boolean('private')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('forum_categories', function (Blueprint $table)
{
$table->renameColumn('category_id', 'parent_category');
$table->dropColumn(['created_at', 'updated_at', 'enable_threads', 'private']);
$table->renameColumn('description', 'subtitle');
});
}
}
|
Bump modular augur's TreeTime version requirement to match remote
Now distinguished from the Python 2 version of TreeTime. | import os
from setuptools import setup
setup(
name = "augur",
version = "0.1.0",
author = "nextstrain developers",
author_email = "[email protected], [email protected]",
description = ("Pipelines for real-time phylogenetic analysis"),
license = "MIT",
keywords = "nextstrain, molecular epidemiology",
url = "https://github.com/nextstrain/augur",
packages=['augur'],
install_requires = [
"biopython >=1.69, ==1.*",
"boto >=2.38, ==2.*",
"cvxopt >=1.1.8, ==1.1.*",
"ipdb >=0.10.1, ==0.10.*",
"matplotlib >=2.0, ==2.*",
"pandas >=0.16.2, <0.18.0",
"pytest >=3.2.1, ==3.*",
"seaborn >=0.6.0, ==0.6.*",
"tox >=2.8.2, ==2.*",
"treetime ==0.4.0"
],
dependency_links = [
"https://api.github.com/repos/neherlab/treetime/tarball/py3#egg=treetime-0.4.0"
],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Science",
"License :: OSI Approved :: MIT License",
],
scripts=['bin/augur']
)
| import os
from setuptools import setup
setup(
name = "augur",
version = "0.1.0",
author = "nextstrain developers",
author_email = "[email protected], [email protected]",
description = ("Pipelines for real-time phylogenetic analysis"),
license = "MIT",
keywords = "nextstrain, molecular epidemiology",
url = "https://github.com/nextstrain/augur",
packages=['augur'],
install_requires = [
"biopython >=1.69, ==1.*",
"boto >=2.38, ==2.*",
"cvxopt >=1.1.8, ==1.1.*",
"ipdb >=0.10.1, ==0.10.*",
"matplotlib >=2.0, ==2.*",
"pandas >=0.16.2, <0.18.0",
"pytest >=3.2.1, ==3.*",
"seaborn >=0.6.0, ==0.6.*",
"tox >=2.8.2, ==2.*",
"treetime ==0.3.0"
],
dependency_links = [
"https://api.github.com/repos/neherlab/treetime/tarball/py3#egg=treetime-0.3.0"
],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Science",
"License :: OSI Approved :: MIT License",
],
scripts=['bin/augur']
)
|
Optimize plugin loading, add error messages | import java.io.*;
import java.net.*;
import java.util.*;
import java.net.ServerSocket;
public class JMP {
public static void main(String[] args) throws IOException {
String mysqlHost = System.getProperty("mysqlHost");
int mysqlPort = Integer.parseInt(System.getProperty("mysqlPort"));
int port = Integer.parseInt(System.getProperty("port"));
boolean listening = true;
ServerSocket listener = null;
ArrayList<Proxy_Plugin> plugins = new ArrayList<Proxy_Plugin>();
try {
listener = new ServerSocket(port);
}
catch (IOException e) {
System.err.print("Could not listen on port\n");
System.exit(-1);
}
String[] ps = System.getProperty("plugins").split(",");
while (listening) {
for (String p: ps) {
try {
plugins.add((Proxy_Plugin) Proxy_Plugin.class.getClassLoader().loadClass(p).newInstance());
System.err.print("Loaded plugin "+p+"\n");
}
catch (java.lang.ClassNotFoundException e) {
System.err.print("Failed to load plugin "+p+"\n");
continue;
}
catch (java.lang.InstantiationException e) {
System.err.print("Failed to load plugin "+p+"\n");
continue;
}
catch (java.lang.IllegalAccessException e) {
System.err.print("Failed to load plugin "+p+"\n");
continue;
}
}
new Proxy(listener.accept(), mysqlHost, mysqlPort, plugins).start();
plugins.clear();
}
listener.close();
}
}
| import java.io.*;
import java.net.*;
import java.util.*;
import java.net.ServerSocket;
public class JMP {
public static void main(String[] args) throws IOException {
String mysqlHost = System.getProperty("mysqlHost");
int mysqlPort = Integer.parseInt(System.getProperty("mysqlPort"));
int port = Integer.parseInt(System.getProperty("port"));
boolean listening = true;
ServerSocket listener = null;
ArrayList<Proxy_Plugin> plugins = new ArrayList<Proxy_Plugin>();
try {
listener = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port");
System.exit(-1);
}
String[] ps = System.getProperty("plugins").split(",");
while (listening) {
plugins.clear();
for (String p: ps) {
try {
plugins.add((Proxy_Plugin) Proxy_Plugin.class.getClassLoader().loadClass(p).newInstance());
}
catch (java.lang.ClassNotFoundException e) {
continue;
}
catch (java.lang.InstantiationException e) {
continue;
}
catch (java.lang.IllegalAccessException e) {
continue;
}
}
new Proxy(listener.accept(), mysqlHost, mysqlPort, plugins).start();
}
listener.close();
}
}
|
Improve generate_tmp_file_path pytest command docs | import os
def generate_tmp_file_path(tmpdir_factory,
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
Generate file path relative to a temporary directory.
:param tmpdir_factory: py.test's `tmpdir_factory` fixture.
:param file_name_with_extension: file name with extension e.g. `file_name.ext`.
:param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa
:return: file path.
"""
basetemp = tmpdir_factory.getbasetemp()
if tmp_dir_path:
if os.path.isabs(tmp_dir_path):
raise ValueError('tmp_dir_path is not a relative path!')
# http://stackoverflow.com/a/16595356/1557013
for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep):
# Accounting for possible path separator at the end.
if tmp_file_dir_path_part:
tmpdir_factory.mktemp(tmp_file_dir_path_part)
tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension)
else:
tmp_file_path = str(basetemp.join(file_name_with_extension))
return tmp_file_path
| import os
def generate_tmp_file_path(tmpdir_factory,
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
Generate file path rooted in a temporary dir.
:param tmpdir_factory: py.test's tmpdir_factory fixture.
:param file_name_with_extension: e.g. 'file.ext'
:param tmp_dir_path: generated tmp file directory path relative to base tmp dir,
e.g. 'file/is/here'.
:return: generated file path.
"""
basetemp = tmpdir_factory.getbasetemp()
if tmp_dir_path:
if os.path.isabs(tmp_dir_path):
raise ValueError('tmp_dir_path is not a relative path!')
# http://stackoverflow.com/a/16595356/1557013
for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep):
# Accounting for possible path separator at the end.
if tmp_file_dir_path_part:
tmpdir_factory.mktemp(tmp_file_dir_path_part)
tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension)
else:
tmp_file_path = str(basetemp.join(file_name_with_extension))
return tmp_file_path
|
Refactor remote_repo, to return None
if there is no remote. | from collections import namedtuple
Remote = namedtuple('Remote', ('name', 'url'))
CommitInfo = namedtuple("CommitInfo", ('commit', 'origin', 'remote_repo'))
class PRInfo(object):
def __init__(self, json):
self.json = json
@property
def base_sha(self):
return self.json['base']['sha']
@property
def head_sha(self):
return self.json['head']['sha']
@property
def has_remote_repo(self):
return self.json['base']['repo']['owner']['login'] != \
self.json['head']['repo']['owner']['login']
@property
def remote_repo(self):
remote = None
if self.has_remote_repo:
remote = Remote(name=self.json['head']['repo']['owner']['login'],
url=self.json['head']['repo']['clone_url'])
return remote
def to_commit_info(self):
return CommitInfo(self.base_sha, self.head_sha, self.remote_repo)
def get_pr_info(requester, reponame, number):
"Returns the PullRequest as a PRInfo object"
resp = requester.get(
'https://api.github.com/repos/%s/pulls/%s' % (reponame, number))
return PRInfo(resp.json)
| from collections import namedtuple
Remote = namedtuple('Remote', ('name', 'url'))
CommitInfo = namedtuple("CommitInfo", ('commit', 'origin', 'remote_repo'))
class PRInfo(object):
def __init__(self, json):
self.json = json
@property
def base_sha(self):
return self.json['base']['sha']
@property
def head_sha(self):
return self.json['head']['sha']
@property
def has_remote_repo(self):
return self.json['base']['repo']['owner']['login'] != \
self.json['head']['repo']['owner']['login']
@property
def remote_repo(self):
return Remote(name=self.json['head']['repo']['owner']['login'],
url=self.json['head']['repo']['clone_url'])
def to_commit_info(self):
remote_repo = None
if self.has_remote_repo:
remote_repo = self.remote_repo
return CommitInfo(self.base_sha, self.head_sha, remote_repo)
def get_pr_info(requester, reponame, number):
"Returns the PullRequest as a PRInfo object"
resp = requester.get(
'https://api.github.com/repos/%s/pulls/%s' % (reponame, number))
return PRInfo(resp.json)
|
Modify the tool-info module according to Philipp's reviews | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + [task.single_input_file]
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = result.RESULT_TRUE_PROP
elif "s UNSATISFIABLE" in line:
status = result.RESULT_FALSE_PROP
if not status:
status = result.RESULT_ERROR
return status
| # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Tool info for Kissat SAT Solver.
URL: http://fmv.jku.at/kissat/
"""
def executable(self, tool_locator):
return tool_locator.find_executable("kissat", subdir="build")
def name(self):
return "Kissat"
def version(self, executable):
return self._version_from_tool(executable)
def cmdline(self, executable, options, task, rlimits):
return [executable] + options + list(task.input_files_or_identifier)
def determine_result(self, run):
"""
@return: status of Kissat after executing a run
"""
status = None
for line in run.output:
if "s SATISFIABLE" in line:
status = "SAT"
elif "s UNSATISFIABLE" in line:
status = "UNSAT"
if (not status or status == result.RESULT_UNKNOWN) and run.was_timeout:
status = "TIMEOUT"
if not status:
status = result.RESULT_ERROR
return status
|
Fix warning, add assignment operator | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), // the package file to use
qunit: { // internal task or name of a plugin (like "qunit")
all: ['js/tests/*.html']
},
watch: {
files: [
'js/tests/*.js',
'js/tests/*.html',
'tmpl/*.html',
'js/*.js',
'src/*.go'
],
tasks: ['qunit', 'shell:buildGo', 'shell:testGo']
},
shell: {
buildGo: {
command: function() {
var gitCmd = 'git rev-parse --short HEAD';
return 'go build -o build/rtfblog' +
' -ldflags "-X main.genVer=$(' + gitCmd + ')"' +
' src/*.go';
},
options: {
stdout: true,
stderr: true
}
},
testGo: {
command: 'go test ./src/...',
options: {
stdout: true,
stderr: true
}
}
}
});
// load up your plugins
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');
// register one or more task lists (you should ALWAYS have a "default" task list)
grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'), // the package file to use
qunit: { // internal task or name of a plugin (like "qunit")
all: ['js/tests/*.html']
},
watch: {
files: [
'js/tests/*.js',
'js/tests/*.html',
'tmpl/*.html',
'js/*.js',
'src/*.go'
],
tasks: ['qunit', 'shell:buildGo', 'shell:testGo']
},
shell: {
buildGo: {
command: function() {
var gitCmd = 'git rev-parse --short HEAD';
return 'go build -o build/rtfblog' +
' -ldflags "-X main.genVer $(' + gitCmd + ')"' +
' src/*.go';
},
options: {
stdout: true,
stderr: true
}
},
testGo: {
command: 'go test ./src/...',
options: {
stdout: true,
stderr: true
}
}
}
});
// load up your plugins
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');
// register one or more task lists (you should ALWAYS have a "default" task list)
grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']);
};
|
Add helper: get single post | <?php
/**
* @example
* FastForward::Helpers()
* ->renderImage(142, 'full');
*/
class FastForward_Helpers {
public function renderImage($id, $size = 'thumbnail') {
echo wp_get_attachment_image($id, $size);
}
public function getImageAllSizes($id, $custom = array()) {
$thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
$medium = wp_get_attachment_image_src($id, 'medium');
$large = wp_get_attachment_image_src($id, 'large');
$full = wp_get_attachment_image_src($id, 'full');
if ($custom) {
$customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1]));
}
$set = array(
'thumbnail' => $thumbnail,
'medium' => $medium,
'large' => $large,
'full' => $full,
'custom' => $customSize
);
return $set;
}
public function getSinglePost($args) {
$args = wp_parse_args($args, array(
'posts_per_page' => 1
));
$results = get_pages($args);
return $results[0];
}
public function help() {
global $FastForward;
$methods = array();
foreach ($FastForward as $obj) {
$methods[get_class($obj)] = get_class_methods($obj);
}
echo '<pre>';
print_r($methods);
echo '</pre>';
}
}
| <?php
/**
* @example
* FastForward::Helpers()
* ->renderImage(142, 'full');
*/
class FastForward_Helpers {
public function renderImage($id, $size = 'thumbnail') {
echo wp_get_attachment_image($id, $size);
}
public function getImageAllSizes($id, $custom = array()) {
$thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
$medium = wp_get_attachment_image_src($id, 'medium');
$large = wp_get_attachment_image_src($id, 'large');
$full = wp_get_attachment_image_src($id, 'full');
if ($custom) {
$customSize = wp_get_attachment_image_src($id, array($custom[0], $custom[1]));
}
$set = array(
'thumbnail' => $thumbnail,
'medium' => $medium,
'large' => $large,
'full' => $full,
'custom' => $customSize
);
return $set;
}
public function help() {
global $FastForward;
$methods = array();
foreach ($FastForward as $obj) {
$methods[get_class($obj)] = get_class_methods($obj);
}
echo '<pre>';
print_r($methods);
echo '</pre>';
}
}
|
Add message for empty slide history | import React from 'react';
import {connectToStores} from 'fluxible-addons-react';
import SlideHistoryStore from '../../../../stores/SlideHistoryStore';
import UserProfileStore from '../../../../stores/UserProfileStore';
import PermissionsStore from '../../../../stores/PermissionsStore';
import {Feed} from 'semantic-ui-react';
import ContentChangeItem from './ContentChangeItem';
class SlideHistoryPanel extends React.Component {
render() {
const changes = this.props.SlideHistoryStore.changes && this.props.SlideHistoryStore.changes.length ? this.props.SlideHistoryStore.changes.map((change, index) => {
return (
<ContentChangeItem selector={this.props.selector} permissions={this.props.PermissionsStore.permissions} change={change} key={index}/>
);
}) : 'There are no changes for this slide.';
return (
<div ref="slideHistoryPanel" className="ui">
<Feed>
{changes}
</Feed>
</div>
);
}
}
SlideHistoryPanel.contextTypes = {
executeAction: React.PropTypes.func.isRequired
};
SlideHistoryPanel = connectToStores(SlideHistoryPanel, [SlideHistoryStore, UserProfileStore, PermissionsStore], (context, props) => {
return {
SlideHistoryStore: context.getStore(SlideHistoryStore).getState(),
UserProfileStore: context.getStore(UserProfileStore).getState(),
PermissionsStore: context.getStore(PermissionsStore).getState()
};
});
export default SlideHistoryPanel;
| import React from 'react';
import {connectToStores} from 'fluxible-addons-react';
import SlideHistoryStore from '../../../../stores/SlideHistoryStore';
import UserProfileStore from '../../../../stores/UserProfileStore';
import PermissionsStore from '../../../../stores/PermissionsStore';
import {Feed} from 'semantic-ui-react';
import ContentChangeItem from './ContentChangeItem';
class SlideHistoryPanel extends React.Component {
render() {
const changes = this.props.SlideHistoryStore.changes ? this.props.SlideHistoryStore.changes.map((change, index) => {
return (
<ContentChangeItem selector={this.props.selector} permissions={this.props.PermissionsStore.permissions} change={change} key={index}/>
);
}) : '';
return (
<div ref="slideHistoryPanel" className="ui">
<Feed>
{changes}
</Feed>
</div>
);
}
}
SlideHistoryPanel.contextTypes = {
executeAction: React.PropTypes.func.isRequired
};
SlideHistoryPanel = connectToStores(SlideHistoryPanel, [SlideHistoryStore, UserProfileStore, PermissionsStore], (context, props) => {
return {
SlideHistoryStore: context.getStore(SlideHistoryStore).getState(),
UserProfileStore: context.getStore(UserProfileStore).getState(),
PermissionsStore: context.getStore(PermissionsStore).getState()
};
});
export default SlideHistoryPanel;
|
Handle null being passed to getUserById | <?php
namespace Hackzilla\Bundle\TicketBundle\Manager;
use Doctrine\ORM\EntityRepository;
use Hackzilla\Bundle\TicketBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
class UserManager implements UserManagerInterface
{
private $tokenStorage;
private $userRepository;
public function __construct(
TokenStorage $tokenStorage,
EntityRepository $userRepository
) {
$this->tokenStorage = $tokenStorage;
$this->userRepository = $userRepository;
}
/**
* @return int
*/
public function getCurrentUser()
{
$user = $this->tokenStorage->getToken()->getUser();
if ($user === 'anon.') {
$user = 0;
}
return $user;
}
/**
* @param int $userId
*
* @return UserInterface|null
*/
public function getUserById($userId)
{
if (!$userId) {
return null;
}
$user = $this->userRepository->find($userId);
return $user;
}
/**
* Current user has permission.
*
* @param UserInterface $user
* @param string $role
*
* @return bool
*/
public function hasRole(UserInterface $user, $role)
{
return in_array(strtoupper($role), $user->getRoles(), true);
}
}
| <?php
namespace Hackzilla\Bundle\TicketBundle\Manager;
use Doctrine\ORM\EntityRepository;
use Hackzilla\Bundle\TicketBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
class UserManager implements UserManagerInterface
{
private $tokenStorage;
private $userRepository;
public function __construct(
TokenStorage $tokenStorage,
EntityRepository $userRepository
) {
$this->tokenStorage = $tokenStorage;
$this->userRepository = $userRepository;
}
/**
* @return int
*/
public function getCurrentUser()
{
$user = $this->tokenStorage->getToken()->getUser();
if ($user === 'anon.') {
$user = 0;
}
return $user;
}
/**
* @param int $userId
*
* @return UserInterface|null
*/
public function getUserById($userId)
{
$user = $this->userRepository->find($userId);
return $user;
}
/**
* Current user has permission.
*
* @param UserInterface $user
* @param string $role
*
* @return bool
*/
public function hasRole(UserInterface $user, $role)
{
return in_array(strtoupper($role), $user->getRoles(), true);
}
}
|
Fix style and missing semi-colon. | <?php // CONFIRMATION DIALOG ?>
<div id="confirmDelete" title="Delete {{ $model }}" style="display: none;">
This action <em>cannot</em> be undone.
Are you sure you want to delete this {{ $model }}?
</div>
<?php // SCRIPT ?>
<script>
$(function() {
var form = $("deleteItem")
var confirm = $( "#confirmDelete" ).dialog({
autoOpen: false,
height: 300,
width: 400,
modal: true,
buttons: {
"Delete": deleteItem,
Cancel: function() {
confirm.dialog( "close" );
}
},
close: function() {
confirm.dialog( "close" );
}
});
function deleteItem() {
id = $(this).data('id');
jQuery.ajax({
url: "{{ url('api/' . $model) }}/" + id,
type: "POST",
data: {
'_token': "{{ csrf_token() }}",
'_method': "DELETE"
},
success: function () {
window.location.reload();
}
});
}
// Add button click handler
$( ".deleteButton" ).button().on( "click", function() {
var id_string = this.id;
id = id_string.substring(7);
confirm.data('id', id);
confirm.dialog( "open" );
});
});
</script> | <?php // CONFIRMATION DIALOG ?>
<div id="confirmDelete" title="Delete {{ $model }}" style="display: none;">
This action <em>cannot</em> be undone.
Are you sure you want to delete this {{ $model }}?
</div>
<?php // SCRIPT ?>
<script>
$(function() {
var form = $("deleteItem")
var confirm = $( "#confirmDelete" ).dialog({
autoOpen: false,
height: 300,
width: 400,
modal: true,
buttons: {
"Delete": deleteItem,
Cancel: function() {
confirm.dialog( "close" );
}
},
close: function() {
confirm.dialog( "close" );
}
});
function deleteItem() {
id = $(this).data('id');
jQuery.ajax({
url: "{{ url('api/' . $model) }}/" + id,
type: "POST",
data: {
'_token': "{{ csrf_token() }}",
'_method': "DELETE"
},
success: function (response) {
window.location.reload();
},
});
}
// Add button click handler
$( ".deleteButton" ).button().on( "click", function() {
var id_string = this.id;
id = id_string.substring(7);
confirm.data('id', id)
confirm.dialog( "open" );
});
});
</script> |
Add key type to refresh token model | <?php
namespace Laravel\Passport;
use Illuminate\Database\Eloquent\Model;
class RefreshToken extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'oauth_refresh_tokens';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The "type" of the primary key ID.
*
* @var string
*/
protected $keyType = 'string';
/**
* The guarded attributes on the model.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'revoked' => 'bool',
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'expires_at',
];
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* Get the access token that the refresh token belongs to.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function accessToken()
{
return $this->belongsTo(Passport::tokenModel());
}
/**
* Revoke the token instance.
*
* @return bool
*/
public function revoke()
{
return $this->forceFill(['revoked' => true])->save();
}
/**
* Determine if the token is a transient JWT token.
*
* @return bool
*/
public function transient()
{
return false;
}
}
| <?php
namespace Laravel\Passport;
use Illuminate\Database\Eloquent\Model;
class RefreshToken extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'oauth_refresh_tokens';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The guarded attributes on the model.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'revoked' => 'bool',
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'expires_at',
];
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* Get the access token that the refresh token belongs to.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function accessToken()
{
return $this->belongsTo(Passport::tokenModel());
}
/**
* Revoke the token instance.
*
* @return bool
*/
public function revoke()
{
return $this->forceFill(['revoked' => true])->save();
}
/**
* Determine if the token is a transient JWT token.
*
* @return bool
*/
public function transient()
{
return false;
}
}
|
Add 'attempts_left' to the http exception. | import json
import requests
SMS_AUTH_ENDPOINT = 'http://localhost:5000'
class SMSAuthClient(object):
def __init__(self, endpoint=SMS_AUTH_ENDPOINT):
self.endpoint = endpoint
def create_auth(self, auth_id, recipient):
payload = {'auth_id': auth_id,
'recipient': recipient}
response = requests.post(self.endpoint, json=payload)
try:
response.raise_for_status()
except requests.exceptions.HTTPError, e:
import pdb; pdb.set_trace()
content = e.response.json()
e.message = content['message']
e.strerror = content['reason']
raise e
return response.json()
def authenticate_code(self, auth_id, code):
args = {'auth_id': auth_id,
'code': code}
response = requests.get(self.endpoint, params=args)
try:
response.raise_for_status()
except requests.exceptions.HTTPError, e:
content = e.response.json()
e.message = content['message']
e.strerror = content['reason']
try:
e.attempts_left = content['attempts_left']
except:
pass
raise e
return response.json()
| import json
import requests
SMS_AUTH_ENDPOINT = 'http://localhost:5000'
class SMSAuthClient(object):
def __init__(self, endpoint=SMS_AUTH_ENDPOINT):
self.endpoint = endpoint
def create_auth(self, auth_id, recipient):
payload = {'auth_id': auth_id,
'recipient': recipient}
response = requests.post(self.endpoint, json=payload)
try:
response.raise_for_status()
except requests.exceptions.HTTPError, e:
import pdb; pdb.set_trace()
content = e.response.json()
e.message = content['message']
e.strerror = content['reason']
raise e
return response.json()
def authenticate_code(self, auth_id, code):
args = {'auth_id': auth_id,
'code': code}
response = requests.get(self.endpoint, params=args)
try:
response.raise_for_status()
except requests.exceptions.HTTPError, e:
content = e.response.json()
e.message = content['message']
e.strerror = content['reason']
raise e
return response.json()
|
Remove constants and internal value of status types | <?php
declare(strict_types=1);
namespace CultuurNet\UDB3\Event\ValueObjects;
use InvalidArgumentException;
final class StatusType
{
private const AVAILABLE = 'Available';
private const TEMPORARILY_UNAVAILABLE = 'TemporarilyUnavailable';
private const UNAVAILABLE = 'Unavailable';
/**
* @var string
*/
private $value;
/**
* @var string[]
*/
private const ALLOWED_VALUES = [
self::AVAILABLE,
self::TEMPORARILY_UNAVAILABLE,
self::UNAVAILABLE,
];
private function __construct(string $value)
{
if (!\in_array($value, self::ALLOWED_VALUES, true)) {
throw new InvalidArgumentException('Status does not support the value "' . $value . '"');
}
$this->value = $value;
}
public static function scheduled(): StatusType
{
return new StatusType(self::AVAILABLE);
}
public static function postponed(): StatusType
{
return new StatusType(self::TEMPORARILY_UNAVAILABLE);
}
public static function cancelled(): StatusType
{
return new StatusType(self::UNAVAILABLE);
}
public function toNative(): string
{
return $this->value;
}
public static function fromNative(string $value): StatusType
{
return new StatusType($value);
}
public function equals(StatusType $status): bool
{
return $this->value === $status->toNative();
}
}
| <?php
declare(strict_types=1);
namespace CultuurNet\UDB3\Event\ValueObjects;
use InvalidArgumentException;
final class StatusType
{
private const SCHEDULED = 'EventScheduled';
private const POSTPONED = 'EventPostponed';
private const CANCELLED = 'EventCancelled';
/**
* @var string
*/
private $value;
/**
* @var string[]
*/
private const ALLOWED_VALUES = [
self::SCHEDULED,
self::POSTPONED,
self::CANCELLED,
];
private function __construct(string $value)
{
if (!\in_array($value, self::ALLOWED_VALUES, true)) {
throw new InvalidArgumentException('Status does not support the value "' . $value . '"');
}
$this->value = $value;
}
public static function scheduled(): StatusType
{
return new StatusType(self::SCHEDULED);
}
public static function postponed(): StatusType
{
return new StatusType(self::POSTPONED);
}
public static function cancelled(): StatusType
{
return new StatusType(self::CANCELLED);
}
public function toNative(): string
{
return $this->value;
}
public static function fromNative(string $value): StatusType
{
return new StatusType($value);
}
public function equals(StatusType $status): bool
{
return $this->value === $status->toNative();
}
}
|
Add 'visit' to tracker stub | (function (instanceName) {
var i,
s,
z,
w = window,
d = document,
q = 'script',
f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
c = function () {
var self = this;
self._e = [];
for (i = 0; i < f.length; i++) {
(function (f) {
self[f] = function () {
// need to do this so params get called properly
self._e.push([f].concat(Array.prototype.slice.call(arguments, 0)));
return self;
};
})(f[i]);
}
};
w._w = w._w || {};
// check if instance of tracker exists
w._w[instanceName] = w[instanceName] = w[instanceName] || new c();
// insert tracker script
s = d.createElement(q);
s.async = 1;
s.src = '//static.woopra.com/js/wpt.min.js?v=3.0.3';
z = d.getElementsByTagName(q)[0];
z.parentNode.insertBefore(s, z);
})('woopra');
| (function (instanceName) {
var i,
s,
z,
w = window,
d = document,
q = 'script',
f = ['config', 'track', 'identify', 'push', 'call'],
c = function () {
var self = this;
self._e = [];
for (i = 0; i < f.length; i++) {
(function (f) {
self[f] = function () {
// need to do this so params get called properly
self._e.push([f].concat(Array.prototype.slice.call(arguments, 0)));
return self;
};
})(f[i]);
}
};
w._w = w._w || {};
// check if instance of tracker exists
w._w[instanceName] = w[instanceName] = w[instanceName] || new c();
// insert tracker script
s = d.createElement(q);
s.async = 1;
s.src = '//static.woopra.com/js/wpt.js?v=3.0.2';
z = d.getElementsByTagName(q)[0];
z.parentNode.insertBefore(s, z);
})('woopra');
|
[Cache/CouchbaseCache] Return false instead of null for compat.
This changeset fixes and verifies that instead of null, false is returned
from the fetch method. This fixes a bug which causes CouchbaseCache not
to work in combination with the ORM library. Test added. | <?php
namespace Doctrine\Tests\Common\Cache;
use Couchbase;
use Doctrine\Common\Cache\CouchbaseCache;
class CouchbaseCacheTest extends CacheTest
{
private $couchbase;
public function setUp()
{
if (extension_loaded('couchbase')) {
try {
$this->couchbase = new Couchbase('127.0.0.1', 'Administrator', 'password', 'default');
} catch(Exception $ex) {
$this->markTestSkipped('Could not instantiate the Couchbase cache because of: ' . $ex);
}
} else {
$this->markTestSkipped('The ' . __CLASS__ .' requires the use of the couchbase extension');
}
}
public function testNoExpire()
{
$cache = $this->_getCacheDriver();
$cache->save('noexpire', 'value', 0);
sleep(1);
$this->assertTrue($cache->contains('noexpire'), 'Couchbase provider should support no-expire');
}
public function testLongLifetime()
{
$cache = $this->_getCacheDriver();
$cache->save('key', 'value', 30 * 24 * 3600 + 1);
$this->assertTrue($cache->contains('key'), 'Couchbase provider should support TTL > 30 days');
}
public function testFalseOnFailedFetch() {
$cache = $this->_getCacheDriver();
$result = $cache->fetch('nonexistent_key');
$this->assertFalse($result);
$this->assertNotNull($result);
}
protected function _getCacheDriver()
{
$driver = new CouchbaseCache();
$driver->setCouchbase($this->couchbase);
return $driver;
}
} | <?php
namespace Doctrine\Tests\Common\Cache;
use Couchbase;
use Doctrine\Common\Cache\CouchbaseCache;
class CouchbaseCacheTest extends CacheTest
{
private $couchbase;
public function setUp()
{
if (extension_loaded('couchbase')) {
try {
$this->couchbase = new Couchbase('127.0.0.1', 'Administrator', 'password', 'default');
} catch(Exception $ex) {
$this->markTestSkipped('Could not instantiate the Couchbase cache because of: ' . $ex);
}
} else {
$this->markTestSkipped('The ' . __CLASS__ .' requires the use of the couchbase extension');
}
}
public function testNoExpire()
{
$cache = $this->_getCacheDriver();
$cache->save('noexpire', 'value', 0);
sleep(1);
$this->assertTrue($cache->contains('noexpire'), 'Couchbase provider should support no-expire');
}
public function testLongLifetime()
{
$cache = $this->_getCacheDriver();
$cache->save('key', 'value', 30 * 24 * 3600 + 1);
$this->assertTrue($cache->contains('key'), 'Couchbase provider should support TTL > 30 days');
}
protected function _getCacheDriver()
{
$driver = new CouchbaseCache();
$driver->setCouchbase($this->couchbase);
return $driver;
}
} |
Fix support for positional parameters in Doctrine ORM | <?php
namespace RulerZ\Target\DoctrineORM;
use Hoa\Ruler\Model as AST;
use RulerZ\Compiler\Context;
use RulerZ\Exception;
use RulerZ\Model;
use RulerZ\Target\GenericSqlVisitor;
use RulerZ\Target\Operators\Definitions as OperatorsDefinitions;
class DoctrineORMVisitor extends GenericSqlVisitor
{
/**
* @var DoctrineAutoJoin
*/
private $autoJoin;
public function __construct(Context $context, OperatorsDefinitions $operators, $allowStarOperator = true)
{
parent::__construct($context, $operators, $allowStarOperator);
$this->autoJoin = new DoctrineAutoJoin($context['em'], $context['root_entities'], $context['root_aliases'], $context['joins']);
}
/**
* @inheritDoc
*/
public function getCompilationData()
{
return [
'detectedJoins' => $this->autoJoin->getDetectedJoins(),
];
}
/**
* {@inheritDoc}
*/
public function visitAccess(AST\Bag\Context $element, &$handle = null, $eldnah = null)
{
return $this->autoJoin->buildAccessPath($element);
}
/**
* {@inheritDoc}
*/
public function visitParameter(Model\Parameter $element, &$handle = null, $eldnah = null)
{
// placeholder for a positional parameters
if (is_int($element->getName())) {
return '?' . $element->getName();
}
// placeholder for a named parameter
return ':' . $element->getName();
}
}
| <?php
namespace RulerZ\Target\DoctrineORM;
use Hoa\Ruler\Model as AST;
use RulerZ\Compiler\Context;
use RulerZ\Exception;
use RulerZ\Model;
use RulerZ\Target\GenericSqlVisitor;
use RulerZ\Target\Operators\Definitions as OperatorsDefinitions;
class DoctrineORMVisitor extends GenericSqlVisitor
{
/**
* @var DoctrineAutoJoin
*/
private $autoJoin;
public function __construct(Context $context, OperatorsDefinitions $operators, $allowStarOperator = true)
{
parent::__construct($context, $operators, $allowStarOperator);
$this->autoJoin = new DoctrineAutoJoin($context['em'], $context['root_entities'], $context['root_aliases'], $context['joins']);
}
/**
* @inheritDoc
*/
public function getCompilationData()
{
return [
'detectedJoins' => $this->autoJoin->getDetectedJoins(),
];
}
/**
* {@inheritDoc}
*/
public function visitAccess(AST\Bag\Context $element, &$handle = null, $eldnah = null)
{
return $this->autoJoin->buildAccessPath($element);
}
/**
* {@inheritDoc}
*/
public function visitParameter(Model\Parameter $element, &$handle = null, $eldnah = null)
{
// make it a placeholder
return ':' . $element->getName();
}
private function getRootAlias()
{
return $this->context['root_aliases'][0];
}
}
|
Fix ArgumentParserTest.test_argv_from_args to be more portable.
One of the tests was testing --jobs 4, but on a machine w/
4 CPUs, that would get reduced to the default. This patch
changes things to test --jobs 3, which is less likely to be
seen in the wild. | # Copyright 2014 Dirk Pranke. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import optparse
import unittest
from typ import ArgumentParser
class ArgumentParserTest(unittest.TestCase):
def test_optparse_options(self):
parser = optparse.OptionParser()
ArgumentParser.add_option_group(parser, 'foo',
discovery=True,
running=True,
reporting=True,
skip='[-d]')
options, _ = parser.parse_args(['-j', '1'])
self.assertEqual(options.jobs, 1)
def test_argv_from_args(self):
def check(argv, expected=None):
parser = ArgumentParser()
args = parser.parse_args(argv)
actual_argv = parser.argv_from_args(args)
expected = expected or argv
self.assertEqual(expected, actual_argv)
check(['--version'])
check(['--coverage', '--coverage-omit', 'foo'])
check(['--jobs', '3'])
check(['-vv'], ['--verbose', '--verbose'])
| # Copyright 2014 Dirk Pranke. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import optparse
import unittest
from typ import ArgumentParser
class ArgumentParserTest(unittest.TestCase):
def test_optparse_options(self):
parser = optparse.OptionParser()
ArgumentParser.add_option_group(parser, 'foo',
discovery=True,
running=True,
reporting=True,
skip='[-d]')
options, _ = parser.parse_args(['-j', '1'])
self.assertEqual(options.jobs, 1)
def test_argv_from_args(self):
def check(argv, expected=None):
parser = ArgumentParser()
args = parser.parse_args(argv)
actual_argv = parser.argv_from_args(args)
expected = expected or argv
self.assertEqual(expected, actual_argv)
check(['--version'])
check(['--coverage', '--coverage-omit', 'foo'])
check(['--jobs', '4'])
check(['-vv'], ['--verbose', '--verbose'])
|
Refactor promise helper function to include notify. | /*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */
'use strict';
var Q = require('q');
var utils = {
/**
* @see http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
*/
generateGUID: function() {
var s4 = function() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};
var guid = [
s4(),
s4(),
'-',
s4(),
'-',
s4(),
'-',
s4(),
'-',
s4(),
s4(),
s4(),
].join('');
return guid;
},
promise: function(callback, thisArg) {
var deferred = Q.defer();
var promise = deferred.promise;
var resolve = function(result) {
if (deferred) {
deferred.resolve(result);
deferred = null;
}
};
var reject = function(reason) {
if (deferred) {
deferred.reject(reason);
deferred = null;
}
};
var notify = function(value) {
if (deferred) {
deferred.notify(value);
}
};
try {
callback.call(thisArg, resolve, reject, notify);
} catch (ex) {
reject(ex);
}
return promise;
},
};
module.exports = utils;
| /*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */
'use strict';
var Q = require('q');
var utils = {
/**
* @see http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
*/
generateGUID: function() {
var s4 = function() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};
var guid = [
s4(),
s4(),
'-',
s4(),
'-',
s4(),
'-',
s4(),
'-',
s4(),
s4(),
s4(),
].join('');
return guid;
},
promise: function(callback, thisArg) {
var deferred = Q.defer();
var promise = deferred.promise;
var done = function(err, result) {
if (deferred) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
deferred = null;
}
};
var resolve = function(result) {
done(null, result);
};
var reject = function(reason) {
done(reason);
};
try {
callback.call(thisArg, resolve, reject);
} catch (ex) {
done(ex);
}
return promise;
},
};
module.exports = utils;
|
conan: Copy find modules to root of module path | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class VeraPPTargetCmakeConan(ConanFile):
name = "verapp-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/verapp-target-cmake"
license = "MIT"
def source(self):
zip_name = "verapp-target-cmake.zip"
download("https://github.com/polysquare/"
"verapp-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="verapp-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/verapp-target-cmake",
src="verapp-target-cmake-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class VeraPPTargetCmakeConan(ConanFile):
name = "verapp-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/verapp-target-cmake"
license = "MIT"
def source(self):
zip_name = "verapp-target-cmake.zip"
download("https://github.com/polysquare/"
"verapp-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/verapp-target-cmake",
src="verapp-target-cmake-" + VERSION,
keep_path=True)
|
Remove debug output in queue display function | ui = {
}
ui.player = {
update: function(trackURI) {
spotify.getTrackInfo(trackURI)
.then(function(track) {
document.getElementById('player-title').innerHTML = track.title
document.getElementById('player-artist').innerHTML = track.artist
document.getElementById('player-album').innerHTML = track.album
document.getElementById('player-img').src = track.cover
});
},
displayQueue: function(queue) {
var queueElement = document.getElementById('queue');
// empty the old queue
while (queueElement.firstChild) {
queueElement.removeChild(queueElement.firstChild);
}
for (i in queue) {
var uri = queue[i]["uri"];
var div = document.createElement("div");
queueElement.appendChild(div);
spotify.getTrackInfo(uri)
.then(function(track) {
var text = document.createTextNode(track.artist + " - " + track.title);
div.appendChild(text);
div.appendChild(document.createElement("br"));
});
}
}
};
ui.uriSelection = {
getUri: function() {
return document.getElementById("uri-to-add").value;
},
clear: function() {
document.getElementById("uri-to-add").value = '';
}
}
| ui = {
}
ui.player = {
update: function(trackURI) {
spotify.getTrackInfo(trackURI)
.then(function(track) {
document.getElementById('player-title').innerHTML = track.title
document.getElementById('player-artist').innerHTML = track.artist
document.getElementById('player-album').innerHTML = track.album
document.getElementById('player-img').src = track.cover
});
},
displayQueue: function(queue) {
console.log(queue);
var queueElement = document.getElementById('queue');
// empty the old queue
while (queueElement.firstChild) {
queueElement.removeChild(queueElement.firstChild);
}
for (i in queue) {
var uri = queue[i]["uri"];
var div = document.createElement("div");
queueElement.appendChild(div);
spotify.getTrackInfo(uri)
.then(function(track) {
var text = document.createTextNode(track.artist + " - " + track.title);
div.appendChild(text);
div.appendChild(document.createElement("br"));
});
}
}
};
ui.uriSelection = {
getUri: function() {
return document.getElementById("uri-to-add").value;
},
clear: function() {
document.getElementById("uri-to-add").value = '';
}
}
|
[Fix]: Fix problem with fragment backstack
Resolves: #
See also: # | package com.kogimobile.android.baselibrary.navigation;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentNavigator {
public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId){
navigateTo(
manager,
fragment,
containerId,
fragment.getClass().getSimpleName(),
false,
false
);
}
public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId,boolean addToBackStack){
navigateTo(
manager,
fragment,
containerId,
fragment.getClass().getSimpleName(),
addToBackStack,
false
);
}
public static void navigateTo(FragmentManager manager,
Fragment fragment,
int containerId,
String fragmentTag,
boolean addToBackStack,
boolean allowCommitStateLoss){
FragmentTransaction ft = manager.beginTransaction();
ft.replace(containerId, fragment,fragmentTag);
if(addToBackStack) {
ft.addToBackStack(fragmentTag);
}
if(allowCommitStateLoss){
ft.commitAllowingStateLoss();
}
else {
ft.commit();
}
}
public static void cleanFragmentStack(FragmentManager fm) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
| package com.kogimobile.android.baselibrary.navigation;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class FragmentNavigator {
public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId){
navigateTo(
manager,
fragment,
containerId,
fragment.getClass().getSimpleName(),
false,
false
);
}
public static void navigateTo(FragmentManager manager, Fragment fragment, int containerId,boolean addToBackStack){
navigateTo(
manager,
fragment,
containerId,
fragment.getClass().getSimpleName(),
addToBackStack,
false
);
}
public static void navigateTo(FragmentManager manager,
Fragment fragment,
int containerId,
String fragmentTag,
boolean addToBackStack,
boolean allowCommitStateLoss){
FragmentTransaction ft = manager.beginTransaction();
ft.addToBackStack(fragmentTag);
ft.replace(containerId, fragment,fragmentTag);
if(allowCommitStateLoss){
ft.commitAllowingStateLoss();
}
else {
ft.commit();
}
if(addToBackStack) {
}
}
public static void cleanFragmentStack(FragmentManager fm) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
|
Remove silly exception inserted for testing | from datetime import datetime
from sqlalchemy import MetaData, Column, ForeignKey, Table
from sqlalchemy import DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
old_revision_table = Table('revision', metadata,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datetime.utcnow),
Column('text', UnicodeText(), nullable=False),
Column('sentiment', Integer, default=0),
Column('user_id', Integer, ForeignKey('user.id'), nullable=False),
Column('comment_id', Integer, ForeignKey('comment.id'), nullable=False),
Column('title', Unicode(255), nullable=True)
)
def upgrade(migrate_engine):
metadata.bind = migrate_engine
revisions_table = Table('revision', metadata, autoload=True)
q = migrate_engine.execute(revisions_table.select())
for (id, _, text, _, _, _, title) in q:
title = title and title.strip() or ''
if len(title) < 5:
continue
if title.startswith('Re: '):
continue
new_text = ('**%(title)s**\n'
'\n'
'%(text)s') % {'title': title,
'text': text}
update_statement = revisions_table.update(
revisions_table.c.id == id, {'text': new_text})
migrate_engine.execute(update_statement)
revisions_table.c.title.drop()
def downgrade(migrate_engine):
raise NotImplementedError()
| from datetime import datetime
from sqlalchemy import MetaData, Column, ForeignKey, Table
from sqlalchemy import DateTime, Integer, Unicode, UnicodeText
metadata = MetaData()
old_revision_table = Table('revision', metadata,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datetime.utcnow),
Column('text', UnicodeText(), nullable=False),
Column('sentiment', Integer, default=0),
Column('user_id', Integer, ForeignKey('user.id'), nullable=False),
Column('comment_id', Integer, ForeignKey('comment.id'), nullable=False),
Column('title', Unicode(255), nullable=True)
)
def upgrade(migrate_engine):
metadata.bind = migrate_engine
revisions_table = Table('revision', metadata, autoload=True)
q = migrate_engine.execute(revisions_table.select())
for (id, _, text, _, _, _, title) in q:
title = title and title.strip() or ''
if len(title) < 5:
continue
if title.startswith('Re: '):
continue
new_text = ('**%(title)s**\n'
'\n'
'%(text)s') % {'title': title,
'text': text}
update_statement = revisions_table.update(
revisions_table.c.id == id, {'text': new_text})
migrate_engine.execute(update_statement)
revisions_table.c.title.drop()
raise Exception('ksjdfkl')
def downgrade(migrate_engine):
raise NotImplementedError()
|
Set static function to public | <?php
namespace Caffeinated\Slugs\Traits;
trait Sluggable
{
/**
* The "booting" method of the model.
*
* @return void
*/
public static function boot()
{
parent::boot();
static::creating(function($model) {
$slugName = static::getSlugName();
$slugField = static::getSlugField();
$model->$slugField = str_slug($model->$slugName);
$latestSlug = static::whereRaw("{$slugField} RLIKE '^{$model->slug}(-[0-9]*)?$'")
->latest('id')
->value($slugField);
if ($latestSlug) {
$pieces = explode('-', $latestSlug);
$number = intval(end($pieces));
$model->$slugField .= '-'.($number + 1);
}
});
}
/**
* Get the name field associated for slugs.
*
* @return string
*/
public static function getSlugName()
{
if (null !== static::$slug['name']) {
return static::$slug['name'];
}
return 'name';
}
/**
* Get the slug field associated for slugs.
*
* @return string
*/
public static function getSlugField()
{
if (null !== static::$slug['field']) {
return static::$slug['field'];
}
return 'slug';
}
}
| <?php
namespace Caffeinated\Slugs\Traits;
trait Sluggable
{
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::creating(function($model) {
$slugName = static::getSlugName();
$slugField = static::getSlugField();
$model->$slugField = str_slug($model->$slugName);
$latestSlug = static::whereRaw("{$slugField} RLIKE '^{$model->slug}(-[0-9]*)?$'")
->latest('id')
->value($slugField);
if ($latestSlug) {
$pieces = explode('-', $latestSlug);
$number = intval(end($pieces));
$model->$slugField .= '-'.($number + 1);
}
});
}
/**
* Get the name field associated for slugs.
*
* @return string
*/
public static function getSlugName()
{
if (null !== static::$slug['name']) {
return static::$slug['name'];
}
return 'name';
}
/**
* Get the slug field associated for slugs.
*
* @return string
*/
public static function getSlugField()
{
if (null !== static::$slug['field']) {
return static::$slug['field'];
}
return 'slug';
}
}
|
Add redirect to login endpoint if 401 received | function redirectLogin() {
window.location.href = '/log_in';
}
function likeComment(event, commentId) {
console.log(forumId);
console.log(commentId);
$.ajax({
'url': '/forums/' + forumId + '/comments/' + commentId + "/like",
'type': 'PUT',
'success': function(res) {
console.log(res);
$(event.target).children('p').text(res.likes.length);
$(event.target).siblings('i').children('p').text(res.dislikes.length);
},
'error': function(err) {
if (err) {
// window.location.href = '/log_in';
console.log(err);
}
},
'dataType': 'json'
})
}
function dislikeComment(event, commentId) {
console.log(forumId);
console.log(commentId);
$.ajax({
'url': '/forums/' + forumId + '/comments/' + commentId + "/dislike",
'type': 'PUT',
'success': function(res) {
$(event.target).children('p').text(res.dislikes.length);
$(event.target).siblings('i').children('p').text(res.likes.length);
},
'error': function(err) {
if (err) {
// window.location.href = '/log_in';
console.log(err);
}
},
'dataType': 'json'
})
}
| function likeComment(event, commentId) {
console.log(forumId);
console.log(commentId);
$.ajax({
'url': '/forums/' + forumId + '/comments/' + commentId + "/like",
'type': 'PUT',
'success': function(res) {
console.log(res);
$(event.target).children('p').text(res.likes.length);
$(event.target).siblings('i').children('p').text(res.dislikes.length);
},
'error': function(err) {
if (err) {
// window.location.href = '/log_in';
console.log(err);
}
},
'dataType': 'json'
})
}
function dislikeComment(event, commentId) {
console.log(forumId);
console.log(commentId);
$.ajax({
'url': '/forums/' + forumId + '/comments/' + commentId + "/dislike",
'type': 'PUT',
'success': function(res) {
$(event.target).children('p').text(res.dislikes.length);
$(event.target).siblings('i').children('p').text(res.likes.length);
},
'error': function(err) {
if (err) {
// window.location.href = '/log_in';
console.log(err);
}
},
'dataType': 'json'
})
}
|
Fix array syntax for 5.3 | <?php
namespace TwigBridgeTests\View;
use PHPUnit_Framework_TestCase;
use Mockery as m;
use Illuminate\View\Environment;
use TwigBridge\View\View;
use TwigBridge\Engines\TwigEngine;
use TwigBridge\Twig\Loader\Filesystem;
use Twig_Environment;
class ViewTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testViewGlobals()
{
$dispatcher = m::mock('Illuminate\Events\Dispatcher');
$dispatcher->shouldReceive('fire')->andReturn(true);
$environment = new Environment(
m::mock('Illuminate\View\Engines\EngineResolver'),
m::mock('Illuminate\View\ViewFinderInterface'),
$dispatcher
);
$engine = $this->getEngine();
$view = new View($environment, $engine, 'base.twig', __DIR__);
$view->render();
// Grab globals set on the Twig environment
$globals = $engine->getTwig()->getGlobals();
$this->assertArrayHasKey('__env', $globals);
$this->assertInstanceOf('Illuminate\View\Environment', $globals['__env']);
}
private function getFilesystem()
{
$finder = m::mock('Illuminate\View\ViewFinderInterface');
$finder->shouldReceive('getHints')->andReturn(array());
$finder->shouldReceive('getPaths')->andReturn(array(
__DIR__.'/../fixtures/Filesystem'
);
return new Filesystem($finder);
}
private function getEngine()
{
$twig = new Twig_Environment($this->getFilesystem(), array());
return new TwigEngine($twig, array());
}
}
| <?php
namespace TwigBridgeTests\View;
use PHPUnit_Framework_TestCase;
use Mockery as m;
use Illuminate\View\Environment;
use TwigBridge\View\View;
use TwigBridge\Engines\TwigEngine;
use TwigBridge\Twig\Loader\Filesystem;
use Twig_Environment;
class ViewTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testViewGlobals()
{
$dispatcher = m::mock('Illuminate\Events\Dispatcher');
$dispatcher->shouldReceive('fire')->andReturn(true);
$environment = new Environment(
m::mock('Illuminate\View\Engines\EngineResolver'),
m::mock('Illuminate\View\ViewFinderInterface'),
$dispatcher
);
$engine = $this->getEngine();
$view = new View($environment, $engine, 'base.twig', __DIR__);
$view->render();
// Grab globals set on the Twig environment
$globals = $engine->getTwig()->getGlobals();
$this->assertArrayHasKey('__env', $globals);
$this->assertInstanceOf('Illuminate\View\Environment', $globals['__env']);
}
private function getFilesystem()
{
$finder = m::mock('Illuminate\View\ViewFinderInterface');
$finder->shouldReceive('getHints')->andReturn([]);
$finder->shouldReceive('getPaths')->andReturn([
__DIR__.'/../fixtures/Filesystem'
]);
return new Filesystem($finder);
}
private function getEngine()
{
$twig = new Twig_Environment($this->getFilesystem(), array());
return new TwigEngine($twig, []);
}
}
|
Reduce number of ReflectionProperty::getName calls | <?php
namespace BroadwaySerialization\Hydration;
/**
* Simple implementation of a hydrator, which uses reflection to iterate over the properties of an object
*/
class HydrateUsingReflection implements Hydrate
{
/**
* @var array An array of arrays of \ReflectionProperty instances
*/
private $properties = [];
/**
* @inheritdoc
*/
public function hydrate(array $data, $object)
{
foreach ($this->propertiesOf($object) as $name => $property) {
if (!isset($data[$name])) {
continue;
}
$property->setValue($object, $data[$name]);
}
}
/**
* @param object $object
* @return \ReflectionProperty[]
*/
private function propertiesOf($object)
{
$className = get_class($object);
if (!isset($this->properties[$className])) {
foreach ((new \ReflectionObject($object))->getProperties() as $property) {
/** @var \ReflectionProperty $property */
$property->setAccessible(true);
$this->properties[$className][$property->getName()] = $property;
}
}
return $this->properties[$className];
}
}
| <?php
namespace BroadwaySerialization\Hydration;
/**
* Simple implementation of a hydrator, which uses reflection to iterate over the properties of an object
*/
class HydrateUsingReflection implements Hydrate
{
/**
* @var array An array of arrays of \ReflectionProperty instances
*/
private $properties = [];
/**
* @inheritdoc
*/
public function hydrate(array $data, $object)
{
foreach ($this->propertiesOf($object) as $property) {
if (!isset($data[$property->getName()])) {
continue;
}
$property->setValue($object, $data[$property->getName()]);
}
}
/**
* @param object $object
* @return \ReflectionProperty[]
*/
private function propertiesOf($object)
{
$className = get_class($object);
if (!isset($this->properties[$className])) {
$this->properties[$className] = (new \ReflectionObject($object))->getProperties();
foreach ($this->properties[$className] as $property) {
/** @var \ReflectionProperty $property */
$property->setAccessible(true);
}
}
return $this->properties[$className];
}
}
|
Add a dummy server - Tests are broken | import unittest
import mock
from tikplay import server
class DummyServer():
def __init__(self, *args, **kwargs):
self._shutdown = False
self._alive = False
def serve_forever(self):
self._alive = True
while not self._shutdown:
if self._shutdown:
break
self._alive = False
def shutdown(self):
self._shutdown = True
def is_alive(self):
return self._alive
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = DummyServer
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class,
handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
def test_start(self):
pass
def test_stop_started(self):
pass
def test_restart(self):
pass
def test_restart_stopped(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
| import unittest
import mock
from tikplay import server
class ServerTestcase(unittest.TestCase):
def setUp(self):
self.handler_class = mock.MagicMock()
self.server_class = mock.MagicMock()
self.server_class.serve_forever = mock.MagicMock()
self.__server = server.Server(host='127.0.0.1', port=4999,
server_class=self.server_class, handler_class=self.handler_class)
def tearDown(self):
self.handler_class.reset_mock()
self.server_class.reset_mock()
def test_start(self):
self.__server.start()
assert self.server_class.return_value.serve_forever.called
assert self.__server.server_thread.isAlive()
def test_stop_stopped(self):
assert not self.__server.server_thread.isAlive()
self.__server.stop()
assert not self.server_class.return_value.shutdown.called
def test_stop_started(self):
self.__server.start()
assert self.__server.server_thread.isAlive()
self.__server.stop()
assert self.server_class.return_value.shutdown.called
def test_restart(self):
pass
class HandlerTestcase(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
|
Fix for fixtures populator entity array | <?php
namespace Kunstmaan\FixturesBundle\Populator;
use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FixturesBundle\Populator\Methods\MethodInterface;
class Populator
{
/**
* @var MethodInterface[]
*/
private $populators;
public function __construct()
{
$this->populators = new ArrayCollection();
}
public function populate($entity, $data)
{
foreach ($data as $property => $value) {
foreach ($this->populators as $populator) {
if ($populator->canSet($entity, $property, $value)) {
if ($value instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
$populator->set($entity, $property, $value->getEntity());
} elseif(is_array($value)) {
foreach($value as &$item) {
if($item instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
$item = $item->getEntity();
}
}
$populator->set($entity, $property, $value);
} else {
$populator->set($entity, $property, $value);
}
break;
}
}
}
}
public function addPopulator(MethodInterface $populator, $alias)
{
$this->populators->set($alias, $populator);
return $this;
}
}
| <?php
namespace Kunstmaan\FixturesBundle\Populator;
use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FixturesBundle\Populator\Methods\MethodInterface;
class Populator
{
/**
* @var MethodInterface[]
*/
private $populators;
public function __construct()
{
$this->populators = new ArrayCollection();
}
public function populate($entity, $data)
{
foreach ($data as $property => $value) {
foreach ($this->populators as $populator) {
if ($populator->canSet($entity, $property, $value)) {
if ($value instanceof \Kunstmaan\FixturesBundle\Loader\Fixture) {
$populator->set($entity, $property, $value->getEntity());
} else {
$populator->set($entity, $property, $value);
}
break;
}
}
}
}
public function addPopulator(MethodInterface $populator, $alias)
{
$this->populators->set($alias, $populator);
return $this;
}
}
|
Fix organizer recap email title | <?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrganizerRecap extends Mailable
{
use Queueable, SerializesModels;
public $participants;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($participants)
{
$this->participants = $participants;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$csv = $this->formatCsv(array_map(function ($participant) {
return [
$participant['name'],
$participant['email']
];
}, $this->participants));
return $this->subject("Récapitulatif Organisateur")
->view('emails.organizer_recap')
->text('emails.organizer_recap_plain')
->attachData($csv, 'secretsanta.csv', [
'mime' => 'text/csv',
]);
}
protected function formatCsv($data, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $fields) {
if (fputcsv($f, $fields, $delimiter, $enclosure, $escape_char) === false) {
return false;
}
}
rewind($f);
$csv_line = stream_get_contents($f);
return rtrim($csv_line);
}
}
| <?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrganizerRecap extends Mailable
{
use Queueable, SerializesModels;
public $participants;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($participants)
{
$this->participants = $participants;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$csv = $this->formatCsv(array_map(function ($participant) {
return [
$participant['name'],
$participant['email']
];
}, $this->participants));
return $this->view('emails.organizer_recap')
->text('emails.organizer_recap_plain')
->attachData($csv, 'secretsanta.csv', [
'mime' => 'text/csv',
]);
}
protected function formatCsv($data, $delimiter = ",", $enclosure = '"', $escape_char = "\\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $fields) {
if (fputcsv($f, $fields, $delimiter, $enclosure, $escape_char) === false) {
return false;
}
}
rewind($f);
$csv_line = stream_get_contents($f);
return rtrim($csv_line);
}
}
|
Fix png for python 2/3 compatibility | from __future__ import absolute_import, print_function, division
from builtins import open
from future import standard_library
standard_library.install_aliases()
import six
import json, numpy as np, os, io
from .base import Property
from . import exceptions
class File(Property):
mode = 'r' #: mode for opening the file.
def validator(self, instance, value):
if hasattr(value, 'read'):
prev = getattr(self, '_p_' + self.name, None)
if prev is not None and value is not prev:
prev.close()
return value
if isinstance(value, six.string_types) and os.path.isfile(value):
return open(value, self.mode)
raise ValueError('The value for "%s" must be an open file or a string.'%self.name)
class Image(File):
def validator(self, instance, value):
import png
if getattr(value, '__valid__', False):
return value
if hasattr(value, 'read'):
png.Reader(value).validate_signature()
else:
with open(value, 'rb') as v:
png.Reader(v).validate_signature()
output = io.BytesIO()
output.name = 'texture.png'
output.__valid__ = True
if hasattr(value, 'read'):
fp = value
fp.seek(0)
else:
fp = open(value, 'rb')
output.write(fp.read())
output.seek(0)
fp.close()
return output
| from __future__ import absolute_import, unicode_literals, print_function, division
from builtins import open
from future import standard_library
standard_library.install_aliases()
import six
import json, numpy as np, os, io
from .base import Property
from . import exceptions
class File(Property):
mode = 'r' #: mode for opening the file.
def validator(self, instance, value):
if hasattr(value, 'read'):
prev = getattr(self, '_p_' + self.name, None)
if prev is not None and value is not prev:
prev.close()
return value
if isinstance(value, six.string_types) and os.path.isfile(value):
return open(value, self.mode)
raise ValueError('The value for "%s" must be an open file or a string.'%self.name)
class Image(File):
def validator(self, instance, value):
import png
if getattr(value, '__valid__', False):
return value
reader = png.Reader(value)
reader.validate_signature()
output = io.BytesIO()
output.name = 'texture.png'
output.__valid__ = True
if hasattr(value, 'read'):
fp = value
fp.seek(0)
else:
fp = open(value, 'rb')
output.write(fp.read())
output.seek(0)
fp.close()
return output
|
Fix test 2_get_file to use try with resources | package getFile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class GetFileImpl {
public static void writeInFile(String file, int i) {
String str = "New writter type INOUT";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
writer.write(str + " " + String.valueOf(i) + "\n");
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(-1);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
public static void readInFile(String filename) {
try (BufferedReader br = new BufferedReader(new FileReader(new File(filename)))) {
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(-1);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
| package getFile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class GetFileImpl {
public static void writeInFile(String file, int i) {
try {
String str = "New writter type INOUT";
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
writer.write(str + " " + String.valueOf(i) + "\n");
writer.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(-1);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
public static void readInFile(String filename) {
try {
File file = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
System.exit(-1);
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
|
Use `Windows.ApplicationModel.Package.current.id.name` instead of `.ProductId` as we get "permission denied" error when trying to retrieve productId
Unable to find any documentation on required permissions... | "use strict"
cordova.commandProxy.add("CsDeviceInfo", {
getAppId: function (successCb, failCb)
{
setTimeout(function () {
try {
successCb(Windows.ApplicationModel.Package.current.id.name)
} catch (e) {
failCb(e)
}
}, 0)
},
getVersionName: function (successCb, failCb)
{
setTimeout(function () {
try {
var version = Windows.ApplicationModel.Package.current.id.version
successCb(
"" +version.major
+"."+version.minor
+"."+version.build
+"."+version.revision
)
} catch (e) {
failCb(e)
}
}, 0)
},
isHackedDevice: function (successCb, failCb)
{
// Assume Windows devices are not "hacked"...
setTimeout(function () { successCb(false) }, 0)
},
})
| "use strict"
cordova.commandProxy.add("CsDeviceInfo", {
getAppId: function (successCb, failCb)
{
setTimeout(function () {
try {
successCb(Windows.ApplicationModel.Package.current.id.ProductId)
} catch (e) {
failCb(e)
}
}, 0)
},
getVersionName: function (successCb, failCb)
{
setTimeout(function () {
try {
var version = Windows.ApplicationModel.Package.current.id.version
successCb(
"" +version.major
+"."+version.minor
+"."+version.build
+"."+version.revision
)
} catch (e) {
failCb(e)
}
}, 0)
},
isHackedDevice: function (successCb, failCb)
{
// Assume Windows devices are not "hacked"...
setTimeout(function () { successCb(false) }, 0)
},
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.