text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Check if allowed_environments is an array. | <?php
/**
* Class Google\Site_Kit\Core\Tags\Guards\Tag_Environment_Type_Guard
*
* @package Google\Site_Kit\Core\Tags\Guards
* @copyright 2022 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Core\Tags\Guards;
use Google\Site_Kit\Core\Guards\Guard_Interface;
/**
* Guard that verifies if we're in a production environment.
*
* @since 1.38.0
* @access private
* @ignore
*/
class Tag_Environment_Type_Guard implements Guard_Interface {
/**
* Determines whether the guarded tag can be activated or not.
*
* @since 1.38.0
*
* @return bool TRUE if guarded tag can be activated, otherwise FALSE.
*/
public function can_activate() {
if ( ! function_exists( 'wp_get_environment_type' ) ) {
return true;
}
$allowed_environments = apply_filters(
'googlesitekit_allowed_tag_environment_types',
array( 'production' )
);
if ( ! is_array( $allowed_environments ) ) {
return false;
}
return in_array( wp_get_environment_type(), $allowed_environments, true );
}
}
| <?php
/**
* Class Google\Site_Kit\Core\Tags\Guards\Tag_Environment_Type_Guard
*
* @package Google\Site_Kit\Core\Tags\Guards
* @copyright 2022 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Core\Tags\Guards;
use Google\Site_Kit\Core\Guards\Guard_Interface;
/**
* Guard that verifies if we're in a production environment.
*
* @since 1.38.0
* @access private
* @ignore
*/
class Tag_Environment_Type_Guard implements Guard_Interface {
/**
* Determines whether the guarded tag can be activated or not.
*
* @since 1.38.0
*
* @return bool TRUE if guarded tag can be activated, otherwise FALSE.
*/
public function can_activate() {
if ( ! function_exists( 'wp_get_environment_type' ) ) {
return true;
}
$allowed_environments = apply_filters(
'googlesitekit_allowed_tag_environment_types',
array( 'production' )
);
return in_array( wp_get_environment_type(), $allowed_environments, true );
}
}
|
WIP: Add button to cancel job | import JobStatus from 'girder_plugins/jobs/JobStatus';
JobStatus.registerStatus({
WORKER_FETCHING_INPUT: {
value: 820,
text: 'Fetching input',
icon: 'icon-download',
color: '#89d2e2'
},
WORKER_CONVERTING_INPUT: {
value: 821,
text: 'Converting input',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_CONVERTING_OUTPUT: {
value: 822,
text: 'Converting output',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_PUSHING_OUTPUT: {
value: 823,
text: 'Pushing output',
icon: 'icon-upload',
color: '#89d2e2'
},
WORKER_CANCELING: {
value: 824,
text: 'Canceling',
icon: 'icon-cancel',
color: '#f89406'
}
});
| import JobStatus from 'girder_plugins/jobs/JobStatus';
JobStatus.registerStatus({
WORKER_FETCHING_INPUT: {
value: 820,
text: 'Fetching input',
icon: 'icon-download',
color: '#89d2e2'
},
WORKER_CONVERTING_INPUT: {
value: 821,
text: 'Converting input',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_CONVERTING_OUTPUT: {
value: 822,
text: 'Converting output',
icon: 'icon-shuffle',
color: '#92f5b5'
},
WORKER_PUSHING_OUTPUT: {
value: 823,
text: 'Pushing output',
icon: 'icon-upload',
color: '#89d2e2'
}
});
|
Use existing score search set schema function for artisan command | <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Console\Commands;
use App\Libraries\Search\ScoreSearch;
use Illuminate\Console\Command;
class EsIndexScoresSetSchema extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'es:index-scores:set-schema
{--schema= : Schema version to be set (can also be specified using environment variable "schema")}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set schema version of score index.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$schema = presence($this->option('schema')) ?? presence(env('schema'));
if ($schema === null) {
return $this->error('Index schema must be specified');
}
(new ScoreSearch())->setSchema($schema);
$this->info("Set score index schema version to {$schema}");
}
}
| <?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use LaravelRedis;
class EsIndexScoresSetSchema extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'es:index-scores:set-schema
{--schema= : Schema version to be set (can also be specified using environment variable "schema")}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Set schema version of score index.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$schema = presence($this->option('schema')) ?? presence(env('schema'));
if ($schema === null) {
return $this->error('Index schema must be specified');
}
LaravelRedis::set('osu-queue:score-index:'.config('osu.elasticsearch.prefix').'schema', $schema);
$this->info("Set score index schema version to {$schema}");
}
}
|
Prepare logic to translate english data to supported languages | const promise = require("bluebird");
const { SUPPORTED_LANGUAGES } = require("./../constants.js");
const { find } = require("lodash");
const options = {
// Initialization Options
promiseLib: promise, // use bluebird as promise library
capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
var db;
checkConnection();
getLocalizationData();
function checkConnection() {
let config;
try {
config = parse(connectionString);
if (process.env.NODE_ENV === "test" || config.host === "localhost") {
config.ssl = false;
} else {
config.ssl = true;
}
} catch (e) {
console.error("# Error parsing DATABASE_URL environment variable");
}
db = pgp(config);
}
function getLocalizationData() {
db.any(`SELECT * FROM localized_texts`)
.then(function(data) {
data.forEach(data => {
SUPPORTED_LANGUAGES.forEach(language => {
if (language.twoLetterCode !== 'en') {
console.log(`Translate to -> ${language.twoLetterCode} - ${data.title}`);
}
});
});
})
.catch(function(error) {
console.log(error);
});
} | const promise = require("bluebird");
const { SUPPORTED_LANGUAGES } = require("./../constants.js");
const { find } = require("lodash");
const options = {
// Initialization Options
promiseLib: promise, // use bluebird as promise library
capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
var db;
checkConnection();
getLocalizationData();
function checkConnection() {
let config;
try {
config = parse(connectionString);
if (process.env.NODE_ENV === "test" || config.host === "localhost") {
config.ssl = false;
} else {
config.ssl = true;
}
} catch (e) {
console.error("# Error parsing DATABASE_URL environment variable");
}
db = pgp(config);
}
function getLocalizationData() {
db.any(`SELECT * FROM localized_texts`)
.then(function(data) {
data.forEach(data => {
});
})
.catch(function(error) {
console.log(error);
});
} |
Fix height of product title to avoid weird tile positioning | import React from 'react';
import PureComponent from '../components/purecomponent.react';
import ProductImage from './product-image.react';
export default class ProductTile extends PureComponent {
render() {
const title = this.props.product.get('title');
const productNumber = this.props.product.get('productNumber');
const normalizedName = this.props.product.get('normalizedName');
return (
<div style={{textAlign: 'center'}} className='col-xs-6 col-sm-4 col-md-3 col-lg-3'>
<div style={{height: '60px'}}>{title}</div>
<div><ProductImage productNumber={productNumber} normalizedName={normalizedName} alt={title}/></div>
</div>
);
}
}
ProductTile.propTypes = {
product: React.PropTypes.shape({get: React.PropTypes.func.isRequired}).isRequired
};
| import React from 'react';
import PureComponent from '../components/purecomponent.react';
import ProductImage from './product-image.react';
export default class ProductTile extends PureComponent {
render() {
const title = this.props.product.get('title');
const productNumber = this.props.product.get('productNumber');
const normalizedName = this.props.product.get('normalizedName');
return (
<div style={{textAlign: 'center'}} className='col-xs-6 col-sm-4 col-md-3 col-lg-3'>
<div>{title}</div>
<div><ProductImage productNumber={productNumber} normalizedName={normalizedName} alt={title}/></div>
</div>
);
}
}
ProductTile.propTypes = {
product: React.PropTypes.shape({get: React.PropTypes.func.isRequired}).isRequired
};
|
Rename binary filename to gifsicle | 'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/jihchi/giflossy-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'macos/gifsicle', 'darwin')
.src(url + 'linux/x86/gifsicle', 'linux', 'x86')
.src(url + 'linux/x64/gifsicle', 'linux', 'x64')
.src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86')
.src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64')
.src(url + 'win/x86/gifsicle.exe', 'win32', 'x86')
.src(url + 'win/x64/gifsicle.exe', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
| 'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/jihchi/giflossy-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'macos/giflossy', 'darwin')
.src(url + 'linux/x86/giflossy', 'linux', 'x86')
.src(url + 'linux/x64/giflossy', 'linux', 'x64')
.src(url + 'freebsd/x86/giflossy', 'freebsd', 'x86')
.src(url + 'freebsd/x64/giflossy', 'freebsd', 'x64')
.src(url + 'win/x86/giflossy.exe', 'win32', 'x86')
.src(url + 'win/x64/giflossy.exe', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'giflossy.exe' : 'giflossy');
|
Fix encoding (breaks for some configurations) | package openmods.utils;
import java.util.Random;
public class StringUtils {
public static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static Random rnd = new Random();
public static String randomString(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
public static String format(String str) {
boolean bold = false;
boolean italic = false;
StringBuilder builder = new StringBuilder();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c == '*') {
bold = !bold;
builder.append(getFormatter(bold, italic));
} else if (c == '`') {
italic = !italic;
builder.append(getFormatter(bold, italic));
} else {
builder.append(c);
}
}
return builder.toString().replaceAll("\\\\n", "\n");
}
public static String getFormatter(boolean bold, boolean italic) {
StringBuilder formatter = new StringBuilder();
formatter.append("\u00a7r");
if (bold) {
formatter.append("\u00a7l");
}
if (italic) {
formatter.append("\u00a7o");
}
return formatter.toString();
}
}
| package openmods.utils;
import java.util.Random;
public class StringUtils {
public static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static Random rnd = new Random();
public static String randomString(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
public static String format(String str) {
boolean bold = false;
boolean italic = false;
StringBuilder builder = new StringBuilder();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c == '*') {
bold = !bold;
builder.append(getFormatter(bold, italic));
} else if (c == '`') {
italic = !italic;
builder.append(getFormatter(bold, italic));
} else {
builder.append(c);
}
}
return builder.toString().replaceAll("\\\\n", "\n");
}
public static String getFormatter(boolean bold, boolean italic) {
StringBuilder formatter = new StringBuilder();
formatter.append("r");
if (bold) {
formatter.append("l");
}
if (italic) {
formatter.append("o");
}
return formatter.toString();
}
}
|
Fix order of imports to comply with isort | from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
|
Change image upload directory to images/ | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified, and can not be altered.
This model uses Django's built-ins for holding the image location and
data in the database, as well as for keeping created and modified
timestamps.
"""
image = models.ImageField(upload_to='images/')
caption = models.TextField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Vendor(models.Model):
"""
The Vendor model holds the information for a vendor, including the
geographic location as a pair of latitudinal/logitudinal coordinates,
a street address, and an optional text description of their location
(in case the address/coordinates are of, say, a dock instead of a shop).
"""
pass
| from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified, and can not be altered.
This model uses Django's built-ins for holding the image location and
data in the database, as well as for keeping created and modified
timestamps.
"""
image = models.ImageField(upload_to='/')
caption = models.TextField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
class Vendor(models.Model):
"""
The Vendor model holds the information for a vendor, including the
geographic location as a pair of latitudinal/logitudinal coordinates,
a street address, and an optional text description of their location
(in case the address/coordinates are of, say, a dock instead of a shop).
"""
pass
|
Update gallery ctrl with responsive service | angular.module('controllers', [])
.controller('NavCtrl', function ($scope, $state) {
$scope.state = $state.current.name
})
.controller('GalleryCtrl', function ($scope, json, responsive) {
var data = json.data
var width = 200
var max = 5
var resizeTimer
$scope.resolution = 0
$scope.columns = function () {
console.log($scope.resolution);
return new Array($scope.resolution);
}
$scope.chunk = function (column, resolution) {
var round = -1
return data.slice(0).filter(function (x, i, a) {
round++
if (round >= resolution) round = 0
if (round == column) return true
})
}
responsive.run(
function () {
$scope.$apply()
},
function (resolution) {
var number = Math.round($(window).width() / width)
if (number > max) number = max
$scope.resolution = number
}
)
})
}), 250)
})
})
.controller('PerformanceCtrl', function ($scope) {
})
.controller('ContactCtrl', function ($scope) {
})
| angular.module('controllers', [])
.controller('NavCtrl', function ($scope, $state) {
$scope.state = $state.current.name
})
.controller('GalleryCtrl', function ($scope, json) {
var data = json.data
var width = 200
var max = 5
var resizeTimer
$scope.resolution = 0
var size = function (callback) {
var number = Math.round($(window).width() / width)
if (number > max) number = max
$scope.resolution = number
if (arguments.length == 1) callback()
}
$scope.getColumns = function() {
return new Array($scope.resolution);
}
$scope.chunk = function (column, resolution) {
var round = -1
return data.slice(0).filter(function (x, i, a) {
round++
if (round >= resolution) round = 0
if (round == column) return true
})
}
size()
$(window).on('resize', function(e) {
clearTimeout(resizeTimer)
resizeTimer = setTimeout(size(function () {
$scope.$apply()
}), 250)
})
})
.controller('PerformanceCtrl', function ($scope) {
})
.controller('ContactCtrl', function ($scope) {
})
|
Add utility to save/load parameters, i.e. models.
Also adds a utility to compute the number of parameters, because that's
always interesting and often reported in papers. | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
| import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
|
Add menu cap to editor | <?php
/**
* Sage includes
*
* The $sage_includes array determines the code library included in your theme.
* Add or remove files to the array as needed. Supports child theme overrides.
*
* Please note that missing files will produce a fatal error.
*
* @link https://github.com/roots/sage/pull/1042
*/
$sage_includes = [
'lib/assets.php', // Scripts and stylesheets
'lib/extras.php', // Custom functions
'lib/setup.php', // Theme setup
'lib/titles.php', // Page titles
'lib/wrapper.php',
'lib/upload.php' // Theme wrapper class
];
foreach ($sage_includes as $file) {
if (!$filepath = locate_template($file)) {
trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR);
}
require_once $filepath;
}
unset($file, $filepath);
function myprefix_unregister_tags() {
unregister_taxonomy_for_object_type('post_tag', 'post');
}
add_action('init', 'myprefix_unregister_tags');
/**
* @var $roleObject WP_Role
*/
$roleObject = get_role( 'editor' );
if (!$roleObject->has_cap( 'edit_theme_options' ) ) {
$roleObject->add_cap( 'edit_theme_options' );
}
function hide_menu() {
global $submenu;
unset($submenu['themes.php'][6]); // remove customize link
remove_submenu_page( 'themes.php', 'themes.php' ); // hide the theme selection submenu
remove_submenu_page( 'themes.php', 'widgets.php' ); // hide the widgets submenu
}
add_action('admin_menu', 'hide_menu');
| <?php
/**
* Sage includes
*
* The $sage_includes array determines the code library included in your theme.
* Add or remove files to the array as needed. Supports child theme overrides.
*
* Please note that missing files will produce a fatal error.
*
* @link https://github.com/roots/sage/pull/1042
*/
$sage_includes = [
'lib/assets.php', // Scripts and stylesheets
'lib/extras.php', // Custom functions
'lib/setup.php', // Theme setup
'lib/titles.php', // Page titles
'lib/wrapper.php',
'lib/upload.php' // Theme wrapper class
];
foreach ($sage_includes as $file) {
if (!$filepath = locate_template($file)) {
trigger_error(sprintf(__('Error locating %s for inclusion', 'sage'), $file), E_USER_ERROR);
}
require_once $filepath;
}
unset($file, $filepath);
function myprefix_unregister_tags() {
unregister_taxonomy_for_object_type('post_tag', 'post');
}
add_action('init', 'myprefix_unregister_tags');
|
Remove pybitcointools in favor of bitcoin | """
pybitcoin
==============
"""
from setuptools import setup, find_packages
setup(
name='pybitcoin',
version='0.9.8',
url='https://github.com/blockstack/pybitcoin',
license='MIT',
author='Blockstack Developers',
author_email='hello@onename.com',
description="""Library for Bitcoin & other cryptocurrencies. Tools are provided for blockchain transactions, RPC calls, and private keys, public keys, and addresses.""",
keywords='bitcoin btc litecoin namecoin dogecoin cryptocurrency',
packages=find_packages(),
zip_safe=False,
install_requires=[
'requests>=2.4.3',
'ecdsa>=0.13',
'commontools==0.1.0',
'utilitybelt>=0.2.1',
'python-bitcoinrpc==0.1',
'keychain>=0.1.4',
'bitcoin>=1.1.39'
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet',
'Topic :: Security :: Cryptography',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| """
pybitcoin
==============
"""
from setuptools import setup, find_packages
setup(
name='pybitcoin',
version='0.9.8',
url='https://github.com/blockstack/pybitcoin',
license='MIT',
author='Blockstack Developers',
author_email='hello@onename.com',
description="""Library for Bitcoin & other cryptocurrencies. Tools are provided for blockchain transactions, RPC calls, and private keys, public keys, and addresses.""",
keywords='bitcoin btc litecoin namecoin dogecoin cryptocurrency',
packages=find_packages(),
zip_safe=False,
install_requires=[
'requests>=2.4.3',
'ecdsa>=0.13',
'commontools==0.1.0',
'utilitybelt>=0.2.1',
'pybitcointools==1.1.15',
'python-bitcoinrpc==0.1',
'keychain>=0.1.4',
'bitcoin>=1.1.39'
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet',
'Topic :: Security :: Cryptography',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Remove overlapping caption in ActionBar example | from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
| from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
text: 'Btn0'
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
|
Add `no_muxer=1` for filename searching | export var name = '射手网 (伪)'
export function search (name) {
let token = window.app.config.subtitleServices.shooterFake.token
return window.fetch(`http://api.assrt.net/v1/sub/search?token=${token}&q=${name}&cnt=10&no_muxer=1`)
.then(res => res.json())
.then(res => {
if (res.sub.subs.length) return res.sub.subs
else return []
})
.then(subs => {
subs.forEach(sub => {
sub.filelist = []
})
return subs
})
}
export function detail (id) {
let token = window.app.config.subtitleServices.shooterFake.token
return window.fetch(`http://api.assrt.net/v1/sub/detail?token=${token}&id=${id}`)
.then(res => res.json())
.then(res => {
return res.sub.subs[0] || {}
})
}
export function searchLink (name) {
return `http://assrt.net/sub/?searchword=${name}`
}
| export var name = '射手网 (伪)'
export function search (name) {
let token = window.app.config.subtitleServices.shooterFake.token
return window.fetch(`http://api.assrt.net/v1/sub/search?token=${token}&q=${name}&cnt=10`)
.then(res => res.json())
.then(res => {
if (res.sub.subs.length) return res.sub.subs
else return []
})
.then(subs => {
subs.forEach(sub => {
sub.filelist = []
})
return subs
})
}
export function detail (id) {
let token = window.app.config.subtitleServices.shooterFake.token
return window.fetch(`http://api.assrt.net/v1/sub/detail?token=${token}&id=${id}`)
.then(res => res.json())
.then(res => {
return res.sub.subs[0] || {}
})
}
export function searchLink (name) {
return `http://assrt.net/sub/?searchword=${name}`
}
|
Remove infinity from valid bounds | from citrination_client.views.descriptors.descriptor import MaterialDescriptor
class RealDescriptor(MaterialDescriptor):
def __init__(self, key, lower_bound, upper_bound, units=""):
self.options = dict(lower_bound=lower_bound, upper_bound=upper_bound, units=units)
super(RealDescriptor, self).__init__(key, "Real")
def validate(self):
raw_lower = self.options["lower_bound"]
raw_upper = self.options["upper_bound"]
try:
lower = float(str(raw_lower))
upper = float(str(raw_upper))
except ValueError:
raise ValueError(
"lower_bound and upper_bound must be floats but got {} and {} respectively".format(
raw_lower, raw_upper)
)
if lower > upper:
raise ValueError("Lower ({}) must be smaller than upper ({})".format(lower, upper))
| from citrination_client.views.descriptors.descriptor import MaterialDescriptor
class RealDescriptor(MaterialDescriptor):
def __init__(self, key, lower_bound="-Infinity", upper_bound="Infinity", units=""):
self.options = dict(lower_bound=lower_bound, upper_bound=upper_bound, units=units)
super(RealDescriptor, self).__init__(key, "Real")
def validate(self):
raw_lower = self.options["lower_bound"]
raw_upper = self.options["upper_bound"]
try:
lower = float(str(raw_lower).replace("Infinity", "inf"))
upper = float(str(raw_upper).replace("Infinity", "inf"))
except ValueError:
raise ValueError(
"lower_bound and upper_bound must be floats (or Infinity/-Infinity) but got {} and {} respectively".format(
raw_lower, raw_upper)
)
if lower > upper:
raise ValueError("Lower ({}) must be smaller than upper ({})".format(lower, upper))
|
Increase value column length in settings to 4000 | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('setting')->comment("Key");
$table->string('value',4000)->nullable()->comment("Value");
$table->boolean('more')->default(NULL);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('settings');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('setting');
$table->string('value')->nullable();
$table->boolean('more')->default(NULL);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('settings');
}
}
|
Test for sort_custom AND sort_default | <?php $sort_custom = $this->configuration->getValue('get.sort_custom'); ?>
<?php $sort_default = $this->configuration->getValue('get.sort_default'); ?>
<?php if ($sort_default || $sort_custom): ?>
/**
* Add sort clauses from "sort_default" and "sort_custom" fields
*
* @param Doctrine_Query $query The query to add joins to
* @param array &$params The filtered parameters for this request
*/
function querySort(Doctrine_Query $query, array &$params)
{
<?php if ($sort_default && count($sort_default) == 2): ?>
$sort = '<?php echo $sort_default[0] ?> <?php echo $sort_default[1] ?>';
<?php endif; ?>
<?php if ($sort_custom): ?>
if (isset($params['sort_by']))
{
$sort = $params['sort_by'];
unset($params['sort_by']);
if (isset($params['sort_order']))
{
$sort .= ' '.$params['sort_order'];
unset($params['sort_order']);
}
}
<?php endif; ?>
if (isset($sort))
{
$query->orderBy($sort);
}
}
<?php else: ?>
/* querySort function omitted, "sort_default" and "sort_custom" not set in
* generator config
*/
<?php endif; ?>
| <?php $sort_custom = $this->configuration->getValue('get.sort_custom'); ?>
<?php $sort_default = $this->configuration->getValue('get.sort_default'); ?>
<?php if ($sort_custom || $sort_custom): ?>
/**
* Add sort clauses from "sort_default" and "sort_custom" fields
*
* @param Doctrine_Query $query The query to add joins to
* @param array &$params The filtered parameters for this request
*/
function querySort(Doctrine_Query $query, array &$params)
{
<?php if ($sort_default && count($sort_default) == 2): ?>
$sort = '<?php echo $sort_default[0] ?> <?php echo $sort_default[1] ?>';
<?php endif; ?>
<?php if ($sort_custom): ?>
if (isset($params['sort_by']))
{
$sort = $params['sort_by'];
unset($params['sort_by']);
if (isset($params['sort_order']))
{
$sort .= ' '.$params['sort_order'];
unset($params['sort_order']);
}
}
<?php endif; ?>
if (isset($sort))
{
$query->orderBy($sort);
}
}
<?php else: ?>
/* querySort function omitted, "sort_default" and "sort_custom" not set in
* generator config
*/
<?php endif; ?>
|
Fix issue with management command log output and non ascii event names | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management import BaseCommand
from ...event import sync_events
class Command(BaseCommand):
def handle(self, *args, **options):
num_new_events, num_updated_ids, num_deleted_ids, \
unsynced_event_names = sync_events()
print("{} new events, {} event ids updated,"
" {} event ids deleted"
.format(num_new_events, num_updated_ids, num_deleted_ids))
if unsynced_event_names:
print("unsynced event names:\n {}"
.format('\n '.join(unsynced_event_names)))
| # -*- coding: utf-8 -*-
from django.core.management import BaseCommand
from ...event import sync_events
class Command(BaseCommand):
def handle(self, *args, **options):
num_new_events, num_updated_ids, num_deleted_ids, \
unsynced_event_names = sync_events()
print("{} new events, {} event ids updated,"
" {} event ids deleted"
.format(num_new_events, num_updated_ids, num_deleted_ids))
if unsynced_event_names:
print("unsynced event names:\n {}"
.format('\n '.join(unsynced_event_names)))
|
Fix typo in feature name | package de.linkvt.bachelor.features.axioms.classexpression;
import de.linkvt.bachelor.features.Feature;
import de.linkvt.bachelor.features.FeatureCategory;
import org.semanticweb.owlapi.model.OWLClass;
import org.springframework.stereotype.Component;
@Component
public class OwlAllDisjointClassesFeature extends Feature {
@Override
public void addToOntology() {
OWLClass opera = featurePool.getExclusiveClass(":Opera");
OWLClass operetta = featurePool.getExclusiveClass(":Operetta");
OWLClass musical = featurePool.getExclusiveClass(":Musical");
addAxiomToOntology(factory.getOWLDisjointClassesAxiom(opera, operetta, musical));
}
@Override
public String getName() {
return "owl:AllDisjointClasses";
}
@Override
public String getToken() {
return "alldisjointclasses";
}
@Override
public FeatureCategory getCategory() {
return FeatureCategory.CLASS_EXPRESSION_AXIOMS;
}
}
| package de.linkvt.bachelor.features.axioms.classexpression;
import de.linkvt.bachelor.features.Feature;
import de.linkvt.bachelor.features.FeatureCategory;
import org.semanticweb.owlapi.model.OWLClass;
import org.springframework.stereotype.Component;
@Component
public class OwlAllDisjointClassesFeature extends Feature {
@Override
public void addToOntology() {
OWLClass opera = featurePool.getExclusiveClass(":Opera");
OWLClass operetta = featurePool.getExclusiveClass(":Operetta");
OWLClass musical = featurePool.getExclusiveClass(":Musical");
addAxiomToOntology(factory.getOWLDisjointClassesAxiom(opera, operetta, musical));
}
@Override
public String getName() {
return "owl:AllDistjointClasses";
}
@Override
public String getToken() {
return "alldisjointclasses";
}
@Override
public FeatureCategory getCategory() {
return FeatureCategory.CLASS_EXPRESSION_AXIOMS;
}
}
|
Allow auto update for prerelease based on betaupdates setting | 'use strict';
const {app, dialog} = require('electron');
const {autoUpdater} = require('electron-updater');
const ConfigUtil = require('./../renderer/js/utils/config-util.js');
function appUpdater() {
// Log whats happening
const log = require('electron-log');
log.transports.file.level = 'info';
autoUpdater.logger = log;
autoUpdater.allowPrerelease = ConfigUtil.getConfigItem('BetaUpdate');
// Ask the user if update is available
// eslint-disable-next-line no-unused-vars
autoUpdater.on('update-downloaded', (event, info) => {
// Ask user to update the app
dialog.showMessageBox({
type: 'question',
buttons: ['Install and Relaunch', 'Later'],
defaultId: 0,
message: 'A new version of ' + app.getName() + ' has been downloaded',
detail: 'It will be installed the next time you restart the application'
}, response => {
if (response === 0) {
setTimeout(() => autoUpdater.quitAndInstall(), 1);
}
});
});
// Init for updates
autoUpdater.checkForUpdates();
}
module.exports = {
appUpdater
};
| 'use strict';
const {app, dialog} = require('electron');
const {autoUpdater} = require('electron-updater');
function appUpdater() {
// Log whats happening
const log = require('electron-log');
log.transports.file.level = 'info';
autoUpdater.logger = log;
autoUpdater.allowPrerelease = false;
// Ask the user if update is available
// eslint-disable-next-line no-unused-vars
autoUpdater.on('update-downloaded', (event, info) => {
// Ask user to update the app
dialog.showMessageBox({
type: 'question',
buttons: ['Install and Relaunch', 'Later'],
defaultId: 0,
message: 'A new version of ' + app.getName() + ' has been downloaded',
detail: 'It will be installed the next time you restart the application'
}, response => {
if (response === 0) {
setTimeout(() => autoUpdater.quitAndInstall(), 1);
}
});
});
// Init for updates
autoUpdater.checkForUpdates();
}
module.exports = {
appUpdater
};
|
Reduce time window between posts to 3 hours | import json
import logging
import os
import subprocess
from celery import Celery
from celery.schedules import crontab
from whistleblower.targets.twitter import Post as TwitterPost
import whistleblower.queue
HOUR = 3600
ENABLED_TARGETS = [
TwitterPost,
]
RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//')
app = Celery('tasks', broker=RABBITMQ_URL)
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
sender.add_periodic_task(3 * HOUR, process_queue.s())
@app.task
def update_queue():
whistleblower.queue.Queue().update()
@app.task
def process_queue():
whistleblower.queue.Queue().process()
@app.task
def publish_reimbursement(reimbursement):
for target in ENABLED_TARGETS:
target(reimbursement).publish()
| import json
import logging
import os
import subprocess
from celery import Celery
from celery.schedules import crontab
from whistleblower.targets.twitter import Post as TwitterPost
import whistleblower.queue
HOUR = 3600
ENABLED_TARGETS = [
TwitterPost,
]
RABBITMQ_URL = os.environ.get('CLOUDAMQP_URL', 'pyamqp://guest@localhost//')
app = Celery('tasks', broker=RABBITMQ_URL)
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
sender.add_periodic_task(4 * HOUR, process_queue.s())
@app.task
def update_queue():
whistleblower.queue.Queue().update()
@app.task
def process_queue():
whistleblower.queue.Queue().process()
@app.task
def publish_reimbursement(reimbursement):
for target in ENABLED_TARGETS:
target(reimbursement).publish()
|
Set content type of package desription | #! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7',
author='oemof developer group',
url='https://oemof.org/',
license='MIT',
author_email='contact@oemof.org',
description='Demandlib of the open energy modelling framework',
long_description=read('README.rst'),
long_description_content_type='text/x-rst',
packages=find_packages(),
install_requires=['numpy >= 1.17.0',
'pandas >= 1.0'],
package_data={
'demandlib': [os.path.join('bdew_data', '*.csv')],
'demandlib.examples': ['*.csv']},
)
| #! /usr/bin/env python
"""Setup information of demandlib.
"""
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='demandlib',
version='0.1.7',
author='oemof developer group',
url='https://oemof.org/',
license='MIT',
author_email='contact@oemof.org',
description='Demandlib of the open energy modelling framework',
long_description=read('README.rst'),
packages=find_packages(),
install_requires=['numpy >= 1.17.0',
'pandas >= 1.0'],
package_data={
'demandlib': [os.path.join('bdew_data', '*.csv')],
'demandlib.examples': ['*.csv']},
)
|
Add proxy method for python2 iterator support | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iterator logic."""
self.current = None
return self
def __next__(self):
"""Implement iterator logic."""
if self.current is None:
self.current = 0
else:
self.current += 1
try:
item = self['_embedded'][self.get_object_name()][self.current]
return self.object_type(item)
except IndexError:
raise StopIteration
next = __next__ # support python2 iterator interface
@property
def count(self):
if 'count' not in self:
return None
return int(self['count'])
def get_offset(self):
if 'offset' not in self:
return None
return self['offset']
| from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iterator logic."""
self.current = None
return self
def __next__(self):
"""Implement iterator logic."""
if self.current is None:
self.current = 0
else:
self.current += 1
try:
item = self['_embedded'][self.get_object_name()][self.current]
return self.object_type(item)
except IndexError:
raise StopIteration
@property
def count(self):
if 'count' not in self:
return None
return int(self['count'])
def get_offset(self):
if 'offset' not in self:
return None
return self['offset']
|
Add bigger delay to scroll component | import { PureComponent } from 'react';
import PropTypes from 'prop-types';
const isServer = typeof window === 'undefined';
class ScrollTo extends PureComponent {
// eslint-disable-line react/prefer-stateless-function
componentDidMount() {
setTimeout(this.handleScroll, this.props.delay);
}
handleFadeOut = (el) => {
el.style.backgroundColor = null; // eslint-disable-line
};
handleFadeIn = (el) => {
const initialColor = el.style.backgroundColor;
el.style.transition = 'background-color 1.5s linear'; // eslint-disable-line
el.style.backgroundColor = '#fefedc'; // eslint-disable-line
setTimeout(() => this.handleFadeOut(el, initialColor), 5000);
};
handleScroll = () => {
const { target, afterScroll } = this.props;
if (target && !isServer) {
const targetBox = target.getBoundingClientRect();
window.scrollTo({
behavior: 'smooth',
left: 0,
top: targetBox.top - 100,
});
this.handleFadeIn(target);
}
afterScroll();
};
render() {
return null;
}
}
ScrollTo.propTypes = {
target: PropTypes.object,
delay: PropTypes.number,
afterScroll: PropTypes.number,
};
ScrollTo.defaultProps = {
delay: 2000,
};
export default ScrollTo;
| import { PureComponent } from 'react';
import PropTypes from 'prop-types';
const isServer = typeof window === 'undefined';
class ScrollTo extends PureComponent {
// eslint-disable-line react/prefer-stateless-function
componentDidMount() {
setTimeout(this.handleScroll, this.props.delay);
}
handleFadeOut = el => {
el.style.backgroundColor = null; // eslint-disable-line
};
handleFadeIn = el => {
const initialColor = el.style.backgroundColor;
el.style.transition = 'background-color 1.5s linear'; // eslint-disable-line
el.style.backgroundColor = '#fefedc'; // eslint-disable-line
setTimeout(() => this.handleFadeOut(el, initialColor), 5000);
};
handleScroll = () => {
const { target, afterScroll } = this.props;
if (target && !isServer) {
const targetBox = target.getBoundingClientRect();
window.scrollTo({
behavior: 'smooth',
left: 0,
top: targetBox.top - 100
});
this.handleFadeIn(target);
}
afterScroll();
};
render() {
return null;
}
}
ScrollTo.propTypes = {
target: PropTypes.object,
delay: PropTypes.number,
afterScroll: PropTypes.number
};
ScrollTo.defaultProps = {
delay: 500
};
export default ScrollTo;
|
Update required version of easy-thumbnails
So we avoid deprecation warnings with Django 1.5 | from distutils.core import setup
from setuptools import setup, find_packages
setup(name = "django-image-cropping",
version = "0.6.3",
description = "A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author = "jonasvp",
author_email = "jvp@jonasundderwolf.de",
url = "http://github.com/jonasundderwolf/django-image-cropping",
#Name the folder where your packages live:
#(If you have other packages (dirs) or modules (py files) then
#put them into the package directory - they will be found
#recursively.)
packages = find_packages(),
include_package_data=True,
install_requires = [
'easy_thumbnails==1.2',
],
test_suite='example.runtests.runtests',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from distutils.core import setup
from setuptools import setup, find_packages
setup(name = "django-image-cropping",
version = "0.6.3",
description = "A reusable app for cropping images easily and non-destructively in Django",
long_description=open('README.rst').read(),
author = "jonasvp",
author_email = "jvp@jonasundderwolf.de",
url = "http://github.com/jonasundderwolf/django-image-cropping",
#Name the folder where your packages live:
#(If you have other packages (dirs) or modules (py files) then
#put them into the package directory - they will be found
#recursively.)
packages = find_packages(),
include_package_data=True,
install_requires = [
'easy_thumbnails==1.1',
],
test_suite='example.runtests.runtests',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Use a chrome window to provide a better notification fallback on OSX when growl isn't installed. | var EXPORTED_SYMBOLS = ["GM_notification"];
var Cc = Components.classes;
var Ci = Components.interfaces;
// The first time this runs, we check if nsIAlertsService is installed and
// works. If it fails, we re-define notify to use a chrome window.
// We check to see if nsIAlertsService works because of the case where Growl
// is not installed. See also https://bugzilla.mozilla.org/show_bug.cgi?id=597165
function notify() {
try {
Cc["@mozilla.org/alerts-service;1"]
.getService(Ci.nsIAlertsService)
.showAlertNotification.apply(null, arguments);
} catch (e) {
notify = function() {
Cc['@mozilla.org/embedcomp/window-watcher;1']
.getService(Ci.nsIWindowWatcher)
.openWindow(null, 'chrome://global/content/alerts/alert.xul',
'_blank', 'chrome,titlebar=no,popup=yes', null)
.arguments = Array.prototype.slice.call(arguments);
};
notify.apply(null, arguments);
}
}
function GM_notification(aMsg, aTitle) {
var title = aTitle ? "" + aTitle : "Greasemonkey";
var message = aMsg ? "" + aMsg : "";
notify(
"chrome://greasemonkey/skin/icon32.png",
title, message, false, "", null);
}; | var EXPORTED_SYMBOLS = ["GM_notification"];
var Cc = Components.classes;
var Ci = Components.interfaces;
// The first time this runs, we check if nsIAlertsService is installed and
// works. If it fails, we re-define notify to use nsIPromptService always.
// We check to see if nsIAlertsService works because of the case where Growl
// is installed. See also https://bugzilla.mozilla.org/show_bug.cgi?id=597165
function notify() {
try {
Cc["@mozilla.org/alerts-service;1"]
.getService(Ci.nsIAlertsService)
.showAlertNotification.apply(null, arguments);
} catch (e) {
notify = function() {
Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService)
.alert(null, "Greasemonkey alert", arguments[2]);
};
notify.apply(null, arguments);
}
}
function GM_notification(aMsg, aTitle) {
var title = aTitle ? "" + aTitle : "Greasemonkey";
var message = aMsg ? "" + aMsg : "";
notify(
"chrome://greasemonkey/skin/icon32.png",
title, message, false, "", null);
};
|
Fix CIPANGO-99: Creating a DiameterServletRequest without specifying the destinationhost field leads to a null pointer exception when sending a the request
git-svn-id: a3e743b3c7f6e97b9a019791beffa901f5d7f1d1@506 657f710f-be33-0410-a596-71a6d81f68ef | // ========================================================================
// Copyright 2010 NEXCOM 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 org.cipango.diameter.router;
import java.util.Hashtable;
import java.util.Map;
import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Peer;
public class DefaultRouter implements DiameterRouter
{
private Map<String, Peer> _peers = new Hashtable<String, Peer>();
public Peer getRoute(DiameterRequest request)
{
if (request.getDestinationHost() == null)
return null;
return _peers.get(request.getDestinationHost());
}
public void peerAdded(Peer peer)
{
_peers.put(peer.getHost(), peer);
}
public void peerRemoved(Peer peer)
{
_peers.remove(peer.getHost());
}
}
| // ========================================================================
// Copyright 2010 NEXCOM 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 org.cipango.diameter.router;
import java.util.Hashtable;
import java.util.Map;
import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Node;
import org.cipango.diameter.node.Peer;
public class DefaultRouter implements DiameterRouter
{
private Map<String, Peer> _peers = new Hashtable<String, Peer>();
public Peer getRoute(DiameterRequest request)
{
return _peers.get(request.getDestinationHost());
}
public void peerAdded(Peer peer)
{
_peers.put(peer.getHost(), peer);
}
public void peerRemoved(Peer peer)
{
_peers.remove(peer.getHost());
}
}
|
Update to work with new method of storing extension data. | ###################################################################################################
#
# chrome_extensions.py
# Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field
#
# Plugin Author: Ryan Benson (ryan@obsidianforensics.com)
#
###################################################################################################
import re
# Config
friendlyName = "Chrome Extension Names"
description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field"
artifactTypes = ["url", "url (archived)"]
remoteLookups = 0
browser = "Chrome"
browserVersion = 1
version = "20150117"
parsedItems = 0
def plugin(target_browser):
extension_re = re.compile(r'^chrome-extension://([a-z]{32})')
global parsedItems
for item in target_browser.parsed_artifacts:
if item.row_type in artifactTypes:
if item.interpretation is None:
m = re.search(extension_re, item.url)
if m:
for ext in target_browser.installed_extensions['data']:
if ext.app_id == m.group(1):
item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description)
parsedItems += 1
# Description of what the plugin did
return "%s extension URLs parsed" % parsedItems | ###################################################################################################
#
# chrome_extensions.py
# Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field
#
# Plugin Author: Ryan Benson (ryan@obsidianforensics.com)
#
###################################################################################################
import re
# Config
friendlyName = "Chrome Extension Names"
description = "Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field"
artifactTypes = ["url", "url (archived)"]
remoteLookups = 0
browser = "Chrome"
browserVersion = 1
version = "20140813"
parsedItems = 0
def plugin(target_browser):
extension_re = re.compile(r'^chrome-extension://([a-z]{32})')
global parsedItems
for item in target_browser.parsed_artifacts:
if item.row_type in artifactTypes:
if item.interpretation is None:
m = re.search(extension_re, item.url)
if m:
for ext in target_browser.installed_extensions:
if ext.app_id == m.group(1):
item.interpretation = "%s (%s) [Chrome Extension]" % (ext.name, ext.description)
parsedItems += 1
# Description of what the plugin did
return "%s extension URLs parsed" % parsedItems |
fix: Remove assert_called for Python 3.5 compatibility | import unittest
import tabula
try:
FileNotFoundError
from unittest.mock import patch, MagicMock
from urllib.request import Request
except NameError:
FileNotFoundError = IOError
from mock import patch, MagicMock
from urllib2 import Request
class TestUtil(unittest.TestCase):
def test_environment_info(self):
self.assertEqual(tabula.environment_info(), None)
@patch('tabula.file_util.shutil.copyfileobj')
@patch('tabula.file_util.urlopen')
@patch('tabula.file_util._create_request')
def test_localize_file_with_user_agent(self, mock_fun, mock_urlopen, mock_copyfileobj):
uri = "https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/12s0324.pdf"
user_agent='Mozilla/5.0'
cm = MagicMock()
cm.getcode.return_value = 200
cm.read.return_value = b'contents'
cm.geturl.return_value = uri
mock_urlopen.return_value = cm
tabula.file_util.localize_file(uri, user_agent=user_agent)
mock_fun.assert_called_with(uri, user_agent)
if __name__ == '__main__':
unittest.main()
| import unittest
import tabula
try:
FileNotFoundError
from unittest.mock import patch, MagicMock
from urllib.request import Request
except NameError:
FileNotFoundError = IOError
from mock import patch, MagicMock
from urllib2 import Request
class TestUtil(unittest.TestCase):
def test_environment_info(self):
self.assertEqual(tabula.environment_info(), None)
@patch('tabula.file_util.shutil.copyfileobj')
@patch('tabula.file_util.urlopen')
@patch('tabula.file_util._create_request')
def test_localize_file_with_user_agent(self, mock_fun, mock_urlopen, mock_copyfileobj):
uri = "https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/12s0324.pdf"
user_agent='Mozilla/5.0'
cm = MagicMock()
cm.getcode.return_value = 200
cm.read.return_value = b'contents'
cm.geturl.return_value = uri
mock_urlopen.return_value = cm
tabula.file_util.localize_file(uri, user_agent=user_agent)
mock_fun.assert_called_with(uri, user_agent)
mock_urlopen.assert_called()
mock_copyfileobj.assert_called()
if __name__ == '__main__':
unittest.main()
|
4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
#
# License: Apache 2.0
#
# TODO: Create a menu for file selection
import ibmcnx.filehandle
import sys
emp1 = ibmcnx.filehandle.Ibmcnxfile()
sys.stdout = emp1
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
#
# License: Apache 2.0
#
# TODO: Create a menu for file selection
import ibmcnx.filehandle
import sys
sys.stdout = open("/tmp/documentation.txt", "w")
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) |
Implement forEach on send sms | var util = require('util');
var _ = require('lodash');
var Promise = require('bluebird');
var twilio = require('twilio');
var BaseSms = require('./BaseSms');
util.inherits(TwilioSms, BaseSms);
/**
* Create new Twilio SMS
* @constructor
*/
function TwilioSms() {
BaseSms.apply(this, arguments);
this.setProvider(twilio(this.get('provider.accountSid'), this.get('provider.authToken')));
}
/**
* Send message to the recipient
* @returns {Promise}
* @private
*/
TwilioSms.prototype._send = function (config) {
return new Promise(function (resolve, reject) {
this.getProvider().messages.create(config, function (error, message) {
return error ? reject(error) : resolve(message);
});
}.bind(this));
};
/**
* Send message
* @param {Object} [_config] Additional configuration
* @returns {Promise}
*/
TwilioSms.prototype.send = function (_config) {
var config = _.merge({}, _.omit(this.get(), 'provider'), _config);
var promises = [];
for (var i = 0; i < config.recipient.length; i++) {
promises.push(this._send({
from: config.sender,
to: config.recipient[i],
body: config.message
}));
}
return Promise.all(promises);
};
module.exports = TwilioSms;
| var util = require('util');
var _ = require('lodash');
var Promise = require('bluebird');
var twilio = require('twilio');
var BaseSms = require('./BaseSms');
util.inherits(TwilioSms, BaseSms);
/**
* Create new Twilio SMS
* @constructor
*/
function TwilioSms() {
BaseSms.apply(this, arguments);
this.setProvider(twilio(this.get('provider.accountSid'), this.get('provider.authToken')));
}
/**
* Send message
* @param {Object} [_config] Additional configuration
* @returns {Promise}
*/
TwilioSms.prototype.send = function (_config) {
var config = _.merge({}, _.omit(this.get(), 'provider'), _config);
return new Promise(function (resolve, reject) {
this.getProvider().messages.create({
from: config.sender,
to: config.recipient,
body: config.message
}, function (error, message) {
return error ? reject(error) : resolve(message);
});
}.bind(this));
};
module.exports = TwilioSms;
|
Fix new i18n utils imports. | # -*- coding: utf-8 -*-
from .i18n import (get_language_name,
get_language,
get_fallback_language,
get_real_field_name,
get_fallback_field_name,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template_name
from .views import get_language_parameter, get_language_tabs
__all__ = [
'get_language_name',
'get_language',
'get_fallback_language',
'build_localized_field_name',
'build_localized_verbose_name',
'load_class',
'get_model_string',
'select_template_name',
'get_language_parameter',
'get_language_tabs',
'chunks',
]
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
| # -*- coding: utf-8 -*-
from .i18n import (get_language_name,
get_language,
get_fallback_language,
build_localized_field_name,
build_localized_verbose_name)
from .models import load_class, get_model_string
from .template import select_template_name
from .views import get_language_parameter, get_language_tabs
__all__ = [
'get_language_name',
'get_language',
'get_fallback_language',
'build_localized_field_name',
'build_localized_verbose_name',
'load_class',
'get_model_string',
'select_template_name',
'get_language_parameter',
'get_language_tabs',
'chunks',
]
def chunks(l, n):
"""
Yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
|
Add an additional post gen hook to remove the jinja2 templates | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('post_gen_project')
import shutil
import os
{% if cookiecutter.docs_tool == "mkdocs" %}
logger.info('Moving files for mkdocs.')
os.rename('mkdocs/mkdocs.yml', 'mkdocs.yml')
shutil.move('mkdocs', 'docs')
shutil.rmtree('sphinxdocs')
{% elif cookiecutter.docs_tool == "sphinx" %}
logger.info('Moving files for sphinx.')
shutil.move('sphinxdocs', 'docs')
shutil.rmtree('mkdocs')
{% else %}
logger.info('Removing all documentation files')
shutil.rmtree('mkdocs')
shutil.rmtree('sphinxdocs')
{% endif %}
logger.info('Removing jinja2 macros')
shutil.rmtree('macros')
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('post_gen_project')
import shutil
import os
{% if cookiecutter.docs_tool == "mkdocs" %}
logger.info('Moving files for mkdocs.')
os.rename('mkdocs/mkdocs.yml', 'mkdocs.yml')
shutil.move('mkdocs', 'docs')
shutil.rmtree('sphinxdocs')
{% elif cookiecutter.docs_tool == "sphinx" %}
logger.info('Moving files for sphinx.')
shutil.move('sphinxdocs', 'docs')
shutil.rmtree('mkdocs')
{% else %}
logger.info('Removing all documentation files')
shutil.rmtree('mkdocs')
shutil.rmtree('sphinxdocs')
{% endif %}
|
Revert the default DNS lookup order to IPv4-first
Fix #467 | 'use strict';
const EventEmitter = require('events');
const dns = require('dns');
const devtools = require('./lib/devtools.js');
const Chrome = require('./lib/chrome.js');
// XXX reset the default that has been changed in
// (https://github.com/nodejs/node/pull/39987) to prefer IPv4. since
// implementations alway bind on 127.0.0.1 this solution should be fairly safe
// (see #467)
dns.setDefaultResultOrder('ipv4first');
function CDP(options, callback) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
const notifier = new EventEmitter();
if (typeof callback === 'function') {
// allow to register the error callback later
process.nextTick(() => {
new Chrome(options, notifier);
});
return notifier.once('connect', callback);
} else {
return new Promise((fulfill, reject) => {
notifier.once('connect', fulfill);
notifier.once('error', reject);
new Chrome(options, notifier);
});
}
}
module.exports = CDP;
module.exports.Protocol = devtools.Protocol;
module.exports.List = devtools.List;
module.exports.New = devtools.New;
module.exports.Activate = devtools.Activate;
module.exports.Close = devtools.Close;
module.exports.Version = devtools.Version;
| 'use strict';
const EventEmitter = require('events');
const devtools = require('./lib/devtools.js');
const Chrome = require('./lib/chrome.js');
function CDP(options, callback) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
const notifier = new EventEmitter();
if (typeof callback === 'function') {
// allow to register the error callback later
process.nextTick(() => {
new Chrome(options, notifier);
});
return notifier.once('connect', callback);
} else {
return new Promise((fulfill, reject) => {
notifier.once('connect', fulfill);
notifier.once('error', reject);
new Chrome(options, notifier);
});
}
}
module.exports = CDP;
module.exports.Protocol = devtools.Protocol;
module.exports.List = devtools.List;
module.exports.New = devtools.New;
module.exports.Activate = devtools.Activate;
module.exports.Close = devtools.Close;
module.exports.Version = devtools.Version;
|
[Socket] Read raw stream when using Socket server (no stream) | <?php
namespace React\Socket;
use React\Stream\Stream;
class Connection extends Stream implements ConnectionInterface
{
public function handleData($stream)
{
$data = stream_socket_recvfrom($stream, $this->bufferSize);
if ('' === $data || false === $data || feof($stream)) {
$this->end();
} else {
$this->emit('data', array($data, $this));
}
}
public function handleClose()
{
if (is_resource($this->stream)) {
stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
fclose($this->stream);
}
}
public function getRemoteAddress()
{
return $this->parseAddress(stream_socket_get_name($this->stream, true));
}
private function parseAddress($address)
{
return trim(substr($address, 0, strrpos($address, ':')), '[]');
}
}
| <?php
namespace React\Socket;
use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;
class Connection extends Stream implements ConnectionInterface
{
public function handleData($stream)
{
$data = fread($stream, $this->bufferSize);
if ('' === $data || false === $data) {
$this->end();
} else {
$this->emit('data', array($data, $this));
}
}
public function handleClose()
{
if (is_resource($this->stream)) {
stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
fclose($this->stream);
}
}
public function getRemoteAddress()
{
return $this->parseAddress(stream_socket_get_name($this->stream, true));
}
private function parseAddress($address)
{
return trim(substr($address, 0, strrpos($address, ':')), '[]');
}
}
|
bugfix: Fix test for method made protected. | <?php
class sspmod_ldap_Auth_Process_BaseFilter_Test extends PHPUnit_Framework_TestCase
{
public function testVarExportHidesLdapPassword()
{
$stub = $this->getMockBuilder('sspmod_ldap_Auth_Process_BaseFilter')
->disableOriginalConstructor()
->getMockForAbstractClass();
$class = new \ReflectionClass($stub);
$method = $class->getMethod('var_export');
$method->setAccessible(true);
$this->assertEquals(
"array ( 'ldap.hostname' => 'ldap://172.17.101.32', 'ldap.port' => 389, 'ldap.password' => '********', )",
$method->invokeArgs($stub, array(array(
'ldap.hostname' => 'ldap://172.17.101.32',
'ldap.port' => 389,
'ldap.password' => 'password',
)))
);
}
}
| <?php
class sspmod_ldap_Auth_Process_BaseFilter_Test extends PHPUnit_Framework_TestCase
{
public function testVarExportHidesLdapPassword()
{
$stub = $this->getMockBuilder('sspmod_ldap_Auth_Process_BaseFilter')
->disableOriginalConstructor()
->getMockForAbstractClass();
$this->assertEquals(
"array ( 'ldap.hostname' => 'ldap://172.17.101.32', 'ldap.port' => 389, 'ldap.password' => '********', )",
$stub->var_export(array(
'ldap.hostname' => 'ldap://172.17.101.32',
'ldap.port' => 389,
'ldap.password' => 'password',
))
);
}
}
|
Reset upload component on tag switch
Closes #4755 | var TagsSettingsMenuView = Ember.View.extend({
saveText: Ember.computed('controller.model.isNew', function () {
return this.get('controller.model.isNew') ?
'Add Tag' :
'Save Tag';
}),
// This observer loads and resets the uploader whenever the active tag changes,
// ensuring that we can reuse the whole settings menu.
updateUploader: Ember.observer('controller.activeTag.image', 'controller.uploaderReference', function () {
var uploader = this.get('controller.uploaderReference'),
image = this.get('controller.activeTag.image');
if (uploader && uploader[0]) {
if (image) {
uploader[0].uploaderUi.initWithImage();
} else {
uploader[0].uploaderUi.reset();
}
}
})
});
export default TagsSettingsMenuView;
| var TagsSettingsMenuView = Ember.View.extend({
saveText: Ember.computed('controller.model.isNew', function () {
return this.get('controller.model.isNew') ?
'Add Tag' :
'Save Tag';
}),
// This observer loads and resets the uploader whenever the active tag changes,
// ensuring that we can reuse the whole settings menu.
updateUploader: Ember.observer('controller.activeTag.image', 'controller.uploaderReference', function () {
var uploader = this.get('controller.uploaderReference'),
image = this.get('controller.activeTag.image');
if (uploader && uploader[0]) {
if (image) {
uploader[0].uploaderUi.initWithImage();
} else {
uploader[0].uploaderUi.initWithDropzone();
}
}
})
});
export default TagsSettingsMenuView;
|
Change timestamp key to time to resolve issues with fluentd | package com.spotify.logging.logback;
import net.logstash.logback.encoder.LogstashEncoder;
import net.logstash.logback.fieldnames.LogstashFieldNames;
public class CustomLogstashEncoder extends LogstashEncoder {
private final LogstashFieldNames logstashFieldNames = new LogstashFieldNames();
{
// These are fields we want ignored for all LogstashEncoders
logstashFieldNames.setLevelValue("[ignore]");
logstashFieldNames.setVersion("[ignore]");
}
public CustomLogstashEncoder() {
super();
}
public CustomLogstashEncoder setupStackdriver() {
// Setup fields according to https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
logstashFieldNames.setTimestamp("time");
logstashFieldNames.setLevel("severity");
this.setFieldNames(logstashFieldNames);
return this;
}
}
| package com.spotify.logging.logback;
import net.logstash.logback.encoder.LogstashEncoder;
import net.logstash.logback.fieldnames.LogstashFieldNames;
public class CustomLogstashEncoder extends LogstashEncoder {
private final LogstashFieldNames logstashFieldNames = new LogstashFieldNames();
{
// These are fields we want ignored for all LogstashEncoders
logstashFieldNames.setLevelValue("[ignore]");
logstashFieldNames.setVersion("[ignore]");
}
public CustomLogstashEncoder() {
super();
}
public CustomLogstashEncoder setupStackdriver() {
// Setup fields according to https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
logstashFieldNames.setTimestamp("timestamp");
logstashFieldNames.setLevel("severity");
this.setFieldNames(logstashFieldNames);
return this;
}
}
|
Add test program ids, unfortunately none seem to give a playable url | #!/usr/bin/php -q
<?php
require_once('lib/YleApi.php');
if (file_exists("config.ini"))
$config=parse_ini_file("config.ini", true);
else
die('Configuration file config.ini is missing');
$api=$config['Generic'];
// TV/Video
//$pid='1-2897178';
//$pid='1-3088770';
//$pid='26-44376';
//$pid='1-2347105';
// Radio
//$pid='1-3045411';
$pid='4-4746868';
$c=new YleApiClient($api['app_id'], $api['app_key'], $api['decrypt']);
$c->set_debug(true);
$a=$c->programs_item($pid);
print_r($a);
$mid=$c->media_find_ondemand_publication_media_id($a);
if ($mid===false)
die('Failed to find ondemand media!');
$a=$c->media_playouts($pid, $mid);
print_r($a);
$eurl=$a->data[0]->url;
$url=$c->media_url_decrypt($eurl);
printf("Media URL is:\n\n%s\n\n", $url);
system("mplayer \"$url\"");
?>
| #!/usr/bin/php -q
<?php
require_once('lib/YleApi.php');
if (file_exists("config.ini"))
$config=parse_ini_file("config.ini", true);
else
die('Configuration file config.ini is missing');
$api=$config['Generic'];
$pid='1-2897178';
$c=new YleApiClient($api['app_id'], $api['app_key'], $api['decrypt']);
$c->set_debug(true);
$a=$c->programs_item($pid);
$mid=$c->media_find_ondemand_publication_media_id($a);
if ($mid===false)
die('Failed to find ondemand media!');
$a=$c->media_playouts($pid, $mid);
print_r($a);
$eurl=$a->data[0]->url;
$url=$c->media_url_decrypt($eurl);
printf("Media URL is:\n\n%s\n\n", $url);
system("mplayer \"$url\"");
?>
|
Handle non existing data files in BaseParser. | import logging
from os import path
import linkedin_scraper
logger = logging.getLogger(__name__)
class BaseParser:
@staticmethod
def get_data_dir():
return path.abspath(path.join(linkedin_scraper.__file__,
'../..', 'data'))
@staticmethod
def normalize_lines(lines):
return set(line.lower().strip() for line in lines)
def get_lines_from_datafile(self, name: str) -> set:
"""
Get and normalize lines from datafile.
:param name: name of the file in package data directory
"""
try:
with open(path.join(self.get_data_dir(), name)) as f:
return self.normalize_lines(f)
except FileNotFoundError:
logger.error('%s not found', name)
return set()
def parse(self, item):
raise NotImplemented()
| from os import path
import linkedin_scraper
class BaseParser:
@staticmethod
def get_data_dir():
return path.abspath(path.join(linkedin_scraper.__file__,
'../..', 'data'))
@staticmethod
def normalize_lines(lines):
return set(line.lower().strip() for line in lines)
def get_lines_from_datafile(self, name: str) -> set:
"""
Get and normalize lines from datafile.
:param name: name of the file in package data directory
"""
with open(path.join(self.get_data_dir(), name)) as f:
return self.normalize_lines(f)
def parse(self, item):
raise NotImplemented()
|
Reorder items in the config | <?php
return [
/*
|--------------------------------------------------------------------------
| Domains
|--------------------------------------------------------------------------
|
| It's recommended to use 2-3 domain shards maximum if you are going
| to use domain sharding.
|
*/
'domains' => [
// 'cdn-1.imgix.net',
// 'cdn-2.imgix.net'
],
/*
|--------------------------------------------------------------------------
| Use Https
|--------------------------------------------------------------------------
|
*/
'useHttps' => false,
/*
|--------------------------------------------------------------------------
| Sign Key
|--------------------------------------------------------------------------
|
| To produce a signed URL, you must enable secure URLs on your source
| and then provide your signature key to the URL builder.
|
*/
'signKey' => '',
/*
|--------------------------------------------------------------------------
| Sharding Strategy
|--------------------------------------------------------------------------
|
| Domain sharding enables you to spread image requests across multiple
| domains. This allows you to bypass the requests-per-host limits of
| browsers.
|
| Available settings:
| - \Imgix\ShardStrategy::CRC
| - \Imgix\ShardStrategy::CYCLE
|
*/
'shardStrategy' => \Imgix\ShardStrategy::CRC,
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Sharding
|--------------------------------------------------------------------------
|
| Domain sharding enables you to spread image requests across multiple
| domains. This allows you to bypass the requests-per-host limits of
| browsers.
|
| Available Settings:
| - \Imgix\ShardStrategy::CRC
| - \Imgix\ShardStrategy::CYCLE
|
*/
'sharding' => \Imgix\ShardStrategy::CRC,
/*
|--------------------------------------------------------------------------
| Domains
|--------------------------------------------------------------------------
|
| It's recommended to use 2-3 domain shards maximum if you are going
| to use domain sharding.
|
*/
'domains' => [
// 'cdn-1.imgix.net',
// 'cdn-2.imgix.net'
],
/*
|--------------------------------------------------------------------------
| HTTPS
|--------------------------------------------------------------------------
|
*/
'useHttps' => false,
/*
|--------------------------------------------------------------------------
| Signed URLs
|--------------------------------------------------------------------------
|
| To produce a signed URL, you must enable secure URLs on your source
| and then provide your signature key to the URL builder.
|
*/
'signKey' => '',
];
|
Fix prefetch. Add styles view | from django.conf import settings
from django.shortcuts import get_object_or_404, render
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
return Page.objects.published().prefetch_related('pagewidget_set__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
def styles(request, name):
namespace = Namespace()
for tv in ThemeValue.objects.all():
namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value))
compiler = Compiler(namespace=namespace)
return compiler.compile_string(src)
| from django.conf import settings
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
return Page.objects.published().prefetch_related('pagewidget__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
#
# Management Interface
#
|
Fix menu with missing values (->values()...) | <?php
namespace Code16\Sharp\View\Components;
use Code16\Sharp\View\Components\Utils\MenuItem;
use Illuminate\Support\Collection;
use Illuminate\View\Component;
class Menu extends Component
{
public string $title;
public ?string $username;
public ?string $currentEntity;
public bool $hasGlobalFilters;
public Collection $items;
public function __construct()
{
$this->title = config("sharp.name", "Sharp");
$this->username = sharp_user()->{config("sharp.auth.display_attribute", "name")};
$this->currentEntity = currentSharpRequest()->breadcrumb()->first()->key ?? null;
$this->hasGlobalFilters = sizeof(config('sharp.global_filters') ?? []) > 0;
$this->items = $this->getItems();
}
public function getItems(): Collection
{
return collect(config("sharp.menu", []))
->map(function($itemConfig) {
return MenuItem::parse($itemConfig);
})
->filter()
->values();
}
public function render()
{
return view('sharp::components.menu', [
'component' => $this,
]);
}
}
| <?php
namespace Code16\Sharp\View\Components;
use Code16\Sharp\View\Components\Utils\MenuItem;
use Illuminate\Support\Collection;
use Illuminate\View\Component;
class Menu extends Component
{
public string $title;
public ?string $username;
public ?string $currentEntity;
public bool $hasGlobalFilters;
public Collection $items;
public function __construct()
{
$this->title = config("sharp.name", "Sharp");
$this->username = sharp_user()->{config("sharp.auth.display_attribute", "name")};
$this->currentEntity = currentSharpRequest()->breadcrumb()->first()->key ?? null;
$this->hasGlobalFilters = sizeof(config('sharp.global_filters') ?? []) > 0;
$this->items = $this->getItems();
}
public function getItems(): Collection
{
return collect(config("sharp.menu", []))
->map(function($itemConfig) {
return MenuItem::parse($itemConfig);
})
->filter();
}
public function render()
{
return view('sharp::components.menu', [
'component' => $this,
]);
}
}
|
Work around service not exiting. | package com.emc.pravega.demo;
import java.time.Duration;
import com.emc.pravega.service.contracts.StreamSegmentStore;
import com.emc.pravega.service.server.host.handler.PravegaConnectionListener;
import com.emc.pravega.service.server.mocks.InMemoryServiceBuilder;
import com.emc.pravega.service.server.store.ServiceBuilderConfig;
import com.emc.pravega.stream.mock.MockStreamManager;
import lombok.Cleanup;
public class StartLocalService {
static final int PORT = 9090;
static final String SCOPE = "Scope";
static final String STREAM_NAME = "Foo";
public static void main(String[] args) throws Exception {
@Cleanup
InMemoryServiceBuilder serviceBuilder = new InMemoryServiceBuilder(ServiceBuilderConfig.getDefaultConfig());
serviceBuilder.getContainerManager().initialize(Duration.ofMinutes(1)).get();
StreamSegmentStore store = serviceBuilder.createStreamSegmentService();
@Cleanup
PravegaConnectionListener server = new PravegaConnectionListener(false, PORT, store);
server.startListening();
@Cleanup
MockStreamManager streamManager = new MockStreamManager(SCOPE, "localhost", StartLocalService.PORT);
streamManager.createStream(STREAM_NAME, null);
Thread.sleep(60000);
System.exit(0);
}
}
| package com.emc.pravega.demo;
import java.time.Duration;
import com.emc.pravega.service.contracts.StreamSegmentStore;
import com.emc.pravega.service.server.host.handler.PravegaConnectionListener;
import com.emc.pravega.service.server.mocks.InMemoryServiceBuilder;
import com.emc.pravega.service.server.store.ServiceBuilderConfig;
import com.emc.pravega.stream.mock.MockStreamManager;
import lombok.Cleanup;
public class StartLocalService {
static final int PORT = 9090;
static final String SCOPE = "Scope";
static final String STREAM_NAME = "Foo";
public static void main(String[] args) throws Exception {
@Cleanup
InMemoryServiceBuilder serviceBuilder = new InMemoryServiceBuilder(ServiceBuilderConfig.getDefaultConfig());
serviceBuilder.getContainerManager().initialize(Duration.ofMinutes(1)).get();
StreamSegmentStore store = serviceBuilder.createStreamSegmentService();
@Cleanup
PravegaConnectionListener server = new PravegaConnectionListener(false, PORT, store);
server.startListening();
@Cleanup
MockStreamManager streamManager = new MockStreamManager(SCOPE, "localhost", StartLocalService.PORT);
streamManager.createStream(STREAM_NAME, null);
Thread.sleep(60000);
}
}
|
Increase iterations. Add assertion of max board cards. | # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr, str2cards
import sys
## argv to strings
hole_cards_str = sys.argv[1]
board_str = ''
if len(sys.argv) > 2:
board_str = sys.argv[2]
## strings to lists of Card objects
hole_cards = str2cards(hole_cards_str)
board = str2cards(board_str)
assert len(board) <= 5
## hole card list to player list-of-lists
assert len(hole_cards) % 2 == 0
n_players = len(hole_cards) / 2
assert n_players > 1
p = []
for i in range(n_players):
pi = hole_cards[i * 2 : i * 2 + 2]
pr(pi)
p.append(pi)
print "Board",
pr(board)
percents = find_pcts_multi(p, board, iter = 20000)
print [round(x, 4) for x in percents]
| # usage: python one_time_eval.py hole_cards [board_cards]
# examples:
# python one_time_eval.py as8sqdtc
# python one_time_eval.py as8sqdtc 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd
# python one_time_eval.py as8sqdtc3d3c 2skskd3h5s
from convenience import find_pcts_multi, pr, str2cards
import sys
## argv to strings
hole_cards_str = sys.argv[1]
board_str = ''
if len(sys.argv) > 2:
board_str = sys.argv[2]
## strings to lists of Card objects
hole_cards = str2cards(hole_cards_str)
board = str2cards(board_str)
## hole card list to player list-of-lists
assert len(hole_cards) % 2 == 0
n_players = len(hole_cards) / 2
assert n_players > 1
p = []
for i in range(n_players):
pi = hole_cards[i * 2 : i * 2 + 2]
pr(pi)
p.append(pi)
print "Board",
pr(board)
percents = find_pcts_multi(p, board, iter = 10000)
print [round(x, 4) for x in percents]
|
Use private function for relation ids | /* @flow weak */
var inflector = require('./utils/inflector');
var merge = require('./utils/merge');
var Relation = function(parent, relation) {
this.parent = parent;
this.relation = relation;
this.namespace = inflector.pluralize(relation);
this.store = parent.store;
};
merge(Relation.prototype, {
all: function() {
return this.store.some(this.namespace, ids(this, false));
},
get: function(id) {
var id = id ? id : ids(this, true);
return this.store.get(this.namespace, id);
}
});
Relation.hasOne = Relation.hasMany = function(relation) {
return function() {
return new Relation(this, relation);
}
};
function ids(relation, singular) {
var postfix = singular ? '_id' : '_ids';
return relation.parent.get(relation.relation + postfix);
}
module.exports = Relation;
| /* @flow weak */
var inflector = require('./utils/inflector');
var merge = require('./utils/merge');
var Relation = function(parent, relation) {
this.parent = parent;
this.relation = relation;
this.namespace = inflector.pluralize(relation);
this.store = parent.store;
};
merge(Relation.prototype, {
all: function() {
return this.store.some(this.namespace, this._ids(false));
},
get: function(id) {
var id = id ? id : this._ids(true);
return this.store.get(this.namespace, id);
},
_ids: function(singular) {
var postfix = singular ? '_id' : '_ids';
return this.parent.get(this.relation + postfix);
}
});
Relation.hasOne = Relation.hasMany = function(relation) {
return function() {
return new Relation(this, relation);
}
};
module.exports = Relation;
|
Drop some unnecessary code from Response | package com.hamishrickerby.http_server;
/**
* Created by rickerbh on 17/08/2016.
*/
public class ResponseFactory {
String rootPath;
public ResponseFactory(String rootPath) {
this.rootPath = rootPath;
}
public Response makeResponse(Request request) {
Response response;
if (isFileResponse(request)) {
response = new FileContentsResponse(request, rootPath);
} else if (isDirectoryResponse(request)) {
response = new DirectoryListingResponse(request, rootPath);
} else {
response = new FourOhFourResponse(request);
}
return response;
}
private boolean isFileResponse(Request request) {
FileServer server = new FileServer(rootPath);
return server.fileExists(request.getPath());
}
private boolean isDirectoryResponse(Request request) {
FileDirectoryServer server = new FileDirectoryServer(rootPath);
return server.directoryExists(request.getPath());
}
}
| package com.hamishrickerby.http_server;
/**
* Created by rickerbh on 17/08/2016.
*/
public class ResponseFactory {
String rootPath;
public ResponseFactory(String rootPath) {
this.rootPath = rootPath;
}
public Response makeResponse(Request request) {
Response response = null;
if (isFileResponse(request)) {
FileContentsResponse fcr = new FileContentsResponse(request, rootPath);
response = fcr;
} else if (isDirectoryResponse(request)) {
DirectoryListingResponse dlr = new DirectoryListingResponse(request, rootPath);
response = dlr;
} else {
response = new FourOhFourResponse(request);
}
return response;
}
private boolean isFileResponse(Request request) {
FileServer server = new FileServer(rootPath);
return server.fileExists(request.getPath());
}
private boolean isDirectoryResponse(Request request) {
FileDirectoryServer server = new FileDirectoryServer(rootPath);
return server.directoryExists(request.getPath());
}
}
|
Make sure we are part of the config. | package main
import (
"flag"
"fmt"
"log"
)
var UniqueId string
var heartbeatChan chan bool
func processCommandLineArguments() (int, int, error) {
var hostId = flag.Int("hostId", 0, "The unique id for the host.")
var port = flag.Int("port", 0, "The per-host unique port")
flag.Parse()
if *hostId == 0 || *port == 0 {
return 0, 0,
fmt.Errorf("Cannot proceed with hostId %d and port %d\n"+
"Usage: ./identity -hostId hostId -port port", *hostId, *port)
}
return *hostId, *port, nil
}
func getMyUniqueId() string {
return UniqueId
}
func main() {
hostId, port, err := processCommandLineArguments()
if err != nil {
fmt.Println("Problem parsing arguments:", err)
return
}
heartbeatChan = make(chan bool)
UniqueId = fmt.Sprintf("%d_%d", hostId, port)
err = initLogger()
if err != nil {
fmt.Println("Problem opening file", err)
return
}
stateMachineInit()
nodeInit()
parseConfig()
if findNode(UniqueId) != nil {
log.Fatal("Could not find myself in the config: ", UniqueId)
}
err = startServer(port)
if err != nil {
fmt.Println("Problem starting server", err)
return
}
}
| package main
import (
"flag"
"fmt"
)
var UniqueId string
var heartbeatChan chan bool
func processCommandLineArguments() (int, int, error) {
var hostId = flag.Int("hostId", 0, "The unique id for the host.")
var port = flag.Int("port", 0, "The per-host unique port")
flag.Parse()
if *hostId == 0 || *port == 0 {
return 0, 0,
fmt.Errorf("Cannot proceed with hostId %d and port %d\n"+
"Usage: ./identity -hostId hostId -port port", *hostId, *port)
}
return *hostId, *port, nil
}
func getMyUniqueId() string {
return UniqueId
}
func main() {
hostId, port, err := processCommandLineArguments()
if err != nil {
fmt.Println("Problem parsing arguments:", err)
return
}
heartbeatChan = make(chan bool)
UniqueId = fmt.Sprintf("%d_%d", hostId, port)
err = initLogger()
if err != nil {
fmt.Println("Problem opening file", err)
return
}
stateMachineInit()
nodeInit()
parseConfig()
err = startServer(port)
if err != nil {
fmt.Println("Problem starting server", err)
return
}
}
|
Remove pylab from import statements | import numpy as np
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*np.eye(2)
observation_covariance = [0.1]
initial_state_mean = [1.0,0.0]
initial_state_covariance = [[1,0.1],[-0.1,1]]
kf = KalmanFilter(
transition_matrices=transition_matrix,observation_matrices=observation_matrix, transition_covariance=transition_covariance,
observation_covariance=observation_covariance, transition_offsets=transition_offset, observation_offsets=observation_offset,
initial_state_mean=initial_state_mean, initial_state_covariance=initial_state_covariance,
random_state=random_state
)
ts = np.linspace(0,0.01*1000,1000)
observations = np.cos(ts) + np.sqrt(0.1) * random_state.randn(1000)
states = np.cos(ts)
t = timeit.timeit('filtered_state_estimates = kf.filter(observations)[0]','from __main__ import kf,observations',number=N)
print t
| import numpy as np
import pylab as pl
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*np.eye(2)
observation_covariance = [0.1]
initial_state_mean = [1.0,0.0]
initial_state_covariance = [[1,0.1],[-0.1,1]]
kf = KalmanFilter(
transition_matrices=transition_matrix,observation_matrices=observation_matrix, transition_covariance=transition_covariance,
observation_covariance=observation_covariance, transition_offsets=transition_offset, observation_offsets=observation_offset,
initial_state_mean=initial_state_mean, initial_state_covariance=initial_state_covariance,
random_state=random_state
)
ts = np.linspace(0,0.01*1000,1000)
observations = np.cos(ts) + np.sqrt(0.1) * random_state.randn(1000)
states = np.cos(ts)
t = timeit.timeit('filtered_state_estimates = kf.filter(observations)[0]','from __main__ import kf,observations',number=N)
print t
|
refactor(citrus-3.0): Add short hand for run methods on test action runner | package com.consol.citrus;
/**
* @author Christoph Deppisch
*/
public interface TestActionRunner {
/**
* Runs given test action.
* @param action
* @param <T>
* @return
*/
default <T extends TestAction> T run(T action) {
return run((TestActionBuilder<T>) () -> action);
}
/**
* Runs given test action.
* @param action
* @param <T>
* @return
*/
default <T extends TestAction> T $(T action) {
return run((TestActionBuilder<T>) () -> action);
}
/**
* Builds and runs given test action.
* @param builder
* @param <T>
* @return
*/
default <T extends TestAction> T $(TestActionBuilder<T> builder) {
return run(builder);
}
/**
* Builds and runs given test action.
* @param builder
* @param <T>
* @return
*/
<T extends TestAction> T run(TestActionBuilder<T> builder);
/**
* Apply test behavior on this test action runner.
* @param behavior
* @return
*/
<T extends TestAction> TestActionBuilder<T> applyBehavior(TestBehavior behavior);
}
| package com.consol.citrus;
/**
* @author Christoph Deppisch
*/
public interface TestActionRunner {
/**
* Runs given test action.
* @param action
* @param <T>
* @return
*/
default <T extends TestAction> T run(T action) {
return run((TestActionBuilder<T>) () -> action);
}
/**
* Builds and runs given test action.
* @param builder
* @param <T>
* @return
*/
<T extends TestAction> T run(TestActionBuilder<T> builder);
/**
* Apply test behavior on this test action runner.
* @param behavior
* @return
*/
<T extends TestAction> TestActionBuilder<T> applyBehavior(TestBehavior behavior);
}
|
FIX Fixed breaking custommenu block that was referencing the Items list prior to saving, if accessed via BlockSet | <?php
/**
* A block that allows end users to manually build a custom (flat or nested) menu
* @author Shea Dawson <shea@silverstripe.com.au>
* @package ba-sis
**/
class CustomMenuBlock extends Block {
private static $singular_name = 'Custom Menu Block';
private static $plural_name = 'Custom Menu Blocks';
private static $db = array(
);
private static $has_many = array(
'Items' => 'CustomMenuBlockItem'
);
public function getCMSFields(){
$fields = parent::getCMSFields();
$fields->removeFieldFromTab('Root', 'Items');
if ($this->ID) {
$config = GridFieldConfig_RecordEditor::create()
->addComponent(new GridFieldOrderableRows());
$grid = GridField::create('Items', 'Items', $this->Items()->filter('ParentID', 0), $config);
$config->getComponentByType('GridFieldDataColumns')
->setDisplayFields(array(
'Title' => 'Menu Item Title',
'Children.Count' => 'Num Children'
));
$fields->addFieldToTab('Root.Main', HeaderField::create('ItemsHeader', 'Menu Items'));
$fields->addFieldToTab('Root.Main', $grid);
}
return $fields;
}
/**
* Method for use in templates to loop over menu items
* @return DataList
**/
public function MenuItems(){
return $this->Items()->filter('ParentID', 0);
}
}
| <?php
/**
* A block that allows end users to manually build a custom (flat or nested) menu
* @author Shea Dawson <shea@silverstripe.com.au>
* @package ba-sis
**/
class CustomMenuBlock extends Block {
private static $singular_name = 'Custom Menu Block';
private static $plural_name = 'Custom Menu Blocks';
private static $db = array(
);
private static $has_many = array(
'Items' => 'CustomMenuBlockItem'
);
public function getCMSFields(){
$fields = parent::getCMSFields();
$fields->removeFieldFromTab('Root', 'Items');
$config = GridFieldConfig_RecordEditor::create()
->addComponent(new GridFieldOrderableRows());
$grid = GridField::create('Items', 'Items', $this->Items()->filter('ParentID', 0), $config);
$config->getComponentByType('GridFieldDataColumns')
->setDisplayFields(array(
'Title' => 'Menu Item Title',
'Children.Count' => 'Num Children'
));
$fields->addFieldToTab('Root.Main', HeaderField::create('ItemsHeader', 'Menu Items'));
$fields->addFieldToTab('Root.Main', $grid);
return $fields;
}
/**
* Method for use in templates to loop over menu items
* @return DataList
**/
public function MenuItems(){
return $this->Items()->filter('ParentID', 0);
}
}
|
Use doc _id field to construct url
Docs don't always have an id property, so we use _id directly instead. | "use strict";
var filter = require('../filter');
module.exports = jsonTransformPlugin;
function jsonTransformPlugin(schema) {
schema.set('toJSON', {transform: filterFields});
}
/**
* Transform a document to a json doc.
*
* - options.fieldSpec The fields to show/hide
*/
function filterFields(doc, ret, options) {
ret = filter(doc, ret, options);
ret = addLinks(doc, ret, options);
return ret;
}
function addLinks(doc, ret, options) {
if (doc.constructor.collection) {
if (options.apiBaseUrl) {
ret.url = [
options.apiBaseUrl,
doc.constructor.collection.name.toLowerCase(),
doc._id
].join('/');
}
if (options.baseUrl && doc.slug) {
ret.html_url = [
options.baseUrl,
doc.constructor.collection.name.toLowerCase(),
doc.slug
].join('/');
}
}
return ret;
}
| "use strict";
var filter = require('../filter');
module.exports = jsonTransformPlugin;
function jsonTransformPlugin(schema) {
schema.set('toJSON', {transform: filterFields});
}
/**
* Transform a document to a json doc.
*
* - options.fieldSpec The fields to show/hide
*/
function filterFields(doc, ret, options) {
ret = filter(doc, ret, options);
ret = addLinks(doc, ret, options);
return ret;
}
function addLinks(doc, ret, options) {
if (doc.constructor.collection) {
if (options.apiBaseUrl) {
ret.url = [
options.apiBaseUrl,
doc.constructor.collection.name.toLowerCase(),
doc.id
].join('/');
}
if (options.baseUrl && doc.slug) {
ret.html_url = [
options.baseUrl,
doc.constructor.collection.name.toLowerCase(),
doc.slug
].join('/');
}
}
return ret;
}
|
Fix import time issue with member_required decorator. | from flask import flash, redirect
from flask_login import current_user
import wrapt
from ..account.views import default_url
def member_required(next_url=None, message=None):
if message is None:
message = "Sorry but you're not a member of Jazzband at the moment."
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
"""
If you decorate a view with this, it will ensure that the current user is
a Jazzband member.
:param func: The view function to decorate.
:type func: function
"""
if next_url is None:
next_url = default_url()
if (
not current_user.is_member
or current_user.is_banned
or current_user.is_restricted
):
flash(message)
return redirect(next_url)
return wrapped(*args, **kwargs)
return wrapper
| from flask import flash, redirect
from flask_login import current_user
import wrapt
from ..account.views import default_url
def member_required(next_url=None, message=None):
if next_url is None:
next_url = default_url()
if message is None:
message = "Sorry but you're not a member of Jazzband at the moment."
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
"""
If you decorate a view with this, it will ensure that the current user is
a Jazzband member.
:param func: The view function to decorate.
:type func: function
"""
if (
not current_user.is_member
or current_user.is_banned
or current_user.is_restricted
):
flash(message)
return redirect(next_url)
return wrapped(*args, **kwargs)
return wrapper
|
Add python 3.6 to the list of supported versions | from setuptools import setup, find_packages
setup(
name='validation',
url='https://github.com/JOIVY/validation',
version='0.1.0',
author='Ben Mather',
author_email='bwhmather@bwhmather.com',
maintainer='',
license='BSD',
description=(
"A library for runtime type checking and validation of python values"
),
long_description=__doc__,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
install_requires=[
'six >= 1.10, < 2',
],
tests_require=[
'pytz',
],
packages=find_packages(),
package_data={
'': ['*.pyi'],
},
entry_points={
'console_scripts': [
],
},
test_suite='validation.tests.suite',
)
| from setuptools import setup, find_packages
setup(
name='validation',
url='https://github.com/JOIVY/validation',
version='0.1.0',
author='Ben Mather',
author_email='bwhmather@bwhmather.com',
maintainer='',
license='BSD',
description=(
"A library for runtime type checking and validation of python values"
),
long_description=__doc__,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=[
'six >= 1.10, < 2',
],
tests_require=[
'pytz',
],
packages=find_packages(),
package_data={
'': ['*.pyi'],
},
entry_points={
'console_scripts': [
],
},
test_suite='validation.tests.suite',
)
|
Make debugging the wsme app a bit easier.
- add a logger so we get exceptions
- setup the port to 8777 so 'pecan serve config.py' works normally
Change-Id: I7374a34ae5534d7d4127e4b405daa11cab5f5547 | # Server Specific Configurations
server = {
'port': '8777',
'host': '0.0.0.0'
}
# Pecan Application Configurations
app = {
'root': 'ceilometer.api.controllers.root.RootController',
'modules': ['ceilometer.api'],
'static_root': '%(confdir)s/public',
'template_path': '%(confdir)s/ceilometer/api/templates',
'debug': False,
}
logging = {
'loggers': {
'root': {'level': 'INFO', 'handlers': ['console']},
'ceilometer': {'level': 'DEBUG', 'handlers': ['console']},
'wsme': {'level': 'DEBUG', 'handlers': ['console']}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
}
},
'formatters': {
'simple': {
'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]'
'[%(threadName)s] %(message)s')
}
},
}
# Custom Configurations must be in Python dictionary format::
#
# foo = {'bar':'baz'}
#
# All configurations are accessible at::
# pecan.conf
| # Server Specific Configurations
server = {
'port': '8080',
'host': '0.0.0.0'
}
# Pecan Application Configurations
app = {
'root': 'ceilometer.api.controllers.root.RootController',
'modules': ['ceilometer.api'],
'static_root': '%(confdir)s/public',
'template_path': '%(confdir)s/ceilometer/api/templates',
'debug': False,
}
logging = {
'loggers': {
'root': {'level': 'INFO', 'handlers': ['console']},
'ceilometer': {'level': 'DEBUG', 'handlers': ['console']}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
}
},
'formatters': {
'simple': {
'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]'
'[%(threadName)s] %(message)s')
}
},
}
# Custom Configurations must be in Python dictionary format::
#
# foo = {'bar':'baz'}
#
# All configurations are accessible at::
# pecan.conf
|
Disable ESLint rules conflicting with Prettier | module.exports = {
extends: ['airbnb-base', 'plugin:flowtype/recommended'],
plugins: ['flowtype'],
env: { es6: true, jest: true, node: true },
// globals: { Generator: true },
rules: {
// Rule to enforce function return types. We disable this because Flow will check our function return types.
'consistent-return': 'off',
// Code style rule to enforce import ordering. We disable this because we use absolute imports for types sometimes after relative imports.
'import/first': 'off',
// Code style rule to prefer a default export instead of a single named export, currently we disable this to allow this behavior. We can decide later to turn this on again if we want.
'import/prefer-default-export': 'off',
// Prettier works better with its default 80 character max-length
'max-len': 'off',
// Conflicts with Prettier's stripping of unnecessary parentheses
'no-confusing-arrow': 'off',
// Rule to restrict usage of confusing code style with mixed boolean operators. We disable this because Prettier removes "unnecessary parentheses" here and breaks this.
'no-mixed-operators': 'off',
// Rule to prevent prefixing of underscores on variable names. We disable this because we use some underscore prefixes in our code.
'no-underscore-dangle': 'off',
},
};
| module.exports = {
extends: ['airbnb-base', 'plugin:flowtype/recommended'],
plugins: ['flowtype'],
env: { es6: true, jest: true, node: true },
// globals: { Generator: true },
rules: {
// Rule to enforce function return types. We disable this because Flow will check our function return types.
'consistent-return': 'off',
// Code style rule to enforce import ordering. We disable this because we use absolute imports for types sometimes after relative imports.
'import/first': 'off',
// Code style rule to prefer a default export instead of a single named export, currently we disable this to allow this behavior. We can decide later to turn this on again if we want.
'import/prefer-default-export': 'off',
// Rule to restrict usage of confusing code style with mixed boolean operators. We disable this because Prettier removes "unnecessary parentheses" here and breaks this.
'no-mixed-operators': 'off',
// Rule to prevent prefixing of underscores on variable names. We disable this because we use some underscore prefixes in our code.
'no-underscore-dangle': 'off',
},
};
|
Hide PointCloudAlignment things from Cura | from . import PointCloudAlignTool
from . import PointCloudAlignView
from UM.Application import Application
def getMetaData():
return {
'type': 'tool',
'plugin':
{
"name": "PointCloudAlignment",
'author': 'Jaime van Kessel',
'version': '1.0',
'description': ''
},
'view':
{
'name': 'PointCloudAlignmentView',
'visible': False
},
'tool':
{
'name': 'PointCloudAlignmentTool',
},
'cura': {
'tool': {
'visible': False
}
}
}
def register(app):
#TODO: Once multiple plugin types are supported, this needs to be removed.
view = PointCloudAlignView.PointCloudAlignView()
view.setPluginId("PointCloudAlignment")
Application.getInstance().getController().addView(view)
return PointCloudAlignTool.PointCloudAlignTool()
| from . import PointCloudAlignTool
from . import PointCloudAlignView
from UM.Application import Application
def getMetaData():
return {
'type': 'tool',
'plugin':
{
"name": "PointCloudAlignment",
'author': 'Jaime van Kessel',
'version': '1.0',
'description': ''
},
'view':
{
'name': 'PointCloudAlignmentView',
'visible': False
},
'tool':
{
'name': 'PointCloudAlignmentTool'
}
}
def register(app):
#TODO: Once multiple plugin types are supported, this needs to be removed.
view = PointCloudAlignView.PointCloudAlignView()
view.setPluginId("PointCloudAlign")
Application.getInstance().getController().addView(view)
return PointCloudAlignTool.PointCloudAlignTool()
|
Handle in case user cancels open skin as project command | import os
import subprocess
import sublime
import sublime_plugin
from .path.skin_path_provider import get_cached_skin_path
class RainmeterOpenSkinAsProjectCommand(sublime_plugin.ApplicationCommand):
def run(self):
skins_path = get_cached_skin_path()
skins = os.listdir(skins_path)
sublime.active_window().show_quick_panel(skins, self.on_skin_selected, 0, 0, None)
def on_skin_selected(self, selected_skin_id):
if selected_skin_id == -1:
return
skins_path = get_cached_skin_path()
skins = os.listdir(skins_path)
selected_skin = skins[selected_skin_id]
selected_skin_path = os.path.join(skins_path, selected_skin)
# to open a folder in new window, just create a new process with the folder as argument
st_path = sublime.executable_path()
subprocess.Popen([
st_path,
selected_skin_path
])
| import os
import subprocess
import sublime
import sublime_plugin
from .path.skin_path_provider import get_cached_skin_path
class RainmeterOpenSkinAsProjectCommand(sublime_plugin.ApplicationCommand):
def run(self):
skins_path = get_cached_skin_path()
skins = os.listdir(skins_path)
sublime.active_window().show_quick_panel(skins, self.on_skin_selected, 0, 0, None)
def on_skin_selected(self, selected_skin_id):
skins_path = get_cached_skin_path()
skins = os.listdir(skins_path)
selected_skin = skins[selected_skin_id]
selected_skin_path = os.path.join(skins_path, selected_skin)
# to open a folder in new window, just create a new process with the folder as argument
st_path = sublime.executable_path()
subprocess.Popen([
st_path,
selected_skin_path
])
|
Use TemplateView to simplify Index view. | """Index page admin view."""
import logging
from django.contrib.auth.decorators import user_passes_test
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
logger = logging.getLogger(__name__)
class Index(TemplateView):
"""Main view for users connecting via web browsers.
This view downloads and displays a JS view. This view first logs in the
user. If the user is a superuser, it shows the Judging view which is used
to manage the competition and evaluate teams.
"""
template_name = 'index.html'
# Use user_passes_test to redirect to login rather than return 403.
@method_decorator(user_passes_test(lambda u: u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(Index, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
context = super(Index, self).get_context_data(**kwargs)
return context
| """Index page admin view."""
import logging
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import View
logger = logging.getLogger(__name__)
class Index(View):
"""Main view for users connecting via web browsers.
This view downloads and displays a JS view. This view first logs in the
user. If the user is a superuser, it shows the Judging view which is used
to manage the competition and evaluate teams.
"""
# We want a real redirect to the login page rather than a 403, so
# we use user_passes_test directly.
@method_decorator(user_passes_test(lambda u: u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(Index, self).dispatch(*args, **kwargs)
def get(self, request):
return render(request, 'index.html')
|
Load file as UTF-8 as default | package fr.univnantes.termsuite.ui.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Scanner;
import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;
public class FileUtil {
public static String toString(File file) throws FileNotFoundException {
Scanner scanner = new Scanner(file, "UTF-8");
String next = scanner.useDelimiter("\\Z").next();
scanner.close();
return next;
}
public static void mkdirs(File file) {
if (file.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
}
}
public static void inputStreamToFile(InputStream is, File targetFile) throws IOException {
byte[] buffer = ByteStreams.toByteArray(is);
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.flush();
outStream.close();
}
public static String getFilename(String path) {
List<String> list = Splitter.on(File.separator).splitToList(path);
return list.get(list.size() - 1);
}
}
| package fr.univnantes.termsuite.ui.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Scanner;
import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;
public class FileUtil {
public static String toString(File file) throws FileNotFoundException {
Scanner scanner = new Scanner(file);
String next = scanner.useDelimiter("\\Z").next();
scanner.close();
return next;
}
public static void mkdirs(File file) {
if (file.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
}
}
public static void inputStreamToFile(InputStream is, File targetFile) throws IOException {
byte[] buffer = ByteStreams.toByteArray(is);
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.flush();
outStream.close();
}
public static String getFilename(String path) {
List<String> list = Splitter.on(File.separator).splitToList(path);
return list.get(list.size() - 1);
}
}
|
Fix reading the "can use" data | var ui_settings = (function() {
var externalDisplayOn = false;
$(document).on("ui-settings", function(event, data) {
if (data.header == "externalDisplay") {
if (data.content.canUseExternalDisplay) {
document.querySelector(".external-display-settings").classList.remove("hidden");
if (data.content.enabled) {
externalDisplayOn = true;
document.querySelector("#external-display-toggle").classList.add("on");
} else {
externalDisplayOn = false;
document.querySelector("#external-display-toggle").classList.remove("on");
}
}
beo.notify(false, "ui-settings");
}
});
function toggleDisplay() {
beo.sendToProduct("ui-settings", "externalDisplayOn", {enabled: (!externalDisplayOn) ? true : false});
if (!externalDisplayOn) {
beo.notify({title: "Turning external display on...", icon: "attention", timeout: false});
} else {
beo.notify({title: "Turning external display off...", icon: "attention", timeout: false});
}
}
return {
toggleDisplay: toggleDisplay
}
})(); | var ui_settings = (function() {
var externalDisplayOn = false;
$(document).on("ui-settings", function(event, data) {
if (data.header == "externalDisplay") {
if (canUseExternalDisplay) {
document.querySelector(".external-display-settings").classList.remove("hidden");
if (data.content.enabled) {
externalDisplayOn = true;
document.querySelector("#external-display-toggle").classList.add("on");
} else {
externalDisplayOn = false;
document.querySelector("#external-display-toggle").classList.remove("on");
}
}
beo.notify(false, "ui-settings");
}
});
function toggleDisplay() {
beo.sendToProduct("ui-settings", "externalDisplayOn", {enabled: (!externalDisplayOn) ? true : false});
if (!externalDisplayOn) {
beo.notify({title: "Turning external display on...", icon: "attention", timeout: false});
} else {
beo.notify({title: "Turning external display off...", icon: "attention", timeout: false});
}
}
return {
toggleDisplay: toggleDisplay
}
})(); |
Groid: Add numObjectTypes to constructor parameters | package com.provinggrounds.match3things.game;
/*
* Represents a game grid. Contains a rectangular grid of numbers.
* All numbers must be positive integers greater than 0, between 1 and numObjectTypes(both inclusive)
*/
public class Grid {
int width;
int height;
/*
* Represents number of unique object types
*/
int numObjectTypes;
int[][] gameGrid;
/*
* Width and height must always be provided to Grid - should not be constructed without initializing/passing in those values
*/
@SuppressWarnings("unused")
private Grid() {
}
Grid(int width, int height, int numObjectTypes) {
this.width = width;
this.height = height;
this.numObjectTypes = numObjectTypes;
initGameGridArray();
}
/*
* Creates grid, allocates storage
*/
private void initGameGridArray() {
gameGrid = new int[width][height];
}
/*
* Initialize/fill game grid with random objects
*/
private void fillGameGrid() {
}
}
| package com.provinggrounds.match3things.game;
/*
* Represents a game grid. Contains a rectangular grid of numbers.
* All numbers must be positive integers greater than 0, between 1 and numObjectTypes(both inclusive)
*/
public class Grid {
int width;
int height;
/*
* Represents number of unique object types
*/
int numObjectTypes;
int[][] gameGrid;
/*
* Width and height must always be provided to Grid - should not be constructed without initializing/passing in those values
*/
@SuppressWarnings("unused")
private Grid() {
}
Grid(int width, int height) {
this.width = width;
this.height = height;
initGameGridArray();
}
/*
* Creates grid, allocates storage
*/
private void initGameGridArray() {
gameGrid = new int[width][height];
}
/*
* Initialize/fill game grid with random objects
*/
private void fillGameGrid() {
}
}
|
Add periods to end of encode/decode comments. | angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8.
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
| angular.module("Prometheus.services").factory('UrlConfigDecoder', function($location) {
return function(defaultHash) {
var hash = $location.hash() || defaultHash;
if (!hash) {
return {};
}
// Decodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
var configJSON = unescape(decodeURIComponent(window.atob(hash)));
var config = JSON.parse(configJSON);
return config;
};
});
angular.module("Prometheus.services").factory('UrlHashEncoder', ["UrlConfigDecoder", function(UrlConfigDecoder) {
return function(config) {
var urlConfig = UrlConfigDecoder();
for (var o in config) {
urlConfig[o] = config[o];
}
var configJSON = JSON.stringify(urlConfig);
// Encodes UTF-8
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64.btoa#Unicode_Strings
return window.btoa(encodeURIComponent(escape(configJSON)));
};
}]);
angular.module("Prometheus.services").factory('UrlConfigEncoder', ["$location", "UrlHashEncoder", function($location, UrlHashEncoder) {
return function(config) {
$location.hash(UrlHashEncoder(config));
};
}]);
angular.module("Prometheus.services").factory('UrlVariablesDecoder', function($location) {
return function() {
return $location.search();
};
});
|
Reorganize front page markup to include a hero section | <?php
get_header(); ?>
<div id="splash" class="hero-area">
<div class="site-hero-title">
<h1 class="site-main-title"><span>Katherine</span> <span>Anne</span> <span>Porter</span></h1>
<span class="site-sub-title">correspondence</span>
</div><!-- .site-hero-title -->
</div><!-- .hero-area -->
<div id="primary" class="content-area">
<section class="site-about-teaser">
<div class="site-call-to-action">
<p class="intro">The University of Maryland Libraries are pleased to be
able to share over 5,000 pages of digitized materials granting
unprecedented access to the ideas, attitudes, and experiences of a
distinguished 20th century American writer.
</p>
<a href="introduction" class="btn main-action-button">Read More</a>
</div>
</section><!-- .site-call-to-action -->
</div><!-- .content-area -->
<?php get_footer(); ?>
| <?php
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<section class="site-hero-section">
<div class="site-title-container p-a-lg">
<h1 class="site-main-title"><span>Katherine</span> <span>Anne</span> <span>Porter</span></h1>
<span class="site-sub-title">correspondence</span>
</div>
</section>
<section class="site-about-teaser">
<div class="site-call-to-action p-a-lg">
<p class="intro">Over 5,000 pages of digitized materials granting unprecedented access
to the ideas, attitudes, and experiences of a distinguished
20th century American writer.
</p>
<a href="introduction" class="btn main-action-button">Read More</a>
</div>
</section>
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
|
Make JobTypeCard use imageProp from propTypes | import React, { Component, PropTypes } from 'react';
import { Card } from 'native-base';
import CardImageHeader from '../../common/card-image-header/cardImageHeader';
import SimpleCardBody from '../../common/simple-card-body/simpleCardBody';
import { imageProp } from '../../common/propTypes';
export default class JobTypeCard extends Component {
static propTypes = {
title: PropTypes.string.isRequired,
cover: imageProp.isRequired,
icon: imageProp.isRequired,
subtitle: PropTypes.string.isRequired,
toNextScreen: PropTypes.func.isRequired,
};
render() {
return (
<Card>
<CardImageHeader
cover={this.props.cover} icon={this.props.icon}
toNextScreen={this.props.toNextScreen}
/>
<SimpleCardBody
title={this.props.title} subtitle={this.props.subtitle}
icon="arrow-forward" toNextScreen={this.props.toNextScreen}
/>
</Card>
);
}
}
| import React, { Component } from 'react';
import { Card } from 'native-base';
import CardImageHeader from '../../common/card-image-header/cardImageHeader';
import SimpleCardBody from '../../common/simple-card-body/simpleCardBody';
export default class JobTypeCard extends Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
cover: React.PropTypes.string.isRequired,
icon: React.PropTypes.string.isRequired,
subtitle: React.PropTypes.string.isRequired,
toNextScreen: React.PropTypes.func.isRequired,
};
render() {
return (
<Card>
<CardImageHeader
cover={this.props.cover} icon={this.props.icon}
toNextScreen={this.props.toNextScreen}
/>
<SimpleCardBody
title={this.props.title} subtitle={this.props.subtitle}
icon="arrow-forward" toNextScreen={this.props.toNextScreen}
/>
</Card>
);
}
}
|
Move AnswerAreaRenderer export after functions
Auditors: alex | require("./all-widgets.js");
module.exports = {
fixupJSON: require("./fixup-json.jsx"),
init: require("./init.js"),
AnswerAreaRenderer: require("./answer-area-renderer.jsx"),
Editor: require("./editor.jsx"),
EditorPage: require("./editor-page.jsx"),
ItemRenderer: require("./item-renderer.jsx"),
Renderer: require("./renderer.jsx"),
RevisionDiff: require("./diffs/revision-diff.jsx"),
StatefulEditorPage: require("./stateful-editor-page.jsx"),
Util: require("./util.js")
};
| require("./all-widgets.js");
module.exports = {
AnswerAreaRenderer: require("./answer-area-renderer.jsx"),
fixupJSON: require("./fixup-json.jsx"),
init: require("./init.js"),
Editor: require("./editor.jsx"),
EditorPage: require("./editor-page.jsx"),
ItemRenderer: require("./item-renderer.jsx"),
Renderer: require("./renderer.jsx"),
RevisionDiff: require("./diffs/revision-diff.jsx"),
StatefulEditorPage: require("./stateful-editor-page.jsx"),
Util: require("./util.js")
};
|
Add meiosis-tracer to requirejs example. | /*global requirejs*/
requirejs.config({
paths: {
meiosis: "../lib/meiosis.min",
meiosisVanillaJs: "../lib/meiosis-vanillajs.min",
meiosisTracer: "../lib/meiosis-tracer.min"
}
});
requirejs(["require", "meiosis", "meiosisVanillaJs", "meiosisTracer",
"./model", "./view", "./ready", "./receiveUpdate"
],
function(require) {
var meiosis = require("meiosis");
var meiosisVanillaJs = require("meiosisVanillaJs");
var meiosisTracer = require("meiosisTracer");
var model = require("./model");
var view = require("./view");
var ready = require("./ready");
var receiveUpdate = require("./receiveUpdate");
var renderer = meiosisVanillaJs.renderer;
var Meiosis = meiosis.init(renderer.intoId("app"));
var createComponent = Meiosis.createComponent;
var Main = createComponent({
initialModel: model.initialModel,
view: view,
ready: ready,
receiveUpdate: receiveUpdate
});
var renderRoot = Meiosis.run(Main);
meiosisTracer(createComponent, renderRoot, "#tracer");
}
);
| /*global requirejs*/
requirejs.config({
paths: {
meiosis: "../lib/meiosis.min",
meiosisVanillaJs: "../lib/meiosis-vanillajs.min"
}
});
requirejs(["require", "meiosis", "meiosisVanillaJs", "./model", "./view", "./ready", "./receiveUpdate"],
function(require) {
var meiosis = require("meiosis");
var meiosisVanillaJs = require("meiosisVanillaJs");
var model = require("./model");
var view = require("./view");
var ready = require("./ready");
var receiveUpdate = require("./receiveUpdate");
var renderer = meiosisVanillaJs.renderer;
var Meiosis = meiosis.init(renderer.intoId("app"));
var createComponent = Meiosis.createComponent;
var Main = createComponent({
initialModel: model.initialModel,
view: view,
ready: ready,
receiveUpdate: receiveUpdate
});
Meiosis.run(Main);
}
);
|
Support Google Apps drive urls | import re
__author__ = 'tigge'
from wand.image import Image
def fix_image(filename, max_width):
with Image(filename=filename) as img:
img.auto_orient()
if img.width > max_width:
ratio = img.height / img.width
img.resize(width=max_width, height=round(max_width * ratio))
img.type = 'optimize'
img.compression_quality = 80
img.save(filename=filename)
def fix_google_drive_download_url(url):
url = re.sub(r"https://drive\.google\.com/(?:a/.*){0,1}file/d/(.*?)/view\?usp=.*",
r"https://drive.google.com/uc?authuser=0&id=\1&export=download", url)
return url
def fix_dropbox_download_url(url):
url = url[:-5] + "?dl=1" if url.startswith("https://www.dropbox.com") and url.endswith("?dl=0") else url
return url
| import re
__author__ = 'tigge'
from wand.image import Image
def fix_image(filename, max_width):
with Image(filename=filename) as img:
img.auto_orient()
if img.width > max_width:
ratio = img.height / img.width
img.resize(width=max_width, height=round(max_width * ratio))
img.type = 'optimize'
img.compression_quality = 80
img.save(filename=filename)
def fix_google_drive_download_url(url):
url = re.sub(r"https://drive\.google\.com/file/d/(.*?)/view\?usp=.*",
r"https://docs.google.com/uc?authuser=0&id=\1&export=download", url)
return url
def fix_dropbox_download_url(url):
url = url[:-5] + "?dl=1" if url.startswith("https://www.dropbox.com") and url.endswith("?dl=0") else url
return url
|
v7: Remove extra newline from `passwd` output
[Finishes #172301989]
Authored-by: Reid Mitchell <15b84f3bcf1e0a1a99817cc9360cedc980d7c5b6@pivotal.io> | package v7
import (
"code.cloudfoundry.org/cli/command/translatableerror"
)
type PasswdCommand struct {
BaseCommand
usage interface{} `usage:"CF_NAME passwd"`
}
func (cmd PasswdCommand) Execute(args []string) error {
err := cmd.SharedActor.CheckTarget(false, false)
if err != nil {
return err
}
currentUser, err := cmd.Config.CurrentUser()
if err != nil {
return err
}
currentPassword, err := cmd.UI.DisplayPasswordPrompt("Current password")
if err != nil {
return err
}
newPassword, err := cmd.UI.DisplayPasswordPrompt("New password")
if err != nil {
return err
}
verifyPassword, err := cmd.UI.DisplayPasswordPrompt("Verify password")
if err != nil {
return err
}
cmd.UI.DisplayNewline()
cmd.UI.DisplayTextWithFlavor("Changing password for user {{.Username}}...", map[string]interface{}{
"Username": currentUser.Name,
})
if newPassword != verifyPassword {
return translatableerror.PasswordVerificationFailedError{}
}
err = cmd.Actor.UpdateUserPassword(currentUser.GUID, currentPassword, newPassword)
if err != nil {
return err
}
cmd.UI.DisplayOK()
cmd.Config.UnsetUserInformation()
cmd.UI.DisplayText("Please log in again.")
return nil
}
| package v7
import (
"code.cloudfoundry.org/cli/command/translatableerror"
)
type PasswdCommand struct {
BaseCommand
usage interface{} `usage:"CF_NAME passwd"`
}
func (cmd PasswdCommand) Execute(args []string) error {
err := cmd.SharedActor.CheckTarget(false, false)
if err != nil {
return err
}
currentUser, err := cmd.Config.CurrentUser()
if err != nil {
return err
}
currentPassword, err := cmd.UI.DisplayPasswordPrompt("Current password")
if err != nil {
return err
}
newPassword, err := cmd.UI.DisplayPasswordPrompt("New password")
if err != nil {
return err
}
verifyPassword, err := cmd.UI.DisplayPasswordPrompt("Verify password")
if err != nil {
return err
}
cmd.UI.DisplayNewline()
cmd.UI.DisplayTextWithFlavor("Changing password for user {{.Username}}...", map[string]interface{}{
"Username": currentUser.Name,
})
cmd.UI.DisplayNewline()
if newPassword != verifyPassword {
return translatableerror.PasswordVerificationFailedError{}
}
err = cmd.Actor.UpdateUserPassword(currentUser.GUID, currentPassword, newPassword)
if err != nil {
return err
}
cmd.UI.DisplayOK()
cmd.Config.UnsetUserInformation()
cmd.UI.DisplayText("Please log in again.")
return nil
}
|
Make redis subscription work with python-redis' latest versions |
import redis
import re
from common import get_db
from datetime import datetime
MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'
def listen(args):
global MSGPATTERN
rserver = redis.Redis('localhost')
pubsub = rserver.pubsub()
pubsub.subscribe(CHANNEL)
db = get_db(args.mongohost)
for packet in pubsub.listen():
try:
if packet['type'] != 'message': continue
match = MSGPATTERN.match(packet['data'])
component = match.group(1)
level = int(match.group(2))
message = match.group(3)
db.insert(dict(
tstamp=datetime.now(),comp=component,lvl=level,msg=message))
except Exception, e:
print e, packet
|
import redis
import re
from common import get_db
from datetime import datetime
MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'
def listen(args):
global MSGPATTERN
rserver = redis.Redis('localhost')
rserver.subscribe(CHANNEL)
db = get_db(args.mongohost)
for packet in rserver.listen():
try:
if packet['type'] != 'message': continue
match = MSGPATTERN.match(packet['data'])
component = match.group(1)
level = int(match.group(2))
message = match.group(3)
db.insert(dict(
tstamp=datetime.now(),comp=component,lvl=level,msg=message))
except Exception, e:
print e, packet
|
Change cardinality of the color range | define([
'streamhub-map/point',
'streamhub-map/views/marker-view',
'inherits',
'd3',
'colorbrewer'
],
function (Point, MarkerView, inherits, d3, colorbrewer) {
var SymbolView = function (point, opts) {
opts = opts || {};
this._maxMetricValue = opts.maxMetricValue;
MarkerView.apply(this, arguments);
};
inherits(SymbolView, MarkerView);
SymbolView.prototype.getRadius = function () {
var getSize = d3.scale.linear()
.domain(this.getDomain())
.range([7.5, 25]);
return getSize(this.getValue());
};
SymbolView.prototype.getValue = function () {
return this._point.getCollection().heatIndex;
};
SymbolView.prototype.render = function () {
MarkerView.prototype.render.call(this, this.getRadius());
var getColor = d3.scale.quantize()
.domain(this.getDomain())
.range(colorbrewer.YlOrRd[5]);
this.el.attr('fill', getColor(this.getValue()));
};
SymbolView.prototype.getDomain = function () {
return [0, this._maxMetricValue()];
};
return SymbolView;
});
| define([
'streamhub-map/point',
'streamhub-map/views/marker-view',
'inherits',
'd3',
'colorbrewer'
],
function (Point, MarkerView, inherits, d3, colorbrewer) {
var SymbolView = function (point, opts) {
opts = opts || {};
this._maxMetricValue = opts.maxMetricValue;
MarkerView.apply(this, arguments);
};
inherits(SymbolView, MarkerView);
SymbolView.prototype.getRadius = function () {
var getSize = d3.scale.linear()
.domain(this.getDomain())
.range([7.5, 25]);
return getSize(this.getValue());
};
SymbolView.prototype.getValue = function () {
return this._point.getCollection().heatIndex;
};
SymbolView.prototype.render = function () {
MarkerView.prototype.render.call(this, this.getRadius());
var getColor = d3.scale.quantize()
.domain(this.getDomain())
.range(colorbrewer.YlOrRd[9]);
this.el.attr('fill', getColor(this.getValue()));
};
SymbolView.prototype.getDomain = function () {
return [0, this._maxMetricValue()];
};
return SymbolView;
});
|
Add caveat about symbols to string error message | /**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
module.exports = function(context) {
function report(node, name, msg) {
context.report(node, `Do not use the ${name} constructor. ${msg}`);
}
function check(node) {
const name = node.callee.name;
switch (name) {
case 'Boolean':
report(
node,
name,
'To cast a value to a boolean, use double negation: !!value'
);
break;
case 'String':
report(
node,
name,
'To cast a value to a string, concat it with the empty string ' +
'(unless it\'s a symbol, which have different semantics): ' +
'\'\' + value'
);
break;
}
}
return {
CallExpression: check,
NewExpression: check,
};
};
| /**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
module.exports = function(context) {
function check(node) {
const name = node.callee.name;
let msg = null;
switch (name) {
case 'Boolean':
msg = 'To cast a value to a boolean, use double negation: !!value';
break;
case 'String':
msg = 'To cast a value to a string, concat it with the empty string: \'\' + value';
break;
}
if (msg) {
context.report(node, `Do not use the ${name} constructor. ${msg}`);
}
}
return {
CallExpression: check,
NewExpression: check,
};
};
|
Add a fuzz call for SBCommunication: obj.connect(None).
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146912 91177308-0d34-0410-b5e6-96231b3b80d8 | """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
broadcaster = obj.GetBroadcaster()
# Do fuzz testing on the broadcaster obj, it should not crash lldb.
import sb_broadcaster
sb_broadcaster.fuzz_obj(broadcaster)
obj.AdoptFileDesriptor(0, False)
obj.AdoptFileDesriptor(1, False)
obj.AdoptFileDesriptor(2, False)
obj.Connect("file:/tmp/myfile")
obj.Connect(None)
obj.Disconnect()
obj.IsConnected()
obj.GetCloseOnEOF()
obj.SetCloseOnEOF(True)
obj.SetCloseOnEOF(False)
#obj.Write(None, sys.maxint, None)
#obj.Read(None, sys.maxint, 0xffffffff, None)
obj.ReadThreadStart()
obj.ReadThreadStop()
obj.ReadThreadIsRunning()
obj.SetReadThreadBytesReceivedCallback(None, None)
| """
Fuzz tests an object after the default construction to make sure it does not crash lldb.
"""
import sys
import lldb
def fuzz_obj(obj):
broadcaster = obj.GetBroadcaster()
# Do fuzz testing on the broadcaster obj, it should not crash lldb.
import sb_broadcaster
sb_broadcaster.fuzz_obj(broadcaster)
obj.AdoptFileDesriptor(0, False)
obj.AdoptFileDesriptor(1, False)
obj.AdoptFileDesriptor(2, False)
obj.Connect("file:/tmp/myfile")
obj.Disconnect()
obj.IsConnected()
obj.GetCloseOnEOF()
obj.SetCloseOnEOF(True)
obj.SetCloseOnEOF(False)
#obj.Write(None, sys.maxint, None)
#obj.Read(None, sys.maxint, 0xffffffff, None)
obj.ReadThreadStart()
obj.ReadThreadStop()
obj.ReadThreadIsRunning()
obj.SetReadThreadBytesReceivedCallback(None, None)
|
Add simple Template constructor to simplify code | module.exports = function parse(value){
if(isTemplateString(value)){
var parameter = Parameter(value);
return Template(function (context){
if(typeof context === "undefined"){
context = {};
}
return context[parameter.key] || parameter.defaultValue;
}, [parameter]);
} else {
return Template(function (){
return value;
}, []);
}
};
// Checks whether a given string fits the form {{xyz}}.
function isTemplateString(str){
return (
(str.length > 5)
&&
(str.substr(0, 2) === "{{")
&&
(str.substr(str.length - 2, 2) === "}}")
);
}
// Constructs a parameter object from the given template string.
// e.g. "{{xyz}}" --> { key: "xyz" }
// e.g. "{{xyz:foo}}" --> { key: "xyz", defaultValue: "foo" }
function Parameter(str){
// Extract the key.
var parameter = {
key: str.substring(2, str.length - 2)
};
// Handle default values.
var colonIndex = parameter.key.indexOf(":");
if(colonIndex !== -1){
parameter.defaultValue = parameter.key.substr(colonIndex + 1);
parameter.key = parameter.key.substr(0, colonIndex);
}
return parameter;
}
// Constructs a template function with `parameters` property.
function Template(fn, parameters){
fn.parameters = parameters;
return fn;
}
| module.exports = function parse(value){
if(isTemplateString(value)){
var parameter = Parameter(value);
var template = function (context){
if(typeof context === "undefined"){
context = {};
}
return context[parameter.key] || parameter.defaultValue;
};
template.parameters = [parameter];
return template;
} else {
var template = function (context){
return value;
};
template.parameters = [];
return template;
}
};
// Checks whether a given string fits the form {{xyz}}.
function isTemplateString(str){
return (
(str.length > 5)
&&
(str.substr(0, 2) === "{{")
&&
(str.substr(str.length - 2, 2) === "}}")
);
}
// Constructs a parameter object from the given template string.
// e.g. "{{xyz}}" --> { key: "xyz" }
// e.g. "{{xyz:foo}}" --> { key: "xyz", defaultValue: "foo" }
function Parameter(str){
// Extract the key.
var parameter = {
key: str.substring(2, str.length - 2)
};
// Handle default values.
var colonIndex = parameter.key.indexOf(":");
if(colonIndex !== -1){
parameter.defaultValue = parameter.key.substr(colonIndex + 1);
parameter.key = parameter.key.substr(0, colonIndex);
}
return parameter;
}
|
Allow gridlines on both major and minor axes. | from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
self.which = 'major'
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
axes.grid(color=self.color, linestyle=self.style,
which=self.which)
# Gridlines should be below plots
axes.set_axisbelow(True)
| from boomslang.LineStyle import LineStyle
class Grid(object):
def __init__(self, color="#dddddd", style="-", visible=True):
self.color = color
self._lineStyle = LineStyle()
self._lineStyle.style = style
self.visible = visible
@property
def style(self):
return self._lineStyle.style
@style.setter
def style(self, value):
self._lineStyle.style = value
@style.getter
def style(self):
return self._lineStyle.style
def draw(self, fig, axes):
if self.visible:
axes.grid(color=self.color, linestyle=self.style)
# Gridlines should be below plots
axes.set_axisbelow(True)
|
Reformat the code to match the rest of Paper.js | /**
* Imports svg into items with groups
* Stetson Alpha - Paper.js
*
*/
var ImportSVG = this.ImportSVG = Base.extend({
{
//initialize
initialize: function()
{
},
/**
*
* Takes the svg dom obj and parses the data
* to create a layer with groups (if needed) with
* items inside. Should support nested groups.
*
* takes in a svg object (xml dom)
* returns Paper.js Layer
*/
importSVG: function(svg)
{
//TODO: return layer;
},
/**
* Creates a Paper.js Group by parsing
* a specific svg g node
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
importGroup: function(svg)
{
//TODO: return group;
},
/**
* Creates a Paper.js Path by parsing
* a specific svg node (rect, path, circle, polygon, etc)
* and creating the right path object based on the svg type.
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
importPath: function(svg)
{
//TODO: return path;
}
}); | /**
* Imports svg into items with groups
* Stetson Alpha - Paper.js
*
*/
var ImportSVG = function()
{
//initialize
function initialize()
{
};
/**
*
* Takes the svg dom obj and parses the data
* to create a layer with groups (if needed) with
* items inside. Should support nested groups.
*
* takes in a svg object (xml dom)
* returns Paper.js Layer
*/
this.importSVG = function(svg)
{
return layer;
};
/**
* Creates a Paper.js Group by parsing
* a specific svg g node
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importGroup(svg)
{
return group;
};
/**
* Creates a Paper.js Path by parsing
* a specific svg node (rect, path, circle, polygon, etc)
* and creating the right path object based on the svg type.
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importPath(svg)
{
return path;
};
initialize(); // calls the init function after class is loaded
}; |
Add Y direction, bouncing, slowing | var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var Ball = function(x, y, radius, context) {
this.x = x;
this.y = y;
this.radius = radius || 10;
this.startAngle = 0;
this.endAngle = (Math.PI * 2);
this.context = context
this.speed = 3
this.xDirection = 1
this.yDirection = 1
}
Ball.prototype.draw = function () {
context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle);
context.fillStyle = "white"
context.fill();
return this;
};
Ball.prototype.move = function () {
this.x = this.x + (this.speed * this.xDirection);
this.y = this.y + (this.speed * this.yDirection);
if (this.x >= canvas.width - this.radius || this.x < 0) {
this.xDirection *= -1;
this.speed *= 0.8
}
if (this.y >= canvas.height - this.radius || this.y < 0) {
this.yDirection *= -1;
}
return this;
};
var golfBall = new Ball(400, 400, 5, 0);
requestAnimationFrame(function gameLoop() {
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
context.closePath();
golfBall.draw().move();
requestAnimationFrame(gameLoop);
});
module.exports = Ball;
| var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var Ball = function(x, y, radius, context) {
this.x = x;
this.y = y;
this.radius = radius || 10;
this.startAngle = 0;
this.endAngle = (Math.PI / 180) * 360;
this.context = context
this.speed = 0
}
Ball.prototype.draw = function () {
context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle);
context.fillStyle = "white"
context.fill();
return this;
};
Ball.prototype.move = function () {
if (this.x < canvas.width - this.radius && this.y < canvas.height - this.radius ){
this.x += this.speed;
// this.y += this.speed;
}
return this;
};
var golfBall = new Ball(350, 450, 5, 0);
requestAnimationFrame(function gameLoop() {
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
context.closePath();
golfBall.draw().move();
requestAnimationFrame(gameLoop);
});
module.exports = Ball;
|
Check for message model in api response | <?php
class Denkmal_Response_Api_MessageTest extends CMTest_TestCase {
protected function setUp() {
CM_Config::get()->Denkmal_Site->url = 'http://denkmal.test';
}
public function tearDown() {
CMTest_TH::clearEnv();
}
public function testMatch() {
$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'));
$response = CM_Response_Abstract::factory($request);
$this->assertInstanceOf('Denkmal_Response_Api_Message', $response);
}
public function testProcess() {
$venue = Denkmal_Model_Venue::create(array('name' => 'Example', 'queued' => true, 'enabled' => false));
$body = 'venue=' . urlencode($venue->getId()) . '&text=' . urlencode('hallo test');
$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'), $body);
$response = new Denkmal_Response_Api_Message($request);
$response->process();
$messageList = new Denkmal_Paging_Message_All();
$this->assertCount(1, $messageList);
/** @var Denkmal_Model_Message $message */
$message = $messageList->getItem(0);
$this->assertEquals($venue, $message->getVenue());
$this->assertSame('hallo test', $message->getText());
$this->assertSameTime(time(), $message->getCreated());
}
}
| <?php
class Denkmal_Response_Api_MessageTest extends CMTest_TestCase {
protected function setUp() {
CM_Config::get()->Denkmal_Site->url = 'http://denkmal.test';
}
public function tearDown() {
CMTest_TH::clearEnv();
}
public function testMatch() {
$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'));
$response = CM_Response_Abstract::factory($request);
$this->assertInstanceOf('Denkmal_Response_Api_Message', $response);
}
public function testProcess() {
$venue = Denkmal_Model_Venue::create(array('name' => 'Example', 'queued' => true, 'enabled' => false));
$body = 'venue=' . urlencode($venue->getId()) . '&text=' . urlencode('hallo test');
$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'), $body);
$response = new Denkmal_Response_Api_Message($request);
$response->process();
}
}
|
Correct the documentation for supported VNC modes | export const INIT_CONSOLE = 'INIT_CONSOLE'
export const DOWNLOAD_CONSOLE = 'DOWNLOAD_CONSOLE'
export const DISCONNECTED_CONSOLE = 'DISCONNECTED_CONSOLE'
export const OPEN_CONSOLE_MODAL = 'OPEN_CONSOLE_MODAL'
export const CLOSE_CONSOLE_MODAL = 'CLOSE_CONSOLE_MODAL'
export const SET_IN_USE_CONSOLE_MODAL_STATE = 'SET_IN_USE_CONSOLE_MODAL_STATE'
export const SET_LOGON_CONSOLE_MODAL_STATE = 'SET_LOGON_CONSOLE_MODAL_STATE'
export const SET_NEW_CONSOLE_MODAL = 'SET_NEW_CONSOLE_MODAL'
export const CONSOLE_OPENED = 'OPENED'
export const CONSOLE_IN_USE = 'IN_USE'
export const CONSOLE_LOGON = 'LOGON'
export const RDP_ID = 'rdp'
// console protocols
export const VNC = 'vnc'
export const SPICE = 'spice'
export const RDP = 'rdp'
// VNC modes sent from the backend (config property ClientModeVncDefault)
export const NO_VNC = 'NoVnc'
export const NATIVE = 'Native'
// UI console types (for spice and rdp protocol name is used directly)
export const BROWSER_VNC = 'BrowserVnc'
export const NATIVE_VNC = 'NativeVnc'
| export const INIT_CONSOLE = 'INIT_CONSOLE'
export const DOWNLOAD_CONSOLE = 'DOWNLOAD_CONSOLE'
export const DISCONNECTED_CONSOLE = 'DISCONNECTED_CONSOLE'
export const OPEN_CONSOLE_MODAL = 'OPEN_CONSOLE_MODAL'
export const CLOSE_CONSOLE_MODAL = 'CLOSE_CONSOLE_MODAL'
export const SET_IN_USE_CONSOLE_MODAL_STATE = 'SET_IN_USE_CONSOLE_MODAL_STATE'
export const SET_LOGON_CONSOLE_MODAL_STATE = 'SET_LOGON_CONSOLE_MODAL_STATE'
export const SET_NEW_CONSOLE_MODAL = 'SET_NEW_CONSOLE_MODAL'
export const CONSOLE_OPENED = 'OPENED'
export const CONSOLE_IN_USE = 'IN_USE'
export const CONSOLE_LOGON = 'LOGON'
export const RDP_ID = 'rdp'
// console protocols
export const VNC = 'vnc'
export const SPICE = 'spice'
export const RDP = 'rdp'
// VNC modes sent from the backend (ClientConsoleMode)
export const NO_VNC = 'NoVnc'
export const NATIVE = 'Native'
// UI console types (for spice and rdp protocol name is used directly)
export const BROWSER_VNC = 'BrowserVnc'
export const NATIVE_VNC = 'NativeVnc'
|
Send token on change password | import { inject as service } from '@ember/service'
import Controller from '@ember/controller'
import { badRequest, notFound } from '../utils/request'
export default Controller.extend({
pilasBloquesApi: service(),
queryParams: ['token'],
token: null,
credentials: {},
usernameExists: true, // Default true for (no) error visualization
wrongCredentials: false,
actions: {
checkUsername(cb) {
this.pilasBloquesApi.passwordRecovery(this.credentials.username)
.then((credentials) => {
this.set("usernameExists", true)
this.set("credentials", credentials)
cb()
})
.catch(notFound(() => {
this.set("usernameExists", false)
}))
},
changePassword(cb) {
this.set("wrongCredentials", false)
this.set("credentials.token", this.token)
this.pilasBloquesApi.changePassword(this.credentials)
.then(cb)
.catch(badRequest(() => {
this.set("wrongCredentials", true)
this.set("credentials.password", "")
}))
},
}
}) | import { inject as service } from '@ember/service'
import Controller from '@ember/controller'
import { badRequest } from '../utils/request'
export default Controller.extend({
pilasBloquesApi: service(),
credentials: {},
usernameExists: true, // Default true for (no) error visualization
wrongCredentials: false,
actions: {
checkUsername(cb) {
this.pilasBloquesApi.passwordRecovery(this.credentials.username)
.then((credentials) => {
this.set("usernameExists", true)
this.set("credentials", credentials)
cb()
})
.catch(notFound(() => {
this.set("usernameExists", false)
}))
},
changePassword(cb) {
this.set("wrongCredentials", false)
this.pilasBloquesApi.changePassword(this.credentials)
.then(cb)
.catch(badRequest(() => {
this.set("wrongCredentials", true)
this.set("credentials.password", "")
}))
},
}
}) |
Add support for Meteor 1.2 | // package metadata file for Meteor.js
/* jshint strict:false */
/* global Package:true */
Package.describe({
name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap
summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.',
version: '3.3.5',
git: 'https://github.com/twbs/bootstrap.git'
});
Package.onUse(function (api) {
api.versionsFrom('METEOR@1.0');
api.use('jquery', 'client');
api.addFiles([
'dist/fonts/glyphicons-halflings-regular.eot',
'dist/fonts/glyphicons-halflings-regular.svg',
'dist/fonts/glyphicons-halflings-regular.ttf',
'dist/fonts/glyphicons-halflings-regular.woff',
'dist/fonts/glyphicons-halflings-regular.woff2'
], 'client', { isAsset: true });
api.addFiles([
'dist/css/bootstrap.css',
'dist/js/bootstrap.js'
], 'client');
});
| // package metadata file for Meteor.js
/* jshint strict:false */
/* global Package:true */
Package.describe({
name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap
summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.',
version: '3.3.5',
git: 'https://github.com/twbs/bootstrap.git'
});
Package.onUse(function (api) {
api.versionsFrom('METEOR@1.0');
api.use('jquery', 'client');
api.addFiles([
'dist/fonts/glyphicons-halflings-regular.eot',
'dist/fonts/glyphicons-halflings-regular.svg',
'dist/fonts/glyphicons-halflings-regular.ttf',
'dist/fonts/glyphicons-halflings-regular.woff',
'dist/fonts/glyphicons-halflings-regular.woff2',
'dist/css/bootstrap.css',
'dist/js/bootstrap.js'
], 'client');
});
|
Add semi-colon and use dot notation. | //Filter experiment or computation templates
Application.Filters.filter('byMediaType', function () {
return function (items, values) {
var matches = [];
if (items) {
items.forEach(function(item) {
if ('mediatype' in item) {
values.forEach(function(val){
if (item.mediatype === val){
matches.push(item);
}
});
}
});
}
return matches;
};
});
| //Filter experiment or computation templates
Application.Filters.filter('byMediaType', function () {
return function (items, values) {
var matches = [];
if (items) {
items.forEach(function(item) {
if ('mediatype' in item) {
values.forEach(function(val){
if (item['mediatype'] == val){
matches.push(item);
}
})
}
});
}
return matches;
};
});
|
Make bodyParser play well with PATCH too. | // Copyright 2012 Mark Cavage, Inc. All rights reserved.
var jsonParser = require('./json_body_parser');
var formParser = require('./form_body_parser');
var multipartParser = require('./multipart_parser');
var errors = require('../errors');
var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError;
function bodyParser(options) {
var parseForm = formParser(options);
var parseJson = jsonParser(options);
var parseMultipart = multipartParser(options);
return function parseBody(req, res, next) {
if (req.method !== 'POST' && req.method !== 'PUT' && req.method !== 'PATCH')
return next();
if (req.contentLength === 0 && !req.chunked)
return next();
if (req.contentType === 'application/json') {
return parseJson(req, res, next);
} else if (req.contentType === 'application/x-www-form-urlencoded') {
return parseForm(req, res, next);
} else if (req.contentType === 'multipart/form-data') {
return parseMultipart(req, res, next);
} else if (options.rejectUnknown !== false) {
return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' +
req.contentType));
}
return next();
};
}
module.exports = bodyParser;
| // Copyright 2012 Mark Cavage, Inc. All rights reserved.
var jsonParser = require('./json_body_parser');
var formParser = require('./form_body_parser');
var multipartParser = require('./multipart_parser');
var errors = require('../errors');
var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError;
function bodyParser(options) {
var parseForm = formParser(options);
var parseJson = jsonParser(options);
var parseMultipart = multipartParser(options);
return function parseBody(req, res, next) {
if (req.method !== 'POST' && req.method !== 'PUT')
return next();
if (req.contentLength === 0 && !req.chunked)
return next();
if (req.contentType === 'application/json') {
return parseJson(req, res, next);
} else if (req.contentType === 'application/x-www-form-urlencoded') {
return parseForm(req, res, next);
} else if (req.contentType === 'multipart/form-data') {
return parseMultipart(req, res, next);
} else if (options.rejectUnknown !== false) {
return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' +
req.contentType));
}
return next();
};
}
module.exports = bodyParser;
|
Fix plan details test name | from changes.testutils import APITestCase
class PlanDetailsTest(APITestCase):
def test_simple(self):
project1 = self.create_project()
project2 = self.create_project()
plan1 = self.create_plan(label='Foo')
plan1.projects.append(project1)
plan1.projects.append(project2)
path = '/api/0/plans/{0}/'.format(plan1.id.hex)
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert data['id'] == plan1.id.hex
assert len(data['projects']) == 2
assert data['projects'][0]['id'] == project1.id.hex
assert data['projects'][1]['id'] == project2.id.hex
| from changes.testutils import APITestCase
class PlanIndexTest(APITestCase):
def test_simple(self):
project1 = self.create_project()
project2 = self.create_project()
plan1 = self.create_plan(label='Foo')
plan1.projects.append(project1)
plan1.projects.append(project2)
path = '/api/0/plans/{0}/'.format(plan1.id.hex)
resp = self.client.get(path)
assert resp.status_code == 200
data = self.unserialize(resp)
assert data['id'] == plan1.id.hex
assert len(data['projects']) == 2
assert data['projects'][0]['id'] == project1.id.hex
assert data['projects'][1]['id'] == project2.id.hex
|
Simplify assertion; testing for empty content is done by the parent | <?php
declare(strict_types=1);
namespace SimpleSAML\SAML2\XML\md;
use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Exception\ProtocolViolationException;
use function filter_var;
/**
* Abstract class implementing LocalizedURIType.
*
* @package simplesamlphp/saml2
*/
abstract class AbstractLocalizedURI extends AbstractLocalizedName
{
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
parent::validateContent($content);
Assert::false(
!filter_var($content, FILTER_VALIDATE_URL),
$this->getQualifiedName() . ' is not a valid URL.',
ProtocolViolationException::class,
);
}
}
| <?php
declare(strict_types=1);
namespace SimpleSAML\SAML2\XML\md;
use SimpleSAML\Assert\Assert;
use SimpleSAML\SAML2\Exception\ProtocolViolationException;
use function filter_var;
/**
* Abstract class implementing LocalizedURIType.
*
* @package simplesamlphp/saml2
*/
abstract class AbstractLocalizedURI extends AbstractLocalizedName
{
/**
* Validate the content of the element.
*
* @param string $content The value to go in the XML textContent
* @throws \Exception on failure
* @return void
*/
protected function validateContent(string $content): void
{
parent::validateContent($content);
Assert::false(
!empty($content) && !filter_var($content, FILTER_VALIDATE_URL),
$this->getQualifiedName() . ' is not a valid URL.',
ProtocolViolationException::class,
);
}
}
|
Change the datatype of length to int | package Controllers;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Image
{
private String filename;
private int length;
private InputStream content;
public Image(String filename) throws FileNotFoundException
{
super();
this.filename = filename;
}
public String getFilename()
{
return filename;
}
public void setFilename(String filename)
{
this.filename = filename;
}
public int getLength()
{
return length;
}
public void setLength(int length)
{
this.length = length;
}
public InputStream getContent()
{
return content;
}
public void setContent(InputStream content)
{
this.content = content;
}
}
| package Controllers;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Image
{
private String filename;
private Long length;
private InputStream content;
public Image(String filename) throws FileNotFoundException
{
super();
this.filename = filename;
}
public String getFilename()
{
return filename;
}
public void setFilename(String filename)
{
this.filename = filename;
}
public Long getLength()
{
return length;
}
public void setLength(Long length)
{
this.length = length;
}
public InputStream getContent()
{
return content;
}
public void setContent(InputStream content)
{
this.content = content;
}
}
|
Put note in output about code coverage not 100% | #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-clover clover.xml tests/DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100% but we need to get there ASAP\n");
exit(0);
}
}
echo "Code coverage was 100%\n";
| #!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-clover clover.xml tests/DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(0); //TODO: Get code coverage to 100%
}
}
echo "Code coverage was 100%\n";
|
Make it a bit more demo-able | import Crafty from 'crafty';
import 'app/components/camera_relative_motion';
Crafty.init(800,600, document.getElementById('game'));
Crafty.background('#000');
Crafty.e('2D, WebGL, Color, Fourway').attr({
x: 200,
y: 200,
w: 20,
h: 20,
z: 5
}).color('#F00');
Crafty.e('2D, Fourway').fourway(100).bind('MotionChange', function(property) {
let newValue = {};
newValue[property.key] = this[property.key];
Crafty.s('CameraSystem').camera.attr(newValue);
})
Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
x: 700,
y: 100,
w: 30,
h: 400,
z: 10
}).color('#00F')
Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
x: 500,
y: 150,
w: 20,
h: 300
}).color('#0F0').cameraRelativeMotion({ xResponse: 0.5, yResponse: 0.5 });
| import Crafty from 'crafty';
import 'app/components/camera_relative_motion';
Crafty.init(800,600, document.getElementById('game'));
Crafty.background('#000');
Crafty.e('2D, WebGL, Color, Fourway').attr({
x: 0,
y: 0,
w: 20,
h: 20
}).color('#F00').fourway(100).bind('MotionChange', function(property) {
let newValue = {};
newValue[property.key] = this[property.key];
Crafty.s('CameraSystem').camera.attr(newValue);
})
Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
x: 400,
y: 400,
w: 20,
h: 20
}).color('#00F')
Crafty.e('2D, WebGL, Color, CameraRelativeMotion').attr({
x: 300,
y: 200,
w: 20,
h: 20
}).color('#0F0').cameraRelativeMotion({ xResponse: 0.5, yResponse: 0.5 });
|
Test sending an unparsable message. | 'use strict';
const http = require('http');
const W3CWebSocket = require('websocket').w3cwebsocket;
const WebSocketAsPromised = require('websocket-as-promised');
const Actions = require('../../common');
const createWsServer = require('../ws_server');
const PORT = 5600;
const httpServer = http.createServer();
createWsServer({ httpServer });
const wsClient = new WebSocketAsPromised(`ws://localhost:${PORT}/`, {
createWebSocket: url => new W3CWebSocket(url, 'jcm2018'),
packMessage: data => JSON.stringify(data),
unpackMessage: message => JSON.parse(message),
attachRequestId: (data, requestId) => ({ ...data, requestId }),
extractRequestId: data => data && data.requestId,
timeout: 5000
});
beforeAll(async () => {
httpServer.listen(PORT);
await wsClient.open();
});
afterAll(async () => {
await wsClient.close();
httpServer.close();
});
afterEach(() => {
wsClient.onMessage.removeAllListeners();
});
it('basic connectivity', async () => {
await wsClient.sendRequest({});
});
it('unparsable message', async done => {
wsClient.onMessage.addListener(message => {
const parsed = JSON.parse(message);
expect(parsed.code).toEqual(Actions.CODE_UNPARSABLE_MESSAGE);
done();
});
await wsClient.send('--');
});
| 'use strict';
const http = require('http');
const W3CWebSocket = require('websocket').w3cwebsocket;
const WebSocketAsPromised = require('websocket-as-promised');
const createWsServer = require('../ws_server');
const PORT = 5600;
const httpServer = http.createServer();
createWsServer({ httpServer });
const wsClient = new WebSocketAsPromised(`ws://localhost:${PORT}/`, {
createWebSocket: url => new W3CWebSocket(url, 'jcm2018'),
packMessage: data => JSON.stringify(data),
unpackMessage: message => JSON.parse(message),
attachRequestId: (data, requestId) => ({ ...data, requestId }),
extractRequestId: data => data && data.requestId,
timeout: 5000
});
beforeAll(async () => {
httpServer.listen(PORT);
await wsClient.open();
});
afterAll(async () => {
await wsClient.close();
httpServer.close();
});
it('basic connectivity', async () => {
await wsClient.sendRequest({});
});
|
Add preliminary ErrorAnalysis test case | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..common import DynamicMethods
from ..expr import Expr, ExprTreeTransformer
from ..semantics import cast_error
class Analysis(DynamicMethods):
def __init__(self, e, **kwargs):
super(Analysis, self).__init__()
self.e = e
self.s = ExprTreeTransformer(Expr(e), **kwargs).closure()
def analyse(self):
return [(self._analyse(t), t) for t in self.s]
def _analyse(self, t):
l = self.list_methods(lambda m: m.endswith('analysis'))
return (f(t) for f in l)
class ErrorAnalysis(Analysis):
def __init__(self, e, v, **kwargs):
super(ErrorAnalysis, self).__init__(e, **kwargs)
self.v = v
def error_analysis(self, t):
return t.error(self.v)
if __name__ == '__main__':
e = '((a + 2) * (a + 3))'
ErrorAnalysis(e, {'a': cast_error('0.1', '0.2')})
| #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..common import DynamicMethods
from ..expr import Expr, ExprTreeTransformer
from ..semantics import cast_error
class Analysis(DynamicMethods):
def __init__(self, e, **kwargs):
super(Analysis, self).__init__()
self.e = e
self.s = ExprTreeTransformer(Expr(e), **kwargs).closure()
def analyse(self):
return [(self._analyse(t), t) for t in self.s]
def _analyse(self, t):
l = self.list_methods(lambda m: m.endswith('analysis'))
return (f(t) for f in l)
class ErrorAnalysis(Analysis):
def __init__(self, e, v, **kwargs):
super(ErrorAnalysis, self).__init__(e, **kwargs)
self.v = v
def error_analysis(self, t):
return t.error(self.v)
|
Add Photo, Quote, Link posts | package tumblr
// Defines each subtype of Post (see consts below) and factory methods
// Post Types
const (
Text = "text"
Quote = "quote"
Link = "link"
Answer = "answer"
Video = "video"
Audio = "audio"
Photo = "photo"
Chat = "chat"
)
// Stuff in the "response":"posts" field
type Post struct {
BlogName string
Id int64
PostURL string
Type string
Timestamp int64
Date string
Format string
ReblogKey string
Tags []string
Bookmarklet bool
Mobile bool
SourceURL string
SourceTitle string
Liked bool
State string // published, ueued, draft, private
TotalPosts int64 // total posts in result set for pagination
}
type TextPost struct {
Post
Title string
Body string
}
// Photo post
type PhotoPost struct {
Post
Photos []PhotoData
Caption string
Width int64
Height int64
}
// One photo in a PhotoPost
type PhotoData struct {
Caption string // photosets only
AltSizes []AltSizeData
}
// One alternate size of a Photo
type AltSizeData struct {
Width int
Height int
URL string
}
// Quote post
type QuotePost struct {
Post
Text string
Source string
}
// Link post
type LinkPost struct {
Title string
URL string
Description string
}
| package tumblr
// Defines each subtype of Post (see consts below) and factory methods
// Post Types
const (
Text = "text"
Quote = "quote"
Link = "link"
Answer = "answer"
Video = "video"
Audio = "audio"
Photo = "photo"
Chat = "chat"
)
// Stuff in the "response":"posts" field
type Post struct {
BlogName string
Id int64
PostURL string
Type string
Timestamp int64
Date string
Format string
ReblogKey string
Tags []string
Bookmarklet bool
Mobile bool
SourceURL string
SourceTitle string
Liked bool
State string // published, ueued, draft, private
TotalPosts int64 // total posts in result set for pagination
}
type TextPost struct {
Post
Title string
Body string
}
type PhotoPost struct {
Post
Photos []PhotoData
}
type PhotoData struct {
}
|
Allow numbers in type format name (int32/int64) | <?php
namespace SwaggerGen\Swagger\Type;
/**
* Abstract foundation of all type definitions.
*
* @package SwaggerGen
* @author Martijn van der Lee <martijn@vanderlee.com>
* @copyright 2014-2015 Martijn van der Lee
* @license https://opensource.org/licenses/MIT MIT
*/
abstract class AbstractType extends \SwaggerGen\Swagger\AbstractObject
{
const REGEX_START = '/^';
const REGEX_FORMAT = '([a-z][a-z0-9]*)';
const REGEX_CONTENT = '(?:\((.*)\))?';
const REGEX_RANGE = '(?:([[<])(\\d*),(\\d*)([\\]>]))?';
const REGEX_DEFAULT = '(?:=(.+))?';
const REGEX_END = '$/i';
protected static function swap(&$a, &$b)
{
$tmp = $a;
$a = $b;
$b = $tmp;
}
/**
* @var string $definition
*/
public function __construct(\SwaggerGen\Swagger\AbstractObject $parent, $definition)
{
parent::__construct($parent);
$this->parseDefinition($definition);
}
abstract protected function parseDefinition($definition);
/**
* Overwrites default AbstractObject parser, since Types should not handle
* extensions themselves.
* @param string $command
* @param string $data
* @return boolean
*/
public function handleCommand($command, $data = null)
{
return false;
}
}
| <?php
namespace SwaggerGen\Swagger\Type;
/**
* Abstract foundation of all type definitions.
*
* @package SwaggerGen
* @author Martijn van der Lee <martijn@vanderlee.com>
* @copyright 2014-2015 Martijn van der Lee
* @license https://opensource.org/licenses/MIT MIT
*/
abstract class AbstractType extends \SwaggerGen\Swagger\AbstractObject
{
const REGEX_START = '/^';
const REGEX_FORMAT = '([a-z]+)';
const REGEX_CONTENT = '(?:\((.*)\))?';
const REGEX_RANGE = '(?:([[<])(\\d*),(\\d*)([\\]>]))?';
const REGEX_DEFAULT = '(?:=(.+))?';
const REGEX_END = '$/i';
protected static function swap(&$a, &$b)
{
$tmp = $a;
$a = $b;
$b = $tmp;
}
/**
* @var string $definition
*/
public function __construct(\SwaggerGen\Swagger\AbstractObject $parent, $definition)
{
parent::__construct($parent);
$this->parseDefinition($definition);
}
abstract protected function parseDefinition($definition);
/**
* Overwrites default AbstractObject parser, since Types should not handle
* extensions themselves.
* @param string $command
* @param string $data
* @return boolean
*/
public function handleCommand($command, $data = null)
{
return false;
}
}
|
Remove type hint from a method argument | <?php
namespace Ofelix03\Transformer;
/**
* @author Felix Otoo <ofelix03@gmail.com>
* @license MIT Check the license file associated with this package for detials of
* the copyright agreements.
*/
class TypeCaster {
const CAST_TYPES = [
'integer' => 'int',
'string' => 'string',
'float' => 'float',
'bool' => 'bool',
'array' => 'array',
];
static function cast($value, $type = "") {
if (is_null($value)) {
throw new \InvalidArgumentException('A value is need for casting. First arugment should be a value to be casted');
}
if (is_null($type)) {
throw new \InvalidArgumentException('A type to cast the value to is needed, none given');
}
if (static::CAST_TYPES['integer'] === $type) {
return (int) $value;
} else if (static::CAST_TYPES['string'] === $type) {
return (string) $value;
} else if (static::CAST_TYPES['bool'] === $type) {
return (bool) $value;
} else if (static::CAST_TYPES['array'] === $type) {
return (array) $value;
}
}
}
| <?php
namespace Ofelix03\Transformer;
/**
* @author Felix Otoo <ofelix03@gmail.com>
* @license MIT Check the license file associated with this package for detials of
* the copyright agreements.
*/
class TypeCaster {
const CAST_TYPES = [
'integer' => 'int',
'string' => 'string',
'float' => 'float',
'bool' => 'bool',
'array' => 'array',
];
static function cast($value, string $type) {
if (is_null($value)) {
throw new \InvalidArgumentException('A value is need for casting. First arugment should be a value to be casted');
}
if (is_null($type)) {
throw new \InvalidArgumentException('A type to cast the value to is needed, none given');
}
if (static::CAST_TYPES['integer'] === $type) {
return (int) $value;
} else if (static::CAST_TYPES['string'] === $type) {
return (string) $value;
} else if (static::CAST_TYPES['bool'] === $type) {
return (bool) $value;
} else if (static::CAST_TYPES['array'] === $type) {
return (array) $value;
}
}
}
|
Use Stringer interface for ApiErrors and ApiError. | package force
import (
"fmt"
"strings"
)
// Custom Error to handle salesforce api responses.
type ApiErrors []*ApiError
type ApiError struct {
Fields []string `json:"fields,omitempty" force:"fields,omitempty"`
Message string `json:"message,omitempty" force:"message,omitempty"`
ErrorCode string `json:"errorCode,omitempty" force:"errorCode,omitempty"`
ErrorName string `json:"error,omitempty" force:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty" force:"error_description,omitempty"`
}
func (e ApiErrors) Error() string {
return e.String()
}
func (e ApiErrors) String() string {
s := make([]string, len(e))
for i, err := range e {
s[i] = err.String()
}
return strings.Join(s, "\n")
}
func (e ApiErrors) Validate() bool {
if len(e) != 0 {
return true
}
return false
}
func (e ApiError) Error() string {
return e.String()
}
func (e ApiError) String() string {
return fmt.Sprintf("%#v", e)
}
func (e ApiError) Validate() bool {
if len(e.Fields) != 0 || len(e.Message) != 0 || len(e.ErrorCode) != 0 || len(e.ErrorName) != 0 || len(e.ErrorDescription) != 0 {
return true
}
return false
}
| package force
import (
"fmt"
)
// Custom Error to handle salesforce api responses.
type ApiErrors []*ApiError
type ApiError struct {
Fields []string `json:"fields,omitempty" force:"fields,omitempty"`
Message string `json:"message,omitempty" force:"message,omitempty"`
ErrorCode string `json:"errorCode,omitempty" force:"errorCode,omitempty"`
ErrorName string `json:"error,omitempty" force:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty" force:"error_description,omitempty"`
}
func (e ApiErrors) Error() string {
return fmt.Sprintf("%#v", e.Errors())
}
func (e ApiErrors) Errors() []string {
eArr := make([]string, len(e))
for i, err := range e {
eArr[i] = err.Error()
}
return eArr
}
func (e ApiErrors) Validate() bool {
if len(e) != 0 {
return true
}
return false
}
func (e ApiError) Error() string {
return fmt.Sprintf("%#v", e)
}
func (e ApiError) Validate() bool {
if len(e.Fields) != 0 || len(e.Message) != 0 || len(e.ErrorCode) != 0 || len(e.ErrorName) != 0 || len(e.ErrorDescription) != 0 {
return true
}
return false
}
|
Update exporter to work with Anki ≥ 2.1.36
`exporters` now takes an argument.
See e3b4802f47395b9c1a75ff89505410e91f34477e
Introduced after 2.1.35 but before 2.1.36. (Testing explicitly shows
that this change is needed for 2.1.36 and 2.1.37, but breaks 2.1.35.)
Fix #113. | import os
import anki.exporting
import anki.hooks
import anki.utils
import aqt.exporting
import aqt.utils
from aqt import QFileDialog
from aqt.exporting import ExportDialog
from ...utils import constants
# aqt part:
def exporter_changed(self, exporter_id):
self.exporter = aqt.exporting.exporters(self.col)[exporter_id][1](self.col)
self.frm.includeMedia.setVisible(hasattr(self.exporter, "includeMedia"))
def get_save_file(parent, title, dir_description, key, ext, fname=None):
if ext == constants.ANKI_EXPORT_EXTENSION:
directory = str(QFileDialog.getExistingDirectory(caption="Select Export Directory",
directory=fname))
if directory:
return os.path.join(directory, str(anki.utils.intTime()))
return None
return aqt.utils.getSaveFile_old(parent, title, dir_description, key, ext, fname)
ExportDialog.exporterChanged = anki.hooks.wrap(ExportDialog.exporterChanged, exporter_changed)
aqt.utils.getSaveFile_old = aqt.utils.getSaveFile
aqt.exporting.getSaveFile = get_save_file # Overriding instance imported with from style import
aqt.utils.getSaveFile = get_save_file
| import os
import anki.exporting
import anki.hooks
import anki.utils
import aqt.exporting
import aqt.utils
from aqt import QFileDialog
from aqt.exporting import ExportDialog
from ...utils import constants
# aqt part:
def exporter_changed(self, exporter_id):
self.exporter = aqt.exporting.exporters()[exporter_id][1](self.col)
self.frm.includeMedia.setVisible(hasattr(self.exporter, "includeMedia"))
def get_save_file(parent, title, dir_description, key, ext, fname=None):
if ext == constants.ANKI_EXPORT_EXTENSION:
directory = str(QFileDialog.getExistingDirectory(caption="Select Export Directory",
directory=fname))
if directory:
return os.path.join(directory, str(anki.utils.intTime()))
return None
return aqt.utils.getSaveFile_old(parent, title, dir_description, key, ext, fname)
ExportDialog.exporterChanged = anki.hooks.wrap(ExportDialog.exporterChanged, exporter_changed)
aqt.utils.getSaveFile_old = aqt.utils.getSaveFile
aqt.exporting.getSaveFile = get_save_file # Overriding instance imported with from style import
aqt.utils.getSaveFile = get_save_file
|
Disable source map for production | const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
context: __dirname,
devtool: 'source-map',
entry: './app/index.jsx',
output: {
path: './public',
publicPath: '/',
filename: 'app-bundle.js'
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
compress: {
warnings: false
}
}),
new HtmlWebpackPlugin({
template: './app/index.html'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.css'],
root: [
path.join(__dirname, 'node_modules'),
path.join(__dirname, 'app')
]
}
}
| const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
context: __dirname,
devtool: 'source-map',
entry: './app/index.jsx',
output: {
path: './public',
publicPath: '/',
filename: 'app-bundle.js'
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: false
}
}),
new HtmlWebpackPlugin({
template: './app/index.html'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.css'],
root: [
path.join(__dirname, 'node_modules'),
path.join(__dirname, 'app')
]
}
}
|
Add a column to set a "parent" fuel | <?php
/*
* This file is part of SmartGas, an iOS app to find the best gas station nearby.
*
* (c) Fábio Santos <ffsantos92@gmail.com>
* (c) Mateus Silva <mateusgsilva_@hotmail.com>
* (c) Fábio Marques <fabio1956.epo@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTypesTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('types', function (Blueprint $table) {
$table->increments('id');
$table->string('value');
$table->integer('parent_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::dropIfExists('types');
}
}
| <?php
/*
* This file is part of SmartGas, an iOS app to find the best gas station nearby.
*
* (c) Fábio Santos <ffsantos92@gmail.com>
* (c) Mateus Silva <mateusgsilva_@hotmail.com>
* (c) Fábio Marques <fabio1956.epo@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTypesTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::create('types', function (Blueprint $table) {
$table->increments('id');
$table->string('value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::dropIfExists('types');
}
}
|
Change regex to find the css import directly after the template.
Fix bug in path to custom-component element. | const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
// Stamp css content into html during development.
router.get('/custom-components/:component/*.html', (req, res) => {
const element = req.params.component;
const elementPath = path.join(__dirname, `../../public/custom-components/${element}/${element}`);
fs.readFile(`${elementPath}.html`, 'utf-8', (err, html) => {
if (err) {
throw err;
}
fs.readFile(`${elementPath}.css`, 'utf-8', (err, css) => {
if (err) {
throw err;
}
// Find the style tag that references the component's css.
const stampLocation = new RegExp(`<template><link.*href=".*?${element}.css.*?".*?\/?>)`);
const taggedCss = `<template><style>${css}</style>`;
res.send(html.replace(stampLocation, taggedCss));
});
});
});
// Don't send the css file if it has been requested directly.
router.get('/custom-components/**/*.css', (req, res) => {
res.send('');
});
// TODO: Add route to transpile js on request.
//router.get('/custom-components/**/*.js', (req, res) => { });
module.exports = {
mountPath: '/',
router: router
};
| const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
// Stamp css content into html during development.
router.get('/custom-components/:component/*.html', (req, res) => {
const element = req.params.component;
const elementPath = path.join(__dirname, `../../public/${element}/${element}`);
fs.readFile(`${elementPath}.html`, { encoding: 'utf-8' }, function (err, html) {
if (err) {
throw err;
}
fs.readFile(`${elementPath}.css`, { encoding: 'utf-8' }, function (err, css) {
if (err) {
throw err;
}
// Find the style tag that references the component's css.
const stampLocation = new RegExp(`^[\S\s]+(<link.*href=".*?${element}.css.*?".*?\/>)`);
const taggedCss = `<style>${css}</style>`;
res.send(html.replace(stampLocation, taggedCss));
});
});
});
// Don't send the css file if it has been requested directly.
router.get('/custom-components/**/*.css', (req, res) => {
res.send('');
});
// TODO: Add route to transpile js on request.
//router.get('/custom-components/**/*.js', (req, res) => { });
module.exports = {
mountPath: '/',
router: router
};
|
Allow 4.x TPG (Terraform Provider Google)
* additionally align minimum 3.x release with VPC module requirement | // Copyright 2021 Google LLC
//
// 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 reswriter
const tfversions string = `
terraform {
required_version = ">= 0.13"
required_providers {
google = {
source = "hashicorp/google"
version = ">= 3.83, < 5.0"
}
google-beta = {
source = "hashicorp/google-beta"
version = ">= 3.83, < 5.0"
}
}
}
`
| // Copyright 2021 Google LLC
//
// 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 reswriter
const tfversions string = `
terraform {
required_version = ">= 0.13"
required_providers {
google = {
source = "hashicorp/google"
version = "~> 3.0"
}
google-beta = {
source = "hashicorp/google-beta"
version = "~> 3.0"
}
}
}
`
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.