text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix load failure if not logged in. | package com.gh4a.loader;
import java.io.IOException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class IsCollaboratorLoader extends BaseLoader<Boolean> {
private String mRepoOwner;
private String mRepoName;
public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
String login = app.getAuthLogin();
if (login == null) {
return false;
}
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, login);
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
// which in turn means he isn't a collaborator
return false;
}
throw e;
}
}
}
| package com.gh4a.loader;
import java.io.IOException;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;
import android.content.Context;
import com.gh4a.Gh4Application;
public class IsCollaboratorLoader extends BaseLoader<Boolean> {
private String mRepoOwner;
private String mRepoName;
public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
super(context);
mRepoOwner = repoOwner;
mRepoName = repoName;
}
@Override
public Boolean doLoadInBackground() throws IOException {
Gh4Application app = Gh4Application.get();
CollaboratorService collabService =
(CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
try {
RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
return collabService.isCollaborator(repoId, app.getAuthLogin());
} catch (RequestException e) {
if (e.getStatus() == 403) {
// the API returns 403 if the user doesn't have push access,
// which in turn means he isn't a collaborator
return false;
}
throw e;
}
}
}
|
Add process monitoring for LBaaS agents
Add neutron-lbaas-agent (LBaaS V1) and neutron-lbaasv2-agent (LBaaS
V2) to the neutron detection plugin. Because the string
"neutron-lbaas-agent" can be both a process name and log file name,
the process monitor is susceptible to false positive matching on that
string. Use a longer part of the python path to disambiguate this
Change-Id: I3081639a6f36a276bab2f9eb1b9b39a5bef452f1 | import monasca_setup.detection
class Neutron(monasca_setup.detection.ServicePlugin):
"""Detect Neutron daemons and setup configuration to monitor them.
"""
def __init__(self, template_dir, overwrite=True, args=None):
service_params = {
'args': args,
'template_dir': template_dir,
'overwrite': overwrite,
'service_name': 'networking',
'process_names': ['neutron-server', 'neutron-openvswitch-agent',
'neutron-rootwrap', 'neutron-dhcp-agent',
'neutron-vpn-agent', 'neutron-metadata-agent',
'neutron-metering-agent', 'neutron-l3-agent',
'neutron-ns-metadata-proxy',
'/opt/stack/service/neutron/venv/bin/neutron-lbaas-agent',
'/opt/stack/service/neutron/venv/bin/neutron-lbaasv2-agent'],
'service_api_url': 'http://localhost:9696',
'search_pattern': '.*v2.0.*'
}
super(Neutron, self).__init__(service_params)
def build_config(self):
"""Build the config as a Plugins object and return."""
# Skip the http check if neutron-server is not on this box
if 'neutron-server' not in self.found_processes:
self.service_api_url = None
self.search_pattern = None
return monasca_setup.detection.ServicePlugin.build_config(self)
| import monasca_setup.detection
class Neutron(monasca_setup.detection.ServicePlugin):
"""Detect Neutron daemons and setup configuration to monitor them.
"""
def __init__(self, template_dir, overwrite=True, args=None):
service_params = {
'args': args,
'template_dir': template_dir,
'overwrite': overwrite,
'service_name': 'networking',
'process_names': ['neutron-server', 'neutron-openvswitch-agent',
'neutron-rootwrap', 'neutron-dhcp-agent',
'neutron-vpn-agent', 'neutron-metadata-agent',
'neutron-metering-agent', 'neutron-l3-agent',
'neutron-ns-metadata-proxy'],
'service_api_url': 'http://localhost:9696',
'search_pattern': '.*v2.0.*'
}
super(Neutron, self).__init__(service_params)
def build_config(self):
"""Build the config as a Plugins object and return."""
# Skip the http check if neutron-server is not on this box
if 'neutron-server' not in self.found_processes:
self.service_api_url = None
self.search_pattern = None
return monasca_setup.detection.ServicePlugin.build_config(self)
|
Improve tests for multilingual json output | var path = require('path');
var _ = require('lodash');
var assert = require('assert');
var fs = require("fs");
var fsUtil = require("../lib/utils/fs");
var testGeneration = function(book, type, func, done) {
var OUTPUT_PATH = book.options.output;
qdone(
book.generate(type)
.then(function() {
func(OUTPUT_PATH);
})
.fin(function() {
return fsUtil.remove(OUTPUT_PATH);
}),
done);
};
describe('Book generation', function () {
it('should correctly generate a book to json', function(done) {
testGeneration(book1, "json", function(output) {
assert(!fs.existsSync(path.join(output, "README.json")));
assert(fs.existsSync(path.join(output, "intro.json")));
assert(fs.existsSync(path.join(output, "sub/test1.json")));
var test1 = JSON.parse(fs.readFileSync(path.join(output, "sub/test1.json")));
assert(test1.sections[0].content.indexOf("intro.html") > 0);
}, done);
});
it('should correctly generate a multilingual book to json', function(done) {
testGeneration(book2, "json", function(output) {
assert(fs.existsSync(path.join(output, "README.json")));
assert(fs.existsSync(path.join(output, "en/README.json")));
assert(fs.existsSync(path.join(output, "fr/README.json")));
}, done);
});
});
| var path = require('path');
var _ = require('lodash');
var assert = require('assert');
var fs = require("fs");
var fsUtil = require("../lib/utils/fs");
var testGeneration = function(book, type, func, done) {
var OUTPUT_PATH = book.options.output;
qdone(
book.generate(type)
.then(function() {
func(OUTPUT_PATH);
})
.fin(function() {
return fsUtil.remove(OUTPUT_PATH);
}),
done);
};
describe('Book generation', function () {
it('should correctly generate a book to json', function(done) {
testGeneration(book1, "json", function(output) {
assert(!fs.existsSync(path.join(output, "README.json")));
assert(fs.existsSync(path.join(output, "intro.json")));
assert(fs.existsSync(path.join(output, "sub/test1.json")));
var test1 = JSON.parse(fs.readFileSync(path.join(output, "sub/test1.json")));
assert(test1.sections[0].content.indexOf("intro.html") > 0);
}, done);
});
it('should correctly generate a multilingual book to json', function(done) {
testGeneration(book2, "json", function(output) {
}, done);
});
});
|
Make class final and mark it as thread-safe.
Future modification or additions to this class must take thread-safety
into consideration. | package alluxio.master.audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import javax.annotation.concurrent.ThreadSafe;
@ThreadSafe
public final class AsyncUserAccessAuditLogWriter {
private static final int QUEUE_SIZE = 100;
private static final Logger LOG = LoggerFactory.getLogger(AsyncUserAccessAuditLogWriter.class);
private boolean mEnabled;
private ArrayBlockingQueue<AuditContext> mAuditLogEntries;
public AsyncUserAccessAuditLogWriter() {
mEnabled = true;
mAuditLogEntries = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
public boolean isEnabled() { return mEnabled; }
public boolean append(AuditContext context) {
try {
mAuditLogEntries.put(context);
} catch (InterruptedException e) {
// Reset the interrupted flag and return because some other thread has
// told us not to wait any more.
Thread.currentThread().interrupt();
return false;
}
return true;
}
public void commit(AuditContext context) {
synchronized (context) {
context.setCommitted(true);
context.notify();
}
AuditContext headContext = mAuditLogEntries.poll();
if (headContext == null) { return; }
synchronized (headContext) {
while (!headContext.isCommitted()) {
try {
headContext.wait();
} catch (InterruptedException e) {
// TODO
return;
}
}
}
LOG.info(headContext.toString());
}
}
| package alluxio.master.audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
public class AsyncUserAccessAuditLogWriter {
private static final int QUEUE_SIZE = 100;
private static final Logger LOG = LoggerFactory.getLogger(AsyncUserAccessAuditLogWriter.class);
private boolean mEnabled;
private ArrayBlockingQueue<AuditContext> mAuditLogEntries;
public AsyncUserAccessAuditLogWriter() {
mEnabled = true;
mAuditLogEntries = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
public boolean isEnabled() { return mEnabled; }
public boolean append(AuditContext context) {
try {
mAuditLogEntries.put(context);
} catch (InterruptedException e) {
// Reset the interrupted flag and return because some other thread has
// told us not to wait any more.
Thread.currentThread().interrupt();
return false;
}
return true;
}
public void commit(AuditContext context) {
synchronized (context) {
context.setCommitted(true);
context.notify();
}
AuditContext headContext = mAuditLogEntries.poll();
if (headContext == null) { return; }
synchronized (headContext) {
while (!headContext.isCommitted()) {
try {
headContext.wait();
} catch (InterruptedException e) {
// TODO
return;
}
}
}
LOG.info(headContext.toString());
}
}
|
Add support for multiple datasets | angular.module('siyfion.sfTypeahead', [])
.directive('sfTypeahead', function () {
return {
restrict: 'ACE',
scope: {
datasets: '=',
ngModel: '='
},
link: function (scope, element) {
element.typeahead(scope.datasets);
// Updates the ngModel binding when a value is manually selected from the dropdown.
// ToDo: Think about how the value could be updated on user entry...
element.bind('typeahead:selected', function (object, datum, dataset) {
scope.$apply(function() {
scope.ngModel = datum;
scope.selectedDataset = dataset
});
});
// Updates the ngModel binding when a query is autocompleted.
element.bind('typeahead:autocompleted', function (object, datum) {
scope.$apply(function() {
scope.ngModel = datum;
});
});
// Updates typeahead when ngModel changed.
scope.$watch('ngModel', function (newVal) {
if ($.isArray(scope.datasets)) {
for (var i=0;i<scope.datasets.length;i++) {
if (scope.datasets[i].name == scope.selectedDataset) {
var valueKey = scope.datasets[i].valueKey;
break;
}
}
} else {
var valueKey = scope.datasets.valueKey;
}
if (newVal && valueKey && newVal.hasOwnProperty(valueKey)) {
newVal = newVal[valueKey];
}
element.typeahead('setQuery', newVal || '');
});
}
};
});
| angular.module('siyfion.sfTypeahead', [])
.directive('sfTypeahead', function () {
return {
restrict: 'ACE',
scope: {
datasets: '=',
ngModel: '='
},
link: function (scope, element) {
element.typeahead(scope.datasets);
// Updates the ngModel binding when a value is manually selected from the dropdown.
// ToDo: Think about how the value could be updated on user entry...
element.bind('typeahead:selected', function (object, datum) {
scope.$apply(function() {
scope.ngModel = datum;
});
});
// Updates the ngModel binding when a query is autocompleted.
element.bind('typeahead:autocompleted', function (object, datum) {
scope.$apply(function() {
scope.ngModel = datum;
});
});
// Updates typeahead when ngModel changed.
scope.$watch('ngModel', function (newVal) {
var valueKey = scope.datasets.valueKey;
if (newVal && valueKey && newVal.hasOwnProperty(valueKey)) {
newVal = newVal[valueKey];
}
element.typeahead('setQuery', newVal || '');
});
}
};
}); |
fix(rasterize-list): Update test to not hang on failed promise-dependant expecation | 'use strict';
const expect = require('../../helpers/expect');
const fs = require('fs');
const sizeOf = require('image-size');
const RasterizeList = require('../../../src/utils/rasterize-list');
describe('RasterizeList', function() {
// Hitting the file system is slow
this.timeout(0);
context('when src and toRasterize', () => {
const src = 'node-tests/fixtures/icon.svg';
const toRasterize = [
{
size: 60,
name: 'icon-60',
path: 'tmp/icon-60.png'
}
];
let subject;
before(() => {
subject = RasterizeList({src: src, toRasterize: toRasterize});
});
after(() => {
toRasterize.forEach((rasterize) => {
fs.unlinkSync(rasterize.path);
});
});
it('returns a promise that resolves to an array', (done) => {
expect(subject).to.eventually.be.a('array').notify(done);
});
it('writes the files to rasterize at the right size', (done) => {
subject.then(() => {
try {
toRasterize.forEach((rasterize) => {
expect(fs.existsSync(rasterize.path)).to.equal(true);
expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
expect(sizeOf(rasterize.path).height).to.equal(rasterize.size);
});
done();
} catch(e) {
done(e);
}
});
});
});
});
| 'use strict';
const expect = require('../../helpers/expect');
const fs = require('fs');
const sizeOf = require('image-size');
const RasterizeList = require('../../../src/utils/rasterize-list');
describe('RasterizeList', function() {
// Hitting the file system is slow
this.timeout(0);
context('when src and toRasterize', () => {
const src = 'node-tests/fixtures/icon.svg';
const toRasterize = [
{
size: 60,
name: 'icon-60',
path: 'tmp/icon-60.png'
}
];
let subject;
before(() => {
subject = RasterizeList({src: src, toRasterize: toRasterize});
});
after(() => {
toRasterize.forEach((rasterize) => {
fs.unlinkSync(rasterize.path);
});
});
it('returns a promise that resolves to an array', (done) => {
expect(subject).to.eventually.be.a('array').notify(done);
});
it('writes the files to rasterize at the right size', (done) => {
subject.then(() => {
toRasterize.forEach((rasterize) => {
expect(fs.existsSync(rasterize.path)).to.equal(true);
expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
expect(sizeOf(rasterize.path).height).to.equal(rasterize.size);
});
done();
});
});
});
});
|
Support file globbing for log processor since names could be dynamic (based on hostname, etc.). | import glob
import re
import snmpy
class log_processor(snmpy.plugin):
def create(self):
for k, v in sorted(self.conf['objects'].items()):
extra = {
'count': re.compile(v['count']),
'reset': re.compile(v['reset']) if 'reset' in v else None,
'start': int(v['start']) if 'start' in v else 0,
'rotate': bool(v['rotate']) if 'rotate' in v else False
}
self.data['1.%s' % k] = 'string', v['label']
self.data['2.%s' % k] = 'integer', extra['start'], extra
self.tail()
@snmpy.plugin.task
def tail(self):
for line in snmpy.plugin.tail(glob.glob(self.conf['file_name'])[0], True):
if line is True:
for item in self.data['2.0':]:
if self.data[item:'rotate'] and line is True:
self.data[item] = self.data[item:'start']
continue
for item in self.data['2.0':]:
count = self.data[item:'count'].search(line)
if count:
self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1)
break
if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line):
self.data[item] = self.data[item:'start']
break
| import re
import snmpy
class log_processor(snmpy.plugin):
def create(self):
for k, v in sorted(self.conf['objects'].items()):
extra = {
'count': re.compile(v['count']),
'reset': re.compile(v['reset']) if 'reset' in v else None,
'start': int(v['start']) if 'start' in v else 0,
'rotate': bool(v['rotate']) if 'rotate' in v else False
}
self.data['1.%s' % k] = 'string', v['label']
self.data['2.%s' % k] = 'integer', extra['start'], extra
self.tail()
@snmpy.plugin.task
def tail(self):
for line in snmpy.plugin.tail(self.conf['file_name'], True):
if line is True:
for item in self.data['2.0':]:
if self.data[item:'rotate'] and line is True:
self.data[item] = self.data[item:'start']
continue
for item in self.data['2.0':]:
count = self.data[item:'count'].search(line)
if count:
self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1)
break
if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line):
self.data[item] = self.data[item:'start']
break
|
Test Depth First Search: Remove console logs | /* eslint-env mocha */
const dfs = require('../../../src').algorithms.search.dfs;
const assert = require('assert');
describe('DFS', () => {
it('should perform dfs on a tree', () => {
const tree = {
root: {
name: 'root',
children: [{
name: 'child_1',
children: [{
name: 'child_4',
children: []
}, {
name: 'child_5',
children: []
}]
}, {
name: 'child_2',
children: [{
name: 'child_6',
children: []
}]
}, {
name: 'child_3',
children: [{
name: 'child_7',
children: []
}]
}]
}
};
const children = [];
dfs(tree.root, 'children', node => children.push(node.name));
assert.deepStrictEqual(
children, [
'root',
'child_3',
'child_7',
'child_2',
'child_6',
'child_1',
'child_5',
'child_4'
]
);
});
});
| /* eslint-env mocha */
const dfs = require('../../../src').algorithms.search.dfs;
const assert = require('assert');
describe('DFS', () => {
it('should perform dfs on a tree', () => {
const tree = {
root: {
name: 'root',
children: [{
name: 'child_1',
children: [{
name: 'child_4',
children: []
}, {
name: 'child_5',
children: []
}]
}, {
name: 'child_2',
children: [{
name: 'child_6',
children: []
}]
}, {
name: 'child_3',
children: [{
name: 'child_7',
children: []
}]
}]
}
};
const children = [];
dfs(tree.root, 'children', node => children.push(node.name));
console.log(children);
assert.deepStrictEqual(
children, [
'root',
'child_3',
'child_7',
'child_2',
'child_6',
'child_1',
'child_5',
'child_4'
]
);
});
});
|
Add example of new cache_time field for callback queries. | <?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Callback query command
*/
class CallbackqueryCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'callbackquery';
/**
* @var string
*/
protected $description = 'Reply to callback query';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$update = $this->getUpdate();
$callback_query = $update->getCallbackQuery();
$callback_query_id = $callback_query->getId();
$callback_data = $callback_query->getData();
$data = [
'callback_query_id' => $callback_query_id,
'text' => 'Hello World!',
'show_alert' => $callback_data === 'thumb up',
'cache_time' => 5,
];
return Request::answerCallbackQuery($data);
}
}
| <?php
/**
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Request;
/**
* Callback query command
*/
class CallbackqueryCommand extends SystemCommand
{
/**
* @var string
*/
protected $name = 'callbackquery';
/**
* @var string
*/
protected $description = 'Reply to callback query';
/**
* @var string
*/
protected $version = '1.1.0';
/**
* Command execute method
*
* @return mixed
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$update = $this->getUpdate();
$callback_query = $update->getCallbackQuery();
$callback_query_id = $callback_query->getId();
$callback_data = $callback_query->getData();
$data = [
'callback_query_id' => $callback_query_id,
'text' => 'Hello World!',
'show_alert' => $callback_data === 'thumb up',
];
return Request::answerCallbackQuery($data);
}
}
|
BAP-2667: Modify CLI installer to allow run common commands from Package Manager[ | <?php
namespace Oro\Bundle\InstallerBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Oro\Bundle\InstallerBundle\CommandExecutor;
class PlatformUpdateCommand extends ContainerAwareCommand
{
/**
* @inheritdoc
*/
protected function configure()
{
$this->setName('oro:platform:update')
->setDescription('Execute platform update commands.');
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$commandExecutor = new CommandExecutor(
$input->hasOption('env') ? $input->getOption('env') : null,
$output,
$this->getApplication()
);
$commandExecutor
->runCommand('oro:entity-config:update')
->runCommand('oro:entity-extend:update')
->runCommand('oro:navigation:init')
->runCommand('assets:install')
->runCommand('assetic:dump')
->runCommand('fos:js-routing:dump', array('--target' => 'web/js/routes.js'))
->runCommand('oro:localization:dump')
->runCommand('oro:translation:dump')
->runCommand('oro:requirejs:build');
}
}
| <?php
namespace Oro\Bundle\InstallerBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Oro\Bundle\InstallerBundle\CommandExecutor;
class PlatformUpdateCommand extends ContainerAwareCommand
{
/**
* @inheritdoc
*/
protected function configure()
{
$this->setName('oro:platform:update')
->setDescription('Execute platform update commands.');
}
/**
* @inheritdoc
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$commandExecutor = new CommandExecutor(
$input->hasOption('env') ? $input->getOption('env') : null,
$output,
$this->getApplication()
);
$commandExecutor
->runCommand('oro:entity-config:update')
->runCommand('oro:entity-extend:update')
->runCommand('oro:navigation:init')
->runCommand('assets:install')
->runCommand('assetic:dump')
->runCommand('fos:js-routing:dump', array('--target' => 'js/routes.js'))
->runCommand('oro:localization:dump')
->runCommand('oro:translation:dump')
->runCommand('oro:requirejs:build');
}
}
|
Fix small bug introduced in 0b8e5d428e60.
Opening file twice. | """
LWR HTTP Client layer based on Python Standard Library (urllib2)
"""
from __future__ import with_statement
from os.path import getsize
import mmap
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
try:
from urllib2 import Request
except ImportError:
from urllib.request import Request
class Urllib2Transport(object):
def _url_open(self, request, data):
return urlopen(request, data)
def execute(self, url, data=None, input_path=None, output_path=None):
request = Request(url=url, data=data)
input = None
try:
if input_path:
if getsize(input_path):
input = open(input_path, 'rb')
data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ)
else:
data = b""
response = self._url_open(request, data)
finally:
if input:
input.close()
if output_path:
with open(output_path, 'wb') as output:
while True:
buffer = response.read(1024)
if not buffer:
break
output.write(buffer)
return response
else:
return response.read()
| """
LWR HTTP Client layer based on Python Standard Library (urllib2)
"""
from __future__ import with_statement
from os.path import getsize
import mmap
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
try:
from urllib2 import Request
except ImportError:
from urllib.request import Request
class Urllib2Transport(object):
def _url_open(self, request, data):
return urlopen(request, data)
def execute(self, url, data=None, input_path=None, output_path=None):
request = Request(url=url, data=data)
input = None
try:
if input_path:
input = open(input_path, 'rb')
if getsize(input_path):
input = open(input_path, 'rb')
data = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ)
else:
data = b""
response = self._url_open(request, data)
finally:
if input:
input.close()
if output_path:
with open(output_path, 'wb') as output:
while True:
buffer = response.read(1024)
if not buffer:
break
output.write(buffer)
return response
else:
return response.read()
|
Change the way an expected set is instantated in a test | package org.tenidwa.collections.utils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.LinkedHashSet;
import org.junit.Assert;
import org.junit.Test;
public final class CollectorsTest {
@Test
public void toImmutableSet() {
Assert.assertEquals(
ImmutableSet.of(1, 2, 3),
Arrays.asList(1, 2, 3).stream()
.collect(Collectors.toImmutableSet())
);
}
@Test
public void toImmutableList() {
Assert.assertEquals(
ImmutableList.of(1, 2, 3),
Arrays.asList(1, 2, 3).stream()
.collect(Collectors.toImmutableList())
);
}
@Test
public void toLinkedHashSet() {
final LinkedHashSet<Integer> expected = new LinkedHashSet<>();
expected.add(1);
expected.add(2);
expected.add(3);
Assert.assertEquals(
expected,
Arrays.asList(1, 2, 3).stream()
.collect(Collectors.toLinkedHashSet())
);
}
}
| package org.tenidwa.collections.utils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.LinkedHashSet;
import org.junit.Assert;
import org.junit.Test;
public final class CollectorsTest {
@Test
public void toImmutableSet() {
Assert.assertEquals(
ImmutableSet.of(1, 2, 3),
Arrays.asList(1, 2, 3).stream()
.collect(Collectors.toImmutableSet())
);
}
@Test
public void toImmutableList() {
Assert.assertEquals(
ImmutableList.of(1, 2, 3),
Arrays.asList(1, 2, 3).stream()
.collect(Collectors.toImmutableList())
);
}
@Test
public void toLinkedHashSet() {
Assert.assertEquals(
new LinkedHashSet<Integer>() {
{
add(1);
add(2);
add(3);
}
},
Arrays.asList(1, 2, 3).stream()
.collect(Collectors.toLinkedHashSet())
);
}
}
|
Change constructor parameter types from DayTime to DateModifying - as this interface defines the only method we need to call. | package uk.ac.ebi.quickgo.rest.period;
import com.google.common.base.Preconditions;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;
import javax.validation.constraints.NotNull;
/**
* An implementation of a {@link Period} which uses two values for {@link DayTime} as start and end points to
* determine remaining time.
*
* @author Tony Wardell
* Date: 11/04/2017
* Time: 12:46
* Created with IntelliJ IDEA.
*/
public class ReducingDailyPeriod implements Period {
@NotNull
private final DateModifying start;
@NotNull
private final DateModifying end;
ReducingDailyPeriod(DateModifying start, DateModifying end) {
Preconditions.checkArgument(Objects.nonNull(start), "The ReducingDailyPeriod constructor start parameter " +
"must not be null.");
Preconditions.checkArgument(Objects.nonNull(end),"The ReducingDailyPeriod constructor end parameter " +
"must not be null.");
this.start = start;
this.end = end;
}
public Duration remainingTime(LocalDateTime target) {
LocalDateTime startDateTime = start.toInstant(target);
LocalDateTime endDateTime = end.toInstant(target);
Duration remaining;
if (target.isAfter(startDateTime) && target.isBefore(endDateTime)){
remaining = Duration.between(target, endDateTime);
}else{
remaining = Duration.ZERO;
}
return remaining;
}
}
| package uk.ac.ebi.quickgo.rest.period;
import com.google.common.base.Preconditions;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;
import javax.validation.constraints.NotNull;
/**
* An implementation of a {@link Period} which uses two values for {@link DayTime} as start and end points to
* determine remaining time.
*
* @author Tony Wardell
* Date: 11/04/2017
* Time: 12:46
* Created with IntelliJ IDEA.
*/
public class ReducingDailyPeriod implements Period {
@NotNull
private final DayTime start;
@NotNull
private final DayTime end;
ReducingDailyPeriod(DayTime start, DayTime end) {
Preconditions.checkArgument(Objects.nonNull(start), "The ReducingDailyPeriod constructor start parameter " +
"must not be null.");
Preconditions.checkArgument(Objects.nonNull(end),"The ReducingDailyPeriod constructor end parameter " +
"must not be null.");
this.start = start;
this.end = end;
}
public Duration remainingTime(LocalDateTime target) {
LocalDateTime startDateTime = start.toInstant(target);
LocalDateTime endDateTime = end.toInstant(target);
Duration remaining;
if (target.isAfter(startDateTime) && target.isBefore(endDateTime)){
remaining = Duration.between(target, endDateTime);
}else{
remaining = Duration.ZERO;
}
return remaining;
}
}
|
Fix typos: encoding, data -> self.encoding, self.data | #! /bin/env python
from landlab.io.vtk.writer import VtkWriter
from landlab.io.vtk.vtktypes import VtkUniformRectilinear
from landlab.io.vtk.vtkxml import (
VtkRootElement,
VtkGridElement,
VtkPieceElement,
VtkPointDataElement,
VtkCellDataElement,
VtkExtent,
VtkOrigin,
VtkSpacing,
)
class VtkUniformRectilinearWriter(VtkWriter):
_vtk_grid_type = VtkUniformRectilinear
def construct_field_elements(self, field):
extent = VtkExtent(field.shape[::-1])
origin = VtkOrigin(field.origin[::-1], field.spacing[::-1])
spacing = VtkSpacing(field.spacing[::-1])
element = {
'VTKFile':
VtkRootElement(VtkUniformRectilinear),
'Grid':
VtkGridElement(VtkUniformRectilinear, WholeExtent=extent,
Origin=origin, Spacing=spacing),
'Piece':
VtkPieceElement(Extent=extent),
'PointData':
VtkPointDataElement(field.at_node, append=self.data,
encoding=self.encoding),
'CellData':
VtkCellDataElement(field.at_cell, append=self.data,
encoding=self.encoding),
}
return element
| #! /bin/env python
from landlab.io.vtk.writer import VtkWriter
from landlab.io.vtk.vtktypes import VtkUniformRectilinear
from landlab.io.vtk.vtkxml import (
VtkRootElement,
VtkGridElement,
VtkPieceElement,
VtkPointDataElement,
VtkCellDataElement,
VtkExtent,
VtkOrigin,
VtkSpacing,
)
class VtkUniformRectilinearWriter(VtkWriter):
_vtk_grid_type = VtkUniformRectilinear
def construct_field_elements(self, field):
extent = VtkExtent(field.shape[::-1])
origin = VtkOrigin(field.origin[::-1], field.spacing[::-1])
spacing = VtkSpacing(field.spacing[::-1])
element = {
'VTKFile':
VtkRootElement(VtkUniformRectilinear),
'Grid':
VtkGridElement(VtkUniformRectilinear, WholeExtent=extent,
Origin=origin, Spacing=spacing),
'Piece':
VtkPieceElement(Extent=extent),
'PointData':
VtkPointDataElement(field.at_node, append=self.data,
encoding=self.encoding),
'CellData':
VtkCellDataElement(field.at_cell, append=data,
encoding=encoding),
}
return element
|
Add StackOverFlowData, not completed yet | """ Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
class StackOverFlowData:
params = {}
def get_answer_by_title(self, title):
pass
| """ Helper classes """
import facebook
import requests as r
class FacebookData:
def __init__(self, token):
"""
:param token: Facebook Page token
:param _api: Instance of the GraphAPI object
"""
self.token = token
self._api = facebook.GraphAPI(self.token)
def get_user_name(self, _id):
"""
:param _id: find user object by _id
:return: first name of user, type -> str
"""
if not isinstance(_id, str):
raise ValueError('id must be a str')
user = self._api.get_object(_id)
return user['first_name'] if user else None
class WeatherData:
"""
Class which collect weather data
"""
def __init__(self, api_token):
"""
:param api_token: Open Weather TOKEN
"""
self.token = api_token
def get_current_weather(self, city_name):
"""
:param city_name: Open weather API, find by city name
:return dictionary object with information
for example:
{'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky'}]}
"""
api_url = f'http://api.openweathermap.org' \
f'/data/2.5/weather?q={city_name}&APPID={self.token}'
info = r.get(api_url).json()
return info
|
Fix command line arguments order for gjslint
Closure Linter does not respect "--strict" flag
if it goes after files list. | /**
* common code goes here
*/
var grunt = require('grunt'),
exec = require('child_process').exec,
_ = grunt.util._;
module.exports.registerTool = function(task, toolname) {
var callback = task.async(),
files = [],
closureLinterPath = task.data.closureLinterPath,
options = grunt.task.current.options(
{
stdout : false,
stderr : false,
failOnError : true,
strict : false
});
// Iterate over all src-dest file pairs.
task.files.forEach(function(f) {
files = files.concat(grunt.file.expand(f.src));
});
//grunt.log.writeflags(options, 'options');
var cmd = closureLinterPath + '/' + toolname;
cmd += options.strict ? ' --strict ' : ' ';
cmd += files.join(' ');
//grunt.log.writeln(cmd);
var task = exec(cmd, options.execOptions, function(err, stdout, stderr) {
if (_.isFunction(options.callback)) {
options.callback.call(task, err, stdout, stderr, callback);
} else {
if (err && options.failOnError) {
grunt.warn(err);
}
callback();
}
});
if (options.stdout) {
task.stdout.pipe(process.stdout);
}
if (options.stderr) {
task.stderr.pipe(process.stderr);
}
}; | /**
* common code goes here
*/
var grunt = require('grunt'),
exec = require('child_process').exec,
_ = grunt.util._;
module.exports.registerTool = function(task, toolname) {
var callback = task.async(),
files = [],
closureLinterPath = task.data.closureLinterPath,
options = grunt.task.current.options(
{
stdout : false,
stderr : false,
failOnError : true,
strict : false
});
// Iterate over all src-dest file pairs.
task.files.forEach(function(f) {
files = files.concat(grunt.file.expand(f.src));
});
//grunt.log.writeflags(options, 'options');
var cmd = closureLinterPath + '/' + toolname + files.join(' ');
cmd += options.strict ? ' --strict' : '';
//grunt.log.writeln(cmd);
var task = exec(cmd, options.execOptions, function(err, stdout, stderr) {
if (_.isFunction(options.callback)) {
options.callback.call(task, err, stdout, stderr, callback);
} else {
if (err && options.failOnError) {
grunt.warn(err);
}
callback();
}
});
if (options.stdout) {
task.stdout.pipe(process.stdout);
}
if (options.stderr) {
task.stderr.pipe(process.stderr);
}
}; |
Refactor Gilda module and add function to get models | """This module implements a client to the Gilda grounding web service,
and contains functions to help apply it during the course of INDRA assembly."""
import requests
from .mapper import GroundingMapper
grounding_service_url = 'http://grounding.indra.bio'
def get_gilda_models():
"""Return a list of strings for which Gilda has a disambiguation model.
Returns
-------
list[str]
A list of entity strings.
"""
res = requests.post(grounding_service_url + '/models')
models = res.json()
return models
def ground_statement(stmt):
"""Set grounding for Agents in a given Statement using Gilda.
This function modifies the original Statement/Agents in place.
Parameters
----------
stmt : indra.statements.Statement
A Statement to ground
"""
if stmt.evidence and stmt.evidence[0].text:
context = stmt.evidence[0].text
else:
context = None
for agent in stmt.agent_list():
if agent is not None and 'TEXT' in agent.db_refs:
txt = agent.db_refs['TEXT']
resp = requests.post(grounding_service_url + '/ground',
json={'text': txt,
'context': context})
results = resp.json()
if results:
db_refs = {'TEXT': txt,
results[0]['term']['db']:
results[0]['term']['id']}
agent.db_refs = db_refs
GroundingMapper.standardize_agent_name(agent,
standardize_refs=True)
def ground_statements(stmts):
"""Set grounding for Agents in a list of Statements using Gilda.
This function modifies the original Statements/Agents in place.
Parameters
----------
stmts : list[indra.statements.Statement]
A list of Statements to ground
"""
for stmt in stmts:
ground_statement(stmt)
| """This module implements a client to the Gilda grounding web service,
and contains functions to help apply it during the course of INDRA assembly."""
import requests
from .mapper import GroundingMapper
grounding_service_url = 'http://grounding.indra.bio/ground'
def ground_statements(stmts):
"""Set grounding for Agents in a list of Statements using Gilda.
This function modifies the original Statements/Agents in place.
Parameters
----------
stmts : list[indra.statements.Statements]
A list of Statements to ground
"""
for stmt in stmts:
if stmt.evidence and stmt.evidence[0].text:
context = stmt.evidence[0].text
else:
context = None
for agent in stmt.agent_list():
if agent is not None and 'TEXT' in agent.db_refs:
txt = agent.db_refs['TEXT']
resp = requests.post(grounding_service_url,
json={'text': txt,
'context': context})
results = resp.json()
if results:
db_refs = {'TEXT': txt,
results[0]['term']['db']:
results[0]['term']['id']}
agent.db_refs = db_refs
GroundingMapper.standardize_agent_name(agent,
standardize_refs=True)
|
Fix for server root relative url | /**
* Created by SuhairZain on 12/5/16.
*/
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var PROD = JSON.parse(process.env.PROD_ENV || '0');
var plugins = [
new HtmlWebpackPlugin({
title: "URL to GDrive",
filename: '../index.html',
template: 'index-file-template.ejs'
})
];
if(PROD){
plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
})
);
plugins.push(
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
);
}
module.exports = {
entry: './src/main.jsx',
output: {
path: "./dist",
publicPath: './dist/',
filename: `bundle_${Date.now()}.js`
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['style', 'css']
}
]
},
plugins: plugins
}; | /**
* Created by SuhairZain on 12/5/16.
*/
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var PROD = JSON.parse(process.env.PROD_ENV || '0');
var plugins = [
new HtmlWebpackPlugin({
title: "URL to GDrive",
filename: '../index.html',
template: 'index-file-template.ejs'
})
];
if(PROD){
plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
})
);
plugins.push(
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
);
}
module.exports = {
entry: './src/main.jsx',
output: {
path: "./dist",
publicPath: '/dist/',
filename: `bundle_${Date.now()}.js`
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['style', 'css']
}
]
},
plugins: plugins
}; |
Fix for the sorted merge step
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@4014 5fb7f6ec-07c1-534a-b4ca-9155e429e800 | package org.pentaho.di.run.sortedmerge;
import junit.framework.TestCase;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;
public class RunSortedMerge extends TestCase
{
public void test_SORTED_MERGE_00()
{
System.out.println();
System.out.println("SORTED MERGE");
System.out.println("==================");
}
public void test_SORTED_MERGE_01_SIMPLE() throws Exception
{
TimedTransRunner timedTransRunner = new TimedTransRunner(
"test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
LogWriter.LOG_LEVEL_ERROR,
AllRunTests.getOldTargetDatabase(),
AllRunTests.getNewTargetDatabase(),
1000000
);
timedTransRunner.runOldAndNew();
be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
assertTrue(oldResult.getNrErrors()==0);
Result newResult = timedTransRunner.getNewResult();
assertTrue(newResult.getNrErrors()==0);
}
}
| package org.pentaho.di.run.sortedmerge;
import junit.framework.TestCase;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;
public class RunSortedMerge extends TestCase
{
public void test_SORTED_MERGE_00()
{
System.out.println();
System.out.println("SORTED MERGE");
System.out.println("==================");
}
public void test_SORTED_MERGE_01_SIMPLE() throws Exception
{
TimedTransRunner timedTransRunner = new TimedTransRunner(
"test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
LogWriter.LOG_LEVEL_ERROR,
AllRunTests.getOldTargetDatabase(),
AllRunTests.getNewTargetDatabase(),
1000
);
timedTransRunner.runOldAndNew();
be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
assertTrue(oldResult.getNrErrors()==0);
Result newResult = timedTransRunner.getNewResult();
assertTrue(newResult.getNrErrors()==0);
}
}
|
Allow preferred width or height to be overridden since it seems that
JScrollPane will happily return some insane value when it's wrapping an
empty JList.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2314 542714f4-19e9-0310-aa3c-eee0fc999fb1 | //
// $Id: SafeScrollPane.java,v 1.7 2003/03/22 01:56:09 mdb Exp $
package com.threerings.media;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
/**
* A scroll pane that is safe to use in frame managed views.
*/
public class SafeScrollPane extends JScrollPane
{
public SafeScrollPane ()
{
}
public SafeScrollPane (Component view)
{
super(view);
}
public SafeScrollPane (Component view, int owidth, int oheight)
{
super(view);
if (owidth != 0 || oheight != 0) {
_override = new Dimension(owidth, oheight);
}
}
// documentation inherited
public Dimension getPreferredSize ()
{
Dimension d = super.getPreferredSize();
if (_override != null) {
if (_override.width != 0) {
d.width = _override.width;
}
if (_override.height != 0) {
d.height = _override.height;
}
}
return d;
}
protected JViewport createViewport ()
{
JViewport vp = new JViewport() {
public void setViewPosition (Point p) {
super.setViewPosition(p);
// simple scroll mode results in setViewPosition causing
// our view to become invalid, but nothing ever happens to
// queue up a revalidate for said view, so we have to do
// it here
Component c = getView();
if (c instanceof JComponent) {
((JComponent)c).revalidate();
}
}
};
vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
return vp;
}
protected Dimension _override;
}
| //
// $Id: SafeScrollPane.java,v 1.6 2002/11/05 21:03:31 mdb Exp $
package com.threerings.media;
import java.awt.Component;
import java.awt.Point;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
/**
* A scroll pane that is safe to use in frame managed views.
*/
public class SafeScrollPane extends JScrollPane
{
public SafeScrollPane ()
{
}
public SafeScrollPane (Component view)
{
super(view);
}
protected JViewport createViewport ()
{
JViewport vp = new JViewport() {
public void setViewPosition (Point p) {
super.setViewPosition(p);
// simple scroll mode results in setViewPosition causing
// our view to become invalid, but nothing ever happens to
// queue up a revalidate for said view, so we have to do
// it here
Component c = getView();
if (c instanceof JComponent) {
((JComponent)c).revalidate();
}
}
};
vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
return vp;
}
}
|
Fix path to "util.js" in test | const util = require('../../lib/util');
describe("Continuous delivery", function() {
describe("utils", function() {
describe("makeStringArray", function() {
it('works when list is a string', function() {
const result = util.makeStringArray('gugus');
expect(result).toEqual(['gugus']);
});
it('works when list is an array', function() {
const result = util.makeStringArray(['first', 'second']);
expect(result).toEqual(['first', 'second']);
});
it('works when list is empty', function() {
const result = util.makeStringArray(undefined);
expect(result).toEqual([]);
});
it('throws when list is weird', function() {
expect(() => util.makeStringArray({}))
.toThrowError('expected list to be a string or an array but got object');
});
it('throws when list has weird element', function() {
expect(() => util.makeStringArray([{}]))
.toThrowError('expected list element to be a string but got object');
});
});
describe('unique', function() {
it('removes duplicated strings only', function() {
expect(util.unique(['a', 'b', 'c', 'd', 'b', 'a', 'd', 'd']))
.toEqual(['a', 'b', 'c', 'd']);
});
});
});
});
| const util = require('../../lib/continuous-delivery/util');
describe("Continuous delivery", function() {
describe("utils", function() {
describe("makeStringArray", function() {
it('works when list is a string', function() {
const result = util.makeStringArray('gugus');
expect(result).toEqual(['gugus']);
});
it('works when list is an array', function() {
const result = util.makeStringArray(['first', 'second']);
expect(result).toEqual(['first', 'second']);
});
it('works when list is empty', function() {
const result = util.makeStringArray(undefined);
expect(result).toEqual([]);
});
it('throws when list is weird', function() {
expect(() => util.makeStringArray({}))
.toThrowError('expected list to be a string or an array but got object');
});
it('throws when list has weird element', function() {
expect(() => util.makeStringArray([{}]))
.toThrowError('expected list element to be a string but got object');
});
});
describe('unique', function() {
it('removes duplicated strings only', function() {
expect(util.unique(['a', 'b', 'c', 'd', 'b', 'a', 'd', 'd']))
.toEqual(['a', 'b', 'c', 'd']);
});
});
});
});
|
Remove unused interface from repository | <?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
// this is an autogenerated file - do not edit
spl_autoload_register(
function($class) {
static $classes = null;
if ($classes === null) {
$classes = array(
'theseer\\fdom\\fdomdocument' => '/src/fDOMDocument.php',
'theseer\\fdom\\fdomdocumentfragment' => '/src/fDOMDocumentFragment.php',
'theseer\\fdom\\fdomelement' => '/src/fDOMElement.php',
'theseer\\fdom\\fdomexception' => '/src/fDOMException.php',
'theseer\\fdom\\fdomnode' => '/src/fDOMNode.php',
'theseer\\fdom\\fdomxpath' => '/src/fDOMXPath.php',
'theseer\\fdom\\xpathquery' => '/src/XPathQuery.php',
'theseer\\fdom\\xpathqueryexception' => '/src/XPathQueryException.php'
);
}
$cn = strtolower($class);
if (isset($classes[$cn])) {
require __DIR__ . $classes[$cn];
}
}
);
// @codeCoverageIgnoreEnd | <?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
// this is an autogenerated file - do not edit
spl_autoload_register(
function($class) {
static $classes = null;
if ($classes === null) {
$classes = array(
'theseer\\fdom\\fdomdocument' => '/src/fDOMDocument.php',
'theseer\\fdom\\fdomdocumentfragment' => '/src/fDOMDocumentFragment.php',
'theseer\\fdom\\fdomelement' => '/src/fDOMElement.php',
'theseer\\fdom\\fdomexception' => '/src/fDOMException.php',
'theseer\\fdom\\fdomnode' => '/src/fDOMNode.php',
'theseer\\fdom\\fdomnodeinterface' => '/src/fDOMNodeInterface.php',
'theseer\\fdom\\fdomxpath' => '/src/fDOMXPath.php',
'theseer\\fdom\\xpathquery' => '/src/XPathQuery.php',
'theseer\\fdom\\xpathqueryexception' => '/src/XPathQueryException.php'
);
}
$cn = strtolower($class);
if (isset($classes[$cn])) {
require __DIR__ . $classes[$cn];
}
}
);
// @codeCoverageIgnoreEnd |
Make user ids v1 UUIDs | var uuid = require('node-uuid');
var util = require('./util');
var bcrypt = require('bcryptjs');
module.exports = function(username, password, callback) {
if (util.isEmpty(username) || util.isEmpty(password)) return callback(new Error('Username and password required'));
this.db.get(this.prefix + this.usernameToIdPrefix + username, function (error) {
if (!error) return callback(new Error('Username not available'));
if (error && !error.message.match(/Key\ not\ found/)) return callback(error);
var id = uuid.v1();
var token = uuid.v4();
bcrypt.hash(password, 8, function(error, hash) {
if (error) return callback(error);
password = hash;
this.db.batch()
.put(this.prefix + this.idToUsernamePrefix + id, username)
.put(this.prefix + this.usernameToIdPrefix + username, id)
.put(this.prefix + this.tokenToIdPrefix + token, id)
.put(this.prefix + this.idToPasswordPrefix + id, password)
.write(function(error) {
if (error) return callback(error);
callback(null, {
username: username,
id: id,
token: token
});
});
}.bind(this));
}.bind(this));
};
| var uuid = require('node-uuid');
var util = require('./util');
var bcrypt = require('bcryptjs');
module.exports = function(username, password, callback) {
if (util.isEmpty(username) || util.isEmpty(password)) return callback(new Error('Username and password required'));
this.db.get(this.prefix + this.usernameToIdPrefix + username, function (error) {
if (!error) return callback(new Error('Username not available'));
if (error && !error.message.match(/Key\ not\ found/)) return callback(error);
var id = uuid.v4();
var token = uuid.v4();
bcrypt.hash(password, 8, function(error, hash) {
if (error) return callback(error);
password = hash;
this.db.batch()
.put(this.prefix + this.idToUsernamePrefix + id, username)
.put(this.prefix + this.usernameToIdPrefix + username, id)
.put(this.prefix + this.tokenToIdPrefix + token, id)
.put(this.prefix + this.idToPasswordPrefix + id, password)
.write(function(error) {
if (error) return callback(error);
callback(null, {
username: username,
id: id,
token: token
});
});
}.bind(this));
}.bind(this));
};
|
Update resize script for new image size | <?php
require_once '../includes/master.inc.php';
$cnt = 0;
$mydir = dir('../media');
while (($file = $mydir->read()) !== false && $cnt < 200) {
if ($file != "." && $file != "..") {
if (strpos($file, '_thumbnail') !== false || strpos($file, '_mid') !== false || strpos($file, '_medlg') !== false) {
//do nothing
} else {
//read in full size and thumbnail to 224x224
$info = pathinfo($file);
$file_name = basename($file, '.' . $info['extension']); //file name with no extention
$file_ext = $info['extension']; //outputs the file extension
$full = "../media/" . $file_name . '.' . $file_ext;
$file_ext = strtolower($file_ext);
$filethumb = "../media/" . $file_name . "_thumbnail" . "." . $file_ext;
list($width, $height) = getimagesize($filethumb);
if ($width != 210 && $height != 210) {
$gd = new GD($full);
$gd->resize(210, 210);
$gd->saveAs($filethumb, $file_ext, 100);
$cnt++;
echo "Resized: $cnt" . '<br>';
}
else {
//echo 'Already Done<br>';
}
}
}
}
$mydir->close();
?>
| <?php
require_once '../includes/master.inc.php';
$cnt = 0;
$mydir = dir('../media');
while (($file = $mydir->read()) !== false && $cnt < 60) {
if ($file != "." && $file != "..") {
if (strpos($file, '_thumbnail') !== false || strpos($file, '_mid') !== false || strpos($file, '_medlg') !== false) {
//do nothing
} else {
//read in full size and thumbnail to 224x224
$info = pathinfo($file);
$file_name = basename($file, '.' . $info['extension']); //file name with no extention
$file_ext = $info['extension']; //outputs the file extension
$full = "../media/" . $file_name . '.' . $file_ext;
$file_ext = strtolower($file_ext);
$filethumb = "../media/" . $file_name . "_thumbnail" . "." . $file_ext;
list($width, $height) = getimagesize($filethumb);
if ($width != 210 && $height != 210) {
$gd = new GD($full);
$gd->resize(210, 210);
$gd->saveAs($filethumb, $file_ext, 100);
$cnt++;
echo "Resized: $cnt" . '<br>';
}
else {
//echo 'Already Done<br>';
}
}
}
}
$mydir->close();
?>
|
Remove the use of `__DIR__` constant. | <?php
namespace SerendipityHQ\Bundle\QueuesBundle;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use SerendipityHQ\Bundle\QueuesBundle\DependencyInjection\CompilerPass\DaemonDependenciesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\VarDumper\VarDumper;
/**
* {@inheritdoc}
*/
class QueuesBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function build(ContainerBuilder $container)
{
parent::build($container);
$modelDir = $this->getPath() . '/Resources/config/doctrine/mappings';
$mappings = [
$modelDir => 'SerendipityHQ\Bundle\QueuesBundle\Model',
];
$ormCompilerClass = DoctrineOrmMappingsPass::class;
if (class_exists($ormCompilerClass)) {
$container->addCompilerPass(
$this->getYamlMappingDriver($mappings)
);
}
$container->addCompilerPass(new DaemonDependenciesPass());
}
/**
* @param array $mappings
*
* @return DoctrineOrmMappingsPass
*/
private function getYamlMappingDriver(array $mappings)
{
return DoctrineOrmMappingsPass::createYamlMappingDriver(
$mappings,
['queues.model_manager_name'],
'queues.backend_orm',
['QueuesBundle' => 'SerendipityHQ\Bundle\QueuesBundle\Model']
);
}
}
| <?php
namespace SerendipityHQ\Bundle\QueuesBundle;
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use SerendipityHQ\Bundle\QueuesBundle\DependencyInjection\CompilerPass\DaemonDependenciesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* {@inheritdoc}
*/
class QueuesBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function build(ContainerBuilder $container)
{
parent::build($container);
$modelDir = realpath(__DIR__ . '/Resources/config/doctrine/mappings');
$mappings = [
$modelDir => 'SerendipityHQ\Bundle\QueuesBundle\Model',
];
$ormCompilerClass = DoctrineOrmMappingsPass::class;
if (class_exists($ormCompilerClass)) {
$container->addCompilerPass(
$this->getYamlMappingDriver($mappings)
);
}
$container->addCompilerPass(new DaemonDependenciesPass());
}
/**
* @param array $mappings
*
* @return DoctrineOrmMappingsPass
*/
private function getYamlMappingDriver(array $mappings)
{
return DoctrineOrmMappingsPass::createYamlMappingDriver(
$mappings,
['queues.model_manager_name'],
'queues.backend_orm',
['QueuesBundle' => 'SerendipityHQ\Bundle\QueuesBundle\Model']
);
}
}
|
Fix running unit tests on Windows | <?php declare(strict_types=1);
namespace Tests\Unit\Translator\Framework;
use PHPUnit\Framework\TestCase;
class HelperTest extends TestCase
{
/** @var string */
private $testDir;
protected function setUp(): void
{
$this->testDir = realpath(__DIR__.'/../..') ?? '';
}
public function testGlobRecursive(): void
{
$fixturesDir = realpath("{$this->testDir}/Fixtures/Glob");
$files = glob_recursive("{$fixturesDir}/*.txt", GLOB_BRACE);
$this->assertEquals([
'/Fixtures/Glob/file1.txt',
'/Fixtures/Glob/file2.txt',
'/Fixtures/Glob/SubDir/SubDirFile1.txt',
'/Fixtures/Glob/SubDir/SubDirFile2.txt',
'/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt',
'/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt',
], $this->replaceDirectorySeparators($this->removeRelativePath($files)));
}
/**
* @param string[] $files
* @return string[]
*/
private function removeRelativePath(array $files): array
{
return array_map(function (string $file): string {
return str_replace($this->testDir, '', $file);
}, $files);
}
/**
* @param string[] $files
* @return string[]
*/
private function replaceDirectorySeparators(array $files): array
{
return array_map(function (string $file): string {
return str_replace('\\', '/', $file);
}, $files);
}
}
| <?php declare(strict_types=1);
namespace Tests\Unit\Translator\Framework;
use PHPUnit\Framework\TestCase;
class HelperTest extends TestCase
{
/** @var string */
private $testDir;
protected function setUp(): void
{
$this->testDir = realpath(__DIR__.'/../..') ?? '';
}
public function testGlobRecursive(): void
{
$fixturesDir = realpath("{$this->testDir}/Fixtures/Glob");
$files = glob_recursive("{$fixturesDir}/*.txt", GLOB_BRACE);
$this->assertEquals([
'/Fixtures/Glob/file1.txt',
'/Fixtures/Glob/file2.txt',
'/Fixtures/Glob/SubDir/SubDirFile1.txt',
'/Fixtures/Glob/SubDir/SubDirFile2.txt',
'/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt',
'/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt',
], $this->removeRelativePath($files));
}
/**
* @param string[] $files
* @return string[]
*/
private function removeRelativePath(array $files): array
{
return array_map(function (string $file): string {
return str_replace($this->testDir, '', $file);
}, $files);
}
}
|
Fix Call to undefined method DOMNodeList::getElementsByTagName() | <?php
namespace Omnipay\SecureTrading\Message;
use DOMDocument;
/**
* ThreeDSecure Request
*
* @method ThreeDSecureResponse send()
*/
class ThreeDSecureRequest extends AbstractPurchaseRequest
{
/**
* @return string
*/
public function getAction()
{
return 'THREEDQUERY';
}
/**
* @return DOMDocument
*/
public function getData()
{
$data = parent::getData();
$this->validate('returnUrl');
/** @var DOMDocument $request */
$request = $data->getElementsByTagName('request')->item(0);
/** @var DOMDocument $merchant */
$merchant = $data->getElementsByTagName('merchant')->item(0);
$merchant->appendChild($data->createElement('termurl', $this->getReturnUrl()));
/** @var DOMDocument $customer */
$customer = $request->getElementsByTagName('customer')->item(0) ?: $request->appendChild($data->createElement('customer'));
$customer->appendChild($data->createElement('accept', $this->getAccept()));
$customer->appendChild($data->createElement('useragent', $this->getUserAgent()));
return $data;
}
/**
* @param string $data
* @return Response
*/
protected function createResponse($data)
{
return $this->response = new ThreeDSecureResponse($this, $data);
}
}
| <?php
namespace Omnipay\SecureTrading\Message;
use DOMDocument;
/**
* ThreeDSecure Request
*
* @method ThreeDSecureResponse send()
*/
class ThreeDSecureRequest extends AbstractPurchaseRequest
{
/**
* @return string
*/
public function getAction()
{
return 'THREEDQUERY';
}
/**
* @return DOMDocument
*/
public function getData()
{
$data = parent::getData();
$this->validate('returnUrl');
/** @var DOMDocument $request */
$request = $data->getElementsByTagName('request');
/** @var DOMDocument $merchant */
$merchant = $data->getElementsByTagName('merchant')->item(0);
$merchant->appendChild($data->createElement('termurl', $this->getReturnUrl()));
/** @var DOMDocument $customer */
$customer = $request->getElementsByTagName('customer')->item(0) ?: $request->appendChild($data->createElement('customer'));
$customer->appendChild($data->createElement('accept', $this->getAccept()));
$customer->appendChild($data->createElement('useragent', $this->getUserAgent()));
return $data;
}
/**
* @param string $data
* @return Response
*/
protected function createResponse($data)
{
return $this->response = new ThreeDSecureResponse($this, $data);
}
}
|
Revert "dont pass bdajax. get it from window"
This reverts commit 05393ce7c10b99eca03f1c8fb5c8f1a3abcc32b1. | /* jslint browser: true */
/* global jQuery, bdajax */
(function($, bdajax) {
"use strict";
$(document).ready(function() {
var binder = function(context) {
$('div.availability', context).unbind('mouseover')
.bind('mouseover', function() {
var details = $('div.availability_details',
$(this));
if (!details.is(":visible")) {
details.show();
}
});
$('div.availability', context).unbind('mouseout')
.bind('mouseout', function() {
var details = $('div.availability_details',
$(this));
if (details.is(":visible")) {
details.hide();
}
});
};
if (typeof(window.bdajax) !== "undefined") {
$.extend(bdajax.binders, {
buyable_controls_binder: binder
});
}
binder(document);
});
})(jQuery, bdajax);
| /* jslint browser: true */
/* global jQuery */
(function($) {
"use strict";
$(document).ready(function() {
var binder = function(context) {
$('div.availability', context).unbind('mouseover')
.bind('mouseover', function() {
var details = $('div.availability_details',
$(this));
if (!details.is(":visible")) {
details.show();
}
});
$('div.availability', context).unbind('mouseout')
.bind('mouseout', function() {
var details = $('div.availability_details',
$(this));
if (details.is(":visible")) {
details.hide();
}
});
};
if (typeof(window.bdajax) !== "undefined") {
$.extend(window.bdajax.binders, {
buyable_controls_binder: binder
});
}
binder(document);
});
})(jQuery);
|
Update Raft web site link |
"use strict";
/*jslint browser: true, nomen: true*/
/*global define*/
define([], function () {
return function (frame) {
var player = frame.player(),
layout = frame.layout();
frame.after(1, function() {
frame.model().clear();
layout.invalidate();
})
.after(500, function () {
frame.model().title = '<h1 style="visibility:visible">The End</h1>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
.after(500, function () {
frame.model().controls.show();
})
.after(500, function () {
frame.model().title = '<h2 style="visibility:visible">For more information:</h2>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/raft.pdf">The Raft Paper</a></h3>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/">Raft Web Site</a></h3>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
player.play();
};
});
|
"use strict";
/*jslint browser: true, nomen: true*/
/*global define*/
define([], function () {
return function (frame) {
var player = frame.player(),
layout = frame.layout();
frame.after(1, function() {
frame.model().clear();
layout.invalidate();
})
.after(500, function () {
frame.model().title = '<h1 style="visibility:visible">The End</h1>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
.after(500, function () {
frame.model().controls.show();
})
.after(500, function () {
frame.model().title = '<h2 style="visibility:visible">For more information:</h2>'
+ '<h3 style="visibility:visible"><a href="https://raft.github.io/raft.pdf">The Raft Paper</a></h3>'
+ '<h3 style="visibility:visible"><a href="http://raftconsensus.github.io/">Raft Web Site</a></h3>'
+ '<br/>' + frame.model().controls.html();
layout.invalidate();
})
player.play();
};
});
|
Remove application ID header from example.
This is no longer required, so no need to present it in the admin panel. | @extends('layout.master')
@section('main_content')
@include('layout.header', ['header' => 'API Keys', 'subtitle' => 'Northstar application access & permissions'])
<div class="container -padded">
<div class="wrapper">
<div class="container__block">
<h1>{{ $key->app_id }}</h1>
</div>
<div class="container__block">
<h4>Credentials:</h4>
<pre>X-DS-REST-API-Key: {{ $key->api_key }}</pre>
<p class="footnote">Send this header with any requests to use this API key.</p>
</div>
<div class="container__block">
<h4>Scopes</h4>
<ul class="list -compacted">
@foreach($key->scope as $scope)
<li>{{ $scope }}</li>
@endforeach
</ul>
</div>
<div class="container__block">
<ul class="form-actions -inline">
<li><a class="button -secondary" href="{{ route('keys.edit', [ $key->api_key]) }}">Edit Key</a></li>
<li>
<form action="{{ route('keys.destroy', $key->api_key) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button class="button -secondary -danger">Delete Key</button>
</form>
</li>
</ul>
</div>
</div>
</div>
@stop
| @extends('layout.master')
@section('main_content')
@include('layout.header', ['header' => 'API Keys', 'subtitle' => 'Northstar application access & permissions'])
<div class="container -padded">
<div class="wrapper">
<div class="container__block">
<h1>{{ $key->app_id }}</h1>
</div>
<div class="container__block">
<h4>Credentials:</h4>
<!-- Strange indentation due to `<pre>` tag respecting all whitespace. -->
<pre> X-DS-Application-Id: {{ $key->app_id }}
X-DS-REST-API-Key: {{ $key->api_key }}</pre>
</div>
<div class="container__block">
<h4>Scopes</h4>
<ul class="list -compacted">
@foreach($key->scope as $scope)
<li>{{ $scope }}</li>
@endforeach
</ul>
</div>
<div class="container__block">
<ul class="form-actions -inline">
<li><a class="button -secondary" href="{{ route('keys.edit', [ $key->api_key]) }}">Edit Key</a></li>
<li>
<form action="{{ route('keys.destroy', $key->api_key) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button class="button -secondary -danger">Delete Key</button>
</form>
</li>
</ul>
</div>
</div>
</div>
@stop
|
Add uuid to remote shell node name.
With this change it's possible to attach several remote shells to the
same cluster. Previously there would be a name conflict.
Change-Id: Ic85f99c8a7c27a80b37ecad994c39557934c7f50
Reviewed-on: http://review.couchbase.org/12365
Tested-by: Aliaksey Artamonau <[email protected]>
Reviewed-by: Aliaksey Kandratsenka <[email protected]> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides info about a particular server.
"""
from usage import usage
import restclient
import simplejson
import subprocess
import sys
from uuid import uuid1
class Info:
def __init__(self):
self.debug = False
def runCmd(self, cmd, server, port,
user, password, opts):
for (o, a) in opts:
if o == '-d' or o == '--debug':
self.debug = True
rest = restclient.RestClient(server, port, {'debug':self.debug})
opts = {'error_msg': 'server-info error'}
data = rest.restCmd('GET', '/nodes/self',
user, password, opts)
json = rest.getJson(data)
for x in ['license', 'licenseValid', 'licenseValidUntil']:
if x in json:
del(json[x])
if cmd == 'server-eshell':
name = 'ctl-%s' % str(uuid1())
p = subprocess.call(['erl','-name',name,
'-setcookie',json['otpCookie'],'-hidden','-remsh',json['otpNode']])
else:
print simplejson.dumps(json, sort_keys=True, indent=2)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides info about a particular server.
"""
from usage import usage
import restclient
import simplejson
import subprocess
import sys
class Info:
def __init__(self):
self.debug = False
def runCmd(self, cmd, server, port,
user, password, opts):
for (o, a) in opts:
if o == '-d' or o == '--debug':
self.debug = True
rest = restclient.RestClient(server, port, {'debug':self.debug})
opts = {'error_msg': 'server-info error'}
data = rest.restCmd('GET', '/nodes/self',
user, password, opts)
json = rest.getJson(data)
for x in ['license', 'licenseValid', 'licenseValidUntil']:
if x in json:
del(json[x])
if cmd == 'server-eshell':
p = subprocess.call(['erl','-name','[email protected]',
'-setcookie',json['otpCookie'],'-hidden','-remsh',json['otpNode']])
else:
print simplejson.dumps(json, sort_keys=True, indent=2)
|
Fix issue where bundle was happening before compile finished | var tsproject = require('tsproject');
var gulp = require('gulp');
var rjs = require('requirejs');
gulp.task('compile', function () {
return tsproject.src('./').pipe(gulp.dest('./'));
});
gulp.task('bundle', [ 'compile' ], function () {
return rjs.optimize({
appDir: 'built/debug',
baseUrl: './',
dir: 'built/min',
paths: {
'VSS': 'empty:',
'q': 'empty:',
'jQuery': 'empty:',
'TFS': 'empty:'
},
modules: [
{
name: 'Calendar/Extension'
},
{
name: 'Calendar/Dialogs'
},
{
name: 'Calendar/EventSources/FreeFormEventsSource'
},
{
name: 'Calendar/EventSources/VSOCapacityEventSource'
},
{
name: 'Calendar/EventSources/VSOIterationEventSource'
},
],
});
});
gulp.task('build', ['bundle']); | var tsproject = require('tsproject');
var gulp = require('gulp');
var rjs = require('requirejs');
gulp.task('compile', function () {
tsproject.src('./')
.pipe(gulp.dest('./'));
});
gulp.task('bundle', function () {
rjs.optimize({
appDir: 'built/debug',
baseUrl: './',
dir: 'built/min',
paths: {
'VSS': 'empty:',
'q': 'empty:',
'jQuery': 'empty:',
'TFS': 'empty:'
},
modules: [
{
name: 'Calendar/Extension'
},
{
name: 'Calendar/Dialogs'
},
{
name: 'Calendar/EventSources/FreeFormEventsSource'
},
{
name: 'Calendar/EventSources/VSOCapacityEventSource'
},
{
name: 'Calendar/EventSources/VSOIterationEventSource'
},
],
});
});
gulp.task('build', [
'compile',
'bundle'
]); |
Add tests for sending messages to emails without account. | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCase):
def test_sending_a_order_related_messages(self):
email = '[email protected]'
user = User.objects.create_user('testuser', email,
'somesimplepassword')
order_number = '12345'
order = create_order(number=order_number, user=user)
et = CommunicationEventType.objects.create(code="ORDER_PLACED",
name="Order Placed",
category="Order related")
messages = et.get_messages({
'order': order,
'lines': order.lines.all()
})
self.assertIn(order_number, messages['body'])
self.assertIn(order_number, messages['html'])
dispatcher = Dispatcher()
dispatcher.dispatch_order_messages(order, messages, et)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn(order_number, message.body)
# test sending messages to emails without account and text body
messages.pop('body')
dispatcher.dispatch_direct_messages(email, messages)
self.assertEqual(len(mail.outbox), 2)
| from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCase):
def test_sending_a_order_related_messages(self):
email = '[email protected]'
user = User.objects.create_user('testuser', email,
'somesimplepassword')
order_number = '12345'
order = create_order(number=order_number, user=user)
et = CommunicationEventType.objects.create(code="ORDER_PLACED",
name="Order Placed",
category="Order related")
messages = et.get_messages({
'order': order,
'lines': order.lines.all()
})
self.assertIn(order_number, messages['body'])
self.assertIn(order_number, messages['html'])
dispatcher = Dispatcher()
dispatcher.dispatch_order_messages(order, messages, et)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn(order_number, message.body)
|
Return this object in setName. | <?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var \Doctrine\Common\Collections\Collection|UserGroup[]
*
* @ORM\ManyToMany(targetEntity="UserGroup")
* @ORM\JoinTable(
* name="user_user_group",
* joinColumns={
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="user_group_id", referencedColumnName="id")
* }
* )
*/
protected $groups;
/**
* @var string
*
* @ORM\Column(type="string")
*/
private $name;
public function __construct()
{
parent::__construct();
$this->groups = new ArrayCollection();
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}
| <?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
/**
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var \Doctrine\Common\Collections\Collection|UserGroup[]
*
* @ORM\ManyToMany(targetEntity="UserGroup")
* @ORM\JoinTable(
* name="user_user_group",
* joinColumns={
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="user_group_id", referencedColumnName="id")
* }
* )
*/
protected $groups;
/**
* @var string
*
* @ORM\Column(type="string")
*/
private $name;
public function __construct()
{
parent::__construct();
$this->groups = new ArrayCollection();
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
}
|
Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1 | from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2>=2.10.1,<3',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
| from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2==2.10',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
|
Add a method for line by line asset parsing | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self, file=None, *args, **argv):
self.fh = None
if file:
self.name = file
self.fh = open(file, 'r')
self.eof = False
def __iter__(self):
return self
def len(self):
"""
Returns the length of the asset
"""
for i, l in enumerate(self.fh):
pass
# rewind the file
self.fh.seek(0)
return i + 1
def parse_line(self, line):
"""
Override this method if you need line
by line parsing of an Asset.
"""
return line.replace('\n','')
def next_asset(self):
"""
Return the next asset.
"""
# XXX this is really written with my feet.
# clean me up please...
line = self.fh.readline()
if line:
parsed_line = self.parse_line(line)
if parsed_line:
return parsed_line
else:
self.fh.seek(0)
raise StopIteration
def next(self):
try:
return self.next_asset()
except:
raise StopIteration
| class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self, file=None, *args, **argv):
self.fh = None
if file:
self.name = file
self.fh = open(file, 'r')
self.eof = False
def __iter__(self):
return self
def len(self):
"""
Returns the length of the asset
"""
for i, l in enumerate(self.fh):
pass
# rewind the file
self.fh.seek(0)
return i + 1
def next_asset(self):
"""
Return the next asset.
"""
# XXX this is really written with my feet.
# clean me up please...
line = self.fh.readline()
if line:
return line.replace('\n','')
else:
self.fh.seek(0)
raise StopIteration
def next(self):
try:
return self.next_asset()
except:
raise StopIteration
|
Add conference name as fallback for subject | /* @flow */
import React, { Component } from 'react';
import { getConferenceName } from '../../../base/conference/functions';
import { connect } from '../../../base/redux';
import { isToolboxVisible } from '../../../toolbox';
import ParticipantsCount from './ParticipantsCount';
/**
* The type of the React {@code Component} props of {@link Subject}.
*/
type Props = {
/**
* The subject or the of the conference.
* Falls back to conference name.
*/
_subject: string,
/**
* Indicates whether the component should be visible or not.
*/
_visible: boolean
};
/**
* Subject react component.
*
* @class Subject
*/
class Subject extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { _subject, _visible } = this.props;
return (
<div className = { `subject ${_visible ? 'visible' : ''}` }>
<span className = 'subject-text'>{ _subject }</span>
<ParticipantsCount />
</div>
);
}
}
/**
* Maps (parts of) the Redux state to the associated
* {@code Subject}'s props.
*
* @param {Object} state - The Redux state.
* @private
* @returns {{
* _subject: string,
* _visible: boolean
* }}
*/
function _mapStateToProps(state) {
return {
_subject: getConferenceName(state),
_visible: isToolboxVisible(state)
};
}
export default connect(_mapStateToProps)(Subject);
| /* @flow */
import React, { Component } from 'react';
import { connect } from '../../../base/redux';
import { isToolboxVisible } from '../../../toolbox';
import ParticipantsCount from './ParticipantsCount';
/**
* The type of the React {@code Component} props of {@link Subject}.
*/
type Props = {
/**
* The subject of the conference.
*/
_subject: string,
/**
* Indicates whether the component should be visible or not.
*/
_visible: boolean
};
/**
* Subject react component.
*
* @class Subject
*/
class Subject extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { _subject, _visible } = this.props;
return (
<div className = { `subject ${_visible ? 'visible' : ''}` }>
<span className = 'subject-text'>{ _subject }</span>
<ParticipantsCount />
</div>
);
}
}
/**
* Maps (parts of) the Redux state to the associated
* {@code Subject}'s props.
*
* @param {Object} state - The Redux state.
* @private
* @returns {{
* _subject: string,
* _visible: boolean
* }}
*/
function _mapStateToProps(state) {
const { subject } = state['features/base/conference'];
return {
_subject: subject,
_visible: isToolboxVisible(state)
};
}
export default connect(_mapStateToProps)(Subject);
|
Add gettype() PHP Function to Twig Extension | <?php
namespace Umpirsky\Twig\Extension;
use Twig_Extension;
use Twig_SimpleFunction;
use BadFunctionCallException;
class PhpFunctionExtension extends Twig_Extension
{
private $functions = array(
'uniqid',
'floor',
'ceil',
'addslashes',
'chr',
'chunk_split',
'convert_uudecode',
'crc32',
'crypt',
'hex2bin',
'md5',
'sha1',
'strpos',
'strrpos',
'ucwords',
'wordwrap',
'gettype',
);
public function __construct(array $functions = array())
{
if ($functions) {
$this->allowFunctions($functions);
}
}
public function getFunctions()
{
$twigFunctions = array();
foreach ($this->functions as $function) {
$twigFunctions[] = new Twig_SimpleFunction($function, $function);
}
return $twigFunctions;
}
public function allowFunction($function)
{
$this->functions[] = $function;
}
public function allowFunctions(array $functions)
{
$this->functions = $functions;
}
public function getName()
{
return 'php_function';
}
}
| <?php
namespace Umpirsky\Twig\Extension;
use Twig_Extension;
use Twig_SimpleFunction;
use BadFunctionCallException;
class PhpFunctionExtension extends Twig_Extension
{
private $functions = array(
'uniqid',
'floor',
'ceil',
'addslashes',
'chr',
'chunk_split',
'convert_uudecode',
'crc32',
'crypt',
'hex2bin',
'md5',
'sha1',
'strpos',
'strrpos',
'ucwords',
'wordwrap',
);
public function __construct(array $functions = array())
{
if ($functions) {
$this->allowFunctions($functions);
}
}
public function getFunctions()
{
$twigFunctions = array();
foreach ($this->functions as $function) {
$twigFunctions[] = new Twig_SimpleFunction($function, $function);
}
return $twigFunctions;
}
public function allowFunction($function)
{
$this->functions[] = $function;
}
public function allowFunctions(array $functions)
{
$this->functions = $functions;
}
public function getName()
{
return 'php_function';
}
}
|
Stop logging the MDB object |
require(['ByteSource', 'AppleVolume'], function(ByteSource, AppleVolume) {
'use strict';
function makeFileDrop(el, callback) {
if (typeof el === 'string') {
el = document.getElementById(el);
if (!el) {
console.error('filedrop element not found');
return;
}
el.addEventListener('dragenter', function(e) {
el.classList.add('dropping');
});
el.addEventListener('dragleave', function(e) {
el.classList.remove('dropping');
});
el.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
el.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
el.classList.remove('dropping');
if (e.dataTransfer.files[0]) {
callback(e.dataTransfer.files[0]);
}
});
el.classList.add('drop-target');
}
}
makeFileDrop('drop-zone', function(droppedFile) {
if (/\.(iso|toast|dsk|img)$/i.test(droppedFile.name)) {
var byteSource = ByteSource.from(droppedFile);
var appleVolume = new AppleVolume(byteSource);
appleVolume.read({});
}
else {
console.log(droppedFile.name);
}
});
});
|
require(['ByteSource', 'AppleVolume'], function(ByteSource, AppleVolume) {
'use strict';
function makeFileDrop(el, callback) {
if (typeof el === 'string') {
el = document.getElementById(el);
if (!el) {
console.error('filedrop element not found');
return;
}
el.addEventListener('dragenter', function(e) {
el.classList.add('dropping');
});
el.addEventListener('dragleave', function(e) {
el.classList.remove('dropping');
});
el.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
el.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
el.classList.remove('dropping');
if (e.dataTransfer.files[0]) {
callback(e.dataTransfer.files[0]);
}
});
el.classList.add('drop-target');
}
}
makeFileDrop('drop-zone', function(droppedFile) {
if (/\.(iso|toast|dsk|img)$/i.test(droppedFile.name)) {
var byteSource = ByteSource.from(droppedFile);
var appleVolume = new AppleVolume(byteSource);
appleVolume.read({
onvolumestart: function(masterDirectoryBlock) {
console.log(masterDirectoryBlock);
}
});
}
else {
console.log(droppedFile.name);
}
});
});
|
Allow data aggregate contents to be traversable | <?php
/*
* This file is part of Transfer.
*
* For the full copyright and license information, please view the LICENSE file located
* in the root directory.
*/
namespace Transfer\Adapter\Transaction;
/**
* Holds data for transaction objects.
*/
class DataAggregate implements \IteratorAggregate
{
/**
* @var \Iterator Data iterator
*/
protected $iterator;
/**
* @param array|\Iterator|\Traversable $data Data array or iterator
*/
public function __construct($data)
{
$this->setData($data);
}
/**
* Returns iterator with associated data.
*
* If the data aggregate was initialized with an array, an \ArrayIterator will be returned.
*
* @return \Iterator Data iterator
*/
public function getData()
{
return $this->iterator;
}
/**
* Assigns data to the aggregate.
*
* @param array|\Iterator $object
*/
public function setData($object)
{
if ($object instanceof \Iterator) {
$this->iterator = $object;
} elseif (is_array($object)) {
$this->iterator = new \ArrayIterator($object);
} else {
throw new \InvalidArgumentException(sprintf(
'Expecting object of type array or \Iterator, %s given',
gettype($object)
));
}
}
/**
* @see self::getData()
*/
public function getIterator()
{
return $this->iterator;
}
}
| <?php
/*
* This file is part of Transfer.
*
* For the full copyright and license information, please view the LICENSE file located
* in the root directory.
*/
namespace Transfer\Adapter\Transaction;
/**
* Holds data for transaction objects.
*/
class DataAggregate implements \IteratorAggregate
{
/**
* @var \Iterator Data iterator
*/
protected $iterator;
/**
* @param array|\Iterator $data Data array or iterator
*/
public function __construct($data)
{
$this->setData($data);
}
/**
* Returns iterator with associated data.
*
* If the data aggregate was initialized with an array, an \ArrayIterator will be returned.
*
* @return \Iterator Data iterator
*/
public function getData()
{
return $this->iterator;
}
/**
* Assigns data to the aggregate.
*
* @param array|\Iterator $object
*/
public function setData($object)
{
if ($object instanceof \Iterator) {
$this->iterator = $object;
} elseif (is_array($object)) {
$this->iterator = new \ArrayIterator($object);
} else {
throw new \InvalidArgumentException(sprintf(
'Expecting object of type array or \Iterator, %s given',
gettype($object)
));
}
}
/**
* @see self::getData()
*/
public function getIterator()
{
return $this->iterator;
}
}
|
Remove useless ACME tab from UI. | 'use strict';
var angular = require('angular');
var traefikCoreProvider = 'traefik.core.provider';
module.exports = traefikCoreProvider;
angular
.module(traefikCoreProvider, ['ngResource'])
.factory('Providers', Providers);
/** @ngInject */
function Providers($resource, $q) {
const resourceProvider = $resource('../api/providers');
return {
get: function () {
return $q((resolve, reject) => {
resourceProvider.get()
.$promise
.then((rawProviders) => {
delete rawProviders.acme;
delete rawProviders.ACME;
for (let providerName in rawProviders) {
if (rawProviders.hasOwnProperty(providerName)) {
if (!providerName.startsWith('$')) {
// BackEnds mapping
let bckends = rawProviders[providerName].backends || {};
rawProviders[providerName].backends = Object.keys(bckends)
.map(key => {
const goodBackend = bckends[key];
goodBackend.backendId = key;
return goodBackend;
});
// FrontEnds mapping
let frtends = rawProviders[providerName].frontends || {};
rawProviders[providerName].frontends = Object.keys(frtends)
.map(key => {
const goodFrontend = frtends[key];
goodFrontend.frontendId = key;
return goodFrontend;
});
}
}
}
resolve(rawProviders);
})
.catch(reject);
});
}
};
}
| 'use strict';
var angular = require('angular');
var traefikCoreProvider = 'traefik.core.provider';
module.exports = traefikCoreProvider;
angular
.module(traefikCoreProvider, ['ngResource'])
.factory('Providers', Providers);
/** @ngInject */
function Providers($resource, $q) {
const resourceProvider = $resource('../api/providers');
return {
get: function () {
return $q((resolve, reject) => {
resourceProvider.get()
.$promise
.then((rawProviders) => {
for (let providerName in rawProviders) {
if (rawProviders.hasOwnProperty(providerName)) {
if (!providerName.startsWith('$')) {
// BackEnds mapping
let bckends = rawProviders[providerName].backends || {};
rawProviders[providerName].backends = Object.keys(bckends)
.map(key => {
const goodBackend = bckends[key];
goodBackend.backendId = key;
return goodBackend;
});
// FrontEnds mapping
let frtends = rawProviders[providerName].frontends || {};
rawProviders[providerName].frontends = Object.keys(frtends)
.map(key => {
const goodFrontend = frtends[key];
goodFrontend.frontendId = key;
return goodFrontend;
});
}
}
}
resolve(rawProviders);
})
.catch(reject);
});
}
};
}
|
Add parameter to Route::model() to force default behavior of using id
This is useful, if you generally want to bind with a slug (web interface)
but sometimes (e.g. API) want to use id. | <?php namespace Felixkiss\SlugRoutes;
use Illuminate\Routing\Router;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SlugRouter extends Router
{
public function model($key, $class, Closure $callback = null, $forceId = false)
{
return $this->bind($key, function($value) use ($class, $callback, $forceId)
{
if (is_null($value)) return null;
// For model binders, we will attempt to retrieve the model using the find
// method on the model instance. If we cannot retrieve the models we'll
// throw a not found exception otherwise we will return the instance.
$model = new $class;
if($forceId === false && $model instanceof SluggableInterface)
{
$model = $model->where($model->getSlugIdentifier(), $value)->first();
}
else
{
$model = $model->find($value);
}
if ( ! is_null($model))
{
return $model;
}
// If a callback was supplied to the method we will call that to determine
// what we should do when the model is not found. This just gives these
// developer a little greater flexibility to decide what will happen.
if ($callback instanceof Closure)
{
return call_user_func($callback);
}
throw new NotFoundHttpException;
});
}
} | <?php namespace Felixkiss\SlugRoutes;
use Illuminate\Routing\Router;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SlugRouter extends Router
{
public function model($key, $class, Closure $callback = null)
{
return $this->bind($key, function($value) use ($class, $callback)
{
if (is_null($value)) return null;
// For model binders, we will attempt to retrieve the model using the find
// method on the model instance. If we cannot retrieve the models we'll
// throw a not found exception otherwise we will return the instance.
$model = new $class;
if($model instanceof SluggableInterface)
{
$model = $model->where($model->getSlugIdentifier(), $value)->first();
}
else
{
$model = $model->find($value);
}
if ( ! is_null($model))
{
return $model;
}
// If a callback was supplied to the method we will call that to determine
// what we should do when the model is not found. This just gives these
// developer a little greater flexibility to decide what will happen.
if ($callback instanceof Closure)
{
return call_user_func($callback);
}
throw new NotFoundHttpException;
});
}
} |
Add code test for test_remove function | from devicehive import NetworkError
from devicehive import ApiResponseError
def test_save(test):
def handle_connect(handler):
name = test.generate_id('n-s')
description = '%s-description' % name
network = handler.api.create_network(name, description)
name = test.generate_id('n-s')
description = '%s-description' % name
network.name = name
network.description = description
network.save()
network_1 = handler.api.get_network(network.id)
network.remove()
try:
network.save()
assert False
except NetworkError:
pass
try:
network_1.save()
assert False
except ApiResponseError as api_response_error:
# TODO: uncomment after server response will be fixed.
# assert api_response_error.code == 404
pass
test.run(handle_connect)
def test_remove(test):
def handle_connect(handler):
name = test.generate_id('n-r')
description = '%s-description' % name
network = handler.api.create_network(name, description)
network_1 = handler.api.get_network(network.id)
network.remove()
assert not network.id
assert not network.name
assert not network.description
try:
network.remove()
assert False
except NetworkError:
pass
try:
network_1.remove()
assert False
except ApiResponseError as api_response_error:
assert api_response_error.code == 404
test.run(handle_connect)
| from devicehive import NetworkError
from devicehive import ApiResponseError
def test_save(test):
def handle_connect(handler):
name = test.generate_id('n-s')
description = '%s-description' % name
network = handler.api.create_network(name, description)
name = test.generate_id('n-s')
description = '%s-description' % name
network.name = name
network.description = description
network.save()
network_1 = handler.api.get_network(network.id)
network.remove()
try:
network.save()
assert False
except NetworkError:
pass
try:
network_1.save()
assert False
except ApiResponseError as api_response_error:
# TODO: uncomment after server response will be fixed.
# assert api_response_error.code == 404
pass
test.run(handle_connect)
def test_remove(test):
def handle_connect(handler):
name = test.generate_id('n-r')
description = '%s-description' % name
network = handler.api.create_network(name, description)
network_1 = handler.api.get_network(network.id)
network.remove()
assert not network.id
assert not network.name
assert not network.description
try:
network.remove()
assert False
except NetworkError:
pass
try:
network_1.remove()
assert False
except ApiResponseError as api_response_error:
# TODO: uncomment after server response will be fixed.
# assert api_response_error.code == 404
pass
test.run(handle_connect)
|
l10n_br_nfse: Update python lib erpbrasil.assinatura version 1.4.0 | # Copyright 2019 KMEE INFORMATICA LTDA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "NFS-e",
"summary": """
NFS-e""",
"version": "14.0.1.7.0",
"license": "AGPL-3",
"author": "KMEE, Odoo Community Association (OCA)",
"maintainers": ["gabrielcardoso21", "mileo", "luismalta", "marcelsavegnago"],
"website": "https://github.com/OCA/l10n-brazil",
"external_dependencies": {
"python": [
"erpbrasil.edoc",
"erpbrasil.assinatura",
"erpbrasil.transmissao",
"erpbrasil.base",
],
},
"depends": [
"l10n_br_fiscal",
],
"data": [
"security/ir.model.access.csv",
"views/document_view.xml",
"views/product_template_view.xml",
"views/product_product_view.xml",
"views/document_line_view.xml",
"views/res_company_view.xml",
"report/danfse.xml",
],
"demo": [
"demo/product_demo.xml",
"demo/fiscal_document_demo.xml",
],
}
| # Copyright 2019 KMEE INFORMATICA LTDA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "NFS-e",
"summary": """
NFS-e""",
"version": "14.0.1.7.0",
"license": "AGPL-3",
"author": "KMEE, Odoo Community Association (OCA)",
"maintainers": ["gabrielcardoso21", "mileo", "luismalta", "marcelsavegnago"],
"website": "https://github.com/OCA/l10n-brazil",
"external_dependencies": {
"python": [
"erpbrasil.edoc",
"erpbrasil.assinatura-nopyopenssl",
"erpbrasil.transmissao",
"erpbrasil.base",
],
},
"depends": [
"l10n_br_fiscal",
],
"data": [
"security/ir.model.access.csv",
"views/document_view.xml",
"views/product_template_view.xml",
"views/product_product_view.xml",
"views/document_line_view.xml",
"views/res_company_view.xml",
"report/danfse.xml",
],
"demo": [
"demo/product_demo.xml",
"demo/fiscal_document_demo.xml",
],
}
|
Update query configuration and source name | const ZoomdataSDK = require('zoomdata-client/distribute/sdk/zoomdata-client.node');
async function run() {
const application = {
secure: true,
host: 'developer.zoomdata.com',
port: 443,
path: '/zoomdata-2.6'
};
const credentials = {
key: 'KVKWiD8kUl'
};
const client = await ZoomdataSDK.createClient({ application, credentials });
console.log('Client ready');
const queryConfig = {
filters: [],
groups: [{
name: 'gender',
limit: 10,
sort: { dir: 'asc', name: 'gender' }
}],
metrics: [
{ name: 'satisfaction', func: 'sum' }
]
};
try {
const data = await fetchData(client, 'My IMPALA Source', queryConfig);
console.log('Received data:', data);
} finally {
client.close();
}
}
async function fetchData(client, name, queryConfig) {
const query = await client.createQuery({ name }, queryConfig);
console.log('Query created');
return new Promise((resolve, reject) => {
console.log('Running query...');
client.runQuery(query, resolve, reject);
});
}
run().catch(console.error);
| const ZoomdataSDK = require('zoomdata-client/distribute/sdk/zoomdata-client.node');
async function run() {
const application = {
secure: true,
host: 'developer.zoomdata.com',
port: 443,
path: '/zoomdata-2.6'
};
const credentials = {
key: 'KVKWiD8kUl'
};
const client = await ZoomdataSDK.createClient({ application, credentials });
console.log('Client ready');
const queryConfig = {
filters: [],
groups: [{
name: 'position',
limit: 10,
sort: { dir: 'asc', name: 'position' }
}],
metrics: [
{ name: 'satisfaction', func: 'sum' }
]
};
try {
const data = await fetchData(client, 'Impala', queryConfig);
console.log('Received data:', data);
} finally {
client.close();
}
}
async function fetchData(client, name, queryConfig) {
const query = await client.createQuery({ name }, queryConfig);
console.log('Query created');
return new Promise((resolve, reject) => {
console.log('Running query...');
client.runQuery(query, resolve, reject);
});
}
run().catch(console.error);
|
Add a shortcut to toggle debug mode. | import React from 'react';
import Invocation from './invocation';
import StatusLine from './status_line';
export default React.createClass({
getInitialState() {
return {vcsData: {
isRepository: true,
branch: 'name',
status: 'clean'
}};
},
componentWillMount() {
this.props.terminal
.on('invocation', this.forceUpdate.bind(this))
.on('vcs-data', (data) => { this.setState({vcsData: data}) });
},
handleKeyDown(event) {
// Ctrl+L.
if (event.ctrlKey && event.keyCode === 76) {
this.props.terminal.clearInvocations();
event.stopPropagation();
event.preventDefault();
}
// Cmd+D.
if (event.metaKey && event.keyCode === 68) {
window.DEBUG = !window.DEBUG;
event.stopPropagation();
event.preventDefault();
this.forceUpdate();
console.log(`Debugging mode has been ${window.DEBUG ? 'enabled' : 'disabled'}.`);
}
},
render() {
var invocations = this.props.terminal.invocations.map((invocation) => {
return (
<Invocation key={invocation.id} invocation={invocation}/>
)
});
return (
<div id="board" onKeyDown={this.handleKeyDown}>
<div id="invocations">
{invocations}
</div>
<StatusLine currentWorkingDirectory={this.props.terminal.currentDirectory}
vcsData={this.state.vcsData}/>
</div>
);
}
});
| import React from 'react';
import Invocation from './invocation';
import StatusLine from './status_line';
export default React.createClass({
getInitialState() {
return {vcsData: {
isRepository: true,
branch: 'name',
status: 'clean'
}};
},
componentWillMount() {
this.props.terminal
.on('invocation', this.forceUpdate.bind(this))
.on('vcs-data', (data) => { this.setState({vcsData: data}) });
},
handleKeyDown(event) {
// Ctrl+l
if (event.ctrlKey && event.keyCode === 76) {
this.props.terminal.clearInvocations();
event.stopPropagation();
event.preventDefault();
}
},
render() {
var invocations = this.props.terminal.invocations.map((invocation) => {
return (
<Invocation key={invocation.id} invocation={invocation}/>
)
});
return (
<div id="board" onKeyDown={this.handleKeyDown}>
<div id="invocations">
{invocations}
</div>
<StatusLine currentWorkingDirectory={this.props.terminal.currentDirectory}
vcsData={this.state.vcsData}/>
</div>
);
}
});
|
Fix normalize signature for sf 4.4
https://github.com/symfony/serializer/blob/4.4/Normalizer/AbstractObjectNormalizer.php | <?php
/**
* Created by PhpStorm.
* User: evaisse
* Date: 05/05/15
* Time: 15:38
*/
namespace evaisse\SimpleHttpBundle\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
class CustomGetSetNormalizer extends GetSetMethodNormalizer
{
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
if ($object instanceof \Throwable) {
return $this->normalizeThrowable($object);
}
return parent::normalize($object, $format, $context);
}
/**
* @param \Throwable $e throwable to normalize
* @return array normalized output
*/
protected function normalizeThrowable(\Throwable $e)
{
$data = array(
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile().':'.$e->getLine(),
'trace' => $e->getTraceAsString(),
);
if ($previous = $e->getPrevious()) {
$data['previous'] = $this->normalizeThrowable($previous);
}
return $data;
}
}
| <?php
/**
* Created by PhpStorm.
* User: evaisse
* Date: 05/05/15
* Time: 15:38
*/
namespace evaisse\SimpleHttpBundle\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
class CustomGetSetNormalizer extends GetSetMethodNormalizer
{
/**
* {@inheritdoc}
*/
public function normalize($object, string $format = null, array $context = array())
{
if ($object instanceof \Throwable) {
return $this->normalizeThrowable($object);
}
return parent::normalize($object, $format, $context);
}
/**
* @param \Throwable $e throwable to normalize
* @return array normalized output
*/
protected function normalizeThrowable(\Throwable $e)
{
$data = array(
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile().':'.$e->getLine(),
'trace' => $e->getTraceAsString(),
);
if ($previous = $e->getPrevious()) {
$data['previous'] = $this->normalizeThrowable($previous);
}
return $data;
}
} |
Adjust generic name validation to better check tag values
e.g. "name=Fast Food" should match "amenity=fast_food" | import { t } from '../util/locale';
import { discardNames } from '../../node_modules/name-suggestion-index/config/filters.json';
export function validationGenericName() {
function isGenericName(entity) {
var name = entity.tags.name;
if (!name) return false;
var i, re;
// test if the name is just the tag value (e.g. "park")
var keys = ['amenity', 'leisure', 'shop', 'man_made', 'tourism'];
for (i = 0; i < keys.length; i++) {
var val = entity.tags[keys[i]];
if (val && val.replace(/\_/g, ' ').toLowerCase() === name.toLowerCase()) {
return name;
}
}
// test if the name is a generic name (e.g. "pizzaria")
for (i = 0; i < discardNames.length; i++) {
re = new RegExp(discardNames[i], 'i');
if (re.test(name)) {
return name;
}
}
return false;
}
return function validation(changes) {
var warnings = [];
for (var i = 0; i < changes.created.length; i++) {
var change = changes.created[i];
var generic = isGenericName(change);
if (generic) {
warnings.push({
id: 'generic_name',
message: t('validations.generic_name'),
tooltip: t('validations.generic_name_tooltip', { name: generic }),
entity: change
});
}
}
return warnings;
};
}
| import { t } from '../util/locale';
import { discardNames } from '../../node_modules/name-suggestion-index/config/filters.json';
export function validationGenericName() {
function isGenericName(entity) {
var name = entity.tags.name;
if (!name) return false;
if (entity.tags.amenity === name ||
entity.tags.leisure === name ||
entity.tags.shop === name ||
entity.tags.man_made === name ||
entity.tags.tourism === name) {
return name;
}
for (var i = 0; i < discardNames.length; i++) {
var re = new RegExp(discardNames[i], 'i');
if (re.test(name)) {
return name;
}
}
return false;
}
return function validation(changes) {
var warnings = [];
for (var i = 0; i < changes.created.length; i++) {
var change = changes.created[i];
var generic = isGenericName(change);
if (generic) {
warnings.push({
id: 'generic_name',
message: t('validations.generic_name'),
tooltip: t('validations.generic_name_tooltip', { name: generic }),
entity: change
});
}
}
return warnings;
};
}
|
Check that params can be null | package com.github.arteam.simplejsonrpc.core.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Date: 07.06.14
* Time: 12:24
* <p>Representation of a JSON-RPC request</p>
*/
public class Request {
@Nullable
private final String jsonrpc;
@Nullable
private final String method;
@Nullable
private final JsonNode params;
@Nullable
private final ValueNode id;
public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc,
@JsonProperty("method") @Nullable String method,
@JsonProperty("params") @Nullable JsonNode params,
@JsonProperty("id") @Nullable ValueNode id) {
this.jsonrpc = jsonrpc;
this.method = method;
this.id = id;
this.params = params;
}
@Nullable
public String getJsonrpc() {
return jsonrpc;
}
@Nullable
public String getMethod() {
return method;
}
@NotNull
public ValueNode getId() {
return id != null ? id : NullNode.getInstance();
}
@NotNull
public JsonNode getParams() {
return params != null ? params : NullNode.getInstance();
}
@Override
public String toString() {
return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}";
}
}
| package com.github.arteam.simplejsonrpc.core.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Date: 07.06.14
* Time: 12:24
* <p>Representation of a JSON-RPC request</p>
*/
public class Request {
@Nullable
private final String jsonrpc;
@Nullable
private final String method;
@NotNull
private final JsonNode params;
@Nullable
private final ValueNode id;
public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc,
@JsonProperty("method") @Nullable String method,
@JsonProperty("params") @NotNull JsonNode params,
@JsonProperty("id") @Nullable ValueNode id) {
this.jsonrpc = jsonrpc;
this.method = method;
this.id = id;
this.params = params;
}
@Nullable
public String getJsonrpc() {
return jsonrpc;
}
@Nullable
public String getMethod() {
return method;
}
@NotNull
public ValueNode getId() {
return id != null ? id : NullNode.getInstance();
}
@NotNull
public JsonNode getParams() {
return params;
}
@Override
public String toString() {
return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}";
}
}
|
Add import statement for get_user_model. | # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
from django.contrib.auth import login
from django.contrib.auth import get_user_model
class Home(View):
# Get the homepage. If the user isn't logged in, (we can find no trace
# of the user) or they are logged in but somehow don't have a valid slug
# then we bounce them to the login page.
# Otherwise (for the moment) we take them to the list of links.
def get(self, request, *args, **kwargs):
userid = request.META.get('HTTP_KEYCLOAK_USERNAME')
if userid:
try:
user = get_user_model().objects.get(userid=userid)
except:
user = get_user_model().objects.create_user(
userid=userid, is_active=True)
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(self.request, user)
self.user = user
return redirect(reverse('link-list'))
try:
u = request.user.slug
if (u is not None and u is not ''):
return redirect(reverse('link-list'))
else:
return redirect(reverse('login'))
except:
return redirect(reverse('login'))
| # (c) Crown Owned Copyright, 2016. Dstl.
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.generic.base import View
from django.contrib.auth import login
class Home(View):
# Get the homepage. If the user isn't logged in, (we can find no trace
# of the user) or they are logged in but somehow don't have a valid slug
# then we bounce them to the login page.
# Otherwise (for the moment) we take them to the list of links.
def get(self, request, *args, **kwargs):
userid = request.META.get('HTTP_KEYCLOAK_USERNAME')
if userid:
try:
user = get_user_model().objects.get(userid=userid)
except:
user = get_user_model().objects.create_user(
userid=userid, is_active=True)
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(self.request, user)
self.user = user
return redirect(reverse('link-list'))
try:
u = request.user.slug
if (u is not None and u is not ''):
return redirect(reverse('link-list'))
else:
return redirect(reverse('login'))
except:
return redirect(reverse('login'))
|
Add \r at the end of Web socket | import os
import socket
import websocket
from . import IOHandler
def resolve_hostname(hostname, port):
# We do our own mDNS resolution
# to enforce we only search for IPV4 address
# and avoid a 5s timeout in the websocket on the ESP
# See https://github.com/esp8266/Arduino/issues/2110
addrinfo = socket.getaddrinfo(hostname, port,
socket.AF_INET, 0,
socket.SOL_TCP)
addr = addrinfo[0][4][0]
return addr
class Ws(IOHandler):
@classmethod
def is_host_compatible(cls, host):
try:
socket.inet_pton(socket.AF_INET, host)
return True
except socket.error:
return host.endswith('.local')
@classmethod
def available_hosts(cls):
hosts = ['pi-gate.local']
return [
ip
for ip in hosts
if os.system('ping -c 1 -W1 -t1 {} > /dev/null 2>&1'.format(ip)) == 0
]
def __init__(self, host, port=9342):
host = resolve_hostname(host, port)
url = 'ws://{}:{}'.format(host, port)
self._ws = websocket.create_connection(url)
def is_ready(self):
return True
def recv(self):
return self._ws.recv()
def write(self, data):
self._ws.send(data + '\r'.encode())
def close(self):
self._ws.close()
| import os
import socket
import websocket
from . import IOHandler
def resolve_hostname(hostname, port):
# We do our own mDNS resolution
# to enforce we only search for IPV4 address
# and avoid a 5s timeout in the websocket on the ESP
# See https://github.com/esp8266/Arduino/issues/2110
addrinfo = socket.getaddrinfo(hostname, port,
socket.AF_INET, 0,
socket.SOL_TCP)
addr = addrinfo[0][4][0]
return addr
class Ws(IOHandler):
@classmethod
def is_host_compatible(cls, host):
try:
socket.inet_pton(socket.AF_INET, host)
return True
except socket.error:
return host.endswith('.local')
@classmethod
def available_hosts(cls):
hosts = ['pi-gate.local']
return [
ip
for ip in hosts
if os.system('ping -c 1 -W1 -t1 {} > /dev/null 2>&1'.format(ip)) == 0
]
def __init__(self, host, port=9342):
host = resolve_hostname(host, port)
url = 'ws://{}:{}'.format(host, port)
self._ws = websocket.create_connection(url)
def is_ready(self):
return True
def recv(self):
return self._ws.recv()
def write(self, data):
self._ws.send(data)
def close(self):
self._ws.close()
|
Add button for jumping to todays date | /**
* Created by nkmathew on 05/07/2016.
*/
$(document).ready(function () {
$("#profile-form").submit(function (e) {
$("#btn-submit-profile").spin(BIG_SPINNER);
var url = '/site/profile';
$.ajax({
type: 'POST',
url: url,
data: $("#profile-form").serialize(),
success: function (data) {
// Remove spinner
$("#btn-submit-profile").spin(false);
// Remove green outline colouring when validation passes
setTimeout(function () {
$('.has-success').each(function () {
$(this).removeClass('has-success');
})
}, 5000);
},
error: function (xhr, status, error) {
$("#btn-invite-sender").spin(false);
$('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText);
$('.alert-box').addClass('alert-danger');
$('.alert-box').show();
},
});
e.preventDefault();
});
$('#profileform-startdate').datepicker({
format: "dd/mm/yyyy",
maxViewMode: 2,
calendarWeeks: true,
todayHighlight: true,
endDate: '0',
toggleActive: true,
orientation: 'auto',
todayBtn: true,
});
});
| /**
* Created by nkmathew on 05/07/2016.
*/
$(document).ready(function () {
$("#profile-form").submit(function (e) {
$("#btn-submit-profile").spin(BIG_SPINNER);
var url = '/site/profile';
$.ajax({
type: 'POST',
url: url,
data: $("#profile-form").serialize(),
success: function (data) {
// Remove spinner
$("#btn-submit-profile").spin(false);
// Remove green outline colouring when validation passes
setTimeout(function () {
$('.has-success').each(function () {
$(this).removeClass('has-success');
})
}, 5000);
},
error: function (xhr, status, error) {
$("#btn-invite-sender").spin(false);
$('.alert-box .msg').html('<h4>' + error + '</h4><br/>' + xhr.responseText);
$('.alert-box').addClass('alert-danger');
$('.alert-box').show();
},
});
e.preventDefault();
});
$('#profileform-startdate').datepicker({
format: "dd/mm/yyyy",
maxViewMode: 2,
calendarWeeks: true,
todayHighlight: true,
endDate: '0',
toggleActive: true,
orientation: 'auto'
});
});
|
Fix automatic reconnect (e.g. on bad auth key)
This took more time than it should have to debug. | import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
async def connect(self):
await super().connect()
self._send_counter = 0 # Important or Telegram won't reply
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
| import struct
from zlib import crc32
from .connection import Connection
from ...errors import InvalidChecksumError
class ConnectionTcpFull(Connection):
"""
Default Telegram mode. Sends 12 additional bytes and
needs to calculate the CRC value of the packet itself.
"""
def __init__(self, ip, port, *, loop):
super().__init__(ip, port, loop=loop)
self._send_counter = 0
def _send(self, data):
# https://core.telegram.org/mtproto#tcp-transport
# total length, sequence number, packet and checksum (CRC32)
length = len(data) + 12
data = struct.pack('<ii', length, self._send_counter) + data
crc = struct.pack('<I', crc32(data))
self._send_counter += 1
self._writer.write(data + crc)
async def _recv(self):
packet_len_seq = await self._reader.readexactly(8) # 4 and 4
packet_len, seq = struct.unpack('<ii', packet_len_seq)
body = await self._reader.readexactly(packet_len - 8)
checksum = struct.unpack('<I', body[-4:])[0]
body = body[:-4]
valid_checksum = crc32(packet_len_seq + body)
if checksum != valid_checksum:
raise InvalidChecksumError(checksum, valid_checksum)
return body
|
Set zip_safe to False to eliminate a variable getting the tests to run | #!/usr/bin/env python
"""
Setup file for toolaudit.
"""
import codecs
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
def read(filename):
"""
Read the contents of the files listed in filenames and return it as a
string.
"""
return codecs.open(os.path.join(here, filename), 'r').read()
setup(
name='toolaudit',
version='0.0.3',
packages=['toolaudit'],
zip_safe=False,
install_requires=[
"argparse>=1.3.0",
"PyYAML>=3.11",
"six>=1.9.0"
],
entry_points={
'console_scripts': [
'toolaudit = toolaudit:main',
],
},
author='Jon Stutters',
author_email='[email protected]',
description='Report on the tools used in your software pipeline.',
long_description=read('README.rst'),
url='https://github.com/jstutters/toolaudit',
include_package_data=True,
license='MIT',
classifiers=[
'Programming Language :: Python',
'Development Status :: 3 - Alpha',
'Natural Language :: English',
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Topic :: System :: Systems Administration'
]
)
| #!/usr/bin/env python
"""
Setup file for toolaudit.
"""
import codecs
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
def read(filename):
"""
Read the contents of the files listed in filenames and return it as a
string.
"""
return codecs.open(os.path.join(here, filename), 'r').read()
setup(
name='toolaudit',
version='0.0.3',
packages=['toolaudit'],
install_requires=[
"argparse>=1.3.0",
"PyYAML>=3.11",
"six>=1.9.0"
],
entry_points={
'console_scripts': [
'toolaudit = toolaudit:main',
],
},
author='Jon Stutters',
author_email='[email protected]',
description='Report on the tools used in your software pipeline.',
long_description=read('README.rst'),
url='https://github.com/jstutters/toolaudit',
include_package_data=True,
license='MIT',
classifiers=[
'Programming Language :: Python',
'Development Status :: 3 - Alpha',
'Natural Language :: English',
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Topic :: System :: Systems Administration'
]
)
|
Use connection check in test | <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use League\Flysystem\FilesystemAdapter;
/**
* @group ftp
*/
class FtpAdapterTest extends FtpAdapterTestCase
{
protected static function createFilesystemAdapter(): FilesystemAdapter
{
$options = FtpConnectionOptions::fromArray([
'host' => 'localhost',
'port' => 2121,
'timestampsOnUnixListingsEnabled' => true,
'root' => '/home/foo/upload/',
'username' => 'foo',
'password' => 'pass',
]);
static::$connectivityChecker = new ConnectivityCheckerThatCanFail(new NoopCommandConnectivityChecker());
return new FtpAdapter($options, null, static::$connectivityChecker);
}
/**
* @test
*/
public function disconnect_after_destruct(): void
{
/** @var FtpAdapter $adapter */
$adapter = $this->adapter();
$reflection = new \ReflectionObject($adapter);
$adapter->fileExists('foo.txt');
$reflectionProperty = $reflection->getProperty('connection');
$reflectionProperty->setAccessible(true);
$connection = $reflectionProperty->getValue($adapter);
unset($reflection);
$this->assertTrue(false !== ftp_pwd($connection));
unset($adapter);
static::clearFilesystemAdapterCache();
$this->assertFalse((new NoopCommandConnectivityChecker())->isConnected($connection));
}
}
| <?php
declare(strict_types=1);
namespace League\Flysystem\Ftp;
use League\Flysystem\FilesystemAdapter;
/**
* @group ftp
*/
class FtpAdapterTest extends FtpAdapterTestCase
{
protected static function createFilesystemAdapter(): FilesystemAdapter
{
$options = FtpConnectionOptions::fromArray([
'host' => 'localhost',
'port' => 2121,
'timestampsOnUnixListingsEnabled' => true,
'root' => '/home/foo/upload/',
'username' => 'foo',
'password' => 'pass',
]);
static::$connectivityChecker = new ConnectivityCheckerThatCanFail(new NoopCommandConnectivityChecker());
return new FtpAdapter($options, null, static::$connectivityChecker);
}
/**
* @test
*/
public function disconnect_after_destruct(): void
{
/** @var FtpAdapter $adapter */
$adapter = $this->adapter();
$reflection = new \ReflectionObject($adapter);
$adapter->fileExists('foo.txt');
$reflectionProperty = $reflection->getProperty('connection');
$reflectionProperty->setAccessible(true);
$connection = $reflectionProperty->getValue($adapter);
unset($reflection);
$this->assertTrue(false !== ftp_pwd($connection));
unset($adapter);
static::clearFilesystemAdapterCache();
$this->assertFalse(@ftp_pwd($connection));
}
}
|
Fix mistaken reference to image_callback. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/Subscriber.
"""
def __init__(self):
self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
Image, self.frame_callback,
queue_size=1)
self.image_publisher = rospy.Publisher("/output/slow_image_raw",
Image, queue_size=1)
rospy.logdebug("Subscribed to /ardrone/image_raw")
self.count = 0
def frame_callback(self, frame):
"""
Callback function of subscribed topic.
"""
# Publish every fifteenth frame
if not self.count % 15:
self.image_publisher.publish(frame)
self.count += 1
def main():
"""Initialize ROS node."""
rospy.init_node("framerate_reducer", anonymous=True)
ImageFeature()
rospy.loginfo("Reducing framerate")
rospy.spin()
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/Subscriber.
"""
def __init__(self):
self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
Image, self.image_callback,
queue_size=1)
self.image_publisher = rospy.Publisher("/output/slow_image_raw",
Image, queue_size=1)
rospy.logdebug("Subscribed to /ardrone/image_raw")
self.count = 0
def frame_callback(self, frame):
"""
Callback function of subscribed topic.
"""
# Publish every fifteenth frame
if not self.count % 15:
self.image_publisher.publish(frame)
self.count += 1
def main():
"""Initialize ROS node."""
rospy.init_node("framerate_reducer", anonymous=True)
ImageFeature()
rospy.loginfo("Reducing framerate")
rospy.spin()
if __name__ == "__main__":
main()
|
Refactor file to match masseuse spec. | /**
* The google api module is responsible for all google operations.
*/
module.exports = function(app){
'use strict';
var _ = require('underscore'),
config = require('../config'),
bridgetown = require('bridgetown-api'),
grasshopper = require('grasshopper-core'),
Response = bridgetown.Response;
//Setup Routes for included functions
app.get('/oauth2callback', [oauth]);
app.get('/googleurl', [url]);
return {
oauth : oauth,
url : url
};
/**
* Method will accept the oauth callback from google, run authentication, then redirect the user to the page that accepts the token.
*/
function oauth(httpRequest, httpResponse){
var code = httpRequest.query.code,
redirectUrl = _.has(config.identities, 'google') ? config.identities.google.redirectUrl : 'defaultRoute';
grasshopper.auth('Google', { code: code })
.then(function(token) {
httpResponse.redirect(redirectUrl+'/'+ new Buffer(token).toString('base64'));
});
}
/**
* Method will return a google auth url.
*/
function url(httpRequest, httpResponse) {
var response = new Response(httpResponse);
grasshopper.googleAuthUrl()
.then(function(url) {
response.writeSuccess(url);
})
.fail(function(message) {
var err = {
code : 400,
message : message
};
response.writeError(err);
})
.done();
}
}; | /**
* The google api module is responsible for all google operations.
*/
module.exports = function(app){
'use strict';
var _ = require('underscore'),
config = require('../config'),
bridgetown = require('bridgetown-api'),
grasshopper = require('grasshopper-core'),
google = {},
Response = bridgetown.Response;
/**
* Method will accept the oauth callback from google, run authentication, then redirect the user to the page that accepts the token.
*/
google.oauth = function(httpRequest, httpResponse){
var code = httpRequest.query.code,
redirectUrl = _.has(config.identities, 'google') ? config.identities.google.redirectUrl : 'defaultRoute';
grasshopper.auth('Google', { code: code })
.then(function(token) {
httpResponse.redirect(redirectUrl+'/'+ new Buffer(token).toString('base64'));
});
};
/**
* Method will return a google auth url.
*/
google.url = function(httpRequest, httpResponse) {
var response = new Response(httpResponse);
grasshopper.googleAuthUrl()
.then(function(url) {
response.writeSuccess(url);
})
.fail(function(message) {
var err = {
code : 400,
message : message
};
response.writeError(err);
})
.done();
};
//Setup Routes for included functions
app.get('/oauth2callback', [google.oauth]);
app.get('/googleurl', [google.url]);
return google;
}; |
Read properties from a property file
Reads a property value from either a project
property file of the file or value is missing,
tries to get a default value for that property. | package nl.codecastle.configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Reads properties file from a given location.
*/
public class PropertiesReader {
private final Properties properties;
private final Properties defaultProperties;
/**
* Reads in the properties from the given path.
* Also reads in the defaults properties from the "default.properties" file.
*
* @param filePath the path of the project properties file
*/
public PropertiesReader(String filePath) {
properties = new Properties();
defaultProperties = new Properties();
try {
InputStream defaultPropertiesStream = getClass().getClassLoader().getResourceAsStream("default.properties");
InputStream projectPropertiesStream = getClass().getClassLoader().getResourceAsStream(filePath);
assert (defaultPropertiesStream != null);
defaultProperties.load(defaultPropertiesStream);
if (projectPropertiesStream != null) {
properties.load(projectPropertiesStream);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the value for the given key from the project properties file.
* If the file is missing it retrieves a value from the default properties.
*
* @param key name of the property needed
* @return the value for the given key
*/
public String getValue(String key) {
if (properties.containsKey(key)) {
return properties.getProperty(key);
} else {
return defaultProperties.getProperty(key);
}
}
}
| package nl.codecastle.configuration;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Reads properties file from a given location.
*/
public class PropertiesReader {
private final Properties properties;
private final Properties defaultProperties;
/**
* Reads in the properties from the given path.
* Also reads in the defaults properties from the "default.properties" file.
*
* @param filePath the path of the project properties file
*/
public PropertiesReader(String filePath) {
properties = new Properties();
defaultProperties = new Properties();
try {
ClassLoader classLoader = getClass().getClassLoader();
InputStream defaultPropertiesStream = classLoader.getResourceAsStream("default.properties");
InputStream projectPropertiesStream = classLoader.getResourceAsStream(filePath);
assert (defaultPropertiesStream != null);
defaultProperties.load(defaultPropertiesStream);
if (projectPropertiesStream != null) {
properties.load(projectPropertiesStream);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the value for the given key from the project properties file.
* If the file is missing it retrieves a value from the default properties.
*
* @param key name of the property needed
* @return the value for the given key
*/
public String getValue(String key) {
if (properties.containsKey(key)) {
return properties.getProperty(key);
} else {
return defaultProperties.getProperty(key);
}
}
}
|
Fix JS ObjectDB class wrapper to use format "plugins.Foo.Bar" not "plugin.Foo.Bar". Oops! | package uk.co.uwcs.choob.support;
import java.io.*;
import org.mozilla.javascript.*;
public final class ObjectDBClassJSWrapper implements ObjectDBClass {
private Function cls;
public ObjectDBClassJSWrapper(Object obj) {
if (!(obj instanceof Function)) {
throw new RuntimeException("Trying to wrap a non-function type as a class!");
}
this.cls = (Function)obj;
}
public String getName() {
Context cx = Context.enter();
try {
try {
String ctorName = (String)JSUtils.getProperty((Scriptable)cls, "name");
Scriptable scope = ((Scriptable)cls).getParentScope();
// Get plugin name from scope (HACK)!
String plugName = "<error>";
while (scope != null) {
try {
plugName = (String)JSUtils.getProperty(scope, "__jsplugman_pluginName");
scope = null;
} catch (NoSuchFieldException e) {
scope = scope.getParentScope();
}
}
return "plugins." + plugName + "." + ctorName;
} catch (NoSuchFieldException e) {
// Do nothing.
}
} finally {
cx.exit();
}
return "";
}
public Object newInstance() {
Context cx = Context.enter();
try {
Scriptable scope = cls.getParentScope();
return cls.construct(cx, scope, new Object[0]);
} finally {
cx.exit();
}
}
}
| package uk.co.uwcs.choob.support;
import java.io.*;
import org.mozilla.javascript.*;
public final class ObjectDBClassJSWrapper implements ObjectDBClass {
private Function cls;
public ObjectDBClassJSWrapper(Object obj) {
if (!(obj instanceof Function)) {
throw new RuntimeException("Trying to wrap a non-function type as a class!");
}
this.cls = (Function)obj;
}
public String getName() {
Context cx = Context.enter();
try {
try {
String ctorName = (String)JSUtils.getProperty((Scriptable)cls, "name");
Scriptable scope = ((Scriptable)cls).getParentScope();
// Get plugin name from scope (HACK)!
String plugName = "<error>";
while (scope != null) {
try {
plugName = (String)JSUtils.getProperty(scope, "__jsplugman_pluginName");
scope = null;
} catch (NoSuchFieldException e) {
scope = scope.getParentScope();
}
}
return "plugin." + plugName + "." + ctorName;
} catch (NoSuchFieldException e) {
// Do nothing.
}
} finally {
cx.exit();
}
return "";
}
public Object newInstance() {
Context cx = Context.enter();
try {
Scriptable scope = cls.getParentScope();
return cls.construct(cx, scope, new Object[0]);
} finally {
cx.exit();
}
}
}
|
Add new page for register to session cleanup. | <?php
/**
* This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
* The license and all terms en conditions that apply to Stippers also apply to this file.
*
* @author Stan Wijckmans
*
* Middleware to do some session cleanup. It removes data from session that's irrelevant for the page you're going to.
*/
require_once "IMiddleware.php";
abstract class SessionCleanup implements IMiddleware {
public static function run(array $requestData) {
if ($requestData['requestedPage'] != 'manageuser' && $requestData['requestedPage'] != 'edituser' && $requestData['requestedPage'] != 'sendemailtousers')
unset($_SESSION['Stippers']['ManageUserSearch']);
if ($requestData['requestedPage'] != 'edituser')
unset($_SESSION['Stippers']['EditUser']);
if ($requestData['requestedPage'] != 'editbrowser')
unset($_SESSION['Stippers']['EditBrowser']);
if ($requestData['requestedPage'] != 'renewuser')
unset($_SESSION['Stippers']['RenewUser']);
if ($requestData['requestedPage'] != 'profile')
unset($_SESSION['Stippers']['Profile']);
if ($requestData['requestedPage'] != 'changepassword')
unset($_SESSION['Stippers']['ChangePassword']);
if ($requestData['requestedPage'] != 'cashregister')
unset($_SESSION['Stippers']['CashRegister']);
return true;
}
}
| <?php
/**
* This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
* The license and all terms en conditions that apply to Stippers also apply to this file.
*
* @author Stan Wijckmans
*
* Middleware to do some session cleanup. It removes data from session that's irrelevant for the page you're going to.
*/
require_once "IMiddleware.php";
abstract class SessionCleanup implements IMiddleware {
public static function run(array $requestData) {
if ($requestData['requestedPage'] != 'manageuser' && $requestData['requestedPage'] != 'edituser' && $requestData['requestedPage'] != 'sendemailtousers')
unset($_SESSION['Stippers']['ManageUserSearch']);
if ($requestData['requestedPage'] != 'edituser')
unset($_SESSION['Stippers']['EditUser']);
if ($requestData['requestedPage'] != 'editbrowser')
unset($_SESSION['Stippers']['EditBrowser']);
if ($requestData['requestedPage'] != 'renewuser')
unset($_SESSION['Stippers']['RenewUser']);
if ($requestData['requestedPage'] != 'profile')
unset($_SESSION['Stippers']['Profile']);
if ($requestData['requestedPage'] != 'changepassword')
unset($_SESSION['Stippers']['ChangePassword']);
return true;
}
}
|
Change default value for root_dir | <?php
namespace Ftrrtf\RollbarBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* @return \Symfony\Component\Config\Definition\Builder\TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ftrrtf_rollbar');
$rootNode
->children()
->arrayNode('notifier')
->children()
->scalarNode('access_token')->isRequired()->end()
->arrayNode('transport')
->addDefaultsIfNotSet()
->children()
->scalarNode('type')->defaultValue('curl')->end()
->end()
->end()
->end()
->end()
->arrayNode('environment')
->children()
// ->scalarNode('host')->defaultNull()->end()
->scalarNode('branch')->defaultValue('master')->end()
->scalarNode('root_dir')->defaultValue('')->end()
->scalarNode('environment')->defaultValue('unknown')->end()
->scalarNode('framework')->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Ftrrtf\RollbarBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* @return \Symfony\Component\Config\Definition\Builder\TreeBuilder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ftrrtf_rollbar');
$rootNode
->children()
->arrayNode('notifier')
->children()
->scalarNode('access_token')->isRequired()->end()
->arrayNode('transport')
->addDefaultsIfNotSet()
->children()
->scalarNode('type')->defaultValue('curl')->end()
->end()
->end()
->end()
->end()
->arrayNode('environment')
->children()
// ->scalarNode('host')->defaultNull()->end()
->scalarNode('branch')->defaultValue('master')->end()
->scalarNode('root_dir')->defaultValue('%kernel.root_dir%/../')->end()
->scalarNode('environment')->defaultValue('unknown')->end()
->scalarNode('framework')->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
|
Add pytz to installation requirements, needed for pedometerpp | from setuptools import setup
import io
# Take from Jeff Knupp's excellent article:
# http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
setup(name='dayonetools',
version='1.0.0',
description='Tools to import multiple services into Day One Journal',
long_description=read('README.md'),
package_data={'': ['README.md']},
license='MIT',
author='Luke Lee',
author_email='[email protected]',
url='https://github.com/durden/dayonetools',
packages=['dayonetools', 'dayonetools.services'],
install_requires=['python-dateutil>=2.2', 'pytz==2014.4'],
platforms='any',
classifiers= [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: System :: Archiving'],
entry_points={
"console_scripts": [
"dayonetools = dayonetools.main:main",
]
},
)
| from setuptools import setup
import io
# Take from Jeff Knupp's excellent article:
# http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
setup(name='dayonetools',
version='1.0.0',
description='Tools to import multiple services into Day One Journal',
long_description=read('README.md'),
package_data={'': ['README.md']},
license='MIT',
author='Luke Lee',
author_email='[email protected]',
url='https://github.com/durden/dayonetools',
packages=['dayonetools', 'dayonetools.services'],
install_requires=['python-dateutil>=2.2'],
platforms='any',
classifiers= [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: System :: Archiving'],
entry_points={
"console_scripts": [
"dayonetools = dayonetools.main:main",
]
},
)
|
Check repo type and repo name alwways on lower case | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\CommandBus\Handler\Repository;
use ApiClients\Client\AppVeyor\AsyncClient;
use ApiClients\Client\AppVeyor\Resource\ProjectInterface;
use ApiClients\Client\Github\CommandBus\Command\Repository\AppVeyorCommand;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
final class AppVeyorHandler
{
/**
* @var AsyncClient
*/
private $appveyor;
/**
* @param AsyncClient $appveyor
*/
public function __construct(AsyncClient $appveyor)
{
$this->appveyor = $appveyor;
}
/**
* @param AppVeyorCommand $command
* @return PromiseInterface
*/
public function handle(AppVeyorCommand $command): PromiseInterface
{
return new Promise(function ($resolve, $reject) use ($command) {
$repo = false;
$this->appveyor->projects()->filter(function (ProjectInterface $project) use ($command) {
return strtolower($project->repositoryType()) === 'github' &&
strtolower($project->repositoryName()) === strtolower($command->getRepository());
})->take(1)->subscribe(function ($repository) use (&$repo) {
$repo = $repository;
}, function ($error) use ($reject) {
$reject($error);
}, function () use (&$repo, $resolve) {
$resolve($repo);
});
});
}
}
| <?php declare(strict_types=1);
namespace ApiClients\Client\Github\CommandBus\Handler\Repository;
use ApiClients\Client\AppVeyor\AsyncClient;
use ApiClients\Client\AppVeyor\Resource\ProjectInterface;
use ApiClients\Client\Github\CommandBus\Command\Repository\AppVeyorCommand;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
final class AppVeyorHandler
{
/**
* @var AsyncClient
*/
private $appveyor;
/**
* @param AsyncClient $appveyor
*/
public function __construct(AsyncClient $appveyor)
{
$this->appveyor = $appveyor;
}
/**
* @param AppVeyorCommand $command
* @return PromiseInterface
*/
public function handle(AppVeyorCommand $command): PromiseInterface
{
return new Promise(function ($resolve, $reject) use ($command) {
$repo = false;
$this->appveyor->projects()->filter(function (ProjectInterface $project) use ($command) {
return $project->repositoryType() === 'github' &&
$project->repositoryName() === $command->getRepository();
})->take(1)->subscribe(function ($repository) use (&$repo) {
$repo = $repository;
}, function ($error) use ($reject) {
$reject($error);
}, function () use (&$repo, $resolve) {
$resolve($repo);
});
});
}
}
|
Make the nonce more secure and faster to generate | # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import time
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0}{1}'.format(
str(int(time.time() * 1000000)),
binascii.hexlify(libnacl.randombytes(24)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')[:libnacl.crypto_box_NONCEBYTES]
| # -*- coding: utf-8 -*-
# Import nacl libs
import libnacl
import libnacl.encode
# Import python libs
import datetime
import binascii
class BaseKey(object):
'''
Include methods for key management convenience
'''
def hex_sk(self):
if hasattr(self, 'sk'):
return libnacl.encode.hex_encode(self.sk)
else:
return ''
def hex_pk(self):
if hasattr(self, 'pk'):
return libnacl.encode.hex_encode(self.pk)
def hex_vk(self):
if hasattr(self, 'vk'):
return libnacl.encode.hex_encode(self.vk)
def hex_seed(self):
if hasattr(self, 'seed'):
return libnacl.encode.hex_encode(self.seed)
def salsa_key():
'''
Generates a salsa2020 key
'''
return libnacl.randombytes(libnacl.crypto_secretbox_KEYBYTES)
def time_nonce():
'''
Generates a safe nonce
The nonce generated here is done by grabbing the 20 digit microsecond
timestamp and appending 4 random chars
'''
nonce = '{0:%Y%m%d%H%M%S%f}{1}'.format(
datetime.datetime.now(),
binascii.hexlify(libnacl.randombytes(2)).decode(encoding='UTF-8'))
return nonce.encode(encoding='UTF-8')
|
Fix issues reported by Sonar | package me.devsaki.hentoid.collection.mikan;
import com.google.gson.annotations.Expose;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;
public class MikanAttribute {
// Published by both Collection and Attributes endpoints
@Expose
public String name;
// Published by Collection (book search, recent) endpoints
@Expose
public String url;
// Published by Attributes endpoints
@Expose
public int id;
@Expose
public int count;
@Expose
public String type;
Attribute toAttribute() {
AttributeType attrType;
switch (type) {
case "language":
attrType = AttributeType.LANGUAGE;
break;
case "character":
attrType = AttributeType.CHARACTER;
break;
case "artist":
attrType = AttributeType.ARTIST;
break;
case "group":
attrType = AttributeType.CIRCLE;
break;
default:
attrType = AttributeType.TAG;
}
Attribute result = new Attribute(attrType, name, url, Site.HITOMI);
result.setCount(count);
result.setExternalId(id);
return result;
}
}
| package me.devsaki.hentoid.collection.mikan;
import com.google.gson.annotations.Expose;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;
public class MikanAttribute {
// Published by both Collection and Attributes endpoints
@Expose
public String name;
// Published by Collection (book search, recent) endpoints
@Expose
public String url;
// Published by Attributes endpoints
@Expose
public int id;
@Expose
public int count;
@Expose
public String type;
Attribute toAttribute() {
AttributeType type;
switch (this.type) {
case "language":
type = AttributeType.LANGUAGE;
break;
case "character":
type = AttributeType.CHARACTER;
break;
case "artist":
type = AttributeType.ARTIST;
break;
case "group":
type = AttributeType.CIRCLE;
break;
default:
type = AttributeType.TAG;
}
Attribute result = new Attribute(type, name, url, Site.HITOMI);
result.setCount(count);
result.setExternalId(id);
return result;
}
}
|
Add support for custom OkHttpClient when creating bot | package com.pengrad.telegrambot;
import com.google.gson.Gson;
import com.pengrad.telegrambot.impl.FileApi;
import com.pengrad.telegrambot.impl.TelegramBotClient;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* stas
* 8/4/15.
*/
public class TelegramBotAdapter {
public static final String API_URL = "https://api.telegram.org/bot";
public static TelegramBot build(String botToken) {
return buildCustom(botToken, client(null));
}
public static TelegramBot buildDebug(String botToken) {
return buildCustom(botToken, client(httpLoggingInterceptor()));
}
public static TelegramBot buildCustom(String botToken, OkHttpClient okHttpClient) {
TelegramBotClient client = new TelegramBotClient(okHttpClient, gson(), apiUrl(botToken));
FileApi fileApi = new FileApi(botToken);
return new TelegramBot(client, fileApi);
}
private static OkHttpClient client(Interceptor interceptor) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (interceptor != null) builder.addInterceptor(interceptor);
return builder.build();
}
private static Interceptor httpLoggingInterceptor() {
return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
}
private static Gson gson() {
return new Gson();
}
private static String apiUrl(String botToken) {
return API_URL + botToken + "/";
}
}
| package com.pengrad.telegrambot;
import com.google.gson.Gson;
import com.pengrad.telegrambot.impl.FileApi;
import com.pengrad.telegrambot.impl.TelegramBotClient;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* stas
* 8/4/15.
*/
public class TelegramBotAdapter {
public static final String API_URL = "https://api.telegram.org/bot";
public static TelegramBot build(String botToken) {
FileApi fileApi = new FileApi(botToken);
TelegramBotClient api = new TelegramBotClient(client(null), gson(), apiUrl(botToken));
return new TelegramBot(api, fileApi);
}
public static TelegramBot buildDebug(String botToken) {
FileApi fileApi = new FileApi(botToken);
TelegramBotClient api = new TelegramBotClient(client(httpLoggingInterceptor()), gson(), apiUrl(botToken));
return new TelegramBot(api, fileApi);
}
private static OkHttpClient client(Interceptor interceptor) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (interceptor != null) builder.addInterceptor(interceptor);
return builder.build();
}
private static Interceptor httpLoggingInterceptor() {
return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
}
private static Gson gson() {
return new Gson();
}
private static String apiUrl(String botToken) {
return API_URL + botToken + "/";
}
}
|
Add delay of 1.5s before search list refresh
It takes one second for elasticsearch to update it's index.
See `index.refresh_interval` in
https://www.elastic.co/guide/en/elasticsearch/reference/5.6/index-modules.html#dynamic-index-settings | 'use strict';
angular.module('mean.icu.ui.searchlist')
.controller('SearchListController', function ($rootScope, $scope, $stateParams, $location, $timeout, results, term, SearchService, UsersService) {
document.me = $scope.me.id;
$scope.results = results;
filterFinalRes();
$scope.inObjArray = function(id,array){
array.forEach(function(w){
if(w._id && w._id === id){
return true;
}
});
return false;
};
$scope.$on('refreshList', function (ev) {
$timeout(() => {
SearchService.find(term).then(function(res){
$scope.results = res;
filterFinalRes();
});
}, 1500)
});
function filterFinalRes(){
UsersService.getMe().then(function(me){
let id = me._id;
let finalResults = [];
for(let i=0; i < $scope.results.length; i++){
let task = $scope.results[i];
if(
task.creator === id
|| task.assign === id
|| $.inArray(id, task.watchers) !== -1
|| $scope.inObjArray(id,task.watchers)){
finalResults.push(task);
}
}
$scope.term = term;
$scope.results = finalResults;
$scope.resultsLength = $scope.results.length;
});
}
//**********Multiple Select*********//
$scope.multipleSelectMode = false;
});
| 'use strict';
angular.module('mean.icu.ui.searchlist')
.controller('SearchListController', function ($rootScope, $scope, $stateParams, $location, $timeout, results, term, SearchService, UsersService) {
document.me = $scope.me.id;
$scope.results = results;
filterFinalRes();
$scope.inObjArray = function(id,array){
array.forEach(function(w){
if(w._id && w._id === id){
return true;
}
});
return false;
};
$scope.$on('refreshList', function (ev) {
SearchService.find(term).then(function(res){
$scope.results = res;
filterFinalRes();
});
});
function filterFinalRes(){
UsersService.getMe().then(function(me){
let id = me._id;
let finalResults = [];
for(let i=0; i < $scope.results.length; i++){
let task = $scope.results[i];
if(
task.creator === id
|| task.assign === id
|| $.inArray(id, task.watchers) !== -1
|| $scope.inObjArray(id,task.watchers)){
finalResults.push(task);
}
}
$scope.term = term;
$scope.results = finalResults;
$scope.resultsLength = $scope.results.length;
});
}
//**********Multiple Select*********//
$scope.multipleSelectMode = false;
});
|
Fix scripting for remote web services. | <?php
namespace DreamFactory\Core\Events;
use DreamFactory\Core\Contracts\ServiceRequestInterface;
use DreamFactory\Core\Contracts\ServiceResponseInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ApiEvent extends ServiceEvent
{
public $request;
public $response;
/**
* Create a new event instance.
*
* @param string $path
* @param ServiceRequestInterface $request
* @param ServiceResponseInterface|null $response
* @param mixed $resource
*/
public function __construct($path, $request, $response = null, $resource = null)
{
$this->request = $request;
$this->response = $response;
if (empty($resource)) {
$name = strtolower($path . '.' . $request->getMethod());
} else {
$name = strtolower($path . '.' . $resource . '.' . $request->getMethod());
}
parent::__construct($name, $resource);
}
public function makeData()
{
$response = (empty($this->response) || $this->response instanceof RedirectResponse ||
$this->response instanceof StreamedResponse)
? [] : $this->response->toArray();
return array_merge(parent::makeData(),
[
'request' => $this->request->toArray(),
'response' => $response
]
);
}
}
| <?php
namespace DreamFactory\Core\Events;
use DreamFactory\Core\Contracts\ServiceRequestInterface;
use DreamFactory\Core\Contracts\ServiceResponseInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ApiEvent extends ServiceEvent
{
public $request;
public $response;
/**
* Create a new event instance.
*
* @param string $path
* @param ServiceRequestInterface $request
* @param ServiceResponseInterface|null $response
* @param mixed $resource
*/
public function __construct($path, $request, $response = null, $resource = null)
{
$this->request = $request;
$this->response = $response;
$name = strtolower($path . '.' . $request->getMethod());
parent::__construct($name, $resource);
}
public function makeData()
{
$response = (empty($this->response) || $this->response instanceof RedirectResponse ||
$this->response instanceof StreamedResponse)
? [] : $this->response->toArray();
return array_merge(parent::makeData(),
[
'request' => $this->request->toArray(),
'response' => $response
]
);
}
}
|
Update leaflet request to be over https | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'leaflet/css/LeafletWidget.css')
}
js = (
'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js',
'leaflet/js/LeafletWidget.js'
)
def render(self, name, value, attrs=None):
# add point
if value:
attrs.update({ 'point': { 'x': value.x,
'y': value.y,
'z': value.z,
'srid': value.srid }
})
return super().render(name, value, attrs)
| from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'leaflet/css/LeafletWidget.css')
}
js = (
'https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.js',
'leaflet/js/LeafletWidget.js'
)
def render(self, name, value, attrs=None):
# add point
if value:
attrs.update({ 'point': { 'x': value.x,
'y': value.y,
'z': value.z,
'srid': value.srid }
})
return super().render(name, value, attrs)
|
Add YiiAsset dependency for widget asset bundles | <?php
/**
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2013
* @package yii2-widgets
* @version 1.0.0
*/
namespace kartik\widgets;
/**
* Base asset bundle for all widgets
*
* @author Kartik Visweswaran <[email protected]>
* @since 1.0
*/
class AssetBundle extends \yii\web\AssetBundle
{
public $depends = [
'yii\web\JqueryAsset',
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
/**
* Set up CSS and JS asset arrays based on the base-file names
*
* @param string $type whether 'css' or 'js'
* @param array $files the list of 'css' or 'js' basefile names
*/
protected function setupAssets($type, $files = [])
{
$srcFiles = [];
$minFiles = [];
foreach ($files as $file) {
$srcFiles[] = "{$file}.{$type}";
$minFiles[] = "{$file}.min.{$type}";
}
if (empty($this->$type)) {
$this->$type = YII_DEBUG ? $srcFiles : $minFiles;
}
}
/**
* Sets the source path if empty
*
* @param string $path the path to be set
*/
protected function setSourcePath($path)
{
if (empty($this->sourcePath)) {
$this->sourcePath = $path;
}
}
}
| <?php
/**
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2013
* @package yii2-widgets
* @version 1.0.0
*/
namespace kartik\widgets;
/**
* Base asset bundle for all widgets
*
* @author Kartik Visweswaran <[email protected]>
* @since 1.0
*/
class AssetBundle extends \yii\web\AssetBundle
{
public $depends = [
'yii\web\JqueryAsset',
'yii\bootstrap\BootstrapAsset',
];
/**
* Set up CSS and JS asset arrays based on the base-file names
*
* @param string $type whether 'css' or 'js'
* @param array $files the list of 'css' or 'js' basefile names
*/
protected function setupAssets($type, $files = [])
{
$srcFiles = [];
$minFiles = [];
foreach ($files as $file) {
$srcFiles[] = "{$file}.{$type}";
$minFiles[] = "{$file}.min.{$type}";
}
if (empty($this->$type)) {
$this->$type = YII_DEBUG ? $srcFiles : $minFiles;
}
}
/**
* Sets the source path if empty
*
* @param string $path the path to be set
*/
protected function setSourcePath($path)
{
if (empty($this->sourcePath)) {
$this->sourcePath = $path;
}
}
}
|
Fix GitHub code editor whitespaces | from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
This method is re-entrant and can be called multiple times.
It displays version information exactly once at application startup.
"""
if cls.initialized:
return
cls.initialized = True
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings # noqa
from axes import checks, signals # noqa
# Skip startup log messages if Axes is not set to verbose
if settings.AXES_VERBOSE:
log.info("AXES: BEGIN LOG")
log.info(
"AXES: Using django-axes version %s",
get_distribution("django-axes").version,
)
if settings.AXES_ONLY_USER_FAILURES:
log.info("AXES: blocking by username only.")
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
log.info("AXES: blocking by combination of username and IP.")
elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
log.info("AXES: blocking by username or IP.")
else:
log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize()
| from logging import getLogger
from pkg_resources import get_distribution
from django import apps
log = getLogger(__name__)
class AppConfig(apps.AppConfig):
name = "axes"
initialized = False
@classmethod
def initialize(cls):
"""
Initialize Axes logging and show version information.
This method is re-entrant and can be called multiple times.
It displays version information exactly once at application startup.
"""
if cls.initialized:
return
cls.initialized = True
# Only import settings, checks, and signals one time after Django has been initialized
from axes.conf import settings # noqa
from axes import checks, signals # noqa
# Skip startup log messages if Axes is not set to verbose
if settings.AXES_VERBOSE:
log.info("AXES: BEGIN LOG")
log.info(
"AXES: Using django-axes version %s",
get_distribution("django-axes").version,
)
if settings.AXES_ONLY_USER_FAILURES:
log.info("AXES: blocking by username only.")
elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP:
log.info("AXES: blocking by combination of username and IP.")
elif settings.AXES_LOCK_OUT_BY_USER_OR_IP:
log.info("AXES: blocking by username or IP.")
else:
log.info("AXES: blocking by IP only.")
def ready(self):
self.initialize()
|
Add in the active level to json output for the mobile game to use | import random as orig_random
from decorator import decorator
import binascii
import struct
import hashlib
from gameserver.database import db
db_session = db.session
random = orig_random.Random()
random.seed()
def node_to_dict(node):
connections = []
for edge in node.lower_edges:
connections.append(
{"to_id": edge.higher_node.id,
"from_id": node.id,
"weight": "{:.2f}".format(edge.weight),
}
)
data = {"id": node.id,
"name": node.name,
"short_name": node.short_name,
"group": node.group,
"leakage": "{:.2f}".format(node.leak),
"max_amount": "{:.2f}".format(node.max_level),
"activation_amount": "{:.2f}".format(node.activation),
"active_level": "{:.2f}".format(node.active_level),
"balance": "{:.2f}".format(node.balance),
"connections": connections
}
return data
def pack_amount(value):
return binascii.hexlify(struct.pack("f", value)).decode('ascii')
def unpack_amount(value):
return struct.unpack("f", binascii.unhexlify(value))[0]
def checksum(seller_id, policy_id, price, salt):
input = "{}{}{}{}".format(seller_id, policy_id, pack_amount(price), salt)
return hashlib.sha1(input).hexdigest()
| import random as orig_random
from decorator import decorator
import binascii
import struct
import hashlib
from gameserver.database import db
db_session = db.session
random = orig_random.Random()
random.seed()
def node_to_dict(node):
connections = []
for edge in node.lower_edges:
connections.append(
{"to_id": edge.higher_node.id,
"from_id": node.id,
"weight": "{:.2f}".format(edge.weight),
}
)
data = {"id": node.id,
"name": node.name,
"short_name": node.short_name,
"group": node.group,
"leakage": "{:.2f}".format(node.leak),
"max_amount": "{:.2f}".format(node.max_level),
"activation_amount": "{:.2f}".format(node.activation),
"balance": "{:.2f}".format(node.balance),
"connections": connections
}
return data
def pack_amount(value):
return binascii.hexlify(struct.pack("f", value)).decode('ascii')
def unpack_amount(value):
return struct.unpack("f", binascii.unhexlify(value))[0]
def checksum(seller_id, policy_id, price, salt):
input = "{}{}{}{}".format(seller_id, policy_id, pack_amount(price), salt)
return hashlib.sha1(input).hexdigest()
|
Set the base url of the dummy app | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
"script-src": "'self' 'unsafe-inline'",
"font-src": "'self'",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data:"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/gloit-component';
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
"script-src": "'self' 'unsafe-inline'",
"font-src": "'self'",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data:"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Add in model contact beforeUpdate | /**
* Contact.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
firstname: {
type: 'string'
},
lastname: {
type: 'string'
},
nickname: {
type: 'string',
unique: true,
required: true
},
email: {
type: 'string',
unique: true
},
password: {
type: 'string'
},
phones: {
collection: 'phone',
via: 'owner'
},
smsSend: {
collection: 'sms',
via: 'recipient'
},
smsReceipt: {
collection: 'sms',
via: 'sender'
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
// Lifecycle Callbacks
beforeCreate: function (values, cb) {
if(typeof values.password !== 'undefined') {
// Encrypt password
bcrypt.hash(values.password, 10, function(err, hash) {
if(err) return cb(err);
values.password = hash;
cb();
});
} else {
cb();
}
},
beforeUpdate: function (values, cb) {
if(typeof values.password !== 'undefined') {
// Encrypt password
bcrypt.hash(values.password, 10, function(err, hash) {
if(err) return cb(err);
values.password = hash;
cb();
});
} else {
cb();
}
}
};
| /**
* Contact.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
firstname: {
type: 'string'
},
lastname: {
type: 'string'
},
nickname: {
type: 'string',
unique: true,
required: true
},
email: {
type: 'string',
unique: true
},
password: {
type: 'string'
},
phones: {
collection: 'phone',
via: 'owner'
},
smsSend: {
collection: 'sms',
via: 'recipient'
},
smsReceipt: {
collection: 'sms',
via: 'sender'
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
// Lifecycle Callbacks
beforeCreate: function (values, cb) {
if(typeof values.password !== 'undefined') {
// Encrypt password
bcrypt.hash(values.password, 10, function(err, hash) {
if(err) return cb(err);
values.password = hash;
cb();
});
} else {
cb();
}
}
};
|
Refactor loadMap to take result |
(function() {
'use strict';
/**
* Controller for the gw app root view -- handles header bar and search bar logic
*/
/* ngInject */
function RootController($log, $state, Geocoder) {
var ctl = this;
initialize();
function initialize() {
ctl.searchText = '';
ctl.suggest = Geocoder.suggest;
ctl.search = search;
}
function search(searchText, magicKey) {
Geocoder.search(searchText, magicKey)
.then(function (results) {
if (results && results.length) {
loadMap(results[0]);
}
})
.catch(function (error) {
$log.debug('Error searching:', error);
});
}
function loadMap(result) {
$log.debug(result);
var sw = L.latLng(result.extent.ymin, result.extent.xmin);
var ne = L.latLng(result.extent.ymax, result.extent.xmax);
var bounds = L.latLngBounds(sw, ne);
$state.go('map', { bbox: bounds.toBBoxString() }, { reload: true });
}
}
angular.module('gw.views.root')
.controller('RootController', RootController);
})();
|
(function() {
'use strict';
/**
* Controller for the gw app root view -- handles header bar and search bar logic
*/
/* ngInject */
function RootController($log, $state, Geocoder) {
var ctl = this;
initialize();
function initialize() {
ctl.searchText = '';
ctl.suggest = Geocoder.suggest;
ctl.search = search;
}
function search(searchText, magicKey) {
Geocoder.search(searchText, magicKey)
.then(loadMap)
.catch(function (error) {
$log.debug('Error searching:', error);
});
}
function loadMap(results) {
if (results && results.length) {
var result = results[0];
$log.debug(result);
var sw = L.latLng(result.extent.ymin, result.extent.xmin);
var ne = L.latLng(result.extent.ymax, result.extent.xmax);
var bounds = L.latLngBounds(sw, ne);
$state.go('map', { bbox: bounds.toBBoxString() });
}
}
}
angular.module('gw.views.root')
.controller('RootController', RootController);
})();
|
Add md5 hash password encryption in SQL | <?php
foreach ( $_POST as $key => $value ) { $$key = $value; }
include 'ConnectDB.php';
session_start();
$_SESSION['username']=$user_username;
unset($_SESSION['password']);
if($user_username==""||$user_password==""){
header("location: login.php?errMsg=".urlencode("Please Fill All the Required Fields!"));
}
else{
$sql = "SELECT username, password FROM Users WHERE username = '{$user_username}';";
$password_hash = md5($user_password);
if($result = $conn->query($sql)) {
if(!$result->num_rows){
header("location: login.php?errMsg=".urlencode("Username not Found"));
}
else
while($row = $result->fetch_assoc())
{
if("{$row['password']}"==$password_hash){
$_SESSION['password'] = $password_hash;
header("location: portal.php");
}
else {
header("location: login.php?errMsg=".urlencode("Wrong Password!"));
}
}
}
else {
header("location: login.php?errMsg=".urlencode("Query on Database Could not be run!"));
}
}
?>
| <?php
foreach ( $_POST as $key => $value ) { $$key = $value; }
include 'ConnectDB.php';
session_start();
$_SESSION['username']=$user_username;
unset($_SESSION['password']);
if($user_username==""||$user_password==""){
header("location: login.php?errMsg=".urlencode("Please Fill All the Required Fields!"));
}
else{
$sql = "SELECT username, password FROM Users WHERE username = '{$user_username}';";
if($result = $conn->query($sql)) {
if(!$result->num_rows){
header("location: login.php?errMsg=".urlencode("Username not Found"));
}
else
while($row = $result->fetch_assoc())
{
if("{$row['password']}"==$user_password){
$_SESSION['password'] = $user_password;
header("location: portal.php");
}
else {
header("location: login.php?errMsg=".urlencode("Wrong Password!"));
}
}
}
else {
header("location: login.php?errMsg=".urlencode("Query on Database Could not be run!"));
}
}
?>
|
Fix resource paths for user file attachments.
When I fixed the names in the user file attachments resource to make it
available within the API templates, I neglected to actually test the javascript
in the Review Board UI, which was still using the old paths and names. This
change fixes it.
Testing done:
Drag-and-dropped an image into a review header.
Reviewed at https://reviews.reviewboard.org/r/8860/ | /**
* A new or existing user file attachment.
*
* Model Attributes:
* caption (string):
* The file attachment's caption.
*
* userName (string):
* The username of the owner of the file attachment.
*
* downloadURL (string):
* The URL to download the file, for existing file attachments.
*
* file (file):
* The file to upload. Only works for newly created
* UserFileAttachments.
*
* filename (string):
* The name of the file, for existing file attachments.
*/
RB.UserFileAttachment = RB.BaseResource.extend({
defaults() {
return _.defaults({
caption: null,
userName: '',
downloadURL: null,
file: null,
filename: null
}, RB.BaseResource.prototype.defaults());
},
rspNamespace: 'user_file_attachment',
payloadFileKeys: ['path'],
attrToJsonMap: {
downloadURL: 'absolute_url',
file: 'path'
},
serializedAttrs: [
'caption',
'file'
],
deserializedAttrs: [
'caption',
'downloadURL',
'filename'
],
serializers: {
file: RB.JSONSerializers.onlyIfValue
},
/**
* Return the URL to use for syncing the model.
*
* Returns:
* string:
* The URL for the resource.
*/
url() {
const username = this.get('userName');
const url = `${SITE_ROOT}api/users/${username}/user-file-attachments/`;
return this.isNew() ? url : `${url}${this.id}/`;
}
});
| /**
* A new or existing user file attachment.
*
* Model Attributes:
* caption (string):
* The file attachment's caption.
*
* userName (string):
* The username of the owner of the file attachment.
*
* downloadURL (string):
* The URL to download the file, for existing file attachments.
*
* file (file):
* The file to upload. Only works for newly created
* UserFileAttachments.
*
* filename (string):
* The name of the file, for existing file attachments.
*/
RB.UserFileAttachment = RB.BaseResource.extend({
defaults() {
return _.defaults({
caption: null,
userName: '',
downloadURL: null,
file: null,
filename: null
}, RB.BaseResource.prototype.defaults());
},
rspNamespace: 'file_attachment',
payloadFileKeys: ['path'],
attrToJsonMap: {
downloadURL: 'absolute_url',
file: 'path'
},
serializedAttrs: [
'caption',
'file'
],
deserializedAttrs: [
'caption',
'downloadURL',
'filename'
],
serializers: {
file: RB.JSONSerializers.onlyIfValue
},
/**
* Return the URL to use for syncing the model.
*
* Returns:
* string:
* The URL for the resource.
*/
url() {
const username = this.get('userName');
const url = `${SITE_ROOT}api/users/${username}/file-attachments/`;
return this.isNew() ? url : `${url}${this.id}/`;
}
});
|
Add client initial request through component did mount | import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as profileActions from '../../modules/profile';
class UserPicPage extends Component {
componentDidMount() {
this.props.fetchProfile();
}
static needs = [profileActions.fetchProfile]
render() {
const {
imgUrl,
followers,
hasError,
} = this.props;
const errorHtml = hasError ? (<div>No Such User!!</div>) : undefined;
return (
<div className="user-pic-page">
<div>Followers: {followers}</div>
<img src={imgUrl} />
{errorHtml}
</div>
);
}
}
UserPicPage.propTypes = {
name: PropTypes.string,
imgUrl: PropTypes.string,
followers: PropTypes.number,
hasError: PropTypes.bool,
fetchProfile: PropTypes.func,
};
function mapStateToProps(state) {
return Object.assign(
{},
state.profile
);
}
function mapDispatchToProps(dispatch) {
return Object.assign(
{},
bindActionCreators(profileActions, dispatch)
);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserPicPage);
| import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as profileActions from '../../modules/profile';
class UserPicPage extends Component {
static needs = [profileActions.fetchProfile]
render() {
const {
imgUrl,
followers,
hasError,
} = this.props;
const errorHtml = hasError ? (<div>No Such User!!</div>) : undefined;
return (
<div className="user-pic-page">
<div>Followers: {followers}</div>
<img src={imgUrl} />
{errorHtml}
</div>
);
}
}
UserPicPage.propTypes = {
name: PropTypes.string,
imgUrl: PropTypes.string,
followers: PropTypes.number,
hasError: PropTypes.bool,
fetchProfile: PropTypes.func,
};
function mapStateToProps(state) {
return Object.assign(
{},
state.profile
);
}
function mapDispatchToProps(dispatch) {
return Object.assign(
{},
bindActionCreators(profileActions, dispatch)
);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserPicPage);
|
FIX: Check for fillOpacity when fill is undefined
Fix for condition where both fill and fillOpacity properties are
undefined | import rgba from './rgba';
import {
ART
} from 'react-native';
let {
LinearGradient,
RadialGradient
} = ART;
let fillPatterns = {};
let fillReg = /^url\(#(\w+?)\)$/;
function isGradient(obj) {
return obj instanceof LinearGradient || obj instanceof RadialGradient;
}
export default function (props) {
let {fill} = props;
if (fill) {
if (isGradient(fill)) {
return fill;
}
let fillOpacity = +props.fillOpacity;
if (isNaN(fillOpacity)) {
fillOpacity = 1;
}
// 尝试匹配 fill="url(#pattern)"
let matched = fill.match(fillReg);
if (matched) {
let patternName = `${matched[1]}:${props.svgId}`;
let pattern = fillPatterns[patternName];
if (pattern) {
if (pattern.length === 2) {
let dimensions = this.getBoundingBox();
return pattern(dimensions, fillOpacity);
} else {
return pattern(fillOpacity);
}
}
return null;
}
return rgba(props.fill, fillOpacity);
} else if (props.fill === undefined) {
let fillOpacity = +props.fillOpacity;
if (isNaN(fillOpacity)) {
fillOpacity = 1;
}
return rgba('#000', fillOpacity);
} else {
return null;
}
}
function set(id, pattern) {
fillPatterns[id] = pattern;
}
function remove(id) {
delete fillPatterns[id];
}
export {
set,
remove
}
| import rgba from './rgba';
import {
ART
} from 'react-native';
let {
LinearGradient,
RadialGradient
} = ART;
let fillPatterns = {};
let fillReg = /^url\(#(\w+?)\)$/;
function isGradient(obj) {
return obj instanceof LinearGradient || obj instanceof RadialGradient;
}
export default function (props) {
let {fill} = props;
if (fill) {
if (isGradient(fill)) {
return fill;
}
let fillOpacity = +props.fillOpacity;
if (isNaN(fillOpacity)) {
fillOpacity = 1;
}
// 尝试匹配 fill="url(#pattern)"
let matched = fill.match(fillReg);
if (matched) {
let patternName = `${matched[1]}:${props.svgId}`;
let pattern = fillPatterns[patternName];
if (pattern) {
if (pattern.length === 2) {
let dimensions = this.getBoundingBox();
return pattern(dimensions, fillOpacity);
} else {
return pattern(fillOpacity);
}
}
return null;
}
return rgba(props.fill, fillOpacity);
} else if (props.fill === undefined) {
return rgba('#000', fillOpacity);
} else {
return null;
}
}
function set(id, pattern) {
fillPatterns[id] = pattern;
}
function remove(id) {
delete fillPatterns[id];
}
export {
set,
remove
}
|
Remove box prefix from config | /*
* Things Gateway Default Configuration.
*
* 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/.
*/
'use strict';
module.exports = {
// Expose CLI
cli: true,
ports: {
https: 4443,
http: 8080
},
adapters : {
gpio: {
enabled: false,
path: './adapters/gpio',
pins: {
18: {
name: 'led',
direction: 'out', // 'in' or 'out'
value: 0 // value on required when 'direction' is 'out'
},
}
},
zigbee: {
enabled: true,
path: './adapters/zigbee',
},
zwave: {
enabled: true,
path: './adapters/zwave',
}
},
adapterManager: {
pairingTimeout: 3 * 60, // seconds
},
database: {
filename: './db.sqlite3',
removeBeforeOpen: false,
},
authentication: {
enabled: true,
defaultUser: null,
secret: 'top secret 51' // DO NOT USE THIS IN PRODUCTION
},
ssltunnel: {
enabled: true,
registration_endpoint: 'mozilla-iot.org',
domain: 'mozilla-iot.org',
pagekite_cmd: './pagekite.py',
port: 443
}
};
| /*
* Things Gateway Default Configuration.
*
* 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/.
*/
'use strict';
module.exports = {
// Expose CLI
cli: true,
ports: {
https: 4443,
http: 8080
},
adapters : {
gpio: {
enabled: false,
path: './adapters/gpio',
pins: {
18: {
name: 'led',
direction: 'out', // 'in' or 'out'
value: 0 // value on required when 'direction' is 'out'
},
}
},
zigbee: {
enabled: true,
path: './adapters/zigbee',
},
zwave: {
enabled: true,
path: './adapters/zwave',
}
},
adapterManager: {
pairingTimeout: 3 * 60, // seconds
},
database: {
filename: './db.sqlite3',
removeBeforeOpen: false,
},
authentication: {
enabled: true,
defaultUser: null,
secret: 'top secret 51' // DO NOT USE THIS IN PRODUCTION
},
ssltunnel: {
enabled: true,
registration_endpoint: 'mozilla-iot.org',
domain: 'box.mozilla-iot.org',
pagekite_cmd: './pagekite.py',
port: 443
}
};
|
Use of commonjs import/export syntaxe | const mongo = require('../db')
const utils = require('../utils')
/**
* User :: {
* id: String,
* username: String,
* password: String,
* createdAt: String
* }
*/
/** String -> String -> User */
function createUser(username, password) {
return {
"id": utils.UUID(),
"username": username,
"password": crypto.createHmac('sha256', password).update(password).digest('base64'),
"createdAt": Date.now()
}
}
/** String -> Promise(Boolean, Error) */
function userExist(username) {
return mongo.connect()
.then(db => db.collection('users').findOne({ username })
.then(mongo.close(db)))
.then(user => user != null)
}
/** User -> Promise(User, Error) */
function saveUser(user) {
return mongo.connect()
.then(db => db.collection('users').insertOne(user)
.then(mongo.close(db)))
.then(() => user)
}
/** String -> String -> Promise({id, username, token : String}, Error) */
exports.register = function register(username, password) {
userExist(username)
.then(exist => exist ?
Promise.reject("The user already exist") :
Promise.resolve(createUser(username, password)))
.then(saveUser)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user)
}))
}
| import mongo from '../db'
import utils from '../utils'
import crypto from 'crypto'
/**
* User :: {
* id: String,
* username: String,
* password: String,
* createdAt: String
* }
*/
/** String -> String -> User */
function createUser(username, password) {
return {
"id": utils.UUID(),
"username": username,
"password": crypto.createHmac('sha256', password).update(password).digest('base64'),
"createdAt": Date.now()
}
}
/** String -> Promise(Boolean, Error) */
function userExist(username) {
return mongo.connect()
.then(db => db.collection('users').findOne({ username })
.then(mongo.close(db)))
.then(user => user != null)
}
/** User -> Promise(User, Error) */
function saveUser(user) {
return mongo.connect()
.then(db => db.collection('users').insertOne(user)
.then(mongo.close(db)))
.then(() => user)
}
/** String -> String -> Promise({id, username, token : String}, Error) */
export function register(username, password) {
userExist(username)
.then(exist => exist ?
Promise.reject("The user already exist") :
Promise.resolve(createUser(username, password)))
.then(saveUser)
.then(user => ({
id: user.id,
username: user.username,
token: utils.genToken(user)
}))
}
|
Fix shape item promise handler test suite | // DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
var expect = require('chai').expect;
describe('Shape Item Promise Handler', function() {
it('changes the promise shape into a content shape and runs a new rendering life cycle for the item', function(done) {
var promiseShape = {
meta: {type: 'shape-item-promise'},
id: 'widget:bar'
};
var item = {id: 'widget:bar', meta: {type: 'foo'}};
var context = {
shape: promiseShape,
renderStream: {},
scope: {
require: function(service) {
switch(service) {
case 'storage-manager':
return {
getAvailableItem: function () {
return item;
}
};
case 'shape':
return require('../services/shape');
case 'content-manager':
return {
getPartNames: function() {
return [];
}
};
}
},
lifecycle: function() {
return function(context, next) {
expect(context.shape.temp.item).to.equal(item);
next();
}
}
}
};
var ShapeItemPromiseHandler = require('../services/shape-item-promise-handler');
ShapeItemPromiseHandler.handle(context, function() {
expect(context.shape.meta.type).to.equal('content');
expect(context.shape.temp.item).to.equal(item);
expect(context.shape.meta.alternates).to.deep.equal(['content-foo', 'content-widget']);
done();
});
});
});
| // DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
var expect = require('chai').expect;
describe('Shape Item Promise Handler', function() {
it('changes the promise shape into a content shape and runs a new rendering life cycle for the item', function(done) {
var promiseShape = {
meta: {type: 'shape-item-promise'},
id: 'widget:bar'
};
var item = {id: 'widget:bar', meta: {type: 'foo'}};
var context = {
shape: promiseShape,
renderStream: {},
scope: {
require: function(service) {
switch(service) {
case 'storage-manager':
return {
getAvailableItem: function () {
return item;
}
};
case 'shape':
return require('../services/shape');
}
},
lifecycle: function() {
return function(context, next) {
expect(context.shape.temp.item).to.equal(item);
next();
}
}
}
};
var ShapeItemPromiseHandler = require('../services/shape-item-promise-handler');
ShapeItemPromiseHandler.handle(context, function() {
expect(context.shape.meta.type).to.equal('content');
expect(context.shape.temp.item).to.equal(item);
expect(context.shape.meta.alternates).to.deep.equal(['content-foo', 'content-widget']);
done();
});
});
});
|
Use the 'with' keyword for managing template file pointers | from django import template
from ..conf import conf
from ..loading import find, MustacheJSTemplateNotFound
register = template.Library()
class MustacheJSNode(template.Node):
def __init__(self, name):
self.name = template.Variable(name)
def render(self, context):
name = self.name.resolve(context)
try:
filepath = find(name)
with open(filepath, "r") as fp:
output = fp.read()
output = output.replace('\\', r'\\')
output = output.replace('\n', r'\n')
output = output.replace("'", r"\'")
output = ("<script>Mustache.TEMPLATES=Mustache.TEMPLATES||{};"
+ "Mustache.TEMPLATES['{0}']='".format(name)
+ output + "';</script>")
except (IOError, MustacheJSTemplateNotFound):
output = ""
if conf.DEBUG:
raise
return output
@register.tag
def mustachejs(parser, token):
"""
Finds the MustacheJS template for the given name and renders it surrounded by
the requisite MustacheJS <script> tags.
"""
bits = token.contents.split()
if len(bits) not in [2, 3]:
raise template.TemplateSyntaxError(
"'mustachejs' tag takes one argument: the name/id of the template")
return MustacheJSNode(bits[1])
| from django import template
from ..conf import conf
from ..loading import find, MustacheJSTemplateNotFound
register = template.Library()
class MustacheJSNode(template.Node):
def __init__(self, name):
self.name = template.Variable(name)
def render(self, context):
name = self.name.resolve(context)
try:
filepath = find(name)
fp = open(filepath, "r")
output = fp.read()
output = output.replace('\\', r'\\')
output = output.replace('\n', r'\n')
output = output.replace("'", r"\'")
fp.close()
output = ("<script>Mustache.TEMPLATES=Mustache.TEMPLATES||{};"
+ "Mustache.TEMPLATES['{0}']='".format(name)
+ output + "';</script>")
except (IOError, MustacheJSTemplateNotFound):
output = ""
if conf.DEBUG:
raise
return output
@register.tag
def mustachejs(parser, token):
"""
Finds the MustacheJS template for the given name and renders it surrounded by
the requisite MustacheJS <script> tags.
"""
bits = token.contents.split()
if len(bits) not in [2, 3]:
raise template.TemplateSyntaxError(
"'mustachejs' tag takes one argument: the name/id of the template")
return MustacheJSNode(bits[1])
|
Update iframe url (the poor video was removed) | import React from 'react';
import { storiesOf } from '@kadira/storybook';
import AspectRatio from '../index';
import '../../aspect-ratio.css';
storiesOf('AspectRatio', module)
.add('Image', () => (
<div className="card">
<h2>Image with Aspect Ratio</h2>
<AspectRatio ratio="3/4" style={{ maxWidth: '400px' }}>
<img src="https://c1.staticflickr.com/4/3896/14550191836_cc0675d906.jpg" alt="demo" />
</AspectRatio>
</div>
))
.add('Background Image', () => (
<div className="card">
<h2>Background image with aspect ratio</h2>
<AspectRatio
ratio="3/4"
style={{
maxWidth: '300px',
backgroundImage: 'url(https://c1.staticflickr.com/4/3896/14550191836_cc0675d906.jpg)',
backgroundSize: 'cover',
}}
/>
</div>
))
.add('Iframe', () => (
<div className="card">
<h2>Iframe with aspect ratio</h2>
<AspectRatio ratio="560/315" style={{ maxWidth: '560px' }}>
<iframe src="https://www.youtube.com/embed/Sv6dMFF_yts" frameBorder="0" allowFullScreen />
</AspectRatio>
</div>
));
| import React from 'react';
import { storiesOf } from '@kadira/storybook';
import AspectRatio from '../index';
import '../../aspect-ratio.css';
storiesOf('AspectRatio', module)
.add('Image', () => (
<div className="card">
<h2>Image with Aspect Ratio</h2>
<AspectRatio ratio="3/4" style={{ maxWidth: '400px' }}>
<img src="https://c1.staticflickr.com/4/3896/14550191836_cc0675d906.jpg" alt="demo" />
</AspectRatio>
</div>
))
.add('Background Image', () => (
<div className="card">
<h2>Background image with aspect ratio</h2>
<AspectRatio
ratio="3/4"
style={{
maxWidth: '300px',
backgroundImage: 'url(https://c1.staticflickr.com/4/3896/14550191836_cc0675d906.jpg)',
backgroundSize: 'cover',
}}
/>
</div>
))
.add('Iframe', () => (
<div className="card">
<h2>Iframe with aspect ratio</h2>
<AspectRatio ratio="560/315" style={{ maxWidth: '560px' }}>
<iframe src="https://www.youtube.com/embed/Bku71V5f66g" frameBorder="0" allowFullScreen />
</AspectRatio>
</div>
));
|
Allow viewport to be initialized with a pre-existing camera model | cinema.views.ViewportView = Backbone.View.extend({
initialize: function (opts) {
this.$el.html(cinema.app.templates.viewport());
this.camera = opts.camera || new cinema.models.CameraModel({
info: this.model
});
this.renderView = new cinema.views.VisualizationCanvasWidget({
el: this.$('.c-app-renderer-container'),
model: this.model,
camera: this.camera
}).render();
this.mouseInteractor = new cinema.utilities.RenderViewMouseInteractor({
renderView: this.renderView,
camera: this.camera
}).enableMouseWheelZoom({
maxZoomLevel: 10,
zoomIncrement: 0.05,
invertControl: false
}).enableDragPan({
keyModifiers: cinema.keyModifiers.SHIFT
}).enableDragRotation({
keyModifiers: null
});
this.listenTo(this.camera, 'change', this._refreshCamera);
},
updateQuery: function (query) {
this.renderView.updateQuery(query);
},
_refreshCamera: function () {
this.renderView.showViewpoint();
}
});
| cinema.views.ViewportView = Backbone.View.extend({
initialize: function () {
this.$el.html(cinema.app.templates.viewport());
this.camera = new cinema.models.CameraModel({
info: this.model
});
this.renderView = new cinema.views.VisualizationCanvasWidget({
el: this.$('.c-app-renderer-container'),
model: this.model,
camera: this.camera
}).render();
this.mouseInteractor = new cinema.utilities.RenderViewMouseInteractor({
renderView: this.renderView,
camera: this.camera
}).enableMouseWheelZoom({
maxZoomLevel: 10,
zoomIncrement: 0.05,
invertControl: false
}).enableDragPan({
keyModifiers: cinema.keyModifiers.SHIFT
}).enableDragRotation({
keyModifiers: null
});
this.listenTo(this.camera, 'change', this._refreshCamera);
},
updateQuery: function (query) {
this.renderView.updateQuery(query);
},
_refreshCamera: function () {
this.renderView.showViewpoint();
},
});
|
Fix refresh button highlighted after click | import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import ContainerFluid from '../ContainerFluid'
import VmUserMessages from '../VmUserMessages'
import UserMenu from './UserMenu'
import { getAllVms } from '../../actions/vm'
/**
* Main application header on top of the page
*/
const VmsPageHeader = ({ title, onRefresh }) => {
const titleStyle = { padding: '0px 0 5px' }
return (
<nav className='navbar navbar-default navbar-pf navbar-fixed-top'>
<ContainerFluid>
<div className='navbar-header'>
<a className='navbar-brand' style={titleStyle} href='/'>{title}</a>
</div>
<ul className='nav navbar-nav navbar-utility'>
<li>
<a href='#' onClick={onRefresh}>
<span className='fa fa-refresh' /> Refresh
</a>
</li>
<UserMenu />
<VmUserMessages />
</ul>
</ContainerFluid>
</nav>
)
}
VmsPageHeader.propTypes = {
title: PropTypes.string.isRequired,
onRefresh: PropTypes.func.isRequired,
}
export default connect(
(state) => ({ }),
(dispatch) => ({
onRefresh: () => dispatch(getAllVms({ shallowFetch: false })),
})
)(VmsPageHeader)
| import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import ContainerFluid from '../ContainerFluid'
import VmUserMessages from '../VmUserMessages'
import UserMenu from './UserMenu'
import { getAllVms } from '../../actions/vm'
/**
* Main application header on top of the page
*/
const VmsPageHeader = ({ title, onRefresh }) => {
const titleStyle = { padding: '0px 0 5px' }
return (
<nav className='navbar navbar-default navbar-pf navbar-fixed-top'>
<ContainerFluid>
<div className='navbar-header'>
<a className='navbar-brand' style={titleStyle} href='/'>{title}</a>
</div>
<ul className='nav navbar-nav navbar-utility'>
<li>
<a href='#' data-toggle='dropdown' onClick={onRefresh}>
<span className='fa fa-refresh' /> Refresh
</a>
</li>
<UserMenu />
<VmUserMessages />
</ul>
</ContainerFluid>
</nav>
)
}
VmsPageHeader.propTypes = {
title: PropTypes.string.isRequired,
onRefresh: PropTypes.func.isRequired,
}
export default connect(
(state) => ({ }),
(dispatch) => ({
onRefresh: () => dispatch(getAllVms({ shallowFetch: false })),
})
)(VmsPageHeader)
|
Add possibility to open comment form by clicking anywhere in the diff line | angular.module('codebrag.commits.comments')
.directive('commentable', function($compile, events) {
var template = $('#inlineCommentForm').html();
return {
restrict: 'A',
link: function(scope, element) {
var alreadyOpened = false;
var onclick = function() {
if(alreadyOpened) {
_locateCommentFormRow().show();
return;
}
element.append(template);
$compile($('tr.comment-form', element).contents())(scope);
alreadyOpened = true;
scope.$digest();
};
var codeLine = $('td.diff-line-code', element);
var commentBox = $('a.comment', element);
codeLine.bind('click', onclick);
commentBox.bind('click', onclick);
scope.$on(events.closeForm, function(event) {
event.stopPropagation();
_locateCommentFormRow().hide();
});
function _locateCommentFormRow() {
return element.find('tr.comment-form');
}
}
}
});
| angular.module('codebrag.commits.comments')
.directive('commentable', function($compile, events) {
var template = $('#inlineCommentForm').html();
return {
restrict: 'A',
link: function(scope, element, attrs) {
var alreadyOpened = false;
var codeLine = $('a.comment', element);
codeLine.bind('click', function() {
if(alreadyOpened) {
_locateCommentFormRow().show();
return;
}
element.append(template);
$compile($('tr.comment-form', element).contents())(scope);
alreadyOpened = true;
scope.$digest();
});
scope.$on(events.closeForm, function(event) {
event.stopPropagation();
_locateCommentFormRow().hide();
});
function _locateCommentFormRow() {
return element.find('tr.comment-form');
}
}
}
});
|
Fix deprecation error because missing the static keyword | <?php
namespace PastryBag\Di;
use Aura\Di\Container;
use Aura\Di\ContainerBuilder;
use Aura\Di\ContainerConfigInterface;
class PastryBag
{
/**
* The current container instance
* @var Container
*/
protected static $instance;
/**
* @param array $configClasses
* @return Container
*/
public static function create(array $configClasses = [])
{
$builder = new ContainerBuilder();
$di = $builder->newInstance($builder::AUTO_RESOLVE);
foreach ($configClasses as $configClass) {
/** @var ContainerConfigInterface $config */
$config = static::getConfig($configClass);
$config->define($di);
}
return $di;
}
/**
* @param Container|null $instance
* @return Container
*/
public static function container(Container $instance = null)
{
if ($instance !== null) {
static::$instance = $instance;
}
return static::$instance;
}
/**
*
* Get config object from connfig class or return the object
*
* @param mixed $config name of class to instantiate
*
* @return Object
* @throws \InvalidArgumentException if invalid config
*
* @access protected
*/
protected static function getConfig($config)
{
if (is_string($config)) {
$config = new $config;
}
if (!$config instanceof ContainerConfigInterface) {
throw new \InvalidArgumentException(
'Container configs must implement ContainerConfigInterface'
);
}
return $config;
}
}
| <?php
namespace PastryBag\Di;
use Aura\Di\Container;
use Aura\Di\ContainerBuilder;
use Aura\Di\ContainerConfigInterface;
class PastryBag
{
/**
* The current container instance
* @var Container
*/
protected static $instance;
/**
* @param array $configClasses
* @return Container
*/
public static function create(array $configClasses = [])
{
$builder = new ContainerBuilder();
$di = $builder->newInstance($builder::AUTO_RESOLVE);
foreach ($configClasses as $configClass) {
/** @var ContainerConfigInterface $config */
$config = static::getConfig($configClass);
$config->define($di);
}
return $di;
}
/**
* @param Container|null $instance
* @return Container
*/
public static function container(Container $instance = null)
{
if ($instance !== null) {
static::$instance = $instance;
}
return static::$instance;
}
/**
*
* Get config object from connfig class or return the object
*
* @param mixed $config name of class to instantiate
*
* @return Object
* @throws \InvalidArgumentException if invalid config
*
* @access protected
*/
protected function getConfig($config)
{
if (is_string($config)) {
$config = new $config;
}
if (!$config instanceof ContainerConfigInterface) {
throw new \InvalidArgumentException(
'Container configs must implement ContainerConfigInterface'
);
}
return $config;
}
}
|
Fix file level doc for test class
Fix DisallowLongArraySyntax to DisallowShortArraySyntax. | <?php
/**
* Unit test class for the DisallowShortArraySyntax sniff.
*
* @author Greg Sherwood <[email protected]>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Standards\Generic\Tests\Arrays;
use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;
class DisallowShortArraySyntaxUnitTest extends AbstractSniffUnitTest
{
/**
* Returns the lines where errors should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @return array<int, int>
*/
public function getErrorList()
{
return array(
3 => 1,
5 => 1,
7 => 1,
8 => 1,
);
}//end getErrorList()
/**
* Returns the lines where warnings should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of warnings that should occur on that line.
*
* @return array<int, int>
*/
public function getWarningList()
{
return array();
}//end getWarningList()
}//end class
| <?php
/**
* Unit test class for the DisallowLongArraySyntax sniff.
*
* @author Greg Sherwood <[email protected]>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer\Standards\Generic\Tests\Arrays;
use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;
class DisallowShortArraySyntaxUnitTest extends AbstractSniffUnitTest
{
/**
* Returns the lines where errors should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @return array<int, int>
*/
public function getErrorList()
{
return array(
3 => 1,
5 => 1,
7 => 1,
8 => 1,
);
}//end getErrorList()
/**
* Returns the lines where warnings should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of warnings that should occur on that line.
*
* @return array<int, int>
*/
public function getWarningList()
{
return array();
}//end getWarningList()
}//end class
|
Change eslint indentation style to 2 spaces | module.exports = {
"env": {
"es6": true,
"node": true
},
"extends": "airbnb-base",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error", 2,
{ "SwitchCase": 1 }
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-console": "off",
"linebreak-style": "off",
"max-len": [
"warn", 120, 2,
{ ignoreComments: true }
],
"quote-props": [
"warn",
"consistent-as-needed"
],
"no-cond-assign": [
"off",
"except-parens"
],
"radix": "off",
"space-infix-ops": "off",
"no-unused-vars": [
"warn",
{
"vars": "local",
"args": "none",
"argsIgnorePattern": "next"
}
],
"default-case": "error",
"no-else-return": "off",
"no-param-reassign": "off",
"quotes": "off",
"space-before-function-paren": [
"error",
{
"anonymous": "never",
"named": "never",
"asyncArrow": "ignore"
}
],
eqeqeq: ["error", "smart"]
}
}; | module.exports = {
"env": {
"es6": true,
"node": true
},
"extends": "airbnb-base",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"error", 4,
{ "SwitchCase": 1 }
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-console": "off",
"linebreak-style": "off",
"max-len": [
"warn", 120, 4,
{ ignoreComments: true }
],
"quote-props": [
"warn",
"consistent-as-needed"
],
"no-cond-assign": [
"off",
"except-parens"
],
"radix": "off",
"space-infix-ops": "off",
"no-unused-vars": [
"warn",
{
"vars": "local",
"args": "none",
"argsIgnorePattern": "next"
}
],
"default-case": "error",
"no-else-return": "off",
"no-param-reassign": "off",
"quotes": "off",
"space-before-function-paren": [
"error",
{
"anonymous": "never",
"named": "never",
"asyncArrow": "ignore"
}
],
eqeqeq: ["error", "smart"]
}
}; |
Allow HTTP auth during tests | from django.conf import settings
from django.utils.translation import ugettext as _
from django_digest import HttpDigestAuthenticator
from rest_framework.authentication import (
BaseAuthentication, get_authorization_header,
BasicAuthentication)
from rest_framework.exceptions import AuthenticationFailed
class DigestAuthentication(BaseAuthentication):
def __init__(self):
self.authenticator = HttpDigestAuthenticator()
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'digest':
return None
if self.authenticator.authenticate(request):
return request.user, None
else:
raise AuthenticationFailed(
_(u"Invalid username/password"))
def authenticate_header(self, request):
response = self.authenticator.build_challenge_response()
return response['WWW-Authenticate']
class HttpsOnlyBasicAuthentication(BasicAuthentication):
def authenticate(self, request):
# The parent class can discern whether basic authentication is even
# being attempted; if it isn't, we need to gracefully defer to other
# authenticators
user_auth = super(HttpsOnlyBasicAuthentication, self).authenticate(
request)
if settings.TESTING_MODE is False and \
user_auth is not None and not request.is_secure():
# Scold the user if they provided correct credentials for basic
# auth but didn't use HTTPS
raise AuthenticationFailed(_(
u'Using basic authentication without HTTPS transmits '
u'credentials in clear text! You MUST connect via HTTPS '
u'to use basic authentication.'
))
return user_auth
| from django.utils.translation import ugettext as _
from django_digest import HttpDigestAuthenticator
from rest_framework.authentication import (
BaseAuthentication, get_authorization_header,
BasicAuthentication)
from rest_framework.exceptions import AuthenticationFailed
class DigestAuthentication(BaseAuthentication):
def __init__(self):
self.authenticator = HttpDigestAuthenticator()
def authenticate(self, request):
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'digest':
return None
if self.authenticator.authenticate(request):
return request.user, None
else:
raise AuthenticationFailed(
_(u"Invalid username/password"))
def authenticate_header(self, request):
response = self.authenticator.build_challenge_response()
return response['WWW-Authenticate']
class HttpsOnlyBasicAuthentication(BasicAuthentication):
def authenticate(self, request):
# The parent class can discern whether basic authentication is even
# being attempted; if it isn't, we need to gracefully defer to other
# authenticators
user_auth = super(HttpsOnlyBasicAuthentication, self).authenticate(
request)
if user_auth is not None and not request.is_secure():
# Scold the user if they provided correct credentials for basic
# auth but didn't use HTTPS
raise AuthenticationFailed(_(
u'Using basic authentication without HTTPS transmits '
u'credentials in clear text! You MUST connect via HTTPS '
u'to use basic authentication.'
))
return user_auth
|
Add optimizer to the API
Former-commit-id: 3e06c976ad6a7d4409817fb0fa1472237bfa28b7 | from .io import preprocess
from .train import train
from .network import mlp
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, batch_size=32, optimizer=None, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
net = mlp(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
loss_type=type)
model, encoder, decoder, loss, extras = net['model'], net['encoder'], \
net['decoder'], net['loss'], \
net['extra_models']
losses = train(x, model, loss,
learning_rate=learning_rate,
epochs=epochs, batch_size=batch_size,
optimizer=optimizer, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
| from .io import preprocess
from .train import train
from .network import mlp
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, batch_size=32, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
net = mlp(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
loss_type=type)
model, encoder, decoder, loss, extras = net['model'], net['encoder'], \
net['decoder'], net['loss'], \
net['extra_models']
losses = train(x, model, loss,
learning_rate=learning_rate,
epochs=epochs, batch_size=batch_size,
**kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
Remove verbose logging on PlayerActionService | <?php
/*
* Spring Signage Ltd - http://www.springsignage.com
* Copyright (C) 2016 Spring Signage Ltd
* (Xmr.php)
*/
namespace Xibo\Middleware;
use Slim\Middleware;
use Xibo\Service\PlayerActionService;
/**
* Class Xmr
* @package Xibo\Middleware
*/
class Xmr extends Middleware
{
public function call()
{
$app = $this->getApplication();
$app->hook('slim.before', function() {
$app = $this->app;
// $app->logService->debug('Registering Player Action Service with DI');
// Player Action Helper
$app->container->singleton('playerActionService', function() use ($app) {
// $app->logService->debug('New Player Action Service from DI');
return new PlayerActionService($app->configService, $app->logService);
});
});
$this->next->call();
// Handle player actions
if ($app->playerActionService != null) {
try {
$app->playerActionService->processQueue();
} catch (\Exception $e) {
$app->logService->error('Unable to Process Queue of Player actions due to %s.', $e->getMessage());
$app->logService->debug($e->getTraceAsString());
}
}
}
} | <?php
/*
* Spring Signage Ltd - http://www.springsignage.com
* Copyright (C) 2016 Spring Signage Ltd
* (Xmr.php)
*/
namespace Xibo\Middleware;
use Slim\Middleware;
use Xibo\Service\PlayerActionService;
/**
* Class Xmr
* @package Xibo\Middleware
*/
class Xmr extends Middleware
{
public function call()
{
$app = $this->getApplication();
$app->hook('slim.before', function() {
$app = $this->app;
//$app->logService->debug('Registering Player Action Service with DI');
// Player Action Helper
$app->container->singleton('playerActionService', function() use ($app) {
$app->logService->debug('New Player Action Service from DI');
return new PlayerActionService($app->configService, $app->logService);
});
});
$this->next->call();
// Handle player actions
if ($app->playerActionService != null) {
try {
$app->playerActionService->processQueue();
} catch (\Exception $e) {
$app->logService->error('Unable to Process Queue of Player actions due to %s.', $e->getMessage());
$app->logService->debug($e->getTraceAsString());
}
}
}
} |
Add validate published on templatetag get all articlebox | # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = slug + '-' + channel_slug
try:
box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug,
date_available__lte=timezone.now(),
published=True)
except ArticleBox.DoesNotExist:
box = None
t = template.loader.get_template('articles/articlebox_detail.html')
if template_name:
t = template.loader.get_template(template_name)
return t.render(template.Context({'articlebox': box, 'slug': slug}))
@register.simple_tag
def get_all_articlebox(channel_slug, template_name=None):
boxes = ArticleBox.objects.filter(site=settings.SITE_ID,
date_available__lte=timezone.now(),
published=True,
channel__slug=channel_slug)
t = template.loader.get_template('articles/articlebox_list.html')
if template_name:
t = template.loader.get_template(template_name)
return t.render(template.Context({'articleboxes': boxes}))
| # -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.articles.models import ArticleBox
register = template.Library()
@register.simple_tag
def get_articlebox(slug, channel_slug=None, template_name=None):
if channel_slug:
slug = slug + '-' + channel_slug
try:
box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug,
date_available__lte=timezone.now(),
published=True)
except ArticleBox.DoesNotExist:
box = None
t = template.loader.get_template('articles/articlebox_detail.html')
if template_name:
t = template.loader.get_template(template_name)
return t.render(template.Context({'articlebox': box, 'slug': slug}))
@register.simple_tag
def get_all_articlebox(channel_slug, template_name=None):
boxes = ArticleBox.objects.filter(site=settings.SITE_ID,
channel__slug=channel_slug)
t = template.loader.get_template('articles/articlebox_list.html')
if template_name:
t = template.loader.get_template(template_name)
return t.render(template.Context({'articleboxes': boxes}))
|
Add step command to help | import backend.Core;
import java.io.IOException;
import parse.GreetParser;
import parse.StepParser;
public class App {
public String getGreeting() {
return "Hello world.";
}
/**
* Main entry point to G2Tutorial.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
if (args[0].equals("greet")) {
// Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
} else if (args[0].equals("init")) {
// Initializes an empty git repo
try {
Core.initCore();
} catch (IOException e) {
System.err.println("Could not init g2t");
e.printStackTrace();
}
System.exit(0);
} else if (args[0].equals("step")) {
// Commits the current changes as a step and starts a new step
Core c = null;
try {
c = new Core();
} catch (IOException e) {
System.err.println("g2t is not initialized");
e.printStackTrace();
}
StepParser p = new StepParser(args, c);
p.parse();
} else {
System.out.println("Available commands:\n"
+ "\tgreet, init, step");
System.exit(1);
}
}
}
| import backend.Core;
import java.io.IOException;
import parse.GreetParser;
import parse.StepParser;
public class App {
public String getGreeting() {
return "Hello world.";
}
/**
* Main entry point to G2Tutorial.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Available commands:\n\tgreet");
System.exit(1);
}
if (args[0].equals("greet")) {
// Greet just exists as a template for parsing
GreetParser p = new GreetParser(args);
p.parse();
} else if (args[0].equals("init")) {
// Initializes an empty git repo
try {
Core.initCore();
} catch (IOException e) {
System.err.println("Could not init g2t");
e.printStackTrace();
}
System.exit(0);
} else if (args[0].equals("step")) {
// Commits the current changes as a step and starts a new step
Core c = null;
try {
c = new Core();
} catch (IOException e) {
System.err.println("g2t is not initialized");
e.printStackTrace();
}
StepParser p = new StepParser(args, c);
p.parse();
} else {
System.out.println("Available commands:\n"
+ "\tgreet, init");
System.exit(1);
}
}
}
|
Fix strategy name in error message. | package org.metaborg.spoofax.core.stratego.primitive.scopegraph;
import org.metaborg.scopegraph.context.IScopeGraphContext;
import org.metaborg.scopegraph.context.IScopeGraphUnit;
import org.metaborg.scopegraph.indices.TermIndex;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class SG_get_ast_analysis extends ScopeGraphPrimitive {
private static final ILogger logger = LoggerUtils.logger(SG_get_ast_analysis.class);
public SG_get_ast_analysis() {
super(SG_get_ast_analysis.class.getSimpleName(), 0, 0);
}
@Override public boolean call(IScopeGraphContext<?> context, IContext env, Strategy[] strategies,
IStrategoTerm[] terms) throws InterpreterException {
final TermIndex index = TermIndex.get(env.current());
if (index == null) {
logger.warn("get-ast-analysis called with non-AST argument {}", env.current());
return false;
}
final IScopeGraphUnit unit = context.unit(index.resource());
final IStrategoTerm analysis = unit.analysis();
if (analysis == null) {
return false;
}
env.setCurrent(analysis);
return true;
}
} | package org.metaborg.spoofax.core.stratego.primitive.scopegraph;
import org.metaborg.scopegraph.context.IScopeGraphContext;
import org.metaborg.scopegraph.context.IScopeGraphUnit;
import org.metaborg.scopegraph.indices.TermIndex;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
public class SG_get_ast_analysis extends ScopeGraphPrimitive {
private static final ILogger logger = LoggerUtils.logger(SG_get_ast_analysis.class);
public SG_get_ast_analysis() {
super(SG_get_ast_analysis.class.getSimpleName(), 0, 0);
}
@Override public boolean call(IScopeGraphContext<?> context, IContext env, Strategy[] strategies,
IStrategoTerm[] terms) throws InterpreterException {
final TermIndex index = TermIndex.get(env.current());
if (index == null) {
logger.warn("get-analysis called with non-AST argument {}", env.current());
return false;
}
final IScopeGraphUnit unit = context.unit(index.resource());
final IStrategoTerm analysis = unit.analysis();
if (analysis == null) {
return false;
}
env.setCurrent(analysis);
return true;
}
} |
Update polyfill url to include default | /* eslint-disable react/no-danger */
import Document, { Head, Main, NextScript } from 'next/document'
import React from 'react'
// The document (which is SSR-only) needs to be customized to expose the locale
// data for the user's locale for React Intl to work in the browser.
export default class IntlDocument extends Document {
static async getInitialProps(context) {
const props = await super.getInitialProps(context)
const {
req: { locale, localeDataScript },
} = context
return {
...props,
locale,
localeDataScript,
}
}
render() {
// Polyfill Intl API for older browsers
const polyfill = `https://cdn.polyfill.io/v2/polyfill.min.js
?features=default,fetch,Intl,Intl.~locale.de,Intl.~locale.en`
return (
<html lang={this.props.locale}>
<Head>
<meta content="text/html; charset=utf-8" httpEquiv="Content-type" />
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="IE=Edge" httpEquiv="X-UA-Compatible" />
<link href="/_next/static/style.css" rel="stylesheet" />
</Head>
<body>
<Main />
<script src={polyfill} />
<script
dangerouslySetInnerHTML={{
__html: this.props.localeDataScript,
}}
/>
<NextScript />
</body>
</html>
)
}
}
| /* eslint-disable react/no-danger */
import Document, { Head, Main, NextScript } from 'next/document'
import React from 'react'
// The document (which is SSR-only) needs to be customized to expose the locale
// data for the user's locale for React Intl to work in the browser.
export default class IntlDocument extends Document {
static async getInitialProps(context) {
const props = await super.getInitialProps(context)
const {
req: { locale, localeDataScript },
} = context
return {
...props,
locale,
localeDataScript,
}
}
render() {
// Polyfill Intl API for older browsers
const polyfill = `https://cdn.polyfill.io/v2/polyfill.min.js
?features=Intl.~locale.${this.props.locale}`
return (
<html lang={this.props.locale}>
<Head>
<meta content="text/html; charset=utf-8" httpEquiv="Content-type" />
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="IE=Edge" httpEquiv="X-UA-Compatible" />
<link href="/_next/static/style.css" rel="stylesheet" />
</Head>
<body>
<Main />
<script src={polyfill} />
<script
dangerouslySetInnerHTML={{
__html: this.props.localeDataScript,
}}
/>
<NextScript />
</body>
</html>
)
}
}
|
Set profile once <select> has been initialized | var EdsnSwitch = (function () {
'use strict';
var EDSN_THRESHOLD = 30,
validBaseLoads = /^(base_load|base_load_edsn)$/;
function swapSelectBox() {
var self = this,
type = $(this.target).data('type'),
profile = $(this.target).data('profile'),
unitSelector = $(this.target).find(".units input"),
units = parseInt(unitSelector.val(), 10),
actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load"),
options = $(".hidden.profile select." + actual).find("option").clone(true, true),
select = $(this.target).find('.editable.profile select');
select.html(options);
if(type === actual) {
select.val(profile);
} else {
select.trigger('change');
}
$(this.target).set('profile', parseInt(select.val(), 10));
$(this.target).set('type', actual);
unitSelector.off('change.units').on('change.units', swapSelectBox.bind(self));
}
EdsnSwitch.prototype = {
isEdsn: function () {
return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function () {
swapSelectBox.call(this);
}
};
function EdsnSwitch() {
return;
}
return EdsnSwitch;
}());
| var EdsnSwitch = (function () {
'use strict';
var EDSN_THRESHOLD = 30,
validBaseLoads = /^(base_load|base_load_edsn)$/;
function swapSelectBox() {
var self = this,
type = $(this.target).data('type'),
profile = $(this.target).data('profile'),
unitSelector = $(this.target).find(".units input"),
units = parseInt(unitSelector.val(), 10),
actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load"),
options = $(".hidden.profile select." + actual).find("option").clone(true, true),
select = $(this.target).find('.editable.profile select');
select.html(options);
if(type === actual) {
select.val(profile);
} else {
select.trigger('change');
}
$(this.target).set('type', actual);
unitSelector.off('change.units').on('change.units', swapSelectBox.bind(self));
}
EdsnSwitch.prototype = {
isEdsn: function () {
return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function () {
swapSelectBox.call(this);
}
};
function EdsnSwitch() {
return;
}
return EdsnSwitch;
}());
|
Update REST API for LVAP handoffs | package net.floodlightcontroller.odin.master;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import net.floodlightcontroller.util.MACAddress;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
public class LvapHandoffResource extends ServerResource {
@SuppressWarnings("unchecked")
@Post
public void store(String flowmod) {
OdinMaster oc = (OdinMaster) getContext().getAttributes().
get(OdinMaster.class.getCanonicalName());
ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> fmdata;
try {
fmdata = mapper.readValue(flowmod, HashMap.class);
String staHwAddress = fmdata.get("clientHwAddress");
String apIpAddress= fmdata.get("apIpAddress");
String poolName = fmdata.get("poolName");
oc.handoffClientToAp(poolName, MACAddress.valueOf(staHwAddress), InetAddress.getByName(apIpAddress));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| package net.floodlightcontroller.odin.master;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import net.floodlightcontroller.util.MACAddress;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
public class LvapHandoffResource extends ServerResource {
@SuppressWarnings("unchecked")
@Post
public void store(String flowmod) {
OdinMaster oc = (OdinMaster) getContext().getAttributes().
get(OdinMaster.class.getCanonicalName());
ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> fmdata;
try {
fmdata = mapper.readValue(flowmod, HashMap.class);
String staHwAddress = fmdata.get("clientHwAddress");
String apIpAddress= fmdata.get("apIpAddress");
oc.handoffClientToAp(PoolManager.GLOBAL_POOL, MACAddress.valueOf(staHwAddress), InetAddress.getByName(apIpAddress));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Add support for Parsedown Extra | <?php
namespace allejo\stakx\Engines;
use Highlight\Highlighter;
class MarkdownEngine extends \ParsedownExtra
{
protected $highlighter;
public function __construct ()
{
parent::__construct();
$this->highlighter = new Highlighter();
}
protected function blockHeader($line)
{
$Block = parent::blockHeader($line);
// Create our unique ids by sanitizing the header content
$id = strtolower($Block['element']['text']);
$id = str_replace(' ', '-', $id);
$id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id);
$id = preg_replace('/-+/', '-', $id);
$Block['element']['attributes']['id'] = $id;
return $Block;
}
public function blockFencedCodeComplete ($block)
{
// The class has a `language-` prefix, remove this to get the language
if (isset($block['element']['text']['attributes']))
{
$language = substr($block['element']['text']['attributes']['class'], 9);
try
{
$highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']);
$block['element']['text']['text'] = $highlighted->value;
// Only return the block if Highlighter knew the language and how to handle it.
return $block;
}
// Exception thrown when language not supported, so just catch it and ignore it.
catch (\DomainException $exception) {}
}
return parent::blockFencedCodeComplete($block);
}
} | <?php
namespace allejo\stakx\Engines;
use Highlight\Highlighter;
class MarkdownEngine extends \Parsedown
{
protected $highlighter;
public function __construct ()
{
$this->highlighter = new Highlighter();
}
protected function blockHeader($line)
{
$Block = parent::blockHeader($line);
// Create our unique ids by sanitizing the header content
$id = strtolower($Block['element']['text']);
$id = str_replace(' ', '-', $id);
$id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id);
$id = preg_replace('/-+/', '-', $id);
$Block['element']['attributes']['id'] = $id;
return $Block;
}
public function blockFencedCodeComplete ($block)
{
// The class has a `language-` prefix, remove this to get the language
if (isset($block['element']['text']['attributes']))
{
$language = substr($block['element']['text']['attributes']['class'], 9);
try
{
$highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']);
$block['element']['text']['text'] = $highlighted->value;
// Only return the block if Highlighter knew the language and how to handle it.
return $block;
}
// Exception thrown when language not supported, so just catch it and ignore it.
catch (\DomainException $exception) {}
}
return parent::blockFencedCodeComplete($block);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.