text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Enable auto-refresh when inviting a participant to an inventory
|
(function() {
'use strict';
angular.module('PDRClient')
.controller('InviteInventoryUserCtrl', InviteInventoryUserCtrl);
InviteInventoryUserCtrl.$inject = [
'$scope',
'$stateParams',
'InventoryInvitation'
];
function InviteInventoryUserCtrl($scope, $stateParams, InventoryInvitation) {
var vm = this;
vm.sendInvitation = function(invitation) {
vm.alerts = [];
vm.addAlert = function(message) {
vm.alerts.push({type: 'danger', msg: message});
};
vm.closeAlert = function(index) {
vm.alerts.splice(index, 1);
};
InventoryInvitation.create({inventory_id: $stateParams.id}, invitation)
.$promise
.then(function() {
$scope.$emit('invite-sent');
$scope.$emit('update_participants');
})
.catch(function(response) {
var errors = response.data.errors;
angular.forEach(errors, function(error, field) {
vm.addAlert(field + " : " + error);
});
});
};
}
})();
|
(function() {
'use strict';
angular.module('PDRClient')
.controller('InviteInventoryUserCtrl', InviteInventoryUserCtrl);
InviteInventoryUserCtrl.$inject = [
'$scope',
'$stateParams',
'InventoryInvitation'
];
function InviteInventoryUserCtrl($scope, $stateParams, InventoryInvitation) {
var vm = this;
vm.sendInvitation = function(invitation) {
vm.alerts = [];
vm.addAlert = function(message) {
vm.alerts.push({type: 'danger', msg: message});
};
vm.closeAlert = function(index) {
vm.alerts.splice(index, 1);
};
InventoryInvitation.create({inventory_id: $stateParams.id}, invitation)
.$promise
.then(function() {
$scope.$emit('invite-sent');
})
.catch(function(response) {
var errors = response.data.errors;
angular.forEach(errors, function(error, field) {
vm.addAlert(field + " : " + error);
});
});
};
}
})();
|
Remove node counts and update docstrings on new view for activity
|
from website import settings
from website.project import Node
from website.project import utils
from modularodm.query.querydialect import DefaultQueryDialect as Q
def activity():
"""Reads node activity from pre-generated popular projects and registrations.
New and Noteworthy projects are set manually or through `scripts/populate_new_and_noteworthy_projects.py`
Popular projects and registrations are generated by `scripts/populate_popular_projects_and_registrations.py`
"""
# New and Noreworthy Projects
new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer
new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers]
# Popular Projects
popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer
# Popular Registrations
popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer
return {
'new_and_noteworthy_projects': new_and_noteworthy_projects,
'recent_public_registrations': utils.recent_public_registrations(),
'popular_public_projects': popular_public_projects,
'popular_public_registrations': popular_public_registrations,
}
|
from website import settings
from website.project import Node
from website.project import utils
from modularodm.query.querydialect import DefaultQueryDialect as Q
def activity():
node_data = utils.get_node_data()
if node_data:
hits = utils.hits(node_data)
else:
hits = {}
# New Projects
new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer
new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers]
# Popular Projects
popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer
# Popular Registrations
popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer
return {
'new_and_noteworthy_projects': new_and_noteworthy_projects,
'recent_public_registrations': utils.recent_public_registrations(),
'popular_public_projects': popular_public_projects,
'popular_public_registrations': popular_public_registrations,
'hits': hits,
}
|
Remove flickr key, add forecast.io key
|
#!/usr/bin/env python3
# weatherBot keys
# Copyright 2015 Brian Mitchell under the MIT license
# See the GitHub repository: https://github.com/bman4789/weatherBot
import os
keys = dict(
consumer_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
forecastio_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)
def set_twitter_env_vars():
if os.getenv('WEATHERBOT_CONSUMER_KEY', 0) is 0 or os.getenv('WEATHERBOT_CONSUMER_SECRET', 0) is 0 \
or os.getenv('WEATHERBOT_ACCESS_KEY', 0) is 0 or os.getenv('WEATHERBOT_ACCESS_SECRET', 0) is 0:
os.environ['WEATHERBOT_CONSUMER_KEY'] = keys['consumer_key']
os.environ['WEATHERBOT_CONSUMER_SECRET'] = keys['consumer_secret']
os.environ['WEATHERBOT_ACCESS_KEY'] = keys['access_key']
os.environ['WEATHERBOT_ACCESS_SECRET'] = keys['access_secret']
def set_forecastio_env_vars():
if os.getenv('WEATHERBOT_FORECASTIO_KEY', 0) is 0:
os.environ['WEATHERBOT_FORECASTIO_KEY'] = keys['forecastio_key']
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# weatherBot keys
# Copyright 2015 Brian Mitchell under the MIT license
# See the GitHub repository: https://github.com/bman4789/weatherBot
import os
keys = dict(
consumer_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
consumer_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
access_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
flickr_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
)
def set_twitter_env_vars():
if os.getenv('WEATHERBOT_CONSUMER_KEY', 0) is 0 or os.getenv('WEATHERBOT_CONSUMER_SECRET', 0) is 0 \
or os.getenv('WEATHERBOT_ACCESS_KEY', 0) is 0 or os.getenv('WEATHERBOT_ACCESS_SECRET', 0) is 0:
os.environ['WEATHERBOT_CONSUMER_KEY'] = keys['consumer_key']
os.environ['WEATHERBOT_CONSUMER_SECRET'] = keys['consumer_secret']
os.environ['WEATHERBOT_ACCESS_KEY'] = keys['access_key']
os.environ['WEATHERBOT_ACCESS_SECRET'] = keys['access_secret']
def set_flickr_env_vars():
if os.getenv('WEATHERBOT_FLICKR_KEY', 0) is 0:
os.environ['WEATHERBOT_FLICKR_KEY'] = keys['flickr_key']
|
Fix one missed logger instance
|
'use strict';
const logger = require('winston');
const Worker = require('./Worker');
class FetchWorker extends Worker {
constructor(blink) {
super(blink);
this.blink = blink;
}
setup() {
this.queue = this.blink.queues.fetchQ;
}
async consume(fetchMessage) {
const { url, options } = fetchMessage.payload.data;
try {
const response = await fetch(url, options);
logger.info(`FetchQ.process() | ${fetchMessage.payload.meta.id} | ${response.status} ${response.statusText}`);
this.queue.ack(fetchMessage);
return true;
} catch (error) {
// Todo: retry
logger.error(`FetchQ.process() | ${fetchMessage.payload.meta.id} | ${error}`);
this.queue.nack(fetchMessage);
}
return false;
}
}
module.exports = FetchWorker;
|
'use strict';
const Worker = require('./Worker');
class FetchWorker extends Worker {
constructor(blink) {
super(blink);
this.blink = blink;
}
setup() {
this.queue = this.blink.queues.fetchQ;
}
async consume(fetchMessage) {
const { url, options } = fetchMessage.payload.data;
try {
const response = await fetch(url, options);
this.logger.info(`FetchQ.process() | ${fetchMessage.payload.meta.id} | ${response.status} ${response.statusText}`);
this.queue.ack(fetchMessage);
return true;
} catch (error) {
// Todo: retry
this.logger.error(`FetchQ.process() | ${fetchMessage.payload.meta.id} | ${error}`);
this.queue.nack(fetchMessage);
}
return false;
}
}
module.exports = FetchWorker;
|
Return a pointer instead of a copy.
This will allow later to change upstream to use a pointer receiver
for this interface so that copies will stop happening.
Signed-off-by: Simo Sorce <65f99581a93cf30dafc32b5c178edc6b0294a07f@redhat.com>
|
package util
import (
"strings"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
)
// ToDefaultAuthorizationAttributes coerces Action to authorizer.Attributes.
func ToDefaultAuthorizationAttributes(user user.Info, namespace string, in authorizationapi.Action) authorizer.Attributes {
tokens := strings.SplitN(in.Resource, "/", 2)
resource := ""
subresource := ""
switch {
case len(tokens) == 2:
subresource = tokens[1]
fallthrough
case len(tokens) == 1:
resource = tokens[0]
}
return &authorizer.AttributesRecord{
User: user,
Verb: in.Verb,
Namespace: namespace,
APIGroup: in.Group,
APIVersion: in.Version,
Resource: resource,
Subresource: subresource,
Name: in.ResourceName,
ResourceRequest: !in.IsNonResourceURL,
Path: in.Path,
}
}
|
package util
import (
"strings"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
)
// ToDefaultAuthorizationAttributes coerces Action to authorizer.Attributes.
func ToDefaultAuthorizationAttributes(user user.Info, namespace string, in authorizationapi.Action) authorizer.Attributes {
tokens := strings.SplitN(in.Resource, "/", 2)
resource := ""
subresource := ""
switch {
case len(tokens) == 2:
subresource = tokens[1]
fallthrough
case len(tokens) == 1:
resource = tokens[0]
}
return authorizer.AttributesRecord{
User: user,
Verb: in.Verb,
Namespace: namespace,
APIGroup: in.Group,
APIVersion: in.Version,
Resource: resource,
Subresource: subresource,
Name: in.ResourceName,
ResourceRequest: !in.IsNonResourceURL,
Path: in.Path,
}
}
|
Build test definitions as umd
|
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';
export default [
{
input: 'mod.ts',
output: {
name: 'KeyCode',
format: 'cjs',
file: 'dist/keycode.cjs.js'
}
},
{
input: 'mod.ts',
output: {
name: 'KeyCode',
format: 'iife',
file: 'dist/keycode.min.js',
sourcemap: true
},
plugins: [typescript(), terser()]
},
{
input: 'mod.ts',
output: {
name: 'KeyCode',
format: 'esm',
file: 'dist/keycode.es6.js'
}
},
{
input: 'test-definitions.ts',
output: {
name: 'KeyCodeJSTestDefinitions',
format: 'umd',
file: 'dist/test-definitions.umd.js'
},
plugins: [typescript()]
}
];
|
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';
export default [
{
input: 'mod.ts',
output: {
name: 'KeyCode',
format: 'cjs',
file: 'dist/keycode.cjs.js'
}
},
{
input: 'mod.ts',
output: {
name: 'KeyCode',
format: 'iife',
file: 'dist/keycode.min.js',
sourcemap: true
},
plugins: [typescript(), terser()]
},
{
input: 'mod.ts',
output: {
name: 'KeyCode',
format: 'esm',
file: 'dist/keycode.es6.js'
}
},
{
input: 'test-definitions.ts',
output: {
format: 'cjs',
file: 'dist/test-definitions.cjs.js'
},
plugins: [typescript()]
}
];
|
Fix HTTPServer imports with Python 3
|
#!/usr/bin/env python
import os
import sys
import webbrowser
if sys.version_info < (3, 0):
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
else:
from http.server import SimpleHTTPRequestHandler
from http.server import HTTPServer
__all__ = ['run_server']
def run_server(port=8000,scene_file="Null"):
#change dir to static first.
os.chdir("static/")
HandlerClass = SimpleHTTPRequestHandler
ServerClass = HTTPServer
Protocol = "HTTP/1.0"
server_address = ('127.0.0.1', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
print("hit ctrl+c to stop the server..")
print("To view visualization, open:\n")
url = "http://localhost:"+ str(sa[1]) + "/index.html?load=" + scene_file
print(url)
webbrowser.open(url)
httpd.serve_forever()
if __name__ == "__main__":
run_server()
|
#!/usr/bin/env python
import os
import webbrowser
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
__all__ = ['run_server']
def run_server(port=8000,scene_file="Null"):
#change dir to static first.
os.chdir("static/")
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
server_address = ('127.0.0.1', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print("Serving HTTP on", sa[0], "port", sa[1], "...")
print("hit ctrl+c to stop the server..")
print("To view visualization, open:\n")
url = "http://localhost:"+ str(sa[1]) + "/index.html?load=" + scene_file
print(url)
webbrowser.open(url)
httpd.serve_forever()
if __name__ == "__main__":
run_server()
|
Fix length of arguments in promise extensions
|
// Used by promise extensions that are based on array extensions.
'use strict';
var callable = require('es5-ext/lib/Object/valid-callable')
, deferred = require('../../deferred')
module.exports = function (name, ext) {
deferred.extend(name, function (cb) {
var def;
(cb == null) || callable(cb);
if (!this.pending) {
this.pending = [];
}
def = deferred();
this.pending.push(name, [arguments, def.resolve]);
return def.promise;
}, function (args, resolve) {
var result;
if (this.failed) {
resolve(this.value);
} else {
try {
result = ext.apply(this.value, args);
} catch (e) {
result = e;
}
resolve(result);
}
}, function (cb) {
var result;
(cb == null) || callable(cb);
if (this.failed) {
return this;
} else {
try {
return ext.apply(this.value, arguments);
} catch (e) {
return promise(e);
}
}
});
};
|
// Used by promise extensions that are based on array extensions.
'use strict';
var callable = require('es5-ext/lib/Object/valid-callable')
, deferred = require('../../deferred')
module.exports = function (name, ext) {
deferred.extend(name, function (cb) {
var def;
(cb == null) || callable(cb);
if (!this.pending) {
this.pending = [];
}
def = deferred();
this.pending.push(name, [arguments, def.resolve]);
return def.promise;
}, function (args, resolve) {
var result;
if (this.failed) {
resolve(this.value);
} else {
try {
result = ext.call(this.value, args[0], args[1], args[2]);
} catch (e) {
result = e;
}
resolve(result);
}
}, function (cb, arg2, arg3) {
var result;
(cb == null) || callable(cb);
if (this.failed) {
return this;
} else {
try {
return ext.call(this.value, cb, arg2, arg3);
} catch (e) {
return promise(e);
}
}
});
};
|
Add doc comments to internal funcs.
|
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package workers
import (
"time"
"github.com/juju/errors"
"github.com/juju/juju/worker/dependency"
)
const (
engineErrorDelay = 3 * time.Second
engineBounceDelay = 10 * time.Second
)
func newEngine() (dependency.Engine, error) {
config := newEngineConfig()
engine, err := dependency.NewEngine(config)
if err != nil {
return nil, errors.Trace(err)
}
return engine, nil
}
func newEngineConfig() dependency.EngineConfig {
return dependency.EngineConfig{
IsFatal: isFatal,
MoreImportant: moreImportant,
ErrorDelay: engineErrorDelay,
BounceDelay: engineBounceDelay,
}
}
// isFatal is an implementation of the IsFatal function in
// dependency.EnginConfig.
func isFatal(err error) bool {
return false
}
// moreImportant is an implementation of the MoreImportant function in
// dependency.EnginConfig.
func moreImportant(err, worst error) error {
return worst
}
|
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package workers
import (
"time"
"github.com/juju/errors"
"github.com/juju/juju/worker/dependency"
)
const (
engineErrorDelay = 3 * time.Second
engineBounceDelay = 10 * time.Second
)
func newEngine() (dependency.Engine, error) {
config := newEngineConfig()
engine, err := dependency.NewEngine(config)
if err != nil {
return nil, errors.Trace(err)
}
return engine, nil
}
func newEngineConfig() dependency.EngineConfig {
return dependency.EngineConfig{
IsFatal: isFatal,
MoreImportant: moreImportant,
ErrorDelay: engineErrorDelay,
BounceDelay: engineBounceDelay,
}
}
func isFatal(err error) bool {
return false
}
func moreImportant(err, worst error) error {
return worst
}
|
snapshot_scheduler: Use the correctly named env vars
|
# -*- encoding: utf-8 -*-
import datetime as dt
import os
import mock
from unittest.mock import patch
import snapshot_scheduler
class patched_datetime(dt.datetime):
@classmethod
def utcnow(cls):
return dt.datetime(2011, 6, 21, 0, 0, 0, 0)
@mock.patch('datetime.datetime', patched_datetime)
def test_writes_message_to_sqs(sns_client, topic_arn):
private_bucket_name = "private_bucket_name"
es_index = "es_index"
patched_os_environ = {
'TOPIC_ARN': topic_arn,
'PRIVATE_BUCKET_NAME': private_bucket_name,
'ES_INDEX': es_index
}
with patch.dict(os.environ, patched_os_environ, clear=True):
snapshot_scheduler.main(sns_client=sns_client)
messages = sns_client.list_messages()
assert len(messages) == 1
assert messages[0][':message'] == {
'time': '2011-06-21T00:00:00',
'private_bucket_name': private_bucket_name,
'es_index': es_index
}
|
# -*- encoding: utf-8 -*-
import datetime as dt
import os
import mock
from unittest.mock import patch
import snapshot_scheduler
class patched_datetime(dt.datetime):
@classmethod
def utcnow(cls):
return dt.datetime(2011, 6, 21, 0, 0, 0, 0)
@mock.patch('datetime.datetime', patched_datetime)
def test_writes_message_to_sqs(sns_client, topic_arn):
private_bucket_name = "private_bucket_name"
es_index = "es_index"
patched_os_environ = {
'TOPIC_ARN': topic_arn,
'TARGET_BUCKET_NAME': private_bucket_name,
'ES_INDEX': es_index
}
with patch.dict(os.environ, patched_os_environ, clear=True):
snapshot_scheduler.main(
event=None,
_ctxt=None,
sns_client=sns_client
)
messages = sns_client.list_messages()
assert len(messages) == 1
assert messages[0][':message'] == {
'time': '2011-06-21T00:00:00',
'private_bucket_name': private_bucket_name,
'es_index': es_index
}
|
Use the AddChildCommand from the UI
|
/*
* EditSomeXML is a graphical XML editor
*
* Copyright (C) 2014 David Jackson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package editor.controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import xml.Element;
import xml.commands.AddChildCommand;
import editor.views.NewElementView;
/**
* The NewElementController deals with the actions of the NewElementView
* @see editor.views.NewElementView
*/
public class NewElementController implements ActionListener {
private NewElementView view;
private Element parent;
public NewElementController(NewElementView view, Element parent) {
this.view = view;
this.parent = parent;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
Element child = new Element(view.getTag());
parent.performCommand(new AddChildCommand(parent, child));
view.dispose();
}
}
|
/*
* EditSomeXML is a graphical XML editor
*
* Copyright (C) 2014 David Jackson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package editor.controllers;
import editor.views.NewElementView;
import xml.Element;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* The NewElementController deals with the actions of the NewElementView
* @see editor.views.NewElementView
*/
public class NewElementController implements ActionListener {
private NewElementView view;
private Element parent;
public NewElementController(NewElementView view, Element parent) {
this.view = view;
this.parent = parent;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
Element child = new Element(view.getTag());
parent.addChild(child);
view.dispose();
}
}
|
Add statement to toggleable variant migration to enable existing
|
<?php
declare(strict_types=1);
namespace Sylius\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20200309172908 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL');
$this->addSql('UPDATE sylius_product_variant SET enabled = 1');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
}
}
|
<?php
declare(strict_types=1);
namespace Sylius\Migrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20200309172908 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant ADD enabled TINYINT(1) NOT NULL');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE sylius_product_variant DROP enabled');
}
}
|
Remove jquery usage & replace with dom apis
|
import { later, cancel } from '@ember/runloop';
import { inject as service } from '@ember/service';
import Router from '../router';
export default {
name: 'add-announcer-to-router',
initialize() {
Router.reopen({
announcer: service('announcer'),
didTransition() {
this._super(...arguments);
this._timerId = later(() => {
if (this.isDestroying || this.isDestroyed) { return; }
let pageTitle = document.title.trim();
let serviceMessage = this.get('announcer.message');
let message = `${pageTitle} ${serviceMessage}`;
this.get('announcer').announce(message, 'polite');
}, 100);
},
willDestroy() {
cancel(this._timerId);
this._super();
}
});
}
};
|
import $ from 'jquery';
import { later, cancel } from '@ember/runloop';
import { inject as service } from '@ember/service';
import Router from '../router';
export default {
name: 'add-announcer-to-router',
initialize: function() {
Router.reopen({
announcer: service('announcer'),
didTransition: function() {
this._super(...arguments);
this._timerId = later(() => {
if (this.isDestroying || this.isDestroyed) { return; }
let pageTitle = $('title').html().trim();
let serviceMessage = this.get('announcer.message');
let message = `${pageTitle} ${serviceMessage}`;
this.get('announcer').announce(message, 'polite');
}, 100);
},
willDestroy() {
cancel(this._timerId);
this._super();
}
});
}
};
|
Add support for google-java-format versions 1.4, 1.5 and 1.6
|
package com.github.sherter.googlejavaformatgradleplugin.format;
import com.google.common.collect.ImmutableList;
/** Static factory method for creating new {@link Formatter}s. */
public class Gjf {
public static final String GROUP_ID = "com.google.googlejavaformat";
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "1.6");
/**
* Constructs a new formatter that delegates to <a
* href="https://github.com/google/google-java-format">google-java-format</a>.
*
* @param classLoader load {@code google-java-format} classes from this {@code ClassLoader}
* @param config configure the formatter according to this configuration
* @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed
*/
public static Formatter newFormatter(ClassLoader classLoader, Configuration config)
throws ReflectiveOperationException {
return newFormatterFactory(classLoader, config).create();
}
private static FormatterFactory newFormatterFactory(
ClassLoader classLoader, Configuration config) {
switch (config.version) {
case "1.0":
return new OneDotZeroFactory(classLoader, config);
case "1.1":
return new OneDotOneFactory(classLoader, config);
default:
return new OneDotOneFactory(classLoader, config);
}
}
}
|
package com.github.sherter.googlejavaformatgradleplugin.format;
import com.google.common.collect.ImmutableList;
/** Static factory method for creating new {@link Formatter}s. */
public class Gjf {
public static final String GROUP_ID = "com.google.googlejavaformat";
public static final String ARTIFACT_ID = "google-java-format";
public static final ImmutableList<String> SUPPORTED_VERSIONS =
ImmutableList.of("1.0", "1.1", "1.2", "1.3");
/**
* Constructs a new formatter that delegates to <a
* href="https://github.com/google/google-java-format">google-java-format</a>.
*
* @param classLoader load {@code google-java-format} classes from this {@code ClassLoader}
* @param config configure the formatter according to this configuration
* @throws ReflectiveOperationException if the requested {@code Formatter} cannot be constructed
*/
public static Formatter newFormatter(ClassLoader classLoader, Configuration config)
throws ReflectiveOperationException {
return newFormatterFactory(classLoader, config).create();
}
private static FormatterFactory newFormatterFactory(
ClassLoader classLoader, Configuration config) {
switch (config.version) {
case "1.0":
return new OneDotZeroFactory(classLoader, config);
case "1.1":
return new OneDotOneFactory(classLoader, config);
default:
return new OneDotOneFactory(classLoader, config);
}
}
}
|
Add `Meteor.isPackageTest` to mirror `isAppTest` and `isTest`.
For #6535
|
var TEST_METADATA_STR;
if (Meteor.isClient) {
TEST_METADATA_STR = meteorEnv.TEST_METADATA;
} else {
TEST_METADATA_STR = process.env.TEST_METADATA;
}
var TEST_METADATA = JSON.parse(TEST_METADATA_STR || "{}");
var testDriverPackageName = TEST_METADATA.driverPackage;
// Note that if we are in test-packages mode neither of these will be set,
// but we will have a test driver package
Meteor.isTest = !!TEST_METADATA.isTest;
Meteor.isAppTest = !!TEST_METADATA.isAppTest;
Meteor.isPackageTest = !!testDriverPackageName && !Meteor.isTest && !Meteor.isAppTest;
if (typeof testDriverPackageName === "string") {
Meteor.startup(function() {
var testDriverPackage = Package[testDriverPackageName];
if (! testDriverPackage) {
throw new Error("Can't find test driver package: " + testDriverPackageName);
}
// On the client, the test driver *must* define `runTests`
if (Meteor.isClient) {
if (typeof testDriverPackage.runTests !== "function") {
throw new Error("Test driver package " + testDriverPackageName
+ " missing `runTests` export");
}
testDriverPackage.runTests();
} else {
// The server can optionally define `start`
if (typeof testDriverPackage.start === "function") {
testDriverPackage.start();
}
}
});
}
|
var TEST_METADATA_STR;
if (Meteor.isClient) {
TEST_METADATA_STR = meteorEnv.TEST_METADATA;
} else {
TEST_METADATA_STR = process.env.TEST_METADATA;
}
var TEST_METADATA = JSON.parse(TEST_METADATA_STR || "{}");
// Note that if we are in test-packages mode neither of these will be set,
// but we will have a test driver package
Meteor.isTest = !!TEST_METADATA.isTest;
Meteor.isAppTest = !!TEST_METADATA.isAppTest;
var testDriverPackageName = TEST_METADATA.driverPackage;
if (typeof testDriverPackageName === "string") {
Meteor.startup(function() {
var testDriverPackage = Package[testDriverPackageName];
if (! testDriverPackage) {
throw new Error("Can't find test driver package: " + testDriverPackageName);
}
// On the client, the test driver *must* define `runTests`
if (Meteor.isClient) {
if (typeof testDriverPackage.runTests !== "function") {
throw new Error("Test driver package " + testDriverPackageName
+ " missing `runTests` export");
}
testDriverPackage.runTests();
} else {
// The server can optionally define `start`
if (typeof testDriverPackage.start === "function") {
testDriverPackage.start();
}
}
});
}
|
Update selectors to match to Google Music UI
|
"use strict";
var $ = require("jquery");
var Plugin = require("../modules/Plugin");
var Utils = require("../modules/Utilities");
var google = Object.create(Plugin);
google.init("google", "Google Play");
google.test = function () {
return (/play\.google\.[A-Z\.]{2,}\/music\/listen/i).test(document.location.href);
};
google.scrape = function () {
return {
album: $(".player-album").text(),
artist: $("#player-artist").text(),
duration: Utils.calculateDuration($("#time_container_duration").text() || ""),
elapsed: Utils.calculateDuration($("#time_container_current").text() || ""),
title: $("#player-song-title").text(),
stopped: !$('[data-id=play-pause]').hasClass("playing")
};
};
module.exports = google;
|
"use strict";
var $ = require("jquery");
var Plugin = require("../modules/Plugin");
var Utils = require("../modules/Utilities");
var google = Object.create(Plugin);
google.init("google", "Google Play");
google.test = function () {
return (/play\.google\.[A-Z\.]{2,}\/music\/listen/i).test(document.location.href);
};
google.scrape = function () {
return {
album: $(".player-album").text(),
artist: $("#player-artist").text(),
duration: Utils.calculateDuration($("#time_container_duration").text() || ""),
elapsed: Utils.calculateDuration($("#time_container_current").text() || ""),
title: $("#playerSongTitle").text(),
stopped: !$('button[data-id="play-pause"]').hasClass("playing")
};
};
module.exports = google;
|
Fix python 3 incompatible print statement
|
import boto.ec2
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('aws_access_key_id')
parser.add_argument('aws_secret_access_key')
parser.add_argument('region')
config = parser.parse_args()
conn = boto.ec2.connect_to_region(config.region,
aws_access_key_id=config.aws_access_key_id,
aws_secret_access_key=config.aws_secret_access_key)
images = conn.get_all_images(owners=['self'])
values = []
for image in images:
values.append('"%s": "%s"' % (image.name, image.id))
print( ','.join(values))
|
import boto.ec2
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('aws_access_key_id')
parser.add_argument('aws_secret_access_key')
parser.add_argument('region')
config = parser.parse_args()
conn = boto.ec2.connect_to_region(config.region,
aws_access_key_id=config.aws_access_key_id,
aws_secret_access_key=config.aws_secret_access_key)
images = conn.get_all_images(owners=['self'])
values = []
for image in images:
values.append('"%s": "%s"' % (image.name, image.id))
print ','.join(values)
|
Implement the EntryPreviewMixin in the EntryDetail view
|
"""Views for Zinnia entries"""
from django.views.generic.dates import BaseDateDetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.archives import ArchiveMixin
from zinnia.views.mixins.entry_preview import EntryPreviewMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
from zinnia.views.mixins.callable_queryset import CallableQuerysetMixin
from zinnia.views.mixins.templates import EntryArchiveTemplateResponseMixin
class EntryDateDetail(ArchiveMixin,
EntryArchiveTemplateResponseMixin,
CallableQuerysetMixin,
BaseDateDetailView):
"""
Mixin combinating:
- ArchiveMixin configuration centralizing conf for archive views
- EntryArchiveTemplateResponseMixin to provide a
custom templates depending on the date
- BaseDateDetailView to retrieve the entry with date and slug
- CallableQueryMixin to defer the execution of the *queryset*
property when imported
"""
queryset = Entry.published.on_site
class EntryDetail(EntryPreviewMixin,
EntryProtectionMixin,
EntryDateDetail):
"""
Detailled archive view for an Entry with password
and login protections and restricted preview.
"""
|
"""Views for Zinnia entries"""
from django.views.generic.dates import BaseDateDetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.archives import ArchiveMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
from zinnia.views.mixins.callable_queryset import CallableQuerysetMixin
from zinnia.views.mixins.templates import EntryArchiveTemplateResponseMixin
class EntryDateDetail(ArchiveMixin,
EntryArchiveTemplateResponseMixin,
CallableQuerysetMixin,
BaseDateDetailView):
"""
Mixin combinating:
- ArchiveMixin configuration centralizing conf for archive views
- EntryArchiveTemplateResponseMixin to provide a
custom templates depending on the date
- BaseDateDetailView to retrieve the entry with date and slug
- CallableQueryMixin to defer the execution of the *queryset*
property when imported
"""
queryset = Entry.published.on_site
class EntryDetail(EntryProtectionMixin, EntryDateDetail):
"""
Detailled view archive view for an Entry
with password and login protections.
"""
|
Fix main invocation on the browser
|
'use strict';
var util = require('util');
var zepto = require('zepto-browserify');
var Controller = require('./controller');
var Model = require('./model');
var $ = zepto.$;
function main() {
var controller = new EntriesController({
el: $('#animus .animus-view'),
});
}
function EntriesController() {
this.constructor.super_.apply(this, arguments);
}
util.inherits(EntriesController, Controller);
EntriesController.prototype.attach = function(el) {
var _this = this;
this.constructor.super_.prototype.attach.call(this, el);
this.$el('input.animus-new-entry-input').on('keydown', function(evt) {
_this.onKeydownNewEntry(evt);
});
};
EntriesController.prototype.onKeydownNewEntry = function(evt) {
console.log(evt.keyCode);
};
function Entry() {
this.createdAt = new Date();
this._super.constructor.apply(this, arguments);
}
util.inherits(Entry, Model);
if(!module.parent) {
$(function() {
main();
});
}
|
'use strict';
var util = require('util');
var zepto = require('zepto-browserify');
var Controller = require('./controller');
var Model = require('./model');
var $ = zepto.$;
function main() {
var controller = new EntriesController({
el: $('#animus .animus-view'),
});
}
function EntriesController() {
this.constructor.super_.apply(this, arguments);
}
util.inherits(EntriesController, Controller);
EntriesController.prototype.attach = function(el) {
var _this = this;
this.constructor.super_.prototype.attach.call(this, el);
this.$el('input.animus-new-entry-input').on('keydown', function(evt) {
_this.onKeydownNewEntry(evt);
});
};
EntriesController.prototype.onKeydownNewEntry = function(evt) {
console.log(evt.keyCode);
};
function Entry() {
this.createdAt = new Date();
this._super.constructor.apply(this, arguments);
}
util.inherits(Entry, Model);
if(!module.parent) {
main();
}
|
Bugfix: Stop handling after responding with 500
|
import http.server
import os
import oldfart.make
__all__ = ['make_http_request_handler_class']
def _send_head(self):
# FIXME: We die here if the directory doesn't exist ('make clean' anyone?)
path = self.translate_path(self.path)
target = os.path.relpath(path, self.maker.project_dir)
if not os.path.isdir(path):
retval, output = self.maker.make(target)
if retval == oldfart.make.FAILURE:
self.send_error(500, 'Could not generate resource')
return None
return super(self.__class__, self).send_head()
def make_http_request_handler_class(name, maker):
cls = type(name, (http.server.SimpleHTTPRequestHandler,), {
'maker': maker,
'send_head': _send_head
})
return cls
|
import http.server
import os
import oldfart.make
__all__ = ['make_http_request_handler_class']
def _send_head(self):
# FIXME: We die here if the directory doesn't exist ('make clean' anyone?)
path = self.translate_path(self.path)
target = os.path.relpath(path, self.maker.project_dir)
if not os.path.isdir(path):
retval, output = self.maker.make(target)
if retval == oldfart.make.FAILURE:
self.send_error(500, 'Could not generate resource')
return super(self.__class__, self).send_head()
def make_http_request_handler_class(name, maker):
cls = type(name, (http.server.SimpleHTTPRequestHandler,), {
'maker': maker,
'send_head': _send_head
})
return cls
|
Revert "get dynamicly if https or http is supported for youtube iframe api"
This reverts commit ffbdfe78a884b06447ff6da01137820224081962.
|
Ext.namespace('Kwf.Utils.YoutubePlayer');
Kwf.Utils.YoutubePlayer.isLoaded = false;
Kwf.Utils.YoutubePlayer.isCallbackCalled = false;
Kwf.Utils.YoutubePlayer.callbacks = [];
Kwf.Utils.YoutubePlayer.load = function(callback, scope)
{
if (Kwf.Utils.YoutubePlayer.isCallbackCalled) {
callback.call(scope || window);
return;
}
Kwf.Utils.YoutubePlayer.callbacks.push({
callback: callback,
scope: scope
});
if (Kwf.Utils.YoutubePlayer.isLoaded) return;
Kwf.Utils.YoutubePlayer.isLoaded = true;
var tag = document.createElement('script');
tag.setAttribute('type', 'text/javascript');
tag.setAttribute('src', 'http://www.youtube.com/iframe_api');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
};
if (typeof window.onYouTubePlayerAPIReady == 'undefined') {
window.onYouTubePlayerAPIReady = function() {
Kwf.Utils.YoutubePlayer.isCallbackCalled = true;
Kwf.Utils.YoutubePlayer.callbacks.forEach(function(i) {
i.callback.call(i.scope || window);
});
}
}
|
Ext.namespace('Kwf.Utils.YoutubePlayer');
Kwf.Utils.YoutubePlayer.isLoaded = false;
Kwf.Utils.YoutubePlayer.isCallbackCalled = false;
Kwf.Utils.YoutubePlayer.callbacks = [];
Kwf.Utils.YoutubePlayer.load = function(callback, scope)
{
if (Kwf.Utils.YoutubePlayer.isCallbackCalled) {
callback.call(scope || window);
return;
}
Kwf.Utils.YoutubePlayer.callbacks.push({
callback: callback,
scope: scope
});
if (Kwf.Utils.YoutubePlayer.isLoaded) return;
Kwf.Utils.YoutubePlayer.isLoaded = true;
var tag = document.createElement('script');
tag.setAttribute('type', 'text/javascript');
tag.setAttribute('src', '//www.youtube.com/iframe_api');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
};
if (typeof window.onYouTubePlayerAPIReady == 'undefined') {
window.onYouTubePlayerAPIReady = function() {
Kwf.Utils.YoutubePlayer.isCallbackCalled = true;
Kwf.Utils.YoutubePlayer.callbacks.forEach(function(i) {
i.callback.call(i.scope || window);
});
}
}
|
Add query to get one element
|
const promise = require('bluebird');
const config = require('./_config');
const options = {
promiseLib: promise
};
const pgp = require('pg-promise')(options);
const connectionString = config.selectENV(process.env.NODE_ENV);
const db = pgp(connectionString);
const getAllTodos = () => {
return db.any('select * from todos')
};
const getOneTodo = (id) => {
return db.one('select * from todos where id = $1', [id])
}
const createTodo = (attributes) => {
const sql = 'insert into todos(description, due) values($1, $2)'
const findsql = 'select * from todos where description = $1'
const variables = [
attributes.description,
attributes.due
]
db.none(sql, variables)
return db.one(findsql, variables)
};
const updateTodo = (id, attributes) => {
attributes.id = parseInt(id)
const sql = 'update todos set description = $1, due = $2 WHERE id = $3'
const variables = [
attributes.description,
attributes.due,
attributes.id
]
return db.none(sql, variables)
};
const deleteTodo = (id) => {
objId = parseInt(id)
return db.result('delete from todos where id = $1', [objId])
};
module.exports = {
getAllTodos,
createTodo,
updateTodo,
deleteTodo,
getOneTodo
};
|
const promise = require('bluebird');
const config = require('./_config');
const options = {
promiseLib: promise
};
const pgp = require('pg-promise')(options);
const connectionString = config.selectENV(process.env.NODE_ENV);
const db = pgp(connectionString);
const getAllTodos = () => {
return db.any('select * from todos')
};
const createTodo = (attributes) => {
const sql = 'insert into todos(description, due) values($1, $2)'
const variables = [
attributes.description,
attributes.due
]
return db.none(sql, variables)
};
const updateTodo = (id, attributes) => {
attributes.id = parseInt(id)
const sql = 'update todos set description = $1, status = $2, due = $3 WHERE id = $4'
const variables = [
attributes.description,
attributes.status,
attributes.due,
attributes.id
]
return db.none(sql, variables)
};
const deleteTodo = (id) => {
objId = parseInt(id)
return db.none('delete from todos where id = $1', [objId])
};
module.exports = {
getAllTodos,
createTodo,
updateTodo,
deleteTodo
};
|
Use an anonymous module declaration for AMD.
This allows loading via AMD using require('bluebird'), to match the npm module name.
|
if( typeof module !== "undefined" && module.exports ) {
module.exports = Promise;
}
else if( typeof define === "function" && define.amd ) {
define(function(){return Promise;});
}
else {
global.Promise = Promise;
}
return Promise;})(
(function(){
//shims for new Function("return this")()
if( typeof this !== "undefined" ) {
return this;
}
if( typeof process !== "undefined" &&
typeof global !== "undefined" &&
typeof process.execPath === "string" ) {
return global;
}
if( typeof window !== "undefined" &&
typeof document !== "undefined" &&
document.defaultView === window ) {
return window;
}
})(),
Function,
Array,
Error,
Object
);
|
if( typeof module !== "undefined" && module.exports ) {
module.exports = Promise;
}
else if( typeof define === "function" && define.amd ) {
define( "Promise", [], function(){return Promise;});
}
else {
global.Promise = Promise;
}
return Promise;})(
(function(){
//shims for new Function("return this")()
if( typeof this !== "undefined" ) {
return this;
}
if( typeof process !== "undefined" &&
typeof global !== "undefined" &&
typeof process.execPath === "string" ) {
return global;
}
if( typeof window !== "undefined" &&
typeof document !== "undefined" &&
document.defaultView === window ) {
return window;
}
})(),
Function,
Array,
Error,
Object
);
|
Use open-ended dependency on six
Having six pinned to 1.5.2 causes issues for e.g. Oscar when other dependencies specify a more current version. AFAIK, six is outstanding at being backwards-compatible, so it should be safe to allow any version above 1.5.2 to be installed.
AFAIK, django-extra-views is compatible with Python 2, so the classifiers should include it.
|
from setuptools import setup
setup(
name='django-extra-views',
version='0.6.5',
url='https://github.com/AndrewIngram/django-extra-views',
install_requires=[
'Django >=1.3',
'six>=1.5.2',
],
description="Extra class-based views for Django",
long_description=open('README.rst', 'r').read(),
license="MIT",
author="Andrew Ingram",
author_email="andy@andrewingram.net",
packages=['extra_views'],
package_dir={'extra_views': 'extra_views'},
include_package_data = True, # include everything in source control
package_data={'extra_views': ['*.py','contrib/*.py','tests/*.py','tests/templates/*.html', 'tests/templates/extra_views/*.html']},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3']
)
|
from setuptools import setup
setup(
name='django-extra-views',
version='0.6.5',
url='https://github.com/AndrewIngram/django-extra-views',
install_requires=[
'Django >=1.3',
'six==1.5.2',
],
description="Extra class-based views for Django",
long_description=open('README.rst', 'r').read(),
license="MIT",
author="Andrew Ingram",
author_email="andy@andrewingram.net",
packages=['extra_views'],
package_dir={'extra_views': 'extra_views'},
include_package_data = True, # include everything in source control
package_data={'extra_views': ['*.py','contrib/*.py','tests/*.py','tests/templates/*.html', 'tests/templates/extra_views/*.html']},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 3']
)
|
Use text/template instead of trying to do things myself. Log errors from ListenAndServe
|
package analytics
import (
"text/template"
"encoding/json"
"net/http"
"log"
"menteslibres.net/gosexy/redis"
)
var client *redis.Client
var redisKey = "analytics"
func redisConnect(host string, port uint)(error) {
var err error
client = redis.New()
err = client.Connect(host, port)
return err
}
func redisStore(value string) {
client.LPush(redisKey, value)
}
func jsHandler(w http.ResponseWriter, r *http.Request) {
serializedRequest, serializeError := json.Marshal(r)
if serializeError != nil {
http.Error(w, serializeError.Error(), http.StatusInternalServerError)
return
}
redisStore(string(serializedRequest))
w.Header().Set("Content-Type", "application/javascript")
w.WriteHeader(http.StatusCreated)
t, _ := template.ParseFiles("templates/analytics.js")
t.Execute(w, nil)
}
func main() {
redisConnect("localhost", 6379)
http.HandleFunc("/analytics.js", jsHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
client.Quit()
}
|
package main
import (
"fmt"
"encoding/json"
"net/http"
"menteslibres.net/gosexy/redis"
)
var client *redis.Client
var redisKey = "analytics"
func redisConnect(host string, port uint)(error) {
var err error
client = redis.New()
err = client.Connect(host, port)
return err
}
func jsHandler(w http.ResponseWriter, r *http.Request) {
serializedRequest, serializeError := json.Marshal(r)
if serializeError != nil {
fmt.Printf("Error: %s", serializeError.Error())
http.Error(w, serializeError.Error(), http.StatusInternalServerError)
}
client.LPush(redisKey, serializedRequest)
return
}
func main() {
redisConnect("localhost", 6379)
http.HandleFunc("/analytics.js", jsHandler)
http.ListenAndServe(":8080", nil)
client.Quit()
}
|
Remove null for empty set
|
package stream.flarebot.flarebot.commands;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import stream.flarebot.flarebot.FlareBot;
import stream.flarebot.flarebot.permissions.PerGuildPermissions;
import java.util.EnumSet;
public interface Command {
void onCommand(User sender, TextChannel channel, Message message, String[] args, Member member);
String getCommand();
String getDescription();
String getUsage();
CommandType getType();
default String getPermission() {
return "flarebot." + getCommand();
}
default EnumSet<Permission> getDiscordPermission() {
return EnumSet.noneOf(Permission.class);
}
default String[] getAliases() {
return new String[]{};
}
default PerGuildPermissions getPermissions(MessageChannel chan) {
return FlareBot.getInstance().getPermissions(chan);
}
default boolean isDefaultPermission() {
return (getPermission() != null && getType() != CommandType.HIDDEN && getType() != CommandType.MODERATION);
}
default boolean deleteMessage() {
return true;
}
default char getPrefix(Guild guild) {
return FlareBot.getPrefix(guild.getId());
}
}
|
package stream.flarebot.flarebot.commands;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import stream.flarebot.flarebot.FlareBot;
import stream.flarebot.flarebot.permissions.PerGuildPermissions;
import java.util.EnumSet;
public interface Command {
void onCommand(User sender, TextChannel channel, Message message, String[] args, Member member);
String getCommand();
String getDescription();
String getUsage();
CommandType getType();
default String getPermission() {
return "flarebot." + getCommand();
}
default EnumSet<Permission> getDiscordPermission() {
return null;
}
default String[] getAliases() {
return new String[]{};
}
default PerGuildPermissions getPermissions(MessageChannel chan) {
return FlareBot.getInstance().getPermissions(chan);
}
default boolean isDefaultPermission() {
return (getPermission() != null && getType() != CommandType.HIDDEN && getType() != CommandType.MODERATION);
}
default boolean deleteMessage() {
return true;
}
default char getPrefix(Guild guild) {
return FlareBot.getPrefix(guild.getId());
}
}
|
Use sys.platform to look at the current platform
Avoids a uname system call
|
import sys, os
def is_running_on_tingbot():
"""
Return True if running as a tingbot.
"""
# TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps.
return 'TB_RUN_ON_LCD' in os.environ
def no_op(*args, **kwargs):
pass
def no_op_returning(return_value):
def inner(*args, **kwargs):
return return_value
return inner
# set fallback functions (some of these will be replaced by the real versions below)
set_backlight = no_op
mouse_attached = no_op_returning(True)
keyboard_attached = no_op_returning(True)
joystick_attached = no_op_returning(False)
get_wifi_cell = no_op_returning(None)
if sys.platform == 'darwin':
from osx import fixup_env, create_main_surface, register_button_callback
elif is_running_on_tingbot():
from tingbot import (fixup_env, create_main_surface, register_button_callback,
set_backlight, mouse_attached, keyboard_attached, joystick_attached,
get_wifi_cell)
else:
from sdl_wrapper import fixup_env, create_main_surface, register_button_callback
|
import platform, os
def is_running_on_tingbot():
"""
Return True if running as a tingbot.
"""
# TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps.
return 'TB_RUN_ON_LCD' in os.environ
def no_op(*args, **kwargs):
pass
def no_op_returning(return_value):
def inner(*args, **kwargs):
return return_value
return inner
# set fallback functions (some of these will be replaced by the real versions below)
set_backlight = no_op
mouse_attached = no_op_returning(True)
keyboard_attached = no_op_returning(True)
joystick_attached = no_op_returning(False)
get_wifi_cell = no_op_returning(None)
if platform.system() == 'Darwin':
from osx import fixup_env, create_main_surface, register_button_callback
elif is_running_on_tingbot():
from tingbot import (fixup_env, create_main_surface, register_button_callback,
set_backlight, mouse_attached, keyboard_attached, joystick_attached,
get_wifi_cell)
else:
from sdl_wrapper import fixup_env, create_main_surface, register_button_callback
|
Use communicate so process out does not deadlock
|
from celery import task
import os
import sys
import subprocess
@task()
def build(build, giturl, branch):
# Use subprocess to execute a build, update the db with results
local = os.path.dirname(sys.argv[0])
buildpack = os.path.join(local, 'bin/build_package')
deployfile = build.project.deploy_file
print "Executing build %s %s" % (giturl, branch)
args = [buildpack, '--branch', branch]
if build.project.deploy_file:
args.extend(['--deploy-file', build.project.deploy_file])
if build.project.release_stream:
args.extend(['--push', build.project.release_stream.push_command])
args.append(giturl)
builder = subprocess.Popen(args,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=local)
stdoutdata, stderrdata = builder.communicate()
build.log = stdoutdata
if builder.returncode != 0:
build.state = 2
else:
build.state = 1
build.save()
|
from celery import task
import os
import sys
import subprocess
@task()
def build(build, giturl, branch):
# Use subprocess to execute a build, update the db with results
local = os.path.dirname(sys.argv[0])
buildpack = os.path.join(local, 'bin/build_package')
deployfile = build.project.deploy_file
print "Executing build %s %s" % (giturl, branch)
args = [buildpack, '--branch', branch]
if build.project.deploy_file:
args.extend(['--deploy-file', build.project.deploy_file])
if build.project.release_stream:
args.extend(['--push', build.project.release_stream.push_command])
args.append(giturl)
builder = subprocess.Popen(args,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=local)
builder.wait()
build.log = builder.stdout.read()
if builder.returncode != 0:
build.state = 2
else:
build.state = 1
build.save()
|
Use python script to send json
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
send_data = {}
send_data['category'] = 'fun'
send_data['bla'] = 'blub'
send_j_data = json.dumps(send_data)
print
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall((len(send_j_data)).to_bytes(2, byteorder='big'))
s.sendall(send_j_data.encode())
# data = s.recv(1024)
# print('Received', repr(data))
# j = json.loads(data)
# print(json.dumps(j, indent=4, sort_keys=True))
|
# A simpel test script for netfortune server
# Copyright © 2017 Christian Rapp
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Echo client program
import socket
import json
HOST = '127.0.0.1' # The remote host
PORT = 13 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
# s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
j = json.loads(data)
print(json.dumps(j, indent=4, sort_keys=True))
|
Move tests into new Given class
|
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
|
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
|
kwf/check: Remove check for db connection
This url is used to check if the webserver is up and running (and can be used by load balancer).
When the database is down that's a different issue the webserver is not responsible for, and
can not be solved by restarting the webserver or something.
Improves OpenShift restarting behaviour
|
<?php
class Kwf_Util_Check
{
public static function dispatch()
{
$ok = true;
$msg = '';
if (file_exists('instance_startup')) {
//can be used while starting up autoscaling instances
$ok = false;
$msg .= 'instance startup in progress';
}
if (!$ok) {
header("HTTP/1.0 500 Error");
echo "<h1>Check failed</h1>";
echo $msg;
} else {
echo "ok";
}
exit;
}
}
|
<?php
class Kwf_Util_Check
{
public static function dispatch()
{
$ok = true;
$msg = '';
if (Kwf_Setup::hasDb()) {
$date = Kwf_Registry::get('db')->query("SELECT NOW()")->fetchColumn();
if (!$date) {
$ok = false;
$msg .= 'mysql connection failed';
}
}
if (file_exists('instance_startup')) {
//can be used while starting up autoscaling instances
$ok = false;
$msg .= 'instance startup in progress';
}
if (!$ok) {
header("HTTP/1.0 500 Error");
echo "<h1>Check failed</h1>";
echo $msg;
} else {
echo "ok";
}
exit;
}
}
|
[BC] Use the value as the version number in the version resolvers
|
<?php
/*
* This file is part of the Api package.
*
* (c) EXSyst
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace EXSyst\Component\Api\Version\Resolver;
use Composer\Semver\Semver;
use EXSyst\Component\Api\Version\VersionResolverInterface;
abstract class AbstractVersionResolver implements VersionResolverInterface
{
/**
* @var array
*/
protected $versions;
/**
* @param array $versions ordered
*/
public function __construct(array $versions)
{
$this->versions = $versions;
}
/**
* @param string $constraint
*
* @return scalar|false
*/
protected function satisfiedBy($constraint)
{
foreach ($this->versions as $version) {
if (Semver::satisfies($version, $constraint)) {
return $version;
}
}
return false;
}
}
|
<?php
/*
* This file is part of the Api package.
*
* (c) EXSyst
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace EXSyst\Component\Api\Version\Resolver;
use Composer\Semver\Semver;
use EXSyst\Component\Api\Version\VersionResolverInterface;
abstract class AbstractVersionResolver implements VersionResolverInterface
{
/**
* @var array
*/
protected $versions;
/**
* @param array $versions ordered
*/
public function __construct(array $versions)
{
$this->versions = $versions;
}
/**
* @param string $constraint
*
* @return scalar|false
*/
protected function satisfiedBy($constraint)
{
foreach ($this->versions as $version => $options) {
if (Semver::satisfies($version, $constraint)) {
return $version;
}
}
return false;
}
}
|
Remove mapPkg from settings collections.
|
import { isDev, getDevelopmentPackages } from 'worona-deps';
import { map } from 'lodash';
import { combineReducers } from 'redux';
import * as deps from '../deps';
const env = isDev ? 'dev' : 'prod';
const mapPkg = pkg => ({ ...pkg, main: pkg.cdn && pkg.cdn.dashboard[env].main.file });
const createSetting = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
const createPkg = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection, mapPkg),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
const devPkgs = map(getDevelopmentPackages(), pkg => pkg.woronaInfo);
export const devPackages = () => devPkgs;
export const collections = () => combineReducers({
live: createSetting('settings-live'),
preview: createSetting('settings-preview'),
packages: createPkg('packages'),
devPackages: combineReducers({ collection: devPackages }),
});
export default () => combineReducers({
collections: collections(),
});
|
import { isDev, getDevelopmentPackages } from 'worona-deps';
import { map } from 'lodash';
import { combineReducers } from 'redux';
import * as deps from '../deps';
const env = isDev ? 'dev' : 'prod';
const mapPkg = pkg => ({ ...pkg, main: pkg.cdn && pkg.cdn.dashboard[env].main.file });
const create = collection => combineReducers({
collection: deps.reducerCreators.collectionCreator(collection, mapPkg),
isReady: deps.reducerCreators.isReadyCreator(collection),
});
const devPkgs = map(getDevelopmentPackages(), pkg => pkg.woronaInfo);
export const devPackages = () => devPkgs;
export const collections = () => combineReducers({
live: create('settings-live'),
preview: create('settings-preview'),
packages: create('packages'),
devPackages: combineReducers({ collection: devPackages }),
});
export default () => combineReducers({
collections: collections(),
});
|
Use lower case import path for logrus
Due to some import problems the author of logrus encourages users to
use all lower case paths. Cf. a [comment on the respective issue on the
logrus
repository](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276)
|
package ginerus
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
func Ginerus() gin.HandlerFunc {
return GinerusWithLogger(logrus.StandardLogger())
}
func GinerusWithLogger(logger *logrus.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
c.Next()
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
comment := c.Errors.String()
userAgent := c.Request.UserAgent()
timeFormatted := end.Format("2006-01-02 15:04:05")
msg := fmt.Sprintf(
"%s %s \"%s %s\" %d %s %s",
clientIP,
timeFormatted,
method,
path,
statusCode,
latency,
userAgent,
)
logger.WithFields(logrus.Fields{
"time": timeFormatted,
"method": method,
"path": path,
"latency": latency,
"ip": clientIP,
"comment": comment,
"status": statusCode,
"user-agent": userAgent,
}).Info(msg)
}
}
|
package ginerus
import (
"fmt"
"time"
"github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
)
func Ginerus() gin.HandlerFunc {
return GinerusWithLogger(logrus.StandardLogger())
}
func GinerusWithLogger(logger *logrus.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
c.Next()
end := time.Now()
latency := end.Sub(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
comment := c.Errors.String()
userAgent := c.Request.UserAgent()
timeFormatted := end.Format("2006-01-02 15:04:05")
msg := fmt.Sprintf(
"%s %s \"%s %s\" %d %s %s",
clientIP,
timeFormatted,
method,
path,
statusCode,
latency,
userAgent,
)
logger.WithFields(logrus.Fields{
"time": timeFormatted,
"method": method,
"path": path,
"latency": latency,
"ip": clientIP,
"comment": comment,
"status": statusCode,
"user-agent": userAgent,
}).Info(msg)
}
}
|
Add test for level being omitted on Routes operation.
Added testing for the default case.
|
/*
* Copyright 2013-2015 the original author or authors.
*
* 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 org.cloudfoundry.operations;
import org.junit.Test;
import static org.cloudfoundry.operations.ValidationResult.Status.VALID;
import static org.junit.Assert.assertEquals;
public final class ListRoutesRequestTest {
@Test
public void isValid() {
ValidationResult result = ListRoutesRequest.builder()
.level(ListRoutesRequest.Level.Organization)
.build()
.isValid();
assertEquals(VALID, result.getStatus());
}
@Test
public void isValidNoLevel() {
ValidationResult result = ListRoutesRequest.builder()
.build()
.isValid();
assertEquals(VALID, result.getStatus());
}
}
|
/*
* Copyright 2013-2015 the original author or authors.
*
* 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 org.cloudfoundry.operations;
import org.junit.Test;
import static org.cloudfoundry.operations.ValidationResult.Status.VALID;
import static org.junit.Assert.assertEquals;
public final class ListRoutesRequestTest {
@Test
public void isValid() {
ValidationResult result = ListRoutesRequest.builder()
.level(ListRoutesRequest.Level.Organization)
.build()
.isValid();
assertEquals(VALID, result.getStatus());
}
}
|
Replace {T} with a unicode tap symbol approximation and replace {S} with a unicode snowflake, how exiting. More symbol replacements to follow
|
import urllib
from util import hook, http
def card_search(query):
base_url = "https://api.deckbrew.com"
name = urllib.quote_plus(query)
search_url = base_url + "/mtg/cards?name=" + name
return http.get_json(search_url)
@hook.command
def mtg(inp, say=None):
'''.mtg <name> - Searches for Magic the Gathering card given <name>
'''
try:
card = card_search(inp)[0]
except IndexError:
return "Card not found."
for valid_edition in range(len(card["editions"])):
if card["editions"][valid_edition]["multiverse_id"] != 0 :
break
results = {
"name": card["name"],
"types": ", ".join(t.capitalize() for t in card["types"]),
"cost": card["cost"].replace('{','').replace('}',''),
"text": card["text"].replace('\n',' ').replace('{T}',u'\u27F3').replace('{S}',u'\u2744'),
"multiverse_id": card["editions"][valid_edition]["multiverse_id"],
}
return u"{name} - {cost} - {types} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results)
if __name__ == "__main__":
print card_search("Black Lotus")
print mtg("Black Lotus")
|
import urllib
from util import hook, http
def card_search(query):
base_url = "https://api.deckbrew.com"
name = urllib.quote_plus(query)
search_url = base_url + "/mtg/cards?name=" + name
return http.get_json(search_url)
@hook.command
def mtg(inp, say=None):
'''.mtg <name> - Searches for Magic the Gathering card given <name>
'''
try:
card = card_search(inp)[0]
except IndexError:
return "Card not found."
for valid_edition in range(len(card["editions"])):
if card["editions"][valid_edition]["multiverse_id"] != 0 :
break
else:
continue
results = {
"name": card["name"],
"types": ", ".join(t.capitalize() for t in card["types"]),
"cost": card["cost"].replace('{','').replace('}',''),
"text": card["text"].replace('\n',' '),
"multiverse_id": card["editions"][valid_edition]["multiverse_id"],
}
return u"{name} - {types} - {cost} | {text} | http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid={multiverse_id}".format(**results)
if __name__ == "__main__":
print card_search("Black Lotus")
print mtg("Black Lotus")
|
Use class_exists to correctly check for pre-existing header type
|
<?php
namespace Versionable\Prospect\Header;
use Versionable\Common\Collection\Map;
class Collection extends Map implements CollectionInterface
{
public function add(HeaderInterface $header)
{
$this->put($header->getName(), $header);
}
public function parse($name, $value)
{
$class_name = 'Versionable\Prospect\Header\\' . \str_replace(' ' , '', \ucwords(\str_replace('-', ' ', $name)));
if (class_exists($class_name)) {
$header = new $class_name($value);
} else {
$header = new Custom($name, $value);
}
$this->add($header);
}
public function toString()
{
$data = '';
foreach ($this as $header)
{
$data .= $header->toString() . "\r\n";
}
return $data;
}
}
|
<?php
namespace Versionable\Prospect\Header;
use Versionable\Common\Collection\Map;
class Collection extends Map implements CollectionInterface
{
public function add(HeaderInterface $header)
{
$this->put($header->getName(), $header);
}
public function parse($name, $value)
{
$class_name = 'Versionable\Prospect\Header\\' . \str_replace(' ' , '', \ucwords(\str_replace('-', ' ', $name)));
try
{
$header = new $class_name($value);
}
catch(\RuntimeException $e)
{
$header = new Custom($name, $value);
}
$this->add($header);
}
public function toString()
{
$data = '';
foreach ($this as $header)
{
$data .= $header->toString() . "\r\n";
}
return $data;
}
}
|
Make note of the need to change the plugin's port when changing the server's
|
#! /usr/bin/env node
const path = require('path');
const fs = require('fs');
const program = require('commander');
const pkg = require('../package.json');
const server = require('../lib/server.js');
function failWithHelp(msg) {
console.log(msg);
program.help();
process.exit(1);
}
program
.version(pkg.version)
.arguments('<dir>')
.option('-p, --port <port>', 'the port to run the server off of. defaults ' +
'to 8080. you also need to change the port that the plugin uses.', 8080)
.action(dir => {
const fullPath = path.resolve(dir);
if (fs.existsSync(fullPath)) {
server(fullPath, program.port);
} else {
failWithHelp(`Could not find a directory at ${fullPath}`)
}
});
program.parse(process.argv);
if (!program.args[0])
failWithHelp('The directory argument is required.');
|
#! /usr/bin/env node
const path = require('path');
const fs = require('fs');
const program = require('commander');
const pkg = require('../package.json');
const server = require('../lib/server.js');
function failWithHelp(msg) {
console.log(msg);
program.help();
process.exit(1);
}
program
.version(pkg.version)
.arguments('<dir>')
.option('-p, --port <port>', 'the port to run the server off of. defaults to 8080.', 8080)
.action(dir => {
const fullPath = path.resolve(dir);
if (fs.existsSync(fullPath)) {
server(fullPath, program.port);
} else {
failWithHelp(`Could not find a directory at ${fullPath}`)
}
});
program.parse(process.argv);
if (!program.args[0])
failWithHelp('The directory argument is required.');
|
Add backward compatibility with old iOS plugin
|
var sms = {
send: function(phone, message, method, successCallback, failureCallback) {
// iOS plugin used to accept comma-separated phone numbers, keep the
// compatibility
if (typeof phone === 'string' && phone.indexOf(',') !== -1) {
phone = phone.split(',');
}
if (Object.prototype.toString.call(phone) !== '[object Array]') {
phone = [phone];
}
cordova.exec(
successCallback,
failureCallback,
'Sms',
'send',
[phone, message, method]
);
}
};
module.exports = sms;
/*SMSComposer.prototype.showSMSComposerWithCB = function(cbFunction,toRecipients,body) {
this.resultCallback = cbFunction;
this.showSms.apply(this,[toRecipients,body]);
};
SMSComposer.prototype._didFinishWithResult = function(res) {
this.resultCallback(res);
};*/
|
var sms = {
send: function(phone, message, method, successCallback, failureCallback) {
if (Object.prototype.toString.call(phone) !== '[object Array]') {
phone = [phone];
}
cordova.exec(
successCallback,
failureCallback,
'Sms',
'send',
[phone, message, method]
);
}
};
module.exports = sms;
/*SMSComposer.prototype.showSMSComposerWithCB = function(cbFunction,toRecipients,body) {
this.resultCallback = cbFunction;
this.showSms.apply(this,[toRecipients,body]);
};
SMSComposer.prototype._didFinishWithResult = function(res) {
this.resultCallback(res);
};*/
|
Change an instance of J2EE -> Jakarta EE
|
/**
* Copyright © 2012-2019 Jesse Gallagher
*
* 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 darwino;
import java.util.List;
import com.darwino.commons.platform.beans.ManagedBeansExtension;
import com.darwino.commons.platform.properties.PropertiesExtension;
import com.darwino.j2ee.platform.DefaultWebBeanExtension;
import com.darwino.j2ee.platform.DefaultWebPropertiesExtension;
/**
* J2EE Plugin for registering the services.
*/
public class AppPlugin extends AppBasePlugin {
public AppPlugin() {
super("frostillic.us Jakarta EE Application"); //$NON-NLS-1$
}
@Override
public void findExtensions(Class<?> serviceClass, List<Object> extensions) {
if(serviceClass==ManagedBeansExtension.class) {
extensions.add(new DefaultWebBeanExtension());
} else if(serviceClass==PropertiesExtension.class) {
extensions.add(new DefaultWebPropertiesExtension());
}
}
}
|
/**
* Copyright © 2012-2019 Jesse Gallagher
*
* 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 darwino;
import java.util.List;
import com.darwino.commons.platform.beans.ManagedBeansExtension;
import com.darwino.commons.platform.properties.PropertiesExtension;
import com.darwino.j2ee.platform.DefaultWebBeanExtension;
import com.darwino.j2ee.platform.DefaultWebPropertiesExtension;
/**
* J2EE Plugin for registering the services.
*/
public class AppPlugin extends AppBasePlugin {
public AppPlugin() {
super("frostillic.us J2EE Application"); //$NON-NLS-1$
}
@Override
public void findExtensions(Class<?> serviceClass, List<Object> extensions) {
if(serviceClass==ManagedBeansExtension.class) {
extensions.add(new DefaultWebBeanExtension());
} else if(serviceClass==PropertiesExtension.class) {
extensions.add(new DefaultWebPropertiesExtension());
}
}
}
|
Fix only JSON stringify objects, not strings
|
#!/usr/bin/env node
var tool = require('./')
var through = require('through2')
var split = require('split')
var minimist = require('minimist')
var argv = minimist(process.argv.slice(2))
var method = argv._[0]
var params = argv._.slice(1)
var operation = tool[method].apply(this, params)
process.stdin.setEncoding('utf8');
if (!process.stdin.isTTY) {
process.stdin
.pipe(split())
.pipe(JSONparse())
.pipe(operation)
.on('data', function(data) {
if (typeof data === 'object') {
data = JSON.stringify(data)
}
console.log(data)
})
.on('error', console.log)
}
function JSONparse() {
var stream = through.obj(transform)
return stream
function transform(obj, enc, next) {
try { obj = JSON.parse(obj) }
catch(e) {}
if (obj !== '') { this.push(obj) }
next()
}
}
|
#!/usr/bin/env node
var tool = require('./')
var through = require('through2')
var split = require('split')
var minimist = require('minimist')
var argv = minimist(process.argv.slice(2))
var method = argv._[0]
var params = argv._.slice(1)
var operation = tool[method].apply(this, params)
process.stdin.setEncoding('utf8');
if (!process.stdin.isTTY) {
process.stdin
.pipe(split())
.pipe(JSONparse())
.pipe(operation)
.on('data', function(data) {
console.log(JSON.stringify(data))
})
.on('error', console.log)
}
function JSONparse() {
var stream = through.obj(transform)
return stream
function transform(obj, enc, next) {
try { obj = JSON.parse(obj) }
catch(e) {}
if (obj !== '') { this.push(obj) }
next()
}
}
|
Fix stupid mistake in DI module.
|
/*
* Copyright (c) 2006-2015 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.nickkeep;
import com.dmdirc.ClientModule;
import dagger.Module;
/**
* Dagger injection module for the Nick Keep plugin
*/
@Module(injects = NickKeepManager.class, addsTo = ClientModule.class)
public class NickKeepModule {}
|
/*
* Copyright (c) 2006-2015 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.nickkeep;
import com.dmdirc.ClientModule;
import dagger.Module;
/**
* Dagger injection module for the Nick Keep plugin
*/
@Module(injects = NickKeepModule.class, addsTo = ClientModule.class)
public class NickKeepModule {}
|
Add GH method for retrieving maintainerd config file.
|
const fetch = require("node-fetch");
const qs = require("qs");
const { load } = require("js-yaml");
const { getInstallationToken } = require("./installation-token");
module.exports.GitHub = class GitHub {
constructor (installationId) {
this.installationId = installationId;
}
get (urlSegment) {
return this.fetch("GET", urlSegment);
}
post (urlSegment, body) {
return this.fetch("POST", urlSegment, body);
}
async fetch (method, urlSegment, body) {
const installationToken = await getInstallationToken(this.installationId);
const headers = {
"User-Agent": "divmain/semver-as-a-service",
"Accept": "application/vnd.github.machine-man-preview+json",
"Authorization": `token ${installationToken}`
};
const opts = {
method,
headers
};
if (method === "POST") {
headers["Content-Type"] = "application/json";
opts.body = body;
}
return fetch(`https://api.github.com${urlSegment}`, opts);
}
getConfig (repoPath) {
return this.get(`/repos/${repoPath}/contents/.maintainerd`)
.then(response => response.json())
.then(json => Buffer.from(json.content, "base64").toString())
.then(yamlString => load(yamlString, "utf8"));
}
}
|
const fetch = require("node-fetch");
const qs = require("qs");
const { load } = require("js-yaml");
const { getInstallationToken } = require("./installation-token");
module.exports.GitHub = class GitHub {
constructor (installationId) {
this.installationId = installationId;
}
get (urlSegment) {
return this.fetch("GET", urlSegment);
}
post (urlSegment, body) {
return this.fetch("POST", urlSegment, body);
}
async fetch (method, urlSegment, body) {
const installationToken = await getInstallationToken(this.installationId);
const headers = {
"User-Agent": "divmain/semver-as-a-service",
"Accept": "application/vnd.github.machine-man-preview+json",
"Authorization": `token ${installationToken}`
};
const opts = {
method,
headers
};
if (method === "POST") {
headers["Content-Type"] = "application/json";
opts.body = body;
}
return fetch(`https://api.github.com${urlSegment}`, opts);
}
}
|
Remove 'thunk' jargon from PythonExecutor
|
import itertools
from functools import partial
import math
from typing import Callable, Iterable
from rechunker.types import CopySpec, StagedCopySpec, Executor
# PythonExecutor represents delayed execution tasks as functions that require
# no arguments.
Task = Callable[[], None]
class PythonExecutor(Executor[Task]):
"""An execution engine based on Python loops.
Supports copying between any arrays that implement ``__getitem__`` and
``__setitem__`` for tuples of ``slice`` objects.
Execution plans for PythonExecutor are functions that accept no arguments.
"""
def prepare_plan(self, specs: Iterable[StagedCopySpec]) -> Task:
tasks = []
for staged_copy_spec in specs:
for copy_spec in staged_copy_spec.stages:
tasks.append(partial(_direct_copy_array, copy_spec))
return partial(_execute_all, tasks)
def execute_plan(self, plan: Task):
plan()
def _direct_copy_array(copy_spec: CopySpec) -> None:
"""Direct copy between zarr arrays."""
source_array, target_array, chunks = copy_spec
shape = source_array.shape
ranges = [range(math.ceil(s / c)) for s, c in zip(shape, chunks)]
for indices in itertools.product(*ranges):
key = tuple(slice(c * i, c * (i + 1)) for i, c in zip(indices, chunks))
target_array[key] = source_array[key]
def _execute_all(tasks: Iterable[Task]) -> None:
for task in tasks:
task()
|
import itertools
from functools import partial
import math
from typing import Any, Callable, Iterable
from rechunker.types import CopySpec, StagedCopySpec, Executor
Thunk = Callable[[], None]
class PythonExecutor(Executor[Thunk]):
"""An execution engine based on Python loops.
Supports copying between any arrays that implement ``__getitem__`` and
``__setitem__`` for tuples of ``slice`` objects.
Execution plans for PythonExecutor are functions that accept no arguments.
"""
def prepare_plan(self, specs: Iterable[StagedCopySpec]) -> Thunk:
tasks = []
for staged_copy_spec in specs:
for copy_spec in staged_copy_spec.stages:
tasks.append(partial(_direct_copy_array, copy_spec))
return partial(_execute_all, tasks)
def execute_plan(self, plan: Thunk):
plan()
def _direct_copy_array(copy_spec: CopySpec) -> None:
"""Direct copy between zarr arrays."""
source_array, target_array, chunks = copy_spec
shape = source_array.shape
ranges = [range(math.ceil(s / c)) for s, c in zip(shape, chunks)]
for indices in itertools.product(*ranges):
key = tuple(slice(c * i, c * (i + 1)) for i, c in zip(indices, chunks))
target_array[key] = source_array[key]
def _execute_all(tasks: Iterable[Callable[[], Any]]) -> None:
for task in tasks:
task()
|
Disable keyboard shortcut if target element is an input element.
|
define(function (require) {
var $ = require("jquery");
var documentKeyboardHandler = require("utilities/documentKeyboardHandler");
var keyboardShortcuts = function (eventBus) {
documentKeyboardHandler(function (event, isDown, isRepeated) {
// spacebar
if (isDown && event.which === 32) {
if (!isRepeated)
eventBus.trigger("togglePlayback");
return false;
}
// shift
if (event.which === 16) {
if (!isRepeated) {
eventBus.trigger("setGridViewState", {
state: isDown ? "play" : "addOrRemove"
});
}
return false;
}
// number keys 1 to 9
if (isDown && event.which >= 49 && event.which <= 57) {
if ($(event.target).is("input"))
return;
if (!isRepeated)
eventBus.trigger("selectTrack", {
trackIndex: event.which - 49
});
return false;
}
});
};
return keyboardShortcuts;
});
|
define(function (require) {
var documentKeyboardHandler = require("utilities/documentKeyboardHandler");
var keyboardShortcuts = function (eventBus) {
documentKeyboardHandler(function (event, isDown, isRepeated) {
// spacebar
if (isDown && event.which === 32) {
if (!isRepeated)
eventBus.trigger("togglePlayback");
return false;
}
// shift
if (event.which === 16) {
if (!isRepeated) {
eventBus.trigger("setGridViewState", {
state: isDown ? "play" : "addOrRemove"
});
}
return false;
}
// number keys 1 to 9
if (isDown && event.which >= 49 && event.which <= 57) {
if (!isRepeated)
eventBus.trigger("selectTrack", {
trackIndex: event.which - 49
});
return false;
}
});
};
return keyboardShortcuts;
});
|
Set behavior prop before added to window
Otherwise there's a noticeable flicker before bottom sheet appears
|
package com.navigation.reactnative;
import android.content.Context;
import android.view.ViewGroup;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.facebook.react.uimanager.PixelUtil;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
public class BottomSheetView extends ViewGroup {
public BottomSheetView(Context context) {
super(context);
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
BottomSheetBehavior bottomSheetBehavior = new BottomSheetBehavior();
bottomSheetBehavior.setPeekHeight((int) PixelUtil.toPixelFromDIP(200));
params.setBehavior(bottomSheetBehavior);
setLayoutParams(params);
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
}
}
|
package com.navigation.reactnative;
import android.content.Context;
import android.view.ViewGroup;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.facebook.react.uimanager.PixelUtil;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
public class BottomSheetView extends ViewGroup {
public BottomSheetView(Context context) {
super(context);
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setBehavior(new BottomSheetBehavior());
setLayoutParams(params);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
BottomSheetBehavior.from(this).setPeekHeight((int) PixelUtil.toPixelFromDIP(200));
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
}
}
|
Fix Map unexepected constructor argument by removing new keyword
|
// @flow
import { Map, Record } from 'immutable';
export type PlayerShape = {
username: string,
displayName: string,
index: number,
ready: boolean
};
export type PlayerType = Record<PlayerShape>;
const PlayerRecord: PlayerType = Record({
username: null,
displayName: null,
index: 0,
ready: false,
});
// $FlowFixMe
export class Player extends PlayerRecord {}
export type PlayersShape = {
all: Map<string, PlayerType>,
current: string
};
export type PlayersType = Record<PlayersShape>;
const PlayersRecord: PlayersType = Record({
all: Map(),
current: '',
});
// $FlowFixMe
export default class PlayerState extends PlayersRecord {
addPlayer(p: PlayerShape) {
const player: Player = new Player(p);
const playerMap = Map({ [player.username]: player });
return this.addPlayers(playerMap).set('current', player.username);
}
addPlayers(p: Map<string, PlayerShape>) {
const players: Map<string, PlayerShape> = Map(p);
return this.mergeIn(['all'], players.map((player: PlayerShape): Player => new Player(player)));
}
}
|
// @flow
import { Map, Record } from 'immutable';
export type PlayerShape = {
username: string,
displayName: string,
index: number,
ready: boolean
};
export type PlayerType = Record<PlayerShape>;
const PlayerRecord: PlayerType = Record({
username: null,
displayName: null,
index: 0,
ready: false,
});
// $FlowFixMe
export class Player extends PlayerRecord {}
export type PlayersShape = {
all: Map<string, PlayerType>,
current: string
};
export type PlayersType = Record<PlayersShape>;
const PlayersRecord: PlayersType = Record({
all: new Map(),
current: '',
});
// $FlowFixMe
export default class PlayerState extends PlayersRecord {
addPlayer(p: PlayerShape) {
const player: Player = new Player(p);
const playerMap = new Map(({ [player.username]: player }: { [key: string]: Player }));
return this.addPlayers(playerMap).set('current', player.username);
}
addPlayers(p: Map<string, PlayerShape>) {
const players: Map<string, PlayerShape> = new Map(p);
return this.mergeIn(['all'], players.map((player: PlayerShape): Player => new Player(player)));
}
}
|
Include domains which have last_modified equal to None
|
from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domain.get_db(), [
domain['id']
for domain in Domain.view(
"domain/domains",
reduce=False,
include_docs=False
)
])
return filter(lambda x: 'last_modified' not in x or not x['last_modified'], docs)
def handle(self, *args, **options):
for domain_doc in self._get_domains_without_last_modified_date():
print "Updating domain {}".format(domain_doc['name'])
domain = Domain.wrap(domain_doc)
domain.save()
|
from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from dimagi.utils.couch.database import iter_docs
class Command(BaseCommand):
def _get_domains_without_last_modified_date(self):
docs = iter_docs(Domain.get_db(), [
domain['id']
for domain in Domain.view(
"domain/domains",
reduce=False,
include_docs=False
)
])
return filter(lambda x: 'last_modified' not in x, docs)
def handle(self, *args, **options):
for domain_doc in self._get_domains_without_last_modified_date():
print "Updating domain {}".format(domain_doc['name'])
domain = Domain.wrap(domain_doc)
domain.save()
|
Fix for all members in the news page.
|
"""The manager for managing team."""
from apps.managers.score_mgr import score_mgr
from apps.managers.team_mgr.models import Team
def team_members(team):
"""Get the team members."""
return team.profile_set.all()
def team_points_leader(round_name="Overall"):
"""Returns the team points leader (the first place) across all groups, as a Team object."""
team_id = score_mgr.team_points_leader(round_name=round_name)
if team_id:
return Team.objects.get(id=team_id)
else:
return Team.objects.all()[0]
def team_points_leaders(num_results=10, round_name="Overall"):
"""Returns the team points leaders across all groups, as a dictionary profile__team__name
and points.
"""
entry = score_mgr.team_points_leaders(num_results=num_results, round_name=round_name)
if entry:
return entry
else:
return Team.objects.all().extra(select={'profile__team__name': 'name', 'points': 0}).values(
'profile__team__name', 'points')[:num_results]
|
"""The manager for managing team."""
from apps.managers.score_mgr import score_mgr
from apps.managers.team_mgr.models import Team
def team_members(team):
"""Get the team members."""
return team.profile_set()
def team_points_leader(round_name="Overall"):
"""Returns the team points leader (the first place) across all groups, as a Team object."""
team_id = score_mgr.team_points_leader(round_name=round_name)
if team_id:
return Team.objects.get(id=team_id)
else:
return Team.objects.all()[0]
def team_points_leaders(num_results=10, round_name="Overall"):
"""Returns the team points leaders across all groups, as a dictionary profile__team__name
and points.
"""
entry = score_mgr.team_points_leaders(num_results=num_results, round_name=round_name)
if entry:
return entry
else:
return Team.objects.all().extra(select={'profile__team__name': 'name', 'points': 0}).values(
'profile__team__name', 'points')[:num_results]
|
Update with reference to global nav partial
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-vertical-align/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-vertical-align/tachyons-vertical-align.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_vertical-align.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/vertical-align/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/vertical-align/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-vertical-align/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-vertical-align/tachyons-vertical-align.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_vertical-align.css', 'utf8')
var template = fs.readFileSync('./templates/docs/vertical-align/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/typography/vertical-align/index.html', html)
|
Add a searchFilter field to ad resource
|
/*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.model.integration.auth;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ActiveDirectoryResource extends AbstractLdapResource {
@JsonProperty(value = "domain")
private String domain;
@JsonProperty(value = "searchFilter")
private String searchFilter;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getSearchFilter() {
return searchFilter;
}
public void setSearchFilter(String searchFilter) {
this.searchFilter = searchFilter;
}
@Override
public String toString() {
return "ActiveDirectoryResource{" + "domain='" + domain + '\'' + ", searchFilter='" + searchFilter + '\'' + '}';
}
}
|
/*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.model.integration.auth;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ActiveDirectoryResource extends AbstractLdapResource {
@JsonProperty(value = "domain")
private String domain;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
@Override
public String toString() {
return "ActiveDirectoryResource{" + "domain='" + domain + '\'' + '}';
}
}
|
Set article slug unique constraint
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug')->unique();
$table->string('description');
$table->string('keywords')->nullable();
$table->text('body');
$table->boolean('enabled')->default(true);
$table->integer('user_id')->unsigned()->index();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug');
$table->string('description');
$table->string('keywords')->nullable();
$table->text('body');
$table->boolean('enabled')->default(true);
$table->integer('user_id')->unsigned()->index();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
|
Add function for string compare ignoring case
|
package main
import (
"fmt"
"strings"
)
var defaultFuncs = map[string]interface{}{
"str": String,
"dec": Decimal,
"eq": Equal,
"eq_igncase": EqualIgnoreCase,
}
func String(v interface{}) string {
switch x := v.(type) {
case string:
x = strings.Replace(x, `\`, `\\`, -1)
x = strings.Replace(x, `"`, `\"`, -1)
return fmt.Sprintf("\"%s\"", x)
case float64:
return fmt.Sprintf("\"%f\"", x)
}
return ""
}
func Decimal(dec int, v interface{}) string {
if f, ok := v.(float64); ok {
fmtstr := fmt.Sprintf("%%.%df", dec)
return fmt.Sprintf(fmtstr, f)
}
return ""
}
func Equal(v1, v2 interface{}) interface{} {
if v1 == v2 {
return v1
}
return nil
}
func EqualIgnoreCase(s1, s2 string) string {
if strings.ToLower(s1) == strings.ToLower(s2) {
return s1
}
return ""
}
|
package main
import (
"fmt"
"strings"
)
var defaultFuncs = map[string]interface{}{
"str": String,
"dec": Decimal,
"eq": Equal,
}
func String(v interface{}) string {
switch x := v.(type) {
case string:
x = strings.Replace(x, `\`, `\\`, -1)
x = strings.Replace(x, `"`, `\"`, -1)
return fmt.Sprintf("\"%s\"", x)
case float64:
return fmt.Sprintf("\"%f\"", x)
}
return ""
}
func Decimal(dec int, v interface{}) string {
if f, ok := v.(float64); ok {
fmtstr := fmt.Sprintf("%%.%df", dec)
return fmt.Sprintf(fmtstr, f)
}
return ""
}
func Equal(v1, v2 interface{}) interface{} {
if v1 == v2 {
return v1
}
return nil
}
|
Add Framework::Pytest to list of classifiers
|
from setuptools import setup
setup(
name="pytest-cpp",
version='0.4',
packages=['pytest_cpp'],
entry_points={
'pytest11': ['cpp = pytest_cpp.plugin'],
},
install_requires=['pytest', 'colorama'],
# metadata for upload to PyPI
author="Bruno Oliveira",
author_email="nicoddemus@gmail.com",
description="Use pytest's runner to discover and execute C++ tests",
long_description=open('README.rst').read(),
license="MIT",
keywords="pytest test unittest",
url="http://github.com/pytest-dev/pytest-cpp",
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Pytest',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: C++',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
],
)
|
from setuptools import setup
setup(
name="pytest-cpp",
version='0.4',
packages=['pytest_cpp'],
entry_points={
'pytest11': ['cpp = pytest_cpp.plugin'],
},
install_requires=['pytest', 'colorama'],
# metadata for upload to PyPI
author="Bruno Oliveira",
author_email="nicoddemus@gmail.com",
description="Use pytest's runner to discover and execute C++ tests",
long_description=open('README.rst').read(),
license="MIT",
keywords="pytest test unittest",
url="http://github.com/pytest-dev/pytest-cpp",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: C++',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
],
)
|
Update error notification on 404 when fetching JSON feed
|
import {fetchJSONFeed as fetchJSONFeedAJAX} from 'src/status/apis'
import {errorThrown} from 'shared/actions/errors'
import * as actionTypes from 'src/status/constants/actionTypes'
import {HTTP_NOT_FOUND} from 'shared/constants'
const fetchJSONFeedRequested = () => ({
type: actionTypes.FETCH_JSON_FEED_REQUESTED,
})
const fetchJSONFeedCompleted = data => ({
type: actionTypes.FETCH_JSON_FEED_COMPLETED,
payload: {data},
})
const fetchJSONFeedFailed = () => ({
type: actionTypes.FETCH_JSON_FEED_FAILED,
})
export const fetchJSONFeedAsync = url => async dispatch => {
dispatch(fetchJSONFeedRequested())
try {
const {data} = await fetchJSONFeedAJAX(url)
dispatch(fetchJSONFeedCompleted(data))
} catch (error) {
console.error(error)
dispatch(fetchJSONFeedFailed())
if (error.status === HTTP_NOT_FOUND) {
dispatch(
errorThrown(
error,
`Failed to fetch News Feed. JSON Feed at '${url}' returned 404 (Not Found)`
)
)
} else {
dispatch(errorThrown(error, 'Failed to fetch NewsFeed'))
}
}
}
|
import {fetchJSONFeed as fetchJSONFeedAJAX} from 'src/status/apis'
import {errorThrown} from 'shared/actions/errors'
import * as actionTypes from 'src/status/constants/actionTypes'
const fetchJSONFeedRequested = () => ({
type: actionTypes.FETCH_JSON_FEED_REQUESTED,
})
const fetchJSONFeedCompleted = data => ({
type: actionTypes.FETCH_JSON_FEED_COMPLETED,
payload: {data},
})
const fetchJSONFeedFailed = () => ({
type: actionTypes.FETCH_JSON_FEED_FAILED,
})
export const fetchJSONFeedAsync = url => async dispatch => {
dispatch(fetchJSONFeedRequested())
try {
const {data} = await fetchJSONFeedAJAX(url)
dispatch(fetchJSONFeedCompleted(data))
} catch (error) {
console.error(error)
dispatch(fetchJSONFeedFailed())
dispatch(
errorThrown(error, `Failed to fetch NewsFeed: ${error.data.message}`)
)
}
}
|
Set default SEASON_YEAR to 2014.
|
<?php
//modify vars below
$db_host = 'localhost';
$db_user = '';
$db_password = '';
$database = 'nflpickem';
$db_prefix = 'nflp_';
$siteUrl = 'http://localhost/personal/phppickem.com/application/';
$allow_signup = true;
$show_signup_link = true;
$user_names_display = 3; // 1 = real names, 2 = usernames, 3 = usernames w/ real names on hover
define('SEASON_YEAR', '2014');
//set timezone offset, hours difference between your server's timezone and eastern
define('SERVER_TIMEZONE_OFFSET', 1);
// ***DO NOT EDIT ANYTHING BELOW THIS LINE***
$dbConnected = false;
error_reporting(0);
if (mysql_connect($db_host, $db_user, $db_password)) {
if (mysql_select_db($database)) {
$dbConnected = true;
}
}
error_reporting(E_ALL ^ E_NOTICE);
|
<?php
//modify vars below
$db_host = 'localhost';
$db_user = '';
$db_password = '';
$database = 'nflpickem';
$db_prefix = 'nflp_';
$siteUrl = 'http://localhost/personal/phppickem.com/application/';
$allow_signup = true;
$show_signup_link = true;
$user_names_display = 3; // 1 = real names, 2 = usernames, 3 = usernames w/ real names on hover
define('SEASON_YEAR', '2013');
//set timezone offset, hours difference between your server's timezone and eastern
define('SERVER_TIMEZONE_OFFSET', 1);
// ***DO NOT EDIT ANYTHING BELOW THIS LINE***
$dbConnected = false;
error_reporting(0);
if (mysql_connect($db_host, $db_user, $db_password)) {
if (mysql_select_db($database)) {
$dbConnected = true;
}
}
error_reporting(E_ALL ^ E_NOTICE);
|
Exclude clear_cache from cache key
|
from django.core.cache import cache
#get the cache key for storage
def cache_get_key(*args, **kwargs):
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
#decorator for caching functions
def cache_for(time):
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
|
from django.core.cache import cache
#get the cache key for storage
def cache_get_key(*args, **kwargs):
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
#decorator for caching functions
def cache_for(time):
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
|
Use the proper method signature to prevent another fatal
|
<?php
namespace WP_CLI;
use \Composer\IO\NullIO;
use \WP_CLI;
/**
* A Composer IO class so we can provide some level of interactivity from WP-CLI
*/
class ComposerIO extends NullIO {
/**
* {@inheritDoc}
*/
public function isVerbose() {
return true;
}
/**
* {@inheritDoc}
*/
public function write( $messages, $newline = true, $verbosity = self::NORMAL ) {
self::output_clean_message( $messages );
}
/**
* {@inheritDoc}
*/
public function writeError( $messages, $newline = true, $verbosity = self::NORMAL ) {
self::output_clean_message( $messages );
}
private static function output_clean_message( $message ) {
$message = preg_replace( '#<(https?)([^>]+)>#', '$1$2', $message );
WP_CLI::log( strip_tags( trim( $message ) ) );
}
}
|
<?php
namespace WP_CLI;
use \Composer\IO\NullIO;
use \WP_CLI;
/**
* A Composer IO class so we can provide some level of interactivity from WP-CLI
*/
class ComposerIO extends NullIO {
/**
* {@inheritDoc}
*/
public function isVerbose() {
return true;
}
/**
* {@inheritDoc}
*/
public function write( $messages, $newline = true ) {
self::output_clean_message( $messages );
}
/**
* {@inheritDoc}
*/
public function writeError( $messages, $newline = true ) {
self::output_clean_message( $messages );
}
private static function output_clean_message( $message ) {
$message = preg_replace( '#<(https?)([^>]+)>#', '$1$2', $message );
WP_CLI::log( strip_tags( trim( $message ) ) );
}
}
|
Add blank (g, fb)RentRollTemplate js functions
|
/*jslint browser: true*/
/*globals $, FB, gapi, fbLogin, setSettings, gGetEmail*/
"use strict";
function populateRentRoll(email) {
if (email === '') {
console.log("populateRentRoll - empty email!");
return;
}
$.ajax({
url: '/tenants',
data: { 'email': email },
success: function (tenants) {
document.getElementById('tenants').innerHTML = tenants;
}
});
}
function gRentRoll(resp) {
populateRentRoll(gGetEmail(resp));
}
function fbRentRoll() {
FB.api('/me', function (response) {
populateRentRoll(response.email);
});
}
function rentRollNotLoggedIn() {
window.location.href = "/submit";
/*var signinForm = document.getElementById("signinform");
if (signinForm == null) {
console.log("rentRollNotLoggedIn - ERROR NO SIGNIN FORM ELEMENT");
return;
}
$.ajax({
url: '/signinform',
success: function( form ) {
signinForm.innerHTML = form;
}
});*/
}
function rentRollTemplateNotLoggedIn() { }}
function gRentRollTemplate(resp) { }
function fbRentRollTemplate() { }
|
/*jslint browser: true*/
/*globals $, FB, gapi, fbLogin, setSettings, gGetEmail*/
"use strict";
function populateRentRoll(email) {
if (email === '') {
console.log("populateRentRoll - empty email!");
return;
}
$.ajax({
url: '/tenants',
data: { 'email': email },
success: function (tenants) {
document.getElementById('tenants').innerHTML = tenants;
}
});
}
function gRentRoll(resp) {
populateRentRoll(gGetEmail(resp));
}
function fbRentRoll() {
FB.api('/me', function (response) {
populateRentRoll(response.email);
});
}
function rentRollNotLoggedIn() {
window.location.href = "/submit";
/*var signinForm = document.getElementById("signinform");
if (signinForm == null) {
console.log("rentRollNotLoggedIn - ERROR NO SIGNIN FORM ELEMENT");
return;
}
$.ajax({
url: '/signinform',
success: function( form ) {
signinForm.innerHTML = form;
}
});*/
}
function rentRollTemplateNotLoggedIn() {
}
|
Make config default to writable
|
<?php
/**
* Phossa Project
*
* PHP version 5.4
*
* @category Library
* @package Phossa2\Config
* @copyright Copyright (c) 2016 phossa.com
* @license http://mit-license.org/ MIT License
* @link http://www.phossa.com/
*/
/*# declare(strict_types=1); */
namespace Phossa2\Config\Traits;
use Phossa2\Config\Interfaces\WritableInterface;
/**
* Implementation of WritableInterface
*
* @package Phossa2\Config
* @author Hong Zhang <phossa@126.com>
* @see WritableInterface
* @version 2.0.0
* @since 2.0.0 added
*/
trait WritableTrait
{
/**
* @var false|mixed
* @access protected
*/
protected $writable = true;
/**
* {@inheritDoc}
*/
public function isWritable()/*# : bool */
{
return false !== $this->writable;
}
/**
* {@inheritDoc}
*/
public function setWritable($writable)
{
$this->writable = $writable;
return $this;
}
// from WritableInterface
abstract public function set(/*# string */ $id, $value);
}
|
<?php
/**
* Phossa Project
*
* PHP version 5.4
*
* @category Library
* @package Phossa2\Config
* @copyright Copyright (c) 2016 phossa.com
* @license http://mit-license.org/ MIT License
* @link http://www.phossa.com/
*/
/*# declare(strict_types=1); */
namespace Phossa2\Config\Traits;
use Phossa2\Config\Interfaces\WritableInterface;
/**
* Implementation of WritableInterface
*
* @package Phossa2\Config
* @author Hong Zhang <phossa@126.com>
* @see WritableInterface
* @version 2.0.0
* @since 2.0.0 added
*/
trait WritableTrait
{
/**
* @var false|mixed
* @access protected
*/
protected $writable = false;
/**
* {@inheritDoc}
*/
public function isWritable()/*# : bool */
{
return false !== $this->writable;
}
/**
* {@inheritDoc}
*/
public function setWritable($writable)
{
$this->writable = $writable;
return $this;
}
// from WritableInterface
abstract public function set(/*# string */ $id, $value);
}
|
Fix missing imports and extends
|
package com.josenaves.plugin;
import android.util.Log;
import android.location.LocationManager;
import android.content.Context;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
public class CheckGps extends CordovaPlugin {
private static final String TAG = CheckGps.class.getSimpleName();
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("isGpsEnabled".equals(action)) {
if (isGpsEnabled()) {
callbackContext.success("GPS is enabled");
} else {
callbackContext.error("GPS is not enabled");
}
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
private boolean isGpsEnabled() {
LocationManager locationManager = (LocationManager) Context.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d(TAG, String.format("CheckGps.isGpsEnabled() = %s", enabled) );
return enabled;
}
}
|
package com.josenaves.plugin;
import android.util.Log;
import android.location.LocationManager;
import android.content.Context;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
public class CheckGps {
private static final String TAG = CheckGps.class.getSimpleName();
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("isGpsEnabled".equals(action)) {
if (isGpsEnabled()) {
callbackContext.success("GPS is enabled");
} else {
callbackContext.error("GPS is not enabled");
}
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
private boolean isGpsEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d(TAG, String.format("CheckGps.isGpsEnabled() = %s", enabled) );
return enabled;
}
}
|
Include test data files in package. Otherwise, they are not copied to the build directory and the tests fail.
|
import re
import setuptools
with open("README.md", "r") as fin:
long_description = fin.read()
long_description = re.sub(
"^(!\[.*\]\()(.*\))",
lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2),
long_description,
flags=re.MULTILINE
)
setuptools.setup(
name="geneagrapher",
version="1.0",
author="David Alber",
author_email="alber.david@gmail.com",
description="Mathematical genealogy grapher.",
entry_points={
'console_scripts':
['ggrapher=geneagrapher.geneagrapher:ggrapher']
},
install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'],
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/davidalber/geneagrapher",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
package_data={'tests': ['geneagrapher/testdata/*.html']},
include_package_data=True,
)
|
import re
import setuptools
with open("README.md", "r") as fin:
long_description = fin.read()
long_description = re.sub(
"^(!\[.*\]\()(.*\))",
lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2),
long_description,
flags=re.MULTILINE
)
setuptools.setup(
name="geneagrapher",
version="1.0",
author="David Alber",
author_email="alber.david@gmail.com",
description="Mathematical genealogy grapher.",
entry_points={
'console_scripts':
['ggrapher=geneagrapher.geneagrapher:ggrapher']
},
install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'],
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/davidalber/geneagrapher",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
|
Manipulation: Check state lost if the name is set for Android 4.0-4.3
Refs gh-1820
Closes gh-1841
|
define([
"../var/support"
], function( support ) {
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0-4.3
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Android<4.2
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<=11+
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
return support;
});
|
define([
"../var/support"
], function( support ) {
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
div.appendChild( input );
// Support: Android<4.2
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<=11+
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
return support;
});
|
Refactor Heroku tests to have shared setup
|
"""Tests for the Wallace API."""
import subprocess
import re
import os
import requests
class TestHeroku(object):
"""The Heroku test class."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox --verbose", shell=True)
os.environ['app_id'] = re.search(
'Running as experiment (.*)...', sandbox_output).group(1)
@classmethod
def teardown_class(cls):
"""Remove the app from Heroku."""
app_id = os.environ['app_id']
subprocess.call(
"heroku apps:destroy --app {} --confirm {}".format(app_id, app_id),
shell=True)
def test_summary(self):
"""Launch the experiment on Heroku."""
app_id = os.environ['app_id']
r = requests.get("http://{}.herokuapp.com/summary".format(app_id))
assert r.json()['status'] == []
|
"""Tests for the Wallace API."""
import subprocess
import re
import requests
class TestHeroku(object):
"""The Heroku test class."""
def test_sandbox(self):
"""Launch the experiment on Heroku."""
sandbox_output = subprocess.check_output(
"cd examples/bartlett1932; wallace sandbox --verbose", shell=True)
id = re.search(
'Running as experiment (.*)...', sandbox_output).group(1)
r = requests.get("http://{}.herokuapp.com/summary".format(id))
assert r.json()['status'] == []
subprocess.call(
"heroku apps:destroy --app {} --confirm {}".format(id),
shell=True)
|
Use tuples for internal type lists in the array API
These are easier for type checkers to handle.
|
import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
|
import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
|
Move database connection code into thread-local context
|
import flask
import psycopg2
DB_URL = 'postgres://rpitours:rpitours@localhost:5432/rpitours'
app = flask.Flask(__name__)
def get_db():
db = getattr(flask.g, 'database', None)
if db is None:
db = flask.g.database = psycopg2.connect(DB_URL)
return db
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['https://example.com/photo1.jpg', 'https://example.com/photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
@app.route('/dbtest')
def dbtest():
get_db()
return flask.jsonify(success=True)
if __name__ == '__main__':
app.run(debug=True)
|
import flask
import psycopg2
app = flask.Flask(__name__)
db = psycopg2.connect('postgres://rpitours:rpitours@localhost:5432/rpitours')
def make_tour():
tour = {
'id': 1,
'name': 'Test Tour',
'waypoints': [
(5, 2),
(2, 3),
(1, 4),
(4, 4)
],
'landmarks': [
{
'name': 'A Place',
'description': 'This is a description of this place.',
'photos': ['https://example.com/photo1.jpg', 'https://example.com/photo2.jpg'],
'coordinate': (3, 4),
}, {
'coordinate': (2, 3),
}, {
'coordinate': (4, 1)
}
]
}
return tour
@app.route('/')
def index():
return flask.jsonify(hello='world')
@app.route('/tours')
def tours():
tour_lst = [make_tour()]
return flask.jsonify(tours=tour_lst)
if __name__ == '__main__':
app.run(debug=True)
|
Use in memory test database
|
import django
from os import path
SECRET_KEY = 'not secret'
INSTALLED_APPS = ('dumper', 'test', 'django.contrib.contenttypes')
TEMPLATE_DEBUG = DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
ROOT_URLCONF = 'test.urls'
# Testing
if django.VERSION[:2] < (1, 6):
INSTALLED_APPS += ('discover_runner',)
TEST_RUNNER = 'discover_runner.DiscoverRunner'
TEST_DISCOVER_TOP_LEVEL = path.dirname(path.dirname(__file__))
# Cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'dumper-default'
},
'other': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'dumper-other'
},
}
MIDDLEWARE_CLASSES = (
'dumper.middleware.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'dumper.middleware.FetchFromCacheMiddleware',
)
|
import django
from os import path
SECRET_KEY = 'not secret'
INSTALLED_APPS = ('dumper', 'test', 'django.contrib.contenttypes')
TEMPLATE_DEBUG = DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'imagekit.db',
},
}
ROOT_URLCONF = 'test.urls'
# Testing
if django.VERSION[:2] < (1, 6):
INSTALLED_APPS += ('discover_runner',)
TEST_RUNNER = 'discover_runner.DiscoverRunner'
TEST_DISCOVER_TOP_LEVEL = path.dirname(path.dirname(__file__))
# Cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'dumper-default'
},
'other': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'dumper-other'
},
}
MIDDLEWARE_CLASSES = (
'dumper.middleware.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'dumper.middleware.FetchFromCacheMiddleware',
)
|
Use same root path for server and hook file lookup
|
#!/usr/bin/env node
// Modules
var connect = require('connect'),
fs = require('fs'),
http = require('http'),
path = require('path'),
serveStatic = require('serve-static'),
serveIndex = require('serve-index');
function main(port, rootPath, indexFile) {
rootPath = path.resolve(rootPath);
var app = connect(),
hookFile = path.join(rootPath, 'web-server-hook.js');
hook = {
config: function() {},
postConfig: function() {}
};
if (fs.existsSync(hookFile)) {
hook = require(hookFile);
}
if (undefined !== hook.config) {
hook.config(app, port, rootPath);
}
app.use(serveStatic(rootPath, {'index': [indexFile]}));
app.use(serveIndex(rootPath, {'icons': true, 'view': 'details'}));
if (undefined !== hook.postConfig) {
hook.postConfig(app, port, rootPath);
}
if (undefined != hook.createServer) {
hook.createServer(app, port, rootPath);
} else {
http.createServer(app).listen(port, function() {
console.log('Static server started at http://localhost:%d/', port);
});
}
}
module.exports = main;
|
#!/usr/bin/env node
// Modules
var connect = require('connect'),
fs = require('fs'),
http = require('http'),
path = require('path'),
serveStatic = require('serve-static'),
serveIndex = require('serve-index');
// Variables
var app = connect(),
hookFile = path.join(process.env.PWD, 'web-server-hook.js');
function main(port, rootPath, indexFile) {
var hook = {
config: function() {},
postConfig: function() {}
};
rootPath = path.resolve(rootPath);
if (fs.existsSync(hookFile)) {
hook = require(hookFile);
}
if (undefined !== hook.config) {
hook.config(app, port, rootPath);
}
app.use(serveStatic(rootPath, {'index': [indexFile]}));
app.use(serveIndex(rootPath, {'icons': true, 'view': 'details'}));
if (undefined !== hook.postConfig) {
hook.postConfig(app, port, rootPath);
}
if (undefined != hook.createServer) {
hook.createServer(app, port, rootPath);
} else {
http.createServer(app).listen(port, function() {
console.log('Static server started at http://localhost:%d/', port);
});
}
}
module.exports = main;
|
Fix aliases and error message.g
|
const Command = require('../structures/command.js');
const request = require('request');
module.exports = class TogetherTube extends Command {
constructor(client) {
super(client);
this.name = "togethertube";
this.aliases = ["ttube", "ttb"];
}
run(message, args, commandLang) {
let embed = this.client.getDekuEmbed(message);
message.channel.startTyping();
request('https://togethertube.com/room/create', (error, response) => {
if (error) {
embed.setColor(this.client.config.colors.error);
embed.setTitle(commandLang.error_title);
embed.setDescription(commandLang.error_description);
} else {
embed.setDescription(response.request.uri.href);
embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/');
}
message.channel.stopTyping();
message.channel.send({embed});
});
}
}
|
const Command = require('../structures/command.js');
const request = require('request');
module.exports = class TogetherTube extends Command {
constructor(client) {
super(client);
this.name = "togethertube";
this.aliases ["ttube", "ttb"];
}
run(message, args, commandLang) {
let embed = this.client.getDekuEmbed(message);
message.channel.startTyping();
request('https://togethertube.com/room/create', (error, response) => {
if (error) {
embed.setColor(this.client.config.colors.error);
embed.setTitle(commandLang.error_title);
embed.setDescription(commandLang.error_description);
} else {
embed.setDescription(response.request.uri.href);
embed.setAuthor('TogetherTube', 'https://togethertube.com/assets/img/favicons/favicon-32x32.png', 'https://togethertube.com/');
message.channel.stopTyping();
message.channel.send({embed});
}
});
}
}
|
Improve the greeting template validation and messages.
|
package hello.models;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class Greeting implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private long id;
@NotEmpty(message = "The greeting cannot be empty.")
@Size(max = 30, message = "The greeting must have 30 characters or less.")
private String template;
public Greeting() {
}
public Greeting(String template) {
this.template = template;
}
public long getId() {
return this.id;
}
public String getTemplate() {
return this.template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getGreeting(String name) {
return String.format(this.template, name);
}
@Override
public String toString() {
return String.format("Greeting [id = %d, template = %s]", this.id, this.template);
}
}
|
package hello.models;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Size;
@Entity
public class Greeting implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private long id;
@Size(min = 1, max = 30)
private String template;
public Greeting() {
}
public Greeting(String template) {
this.template = template;
}
public long getId() {
return this.id;
}
public String getTemplate() {
return this.template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getGreeting(String name) {
return String.format(this.template, name);
}
@Override
public String toString() {
return String.format("Greeting [id = %d, template = %s]", this.id, this.template);
}
}
|
Make controller routes as expressions.
|
import express from 'express';
import bodyParser from 'body-parser';
import * as repoModel from '../models/repo';
import * as tokenModel from '../models/token';
import * as packageModel from '../models/package';
const jsonParser = bodyParser.json();
const router = new express.Router();
export default router;
router.get('/', (req, res) =>
res.send('hello world'));
router.get('/:provider/:user', (req, res) =>
repoModel.query(req.params)
.then(result => res.json(result),
error => res.send(error)));
router.route('/token/:provider/:user/:repo')
.get((req, res) =>
tokenModel.get(req.params)
.then(token => res.json(token),
error => res.send(error)))
.post((req, res) =>
tokenModel.create(req.params)
.then(token => res.json(token),
error => res.send(error.toString())));
router.route('/:provider/:user/:repo')
.get((req, res) =>
packageModel.query(req.params)
.then(result => res.json(result),
error => res.send(error)))
.post(jsonParser, (req, res) =>
tokenModel.validate({ ...req.params, token: req.body.token })
.then(() => packageModel.upsert({ ...req.params, ...req.body }))
.then(entity => res.json(entity),
error => res.send(error.toString())));
|
import express from 'express';
import bodyParser from 'body-parser';
import * as repoModel from '../models/repo';
import * as tokenModel from '../models/token';
import * as packageModel from '../models/package';
const jsonParser = bodyParser.json();
const router = new express.Router();
export default router;
router.get('/', (req, res) =>
res.send('hello world'));
router.get('/:provider/:user', (req, res) => {
repoModel.query(req.params)
.then(result => res.json(result),
error => res.send(error));
});
router.route('/token/:provider/:user/:repo')
.get((req, res) => {
tokenModel.get(req.params)
.then(token => res.json(token),
error => res.send(error));
})
.post((req, res) => {
tokenModel.create(req.params)
.then(token => res.json(token),
error => res.send(error.toString()));
});
router.route('/:provider/:user/:repo')
.get((req, res) => {
packageModel.query(req.params)
.then(result => res.json(result),
error => res.send(error));
})
.post(jsonParser, (req, res) => {
tokenModel.validate({ ...req.params, token: req.body.token })
.then(() => packageModel.upsert({ ...req.params, ...req.body }))
.then(entity => res.json(entity),
error => res.send(error.toString()));
});
|
Add role on signup user create
|
var bcrypt = require( 'bcrypt' );
var appModels = require( '../models' );
var systemError = require( '../utils' ).systemError;
exports.isEmailInUse = function ( email, callback ) {
appModels.User.findOne( { email: email }, function ( err, user ) {
if ( err ) {
return callback( systemError( err ) );
}
if ( user ) {
return callback( null, true );
}
return callback( null, false );
} );
};
exports.createUser = function ( email, password, callback ) {
var newUserData = {
email: email,
password: bcrypt.hashSync( password, 8 ),
role: "user"
};
appModels.User.create( newUserData, function ( err, newUser ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, newUser );
} );
};
|
var bcrypt = require( 'bcrypt' );
var appModels = require( '../models' );
var systemError = require( '../utils' ).systemError;
exports.isEmailInUse = function ( email, callback ) {
appModels.User.findOne( { email: email }, function ( err, user ) {
if ( err ) {
return callback( systemError( err ) );
}
if ( user ) {
return callback( null, true );
}
return callback( null, false );
} );
};
exports.createUser = function ( email, password, callback ) {
var newUserData = {
email: email,
password: bcrypt.hashSync( password, 8 )
};
appModels.User.create( newUserData, function ( err, newUser ) {
if ( err ) {
return callback( systemError( err ) );
}
return callback( null, newUser );
} );
};
|
Remove explicit link to homepage view in i4p_base
|
#-- encoding: utf-8 --
from django.conf.urls.defaults import patterns, url
from haystack.views import search_view_factory
import views
import ajax
urlpatterns = patterns('',
#url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slider-bestof'),
url(r'^homepage/ajax/slider/latest/$', ajax.slider_latest, name='i4p-homepage-ajax-slider-latest'),
url(r'^homepage/ajax/slider/commented/$', ajax.slider_most_commented, name='i4p-homepage-ajax-slider-commented'),
url(r'^history/check_version/(?P<pk>[\d]+)$', views.VersionActivityCheckView.as_view(), name='history-check-version'),
url(r'^search/', search_view_factory(view_class=views.SearchView), name='i4p-search'),
url(r'^location/(?P<location_id>\d+)', views.LocationEditView.as_view(), name='i4p-location-edit'),
url(r'^locations/$', views.LocationListView.as_view(), name='i4p-location-list'),
url(r'^locations/missing/(?P<missing_field_name>\w+)$', views.LocationListView.as_view(), name='i4p-location-missing-list'),
)
|
#-- encoding: utf-8 --
from django.conf.urls.defaults import patterns, url
from haystack.views import search_view_factory
import views
import ajax
urlpatterns = patterns('',
url(r'^$', views.homepage, name='i4p-index'),
url(r'^homepage/ajax/slider/bestof/$', ajax.slider_bestof, name='i4p-homepage-ajax-slider-bestof'),
url(r'^homepage/ajax/slider/latest/$', ajax.slider_latest, name='i4p-homepage-ajax-slider-latest'),
url(r'^homepage/ajax/slider/commented/$', ajax.slider_most_commented, name='i4p-homepage-ajax-slider-commented'),
url(r'^history/check_version/(?P<pk>[\d]+)$', views.VersionActivityCheckView.as_view(), name='history-check-version'),
url(r'^search/', search_view_factory(view_class=views.SearchView), name='i4p-search'),
url(r'^location/(?P<location_id>\d+)', views.LocationEditView.as_view(), name='i4p-location-edit'),
url(r'^locations/$', views.LocationListView.as_view(), name='i4p-location-list'),
url(r'^locations/missing/(?P<missing_field_name>\w+)$', views.LocationListView.as_view(), name='i4p-location-missing-list'),
)
|
Fix the cutting out of the first 6 chars
|
// Internet Icon by Freepik (http://www.flaticon.com/free-icon/worldwide_448589)
const urlencode = require('urlencode');
module.exports = {
action: 'openurl',
query: (query) => {
const items = [];
const searchTerm = query.slice(0);
const url = 'https:\/\/www.google.com/search?q=' + urlencode(searchTerm);
items.push({
title: `Search Google for ${searchTerm}`,
subtitle: 'Open in browser',
arg: url,
icon: {
path: './icon.png'
}
});
return { items };
}
};
|
// Internet Icon by Freepik (http://www.flaticon.com/free-icon/worldwide_448589)
const urlencode = require('urlencode');
module.exports = {
action: 'openurl',
query: (query) => {
const items = [];
const searchTerm = query.slice(6);
const url = 'https:\/\/www.google.com/search?q=' + urlencode(searchTerm);
items.push({
title: `Search Google for ${searchTerm}`,
subtitle: 'Open in browser',
arg: url,
icon: {
path: './icon.png'
}
});
return { items };
}
};
|
Allow phone numbers from 8 to 12 digits instead of fixed 11
|
<?php
namespace Difra\Security\Filter;
/**
* Class Phone
* @package Difra\Security\Filter
*/
class Phone implements Common
{
/**
* Validate input string
* @param string $string
* @return bool
*/
public static function validate($string)
{
$ph = str_replace(['+', '(', ')', '-', ' '], '', $string);
return ctype_digit($ph) and mb_strlen($ph) >= 8 and mb_strlen($ph) <= 12;
}
/**
* Sanitize input string
* @param string $string
* @return string
*/
public static function sanitize($string)
{
if (!self::validate($string)) {
return null;
}
return str_replace(['+', '(', ')', '-', ' '], '', $string);
}
}
|
<?php
namespace Difra\Security\Filter;
class Phone implements Common
{
/**
* Validate input string
* @param string $string
* @return bool
*/
public static function validate($string)
{
$ph = str_replace(['+', '(', ')', '-', ' '], '', $string);
return ctype_digit($ph) and mb_strlen($ph) == 11;
}
/**
* Sanitize input string
* @param string $string
* @return string
*/
public static function sanitize($string)
{
if (!self::validate($string)) {
return null;
}
return str_replace(['+', '(', ')', '-', ' '], '', $string);
}
}
|
Set num of threads 1 on service node
|
package io.scalecube.gateway.examples;
import io.scalecube.config.ConfigRegistry;
import io.scalecube.gateway.config.GatewayConfigRegistry;
import io.scalecube.services.Microservices;
import io.scalecube.transport.Address;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Runner for example services.
*/
public class ExamplesRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(ExamplesRunner.class);
private static final String DECORATOR =
"***********************************************************************";
/**
* Main method of runner for example services.
*
* @param args - program arguments.
* @throws InterruptedException - thrown if was interrupted.
*/
public static void main(String[] args) throws InterruptedException {
ConfigRegistry configRegistry = GatewayConfigRegistry.configRegistry();
ExamplesConfig config =
configRegistry.objectValue("io.scalecube.gateway.examples", ExamplesConfig.class, null);
LOGGER.info(DECORATOR);
LOGGER.info("Starting Examples services on " + config);
LOGGER.info(DECORATOR);
int servicePort = config.getServicePort();
Address[] seeds = config.getSeedAddress().stream().map(Address::from).toArray(Address[]::new);
Microservices.builder()
.seeds(seeds)
.servicePort(servicePort)
.services(new GreetingServiceImpl())
.numOfThreads(1)
.startAwait();
Thread.currentThread().join();
}
}
|
package io.scalecube.gateway.examples;
import io.scalecube.config.ConfigRegistry;
import io.scalecube.gateway.config.GatewayConfigRegistry;
import io.scalecube.services.Microservices;
import io.scalecube.transport.Address;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Runner for example services.
*/
public class ExamplesRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(ExamplesRunner.class);
private static final String DECORATOR =
"***********************************************************************";
/**
* Main method of runner for example services.
*
* @param args - program arguments.
* @throws InterruptedException - thrown if was interrupted.
*/
public static void main(String[] args) throws InterruptedException {
ConfigRegistry configRegistry = GatewayConfigRegistry.configRegistry();
ExamplesConfig config =
configRegistry.objectValue("io.scalecube.gateway.examples", ExamplesConfig.class, null);
LOGGER.info(DECORATOR);
LOGGER.info("Starting Examples services on " + config);
LOGGER.info(DECORATOR);
int servicePort = config.getServicePort();
Address[] seeds = config.getSeedAddress().stream().map(Address::from).toArray(Address[]::new);
Microservices.builder()
.seeds(seeds)
.servicePort(servicePort)
.services(new GreetingServiceImpl())
.startAwait();
Thread.currentThread().join();
}
}
|
Test that mx checks are not done
|
var utils = require('../lib/utils'),
_ = require('underscore');
exports.test_is_email = function ( test ) {
var good = [
'bob@example.com',
'fred@thisdomaindoesnotexist.bogus'
];
var bad = [
'foo',
'foo@',
'@example.com',
'',
null
];
test.expect( good.length + bad.length );
_.each( good, function ( email ) {
test.ok( utils.is_email(email), "is an email: " + email );
});
_.each( bad, function ( email ) {
test.ok( ! utils.is_email(email), "not an email: " + email );
});
test.done();
};
|
var utils = require('../lib/utils'),
_ = require('underscore');
exports.test_is_email = function ( test ) {
var good = [
'bob@example.com',
];
var bad = [
'foo',
'foo@',
'@example.com',
'',
null
];
test.expect( good.length + bad.length );
_.each( good, function ( email ) {
test.ok( utils.is_email(email), "is an email: " + email );
});
_.each( bad, function ( email ) {
test.ok( ! utils.is_email(email), "not an email: " + email );
});
test.done();
};
|
Fix all string throw statements
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('../../../build/npm/update-grammar');
function adaptInjectionScope(grammar) {
// we're using the HTML grammar from https://github.com/textmate/html.tmbundle which has moved away from source.js.embedded.html
let oldInjectionKey = "text.html.php - (meta.embedded | meta.tag), L:text.html.php meta.tag, L:source.js.embedded.html";
let newInjectionKey = "text.html.php - (meta.embedded | meta.tag), L:text.html.php meta.tag, L:text.html.php source.js";
var injections = grammar.injections;
var injection = injections[oldInjectionKey];
if (!injections) {
throw new Error("Can not find PHP injection");
}
delete injections[oldInjectionKey];
injections[newInjectionKey] = injection;
}
updateGrammar.update('atom/language-php', 'grammars/php.cson', './syntaxes/php.tmLanguage.json', adaptInjectionScope);
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('../../../build/npm/update-grammar');
function adaptInjectionScope(grammar) {
// we're using the HTML grammar from https://github.com/textmate/html.tmbundle which has moved away from source.js.embedded.html
let oldInjectionKey = "text.html.php - (meta.embedded | meta.tag), L:text.html.php meta.tag, L:source.js.embedded.html";
let newInjectionKey = "text.html.php - (meta.embedded | meta.tag), L:text.html.php meta.tag, L:text.html.php source.js";
var injections = grammar.injections;
var injection = injections[oldInjectionKey];
if (!injections) {
throw "Can not find PHP injection";
}
delete injections[oldInjectionKey];
injections[newInjectionKey] = injection;
}
updateGrammar.update('atom/language-php', 'grammars/php.cson', './syntaxes/php.tmLanguage.json', adaptInjectionScope);
|
Change test wrapper callback from `call` to `apply`
|
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export default function testWrapper(testName, callback, qunit) {
function wrapper() {
var context = getContext();
var result = callback.apply(context, arguments);
function failTestOnPromiseRejection(reason) {
var message;
if (reason instanceof Error) {
message = reason.stack;
if (reason.message && message.indexOf(reason.message) < 0) {
// PhantomJS has a `stack` that does not contain the actual
// exception message.
message = Ember.inspect(reason) + "\n" + message;
}
} else {
message = Ember.inspect(reason);
}
ok(false, message);
}
Ember.run(function(){
QUnit.stop();
Ember.RSVP.Promise.resolve(result)['catch'](failTestOnPromiseRejection)['finally'](QUnit.start);
});
}
qunit(testName, wrapper);
}
|
import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export default function testWrapper(testName, callback, qunit) {
function wrapper(assert) {
var context = getContext();
var result = callback.call(context, assert);
function failTestOnPromiseRejection(reason) {
var message;
if (reason instanceof Error) {
message = reason.stack;
if (reason.message && message.indexOf(reason.message) < 0) {
// PhantomJS has a `stack` that does not contain the actual
// exception message.
message = Ember.inspect(reason) + "\n" + message;
}
} else {
message = Ember.inspect(reason);
}
ok(false, message);
}
Ember.run(function(){
QUnit.stop();
Ember.RSVP.Promise.resolve(result)['catch'](failTestOnPromiseRejection)['finally'](QUnit.start);
});
}
qunit(testName, wrapper);
}
|
Fix gettatr object and name.
|
# -*- coding: utf-8 -*-
class Manager(object):
# should be re-defined in a subclass
state_name = None
object_type = None
def __init__(self, api):
self.api = api
# shortcuts
@property
def state(self):
return self.api.state
@property
def queue(self):
return self.api.queue
@property
def token(self):
return self.api.token
class AllMixin(object):
def all(self, filt=None):
return list(filter(filt, self.state[self.state_name]))
class GetByIdMixin(object):
def get_by_id(self, obj_id, only_local=False):
"""
Finds and returns the object based on its id.
"""
for obj in self.state[self.state_name]:
if obj['id'] == obj_id or obj.temp_id == str(obj_id):
return obj
if not only_local and self.object_type is not None:
getter = getattr(eval('self.api.%ss' % self.object_type) , 'get')
return getter(obj_id)
return None
class SyncMixin(object):
"""
Syncs this specific type of objects.
"""
def sync(self):
return self.api.sync()
|
# -*- coding: utf-8 -*-
class Manager(object):
# should be re-defined in a subclass
state_name = None
object_type = None
def __init__(self, api):
self.api = api
# shortcuts
@property
def state(self):
return self.api.state
@property
def queue(self):
return self.api.queue
@property
def token(self):
return self.api.token
class AllMixin(object):
def all(self, filt=None):
return list(filter(filt, self.state[self.state_name]))
class GetByIdMixin(object):
def get_by_id(self, obj_id, only_local=False):
"""
Finds and returns the object based on its id.
"""
for obj in self.state[self.state_name]:
if obj['id'] == obj_id or obj.temp_id == str(obj_id):
return obj
if not only_local and self.object_type is not None:
getter = getattr(self.api, '%s/get' % self.object_type)
return getter(obj_id)
return None
class SyncMixin(object):
"""
Syncs this specific type of objects.
"""
def sync(self):
return self.api.sync()
|
Remove skip of test_get_cluster function for websocket transport
|
from tests import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_server_url'] is None
assert isinstance(info['rest_server_url'], string)
return
assert isinstance(info['websocket_server_url'], string)
assert info['rest_server_url'] is None
test.run(handle_connect)
def test_get_cluster(test):
def handle_connect(handler):
cluster_info = handler.api.get_cluster_info()
assert isinstance(cluster_info['bootstrap.servers'], string)
assert isinstance(cluster_info['zookeeper.connect'], string)
test.run(handle_connect)
|
from tests import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_server_url'] is None
assert isinstance(info['rest_server_url'], string)
return
assert isinstance(info['websocket_server_url'], string)
assert info['rest_server_url'] is None
test.run(handle_connect)
def test_get_cluster(test):
# TODO: implement websocket support when API will be added.
test.only_http_implementation()
def handle_connect(handler):
cluster_info = handler.api.get_cluster_info()
assert isinstance(cluster_info['bootstrap.servers'], string)
assert isinstance(cluster_info['zookeeper.connect'], string)
test.run(handle_connect)
|
Support the new google play motion activity format
As part of the change to slim down the apk for android,
https://github.com/e-mission/e-mission-phone/pull/46,
https://github.com/e-mission/e-mission-data-collection/pull/116
we switched from google play version from 8.1.0 to 8.3.0, which is the version
that has separate jar files, at least in my install.
But this changed the motion activity format - the field names are now `zzaKM`
and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the
server to handle this use case as well.
Note that we should really fix
https://github.com/e-mission/e-mission-data-collection/issues/80
to stop running into this in the future
|
import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
Fix syntax error for gtm experiment js
|
function utmx_section(){}function utmx(){}(function(){var k='73768344-10',d=document,l=d.location,c=d.cookie; if(l.search.indexOf('utm_expid='+k)>0)return; function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;d.write('<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com/ga_exp.js?'+'utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+'" type="text/javascript" charset="utf-8"><\/sc'+'ript>')})();utmx('url','A/B');
|
function utmx_section(){}function utmx(){}(function(){var k='73768344-10',d=document,l=d.location,c=d.cookie; if(l.search.indexOf('utm_expid='+k)>0)return; function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;d.write('<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':'://www')+'.google-analytics.com/ga_exp.js?'+'utmxkey='+k+'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+'" type="text/javascript" charset="utf-8"><\/sc'+'ript>')})();</script><script>utmx('url','A/B');
|
Kill switch and check if method exists instead
|
<?php
namespace Northstar\Merge;
class Merger
{
public function __construct()
{
}
public function merge($field, $target, $duplicate)
{
$mergeMethod = 'merge' . studly_case($field);
if (! method_exists($this, $mergeMethod)) {
// throw error here
return false;
}
return $this->{$mergeMethod}($target, $duplicate);
}
public function mergeLastAuthenticatedAt($target, $duplicate)
{
$targetValue = $target->last_authenticated_at;
$duplicateValue = $duplicate->last_authenticated_at;
return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
}
public function mergeLastMessagedAt($target, $duplicate)
{
$targetValue = $target->last_messaged_at;
$duplicateValue = $duplicate->last_messaged_at;
return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
}
}
|
<?php
namespace Northstar\Merge;
class Merger
{
public function __construct()
{
}
public function merge($field, $target, $duplicate)
{
switch ($field) {
case 'last_authenticated_at':
return $this->mergeLastAuthenticatedAt($target, $duplicate);
case 'last_messaged_at':
return $this->mergeLastMessagedAt($target, $duplicate);
default:
return false;
}
}
public function mergeLastAuthenticatedAt($target, $duplicate)
{
$targetValue = $target->last_authenticated_at;
$duplicateValue = $duplicate->last_authenticated_at;
return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
}
public function mergeLastMessagedAt($target, $duplicate)
{
$targetValue = $target->last_messaged_at;
$duplicateValue = $duplicate->last_messaged_at;
return $targetValue > $duplicateValue ? $targetValue : $duplicateValue;
}
}
|
[TASK] Add settings for Clone plugin
|
<?php
namespace NamelessCoder\GizzleGitPlugins\GizzlePlugins;
use NamelessCoder\Gizzle\Payload;
use NamelessCoder\Gizzle\PluginInterface;
/**
* Class ClonePlugin
*/
class ClonePlugin extends AbstractGitPlugin implements PluginInterface {
const OPTION_DIRECTORY = 'directory';
const OPTION_REPOSITORY = 'repository';
const OPTION_BRANCH = 'branch';
const OPTION_DEPTH = 'depth';
/**
* @var array
*/
protected $settings = array();
/**
* Initialize the plugin with an array of settings.
*
* @param array $settings
* @return void
*/
public function initialize(array $settings) {
$this->settings = $settings;
}
/**
* Analyse $payload and return TRUE if this plugin should
* be triggered in processing the payload.
*
* @param Payload $payload
* @return boolean
*/
public function trigger(Payload $payload) {
}
/**
* Perform whichever task the Plugin should perform based
* on the payload's data.
*
* @param Payload $payload
* @return void
*/
public function process(Payload $payload) {
}
}
|
<?php
namespace NamelessCoder\GizzleGitPlugins\GizzlePlugins;
use NamelessCoder\Gizzle\Payload;
use NamelessCoder\Gizzle\PluginInterface;
/**
* Class ClonePlugin
*/
class ClonePlugin extends AbstractGitPlugin implements PluginInterface {
/**
* @var array
*/
protected $settings = array();
/**
* Initialize the plugin with an array of settings.
*
* @param array $settings
* @return void
*/
public function initialize(array $settings) {
$this->settings = $settings;
}
/**
* Analyse $payload and return TRUE if this plugin should
* be triggered in processing the payload.
*
* @param Payload $payload
* @return boolean
*/
public function trigger(Payload $payload) {
}
/**
* Perform whichever task the Plugin should perform based
* on the payload's data.
*
* @param Payload $payload
* @return void
*/
public function process(Payload $payload) {
}
}
|
Remove download URL since Github doesn't get his act together. Damnit
committer: Jannis Leidel <9b7c7d158dc2d8ee5ad777a516c517e4cfb54547@leidel.info>
|
from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Use the multi-platform gesellix/echo-server image
|
package de.gesellix.gradle.docker.testutil;
import de.gesellix.docker.client.DockerClient;
import java.util.Objects;
public class TestImage {
private final DockerClient dockerClient;
private final String repository;
private final String tag;
private final boolean isWindows;
public TestImage(DockerClient dockerClient) {
this.dockerClient = dockerClient;
this.isWindows = Objects.requireNonNull(dockerClient.version().getContent().getOs()).equalsIgnoreCase("windows");
this.repository = "gesellix/echo-server";
this.tag = "2022-04-08T22-27-00";
// TODO consider NOT calling prepare inside the constructor
prepare();
}
public void prepare() {
dockerClient.pull(null, null, getImageName(), getImageTag());
}
public boolean isWindows() {
return isWindows;
}
public String getImageWithTag() {
return getImageName() + ":" + getImageTag();
}
public String getImageName() {
return repository;
}
public String getImageTag() {
return tag;
}
}
|
package de.gesellix.gradle.docker.testutil;
import de.gesellix.docker.client.DockerClient;
import java.util.Objects;
public class TestImage {
private final DockerClient dockerClient;
private final String repository;
private final String tag;
private final boolean isWindows;
public TestImage(DockerClient dockerClient) {
this.dockerClient = dockerClient;
this.isWindows = Objects.requireNonNull(dockerClient.version().getContent().getOs()).equalsIgnoreCase("windows");
this.repository = "gesellix/echo-server";
this.tag = isWindows ? "os-windows" : "os-linux";
// TODO consider NOT calling prepare inside the constructor
prepare();
}
public void prepare() {
dockerClient.pull(null, null, getImageName(), getImageTag());
}
public boolean isWindows() {
return isWindows;
}
public String getImageWithTag() {
return getImageName() + ":" + getImageTag();
}
public String getImageName() {
return repository;
}
public String getImageTag() {
return tag;
}
}
|
Use `error` instead of `load`.
|
/** Implements process.nextTick() in a browser environment.
* Where other implementations use postMessage, this uses the Image constructor and data URIs, because postMessage spam sucks.
* However, if gaining a few fractions of a millisecond in Firefox matter to you, set process.nextTick.enablePostMesage to true.
*/
process.nextTick = (function() {
var img,
queue = [],
noArgs = [],
pm = !!window.postMessage,
slice = Array.prototype.slice;
function tick() {
var len = queue.length,
q = queue.splice(0, len),
i;
for (i=0; i<len; i+=2) {
q[i].apply(process, q[i+1]);
}
}
window.addEventListener('message', tick);
return function nextTick(callback) {
var args = noArgs;
if (arguments.length>1) {
args = slice.call(arguments, 1);
}
queue.push(callback, args);
if (queue.length===2) {
if (pm && nextTick.enablePostMessage===true) {
window.postMessage(' ', '*');
}
else {
img = new Image();
img.onerror = tick;
img.src = '';
}
}
};
}());
|
/** Implements process.nextTick() in a browser environment.
* Where other implementations use postMessage, this uses the Image constructor and data URIs, because postMessage spam sucks.
* However, if gaining a few fractions of a millisecond in Firefox matter to you, set process.nextTick.enablePostMesage to true.
*/
process.nextTick = (function() {
var img = new Image(),
queue = [],
noArgs = [],
pm = !!window.postMessage,
slice = Array.prototype.slice,
dataUri = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
function tick() {
var len = queue.length,
q = queue.splice(0, len),
i;
for (i=0; i<len; i+=2) {
q[i].apply(process, q[i+1]);
}
}
img.onload = img.onerror = tick;
window.addEventListener('message', tick);
return function nextTick(callback) {
var args = noArgs;
if (arguments.length>1) {
args = slice.call(arguments, 1);
}
queue.push(callback, args);
if (queue.length===2) {
if (pm && nextTick.enablePostMessage===true) {
window.postMessage(' ', '*');
}
else {
img.src = '';
img.src = dataUri;
}
}
};
}());
|
Add counter for cleanup tasks not following the decorator
|
from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.experimental.stats import RCount, incr
from changes.models import Task
from changes.queue.task import TrackedTask, tracked_task
CHECK_TIME = timedelta(minutes=60)
@tracked_task
def cleanup_tasks():
with RCount('cleanup_tasks'):
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
"""
now = datetime.utcnow()
cutoff = now - CHECK_TIME
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < cutoff,
)
for task in pending_tasks:
incr('cleanup_unfinished')
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
|
from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.experimental.stats import RCount
from changes.models import Task
from changes.queue.task import TrackedTask, tracked_task
CHECK_TIME = timedelta(minutes=60)
@tracked_task
def cleanup_tasks():
with RCount('cleanup_tasks'):
"""
Find any tasks which haven't checked in within a reasonable time period and
requeue them if necessary.
"""
now = datetime.utcnow()
cutoff = now - CHECK_TIME
pending_tasks = Task.query.filter(
Task.status != Status.finished,
Task.date_modified < cutoff,
)
for task in pending_tasks:
task_func = TrackedTask(queue.get_task(task.task_name))
task_func.delay(
task_id=task.task_id.hex,
parent_task_id=task.parent_id.hex if task.parent_id else None,
**task.data['kwargs']
)
|
Improve the math here, and make it less confusing
|
package de.gurkenlabs.litiengine;
import de.gurkenlabs.litiengine.util.TimeUtilities;
public class RenderLoop extends UpdateLoop {
private int maxFps;
public RenderLoop(String name) {
super(name);
this.maxFps = Game.getConfiguration().client().getMaxFps();
}
@Override
public void run() {
while (!interrupted()) {
final long fpsWait = (long) (1000.0 / this.maxFps);
final long renderStart = System.nanoTime();
try {
Game.getCamera().updateFocus();
this.update();
Game.getScreenManager().getRenderComponent().render();
final long renderTime = (long) TimeUtilities.nanoToMs(System.nanoTime() - renderStart);
long wait = Math.max(0, fpsWait - renderTime);
if (wait != 0) {
Thread.sleep(wait);
}
} catch (final InterruptedException e) {
break;
}
}
}
@Override
public void terminate() {
interrupt();
}
public int getMaxFps() {
return maxFps;
}
public void setMaxFps(int maxFps) {
this.maxFps = maxFps;
}
}
|
package de.gurkenlabs.litiengine;
import de.gurkenlabs.litiengine.util.TimeUtilities;
public class RenderLoop extends UpdateLoop {
private int maxFps;
public RenderLoop(String name) {
super(name);
this.maxFps = Game.getConfiguration().client().getMaxFps();
}
@Override
public void run() {
while (!interrupted()) {
final long fpsWait = (long) (1.0 / this.maxFps * 1000);
final long renderStart = System.nanoTime();
try {
Game.getCamera().updateFocus();
this.update();
Game.getScreenManager().getRenderComponent().render();
final long renderTime = (long) TimeUtilities.nanoToMs(System.nanoTime() - renderStart);
long wait = Math.max(0, fpsWait - renderTime);
if (wait != 0) {
Thread.sleep(wait);
}
} catch (final InterruptedException e) {
break;
}
}
}
@Override
public void terminate() {
interrupt();
}
public int getMaxFps() {
return maxFps;
}
public void setMaxFps(int maxFps) {
this.maxFps = maxFps;
}
}
|
Remove old check for environment.php (replaced with config.php)
|
<?php
try {
/**
* Use composer autoloader
*/
if (!file_exists($composerAutoload = __DIR__ . '/../vendor/autoload.php')) {
header('HTTP/1.1 500');
die("<h1>Server Error</h1><p>Composer vendors are not installed on the server.</p>");
}
require_once $composerAutoload;
unset($composerAutoload);
/**
* Read the configuration
*/
$config = include __DIR__ . "/../app/config/config.php";
/**
* Read auto-loader
*/
include __DIR__ . "/../app/config/loader.php";
/**
* Read services
*/
include __DIR__ . "/../app/config/services.php";
/**
* Handle the request
*/
$application = new \Phalcon\Mvc\Application($di);
echo $application->handle()->getContent();
} catch (\Exception $e) {
/**
* Clear the buffer and show the 500 error page
*/
if (!DEV_MODE) {
ob_flush();
header('HTTP/1.1 500 Internal Server Error', true, 500);
include __DIR__ .'/maintenance/error-500.html';
}
throw $e;
}
|
<?php
try {
/**
* Use composer autoloader
*/
if (!file_exists($composerAutoload = __DIR__ . '/../vendor/autoload.php')) {
header('HTTP/1.1 500');
die("<h1>Server Error</h1><p>Composer vendors are not installed on the server.</p>");
}
require_once $composerAutoload;
unset($composerAutoload);
/**
* Read the configuration
*/
$config = include __DIR__ . "/../app/config/config.php";
/**
* Read auto-loader
*/
include __DIR__ . "/../app/config/loader.php";
/**
* Read services
*/
include __DIR__ . "/../app/config/services.php";
/**
* Read environment
*/
if (file_exists($environment = __DIR__ . "/../environment.php")) include $environment;
/**
* Handle the request
*/
$application = new \Phalcon\Mvc\Application($di);
echo $application->handle()->getContent();
} catch (\Exception $e) {
/**
* Clear the buffer and show the 500 error page
*/
if (!DEV_MODE) {
ob_flush();
header('HTTP/1.1 500 Internal Server Error', true, 500);
include __DIR__ .'/maintenance/error-500.html';
}
throw $e;
}
|
Stop using `flask.ext.*` in tests.
|
import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
import flask
from flask_images import Images, ImageSize, resized_img_src
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
|
import unittest
import sys
from six import PY3
if PY3:
from urllib.parse import urlsplit, parse_qsl
else:
from urlparse import urlsplit, parse_qsl
import werkzeug as wz
from flask import Flask, url_for, render_template_string
from flask.ext.images import Images, ImageSize, resized_img_src
import flask
flask_version = tuple(map(int, flask.__version__.split('.')))
class TestCase(unittest.TestCase):
def setUp(self):
self.app = self.create_app()
self.app_ctx = self.app.app_context()
self.app_ctx.push()
self.req_ctx = self.app.test_request_context('http://localhost:8000/')
self.req_ctx.push()
self.client = self.app.test_client()
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SERVER_NAME'] = 'localhost'
app.config['SECRET_KEY'] = 'secret secret'
app.config['IMAGES_PATH'] = ['assets']
self.images = Images(app)
return app
def assert200(self, res):
self.assertEqual(res.status_code, 200)
|
Set site tagline variable to display next to the logo
|
<header class="site-header" role="banner">
<div class="wrap grid">
<h1 class="logo grid-item one-half"><a class="brand" href="<?= esc_url(home_url('/')); ?>"><svg class="icon icon-logo"><use xlink:href="#icon-logo"/></svg><span class="sr-only"><?php bloginfo('name'); ?></span></a> <span class="sub-title">— <?php echo get_bloginfo ( 'description' ); ?></span></h1>
<nav class="site-nav grid-item one-half" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);
endif;
?>
<div class="nav-actions">
<a class="show-collection" href="/collection/"><span class="sr-only">Collection</span><svg class="icon icon-collection"><use xlink:href="#icon-collection"></svg></a>
<a class="show-search" href="/search/"><span class="sr-only">Search</span><svg class="icon icon-search"><use xlink:href="#icon-search"></svg></a>
</div>
</nav>
</div>
<?php global $collection; $collection = \Firebelly\Collections\get_active_collection(); ?>
<section class="collection mini" data-id="<?= $collection->ID ?>">
<?php include(locate_template('templates/collection.php')); ?>
</section>
</header>
|
<header class="site-header" role="banner">
<div class="wrap grid">
<h1 class="logo grid-item one-half"><a class="brand" href="<?= esc_url(home_url('/')); ?>"><svg class="icon icon-logo"><use xlink:href="#icon-logo"/></svg><span class="sr-only"><?php bloginfo('name'); ?></span></a> <span class="sub-title">— Design for a changing world.</span></h1>
<nav class="site-nav grid-item one-half" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);
endif;
?>
<div class="nav-actions">
<a class="show-collection" href="/collection/"><span class="sr-only">Collection</span><svg class="icon icon-collection"><use xlink:href="#icon-collection"></svg></a>
<a class="show-search" href="/search/"><span class="sr-only">Search</span><svg class="icon icon-search"><use xlink:href="#icon-search"></svg></a>
</div>
</nav>
</div>
<?php global $collection; $collection = \Firebelly\Collections\get_active_collection(); ?>
<section class="collection mini" data-id="<?= $collection->ID ?>">
<?php include(locate_template('templates/collection.php')); ?>
</section>
</header>
|
Update argument to createContentItem in Content
to object
|
// ----------------------------------------------------------------
// Content Class
class Content {
static get TYPE_NAME_KEY() {
return 0;
}
static get CONTENT() {
return 'content';
}
static get ITEM() {
return 'content-item';
}
static get ITEM_HEADER() {
return 'content-item-header';
}
static get ITEM_NAME() {
return 'content-item-name';
}
static get ITEM_KEYS() {
return 'content-item-keys';
}
static get ITEM_KEY() {
return 'content-item-key';
}
static createContentItem({
type = Content.TYPE_NAME_KEY,
header = null,
name = null,
keys = null
} = {}) {
let result = '';
return result;
}
}
|
// ----------------------------------------------------------------
// Content Class
class Content {
static get TYPE_NAME_KEY() {
return 0;
}
static get CONTENT() {
return 'content';
}
static get ITEM() {
return 'content-item';
}
static get ITEM_HEADER() {
return 'content-item-header';
}
static get ITEM_NAME() {
return 'content-item-name';
}
static get ITEM_KEYS() {
return 'content-item-keys';
}
static get ITEM_KEY() {
return 'content-item-key';
}
static createContentItem(
_type = Content.TYPE_NAME_KEY,
_header = null,
_name = null,
..._key = []
) {
let result = '';
return result;
}
}
|
Add proptypes, navbar changes on isAuthed true
|
import React, { PropTypes } from 'react'
import { Navigation } from 'components'
import { connect } from 'react-redux'
import { container, innerContainer } from './styles.css'
const MainContainer = React.createClass({
propTypes: {
isAuthed: PropTypes.bool.isRequired,
},
render () {
// console.log('props', this.props);
return (
<div className={container}>
<Navigation isAuthed={this.props.isAuthed}/>
<div className={innerContainer}>
{this.props.children}
</div>
</div>
)
},
})
// function mapStateToProps (state) {
// return {
// isAuthed: state.isAuthed,
// }
// }
export default connect(
(state) => ({isAuthed: state.isAuthed})
)(MainContainer)
|
import React from 'react'
import { Navigation } from 'components'
import { connect } from 'react-redux'
import { container, innerContainer } from './styles.css'
const MainContainer = React.createClass({
render () {
// console.log('props', this.props);
return (
<div className={container}>
<Navigation isAuthed={this.props.isAuthed}/>
<div className={innerContainer}>
{this.props.children}
</div>
</div>
)
},
})
// function mapStateToProps (state) {
// return {
// isAuthed: state.isAuthed,
// }
// }
export default connect(
(state) => ({isAuthed: state.isAuthed})
)(MainContainer)
|
Update a click in a test
|
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open('http://xkcd.com/353/')
self.assert_element('img[alt="Python"]')
self.click('a[rel="license"]')
text = self.get_text("div center")
self.assertTrue("reuse any of my drawings" in text)
self.open('http://xkcd.com/1481/')
title = self.get_attribute('#comic img', 'title')
self.assertTrue('connections to the server' in title)
self.click('link=Blag')
self.assert_text('The blag of the webcomic', 'h2')
self.update_text('input#s', 'Robots!\n')
self.assert_text('Hooray robots!', '#content')
self.open('http://xkcd.com/1319/')
self.assert_text('Automation', 'div#ctitle')
|
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open('http://xkcd.com/353/')
self.assert_element('img[alt="Python"]')
self.click('a[rel="license"]')
text = self.get_text("div center")
self.assertTrue("reuse any of my drawings" in text)
self.open('http://xkcd.com/1481/')
title = self.get_attribute('#comic img', 'title')
self.assertTrue('connections to the server' in title)
self.click_link_text('Blag')
self.assert_text('The blag of the webcomic', 'h2')
self.update_text('input#s', 'Robots!\n')
self.assert_text('Hooray robots!', '#content')
self.open('http://xkcd.com/1319/')
self.assert_text('Automation', 'div#ctitle')
|
Print gin config includes and imports when starting training.
PiperOrigin-RevId: 342367820
|
# coding=utf-8
# Copyright 2020 The Tensor2Robot Authors.
#
# 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.
# Lint as python3
"""Binary for training TFModels with Estimator API."""
from absl import app
from absl import flags
import gin
from tensor2robot.utils import train_eval
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
def main(unused_argv):
gin.parse_config_files_and_bindings(
FLAGS.gin_configs, FLAGS.gin_bindings, print_includes_and_imports=True)
train_eval.train_eval_model()
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
|
# coding=utf-8
# Copyright 2020 The Tensor2Robot Authors.
#
# 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.
# Lint as python3
"""Binary for training TFModels with Estimator API."""
from absl import app
from absl import flags
import gin
from tensor2robot.utils import train_eval
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
def main(unused_argv):
gin.parse_config_files_and_bindings(FLAGS.gin_configs, FLAGS.gin_bindings)
train_eval.train_eval_model()
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
|
Add --no-glob option to cli
|
#!/usr/bin/env node
var rimraf = require('./')
var help = false
var dashdash = false
var noglob = false
var args = process.argv.slice(2).filter(function(arg) {
if (dashdash)
return !!arg
else if (arg === '--')
dashdash = true
else if (arg === '--no-glob' || arg === '-G')
noglob = true
else if (arg === '--glob' || arg === '-g')
noglob = false
else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/))
help = true
else
return !!arg
})
if (help || args.length === 0) {
// If they didn't ask for help, then this is not a "success"
var log = help ? console.log : console.error
log('Usage: rimraf <path> [<path> ...]')
log('')
log(' Deletes all files and folders at "path" recursively.')
log('')
log('Options:')
log('')
log(' -h, --help Display this usage info')
log(' -G, --no-glob Do not expand glob patterns in arguments')
log(' -g, --glob Expand glob patterns in arguments (default)')
process.exit(help ? 0 : 1)
} else
go(0)
function go (n) {
if (n >= args.length)
return
var options = {}
if (noglob)
options = { glob: false }
rimraf(args[n], options, function (er) {
if (er)
throw er
go(n+1)
})
}
|
#!/usr/bin/env node
var rimraf = require('./')
var help = false
var dashdash = false
var args = process.argv.slice(2).filter(function(arg) {
if (dashdash)
return !!arg
else if (arg === '--')
dashdash = true
else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/))
help = true
else
return !!arg
});
if (help || args.length === 0) {
// If they didn't ask for help, then this is not a "success"
var log = help ? console.log : console.error
log('Usage: rimraf <path> [<path> ...]')
log('')
log(' Deletes all files and folders at "path" recursively.')
log('')
log('Options:')
log('')
log(' -h, --help Display this usage info')
process.exit(help ? 0 : 1)
} else
go(0)
function go (n) {
if (n >= args.length)
return
rimraf(args[n], function (er) {
if (er)
throw er
go(n+1)
})
}
|
Add .ts files to loader
|
const path = require("path")
const PATHS = {
app: path.join(__dirname, 'src/index.tsx'),
}
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
publicPath: "http://localhost:8080/"
},
mode: 'development',
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/
},
{
test: /\.jsx?$/,
use: 'react-hot-loader/webpack',
include: /node_modules/,
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
devServer: {
index: 'index.html',
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
},
devtool: 'inline-source-map'
}
|
const path = require("path")
const PATHS = {
app: path.join(__dirname, 'src/index.tsx'),
}
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
publicPath: "http://localhost:8080/"
},
mode: 'development',
module: {
rules: [
{
test: /\.(js|jsx|tsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/
},
{
test: /\.jsx?$/,
use: 'react-hot-loader/webpack',
include: /node_modules/,
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
devServer: {
index: 'index.html',
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
}
},
devtool: 'inline-source-map'
}
|
Use current version as default range with fallback to a new version
|
const fs = require( 'fs' );
const path = require( 'path' );
const DEFAULT_CONFIG = {
extends: 'kokarn'
};
const DEFAULT_TEST_COMMAND = 'eslint *.js';
const DEFAULT_ENGINE = process.version.replace( 'v', '^' ) || '^10.10.0';
const PACKAGE_PATH = path.join( __dirname, '../../../', 'package.json' );
let packageData = '';
let write = false;
try {
packageData = JSON.parse( fs.readFileSync( PACKAGE_PATH, 'utf8' ) );
} catch ( error ) {
console.log( `Failed to load package.json in ${ PACKAGE_PATH }, skipping setup` );
process.exit( 0 );
}
if( !packageData.scripts ){
packageData.scripts = {
pretest: DEFAULT_TEST_COMMAND
};
write = true;
} else if ( packageData.scripts && !packageData.scripts.pretest ){
packageData.scripts.pretest = DEFAULT_TEST_COMMAND;
write = true;
}
if ( !packageData.engines ){
packageData.engines = {
node: DEFAULT_ENGINE
};
write = true;
}
if ( !packageData.eslintConfig ) {
packageData.eslintConfig = DEFAULT_CONFIG;
write = true;
}
if ( write ) {
fs.writeFileSync( PACKAGE_PATH, JSON.stringify( packageData, null, 2 ) );
}
|
const fs = require( 'fs' );
const path = require( 'path' );
const DEFAULT_CONFIG = {
extends: 'kokarn'
};
const DEFAULT_TEST_COMMAND = 'eslint *.js';
const DEFAULT_ENGINE = '^6.9.4';
const PACKAGE_PATH = path.join( __dirname, '../../../', 'package.json' );
let packageData = '';
let write = false;
try {
packageData = JSON.parse( fs.readFileSync( PACKAGE_PATH, 'utf8' ) );
} catch ( error ) {
console.log( `Failed to load package.json in ${ PACKAGE_PATH }, skipping setup` );
process.exit( 0 );
}
if( !packageData.scripts ){
packageData.scripts = {
pretest: DEFAULT_TEST_COMMAND
};
write = true;
} else if ( packageData.scripts && !packageData.scripts.pretest ){
packageData.scripts.pretest = DEFAULT_TEST_COMMAND;
write = true;
}
if ( !packageData.engines ){
packageData.engines = {
node: DEFAULT_ENGINE
};
write = true;
}
if ( !packageData.eslintConfig ) {
packageData.eslintConfig = DEFAULT_CONFIG;
write = true;
}
if ( write ) {
fs.writeFileSync( PACKAGE_PATH, JSON.stringify( packageData, null, 2 ) );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.