text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add explicit comments in test using reserved binding name
|
/*jshint -W030 */
var gremlin = require('../');
describe('Bindings', function() {
it('should support bindings with client.execute()', function(done) {
var client = gremlin.createClient();
client.execute('g.v(x)', { x: 1 }, function(err, result) {
(err === null).should.be.true;
result.length.should.equal(1);
done();
});
});
it('should support bindings with client.stream()', function(done) {
var client = gremlin.createClient();
var stream = client.stream('g.v(x)', { x: 1 });
stream.on('data', function(result) {
result.id.should.equal(1);
});
stream.on('end', function() {
done();
});
});
it('should give an error with erroneous binding name in .exec', function(done) {
var client = gremlin.createClient();
// This is supposed to throw a NoSuchElementException in Gremlin Server:
// --> "The vertex with id id of type does not exist in the graph"
// id is a reserved (imported) variable and can't be used in a script
client.execute('g.v(id)', { id: 1 }, function(err, result) {
(err !== null).should.be.true;
(result === undefined).should.be.true;
done();
});
});
});
|
/*jshint -W030 */
var gremlin = require('../');
describe('Bindings', function() {
it('should support bindings with client.execute()', function(done) {
var client = gremlin.createClient();
client.execute('g.v(x)', { x: 1 }, function(err, result) {
(err === null).should.be.true;
result.length.should.equal(1);
done();
});
});
it('should support bindings with client.stream()', function(done) {
var client = gremlin.createClient();
var stream = client.stream('g.v(x)', { x: 1 });
stream.on('data', function(result) {
result.id.should.equal(1);
});
stream.on('end', function() {
done();
});
});
it('should give an error with erroneous binding name in .exec', function(done) {
var client = gremlin.createClient();
client.execute('g.v(id)', { id: 1 }, function(err, result) {
(err !== null).should.be.true;
(result === undefined).should.be.true;
done();
});
});
});
|
Allow DB migrations source path customization
|
package buildlog
import (
"fmt"
"log"
"os"
"github.com/mattes/migrate"
"github.com/mattes/migrate/database/postgres"
_ "github.com/mattes/migrate/source/file"
)
type migrationLogger struct {
}
func (m migrationLogger) Verbose() bool {
return false
}
func (m migrationLogger) Printf(format string, v ...interface{}) {
s := fmt.Sprintf(format, v...)
log.Printf("[db migration] %s", s)
}
func (bl *BuildLog) MigrateDb() error {
driver, err := postgres.WithInstance(bl.db, &postgres.Config{})
if err != nil {
return err
}
source := os.Getenv("DB_MIGRATIONS_SOURCE_URI")
if source == "" {
source = "file://migrations"
}
log.Printf("Using DB migrations file from %s\n", source)
m, err := migrate.NewWithDatabaseInstance(source, "postgres", driver)
if err != nil {
return err
}
m.Log = migrationLogger{}
err = m.Up()
if err != migrate.ErrNoChange {
return err
}
return nil
}
|
package buildlog
import (
"fmt"
"log"
"github.com/mattes/migrate"
"github.com/mattes/migrate/database/postgres"
_ "github.com/mattes/migrate/source/file"
)
type migrationLogger struct {
}
func (m migrationLogger) Verbose() bool {
return false
}
func (m migrationLogger) Printf(format string, v ...interface{}) {
s := fmt.Sprintf(format, v...)
log.Printf("[db migration] %s", s)
}
func (bl *BuildLog) MigrateDb() error {
driver, err := postgres.WithInstance(bl.db, &postgres.Config{})
if err != nil {
return err
}
m, err := migrate.NewWithDatabaseInstance("file://migrations", "postgres", driver)
if err != nil {
return err
}
m.Log = migrationLogger{}
err = m.Up()
if err != migrate.ErrNoChange {
return err
}
return nil
}
|
Fix codestyle by adding a space between string concatenation
|
<?php
namespace Frisbee\Controller;
use Frisbee\Bootstrap\BootstrapInterface;
use Frisbee\Exception\Flingable;
abstract class AbstractController extends Flingable implements ControllerInterface
{
/**
* @var BootstrapInterface
*/
private $bootstrap;
/**
* @var string
*/
protected $method;
public function __construct(BootstrapInterface $bootstrap, $defaultMethod = 'index')
{
$this->bootstrap = $bootstrap;
$this->method = $defaultMethod;
}
public function run()
{
// You could implement "middleware" here or load dependencies in your controller by using boomerang
}
public function next()
{
$dispatchMethod = $this->method . 'Action';
if (!method_exists($this, $dispatchMethod)) {
throw new \Exception(
sprintf('requested method: %s does not exist in controller %s', $dispatchMethod, get_class($this))
);
}
return $this->$dispatchMethod();
}
}
|
<?php
namespace Frisbee\Controller;
use Frisbee\Bootstrap\BootstrapInterface;
use Frisbee\Exception\Flingable;
abstract class AbstractController extends Flingable implements ControllerInterface
{
/**
* @var BootstrapInterface
*/
private $bootstrap;
/**
* @var string
*/
protected $method;
public function __construct(BootstrapInterface $bootstrap, $defaultMethod = 'index')
{
$this->bootstrap = $bootstrap;
$this->method = $defaultMethod;
}
public function run()
{
// You could implement "middleware" here or load dependencies in your controller by using boomerang
}
public function next()
{
$dispatchMethod = $this->method.'Action';
if (!method_exists($this, $dispatchMethod)) {
throw new \Exception(
sprintf('requested method: %s does not exist in controller %s', $dispatchMethod, get_class($this))
);
}
return $this->$dispatchMethod();
}
}
|
Add compatibility to old uuid key
|
import has from 'lodash/has';
import isPlainObject from 'lodash/isPlainObject';
import isArray from 'lodash/isArray';
const UUID_KEY_PATTERN = /__.+uuid__/i;
const OLD_KEY = 'zent-design-uuid';
export default function stripUUID(value) {
if (isPlainObject(value)) {
// eslint-disable-next-line
for (const key in value) {
if (has(value, key)) {
if (OLD_KEY === key || UUID_KEY_PATTERN.test(key)) {
delete value[key];
} else {
const oldValue = value[key];
const newValue = stripUUID(oldValue);
if (newValue !== oldValue) {
value[key] = newValue;
}
}
}
}
} else if (isArray(value)) {
value.forEach(v => stripUUID(v));
}
return value;
}
|
import has from 'lodash/has';
import isPlainObject from 'lodash/isPlainObject';
import isArray from 'lodash/isArray';
const UUID_KEY_PATTERN = /__.+uuid__/i;
export default function stripUUID(value) {
if (isPlainObject(value)) {
// eslint-disable-next-line
for (const key in value) {
if (has(value, key)) {
if (UUID_KEY_PATTERN.test(key)) {
delete value[key];
} else {
const oldValue = value[key];
const newValue = stripUUID(oldValue);
if (newValue !== oldValue) {
value[key] = newValue;
}
}
}
}
} else if (isArray(value)) {
value.forEach(v => stripUUID(v));
}
return value;
}
|
Fix export collections with sub-collections
|
function collectionToBookmarkHtml(collection) {
var html = addHeader();
html += "<DL><p>";
html += transformCollection(collection);
html += "</DL><p>";
return html;
}
function collectionsToBookmarkHtml(collections) {
var html = addHeader();
html += "<DL><p>";
$.each(collections, function (index, collection) {
html += transformCollection(collection);
});
html += "</DL><p>";
return html;
}
function addHeader() {
var html = "<!DOCTYPE NETSCAPE-Bookmark-file-1>";
html += "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">";
html += "<TITLE>Linky Bookmarks</TITLE>";
html += "<H1>Linky Bookmarks</H1>"
return html;
}
function transformCollection(collection) {
var html = "<DT><H3>" + collection.text + "</H3>";
html += "<DL><p>";
$.each(collection.bookmarks, function (index, bookmark) {
html += "<DT><A HREF=\""+ bookmark.url + "\" ICON=\"default\">" + bookmark.text + "</A>";
});
$.each(collection.nodes, function (index, node) {
html += transformCollection(node);
});
html += "</DL><p>";
return html;
}
|
function collectionToBookmarkHtml(collection) {
var html = addHeader();
html += "<DL><p>";
html += transformCollection(collection);
html += "</DL><p>";
return html;
}
function collectionsToBookmarkHtml(collections) {
var html = addHeader();
html += "<DL><p>";
$.each(collections, function (index, collection) {
html += transformCollection(collection);
});
html += "</DL><p>";
return html;
}
function addHeader() {
var html = "<!DOCTYPE NETSCAPE-Bookmark-file-1>";
html += "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">";
html += "<TITLE>Linky Bookmarks</TITLE>";
html += "<H1>Linky Bookmarks</H1>"
return html;
}
function transformCollection(collection) {
var html = "<DT><H3>" + collection.text + "</H3>";
html += "<DL><p>";
$.each(collection.bookmarks, function (index, bookmark) {
html += "<DT><A HREF=\""+ bookmark.url + "\" ICON=\"default\">" + bookmark.text + "</A>";
});
$.each(collection.nodes, function (index, node) {
transformCollection(html, node);
});
html += "</DL><p>";
return html;
}
|
Resolve XXE vulnerability in XML validation
|
package manage.validations;
import org.everit.json.schema.FormatValidator;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;
public class XMLFormatValidator implements FormatValidator {
private static final String FEATURE_DISABLE_DOCTYPE = "http://apache.org/xml/features/disallow-doctype-decl";
@Override
public Optional<String> validate(String subject) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
try {
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature(FEATURE_DISABLE_DOCTYPE, true);
factory.newDocumentBuilder().parse(new ByteArrayInputStream(subject.getBytes()));
} catch (ParserConfigurationException | SAXException | IOException e) {
return Optional.of(e.toString());
}
return Optional.empty();
}
@Override
public String formatName() {
return "xml";
}
}
|
package manage.validations;
import org.everit.json.schema.FormatValidator;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;
public class XMLFormatValidator implements FormatValidator {
@Override
public Optional<String> validate(String subject) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
try {
factory.newDocumentBuilder().parse(new ByteArrayInputStream(subject.getBytes()));
} catch (ParserConfigurationException | SAXException | IOException e) {
return Optional.of(e.toString());
}
return Optional.empty();
}
@Override
public String formatName() {
return "xml";
}
}
|
Return sorted values for scores
|
"""
Blueprint implementing the API wrapper.
:author: 2013, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
import json
from flask import Blueprint, request, abort
from .utils import JSONError
from .calc import calculate_scores
api = Blueprint('api', __name__, url_prefix='/v1')
class ScoresResponse(object):
def __init__(self, scores, errors):
self.scores = scores
self.errors = errors
@property
def sorted_scores(self):
# Sort by descending by value
return dict(sorted(self.scores.items(), key=lambda x: -x[1]))
def to_json(self):
return {'scores': self.sorted_scores, 'errors': list(self.errors)}
@api.route('/score', methods=['POST'])
def score():
"""Calculate the score for a given result set."""
try:
results = json.loads(request.data)['results']
except (ValueError, KeyError):
abort(400)
if not isinstance(results, list):
abort(400)
try:
results = calculate_scores(results)
except Exception as err:
return JSONError('CALCULATION_ERROR', code=-1, message=str(err))\
.to_error()
return ScoresResponse(*results)
|
"""
Blueprint implementing the API wrapper.
:author: 2013, Pascal Hartig <phartig@weluse.de>
:license: BSD
"""
import json
from flask import Blueprint, request, abort
from .utils import JSONError
from .calc import calculate_scores
api = Blueprint('api', __name__, url_prefix='/v1')
class ScoresResponse(object):
def __init__(self, scores, errors):
self.scores = scores
self.errors = errors
def to_json(self):
return {'scores': self.scores, 'errors': list(self.errors)}
@api.route('/score', methods=['POST'])
def score():
"""Calculate the score for a given result set."""
try:
results = json.loads(request.data)['results']
except (ValueError, KeyError):
abort(400)
if not isinstance(results, list):
abort(400)
try:
results = calculate_scores(results)
except Exception as err:
return JSONError('CALCULATION_ERROR', code=-1, message=str(err))\
.to_error()
return ScoresResponse(*results)
|
Fix wrong display fullName in sophancong gird.
|
/**
* Created by dungvn3000 on 4/4/14.
*/
Ext.define('sunerp.component.NhanVienCb', {
extend: 'sunerp.component.Combobox',
alias: 'widget.nhanviencb',
gird: null,
valueField: 'maNv',
displayField: 'fullName',
inject: ['userService'],
config: {
userService: null
},
initComponent: function () {
var phongBanId = this.getUserService().getCurrentUser().phongBanId;
this.store = Ext.create('sunerp.store.NhanVienStore');
if(phongBanId) {
this.store.filter('phongBanId', String(phongBanId));
}
this.store.load();
this.callParent(arguments);
},
onItemClick: function (picker, record) {
var me = this;
me.callParent(arguments);
if (me.gird && me.gird.getSelectionModel().hasSelection()) {
var model = me.gird.getSelectionModel().getLastSelected();
model.set('nhanVienId', record.getData().id);
model.set('nhanVien', record.getData());
}
}
});
|
/**
* Created by dungvn3000 on 4/4/14.
*/
Ext.define('sunerp.component.NhanVienCb', {
extend: 'sunerp.component.Combobox',
alias: 'widget.nhanviencb',
gird: null,
valueField: 'maNv',
displayField: 'fullName',
inject: ['userService'],
config: {
userService: null
},
initComponent: function () {
var phongBanId = this.getUserService().getCurrentUser().phongBanId;
this.store = Ext.create('sunerp.store.NhanVienStore');
if(phongBanId) {
this.store.filter('phongBanId', String(phongBanId));
}
this.store.load();
this.callParent(arguments);
},
onItemClick: function (picker, record) {
var me = this;
me.callParent(arguments);
if (me.gird && me.gird.getSelectionModel().hasSelection()) {
var model = me.gird.getSelectionModel().getLastSelected();
model.set('nhanVienId', record.getData().id);
}
}
});
|
Allow reading word list from stdin.
|
import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
print json.dumps(result, indent=4, sort_keys=True)
else:
json.dump(result, sys.stdout)
class airtable:
"""Sync lists to Airtable"""
def load(self, list_url, endpoint, key):
airtable = Airtable(endpoint, key)
words = VocabularyCom().collect(list_url)
airtable.load(words)
print 'List loaded to Airtable.'
def load_from_stdin(self, endpoint, key):
words = json.load(sys.stdin)
airtable = Airtable(endpoint, key)
airtable.load(words)
print 'List loaded to Airtable.'
if __name__ == '__main__':
fire.Fire(CLI)
|
import fire
import json
import sys
from source import VocabularyCom
from airtable import Airtable
class CLI:
class source:
"""Import word lists from various sources"""
def vocabulary_com(self, list_url, pretty=False):
result = VocabularyCom().collect(list_url)
if pretty:
print json.dumps(result, indent=4, sort_keys=True)
else:
json.dump(result, sys.stdout)
class airtable:
"""Sync lists to Airtable"""
def load(self, list_url, endpoint, key):
airtable = Airtable(endpoint, key)
words = VocabularyCom().collect(list_url)
airtable.load(words)
print 'List loaded to Airtable.'
if __name__ == '__main__':
fire.Fire(CLI)
|
Fix parse_requirements call for new pip version.
|
#!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
import uuid
def get_requirements(*args):
"""Parse all requirements files given and return a list of the
dependencies"""
install_deps = []
try:
for fpath in args:
install_deps.extend([str(d.req) for d in parse_requirements(fpath, session=uuid.uuid1())])
except:
print('Error reading {} file looking for dependencies.'.format(fpath))
return [dep for dep in install_deps if dep != 'None']
if __name__ == '__main__':
for line in fileinput.input():
req_filepaths = sys.argv[1:]
deps = get_requirements(*req_filepaths)
try:
for dep_name in deps:
cmd = "pip install '{0}'".format(dep_name)
print('#', cmd)
subprocess.check_call(cmd, shell=True)
except:
print('Error installing {}'.format(dep_name))
|
#!/usr/bin/env python
"""
Install the packages you have listed in the requirements file you input as
first argument.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
import fileinput
import subprocess
from pip.req import parse_requirements
def get_requirements(*args):
"""Parse all requirements files given and return a list of the
dependencies"""
install_deps = []
try:
for fpath in args:
install_deps.extend([str(d.req) for d in parse_requirements(fpath)])
except:
print('Error reading {} file looking for dependencies.'.format(fpath))
return [dep for dep in install_deps if dep != 'None']
if __name__ == '__main__':
for line in fileinput.input():
req_filepaths = sys.argv[1:]
deps = get_requirements(*req_filepaths)
try:
for dep_name in deps:
cmd = "pip install '{0}'".format(dep_name)
print('#', cmd)
subprocess.check_call(cmd, shell=True)
except:
print('Error installing {}'.format(dep_name))
|
FIX Неправильно обрабатывались юзеры без дисплейнейма
|
registerAction(function (node) {
if (!settings["fixNames"]) return;
node = node || document.body;
toArray(node.querySelectorAll(".content > .l_profile, .lbody > .l_profile, .name > .l_profile, .foaf > .l_profile"))
.forEach(function (node) {
var login = node.getAttribute("href").substr(1);
if (node.innerHTML != login) {
node.dataset["displayName"] = node.innerHTML;
node.innerHTML = login;
}
});
// В попапе показываем оригинальное имя
toArray(node.querySelectorAll("#popup .name > .l_profile"))
.forEach(function (node) {
var sn = node.dataset["displayName"];
if (sn !== undefined) node.innerHTML = node.dataset["displayName"];
});
});
|
registerAction(function (node) {
if (!settings["fixNames"]) return;
node = node || document.body;
toArray(node.querySelectorAll(".content > .l_profile, .lbody > .l_profile, .name > .l_profile, .foaf > .l_profile"))
.forEach(function (node) {
var login = node.getAttribute("href").substr(1);
if (node.innerHTML != login) {
node.dataset["displayName"] = node.innerHTML;
node.innerHTML = login;
}
});
// В попапе показываем оригинальное имя
toArray(node.querySelectorAll("#popup .name > .l_profile"))
.forEach(function (node) {
node.innerHTML = node.dataset["displayName"];
});
});
|
Change ticker font scale factor to 0.7
|
Dashboard.TickerWidget = Dashboard.Widget.extend({
sourceData: "",
templateName: 'ticker_widget',
classNames: ['widget', 'widget-ticker'],
widgetView: function() {
var widget = this;
return this._super().reopen({
didInsertElement: function() {
var scaleFactor = 0.7;
var widgetHeight = this.$().height();
var fontSize = widgetHeight * scaleFactor;
var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) /
DashboardConfig.dim[0] - DashboardConfig.widgetMargins;
var widgetWidth = widgetUnitWidth * widget.get('sizex') +
DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5;
this.$().css('font-size', fontSize + 'px');
this.$('.marquee').css('max-width', widgetWidth + 'px');
}
});
}.property()
});
|
Dashboard.TickerWidget = Dashboard.Widget.extend({
sourceData: "",
templateName: 'ticker_widget',
classNames: ['widget', 'widget-ticker'],
widgetView: function() {
var widget = this;
return this._super().reopen({
didInsertElement: function() {
var scaleFactor = 0.5;
var scaleSource = this.$().height();
var fontSize = scaleSource * scaleFactor;
var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) /
DashboardConfig.dim[0] - DashboardConfig.widgetMargins;
var widgetWidth = widgetUnitWidth * widget.get('sizex') +
DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5;
this.$().css('font-size', fontSize + 'px');
this.$('.marquee').css('max-width', widgetWidth + 'px');
}
});
}.property()
});
|
Comment out rush warning and job score on job event detail
|
<?php $job = $item->assocObject;?>
<?php $id = 'job_evt_'.$job->ID.$item->ID;?>
<div id="<?php echo $id;?>">
<div class="pad"><?php
$job = $item->getAssocObject();
?>
<?php /* js: hide rush warning
<?php if($job->RUSH){?>
<span class="warning">RUSH</span>
<?php } ?>
*/ ?>
<a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job->ID));?>">
<?php echo CHtml::encode($job->NAME);?>
</a>
<?php /* js: hide job score
(<strong><?php echo $job->score;?></strong>)
*/ ?>
<?php echo CHtml::activeHiddenField($item, 'ID');?>
<?php Yii::app()->clientScript->registerCss($id, "#$id{}");/*480 is number of minutes in 8 hours*/?></div>
</div>
|
<?php $job = $item->assocObject;?>
<?php $id = 'job_evt_'.$job->ID.$item->ID;?>
<div id="<?php echo $id;?>">
<div class="pad"><?php
$job = $item->getAssocObject();
?>
<?php if($job->RUSH){?>
<span class="warning">RUSH</span>
<?php } ?>
<a href="<?php echo CHtml::normalizeUrl(array('job/view', 'id'=>$job->ID));?>">
<?php echo CHtml::encode($job->NAME);?>
</a> (<strong><?php echo $job->score;?></strong>)
<?php echo CHtml::activeHiddenField($item, 'ID');?>
<?php Yii::app()->clientScript->registerCss($id, "#$id{}");/*480 is number of minutes in 8 hours*/?></div>
</div>
|
Make lexer argument optional and guess content if not provided
|
// Pygments wrapper for golang. Pygments is a syntax highlighter
package pygments
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
)
var (
bin = "pygmentize"
)
func Binary(path string) {
bin = path
}
func Which() string {
return bin
}
func Highlight(code string, lexer string, format string, enc string) string {
if _, err := exec.LookPath(bin); err != nil {
fmt.Println("You do not have " + bin + " installed!")
os.Exit(0)
}
// Guess the lexer based on content if a specific one is not provided
lexerArg := "-g"
if lexer != "" {
lexerArg = "-l" + lexer
}
cmd := exec.Command(bin, lexerArg, "-f"+format, "-O encoding="+enc)
cmd.Stdin = strings.NewReader(code)
var out bytes.Buffer
cmd.Stdout = &out
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
fmt.Println(stderr.String())
fmt.Println(err)
os.Exit(0)
}
return out.String()
}
|
// Pygments wrapper for golang. Pygments is a syntax highlighter
package pygments
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
)
var (
bin = "pygmentize"
)
func Binary(path string) {
bin = path
}
func Which() string {
return bin
}
func Highlight(code string, lexer string, format string, enc string) string {
if _, err := exec.LookPath(bin); err != nil {
fmt.Println("You do not have " + bin + " installed!")
os.Exit(0)
}
cmd := exec.Command(bin, "-l"+lexer, "-f"+format, "-O encoding="+enc)
cmd.Stdin = strings.NewReader(code)
var out bytes.Buffer
cmd.Stdout = &out
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
fmt.Println(stderr.String())
fmt.Println(err)
os.Exit(0)
}
return out.String()
}
|
Remove underlines that indicate privacy
|
const buildRequest = function (url, method, responseType, headers) {
const internalHeaders = headers || {};
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.responseType = responseType;
req.open(method.toUpperCase(), url);
Object.keys(internalHeaders).forEach((headerKey) => {
req.setRequestHeader(headerKey, internalHeaders[headerKey]);
});
req.onload = () => {
if (req.status >= 200 && req.status <= 299) {
resolve(req.response);
}
else {
reject(req);
}
};
req.onerror = () => {
console.error('Network error.');
};
req.send();
});
};
const get = function (url, responseType, headers) {
if (!url) {
console.error(`URL can't be ${url}.`);
}
return buildRequest(url, 'GET', responseType, headers);
};
export {get};
|
const buildRequest = function (url, method, responseType, headers) {
const internalHeaders = headers || {};
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.responseType = responseType;
req.open(method.toUpperCase(), url);
Object.keys(internalHeaders).forEach((headerKey) => {
req.setRequestHeader(headerKey, internalHeaders[headerKey]);
});
req.onload = () => {
if (req.status >= 200 && req.status <= 299) {
resolve(req.response);
}
else {
reject(req);
}
};
req.onerror = () => {
console.error('Network error.');
};
req.send();
});
};
const get = function (url, responseType, headers) {
if (!url) {
console.error(`URL can't be ${url}.`);
}
return _buildRequest(url, 'GET', responseType, headers);
};
export {get};
|
Store songs, artists, and albums as objects
Add 'favorite' bool as property of each object
|
'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('HomeController', ['$scope', function($scope) {
$scope.allMusic = [];
$scope.albums = [];
$scope.artists = [];
$scope.songs = [];
$scope.metadata = {song: '', artist: '', album: ''};
$scope.saveMusic = function() {
$scope.allMusic.push($scope.metadata);
$scope.albums.push({title: $scope.metadata.album, favorite: false});
$scope.artists.push({name: $scope.metadata.artist, favorite: false});
$scope.songs.push({title: $scope.metadata.song, favorite: false});
// Clear out data after it has been saved!
$scope.metadata = {song: '', artist: '', album: ''};
};
}])
.controller('AlbumsController', ['$scope', function($scope) {
}])
.controller('ArtistsController', ['$scope', function($scope) {
}])
.controller('SongsController', ['$scope', function($scope) {
}])
.controller('FavoritesController', ['$scope', function($scope) {
}]);
|
'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('HomeController', ['$scope', function($scope) {
$scope.allMusic = [];
$scope.albums = [];
$scope.artists = [];
$scope.songs = [];
$scope.metadata = {song: '', artist: '', album: ''};
$scope.saveMusic = function() {
$scope.allMusic.push($scope.metadata);
$scope.albums.push($scope.metadata.album);
$scope.artists.push($scope.metadata.artist);
$scope.songs.push($scope.metadata.song);
// Clear out data after it has been saved!
$scope.metadata = {song: '', artist: '', album: ''};
};
}])
.controller('AlbumsController', ['$scope', function($scope) {
}])
.controller('ArtistsController', ['$scope', function($scope) {
}])
.controller('SongsController', ['$scope', function($scope) {
}])
.controller('FavoritesController', ['$scope', function($scope) {
}]);
|
Change menu text from edit/delete datasource -> manage datasources
|
/*
* Copyright 2014 Codenvy, S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codenvy.ide.ext.datasource.client.editdatasource;
import com.google.gwt.i18n.client.Messages;
public interface EditDatasourceMessages extends Messages {
@DefaultMessage("Edit Datasource")
String editButtonText();
@DefaultMessage("Delete Datasources")
String deleteButtonText();
@DefaultMessage("Close")
String closeButtonText();
@DefaultMessage("Manage datasources")
String editDatasourcesMenuText();
@DefaultMessage("Manage datasources")
String editDatasourcesDialogText();
@DefaultMessage("Datasources")
String datasourcesListLabel();
@DefaultMessage("Cannot edit more than one datasource")
String editMultipleSelectionMessage();
@DefaultMessage("No datasource selected")
String editOrDeleteNoSelectionMessage();
@DefaultMessage("Delete {0} datasources")
String confirmDeleteDatasources(int size);
@DefaultMessage("No datasources configured")
String emptyDatasourceList();
}
|
/*
* Copyright 2014 Codenvy, S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codenvy.ide.ext.datasource.client.editdatasource;
import com.google.gwt.i18n.client.Messages;
public interface EditDatasourceMessages extends Messages {
@DefaultMessage("Edit Datasource")
String editButtonText();
@DefaultMessage("Delete Datasources")
String deleteButtonText();
@DefaultMessage("Close")
String closeButtonText();
@DefaultMessage("Edit/Delete datasources")
String editDatasourcesMenuText();
@DefaultMessage("Edit/Delete datasources")
String editDatasourcesDialogText();
@DefaultMessage("Datasources")
String datasourcesListLabel();
@DefaultMessage("Cannot edit more than one datasource")
String editMultipleSelectionMessage();
@DefaultMessage("No datasource selected")
String editOrDeleteNoSelectionMessage();
@DefaultMessage("Delete {0} datasources")
String confirmDeleteDatasources(int size);
@DefaultMessage("No datasources configured")
String emptyDatasourceList();
}
|
Fix redirects causing duplicate setup method calls
Triggering a transition from the beforeModel method in the application route will cause the beforeModel method to be called again on the next transition. Moving the transition call to the redirect method fixes this.
|
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isPresent } from '@ember/utils';
export default class ApplicationRoute extends Route {
@service('remotestorage') storage;
@service localData;
@service logger;
@service coms;
async beforeModel () {
super.beforeModel(...arguments);
await this.storage.ensureReadiness();
await this.localData.setDefaultValues();
await this.coms.instantiateAccountsAndChannels();
this.coms.setupListeners();
// See a list of allowed types in logger.js
// Add or remove all your log types here:
// this.logger.add('message');
// this.logger.remove('join');
// this.logger.disable();
// this.logger.enable();
}
redirect (model, transition) {
if (isPresent(transition.intent.url) &&
transition.intent.url.includes('add-account')) {
return;
}
if (!this.coms.onboardingComplete) {
this.transitionTo('welcome');
}
}
@action
leaveChannel (channel) {
this.coms.removeChannel(channel);
// Switch to last channel if the channel parted was currently open
if (channel.visible) {
let lastChannel = this.coms.sortedChannels.lastObject;
this.transitionTo('channel', lastChannel);
}
}
}
|
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isPresent } from '@ember/utils';
export default class ApplicationRoute extends Route {
@service('remotestorage') storage;
@service localData;
@service logger;
@service coms;
async beforeModel (transition) {
super.beforeModel(...arguments);
await this.storage.ensureReadiness();
await this.localData.setDefaultValues();
await this.coms.instantiateAccountsAndChannels();
this.coms.setupListeners();
if (isPresent(transition.intent.url) &&
transition.intent.url.includes('add-account')) {
return;
}
if (!this.coms.onboardingComplete) {
this.transitionTo('welcome');
}
// See a list of allowed types in logger.js
// Add or remove all your log types here:
// this.logger.add('message');
// this.logger.remove('join');
// this.logger.disable();
// this.logger.enable();
}
@action
leaveChannel (channel) {
this.coms.removeChannel(channel);
// Switch to last channel if the channel parted was currently open
if (channel.visible) {
let lastChannel = this.coms.sortedChannels.lastObject;
this.transitionTo('channel', lastChannel);
}
}
}
|
Allow PeriodicRefresher to be force-refreshed
|
import {autobind} from 'core-decorators';
const refreshMapPerUniqueId = new WeakMap();
export default class PeriodicRefresher {
refresh() {
this._callback();
}
static getRefreshMap(uniqueId) {
let refreshMap = refreshMapPerUniqueId.get(uniqueId);
if (!refreshMap) {
refreshMap = new Map();
refreshMapPerUniqueId.set(uniqueId, refreshMap);
}
return refreshMap;
}
constructor(uniqueId, options) {
this.options = options;
this._refreshesPerId = PeriodicRefresher.getRefreshMap(uniqueId);
}
start() {
if (!this._timer) {
this._scheduleNext();
}
}
_stop() {
if (this._timer) {
clearTimeout(this._timer);
delete this._timer;
}
}
_scheduleNext() {
this._timer = setTimeout(this.refreshNow, this.options.interval());
}
@autobind
refreshNow(force = false) {
const currentId = this.options.getCurrentId();
const lastRefreshForId = this._refreshesPerId.get(currentId) || 0;
const delta = performance.now() - lastRefreshForId;
if (force || delta > this.options.minimumIntervalPerId) {
this._refreshesPerId.set(currentId, performance.now());
this.options.refresh();
}
this._scheduleNext();
}
destroy() {
this._stop();
}
}
|
import {autobind} from 'core-decorators';
const refreshMapPerUniqueId = new WeakMap();
export default class PeriodicRefresher {
static getRefreshMap(uniqueId) {
let refreshMap = refreshMapPerUniqueId.get(uniqueId);
if (!refreshMap) {
refreshMap = new Map();
refreshMapPerUniqueId.set(uniqueId, refreshMap);
}
return refreshMap;
}
constructor(uniqueId, options) {
this.options = options;
this._refreshesPerId = PeriodicRefresher.getRefreshMap(uniqueId);
}
start() {
if (!this._timer) {
this.scheduleNext();
}
}
stop() {
if (this._timer) {
clearTimeout(this._timer);
delete this._timer;
}
}
scheduleNext() {
this._timer = setTimeout(this.tick, this.options.interval());
}
@autobind
tick() {
const currentId = this.options.getCurrentId();
const lastRefreshForId = this._refreshesPerId.get(currentId) || 0;
const delta = performance.now() - lastRefreshForId;
if (delta > this.options.minimumIntervalPerId) {
this._refreshesPerId.set(currentId, performance.now());
this.options.refresh();
}
this.scheduleNext();
}
refresh() {
this._callback();
}
destroy() {
this.stop();
}
}
|
Revert "Added a validation into the parser"
This reverts commit 36a90ec21a9be5e5534017360051be49f3a0c2a9.
|
const {
UtilsParsingError,
UtilsRuntimeError,
} = require('./UtilsErrors');
const {
RequestRuntimeError,
} = require('../../Request/RequestErrors');
function currencyConvertParse(json) {
try {
json = json['util:CurrencyConversion'].map(curr => ({
from: curr.From,
to: curr.To,
rate: parseFloat(curr.BankSellingRate),
}));
} catch (e) {
throw new UtilsParsingError(json);
}
return json;
}
function dataTypeParse(json) {
return json['util:ReferenceDataItem'];
}
const errorHandler = function (rsp) {
let errorInfo;
let code;
try {
errorInfo = rsp.detail[`common_${this.uapi_version}:ErrorInfo`];
code = errorInfo[`common_${this.uapi_version}:Code`];
} catch (err) {
throw new RequestRuntimeError.UnhandledError(null, new UtilsRuntimeError(rsp));
}
switch (code) {
default:
throw new RequestRuntimeError.UnhandledError(null, new UtilsRuntimeError(rsp));
}
};
module.exports = {
UTILS_ERROR: errorHandler,
CURRENCY_CONVERSION: currencyConvertParse,
REFERENCE_DATATYPE: dataTypeParse,
};
|
const {
UtilsParsingError,
UtilsRuntimeError,
} = require('./UtilsErrors');
const {
RequestRuntimeError,
} = require('../../Request/RequestErrors');
function currencyConvertParse(json) {
try {
json = json['util:CurrencyConversion'].map(curr => ({
from: curr.From,
to: curr.To,
rate: parseFloat(curr.BankSellingRate),
}));
} catch (e) {
throw new UtilsParsingError(json);
}
return json;
}
function dataTypeParse(json) {
try {
json = json['util:ReferenceDataItem'];
} catch (e) {
throw new UtilsParsingError(json);
}
return json;
}
const errorHandler = function (rsp) {
let errorInfo;
let code;
try {
errorInfo = rsp.detail[`common_${this.uapi_version}:ErrorInfo`];
code = errorInfo[`common_${this.uapi_version}:Code`];
} catch (err) {
throw new RequestRuntimeError.UnhandledError(null, new UtilsRuntimeError(rsp));
}
switch (code) {
default:
throw new RequestRuntimeError.UnhandledError(null, new UtilsRuntimeError(rsp));
}
};
module.exports = {
UTILS_ERROR: errorHandler,
CURRENCY_CONVERSION: currencyConvertParse,
REFERENCE_DATATYPE: dataTypeParse,
};
|
Swap seeding positions of known/test user.
|
<?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use eien\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
User::create([
'name' => 'amatsuka',
'email' => 'amatsuka@amatsuka.amatsuka',
'username' => 'amatsuka',
'password' => bcrypt('kappa'),
'api_token' => str_random(60)
]);
foreach (range(1, 9) as $inx) {
User::create([
'name' => $faker->name,
'email' => $faker->email,
'username' => $faker->userName,
'password' => bcrypt('kappa')
]);
}
}
}
|
<?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use eien\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
foreach (range(1, 9) as $inx) {
User::create([
'name' => $faker->name,
'email' => $faker->email,
'username' => $faker->userName,
'password' => bcrypt('kappa')
]);
}
User::create([
'name' => 'amatsuka',
'email' => 'amatsuka@amatsuka.amatsuka',
'username' => 'amatsuka',
'password' => bcrypt('kappa'),
'api_token' => str_random(60)
]);
}
}
|
Remove loading of requirements from pip-requires
|
from setuptools import setup, find_packages
requirements = ['virtualenv', 'pyparsing==1.5.7', 'pydot==1.0.2']
desc = ''
with open('README.rst') as f:
desc = f.read()
setup(
name='packmap',
version='0.0.1',
description=('PackMap discovers all dependencies for a specific'
'Python package'),
long_description=(desc),
url='https://github.com/jmvrbanac/PackMap',
author='John Vrbanac',
author_email='john.vrbanac@linux.com',
license='Apache License 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.7',
'Operating System :: POSIX :: Linux',
'Environment :: Console',
'Topic :: Utilities'
],
keywords='discover package dependencies graph dependency requirement',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
install_requires=requirements,
package_data={},
data_files=[],
entry_points={
'console_scripts': [
'packmap = packmap.cli:main'
],
},
)
|
from setuptools import setup, find_packages
# Dirty requirements loads
requirements = []
with open('pip-requires') as f:
requirements = f.read().splitlines()
desc = ''
with open('README.rst') as f:
desc = f.read()
setup(
name='packmap',
version='0.0.1',
description=('PackMap discovers all dependencies for a specific'
'Python package'),
long_description=(desc),
url='https://github.com/jmvrbanac/PackMap',
author='John Vrbanac',
author_email='john.vrbanac@linux.com',
license='Apache License 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.7',
'Operating System :: POSIX :: Linux',
'Environment :: Console',
'Topic :: Utilities'
],
keywords='discover package dependencies graph dependency requirement',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
install_requires=requirements,
package_data={},
data_files=[],
entry_points={
'console_scripts': [
'packmap = packmap.cli:main'
],
},
)
|
Use brighter colors in contextual Graphite graphs
|
// TODO: This is not a real model or controller
App.Graphs = Ember.Controller.extend({
graph: function(emberId, entityName, entityType, numSeries) {
entityName = entityName.replace(/\./g, '-');
var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName '&graphVars={"colorList":"yellow,green,orange,red,blue,pink"}';
if (numSeries) url += '&numSeries=' + numSeries;
return Ember.$.ajax({
url: url,
type: 'GET',
dataType: 'json'
}).then(function (data) {
if (entityType == 'node') {
App.store.getById('node', emberId).set('graphs', App.associativeToNumericArray(data));
} else if (entityType == 'vm') {
App.store.getById('vm', emberId).set('graphs', App.associativeToNumericArray(data));
}
});
}
});
App.graphs = App.Graphs.create();
|
// TODO: This is not a real model or controller
App.Graphs = Ember.Controller.extend({
graph: function(emberId, entityName, entityType, numSeries) {
entityName = entityName.replace(/\./g, '-');
var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName;
if (numSeries) url += '&numSeries=' + numSeries;
return Ember.$.ajax({
url: url,
type: 'GET',
dataType: 'json'
}).then(function (data) {
if (entityType == 'node') {
App.store.getById('node', emberId).set('graphs', App.associativeToNumericArray(data));
} else if (entityType == 'vm') {
App.store.getById('vm', emberId).set('graphs', App.associativeToNumericArray(data));
}
});
}
});
App.graphs = App.Graphs.create();
|
Add background color for Toolbar
Fix #90
|
import React from 'react'
import { inject, observer } from 'mobx-react'
import Toolbar from './Toolbar'
import ToolbarIndicator from './ToolbarIndicator'
@inject('userStore')
@observer
export default class ToolbarWrapper extends React.Component {
render () {
const {
lazyHideToolbar, showToolbar
} = this.props.userStore
return (
<div onMouseEnter={showToolbar}
onMouseLeave={lazyHideToolbar}
style={{
display: 'flex',
width: 'fit-content',
position: 'fixed',
bottom: 0,
right: 0,
backgroundColor: 'rgba(255, 255, 255, 0.8)'
}}
>
<Toolbar />
<ToolbarIndicator />
</div>
)
}
}
|
import React from 'react'
import { inject, observer } from 'mobx-react'
import Toolbar from './Toolbar'
import ToolbarIndicator from './ToolbarIndicator'
@inject('userStore')
@observer
export default class ToolbarWrapper extends React.Component {
render () {
const {
lazyHideToolbar, showToolbar
} = this.props.userStore
return (
<div onMouseEnter={showToolbar}
onMouseLeave={lazyHideToolbar}
style={{
display: 'flex',
width: 'fit-content',
position: 'fixed',
bottom: 0,
right: 0
}}
>
<Toolbar />
<ToolbarIndicator />
</div>
)
}
}
|
Load intl packages from correct location
This path changed in the last major version to remove `dist`.
|
export async function loadPolyfills() {
await Promise.all([
intlPluralRules(),
intlRelativeTimeFormat(),
]);
}
async function intlPluralRules() {
if ('Intl' in window && 'PluralRules' in Intl) {
return;
}
await import('@formatjs/intl-pluralrules/polyfill');
await Promise.all([
import('@formatjs/intl-pluralrules/locale-data/en'),
import('@formatjs/intl-pluralrules/locale-data/es'),
import('@formatjs/intl-pluralrules/locale-data/fr'),
]);
}
async function intlRelativeTimeFormat() {
if ('Intl' in window && 'RelativeTimeFormat' in Intl) {
return;
}
await import('@formatjs/intl-relativetimeformat/polyfill');
await Promise.all([
import('@formatjs/intl-relativetimeformat/locale-data/en'),
import('@formatjs/intl-relativetimeformat/locale-data/es'),
import('@formatjs/intl-relativetimeformat/locale-data/fr'),
]);
}
|
export async function loadPolyfills() {
await Promise.all([
intlPluralRules(),
intlRelativeTimeFormat(),
]);
}
async function intlPluralRules() {
if ('Intl' in window && 'PluralRules' in Intl) {
return;
}
await import('@formatjs/intl-pluralrules/polyfill');
await Promise.all([
import('@formatjs/intl-pluralrules/dist/locale-data/en'),
import('@formatjs/intl-pluralrules/dist/locale-data/es'),
import('@formatjs/intl-pluralrules/dist/locale-data/fr'),
]);
}
async function intlRelativeTimeFormat() {
if ('Intl' in window && 'RelativeTimeFormat' in Intl) {
return;
}
await import('@formatjs/intl-relativetimeformat/polyfill');
await Promise.all([
import('@formatjs/intl-relativetimeformat/dist/locale-data/en'),
import('@formatjs/intl-relativetimeformat/dist/locale-data/es'),
import('@formatjs/intl-relativetimeformat/dist/locale-data/fr'),
]);
}
|
Add a logfile for tutorial01
|
package main
import (
"fmt"
"hge"
)
var h *hge.HGE
func FrameFunc() int {
if h.Input_GetKeyState(hge.K_ESCAPE) {
return 1
}
return 0
}
func main() {
h = hge.Create(hge.VERSION)
defer h.Release()
h.System_SetState(hge.LOGFILE, "tutorial01.log")
h.System_SetState(hge.FRAMEFUNC, FrameFunc)
h.System_SetState(hge.TITLE, "HGE Tutorial 01 - Minimal HGE application")
h.System_SetState(hge.WINDOWED, true)
h.System_SetState(hge.USESOUND, false)
h.System_Log("Test")
h.System_Log("Test vararg: %s %d", "test", 15)
if h.System_Initiate() {
defer h.System_Shutdown()
h.System_Log("Test")
h.System_Log("Test vararg: %s %d", "test", 15)
h.System_Start()
} else {
fmt.Println("Error: ", h.System_GetErrorMessage())
}
h.System_Log("Test")
}
|
package main
import (
"fmt"
"hge"
)
var h *hge.HGE
func FrameFunc() int {
if h.Input_GetKeyState(hge.K_ESCAPE) {
return 1
}
return 0
}
func main() {
h = hge.Create(hge.VERSION)
defer h.Release()
h.System_SetState(hge.FRAMEFUNC, FrameFunc)
h.System_SetState(hge.TITLE, "HGE Tutorial 01 - Minimal HGE application")
h.System_SetState(hge.WINDOWED, true)
h.System_SetState(hge.USESOUND, false)
h.System_Log("Test")
h.System_Log("Test vararg: %s %d", "test", 15)
if h.System_Initiate() {
defer h.System_Shutdown()
h.System_Log("Test")
h.System_Log("Test vararg: %s %d", "test", 15)
h.System_Start()
} else {
fmt.Println("Error: ", h.System_GetErrorMessage())
}
h.System_Log("Test")
}
|
Fix accidental context menu opening in Windows
|
import $ from 'jquery'
export default function GameScene(display) {
return function (container) {
let handler = () => false
$(window).on('touchstart', handler)
showCanvas(display, container)
return {
teardown() {
$(window).off('touchstart', handler)
},
}
}
}
function showCanvas(display, container) {
var { view, wrapper } = display
var { width, height } = view
container.appendChild(wrapper)
container.addEventListener('touchstart', disableContextMenu)
function disableContextMenu() {
container.removeEventListener('touchstart', disableContextMenu)
container.addEventListener('contextmenu', e => {
e.preventDefault()
})
}
resize()
$(window).on('resize', resize)
function resize() {
var scale = Math.min(window.innerWidth / width, window.innerHeight / height)
view.style.width = Math.round(width * scale) + 'px'
view.style.height = Math.round(height * scale) + 'px'
wrapper.style.width = Math.round(width * scale) + 'px'
wrapper.style.height = Math.round(height * scale) + 'px'
var yOffset = (window.innerHeight - height * scale) / 2
wrapper.style.marginTop = Math.round(yOffset) + 'px'
}
return wrapper
}
|
import $ from 'jquery'
export default function GameScene(display) {
return function (container) {
let handler = () => false
$(window).on('touchstart', handler)
showCanvas(display, container)
return {
teardown() {
$(window).off('touchstart', handler)
},
}
}
}
function showCanvas(display, container) {
var { view, wrapper } = display
var { width, height } = view
container.appendChild(wrapper)
resize()
$(window).on('resize', resize)
function resize() {
var scale = Math.min(window.innerWidth / width, window.innerHeight / height)
view.style.width = Math.round(width * scale) + 'px'
view.style.height = Math.round(height * scale) + 'px'
wrapper.style.width = Math.round(width * scale) + 'px'
wrapper.style.height = Math.round(height * scale) + 'px'
var yOffset = (window.innerHeight - height * scale) / 2
wrapper.style.marginTop = Math.round(yOffset) + 'px'
}
return wrapper
}
|
Use mocha style reporting for tests
|
var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ], // use PhantomJS for now (@gordyd - I'm using a VM)
singleRun: true,
frameworks: [ 'mocha', 'sinon' ], // Mocha is our testing framework of choice
files: [
'tests.webpack.js' //just load this file
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader
},
reporters: [ 'mocha', 'dot' ],
webpack: { // kind of a copy of your webpack config
devtool: 'inline-source-map', //just do inline source maps instead of the default
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader' },
{ test: /\.json$/, loader: 'json-loader' }
]
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
}
});
};
|
var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ 'PhantomJS' ], // use PhantomJS for now (@gordyd - I'm using a VM)
singleRun: true,
frameworks: [ 'mocha', 'sinon' ], // Mocha is our testing framework of choice
files: [
'tests.webpack.js' //just load this file
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ] //preprocess with webpack and our sourcemap loader
},
reporters: [ 'dots' ], //report results in this format
webpack: { //kind of a copy of your webpack config
devtool: 'inline-source-map', //just do inline source maps instead of the default
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader' },
{ test: /\.json$/, loader: 'json-loader' }
]
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
}
});
};
|
Make class serializable so that it'll work with the session stuff
|
/*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.sys.businessobject;
import java.io.Serializable;
/**
* AccountingLineDecoration contains information needed by the user interface to display a given AccountingLine.
*/
public class AccountingLineDecorator implements Serializable {
private boolean revertible;
public AccountingLineDecorator() {
revertible = false;
}
public boolean getRevertible() {
return revertible;
}
public void setRevertible(boolean revertible) {
this.revertible = revertible;
}
}
|
/*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.sys.businessobject;
/**
* AccountingLineDecoration contains information needed by the user interface to display a given AccountingLine.
*/
public class AccountingLineDecorator {
private boolean revertible;
public AccountingLineDecorator() {
revertible = false;
}
public boolean getRevertible() {
return revertible;
}
public void setRevertible(boolean revertible) {
this.revertible = revertible;
}
}
|
Change PyPI development status from pre-alpha to beta.
|
#!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cross-platform colored terminal text.',
long_description=get_long_description('README.txt'),
keywords='color colour terminal text ansi windows crossplatform xplatform',
author='Jonathan Hartley',
author_email='tartley@tartley.com',
url='http://code.google.com/p/colorama/',
license='BSD',
packages=[NAME],
# see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Terminals',
]
)
|
#!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cross-platform colored terminal text.',
long_description=get_long_description('README.txt'),
keywords='color colour terminal text ansi windows crossplatform xplatform',
author='Jonathan Hartley',
author_email='tartley@tartley.com',
url='http://code.google.com/p/colorama/',
license='BSD',
packages=[NAME],
# see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Topic :: Terminals',
]
)
|
Fix check for cls attribute
* If resolved_view has a cls attribute then view should already be a
class.
|
import warnings
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLTestMixin(object):
def assert_url_matches_view(self, view, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the expected view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
resolved_view = resolve(expected_url).func
if hasattr(resolved_view, 'cls'):
self.assertEqual(resolved_view.cls, view)
else:
self.assertEqual(resolved_view.__name__, view.__name__)
class URLTestCase(URLTestMixin, TestCase):
pass
|
import warnings
from django.core.urlresolvers import resolve, reverse
from django.test import TestCase
class URLTestMixin(object):
def assert_url_matches_view(self, view, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the expected view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
resolved_view = resolve(expected_url).func
if hasattr(view, 'cls'):
self.assertEqual(resolved_view.cls, view)
else:
self.assertEqual(resolved_view.__name__, view.__name__)
class URLTestCase(URLTestMixin, TestCase):
pass
|
Update to ensure backwards compatibility for Laravel 5.8 and below
|
<?php
namespace Coreplex\Meta\Managers;
use Illuminate\Support\Manager;
use Coreplex\Meta\Eloquent\Repository as EloquentRepository;
class Store extends Manager
{
public function createEloquentDriver()
{
return new EloquentRepository;
}
/**
* Get the default authentication driver name.
*
* @return string
*/
public function getDefaultDriver()
{
$container = ! empty($this->container) ? $this->container : $this->app;
return $container['config']['drivers.store'];
}
/**
* Set the default authentication driver name.
*
* @param string $name
* @return void
*/
public function setDefaultDriver($name)
{
$container = ! empty($this->container) ? $this->container : $this->app;
$container['config']['drivers.store'] = $name;
}
}
|
<?php
namespace Coreplex\Meta\Managers;
use Illuminate\Support\Manager;
use Coreplex\Meta\Eloquent\Repository as EloquentRepository;
class Store extends Manager
{
public function createEloquentDriver()
{
return new EloquentRepository;
}
/**
* Get the default authentication driver name.
*
* @return string
*/
public function getDefaultDriver()
{
return $this->container['config']['drivers.store'];
}
/**
* Set the default authentication driver name.
*
* @param string $name
* @return void
*/
public function setDefaultDriver($name)
{
$this->container['config']['drivers.store'] = $name;
}
}
|
Fix the flex on panels with buttons
|
import React from "react";
class IntroWithButton extends React.Component {
static displayName = "Panel.IntroWithButton";
static propTypes = {
children: React.PropTypes.node.isRequired
};
render() {
let children = React.Children.toArray(this.props.children);
let intro;
let button;
if(children.length == 1) {
intro = children;
} else {
button = children.pop();
intro = children;
}
if(button) {
button = (
<div className="ml3 flex-none">
{button}
</div>
);
}
return (
<div className="py3 px3 flex">
<div className="flex-auto">{intro}</div>
{button}
</div>
);
}
}
export default IntroWithButton;
|
import React from "react";
class IntroWithButton extends React.Component {
static displayName = "Panel.IntroWithButton";
static propTypes = {
children: React.PropTypes.node.isRequired
};
render() {
let children = React.Children.toArray(this.props.children);
let intro;
let button;
if(children.length == 1) {
intro = children;
} else {
button = children.pop();
intro = children;
}
if(button) {
button = (
<div className="ml3 flex-no-shrink">
{button}
</div>
);
}
return (
<div className="py3 px3 flex">
{intro}
{button}
</div>
);
}
}
export default IntroWithButton;
|
BAP-4210: Add EntityExtendBundle dumper extension to generate activity association entities. Refactoring
|
<?php
namespace Oro\Bundle\EntityExtendBundle\Tools;
use Oro\Bundle\EntityConfigBundle\Config\ConfigInterface;
abstract class MultipleAssociationExtendConfigDumperExtension extends AbstractAssociationExtendConfigDumperExtension
{
/**
* {@inheritdoc}
*/
protected function getAssociationType()
{
return 'manyToMany';
}
/**
* {@inheritdoc}
*/
protected function isTargetEntityApplicable(ConfigInterface $targetEntityConfig)
{
$entityClasses = $targetEntityConfig->get($this->getAssociationAttributeName());
return !empty($entityClasses);
}
/**
* {@inheritdoc}
*/
public function preUpdate(array &$extendConfigs)
{
$targetEntityConfigs = $this->getTargetEntityConfigs();
foreach ($targetEntityConfigs as $targetEntityConfig) {
$entityClasses = $targetEntityConfig->get($this->getAssociationAttributeName());
if (!empty($entityClasses)) {
$targetEntityClass = $targetEntityConfig->getId()->getClassName();
foreach ($entityClasses as $entityClass) {
$this->createAssociation($entityClass, $targetEntityClass);
}
}
}
}
}
|
<?php
namespace Oro\Bundle\EntityExtendBundle\Tools;
use Oro\Bundle\EntityConfigBundle\Config\ConfigInterface;
abstract class MultipleAssociationExtendConfigDumperExtension extends AbstractAssociationExtendConfigDumperExtension
{
/**
* {@inheritdoc}
*/
protected function getAssociationType()
{
return 'manyToMany';
}
/**
* {@inheritdoc}
*/
protected function isTargetEntityApplicable(ConfigInterface $targetEntityConfig)
{
$entityClasses = $targetEntityConfig->get($this->getAssociationAttributeName());
return !empty($entityClasses);
}
/**
* {@inheritdoc}
*/
public function preUpdate(array &$extendConfigs)
{
$targetEntityConfigs = $this->getTargetEntityConfigs();
foreach ($targetEntityConfigs as $targetEntityConfig) {
$entityClasses = $targetEntityConfig->get($this->getAssociationAttributeName());
if (!empty($entityClasses)) {
foreach ($entityClasses as $entityClass) {
$this->createAssociation($entityClass, $targetEntityConfig->getId()->getClassName());
}
}
}
}
}
|
Fix stale environment header vhost metadata
*Really* closes
https://github.com/aptible/dashboard.aptible.com/issues/496 by binding
the computed vhost metadata to the parent environment.
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
maxVisibleDomainNames: 1,
displayVhostNames: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames').join(', ');
}),
showVhostTooltip: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames');
}),
vhostRemaining: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames');
}),
vhostNamesSnippet: Ember.computed('model.vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(0, this.get('maxVisibleDomainNames')).join(', ');
}),
vhostNamesTooltip: Ember.computed('model.vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(this.get('maxVisibleDomainNames')).join(', ');
})
});
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: '',
maxVisibleDomainNames: 1,
displayVhostNames: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames').join(', ');
}),
showVhostTooltip: Ember.computed('model.vhostNames', function() {
return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames');
}),
vhostRemaining: Ember.computed('vhostNames', function() {
return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames');
}),
vhostNamesSnippet: Ember.computed('vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(0, this.get('maxVisibleDomainNames')).join(', ');
}),
vhostNamesTooltip: Ember.computed('vhostNames', function() {
let names = this.model.get('vhostNames');
return names.slice(this.get('maxVisibleDomainNames')).join(', ');
})
});
|
Use Vary header by default
|
package core
import "net/http"
type handlersStack []func(*Context)
var handlers handlersStack
// Use adds a handler to the handlers stack.
func Use(h func(*Context)) {
handlers = append(handlers, h)
}
func (h handlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Init a new context for the request.
c := &Context{
ResponseWriter: w,
Request: r,
index: -1, // Begin with -1 because the NextWriter will increment index before calling the first handler.
}
// Enter the handlers stack.
// We use a binder to set the c.written flag on first write and break handlers chain.
c.ResponseWriter = ResponseWriterBinder{
Writer: c.ResponseWriter,
ResponseWriter: c.ResponseWriter,
BeforeWrite: func([]byte) { c.written = true },
}
// Use default headers.
c.ResponseWriter.Header().Set("Connection", "keep-alive")
c.ResponseWriter.Header().Set("Vary", "Accept-Encoding")
c.Next()
}
|
package core
import "net/http"
type handlersStack []func(*Context)
var handlers handlersStack
// Use adds a handler to the handlers stack.
func Use(h func(*Context)) {
handlers = append(handlers, h)
}
func (h handlersStack) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Init a new context for the request.
c := &Context{
ResponseWriter: w,
Request: r,
index: -1, // Begin with -1 because the NextWriter will increment index before calling the first handler.
}
// Enter the handlers stack.
// We use a binder to set the c.written flag on first write and break handlers chain.
c.ResponseWriter = ResponseWriterBinder{
Writer: c.ResponseWriter,
ResponseWriter: c.ResponseWriter,
BeforeWrite: func([]byte) { c.written = true },
}
// Say to the client to "keep-alive" by default.
c.ResponseWriter.Header().Set("Connection", "keep-alive")
c.Next()
}
|
Refactor to reuse test case initialization code
|
/* global describe it beforeEach */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonChai)
const expect = chai.expect
describe('exec', function () {
let exec
let stubs
beforeEach(function () {
exec = sinon.stub()
stubs = {
child_process: {
exec
}
}
})
it('rejects if childProcess.exec fails', function () {
exec.yields('some error')
const util = requireInject('../lib/util', stubs)
return expect(util.exec('command'))
.to.be.eventually.rejectedWith('some error')
})
it('resolves if childProcess.exec succeeds', function () {
exec.yields(null, 'stdout', 'stderr')
const util = requireInject('../lib/util', stubs)
return expect(util.exec('command')).to.eventually.deep.equal({
command: 'command',
stdout: 'stdout',
stderr: 'stderr'
})
})
})
|
/* global describe it */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonChai)
const expect = chai.expect
describe('exec', function () {
it('rejects if childProcess.exec fails', function () {
const exec = sinon.stub().yields('some error')
const stubs = {
child_process: {
exec
}
}
const util = requireInject('../lib/util', stubs)
return expect(util.exec('command'))
.to.be.eventually.rejectedWith('some error')
})
it('resolves if childProcess.exec succeeds', function () {
const exec = sinon.stub().yields(null, 'stdout', 'stderr')
const stubs = {
child_process: {
exec
}
}
const util = requireInject('../lib/util', stubs)
return expect(util.exec('command')).to.eventually.deep.equal({
command: 'command',
stdout: 'stdout',
stderr: 'stderr'
})
})
})
|
Fix cookie not being parsed on load.
If you have to stringify your object before saving, and you add that,
to the `_cookies` cache, then you'll return that on `load` after setting
it with `save`.
While if the value is already set, the script correctly parses the cookie
values and what you load is returned as an object.
This oneliner takes care of that for you.
|
var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
_cookies[name] = val;
// Cookies only work in the browser
if (typeof document === 'undefined') return;
// allow you to work with cookies as objects.
if (typeof val === 'object') val = JSON.stringify(val);
document.cookie = cookie.serialize(name, val, opt);
}
var reactCookie = {
load: load,
save: save
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
|
var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
_cookies[name] = val;
// Cookies only work in the browser
if (typeof document === 'undefined') return;
document.cookie = cookie.serialize(name, val, opt);
}
var reactCookie = {
load: load,
save: save
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
|
Fix path for custom plugin
|
/* jshint node: true */
'use strict';
const Funnel = require('broccoli-funnel');
const path = require('path');
const mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-bootstrap-datetimepicker',
included: function(app) {
this._super.included(app);
// Import unminified css and js
let basePath = `${this.treePaths.vendor}/eonasdan-bootstrap-datetimepicker`;
app.import(`${basePath}/build/css/bootstrap-datetimepicker.css`);
app.import(`${basePath}/src/js/bootstrap-datetimepicker.js`);
},
treeForVendor: function(vendorTree) {
let trees = [];
if (vendorTree) {
trees.push(vendorTree);
}
let datetimepickerJs = require.resolve('eonasdan-bootstrap-datetimepicker-ie');
let datetimepickerPath = path.join(path.dirname(datetimepickerJs), '../../');
trees.push(new Funnel(datetimepickerPath, {
destDir: 'eonasdan-bootstrap-datetimepicker',
include: ['build/css/bootstrap-datetimepicker.css', 'src/js/bootstrap-datetimepicker.js']
}));
return mergeTrees(trees);
}
};
|
/* jshint node: true */
'use strict';
const Funnel = require('broccoli-funnel');
const path = require('path');
const mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-bootstrap-datetimepicker',
included: function(app) {
this._super.included(app);
// Import unminified css and js
let basePath = `${this.treePaths.vendor}/eonasdan-bootstrap-datetimepicker`;
app.import(`${basePath}/build/css/bootstrap-datetimepicker.css`);
app.import(`${basePath}/src/js/bootstrap-datetimepicker.js`);
},
treeForVendor: function(vendorTree) {
let trees = [];
if (vendorTree) {
trees.push(vendorTree);
}
let datetimepickerJs = require.resolve('eonasdan-bootstrap-datetimepicker');
let datetimepickerPath = path.join(path.dirname(datetimepickerJs), '../../');
trees.push(new Funnel(datetimepickerPath, {
destDir: 'eonasdan-bootstrap-datetimepicker',
include: ['build/css/bootstrap-datetimepicker.css', 'src/js/bootstrap-datetimepicker.js']
}));
return mergeTrees(trees);
}
};
|
Redux: Create our own createStore and fix typo
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// import {createStore} from 'redux';
// ReactDOM.render(<App />, document.getElementById('app'));
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
const createStore = (render) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = render(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};
dispatch({});
return {getState, dispatch, subscribe};
}
const store = createStore(counter);
// This is the callback for store
// whenver there is an dispatcher event.
const render = () => {
document.body.innerText = store.getState();
if (store.getState() === 10) {
// Unsubscribe!!
subsciption();
}
};
var subsciption = store.subscribe(render);
render();
document.addEventListener('click', () => {
store.dispatch({type: 'INCREMENT'});
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// import {createStore} from 'redux';
// ReactDOM.render(<App />, document.getElementById('app'));
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
const createStore = (render) => {
let state;
let listeners = [];
const getState = () => state;
const = (action) => {
state = render(state, action);
listeners.forEach(listener => listener());
};
const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};
dispatch({});
return {getState, dispatch, subscribe};
}
const store = createStore(counter);
// This is the callback for store
// whenver there is an dispatcher event.
const render = () => {
document.body.innerText = store.getState();
if (store.getState() === 10) {
// Unsubscribe!!
subsciption();
}
};
var subsciption = store.subscribe(render);
render();
document.addEventListener('click', () => {
store.dispatch({type: 'INCREMENT'});
});
|
Test all methods are found by factory reparceler.
|
package pl.mg6.testsupport;
import junit.framework.TestCase;
import java.util.List;
import pl.mg6.testsupport.data.Simple;
import pl.mg6.testsupport.factory.SimpleFactory;
public class FactoryReparcelerTestCase extends TestCase {
private final FactoryReparceler reparceler = new FactoryReparceler();
public void testSimpleParcelableShouldBeEqual() {
List<ReparcelingResult<Simple>> resultList = reparceler.reparcel(SimpleFactory.class, Simple.class);
for (ReparcelingResult<Simple> result : resultList) {
assertNotNull(result.getOriginal());
assertNotNull(result.getReparceled());
assertNotSame(result.getOriginal(), result.getReparceled());
assertTrue(result.areEqual());
assertNull(result.getError());
}
}
public void testFactoryReparcelerShouldFindAllMethods() {
List<ReparcelingResult<Simple>> resultList = reparceler.reparcel(SimpleFactory.class, Simple.class);
assertEquals(3, resultList.size());
assertEquals("withZero", resultList.get(2).getMethodName());
assertEquals("withPerfectNumber", resultList.get(1).getMethodName());
assertEquals("withMaxValue", resultList.get(0).getMethodName());
}
}
|
package pl.mg6.testsupport;
import junit.framework.TestCase;
import java.util.List;
import pl.mg6.testsupport.data.Simple;
import pl.mg6.testsupport.factory.SimpleFactory;
public class FactoryReparcelerTestCase extends TestCase {
private final FactoryReparceler reparceler = new FactoryReparceler();
public void testSimpleParcelableShouldBeEqual() {
List<ReparcelingResult<Simple>> resultList = reparceler.reparcel(SimpleFactory.class, Simple.class);
for (ReparcelingResult<Simple> result : resultList) {
assertNotNull(result.getOriginal());
assertNotNull(result.getReparceled());
assertNotSame(result.getOriginal(), result.getReparceled());
assertTrue(result.areEqual());
assertNull(result.getError());
}
}
}
|
Handle no latest event (fixes GH-1727)
|
from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, group):
"""
Retrieve the latest sample for an aggregate
Return details on the latest sample for this aggregate.
{method} {path}
"""
event = group.get_latest_event()
if not event:
return Response({'detail': 'No events found for group'}, status=404)
try:
return client.get('/events/{}/'.format(event.id), request.user, request.auth)
except client.ApiError as e:
return Response(e.body, status=e.status_code)
|
from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api import client
from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
class GroupEventsLatestEndpoint(GroupEndpoint):
doc_section = DocSection.EVENTS
def get(self, request, group):
"""
Retrieve the latest sample for an aggregate
Return details on the latest sample for this aggregate.
{method} {path}
"""
event = group.get_latest_event()
try:
return client.get('/events/{}/'.format(event.id), request.user, request.auth)
except client.ApiError as e:
return Response(e.body, status=e.status_code)
|
Add a test case for instanceof expressions
|
// fails
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// NAME_NOT_FOUND
// TYPE_MISMATCH
package java.util;
// import java.lang.*;
import java.io.File;
import java.io.JFile; // fails
class A extends Object {
String fname = "filename";
File file = new java.io.File(fname);
JFile jfile = new JFile(fname); /* fails four times:
1- The first use of JFille
2- The second use of JFille
3- The missing constructor of JFille
4- The unresolved types information
*/
Object b1 = new Object();
Object b2 = new Object();
Object b3 = new Object();
public String m(String a) {
if("" instanceof String) {
System.out.println("");
}
String s = "";
Object b4 = new Object();
Object b5 = new Object();
return m(s);
}
}
|
// fails
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// TYPE_NOT_FOUND
// NAME_NOT_FOUND
// TYPE_MISMATCH
package java.util;
// import java.lang.*;
import java.io.File;
import java.io.JFile; // fails
class A extends Object {
String fname = "filename";
File file = new java.io.File(fname);
JFile jfile = new JFile(fname); /* fails four times:
1- The first use of JFille
2- The second use of JFille
3- The missing constructor of JFille
4- The unresolved types information
*/
Object b1 = new Object();
Object b2 = new Object();
Object b3 = new Object();
public String m(String a) {
String s = "";
Object b4 = new Object();
Object b5 = new Object();
return m(s);
}
}
|
Fix request logger for use cases when childLogger middleware was not
used.
|
var uuid = require('node-uuid');
var bunyan = require('bunyan');
module.exports = function(loggerInstance) {
if (!loggerInstance) {
var opts = {
stream: process.stdout,
serializers: {
req: bunyan.stdSerializers.req
}
};
loggerInstance = bunyan.createLogger(opts);
}
return {
childLogger: function(req, res, next) {
var reqId = uuid.v1();
req.log = loggerInstance.child({req_id: reqId});
next();
},
requestLogger: function(req, res, next) {
var log = req.log || loggerInstance;
log.info({req: req}, 'HTTP');
next();
}
}
};
|
var uuid = require('node-uuid');
var bunyan = require('bunyan');
module.exports = function(loggerInstance) {
if (!loggerInstance) {
var opts = {
stream: process.stdout,
serializers: {
req: bunyan.stdSerializers.req
}
};
loggerInstance = bunyan.createLogger(opts);
}
return {
childLogger: function(req, res, next) {
var reqId = uuid.v1();
req.log = loggerInstance.child({req_id: reqId});
next();
},
requestLogger: function(req, res, next) {
req.log.info({req: req}, 'HTTP');
next();
}
}
};
|
Include trailing slash in URL.
|
package tempredis
import "fmt"
// Config is a key-value map of Redis config settings.
type Config map[string]string
// Host returns the host for a Redis server configured with this Config as
// "host:port".
func (c Config) Host() string {
bind, ok := c["bind"]
if !ok {
bind = "127.0.0.1"
}
port, ok := c["port"]
if !ok {
port = "6379"
}
return fmt.Sprintf("%s:%s", bind, port)
}
// URL returns a Redis URL for a Redis server configured with this Config.
func (c Config) URL() string {
password := c.Password()
if len(password) == 0 {
return fmt.Sprintf("redis://%s/", c.Host())
} else {
return fmt.Sprintf("redis://:%s@%s/", password, c.Host())
}
}
// Password returns the password for a Redis server configured with this
// Config. If the server doesn't require authentication, an empty string will
// be returned.
func (c Config) Password() string {
return c["requirepass"]
}
|
package tempredis
import "fmt"
// Config is a key-value map of Redis config settings.
type Config map[string]string
// Host returns the host for a Redis server configured with this Config as
// "host:port".
func (c Config) Host() string {
bind, ok := c["bind"]
if !ok {
bind = "127.0.0.1"
}
port, ok := c["port"]
if !ok {
port = "6379"
}
return fmt.Sprintf("%s:%s", bind, port)
}
// URL returns a Redis URL for a Redis server configured with this Config.
func (c Config) URL() string {
password := c.Password()
if len(password) == 0 {
return fmt.Sprintf("redis://%s", c.Host())
} else {
return fmt.Sprintf("redis://:%s@%s", password, c.Host())
}
}
// Password returns the password for a Redis server configured with this
// Config. If the server doesn't require authentication, an empty string will
// be returned.
func (c Config) Password() string {
return c["requirepass"]
}
|
Fix and add terminate to set Content-Type and Accept header
|
<?php
namespace Stack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
class JsonRequest implements HttpKernelInterface, TerminableInterface
{
private $app;
private $contentType;
public function __construct(HttpKernelInterface $app, $contentType = 'application/json')
{
$this->app = $app;
$this->contentType = $contentType;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if (0 === strpos($request->headers->get('Content-Type'), $this->contentType)) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
return $this->app->handle($request, $type, $catch);
}
public function terminate(Request $request, Response $response)
{
$request->headers->set('Content-Type', $this->contentType);
$request->headers->set('Accept', $this->contentType);
if ($this->app instanceof TerminableInterface) {
$this->app->terminate($request, $response);
}
}
}
|
<?php
namespace Stack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class JsonRequest implements HttpKernelInterface
{
private $app;
private $contentTypes = array('application/json');
public function __construct(HttpKernelInterface $app, array $contentTypes = array())
{
$this->app = $app;
}
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if (in_array($request->headers->get('Content-Type'), $this->contentTypes, true)) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
return $this->app->handle($request, $type, $catch);
}
}
|
Replace definition of missing constant PREG_BAD_UTF8_OFFSET_ERROR in HHVM by not using it at all
|
<?php
namespace Gobie\Regex\Drivers\Pcre;
use Gobie\Regex\RegexException;
class PcreRegexException extends RegexException
{
public static $messages = array(
PREG_INTERNAL_ERROR => 'Internal error',
PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data',
// HHVM fix, constant PREG_BAD_UTF8_OFFSET_ERROR replaced by its number
5 => 'The offset didn\'t correspond to the begin of a valid UTF-8 code point',
);
public function __construct($message, $code = null, $pattern = null)
{
if (!$message && isset(self::$messages[$code])) {
$message = self::$messages[$code];
}
parent::__construct($message, $code, $pattern);
}
}
|
<?php
namespace Gobie\Regex\Drivers\Pcre;
use Gobie\Regex\RegexException;
// hhvm fix
if (!\defined('PREG_BAD_UTF8_OFFSET_ERROR')) {
\define('PREG_BAD_UTF8_OFFSET_ERROR', 5);
};
class PcreRegexException extends RegexException
{
public static $messages = array(
PREG_INTERNAL_ERROR => 'Internal error',
PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data',
PREG_BAD_UTF8_OFFSET_ERROR => 'The offset didn\'t correspond to the begin of a valid UTF-8 code point',
);
public function __construct($message, $code = null, $pattern = null)
{
if (!$message && isset(self::$messages[$code])) {
$message = self::$messages[$code];
}
parent::__construct($message, $code, $pattern);
}
}
|
Add Sponsor component to home page
|
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Theme from '../../../config/theme';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import UpIcon from 'material-ui/svg-icons/navigation/arrow-upward';
import Header from '../Header';
import News from '../News';
import Sponsor from '../Sponsor';
import styles from './index.css';
class App extends React.Component {
render () {
return (
<MuiThemeProvider muiTheme={Theme}>
<div>
<Header />
<News />
<Sponsor />
</div>
</MuiThemeProvider>
)
}
};
export default App;
|
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Theme from '../../../config/theme';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import UpIcon from 'material-ui/svg-icons/navigation/arrow-upward';
import Header from '../Header';
import News from '../News';
import styles from './index.css';
class App extends React.Component {
render () {
return (
<MuiThemeProvider muiTheme={Theme}>
<div>
<Header />
<News />
</div>
</MuiThemeProvider>
)
}
};
export default App;
|
Add Python 3.6 to classifiers
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="exec-wrappers",
version='1.0.3',
author="Guilherme Quentel Melo",
author_email="gqmelo@gmail.com",
url="https://github.com/gqmelo/exec-wrappers",
license="MIT",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
description="wrappers for running commands that need some initial setup",
long_description=open('README.rst').read(),
packages=['exec_wrappers'],
entry_points={'console_scripts': 'create-wrappers = exec_wrappers.create_wrappers:main'},
package_data={'exec_wrappers': ['templates/*/*']},
include_package_data=True,
install_requires=[],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="exec-wrappers",
version='1.0.3',
author="Guilherme Quentel Melo",
author_email="gqmelo@gmail.com",
url="https://github.com/gqmelo/exec-wrappers",
license="MIT",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
description="wrappers for running commands that need some initial setup",
long_description=open('README.rst').read(),
packages=['exec_wrappers'],
entry_points={'console_scripts': 'create-wrappers = exec_wrappers.create_wrappers:main'},
package_data={'exec_wrappers': ['templates/*/*']},
include_package_data=True,
install_requires=[],
)
|
Use of 'Else' for Stop Executing After Occuring Error
|
var registerAction = require('../logic/account/registerAction')
var userChecker = require('../logic/account/userChecker')
exports.register = {
name: "register",
description: "Register a User",
run: function (api, data, next) {
var payload = JSON.parse(JSON.stringify(data.connection.rawConnection.params.body))
userChecker.startUserChecking(api.redisClient, payload.accountModel, function (err, result) {
if (err) {
data.response.error = err.error
next(err)
} else {
registerAction.register(api.redisClient, payload, function (err, replies) {
if (err) {
data.response.error = err.error
next(err)
}
data.response.result = replies
next()
})
}
})
}
}
|
var registerAction = require('../logic/account/registerAction')
var userChecker = require('../logic/account/userChecker')
exports.register = {
name: "register",
description: "Register a User",
run: function(api, data, next) {
var payload = JSON.parse(JSON.stringify(data.connection.rawConnection.params.body))
userChecker.startUserChecking(api.redisClient, payload.accountModel, function(err, result) {
if (err) {
data.response.error = err.error
next(err)
}
registerAction.register(api.redisClient, payload, function (err, replies) {
if (err) {
data.response.error = err.error
next(err)
}
data.response.result = replies
next()
})
})
}
}
|
Use sorted on the set to parametrize tests so that pytest-xdist works
|
import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(getattr(cupyx.scipy.special, f), cupy.ufunc)
}
@testing.gpu
@testing.with_requires("scipy")
@pytest.mark.parametrize("ufunc", sorted(cupyx_scipy_ufuncs & scipy_ufuncs))
class TestUfunc:
@testing.numpy_cupy_allclose(atol=1e-5)
def test_dispatch(self, xp, ufunc):
ufunc = getattr(scipy.special, ufunc)
# some ufunc (like sph_harm) do not work with float inputs
# therefore we retrieve the types from the ufunc itself
types = ufunc.types[0]
args = [
cupy.testing.shaped_random((5,), xp, dtype=types[i])
for i in range(ufunc.nargs - 1)
]
res = ufunc(*args)
assert type(res) == xp.ndarray
return res
|
import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(getattr(cupyx.scipy.special, f), cupy.ufunc)
}
@testing.gpu
@testing.with_requires("scipy")
@pytest.mark.parametrize("ufunc", cupyx_scipy_ufuncs & scipy_ufuncs)
class TestUfunc:
@testing.numpy_cupy_allclose(atol=1e-5)
def test_dispatch(self, xp, ufunc):
ufunc = getattr(scipy.special, ufunc)
# some ufunc (like sph_harm) do not work with float inputs
# therefore we retrieve the types from the ufunc itself
types = ufunc.types[0]
args = [
cupy.testing.shaped_random((5,), xp, dtype=types[i])
for i in range(ufunc.nargs - 1)
]
res = ufunc(*args)
assert type(res) == xp.ndarray
return res
|
perf(mapboxgl): Disable interactivity on the mapbox gl layer since it is handled by leaflet
|
import L from 'leaflet'
import {} from 'mapbox-gl-leaflet'
import {GridLayer, withLeaflet} from 'react-leaflet'
const accessToken = process.env.MAPBOX_ACCESS_TOKEN
const attribution = `© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>`
const defaultStyle = 'mapbox/light-v10'
const getStyle = (style = defaultStyle) => `mapbox://styles/${style}`
class MapBoxGLLayer extends GridLayer {
componentDidUpdate() {
if (this.leafletElement && this.leafletElement._glMap) {
this.leafletElement._glMap.resize()
}
}
createLeafletElement(props) {
return L.mapboxGL({
accessToken,
attribution,
interactive: false,
pane: props.leaflet.map._panes.tilePane,
style: getStyle(props.style)
})
}
}
export default withLeaflet(MapBoxGLLayer)
|
import L from 'leaflet'
import {} from 'mapbox-gl-leaflet'
import {GridLayer, withLeaflet} from 'react-leaflet'
const accessToken = process.env.MAPBOX_ACCESS_TOKEN
const attribution = `© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>`
const defaultStyle = 'mapbox/light-v10'
const getStyle = (style = defaultStyle) => `mapbox://styles/${style}`
class MapBoxGLLayer extends GridLayer {
componentDidUpdate() {
if (this.leafletElement && this.leafletElement._glMap) {
this.leafletElement._glMap.resize()
}
}
createLeafletElement(props) {
return L.mapboxGL({
accessToken,
attribution,
pane: props.leaflet.map._panes.tilePane,
style: getStyle(props.style)
})
}
}
export default withLeaflet(MapBoxGLLayer)
|
Add a private constructor to hide the implicit public one
Add a private constructor to hide the implicit public one on
OpenConfigComparatorFactory.
Change-Id: Id24e1b3bb8c59e0eaed71093acd4443e75ac50db
Signed-off-by: Claudio D. Gasparini <3480fb4575078d890be8aed0007cb1d8785aa579@cisco.com>
|
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.openconfig.impl.comparator;
import com.google.common.collect.ImmutableMap;
import org.opendaylight.protocol.bgp.openconfig.impl.spi.OpenConfigComparator;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.Bgp;
import org.opendaylight.yangtools.yang.binding.DataObject;
public final class OpenConfigComparatorFactory {
private OpenConfigComparatorFactory() {
throw new UnsupportedOperationException();
}
private static final ImmutableMap<Class<?>, OpenConfigComparator<? extends DataObject>> COMPARATORS = ImmutableMap.<Class<?>, OpenConfigComparator<? extends DataObject>>builder()
.put(Bgp.class, new GlobalComparator())
.put(Neighbor.class, new NeighborComparator())
.build();
public static <T extends DataObject> OpenConfigComparator<T> getComparator(final Class<T> clazz) {
return (OpenConfigComparator<T>) COMPARATORS.get(clazz);
}
}
|
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.bgp.openconfig.impl.comparator;
import com.google.common.collect.ImmutableMap;
import org.opendaylight.protocol.bgp.openconfig.impl.spi.OpenConfigComparator;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.Bgp;
import org.opendaylight.yangtools.yang.binding.DataObject;
public final class OpenConfigComparatorFactory {
private static final ImmutableMap<Class<?>, OpenConfigComparator<? extends DataObject>> COMPARATORS = ImmutableMap.<Class<?>, OpenConfigComparator<? extends DataObject>>builder()
.put(Bgp.class, new GlobalComparator())
.put(Neighbor.class, new NeighborComparator())
.build();
public static <T extends DataObject> OpenConfigComparator<T> getComparator(final Class<T> clazz) {
return (OpenConfigComparator<T>) COMPARATORS.get(clazz);
}
}
|
REmove unused dependency on jsEncode
|
/** MIT License (c) copyright 2010-2013 B Cavalier & J Hann */
/**
* curl json! cram plugin
*/
define(function () {
return {
compile: function (pluginId, resId, req, io, config) {
var absId;
absId = pluginId + '!' + resId;
io.read(
resId,
function (source) {
if (config.strictJSONParse) {
try { JSON.parse(source); } catch (ex) { io.error(ex); }
}
// write-out define(id,function(){return{/* json here */}});
source = 'define("'
+ absId
+ '", function () { return '
+ source
+ '; });';
io.write(source);
},
io.error
);
}
};
});
|
/** MIT License (c) copyright 2010-2013 B Cavalier & J Hann */
/**
* curl json! cram plugin
*/
define(['./jsEncode'], function (jsEncode) {
return {
compile: function (pluginId, resId, req, io, config) {
var absId;
absId = pluginId + '!' + resId;
io.read(
resId,
function (source) {
if (config.strictJSONParse) {
try { JSON.parse(source); } catch (ex) { io.error(ex); }
}
// write-out define(id,function(){return{/* json here */}});
source = 'define("'
+ absId
+ '", function () { return '
+ source
+ '; });';
io.write(source);
},
io.error
);
}
};
});
|
Rework HOME fixture so it doesn't leave os.environ corrupted
|
import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
old_home = os.environ['HOME']
try:
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have imported things based on this.
# Essentially we blast away the entire module and reload it from scratch.
for name in list(sys.modules.keys()):
if name.startswith('homely.'):
sys.modules.pop(name, None)
os.environ['HOME'] = home
yield home
finally:
os.environ['HOME'] = old_home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
|
import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have imported things based on this.
# Essentially we blast away the entire module and reload it from scratch.
for name in list(sys.modules.keys()):
if name.startswith('homely.'):
sys.modules.pop(name, None)
os.environ['HOME'] = home
return home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
|
Remove unused functions from the Mode base object
|
# The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
from txircd.utils import now
class Module(object):
def hook(self, base):
self.ircd = base
return self
class Mode(object):
def hook(self, base):
self.ircd = base
return self
def checkSet(self, user, target, param):
return [True, param]
def checkUnset(self, user, target, param):
return [True, param]
def showParam(self, user, target, param):
return param
def checkPermission(self, user, cmd, data):
return data
def namesListEntry(self, recipient, channel, user, representation):
return representation
class Command(object):
def hook(self, base):
self.ircd = base
return self
def onUse(self, user, data):
pass
def processParams(self, user, params):
return {
"user": user,
"params": params
}
def updateActivity(self, user):
user.lastactivity = now()
|
# The purpose of this file is to provide base classes with the needed functions
# already defined; this allows us to guarantee that any exceptions raised
# during function calls are a problem with the module and not just that the
# particular function isn't defined.
from txircd.utils import now
class Module(object):
def hook(self, base):
self.ircd = base
return self
class Mode(object):
def hook(self, base):
self.ircd = base
return self
def checkSet(self, user, target, param):
return [True, param]
def checkUnset(self, user, target, param):
return [True, param]
def showParam(self, user, target, param):
return param
def onJoin(self, channel, user, params):
return "pass"
def checkPermission(self, user, cmd, data):
return data
def onMessage(self, sender, target, message):
return ["pass"]
def onPart(self, channel, user, reason):
pass
def onTopicChange(self, channel, user, topic):
pass
def namesListEntry(self, recipient, channel, user, representation):
return representation
def commandData(self, command, *args):
pass
class Command(object):
def hook(self, base):
self.ircd = base
return self
def onUse(self, user, data):
pass
def processParams(self, user, params):
return {
"user": user,
"params": params
}
def updateActivity(self, user):
user.lastactivity = now()
|
Remove the machine id from state when the machine is deleted
|
package triton
import (
"fmt"
"time"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
)
// StepDeleteMachine deletes the machine with the ID specified in state["machine"]
type StepDeleteMachine struct{}
func (s *StepDeleteMachine) Run(state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
machineId := state.Get("machine").(string)
ui.Say("Deleting source machine...")
err := driver.DeleteMachine(machineId)
if err != nil {
state.Put("error", fmt.Errorf("Problem deleting source machine: %s", err))
return multistep.ActionHalt
}
ui.Say("Waiting for source machine to be deleted...")
err = driver.WaitForMachineDeletion(machineId, 10*time.Minute)
if err != nil {
state.Put("error", fmt.Errorf("Problem waiting for source machine to be deleted: %s", err))
return multistep.ActionHalt
}
state.Put("machine", "")
return multistep.ActionContinue
}
func (s *StepDeleteMachine) Cleanup(state multistep.StateBag) {
// No clean up to do here...
}
|
package triton
import (
"fmt"
"time"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
)
// StepDeleteMachine deletes the machine with the ID specified in state["machine"]
type StepDeleteMachine struct{}
func (s *StepDeleteMachine) Run(state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
machineId := state.Get("machine").(string)
ui.Say("Deleting source machine...")
err := driver.DeleteMachine(machineId)
if err != nil {
state.Put("error", fmt.Errorf("Problem deleting source machine: %s", err))
return multistep.ActionHalt
}
ui.Say("Waiting for source machine to be deleted...")
err = driver.WaitForMachineDeletion(machineId, 10*time.Minute)
if err != nil {
state.Put("error", fmt.Errorf("Problem waiting for source machine to be deleted: %s", err))
return multistep.ActionHalt
}
return multistep.ActionContinue
}
func (s *StepDeleteMachine) Cleanup(state multistep.StateBag) {
// No clean up to do here...
}
|
Fix multiselect user/group field when retrieving results from a report
|
from .base import MultiSelectField
from swimlane.core.resources.usergroup import UserGroup
class UserGroupField(MultiSelectField):
"""Manages getting/setting users from record User/Group fields"""
field_type = 'Core.Models.Fields.UserGroupField, Core'
supported_types = [UserGroup]
def set_swimlane(self, value):
"""Workaround for reports returning an empty usergroup field as a single element list with no id/name"""
if value == [{"$type": "Core.Models.Utilities.UserGroupSelection, Core"}]:
value = []
return super(UserGroupField, self).set_swimlane(value)
def cast_to_python(self, value):
"""Convert JSON definition to UserGroup object"""
# v2.x does not provide a distinction between users and groups at the field selection level, can only return
# UserGroup instances instead of specific User or Group instances
if value is not None:
value = UserGroup(self.record._swimlane, value)
return value
def cast_to_swimlane(self, value):
"""Dump UserGroup back to JSON representation"""
if value is not None:
value = value.get_usergroup_selection()
return value
|
from .base import MultiSelectField
from swimlane.core.resources.usergroup import UserGroup
class UserGroupField(MultiSelectField):
"""Manages getting/setting users from record User/Group fields"""
field_type = 'Core.Models.Fields.UserGroupField, Core'
supported_types = [UserGroup]
def cast_to_python(self, value):
"""Convert JSON definition to UserGroup object"""
# v2.x does not provide a distinction between users and groups at the field selection level, can only return
# UserGroup instances instead of specific User or Group instances
if value is not None:
value = UserGroup(self.record._swimlane, value)
return value
def cast_to_swimlane(self, value):
"""Dump UserGroup back to JSON representation"""
if value is not None:
value = value.get_usergroup_selection()
return value
|
Update to indicate the ARN is used
|
package main
import (
"os"
"github.com/remind101/empire/pkg/heroku"
)
var cmdCertAttach = &Command{
Run: runCertAttach,
Usage: "cert-attach <aws_cert_arn>",
NeedsApp: true,
Category: "certs",
Short: "attach a certificate to an app",
Long: `
Attaches an SSL certificate to an applications web process. When using the ECS backend, this will attach an IAM server certificate to the applications ELB.
Before running this command, you should upload your SSL certificate and key to IAM using the AWS CLI.
Examples:
$ aws iam upload-server-certificate --server-certificate-name myServerCertificate --certificate-body file://public_key_cert_file.pem --private-key file://my_private_key.pem --certificate-chain file://my_certificate_chain_file.pem
# ^^ The above command will return the ARN of the certificate, you'll need that for the command below
# Say it returns the arn arn:aws:iam::123456789012:server-certificate/myServerCertificate, you'd use that like this:
$ emp cert-attach arn:aws:iam::123456789012:server-certificate/myServerCertificate -a myapp
`,
}
func runCertAttach(cmd *Command, args []string) {
if len(args) == 0 {
cmd.PrintUsage()
os.Exit(2)
}
cert := args[0]
_, err := client.AppUpdate(mustApp(), &heroku.AppUpdateOpts{
Cert: &cert,
})
must(err)
}
|
package main
import (
"os"
"github.com/remind101/empire/pkg/heroku"
)
var cmdCertAttach = &Command{
Run: runCertAttach,
Usage: "cert-attach <aws_cert_name>",
NeedsApp: true,
Category: "certs",
Short: "attach a certificate to an app",
Long: `
Attaches an SSL certificate to an applications web process. When using the ECS backend, this will attach an IAM server certificate to the applications ELB.
Before running this command, you should upload your SSL certificate and key to IAM using the AWS CLI.
Examples:
$ aws iam upload-server-certificate --server-certificate-name myServerCertificate --certificate-body file://public_key_cert_file.pem --private-key file://my_private_key.pem --certificate-chain file://my_certificate_chain_file.pem
$ emp cert-attach myServerCertificate -a myapp
`,
}
func runCertAttach(cmd *Command, args []string) {
if len(args) == 0 {
cmd.PrintUsage()
os.Exit(2)
}
cert := args[0]
_, err := client.AppUpdate(mustApp(), &heroku.AppUpdateOpts{
Cert: &cert,
})
must(err)
}
|
Add placeholders for user notification
|
import React from 'react';
import './TicTacToe.scss';
import { connect } from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';
import GameBoard from './components/GameBoard';
const mapStateToProps = (state) => {
return {
playerTurn: state.tictactoe.playerTurn
};
};
class TicTacToe extends React.Component {
static propTypes = {
playerTurn: React.PropTypes.bool,
computer_move: React.PropTypes.func
}
componentWillReceiveProps (propObj) {
if (!propObj.playerTurn) {
this.props.computer_move();
}
if (propObj.winner && propObj.winner.result === 'draw') {
// do very cool modal fadein
} else if (propObj.winner) {
// do very cool modal fadein with computer winning
}
// nothing else, the player can't win
}
render () {
return (
<div>
<h1 className='text-center'>Tic-Tac-Toe</h1>
<GameBoard />
</div>
);
}
}
export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
|
import React from 'react';
import './TicTacToe.scss';
import { connect } from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';
import GameBoard from './components/GameBoard';
const mapStateToProps = (state) => {
return {
playerTurn: state.tictactoe.playerTurn
};
};
class TicTacToe extends React.Component {
static propTypes = {
playerTurn: React.PropTypes.bool,
computer_move: React.PropTypes.func
}
componentWillReceiveProps (propObj) {
if (!propObj.playerTurn) {
this.props.computer_move();
}
}
render () {
return (
<div>
<h1 className='text-center'>Tic-Tac-Toe</h1>
<GameBoard />
</div>
);
}
}
export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
|
Change tag name from pjax to psxhr
|
<?php
if (isset($_GET['get-date'])) {
echo uniqid();
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title></title>
</head>
<body>
<div psxhr="true" psxhr-href="<?= $_SERVER['PHP_SELF']; ?>?get-date=true" psxhr-time="1000" psxhr-response="text" psxhr-event="click">
This block must be restart
</div>
<form psxhr="true" method="GET" action="<?= $_SERVER['PHP_SELF']; ?>" psxhr-state="true" psxhr-event="submit">
<input id="" type="text" name="test" value="Hello">
<input id="" type="text" name="tes[]" value="ello">
<input id="" type="text" name="tes[]" value="Hello">
This block must be restart
<input type="submit" value="send" name="test">
</form>
</body>
<script src="pjax/src/PSXhr.js"></script>
<script>
PSXhr.init();
</script>
</html>
|
<?php
if (isset($_GET['get-date'])) {
echo uniqid();
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title></title>
</head>
<body>
<div pjax="true" pjax-href="<?= $_SERVER['PHP_SELF']; ?>?get-date=true" pjax-time="1000" pjax-response="text" pjax-event="click">
This block must be restart
</div>
<form pjax="true" method="POST" pjax-method="POST" pjax-href="<?= $_server['php_self']; ?>" action="<?= $_server['php_self']; ?>" pjax-event="submit">
<input id="" type="text" name="test" value="Hello">
This block must be restart
<input type="submit" value="send">
</form>
</body>
<script src="src/pjax.js"></script>
<script>
PjaxElement.setPjax();
</script>
</html>
|
Fix url attribute on share serializer :)
|
from bioshareX.models import ShareLog, Share, Tag, ShareStats
from rest_framework import serializers
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class UserSerializer(serializers.ModelSerializer):
class Meta:
fields=('first_name','last_name','email','username','id')
model = User
class ShareLogSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
paths = serializers.JSONField()
class Meta:
model = ShareLog
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
class ShareStatsSerializer(serializers.ModelSerializer):
class Meta:
model = ShareStats
fields = ('num_files','bytes','updated')
class ShareSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField()
stats = ShareStatsSerializer(many=False,read_only=True)
tags = TagSerializer(many=True,read_only=True)
owner = UserSerializer(read_only=True)
def get_url(self,obj):
return reverse('list_directory',kwargs={'share':obj.id})
class Meta:
model = Share
|
from bioshareX.models import ShareLog, Share, Tag, ShareStats
from rest_framework import serializers
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class UserSerializer(serializers.ModelSerializer):
class Meta:
fields=('first_name','last_name','email','username','id')
model = User
class ShareLogSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
paths = serializers.JSONField()
class Meta:
model = ShareLog
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
class ShareStatsSerializer(serializers.ModelSerializer):
class Meta:
model = ShareStats
fields = ('num_files','bytes','updated')
class ShareSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField()
stats = ShareStatsSerializer(many=False,read_only=True)
tags = TagSerializer(many=True,read_only=True)
owner = UserSerializer(read_only=True)
def get_url(self,obj):
reverse('list_directory',kwargs={'share':obj.id})
class Meta:
model = Share
|
Fix duplicate `graphql` package bug by checking for local installation
See https://github.com/graphql/graphiql/issues/58 for more info
|
const axios = require('axios')
const path = require('path')
let GraphQL
try {
// do to GraphQL schema issue [see](https://github.com/graphql/graphiql/issues/58)
GraphQL = require(path.join(process.cwd(), './node_modules/graphql'))
} catch (e) {
// fallback if graphql is not installed locally
GraphQL = require('graphql')
}
const { graphql } = GraphQL
const { correctURL, encode, DEFAULT_CONFIG } = require('./util')
function Gest (schema, config = {}) {
const { baseURL, headers, timeout } = Object.assign(DEFAULT_CONFIG, config)
return function (query) {
if (baseURL) {
const instance = axios.create({
timeout,
headers
})
const corrected = correctURL(baseURL)
if (config.verbose) console.log(`${query} -> ${corrected}`)
return instance.post(corrected, encode(query))
.then(res => res.data)
}
if (config.verbose) console.log(query)
return graphql(schema, query)
}
}
module.exports = exports.default = Gest
|
const axios = require('axios')
const { graphql } = require('graphql')
const { correctURL, encode, DEFAULT_CONFIG } = require('./util')
function Gest (schema, config = {}) {
const { baseURL, headers, timeout } = Object.assign(DEFAULT_CONFIG, config)
return function (query) {
if (baseURL) {
const instance = axios.create({
timeout,
headers
})
const corrected = correctURL(baseURL)
if (config.verbose) console.log(`${query} -> ${corrected}`)
return instance.post(corrected, encode(query))
.then(res => res.data)
}
if (config.verbose) console.log(query)
return graphql(schema, query)
}
}
module.exports = exports.default = Gest
|
Modify the picture plugin slightly
|
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
plugin_pool.register_plugin(PicturePlugin)
|
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
def icon_src(self, instance):
# TODO - possibly use 'instance' and provide a thumbnail image
return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin)
|
Change font-awesome css file to compile
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
gulp.task('default',['sass'], function() {
});
gulp.task("sass", function () {
gulp.src("./sass/*.scss")
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
.pipe(sourcemaps.write("./css"))
.pipe(gulp.dest("./css"));
});
gulp.task('concat', function() {
return gulp.src(['./sass/*.scss', './bower_components/bootswatch/bootstrap.css','./bower_components/font-awesome/css/font-awesome.css'])
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
.pipe(concat('style.css'))
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function(){
gulp.watch('./sass/*.scss', ['concat']);
// Other watchers
});
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
gulp.task('default',['sass'], function() {
});
gulp.task("sass", function () {
gulp.src("./sass/*.scss")
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
.pipe(sourcemaps.write("./css"))
.pipe(gulp.dest("./css"));
});
gulp.task('concat', function() {
return gulp.src(['./sass/*.scss', './bower_components/bootswatch/bootstrap.min.css','./bower_components/font-awesome/css/font-awesome.min.css'])
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
.pipe(concat('style.css'))
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function(){
gulp.watch('./sass/*.scss', ['concat']);
// Other watchers
});
|
Fix unhandled promise rejection error reporting to Sentry
|
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import './static/bootstrap/css/bootstrap.css';
import App from './Main/App';
import ErrorBoundary from './Main/ErrorBoundary';
import { unregister } from './registerServiceWorker';
function isError(x) {
return x instanceof Error;
}
function toMessage(x) {
return isError(x) ? x.message : x;
}
function toStack(x) {
return isError(x) ? x.stack : undefined;
}
window.addEventListener('unhandledrejection', event => {
const message = toMessage(event);
console.error(`Unhandled rejection: ${message}`);
Raven && Raven.captureException(new Error('Unhandled promise rejection'), { // eslint-disable-line no-undef
extra: {
reason: message,
stack: toStack(event),
},
});
});
render(
<ErrorBoundary>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="report/:reportCode" />
<Route path="report/:reportCode/:fightId" />
<Route path="report/:reportCode/:fightId/:playerName" />
<Route path="report/:reportCode/:fightId/:playerName/:resultTab" />
</Route>
</Router>
</ErrorBoundary>,
document.getElementById('app-mount')
);
unregister();
|
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import './static/bootstrap/css/bootstrap.css';
import App from './Main/App';
import ErrorBoundary from './Main/ErrorBoundary';
import { unregister } from './registerServiceWorker';
function isError(x) {
return x instanceof Error;
}
function toMessage(x) {
return isError(x) ? x.message : x;
}
function toStack(x) {
return isError(x) ? x.stack : undefined;
}
window.addEventListener('unhandledRejection', event => {
const message = toMessage(event);
console.error(`Unhandled rejection: ${message}`);
Raven && Raven.captureException(new Error('Unhandled promise rejection'), { // eslint-disable-line no-undef
extra: {
reason: message,
stack: toStack(event),
},
});
});
render(
<ErrorBoundary>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="report/:reportCode" />
<Route path="report/:reportCode/:fightId" />
<Route path="report/:reportCode/:fightId/:playerName" />
<Route path="report/:reportCode/:fightId/:playerName/:resultTab" />
</Route>
</Router>
</ErrorBoundary>,
document.getElementById('app-mount')
);
unregister();
|
Add method to create a normal user
|
from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, password):
""" Create an admin user
"""
domain = models.Domain.query.get(domain_name)
if not domain:
domain = models.Domain(name=domain_name)
db.session.add(domain)
user = models.User(
localpart=localpart,
domain=domain,
global_admin=True,
password=hash.sha512_crypt.encrypt(password)
)
db.session.add(user)
db.session.commit()
@manager.command
def user(localpart, domain_name, password):
""" Create an user
"""
domain = models.Domain.query.get(domain_name)
if not domain:
domain = models.Domain(name=domain_name)
db.session.add(domain)
user = models.User(
localpart=localpart,
domain=domain,
global_admin=False,
password=hash.sha512_crypt.encrypt(password)
)
db.session.add(user)
db.session.commit()
if __name__ == "__main__":
manager.run()
|
from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, password):
""" Create an admin user
"""
domain = models.Domain.query.get(domain_name)
if not domain:
domain = models.Domain(name=domain_name)
db.session.add(domain)
user = models.User(
localpart=localpart,
domain=domain,
global_admin=True,
password=hash.sha512_crypt.encrypt(password)
)
db.session.add(user)
db.session.commit()
if __name__ == "__main__":
manager.run()
|
Fix missing name on password field
|
<div class="app-user app-user-login">
<h2>Connexion</h2>
<div class="login-form">
<form id="Connexion" method="post" action="<?php echo Config::get('config.base'); ?>/user/login">
<div>
<label for="email">Email</label><input name="email" id="email" type="text" required /><br/>
<label for="password">Mot de Passe</label><input name="password" id="password" type="password" required /><br/>
<input type="submit" value="Se Connecter" class="submit" />
</div>
</form>
<div class="links">
<a href="<?php echo Config::get('config.base'); ?>/user/register" class="password-lost">Mot de passe oublié</a>
<a href="<?php echo Config::get('config.base'); ?>/user/lostpassword" class="register">Pas encore inscrit ?</a>
</div>
</div>
</div>
|
<div class="app-user app-user-login">
<h2>Connexion</h2>
<div class="login-form">
<form id="Connexion" method="post" action="<?php echo Config::get('config.base'); ?>/user/login">
<div>
<label for="email">Email</label><input name="email" id="email" type="text" required /><br/>
<label for="password">Mot de Passe</label><input id="password" type="password" required /><br/>
<input type="submit" value="Se Connecter" class="submit" />
</div>
</form>
<div class="links">
<a href="<?php echo Config::get('config.base'); ?>/user/register" class="password-lost">Mot de passe oublié</a>
<a href="<?php echo Config::get('config.base'); ?>/user/lostpassword" class="register">Pas encore inscrit ?</a>
</div>
</div>
</div>
|
Allow saving to a file that does not already exist again.
|
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename = tkFileDialog.askopenfilename(filetypes=filetypes)
if not os.path.isfile(input_filename):
exit(0)
output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv")
if output_filename:
joiner = joincsv.RecordJoiner(input_filename)
joiner.save(output_filename)
|
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename = tkFileDialog.askopenfilename(filetypes=filetypes)
if not os.path.isfile(input_filename):
exit(0)
output_filename = tkFileDialog.asksaveasfilename(filetypes=filetypes, defaultextension=".csv")
if not os.path.isfile(output_filename):
exit(0)
joiner = joincsv.RecordJoiner(input_filename)
joiner.save(output_filename)
|
Add the ability to specify snippets on a per-invocation basis.
|
'use strict';
/*****
* Vain
*
* A view-first templating engine for Node.js.
*****/
var jsdom = require('jsdom'),
$ = require('jquery')(jsdom.jsdom().createWindow()),
snippetRegistry = {};
/**
* Register a snippet in the snippet registry.
**/
exports.registerSnippet = function(snippetName, snippetFn) {
snippetRegistry[snippetName] = snippetFn;
};
/**
* Process the given markup.
**/
exports.render = function(input, options, fn) {
if ('function' === typeof options) {
fn = options;
options = undefined;
}
options = options || {};
var $template = $(input),
snippetHandlers = $.merge(snippetRegistry, options.snippets || {});
$template.find("data-vain").each(function() {
var snippetName = $(this).data('vain');
if ('function' === typeof snippetRegistry[snippetName]) {
$(this).replaceWith(snippetRegistry[snippetName](this));
}
});
return $("<div />").append($template).html();
};
/**
* Process a given file.
**/
exports.renderFile = function(path, options, fn) {
//
};
// Express support.
exports.__express = exports.renderFile;
|
'use strict';
/*****
* Vain
*
* A view-first templating engine for Node.js.
*****/
var jsdom = require('jsdom'),
$ = require('jquery')(jsdom.jsdom().createWindow()),
snippetRegistry = {};
/**
* Register a snippet in the snippet registry.
**/
exports.registerSnippet = function(snippetName, snippetFn) {
snippetRegistry[snippetName] = snippetFn;
};
/**
* Process the given markup.
**/
exports.render = function(input, options, fn) {
if ('function' === typeof options) {
fn = options;
options = undefined;
}
options = options || {};
var $template = $(input);
$template.find("data-vain").each(function() {
var snippetName = $(this).data('vain');
if ('function' === typeof snippetRegistry[snippetName]) {
$(this).replaceWith(snippetRegistry[snippetName](this));
}
});
return $("<div />").append($template).html();
};
/**
* Process a given file.
**/
exports.renderFile = function(path, options, fn) {
//
};
// Express support.
exports.__express = exports.renderFile;
|
Remove @NotNull annotation to name field.
|
package com.zyeeda.framework.entities.base;
import javax.validation.constraints.NotNull;
@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {
private static final long serialVersionUID = -2200108673372668900L;
private String name;
private String description;
@javax.persistence.Basic
@javax.persistence.Column(name = "F_NAME")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@javax.persistence.Basic
@javax.persistence.Column(name = "F_DESC", length = 2000)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
package com.zyeeda.framework.entities.base;
import javax.validation.constraints.NotNull;
@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {
private static final long serialVersionUID = -2200108673372668900L;
private String name;
private String description;
@javax.persistence.Basic
@javax.persistence.Column(name = "F_NAME")
@NotNull
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@javax.persistence.Basic
@javax.persistence.Column(name = "F_DESC", length = 2000)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
Add results to LoadSessionServlet model.
Each reservation may contain many results. Since clients may
be depending on these results we will want to keep them
constant when loading sessions from the CMS. This means that
results must be included in the model that is used to update
the reservation.
Change-Id: I8318b3866573b71a4e02dbd43541021f78a57f34
|
/*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.server.schedule.reservations.model;
import java.util.Map;
/**
* Representation of a Reservation object in RTDB.
*/
public class Reservation implements Comparable<Reservation> {
public long last_status_changed;
public String status;
public Map<String, String> results;
@Override
public int compareTo(Reservation reservation) {
if (last_status_changed < reservation.last_status_changed) {
return -1;
} else if (last_status_changed > reservation.last_status_changed) {
return 1;
}
return 0;
}
}
|
/*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.server.schedule.reservations.model;
/**
* Representation of a Reservation object in RTDB.
*/
public class Reservation implements Comparable<Reservation> {
public long last_status_changed;
public String status;
@Override
public int compareTo(Reservation reservation) {
if (last_status_changed < reservation.last_status_changed) {
return -1;
} else if (last_status_changed > reservation.last_status_changed) {
return 1;
}
return 0;
}
}
|
Switch to using block chainer
|
""" Test a pipeline with repeated FFTs and inverse FFTs """
from timeit import default_timer as timer
import numpy as np
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class GPUFFTBenchmarker(PipelineBenchmarker):
""" Test the sigproc read function """
def run_benchmark(self):
with bf.Pipeline() as pipeline:
datafile = "numpy_data0.bin"
bc = bf.BlockChainer()
bc.blocks.binary_io.BinaryFileReadBlock(
[datafile], gulp_size=32768, gulp_nframe=4, dtype='f32')
bc.blocks.copy('cuda')
bc.blocks.print_header()
start = timer()
pipeline.run()
end = timer()
self.total_clock_time = end-start
#sigproc_benchmarker = SigprocBenchmarker()
#print sigproc_benchmarker.average_benchmark(10)
t = np.arange(32768*1024)
w = 0.01
s = np.sin(w * 4 * t, dtype='float32')
with open('numpy_data0.bin', 'wb') as myfile: pass
s.tofile('numpy_data0.bin')
gpufftbenchmarker = GPUFFTBenchmarker()
print gpufftbenchmarker.average_benchmark(4)
|
""" Test a pipeline with repeated FFTs and inverse FFTs """
from timeit import default_timer as timer
import numpy as np
import bifrost as bf
from bifrost import pipeline as bfp
from bifrost import blocks as blocks
from bifrost_benchmarks import PipelineBenchmarker
class GPUFFTBenchmarker(PipelineBenchmarker):
""" Test the sigproc read function """
def run_benchmark(self):
with bf.Pipeline() as pipeline:
datafile = "numpy_data0.bin"
data = blocks.binary_io.BinaryFileReadBlock(
[datafile], gulp_size=32768, gulp_nframe=4, dtype='f32')
#data.on_data = self.timeit(data.on_data)
start = timer()
pipeline.run()
end = timer()
self.total_clock_time = end-start
#sigproc_benchmarker = SigprocBenchmarker()
#print sigproc_benchmarker.average_benchmark(10)
t = np.arange(32768*1024)
w = 0.01
s = np.sin(w * 4 * t, dtype='float32')
with open('numpy_data0.bin', 'wb') as myfile: pass
s.tofile('numpy_data0.bin')
gpufftbenchmarker = GPUFFTBenchmarker()
print gpufftbenchmarker.average_benchmark(10)
|
Add pubish action helper for influxdb
|
#-*- coding:utf-8 -*-
import sys
import logging
from influxdb import InfluxDBClient as OriginalInfluxDBClient
class InfluxDBClient(OriginalInfluxDBClient):
def Publish(self, measurement, tags):
return InfluxDBPublish(self, measurement, tags)
class InfluxDBPublish(object):
def __init__(self, influxdb, measurement, tags):
assert(isinstance(influxdb, InfluxDBClient))
self.influxdb = influxdb
self.tags = tags
self.measurement = measurement
self._logger = logging.getLogger("gsensors.InfluxDBPublish")
def __call__(self, source, value):
#TODO what when error ?
json_body = [
{
"measurement": self.measurement,
"tags": self.tags,
"fields": {
"value": value
}
}
]
self.influxdb.write_points(json_body)
self._logger.debug("Write for measurement '%s'" % self.measurement)
|
#-*- coding:utf-8 -*-
import sys
import logging
from influxdb import InfluxDBClient
class InfluxDBPublish(object):
def __init__(self, influxdb, measurement, tags):
assert(isinstance(influxdb, InfluxDBClient))
self.influxdb = influxdb
self.tags = tags
self.measurement = measurement
self._logger = logging.getLogger("gsensors.InfluxDBPublish")
def __call__(self, source, value):
#TODO what when error ?
json_body = [
{
"measurement": self.measurement,
"tags": self.tags,
"fields": {
"value": value
}
}
]
self.influxdb.write_points(json_body)
self._logger.debug("Write for measurement '%s'" % self.measurement)
|
Add confirmation to user password validation.
|
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;
class User extends Authenticatable
{
static $rules = [
'name' => 'required|max:255',
'email' => 'required|email',
'password' => 'required|confirmed|min:8|max:255'
];
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public $timestamps = true;
public $relationships = ['devices', 'templates', 'tokens'];
public $guardCreate = false;
static function findByToken ($token)
{
$userToken = UserToken::where('token', $token)->first();
if ( ! $userToken) return;
return static::findOrFail($userToken->user_id);
}
function getDates ()
{
return ['last_login', 'created_at', 'updated_at'];
}
function devices ()
{
return $this->belongsToMany(Device::class, 'user_devices');
}
function templates ()
{
return $this->hasMany(Template::class);
}
function tokens ()
{
return $this->hasMany(UserToken::class);
}
function setPasswordAttribute ($val)
{
$this->attributes['password'] = Hash::make($val);
}
function getUserIdsAttribute ()
{
return [(int) $this->id];
}
}
|
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hash;
class User extends Authenticatable
{
static $rules = [
'name' => 'required|max:255',
'email' => 'required|email',
'password' => 'required|min:8|max:255'
];
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public $timestamps = true;
public $relationships = ['devices', 'templates', 'tokens'];
public $guardCreate = false;
static function findByToken ($token)
{
$userToken = UserToken::where('token', $token)->first();
if ( ! $userToken) return;
return static::findOrFail($userToken->user_id);
}
function getDates ()
{
return ['last_login', 'created_at', 'updated_at'];
}
function devices ()
{
return $this->belongsToMany(Device::class, 'user_devices');
}
function templates ()
{
return $this->hasMany(Template::class);
}
function tokens ()
{
return $this->hasMany(UserToken::class);
}
function setPasswordAttribute ($val)
{
$this->attributes['password'] = Hash::make($val);
}
function getUserIdsAttribute ()
{
return [(int) $this->id];
}
}
|
Support HTML5's input type 'tel'
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonenumber import to_python
class PhoneNumberField(CharField):
default_error_messages = {
'invalid': _('Enter a valid phone number.'),
}
default_validators = [validate_international_phonenumber]
def __init__(self, *args, **kwargs):
super(PhoneNumberField, self).__init__(*args, **kwargs)
self.widget.input_type = 'tel'
def to_python(self, value):
phone_number = to_python(value)
if phone_number and not phone_number.is_valid():
raise ValidationError(self.error_messages['invalid'])
return phone_number
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonenumber import to_python
class PhoneNumberField(CharField):
default_error_messages = {
'invalid': _('Enter a valid phone number.'),
}
default_validators = [validate_international_phonenumber]
def to_python(self, value):
phone_number = to_python(value)
if phone_number and not phone_number.is_valid():
raise ValidationError(self.error_messages['invalid'])
return phone_number
|
Install now drops and recreates the database
|
process.env.NODE_CONFIG_DIR="../config/";
var mysql = require("promise-mysql");
var config = require("config");
var fs = require("fs");
var connection;
mysql.createConnection({
host: config.get("database.host"),
user: config.get("database.username"),
password: config.get("database.password"),
multipleStatements: true
}).then((conn) => {
connection = conn;
return connection.query("DROP DATABASE " + config.get("database.name"));
}).then(function() {
return connection.query("CREATE DATABASE IF NOT EXISTS " + config.get("database.name"));
}).then(() => {
return connection.query("USE " + config.get("database.name"));
}).then(() => {
var exampleDB = fs.readFileSync("exampleDatabase.sql", "utf8");
return connection.query(exampleDB);
}).then((res) => {
console.log("Finished importing sql. Your install is now ready.");
process.exit(0);
}).catch((err) => {
console.log("ERROR", err);
process.exit(1);
});
|
process.env.NODE_CONFIG_DIR="../config/";
var mysql = require("promise-mysql");
var config = require("config");
var fs = require("fs");
var connection;
mysql.createConnection({
host: config.get("database.host"),
user: config.get("database.username"),
password: config.get("database.password"),
multipleStatements: true
}).then(function(conn) {
connection = conn;
return connection.query("CREATE DATABASE IF NOT EXISTS " + config.get("database.name"));
}).then(() => {
return connection.query("USE " + config.get("database.name"));
}).then(() => {
var exampleDB = fs.readFileSync("exampleDatabase.sql", "utf8");
return connection.query(exampleDB);
}).then((res) => {
console.log("Finished importing sql. Your install is now ready.");
process.exit(0);
}).catch((err) => {
console.log("ERROR", err);
process.exit(1);
});
|
Remove unnecessary call to loadTasks.
|
/*
* grunt-check-pages
* https://github.com/DavidAnson/grunt-check-pages
*
* Copyright (c) 2014 David Anson
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
// Linting
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
// Unit tests
nodeunit: {
tests: ['test/*_test.js']
}
});
// Load required plugins
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Default: Test and lint
grunt.registerTask('default', ['nodeunit', 'jshint']);
};
|
/*
* grunt-check-pages
* https://github.com/DavidAnson/grunt-check-pages
*
* Copyright (c) 2014 David Anson
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration
grunt.initConfig({
// Linting
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'test/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
// Unit tests
nodeunit: {
tests: ['test/*_test.js']
}
});
// Load this plugin's task
grunt.loadTasks('tasks');
// Load required plugins
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Default: Test and lint
grunt.registerTask('default', ['nodeunit', 'jshint']);
};
|
Fix typo causing strangeness in transition to photo-card schema mode
|
import { task } from 'ember-concurrency';
import { tracked } from '@glimmer/tracking';
import BaseIsolatedLayoutComponent from '../base-isolated-layout';
export default class PhotoCardIsolatedComponent extends BaseIsolatedLayoutComponent {
@tracked bylineName;
@tracked bylineImageURL;
constructor(...args) {
super(...args);
this.loadBylineCard.perform();
}
@task(function*() {
let byline = yield this.args.card.value('photo-byline');
if (!byline) {
return;
}
this.bylineName = yield byline.value('name');
this.bylineImageURL = yield byline.value('image');
})
loadBylineCard;
notByline(fieldCard) {
return fieldCard.name !== 'photo-byline';
}
get bylineIsEditable() {
return this.args.mode === 'edit' || this.args.mode === 'schema';
}
}
|
import { task } from 'ember-concurrency';
import { tracked } from '@glimmer/tracking';
import BaseIsolatedLayoutComponent from '../base-isolated-layout';
export default class PhotoCardIsolatedComponent extends BaseIsolatedLayoutComponent {
@tracked bylineName;
@tracked bylineImageURL;
constructor(...args) {
super(...args);
this.loadBylineCard.perform();
}
@task(function*() {
let byline = yield this.args.card.value('photo-byline');
if (!byline) {
return;
}
this.bylineName = yield byline.value('name');
this.bylineImageURL = yield byline.value('image');
})
loadBylineCard;
notByline(fieldCard) {
return fieldCard.name !== 'photo-byline';
}
get bylineIsEditable() {
return this.args.mode === 'edit' || this.args.model === 'schema';
}
}
|
Add debug logging to elm-format
|
from __future__ import print_function
import subprocess
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "elm-format {} --yes".format(self.view.file_name())
p = subprocess.Popen(command, stdout=subprocess.PIPE, sterr=subprocess.PIPE, shell=True)
output, errors = p.communicate()
settings = sublime.load_settings('Elm Language Support.sublime-settings')
if settings.get('debug', False):
string_settings = sublime.load_settings('Elm User Strings.sublime-settings')
print(string_settings.get('logging.prefix', '') + '(elm-format) ' + output.strip(), 'errors: ' + errors.strip())
class ElmFormatOnSave(sublime_plugin.EventListener):
def on_pre_save(self, view):
sel = view.sel()[0]
region = view.word(sel)
scope = view.scope_name(region.b)
if scope.find('source.elm') != -1:
settings = sublime.load_settings('Elm Language Support.sublime-settings')
if settings.get('elm_format_on_save', False):
regex = settings.get('elm_format_filename_filter', '')
if not (len(regex) > 0 and re.search(regex, view.file_name()) is not None):
view.run_command('elm_format')
|
import subprocess
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
command = "elm-format {} --yes".format(self.view.file_name())
p = subprocess.Popen(command, shell=True)
class ElmFormatOnSave(sublime_plugin.EventListener):
def on_pre_save(self, view):
sel = view.sel()[0]
region = view.word(sel)
scope = view.scope_name(region.b)
if scope.find('source.elm') != -1:
settings = sublime.load_settings('Elm Language Support.sublime-settings')
if settings.get('elm_format_on_save', False):
regex = settings.get('elm_format_filename_filter', '')
if not (len(regex) > 0 and re.search(regex, view.file_name()) is not None):
view.run_command('elm_format')
|
[Biography] Fix case where artist blurb was null and RN couldn't render
|
/* @flow */
'use strict';
import Relay from 'react-relay';
import React from 'react-native';
const { View, Text, Dimensions } = React;
import removeMarkdown from 'remove-markdown';
import Headline from '../text/headline';
import SerifText from '../text/serif';
const sideMargin = Dimensions.get('window').width > 700 ? 50 : 0;
class Biography extends React.Component {
static propTypes = {
artist: React.PropTypes.shape({
bio: React.PropTypes.string,
}),
};
render() {
const artist = this.props.artist;
if (!artist.blurb && !artist.bio) { return null; }
return (
<View style={{marginLeft: sideMargin, marginRight: sideMargin}}>
<Headline style={{ marginBottom: 20 }}>Biography</Headline>
{ this.blurb(artist) }
<SerifText style={{ marginBottom: 40 }}>{artist.bio}</SerifText>
</View>
);
}
blurb(artist) {
return artist.blurb ? <SerifText style={{ marginBottom: 20, lineHeight: 25 }} numberOfLines={0}>{removeMarkdown(artist.blurb)}</SerifText> : null;
}
}
export default Relay.createContainer(Biography, {
fragments: {
artist: () => Relay.QL`
fragment on Artist {
bio
blurb
}
`,
}
});
|
/* @flow */
'use strict';
import Relay from 'react-relay';
import React from 'react-native';
const { View, Text, Dimensions } = React;
import removeMarkdown from 'remove-markdown';
import Headline from '../text/headline';
import SerifText from '../text/serif';
const sideMargin = Dimensions.get('window').width > 700 ? 50 : 0;
class Biography extends React.Component {
static propTypes = {
artist: React.PropTypes.shape({
bio: React.PropTypes.string,
}),
};
render() {
const artist = this.props.artist;
if (artist.blurb.length === 0 && artist.bio.length === 0) { return null; }
return (
<View style={{marginLeft: sideMargin, marginRight: sideMargin}}>
<Headline style={{ marginBottom: 20 }}>Biography</Headline>
{ this.blurb(artist) }
<SerifText style={{ marginBottom: 40 }}>{artist.bio}</SerifText>
</View>
);
}
blurb(artist) {
return artist.blurb ? <SerifText style={{ marginBottom: 20, lineHeight: 25 }} numberOfLines={0}>{removeMarkdown(artist.blurb)}</SerifText> : null;
}
}
export default Relay.createContainer(Biography, {
fragments: {
artist: () => Relay.QL`
fragment on Artist {
bio
blurb
}
`,
}
});
|
Check that ImagePaths aren't empty in testing
|
package talks
import (
"fmt"
"testing"
assert "github.com/stretchr/testify/require"
)
func TestCompile(t *testing.T) {
talk, err := Compile("../content", "../content/talks-drafts", "paradise-lost.yaml", true)
assert.NoError(t, err)
assert.Equal(t, true, talk.Draft)
assert.NotEmpty(t, talk.Intro)
assert.NotEmpty(t, talk.IntroRaw)
assert.NotEmpty(t, talk.Title)
publishingInfo := talk.PublishingInfo()
assert.Contains(t, publishingInfo, talk.Event)
assert.Contains(t, publishingInfo, talk.Location)
assert.Contains(t, publishingInfo, talk.Title)
for i, slide := range talk.Slides {
if slide.CaptionRaw != "" {
assert.NotEmpty(t, slide.Caption)
}
assert.Equal(t, fmt.Sprintf("%03d", i+1), slide.Number)
assert.NotEmpty(t, slide.ImagePath)
}
}
|
package talks
import (
"fmt"
"testing"
assert "github.com/stretchr/testify/require"
)
func TestCompile(t *testing.T) {
talk, err := Compile("../content", "../content/talks-drafts", "paradise-lost.yaml", true)
assert.NoError(t, err)
assert.Equal(t, true, talk.Draft)
assert.NotEmpty(t, talk.Intro)
assert.NotEmpty(t, talk.IntroRaw)
assert.NotEmpty(t, talk.Title)
publishingInfo := talk.PublishingInfo()
assert.Contains(t, publishingInfo, talk.Event)
assert.Contains(t, publishingInfo, talk.Location)
assert.Contains(t, publishingInfo, talk.Title)
for i, slide := range talk.Slides {
if slide.CaptionRaw != "" {
assert.NotEmpty(t, slide.Caption)
}
assert.Equal(t, fmt.Sprintf("%03d", i+1), slide.Number)
}
}
|
Change the comment of InterleavingMethod.evaluate
|
class InterleavingMethod(object):
'''
Interleaving
'''
def interleave(self, k, a, b):
'''
k: the maximum length of resultant interleaving
a: a list of document IDs
b: a list of document IDs
Return an instance of Ranking
'''
raise NotImplementedError()
def multileave(self, k, *lists):
'''
k: the maximum length of resultant multileaving
*lists: lists of document IDs
Return an instance of Ranking
'''
raise NotImplementedError()
def evaluate(self, ranking, clicks):
'''
ranking: an instance of Ranking generated by Balanced.interleave
clicks: a list of indices clicked by a user
Return a list of pairs of ranker indices
in which element (i, j) indicates i won j.
e.g. a result [(1, 0), (2, 1), (2, 0)] indicates
ranker 1 won ranker 0, and ranker 2 won ranker 0 as well as ranker 1.
'''
raise NotImplementedError()
|
class InterleavingMethod(object):
'''
Interleaving
'''
def interleave(self, k, a, b):
'''
k: the maximum length of resultant interleaving
a: a list of document IDs
b: a list of document IDs
Return an instance of Ranking
'''
raise NotImplementedError()
def multileave(self, k, *lists):
'''
k: the maximum length of resultant multileaving
*lists: lists of document IDs
Return an instance of Ranking
'''
raise NotImplementedError()
def evaluate(self, ranking, clicks):
'''
ranking: an instance of Ranking generated by Balanced.interleave
clicks: a list of indices clicked by a user
Return one of the following tuples:
- (1, 0): Ranking 'a' won
- (0, 1): Ranking 'b' won
- (0, 0): Tie
'''
raise NotImplementedError()
|
Change package name in tests
|
import pytest
from curryer import curry
class TestCurry:
def test_curry_as_decorator(self):
"""Ensure that currypy.curry can be used as a decorator"""
@curry
def func():
pass
assert func.curried is False
def test_curry_refuses_None(self):
"""Ensure that currypy.curry refuses None"""
with pytest.raises(TypeError):
curry(None)
def test_curries_when_given_parameters(self):
@curry
def add(a, b):
return a + b
assert add(1).curried is True
def test_evaluates_when_given_enough_parameters(self):
@curry
def add(a, b):
return a + b
assert add(1)(2) == 3
assert add(1, 2) == 3
|
import pytest
from currypy import curry
class TestCurry:
def test_curry_as_decorator(self):
"""Ensure that currypy.curry can be used as a decorator"""
@curry
def func():
pass
assert func.curried is False
def test_curry_refuses_None(self):
"""Ensure that currypy.curry refuses None"""
with pytest.raises(TypeError):
curry(None)
def test_curries_when_given_parameters(self):
@curry
def add(a, b):
return a + b
assert add(1).curried is True
def test_evaluates_when_given_enough_parameters(self):
@curry
def add(a, b):
return a + b
assert add(1)(2) == 3
assert add(1, 2) == 3
|
Move variable declaration up a level to ensure it exists later
|
import React from 'react'
import { prefixLink } from './gatsby-helpers'
let stylesStr
if (process.env.NODE_ENV === `production`) {
try {
stylesStr = require(`!raw!public/styles.css`)
} catch (e) {
// ignore
}
}
const htmlStyles = (args = {}) => {
if (process.env.NODE_ENV === `production`) {
if (args.link) {
// If the user wants to reference the external stylesheet return a link.
return <link rel="stylesheet" type="text/css" href={prefixLink(`/styles.css`)} media="screen" />
} else {
// Default to returning the styles inlined.
return <style id="gatsby-inlined-css" dangerouslySetInnerHTML={{ __html: stylesStr }} />
}
}
// In dev just return an empty style element.
return <style />
}
module.exports = htmlStyles
|
import React from 'react'
import { prefixLink } from './gatsby-helpers'
if (process.env.NODE_ENV === `production`) {
let stylesStr
try {
stylesStr = require(`!raw!public/styles.css`)
} catch (e) {
// ignore
}
}
const htmlStyles = (args = {}) => {
if (process.env.NODE_ENV === `production`) {
if (args.link) {
// If the user wants to reference the external stylesheet return a link.
return <link rel="stylesheet" type="text/css" href={prefixLink(`/styles.css`)} media="screen" />
} else {
// Default to returning the styles inlined.
return <style id="gatsby-inlined-css" dangerouslySetInnerHTML={{ __html: stylesStr }} />
}
}
// In dev just return an empty style element.
return <style />
}
module.exports = htmlStyles
|
Update UserRegistrationForm to be connected to an existing OSF user.
|
from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(forms.Form):
""" A form that finds an existing OSF User, and grants permissions to that
user so that they can use the admin app"""
osf_id = forms.CharField(required=True, max_length=5, min_length=5)
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(Q(name='prereg_group') | Q(name='osf_admin')),
required=True
)
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
|
from __future__ import absolute_import
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group
from osf.models.user import OSFUser
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(UserCreationForm):
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(name='prereg_group'),
widget=FilteredSelectMultiple('verbose name', is_stacked=False),
required=False
)
class Meta:
model = OSFUser
fields = ['given_name', 'username']
def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['osf_id'].required = True
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
|
Add GET location by ID route.
|
const express = require('express');
const router = express.Router();
const authController = require('./authController');
const locationsController = require('./locationsController');
const locationTypeController = require('./locationTypeController');
const happyHoursController = require('./happyHoursController');
router.post('/v1/auth', authController.getAuth);
router.post(
'/v1/auth/test',
authController.checkAuth,
authController.testCheckAuth
);
router.post(
'/v1/locations',
authController.checkAuth,
locationsController.addLocation
);
router.get('/v1/locations', locationsController.getLocations);
router.get('/v1/locations/:id', locationsController.getLocationById);
router.delete(
'/v1/locations/:id',
authController.checkAuth,
locationsController.deleteLocation
);
router.get(
'/v1/locations/:id/happyhours',
happyHoursController.getHappyHoursByLocation
);
router.post(
'/v1/happyhours',
authController.checkAuth,
happyHoursController.addHappyHours
);
router.put(
'/v1/happyhours/:id',
authController.checkAuth,
happyHoursController.updateHappyHours
);
router.delete(
'/v1/happyhours/:id',
authController.checkAuth,
happyHoursController.deleteHappyHours
);
router.get('/v1/locationtypes', locationTypeController.getLocationTypes);
module.exports = router;
|
const express = require('express');
const router = express.Router();
const authController = require('./authController');
const locationsController = require('./locationsController');
const locationTypeController = require('./locationTypeController');
const happyHoursController = require('./happyHoursController');
router.post('/v1/auth', authController.getAuth);
router.post(
'/v1/auth/test',
authController.checkAuth,
authController.testCheckAuth
);
router.post(
'/v1/locations',
authController.checkAuth,
locationsController.addLocation
);
router.get('/v1/locations', locationsController.getLocations);
router.delete(
'/v1/locations/:id',
authController.checkAuth,
locationsController.deleteLocation
);
router.get(
'/v1/locations/:id/happyhours',
happyHoursController.getHappyHoursByLocation
);
router.post(
'/v1/happyhours',
authController.checkAuth,
happyHoursController.addHappyHours
);
router.put(
'/v1/happyhours/:id',
authController.checkAuth,
happyHoursController.updateHappyHours
);
router.delete(
'/v1/happyhours/:id',
authController.checkAuth,
happyHoursController.deleteHappyHours
);
router.get('/v1/locationtypes', locationTypeController.getLocationTypes);
module.exports = router;
|
Fix Wholeness of the World to be max 1 per round
|
const DrawCard = require('../../drawcard.js');
class WholenessOfTheWorld extends DrawCard {
setupCardAbilities(ability) {
this.wouldInterrupt({
title: 'Keep a claimed ring',
when: {
onReturnRing: (event, context) => event.ring.claimedBy === context.player.name
},
cannotBeMirrored: true,
effect: 'prevent {1} from returning to the unclaimed pool',
effectArgs: context => context.event.ring,
handler: context => context.cancel(),
max: ability.limit.perRound(1)
});
}
}
WholenessOfTheWorld.id = 'wholeness-of-the-world';
module.exports = WholenessOfTheWorld;
|
const DrawCard = require('../../drawcard.js');
class WholenessOfTheWorld extends DrawCard {
setupCardAbilities() {
this.wouldInterrupt({
title: 'Keep a claimed ring',
when: {
onReturnRing: (event, context) => event.ring.claimedBy === context.player.name
},
cannotBeMirrored: true,
effect: 'prevent {1} from returning to the unclaimed pool',
effectArgs: context => context.event.ring,
handler: context => context.cancel()
});
}
}
WholenessOfTheWorld.id = 'wholeness-of-the-world';
module.exports = WholenessOfTheWorld;
|
Set return with config SentinelBootstraper instance
|
<?php
if (!function_exists('auth')) {
function auth()
{
return sentinel();
}
}
if (!function_exists('sentinel')) {
function sentinel()
{
$config = new Library\Sentinel\SentinelBootstrapper(__DIR__.'/../config/sentinel.php');
return Cartalyst\Sentinel\Native\Facades\Sentinel::instance($config)->getSentinel();
}
}
if (!function_exists('user')) {
function user($user = null)
{
if ($user == null)
return sentinel()->getUser();
elseif ($user instanceof \Cartalyst\Sentinel\Users\UserInterface)
return sentinel()->findById($user->id);
elseif (is_numeric($user))
return sentinel()->findById($user);
else
return null;
}
}
|
<?php
if (!function_exists('auth')) {
function auth()
{
return sentinel();
}
}
if (!function_exists('sentinel')) {
function sentinel()
{
return Cartalyst\Sentinel\Native\Facades\Sentinel::instance()->getSentinel();
}
}
if (!function_exists('user')) {
function user($user = null)
{
if ($user == null)
return sentinel()->getUser();
elseif ($user instanceof \Cartalyst\Sentinel\Users\UserInterface)
return sentinel()->findById($user->id);
elseif (is_numeric($user))
return sentinel()->findById($user);
else
return null;
}
}
|
Fix displaying quotes in followups list
|
angular.module('codebrag.common.directives')
.directive('reactionMessageSummary', function($filter) {
return {
restrict: 'E',
template: '<span ng-bind-html-unsafe="reactionMessage"></span>',
replace: true,
scope: {
reaction: '='
},
link: function(scope, el, attrs) {
var reaction = scope.reaction;
if(reaction.message) {
scope.reactionMessage = $filter('truncate')(reaction.message, 50);
} else {
scope.reactionMessage = reaction.reactionAuthor + ' liked your code.';
}
}
}
});
|
angular.module('codebrag.common.directives')
.directive('reactionMessageSummary', function() {
return {
restrict: 'E',
template: '<span>{{reactionMessage | truncate:50}}</span>',
replace: true,
scope: {
reaction: '='
},
link: function(scope, el, attrs) {
var reaction = scope.reaction;
if(reaction.message) {
scope.reactionMessage = reaction.message;
} else {
scope.reactionMessage = reaction.reactionAuthor + ' liked your code.';
}
}
}
});
|
Fix media deletion issues and media model implicit binding
|
<?php
declare(strict_types=1);
use Cortex\Foundation\Http\Middleware\Clockwork;
use Illuminate\Database\Eloquent\Relations\Relation;
return function () {
// Bind route models and constrains
Route::pattern('locale', '[a-z]{2}');
Route::pattern('media', '[a-zA-Z0-9-_]+');
Route::pattern('accessarea', '[a-zA-Z0-9-_]+');
Route::model('media', config('media-library.media_model'));
Route::model('accessarea', config('cortex.foundation.models.accessarea'));
// Map relations
Relation::morphMap([
'media' => config('media-library.media_model'),
'accessarea' => config('cortex.foundation.models.accessarea'),
]);
// Append middleware to the 'web' middleware group
$this->app->environment('production') || Route::pushMiddlewareToGroup('web', Clockwork::class);
};
|
<?php
declare(strict_types=1);
use Cortex\Foundation\Http\Middleware\Clockwork;
use Illuminate\Database\Eloquent\Relations\Relation;
return function () {
// Bind route models and constrains
Route::pattern('locale', '[a-z]{2}');
Route::pattern('accessarea', '[a-zA-Z0-9-_]+');
Route::model('media', config('medialibrary.media_model'));
Route::model('accessarea', config('cortex.foundation.models.accessarea'));
// Map relations
Relation::morphMap([
'media' => config('medialibrary.media_model'),
'accessarea' => config('cortex.foundation.models.accessarea'),
]);
// Append middleware to the 'web' middleware group
$this->app->environment('production') || Route::pushMiddlewareToGroup('web', Clockwork::class);
};
|
Make helper functions full `@deploy`s so they support global pyinfra kwargs.
|
from pyinfra.api import deploy
from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
@deploy('Deploy Kubernetes master')
def deploy_kubernetes_master(
state, host,
etcd_nodes,
):
# Install server components
install_kubernetes(components=(
'kube-apiserver', 'kube-scheduler', 'kube-controller-manager',
))
# Configure the API server, passing in our etcd nodes
configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes)
configure_kubernetes_component('kube-scheduler')
configure_kubernetes_component('kube-controller-manager')
@deploy('Deploy Kubernetes node')
def deploy_kubernetes_node(
state, host,
master_address,
):
# Install node components
install_kubernetes(components=(
'kubelet', 'kube-proxy',
))
# Setup the kubeconfig for kubelet & kube-proxy to use
configure_kubeconfig(master_address)
configure_kubernetes_component('kubelet')
configure_kubernetes_component('kube-proxy')
|
from .configure import configure_kubeconfig, configure_kubernetes_component
from .install import install_kubernetes
def deploy_kubernetes_master(etcd_nodes):
# Install server components
install_kubernetes(components=(
'kube-apiserver', 'kube-scheduler', 'kube-controller-manager',
))
# Configure the API server, passing in our etcd nodes
configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes)
configure_kubernetes_component('kube-scheduler')
configure_kubernetes_component('kube-controller-manager')
def deploy_kubernetes_node(master_address):
# Install node components
install_kubernetes(components=(
'kubelet', 'kube-proxy',
))
# Setup the kubeconfig for kubelet & kube-proxy to use
configure_kubeconfig(master_address)
configure_kubernetes_component('kubelet')
configure_kubernetes_component('kube-proxy')
|
Use double quotes instead of single ones.
|
var gulp = require("gulp");
var tasks = [];
// Browserify
var browserify = require("browserify");
var vinylSourceStream = require("vinyl-source-stream");
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform("brfs");
bundle = function() {
bundler.bundle()
.pipe(vinylSourceStream(output+".js"))
.pipe(gulp.dest(destination));
};
bundle();
});
tasks.push(output+"-browserify");
};
makeBrowserify("./api/index.js", "./public", "api");
// Watch
gulp.task("watch", function() {
gulp.watch(["./api/*"], ["api-browserify"]);
});
// All
gulp.task("default", tasks);
|
var gulp = require('gulp');
var tasks = [];
// Browserify
var browserify = require('browserify');
var vinylSourceStream = require('vinyl-source-stream');
var makeBrowserify = function(source, destination, output) {
gulp.task(output+"-browserify", function() {
bundler = browserify(source);
bundler.transform('brfs');
bundle = function() {
bundler.bundle()
.pipe(vinylSourceStream(output+".js"))
.pipe(gulp.dest(destination));
};
bundle();
});
tasks.push(output+"-browserify");
};
makeBrowserify("./api/index.js", "./public", "api");
// Watch
gulp.task("watch", function() {
gulp.watch(["./api/*"], ["api-browserify"]);
});
// All
gulp.task('default', tasks);
|
Replace function that IE11 does not support
https://bugzilla.redhat.com/show_bug.cgi?id=1448104
|
//= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
$('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
});
|
//= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].includes(state)) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
$('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
});
|
Update default CONDA_NPY to 18
|
from __future__ import print_function, division, absolute_import
import os
import sys
from os.path import abspath, expanduser, join
import conda.config as cc
CONDA_PY = int(os.getenv('CONDA_PY', cc.default_python.replace('.', '')))
CONDA_NPY = int(os.getenv('CONDA_NPY', 18))
PY3K = int(bool(CONDA_PY >= 30))
if cc.root_writable:
croot = join(cc.root_dir, 'conda-bld')
else:
croot = abspath(expanduser('~/conda-bld'))
build_prefix = join(cc.envs_dirs[0], '_build')
test_prefix = join(cc.envs_dirs[0], '_test')
def _get_python(prefix):
if sys.platform == 'win32':
res = join(prefix, 'python.exe')
else:
res = join(prefix, 'bin/python')
return res
build_python = _get_python(build_prefix)
test_python = _get_python(test_prefix)
def show():
import conda.config as cc
print('CONDA_PY:', CONDA_PY)
print('CONDA_NPY:', CONDA_NPY)
print('subdir:', cc.subdir)
print('croot:', croot)
|
from __future__ import print_function, division, absolute_import
import os
import sys
from os.path import abspath, expanduser, join
import conda.config as cc
CONDA_PY = int(os.getenv('CONDA_PY', cc.default_python.replace('.', '')))
CONDA_NPY = int(os.getenv('CONDA_NPY', 17))
PY3K = int(bool(CONDA_PY >= 30))
if cc.root_writable:
croot = join(cc.root_dir, 'conda-bld')
else:
croot = abspath(expanduser('~/conda-bld'))
build_prefix = join(cc.envs_dirs[0], '_build')
test_prefix = join(cc.envs_dirs[0], '_test')
def _get_python(prefix):
if sys.platform == 'win32':
res = join(prefix, 'python.exe')
else:
res = join(prefix, 'bin/python')
return res
build_python = _get_python(build_prefix)
test_python = _get_python(test_prefix)
def show():
import conda.config as cc
print('CONDA_PY:', CONDA_PY)
print('CONDA_NPY:', CONDA_NPY)
print('subdir:', cc.subdir)
print('croot:', croot)
|
Update solution to be consistent
|
def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_valid = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="valid", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
img_in = np.expand_dims(sample_image, 0)
img_out_same = conv_strides_same.predict(img_in)
img_out_valid = conv_strides_valid.predict(img_in)
print("Shape of result with SAME padding:", img_out_same.shape)
print("Shape of result with VALID padding:", img_out_valid.shape)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
ax0.imshow(img_in[0].astype(np.uint8))
ax1.imshow(img_out_same[0].astype(np.uint8))
ax2.imshow(img_out_valid[0].astype(np.uint8))
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, outputs=x)
x2 = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="valid", kernel_initializer=my_init)(inp)
conv_strides_valid = Model(inputs=inp, outputs=x2)
img_out = conv_strides_same.predict(np.expand_dims(sample_image, 0))
img_out2 = conv_strides_valid.predict(np.expand_dims(sample_image, 0))
show(img_out[0])
print("Shape of result with SAME padding:", img_out.shape)
print("Shape of result with VALID padding:", img_out2.shape)
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
Add decoder_datasets() to BaseModelParams to indicate which datasets are to be decoded.
PiperOrigin-RevId: 413779472
|
# Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""BaseModelParams class definition."""
import abc
from typing import List, Type, TypeVar
from lingvo.jax import base_input
from lingvo.jax import py_utils
InstantiableParams = py_utils.InstantiableParams
_BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams')
BaseModelParamsT = Type[_BaseModelParamsT]
class BaseModelParams(metaclass=abc.ABCMeta):
"""Encapsulates the parameters for a model."""
# p.is_training on each input param is used to determine whether
# the dataset is used for training or eval.
@abc.abstractmethod
def datasets(self) -> List[base_input.BaseInputParams]:
"""Returns the list of dataset parameters."""
# Optional. Returns a list of datasets to be decoded.
def decoder_datasets(self) -> List[base_input.BaseInputParams]:
"""Returns the list of dataset parameters for decoder."""
return []
@abc.abstractmethod
def task(self) -> InstantiableParams:
"""Returns the task parameters."""
|
# Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""BaseModelParams class definition."""
import abc
from typing import List, Type, TypeVar
from lingvo.jax import base_input
from lingvo.jax import py_utils
InstantiableParams = py_utils.InstantiableParams
_BaseModelParamsT = TypeVar('_BaseModelParamsT', bound='BaseModelParams')
BaseModelParamsT = Type[_BaseModelParamsT]
class BaseModelParams(metaclass=abc.ABCMeta):
"""Encapsulates the parameters for a model."""
@abc.abstractmethod
def datasets(self) -> List[base_input.BaseInputParams]:
"""Returns the list of dataset parameters."""
@abc.abstractmethod
def task(self) -> InstantiableParams:
"""Returns the task parameters."""
|
Update blueprint to prepare for publishing.
|
module.exports = {
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
afterInstall: function() {
return this.addBowerPackagesToProject([
{ name: 'qunit', target: '~1.20.0' },
{ name: 'ember-cli-test-loader', target: '0.2.1' },
{ name: 'ember-qunit-notifications', target: '0.1.0' },
{ name: 'ember-qunit', target: '0.4.17' }
]);
}
};
|
module.exports = {
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
},
afterInstall: function() {
return this.addBowerPackagesToProject([
{ name: 'qunit', target: '~1.19.0' },
{ name: 'ember-cli-test-loader', target: '0.2.1' },
{ name: 'ember-qunit-notifications', target: '0.0.7' },
{ name: 'ember-qunit', target: '0.4.16' }
]);
}
};
|
Check props before calling function
|
// main.js
(function() {
'use strict';
var React = require('react');
var d3 = require('d3');
var Whiteboard = React.createClass({
svg: null,
propTypes: {
width: React.PropTypes.number,
height: React.PropTypes.number,
listener: React.PropTypes.func
},
componentDidMount: function() {
this.svg = d3.select(this.refs.whiteboard).append('svg')
.attr('width', this.props.width)
.attr('height', this.props.height);
var that = this;
this.svg.on('click.whiteboard', function() {
if (that.props.listener) {
that.props.listener(d3.event);
}
});
},
render: function() {
return (<div ref="whiteboard"></div>);
}
});
module.exports = Whiteboard;
})();
|
// main.js
(function() {
'use strict';
var React = require('react');
var d3 = require('d3');
var Whiteboard = React.createClass({
svg: null,
propTypes: {
width: React.PropTypes.number,
height: React.PropTypes.number,
listener: React.PropTypes.func
},
componentDidMount: function() {
this.svg = d3.select(this.refs.whiteboard).append('svg')
.attr('width', this.props.width)
.attr('height', this.props.height);
var that = this;
this.svg.on('click.whiteboard', function() {
that.props.listener(d3.event);
});
},
render: function() {
return (<div ref="whiteboard"></div>);
}
});
module.exports = Whiteboard;
})();
|
Use only 1byte on setValue
|
package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiUUID;
import com.uxxu.konashi.lib.KonashiUtils;
import com.uxxu.konashi.lib.store.UartStore;
import com.uxxu.konashi.lib.util.UartUtils;
import java.util.UUID;
/**
* Created by e10dokup on 2015/09/23
**/
public class UartModeAction extends UartAction {
private static final String TAG = UartModeAction.class.getSimpleName();
private final UartModeAction self = this;
private static final UUID UUID = KonashiUUID.UART_CONFIG_UUID;
private int mMode;
public UartModeAction(BluetoothGattService service, int mode, UartStore store) {
super(service, UUID, store, true);
mMode = mode;
}
@Override
protected void setValue() {
getCharacteristic().setValue(new byte[]{KonashiUtils.int2bytes(mMode)[0]});
}
@Override
protected boolean hasValidParams() {
return UartUtils.isValidMode(mMode);
}
}
|
package com.uxxu.konashi.lib.action;
import android.bluetooth.BluetoothGattService;
import com.uxxu.konashi.lib.KonashiUUID;
import com.uxxu.konashi.lib.KonashiUtils;
import com.uxxu.konashi.lib.store.UartStore;
import com.uxxu.konashi.lib.util.UartUtils;
import java.util.UUID;
/**
* Created by e10dokup on 2015/09/23
**/
public class UartModeAction extends UartAction {
private static final String TAG = UartModeAction.class.getSimpleName();
private final UartModeAction self = this;
private static final UUID UUID = KonashiUUID.UART_CONFIG_UUID;
private int mMode;
public UartModeAction(BluetoothGattService service, int mode, UartStore store) {
super(service, UUID, store, true);
mMode = mode;
}
@Override
protected void setValue() {
getCharacteristic().setValue(KonashiUtils.int2bytes(mMode));
}
@Override
protected boolean hasValidParams() {
return UartUtils.isValidMode(mMode);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.