text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add some Google Dev related YT Channel IDs
|
/*
* Copyright 2013 The GDG Frisbee Project
*
* 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.gdg.frisbee.android;
/**
* Created with IntelliJ IDEA.
* User: maui
* Date: 20.04.13
* Time: 12:19
*/
public class Const {
// Settings
public static final String SETTINGS_FIRST_START = "gdg_first_start";
public static final boolean SETTINGS_FIRST_START_DEFAULT = true;
public static final String GOOGLE_DEVELOPERS_YT_ID = "UC_x5XG1OV2P6uZZ5FSM9Ttw";
public static final String ANDROID_DEVELOPERS_YT_ID = "UCVHFbqXqoYvEWM1Ddxl0QDg";
public static final String YOUTUBE_DEVELOPERS_YT_ID = "UCtVd0c0tGXuTSbU5d8cSBUg";
}
|
/*
* Copyright 2013 The GDG Frisbee Project
*
* 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.gdg.frisbee.android;
/**
* Created with IntelliJ IDEA.
* User: maui
* Date: 20.04.13
* Time: 12:19
*/
public class Const {
// Settings
public static final String SETTINGS_FIRST_START = "gdg_first_start";
public static final boolean SETTINGS_FIRST_START_DEFAULT = true;
}
|
tests/dot: Test that x² == |x|²
|
from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x: Vector2):
assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
|
from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
|
[RN] Use a SafeAreaView for OverlayFrame
|
// @flow
import React, { Component, type Node } from 'react';
import { SafeAreaView } from 'react-native';
import { overlayFrame as styles } from './styles';
/**
* The type of the React {@code Component} props of {@code OverlayFrame}.
*/
type Props = {
/**
* The children components to be displayed into the overlay frame.
*/
children: Node,
};
/**
* Implements a React component to act as the frame for overlays.
*/
export default class OverlayFrame extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
return (
<SafeAreaView style = { styles.container }>
{ this.props.children }
</SafeAreaView>
);
}
}
|
// @flow
import React, { Component } from 'react';
import { View } from 'react-native';
import { overlayFrame as styles } from './styles';
/**
* The type of the React {@code Component} props of {@code OverlayFrame}.
*/
type Props = {
/**
* The children components to be displayed into the overlay frame.
*/
children?: React$Node,
};
/**
* Implements a React component to act as the frame for overlays.
*/
export default class OverlayFrame extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {React$Element}
*/
render() {
return (
<View style = { styles.container }>
{ this.props.children }
</View>
);
}
}
|
Add fix for analog watch
|
<?php /**
* Created by PhpStorm.
* User: Philipp Dippel
* Date: 31.05.17
* Time: 17:44
*/
?>
<div id="mainContainer">
<canvas id="mainCanvas" width="2000" height="2000"></canvas>
</div>
<script type="text/javascript">
$('document').ready(function ()
{
$.getScript("widgets/Analoguhr/ClockStyleKit.js")
.done(function (script, textStatus)
{
clock();
})
.fail(function (jqxhr, settings, exception)
{
console.error("Failed to load ClockStyleKit");
console.error(exception);
});
});
</script>
|
<?php /**
* Created by PhpStorm.
* User: Philipp Dippel
* Date: 31.05.17
* Time: 17:44
*/
?>
<div id="mainContainer">
<canvas id="mainCanvas" width="2000" height="2000"></canvas>
</div>
<script type="text/javascript">
$('document').ready(function ()
{
$.getScript("widgets/Analoguhr/ClockStylekit.js")
.done(function (script, textStatus)
{
clock();
})
.fail(function (jqxhr, settings, exception)
{
console.error("Failed to load ClockStylekit");
cosnole.error(exception);
});
});
</script>
|
Support for setting fake AWS creds
|
package com.github.mlk.junit.rules;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.github.mlk.junit.rules.helpers.dynamodb.DynamoExample;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
public class HttpDynamoDbRuleTest {
@Rule
public HttpDynamoDbRule subject = new HttpDynamoDbRule();
@Test
public void getterSetterTest() {
String randomValue = UUID.randomUUID().toString();
DynamoExample exampleClient = new DynamoExample(AmazonDynamoDBClientBuilder
.standard()
.withEndpointConfiguration(new EndpointConfiguration(subject.getEndpoint(), "eu-west-1"))
.build());
exampleClient.createTable();
exampleClient.setValue(1L, randomValue);
assertThat(exampleClient.getValue(1L), is(randomValue));
}
}
|
package com.github.mlk.junit.rules;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.github.mlk.junit.rules.helpers.dynamodb.DynamoExample;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
public class HttpDynamoDbRuleTest {
@Rule
public HttpDynamoDbRule subject = new HttpDynamoDbRule();
@Test
public void getterSetterTest() {
String randomValue = UUID.randomUUID().toString();
DynamoExample exampleClient = new DynamoExample(AmazonDynamoDBClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("anything", "anything")))
.withEndpointConfiguration(new EndpointConfiguration(subject.getEndpoint(), "eu-west-1"))
.build());
exampleClient.createTable();
exampleClient.setValue(1L, randomValue);
assertThat(exampleClient.getValue(1L), is(randomValue));
}
}
|
Fix sfEventLogger: add priority and event.name overriding
|
<?php
/**
* sfEventLogger sends log messages to the event dispatcher to be processed
* by registered loggers.
*
* @package symfony
* @subpackage log
* @author Jérôme Tamarelle <jtamarelle@groupe-exp.com>
*/
class sfEventLogger extends sfLogger
{
/**
* {@inheritDoc}
*/
public function initialize(sfEventDispatcher $dispatcher, $options = array())
{
$this->dispatcher = $dispatcher;
$this->options = $options;
if (isset($this->options['level']))
{
$this->setLogLevel($this->options['level']);
}
// Use the default "command.log" event if not overriden
if (!isset($this->options['event_name'])) {
$this->options['event_name'] = 'command.log';
}
}
/**
* {@inheritDoc}
*/
protected function doLog($message, $priority)
{
$this->dispatcher->notify(new sfEvent($this, $this->options['event_name'], array($message, 'priority' => $priority)));
}
}
|
<?php
/**
* sfEventLogger sends log messages to the event dispatcher to be processed
* by registered loggers.
*
* @package symfony
* @subpackage log
* @author Jérôme Tamarelle <jtamarelle@groupe-exp.com>
*/
class sfEventLogger extends sfLogger
{
/**
* {@inheritDoc}
*/
public function initialize(sfEventDispatcher $dispatcher, $options = array())
{
$this->dispatcher = $dispatcher;
$this->options = $options;
if (isset($this->options['level']))
{
$this->setLogLevel($this->options['level']);
}
}
/**
* {@inheritDoc}
*/
protected function doLog($message, $priority)
{
$this->dispatcher->notify(new sfEvent($this, 'command.log', array($message)));
}
}
|
Revert "Return no variance by default instead of null."
This reverts commit ab20a6a3bfbdbf406c0bbeb59b9a3b934c760d99.
|
package com.openxc.measurements;
import com.openxc.units.Unit;
import com.openxc.util.AgingData;
import com.openxc.util.Range;
public class Measurement<TheUnit extends Unit> implements MeasurementInterface {
private AgingData<TheUnit> mValue;
private Range<TheUnit> mRange;
public Measurement() {
mValue = new AgingData<TheUnit>();
}
public Measurement(TheUnit value) {
mValue = new AgingData<TheUnit>(value);
}
public Measurement(TheUnit value, Range<TheUnit> range) {
this(value);
mRange = range;
}
public double getAge() throws NoValueException {
return mValue.getAge();
}
public boolean hasRange() {
return mRange != null;
}
public Range<TheUnit> getRange() throws NoRangeException {
if(!hasRange()) {
throw new NoRangeException();
}
return mRange;
}
public TheUnit getVariance() {
return null;
}
public TheUnit getValue() throws NoValueException {
return mValue.getValue();
}
public boolean isNone() {
return mValue.isNone();
}
}
|
package com.openxc.measurements;
import com.openxc.units.Unit;
import com.openxc.util.AgingData;
import com.openxc.util.Range;
public class Measurement<TheUnit extends Unit> implements MeasurementInterface {
private AgingData<TheUnit> mValue;
private Range<TheUnit> mRange;
public Measurement() {
mValue = new AgingData<TheUnit>();
}
public Measurement(TheUnit value) {
mValue = new AgingData<TheUnit>(value);
}
public Measurement(TheUnit value, Range<TheUnit> range) {
this(value);
mRange = range;
}
public double getAge() throws NoValueException {
return mValue.getAge();
}
public boolean hasRange() {
return mRange != null;
}
public Range<TheUnit> getRange() throws NoRangeException {
if(!hasRange()) {
throw new NoRangeException();
}
return mRange;
}
public TheUnit getVariance() {
return 0.0;
}
public TheUnit getValue() throws NoValueException {
return mValue.getValue();
}
public boolean isNone() {
return mValue.isNone();
}
}
|
Comment was just not true anymore
[ci skip]
|
package i5.las2peer.persistency;
/**
* The old XmlAble interface enforced an setStateFromXmlMethod.
*
* Due to several problems I decided to remove this method and leave the <i>deserialization</i>
* in the hand of the programmer.
*
* If standard methods are to be used, the programmer of an XmlAble class should used one of
* the following methods
*
* <ol>
* <li>Use a factory called createFromXml ( String xml )<br>
* This is the preferred idea. An interface may not enforce static methods however...</li>
* <li>Use a Constructor with a single String parameter</li>
* <li>Use a base constructor in combination with setStateFromXml ( String )<br>
* This corresponds to the old XmlAble.</li>
* </ol>
*
* @author Holger Janßen
*
*/
public interface XmlAble
{
/**
* Returns a XML representation of this object.
*
*
* @return a String
*
*/
public String toXmlString ();
}
|
package i5.las2peer.persistency;
/**
* The old XmlAble interface enforced an setStateFromXmlMethod.
*
* Due to several problems I decided to remove this method and leave the <i>deserialization</i>
* in the hand of the programmer.
*
* If standard methods are to be used, the programmer of an XmlAble class should used one of
* the following methods
*
* <ol>
* <li>Use a factory called createFromXml ( String xml )<br>
* This is the preferred idea. An interface may not enforce static methods however...</li>
* <li>Use a Constructor with a single String parameter</li>
* <li>Use a base constructor in combination with setStateFromXml ( String )<br>
* This corresponds to the old XmlAble.</li>
* </ol>
*
* @author Holger Janßen
*
*/
public interface XmlAble
{
/**
* Returns a XML representation of this object.
*
* This method will be used by an object manager to get a persistency representation
* of this object.
*
*
* @return a String
*
*/
public String toXmlString ();
}
|
Fix grunt task on watch
|
const path = require('path');
const fs = require('fs');
const sass = require('node-sass');
const { promisify } = require('util');
const mkdirp = require('mkdirp');
const renderAsPromised = promisify(sass.render);
const writeFileAsPromised = promisify(fs.writeFile);
const mkdirpAsPromised = promisify(mkdirp);
module.exports = function (grunt) {
grunt.registerMultiTask('sass', 'compile sass', function () {
let done = this.async(),
promises;
mkdirpAsPromised(path.dirname(this.data.dest))
.then(() => Promise.all(this.filesSrc.map((file) =>
renderAsPromised({ file })
.then(({ css }) => writeFileAsPromised(this.data.dest, css))
.then(() => grunt.log.ok(`Written ${this.data.dest}`))
)))
.then(done)
.catch(error => {
grunt.log.error(error);
done(false);
});
});
};
|
const path = require('path');
const fs = require('fs');
const sass = require('node-sass');
const { promisify } = require('util');
const mkdirp = require('mkdirp');
const renderAsPromised = promisify(sass.render);
const writeFileAsPromised = promisify(fs.writeFile);
const mkdirpAsPromised = promisify(mkdirp);
module.exports = function (grunt) {
grunt.registerMultiTask('sass', 'compile sass', function () {
let done = this.async(),
promises;
mkdirpAsPromised(path.dirname(this.data.dest))
.then(
Promise.all(this.filesSrc.map((file) =>
renderAsPromised({ file })
.then(({ css }) => writeFileAsPromised(this.data.dest, css)))
))
.then(() => {
grunt.log.ok(`Written ${this.data.dest}`);
done();
})
.catch(error => {
grunt.log.error(error);
done(false);
});
});
};
|
Change categories field to non required.
|
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Role(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(max_length=100)
weight = models.PositiveSmallIntegerField(default=1)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "categories"
ordering = ['weight']
class Employee(AbstractUser):
role = models.ForeignKey(Role, null=True, blank=True)
skype_id = models.CharField(max_length=200, null=True, blank=True)
last_month_score = models.PositiveIntegerField(default=0)
current_month_score = models.PositiveIntegerField(default=0)
level = models.PositiveIntegerField(default=0)
total_score = models.PositiveIntegerField(default=0)
avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
categories = models.ManyToManyField(Category, blank=True)
|
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Role(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Category(models.Model):
name = models.CharField(max_length=100)
weight = models.PositiveSmallIntegerField(default=1)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "categories"
ordering = ['weight']
class Employee(AbstractUser):
role = models.ForeignKey(Role, null=True, blank=True)
skype_id = models.CharField(max_length=200, null=True, blank=True)
last_month_score = models.PositiveIntegerField(default=0)
current_month_score = models.PositiveIntegerField(default=0)
level = models.PositiveIntegerField(default=0)
total_score = models.PositiveIntegerField(default=0)
avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
categories = models.ManyToManyField(Category)
|
Update to version 0.1.1 for the next push
|
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='savu',
version='0.1.1',
description='Savu Python Tomography Pipeline',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering'
],
author='Mark Basham',
author_email='scientificsoftware@diamond.ac.uk',
license='Apache License, Version 2.0',
packages=['savu',
'savu.core',
'savu.data',
'savu.mpi_test',
'savu.mpi_test.dls',
'savu.plugins',
'savu.test'],
include_package_data=True,
zip_safe=False)
|
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='savu',
version='0.1',
description='Savu Python Tomography Pipeline',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering'
],
author='Mark Basham',
author_email='scientificsoftware@diamond.ac.uk',
license='Apache License, Version 2.0',
packages=['savu',
'savu.core',
'savu.data',
'savu.mpi_test',
'savu.mpi_test.dls',
'savu.plugins',
'savu.test'],
include_package_data=True,
zip_safe=False)
|
Define a default value for the number of values used to populate KEYS.
|
<?php
namespace Predis\Commands;
abstract class ScriptedCommand extends ServerEval {
public abstract function getScript();
protected function keysCount() {
// The default behaviour is to use the first argument as the only value
// for KEYS and the rest of the arguments (if any) for ARGV. When -1 is
// returned, all the arguments are considered as values for KEYS.
return 1;
}
protected function filterArguments(Array $arguments) {
if (($keys = $this->keysCount()) === -1) {
$keys = count($arguments);
}
return array_merge(array($this->getScript(), $keys), $arguments);
}
protected function getKeys() {
$arguments = $this->getArguments();
if (($keys = $this->keysCount()) === -1) {
return array_slice($arguments, 2);
}
return array_slice($arguments, 2, $keys);
}
}
|
<?php
namespace Predis\Commands;
abstract class ScriptedCommand extends ServerEval {
public abstract function getScript();
public abstract function keysCount();
protected function filterArguments(Array $arguments) {
if (($keys = $this->keysCount()) === -1) {
$keys = count($arguments);
}
return array_merge(array($this->getScript(), $keys), $arguments);
}
protected function getKeys() {
$arguments = $this->getArguments();
if (($keys = $this->keysCount()) === -1) {
return array_slice($arguments, 2);
}
return array_slice($arguments, 2, $keys);
}
}
|
Use real path for views instead of alias
|
<?php
/**
* HiDev plugin for license generation.
*
* @link https://github.com/hiqdev/hidev-license
* @package hidev-license
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
return [
'controllerMap' => [
'LICENSE' => [
'class' => \hidev\license\console\LicenseController::class,
],
],
'components' => [
'license' => [
'class' => \hidev\license\components\License::class,
],
'view' => [
'theme' => [
'pathMap' => [
'@hidev/views' => [dirname(__DIR__) . '/src/views'],
],
],
],
],
];
|
<?php
/**
* HiDev plugin for license generation.
*
* @link https://github.com/hiqdev/hidev-license
* @package hidev-license
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
return [
'controllerMap' => [
'LICENSE' => [
'class' => \hidev\license\console\LicenseController::class,
],
],
'components' => [
'license' => [
'class' => \hidev\license\components\License::class,
],
'view' => [
'theme' => [
'pathMap' => [
'@hidev/views' => ['@hidev/license/views'],
],
],
],
],
];
|
Remove defers from docker remote promise api
|
var docker = require('docker-remote-api'),
request = docker(),
Q = require('q');
var DockerRemote = function() {};
DockerRemote.containers = function() {
return new Q.Promise(function(resolve, reject) {
request.get('/containers/json', {json:true}, function(err, containers) {
if (err) defer.reject(err);
resolve(containers);
});
});
};
DockerRemote.processes = function(containerID) {
return new Q.Promise(function(resolve, reject) {
request.get('/containers/'+ containerID +'/top', {json:true}, function(err, processes) {
if (err) defer.reject(err);
resolve(processes);
});
});
};
DockerRemote.stats = function(containerID) {
return new Q.Promise(function(resolve, reject) {
request.get('/containers/'+ containerID +'/stats?stream=false', {json:true}, function(err, stats) {
if (err) defer.reject(err);
resolve(stats);
});
});
};
module.exports = DockerRemote;
|
var docker = require('docker-remote-api'),
request = docker(),
Q = require('q');
var DockerRemote = function() {};
DockerRemote.containers = function() {
var defer = Q.defer();
request.get('/containers/json', {json:true}, function(err, containers) {
if (err) defer.reject(err);
defer.resolve(containers);
});
return defer.promise;
};
DockerRemote.processes = function(containerID) {
var defer = Q.defer();
request.get('/containers/'+ containerID +'/top', {json:true}, function(err, processes) {
if (err) defer.reject(err);
defer.resolve(processes);
});
return defer.promise;
};
DockerRemote.stats = function(containerID) {
var defer = Q.defer();
request.get('/containers/'+ containerID +'/stats?stream=false', {json:true}, function(err, stats) {
if (err) defer.reject(err);
defer.resolve(stats);
});
return defer.promise;
};
module.exports = DockerRemote;
|
feat: Modify the expression of sequence and sequence consistent maps
|
export default {
default: [
'呵呵', '哈哈', '吐舌', '啊', '酷', '怒', '开心', '汗', '泪', '黑线',
'鄙视', '不高兴', '真棒', '钱', '疑问', '阴险', '吐', '咦', '委屈', '花心',
'呼', '笑眼', '冷', '太开心', '滑稽', '勉强', '狂汗', '乖', '睡觉', '惊哭',
'升起', '惊讶', '喷', '爱心', '心碎', '玫瑰', '礼物', '星星月亮', '太阳', '音乐',
'灯泡', '蛋糕', '彩虹', '钱币', '咖啡', 'haha', '胜利', '大拇指', '弱', 'ok',
],
};
|
export default {
default: [
'呵呵', '哈哈', '吐舌', '啊', '酷', '怒', '开心', '汗', '泪', '黑线',
'鄙视', '不高兴', '真棒', '钱', '疑问', '阴险', '吐', '咦', '委屈', '花心',
'呼', '笑眼', '冷', '太开心', '滑稽', '勉强', '狂汗', '乖', '睡觉', '惊哭',
'升起', '惊讶', '喷', '爱心', '心碎', '玫瑰', '礼物', '彩虹', '星星月亮', '太阳',
'钱币', '灯泡', '咖啡', '蛋糕', '音乐', 'haha', '胜利', '大拇指', '弱', 'ok',
],
};
|
Check date time based pattern as module version
|
/*
* Bach - Java Shell Builder
* Copyright (C) 2019 Christian Stein
*
* 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
*
* https://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 it;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.lang.module.ModuleDescriptor;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;
class BachTests {
@Test
void moduleDescriptorParsesVersion() {
var pattern = DateTimeFormatter.ofPattern("yyyy.MM.dd.HHmmss").withZone(ZoneId.of("UTC"));
assertDoesNotThrow(() -> ModuleDescriptor.Version.parse(pattern.format(Instant.now())));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse(""));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("-"));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("master"));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("ea"));
}
}
|
/*
* Bach - Java Shell Builder
* Copyright (C) 2019 Christian Stein
*
* 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
*
* https://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 it;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import de.sormuras.bach.Bach;
import java.lang.module.ModuleDescriptor;
import org.junit.jupiter.api.Test;
class BachTests {
@Test
void moduleDescriptorParsesVersion() {
assertDoesNotThrow(() -> ModuleDescriptor.Version.parse("2.0-ea"));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse(""));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("-"));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("master"));
assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("ea"));
}
}
|
Fix silent crash when checking permissions
|
<?php
class User extends ActiveRecord implements ILinkable {
protected $hasMany = array('Post' => array('thisKey' => 'user_id'),
'Comment' => array('thisKey' => 'user_id'),
);
protected $belongsTo = array('Group' => array('otherKey' => 'group_id'),);
protected $validate = array(
'username' => array('presence' => true,),
'password' => array('presence' => true,),
'email' => array('presence' => true, 'email' => true),
'confirm_password' => array('presence' => true,
'ruleConfirm' => array('callback' => 'confirmPassword',
'message' => 'The two passwords are not identical'
),
),
);
protected $fields = array('username' => 'Username', 'email' => 'Email',
'password' => 'Password', 'confirm_password' => 'Confirm password',
);
protected $defaults = array('cookie' => '', 'session' => '', 'ip' => '',
'group_id' => 0,
);
public function getRoute() {
return array('controller' => 'Users', 'action' => 'view',
'parameters' => array($this->username)
);
}
public function hasPermission($key) {
return $group AND $group->hasPermission($key);
}
protected function confirmPassword($value) {
return $value == $this->password;
}
}
|
<?php
class User extends ActiveRecord implements ILinkable {
protected $hasMany = array('Post' => array('thisKey' => 'user_id'),
'Comment' => array('thisKey' => 'user_id'),
);
protected $belongsTo = array('Group' => array('otherKey' => 'group_id'),);
protected $validate = array(
'username' => array('presence' => true,),
'password' => array('presence' => true,),
'email' => array('presence' => true, 'email' => true),
'confirm_password' => array('presence' => true,
'ruleConfirm' => array('callback' => 'confirmPassword',
'message' => 'The two passwords are not identical'
),
),
);
protected $fields = array('username' => 'Username', 'email' => 'Email',
'password' => 'Password', 'confirm_password' => 'Confirm password',
);
protected $defaults = array('cookie' => '', 'session' => '', 'ip' => '',
'group_id' => 0,
);
public function getRoute() {
return array('controller' => 'Users', 'action' => 'view',
'parameters' => array($this->username)
);
}
public function hasPermission($key) {
return $this->getGroup()
->hasPermission($key);
}
protected function confirmPassword($value) {
return $value == $this->password;
}
}
|
Fix line numbers for HTML5 source maps
|
var $hx_script = (function(exports, global) { ::SOURCE_FILE::});
(function ($hx_exports, $global) { "use strict";
$hx_exports.lime = $hx_exports.lime || {};
$hx_exports.lime.$scripts = $hx_exports.lime.$scripts || {};
$hx_exports.lime.$scripts["::APP_FILE::"] = $hx_script;
$hx_exports.lime.embed = function(projectName) { var exports = {};
$hx_exports.lime.$scripts[projectName](exports, $global);
for (var key in exports) $hx_exports[key] = $hx_exports[key] || exports[key];
exports.lime.embed.apply(exports.lime, arguments);
return exports;
};
})(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this, typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : this);
::if embeddedLibraries::::foreach (embeddedLibraries)::::__current__::
::end::::end::
|
::if embeddedLibraries::::foreach (embeddedLibraries)::
::__current__::::end::::end::
// lime.embed namespace wrapper
(function ($hx_exports, $global) { "use strict";
$hx_exports.lime = $hx_exports.lime || {};
$hx_exports.lime.$scripts = $hx_exports.lime.$scripts || {};
$hx_exports.lime.$scripts["::APP_FILE::"] = (function(exports, global) {
::SOURCE_FILE::
});
// End namespace wrapper
$hx_exports.lime.embed = function(projectName) { var exports = {};
$hx_exports.lime.$scripts[projectName](exports, $global);
for (var key in exports) $hx_exports[key] = $hx_exports[key] || exports[key];
exports.lime.embed.apply(exports.lime, arguments);
return exports;
};
})(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this, typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : this);
|
Add firefox to the list of karma test browsers
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'karma-typescript'],
files: [
{pattern: 'src/**/*.ts'}
],
preprocessors: {
'**/*.ts': ['karma-typescript'], // *.tsx for React Jsx
},
karmaTypescriptConfig: {
tsconfig: "tsconfig.json"
},
reporters: ['progress', 'karma-typescript'],
browsers: ['Chrome', 'Firefox']
});
};
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'karma-typescript'],
files: [
{pattern: 'src/**/*.ts'}
],
preprocessors: {
'**/*.ts': ['karma-typescript'], // *.tsx for React Jsx
},
karmaTypescriptConfig: {
tsconfig: "tsconfig.json"
},
reporters: ['progress', 'karma-typescript'],
browsers: ['Chrome']
});
};
|
Comment about excluding Git repositories from requirements.txt
|
#!/usr/bin/env python
from os.path import join
from setuptools import setup, find_packages
# Change geokey_sapelli version here (and here alone!):
VERSION_PARTS = (0, 6, 7)
name = 'geokey-sapelli'
version = '.'.join(map(str, VERSION_PARTS))
repository = join('https://github.com/ExCiteS', name)
def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = list()
for line in open('requirements.txt').readlines():
# skip to next iteration if comment, Git repository or empty line
if line.startswith('#') or line.startswith('git+https') or line == '':
continue
# add line to requirements
requirements.append(line.rstrip())
return requirements
setup(
name=name,
version=version,
description='Read Sapelli project and load data from CSVs to GeoKey',
url=repository,
download_url=join(repository, 'tarball', version),
author='ExCiteS',
author_email='excitesucl@gmail.com',
packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']),
install_requires=get_install_requires(),
include_package_data=True,
)
|
#!/usr/bin/env python
from os.path import join
from setuptools import setup, find_packages
# Change geokey_sapelli version here (and here alone!):
VERSION_PARTS = (0, 6, 7)
name = 'geokey-sapelli'
version = '.'.join(map(str, VERSION_PARTS))
repository = join('https://github.com/ExCiteS', name)
def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = list()
for line in open('requirements.txt').readlines():
# skip to next iteration if comment or empty line
if line.startswith('#') or line.startswith('git+https') or line == '':
continue
# add line to requirements
requirements.append(line.rstrip())
return requirements
setup(
name=name,
version=version,
description='Read Sapelli project and load data from CSVs to GeoKey',
url=repository,
download_url=join(repository, 'tarball', version),
author='ExCiteS',
author_email='excitesucl@gmail.com',
packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']),
install_requires=get_install_requires(),
include_package_data=True,
)
|
Check for permissions before submitting header request
|
/* global Office */
/* global sendHeadersRequestEWS */
/* global sendHeadersRequestRest */
/* global ShowError */
/* exported sendHeadersRequest */
/**
* GetHeaderRest.js
*
* Selector for switching between EWS and Rest logic
*/
function sendHeadersRequest(headersLoadedCallback) {
if (!Office.context.mailbox || !Office.context.mailbox.item) {
ShowError(null, "No item selected", true);
return;
}
if (!sufficientPermission()) {
ShowError(null, "Insufficient permissions to request headers", false);
return;
}
try {
if (canUseRest()) {
sendHeadersRequestRest(headersLoadedCallback);
}
else {
sendHeadersRequestEWS(headersLoadedCallback);
}
} catch (e) {
ShowError(e, "Could not send header request");
}
}
function sufficientPermission() {
if (!Office.context.mailbox) return false;
if (!Office.context.mailbox._initialData$p$0) return false;
if (Office.context.mailbox._initialData$p$0._permissionLevel$p$0 < 1) return false;
return true;
}
function canUseRest() {
if (!Office.context.requirements.isSetSupported("Mailbox", 1.5)) return false;
if (!sufficientPermission()) return false;
if (!Office.context.mailbox.getCallbackTokenAsync) return false;
return true;
}
|
/* global Office */
/* global sendHeadersRequestEWS */
/* global sendHeadersRequestRest */
/* global ShowError */
/* exported sendHeadersRequest */
/**
* GetHeaderRest.js
*
* Selector for switching between EWS and Rest logic
*/
function sendHeadersRequest(headersLoadedCallback) {
if (!Office.context.mailbox || !Office.context.mailbox.item) {
ShowError(null, "No item selected", true);
return;
}
try {
if (canUseRest()) {
sendHeadersRequestRest(headersLoadedCallback);
}
else {
sendHeadersRequestEWS(headersLoadedCallback);
}
} catch (e) {
ShowError(e, "Could not send header request");
}
}
function canUseRest() {
if (!Office.context.requirements.isSetSupported("Mailbox", 1.5)) return false;
if (Office.context.mailbox._initialData$p$0._permissionLevel$p$0 < 1) return false;
if (!Office.context.mailbox.getCallbackTokenAsync) return false;
return true;
}
|
Fix Twisted requirement (I think?)
git-svn-id: 0754dbe6ae3ac1ca1635dae9a69e589ef5e7cc4d@61 8ed0a6ef-5846-dd11-a15a-00e9354ff7a0
|
#!/usr/bin/env python2.6
try:
from setuptools import setup
except:
from distutils.core import setup
def getVersion():
import os
packageSeedFile = os.path.join("lib", "_version.py")
ns = {"__name__": __name__, }
execfile(packageSeedFile, ns)
return ns["version"]
version = getVersion()
setup(
name = version.package,
version = version.short(),
description = "Pub Client and Service",
long_description = "Pub key management service and client",
author = "Oliver Gould", author_email = "ver@yahoo-inc.com",
maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com",
requires = ["jersey", "Twisted", "pendrell>=0.3.0", ],
packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ],
scripts = ["bin/jget", "bin/pubc", ],
package_dir = {"pub": "lib", },
package_data = {"twisted.plugins": ["pubs.py"], },
)
|
#!/usr/bin/env python2.6
try:
from setuptools import setup
except:
from distutils.core import setup
def getVersion():
import os
packageSeedFile = os.path.join("lib", "_version.py")
ns = {"__name__": __name__, }
execfile(packageSeedFile, ns)
return ns["version"]
version = getVersion()
setup(
name = version.package,
version = version.short(),
description = "Pub Client and Service",
long_description = "Pub key management service and client",
author = "Oliver Gould", author_email = "ver@yahoo-inc.com",
maintainer = "Oliver Gould", maintainer_email = "ver@yahoo-inc.com",
requires = ["jersey", "twisted", "twisted.conch", "pendrell(>=0.2.0)", ],
packages = ["pub", "pub.cases", "pub.client", "twisted.plugins", ],
scripts = ["bin/jget", "bin/pubc", ],
package_dir = {"pub": "lib", },
package_data = {"twisted.plugins": ["pubs.py"], },
)
|
[android] Revert changes - added methods like legacy auth fragment
|
package com.mapswithme.maps.base;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mapswithme.maps.auth.Authorizer;
import com.mapswithme.maps.auth.TargetFragmentCallback;
public abstract class BaseAuthFragment extends BaseAsyncOperationFragment
implements Authorizer.Callback, TargetFragmentCallback
{
@NonNull
private final Authorizer mAuthorizer = new Authorizer(this);
protected void authorize()
{
mAuthorizer.authorize();
}
@Override
@CallSuper
public void onStart()
{
super.onStart();
mAuthorizer.attach(this);
}
@Override
@CallSuper
public void onStop()
{
super.onStop();
mAuthorizer.detach();
}
@Override
public void onTargetFragmentResult(int resultCode, @Nullable Intent data)
{
mAuthorizer.onTargetFragmentResult(resultCode, data);
}
@Override
public boolean isTargetAdded()
{
return isAdded();
}
protected boolean isAuthorized()
{
return mAuthorizer.isAuthorized();
}
}
|
package com.mapswithme.maps.base;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mapswithme.maps.auth.Authorizer;
import com.mapswithme.maps.auth.TargetFragmentCallback;
public abstract class BaseAuthFragment extends BaseAsyncOperationFragment
implements Authorizer.Callback, TargetFragmentCallback
{
@NonNull
private final Authorizer mAuthorizer = new Authorizer(this);
protected void authorize()
{
mAuthorizer.authorize();
}
@Override
@CallSuper
public void onAttach(Context context)
{
super.onAttach(context);
mAuthorizer.attach(this);
}
@Override
@CallSuper
public void onDestroyView()
{
super.onDestroyView();
mAuthorizer.detach();
}
@Override
public void onTargetFragmentResult(int resultCode, @Nullable Intent data)
{
mAuthorizer.onTargetFragmentResult(resultCode, data);
}
@Override
public boolean isTargetAdded()
{
return isAdded();
}
protected boolean isAuthorized()
{
return mAuthorizer.isAuthorized();
}
}
|
Remove remnants of category from Service class.
|
var bb = bb || {};
bb.Service = function(bucketName, dataStore) {
this.dataStore = dataStore;
this.bucketName = bucketName;
this.dataStore.ensureBucketExists(bucketName);
};
bb.Service.prototype.add = function(name) {
this.dataStore.addEntryTo(this.bucketName, {
'name': name
});
};
bb.Service.prototype.getAll = function() {
return this.dataStore.getBucket(this.bucketName);
};
bb.Service.prototype.getById = function(id) {
return this.dataStore.getEntryFrom(this.bucketName, id);
};
bb.Service.prototype.isNameInUse = function(name) {
var collection = this.dataStore.getBucket(this.bucketName);
var lcNewName = String(name).trim().toLowerCase();
for (var id in collection) {
if (collection.hasOwnProperty(id)) {
var lcExistingName = collection[id].name.toLowerCase();
if (lcExistingName === lcNewName) {
return true;
}
}
}
return false;
};
bb.Service.prototype.rename = function(id, newName) {
var entry = this.getById(id);
if (this.isNameInUse(newName)) {
alert('You already have one named "' + newName + '".');
} else {
entry.name = newName;
this.dataStore.updateEntry(this.bucketName, entry);
}
};
|
var bb = bb || {};
bb.Service = function(bucketName, dataStore) {
this.dataStore = dataStore;
this.bucketName = bucketName;
this.dataStore.ensureBucketExists(bucketName);
};
bb.Service.prototype.add = function(name) {
this.dataStore.addEntryTo(this.bucketName, new bb.Category({
'name': name
}));
};
bb.Service.prototype.getAll = function() {
return this.dataStore.getBucket(this.bucketName);
};
bb.Service.prototype.getById = function(categoryId) {
return this.dataStore.getEntryFrom(this.bucketName, categoryId);
};
bb.Service.prototype.isNameInUse = function(name) {
var collection = this.dataStore.getBucket(this.bucketName);
var lcNewName = String(name).trim().toLowerCase();
for (var id in collection) {
if (collection.hasOwnProperty(id)) {
var lcExistingName = collection[id].name.toLowerCase();
if (lcExistingName === lcNewName) {
return true;
}
}
}
return false;
};
bb.Service.prototype.rename = function(id, newName) {
var entry = this.getById(id);
if (this.isNameInUse(newName)) {
alert('You already have one named "' + newName + '".');
} else {
entry.name = newName;
this.dataStore.updateEntry(this.bucketName, entry);
}
};
|
Allow Watcher interval to be configurable.
Running `broccoli serve` on the Ember code base takes approximately
13.5% CPU on a rMBP. Modifying this interval to 250 cuts that to
approximately 6%.
|
var EventEmitter = require('events').EventEmitter
var helpers = require('broccoli-kitchen-sink-helpers')
module.exports = Watcher
function Watcher(builder, options) {
this.builder = builder
this.options = options || {}
this.check()
}
Watcher.prototype = Object.create(EventEmitter.prototype)
Watcher.prototype.constructor = Watcher
Watcher.prototype.check = function() {
try {
var interval = this.options.interval || 100
var newStatsHash = this.builder.treesRead.map(function (tree) {
return typeof tree === 'string' ? helpers.hashTree(tree) : ''
}).join('\x00')
if (newStatsHash !== this.statsHash) {
this.statsHash = newStatsHash
this.current = this.builder.build()
this.current.then(function(directory) {
this.emit('change', directory)
return directory
}.bind(this), function(error) {
this.emit('error', error)
throw error
}.bind(this)).finally(this.check.bind(this))
} else {
setTimeout(this.check.bind(this), interval)
}
} catch (err) {
console.error('Uncaught error in Broccoli file watcher:')
console.error(err.stack)
console.error('Watcher quitting') // do not schedule check with setTimeout
}
}
Watcher.prototype.then = function(success, fail) {
return this.current.then(success, fail)
}
|
var EventEmitter = require('events').EventEmitter
var helpers = require('broccoli-kitchen-sink-helpers')
module.exports = Watcher
function Watcher(builder) {
this.builder = builder
this.check()
}
Watcher.prototype = Object.create(EventEmitter.prototype)
Watcher.prototype.constructor = Watcher
Watcher.prototype.check = function() {
try {
var newStatsHash = this.builder.treesRead.map(function (tree) {
return typeof tree === 'string' ? helpers.hashTree(tree) : ''
}).join('\x00')
if (newStatsHash !== this.statsHash) {
this.statsHash = newStatsHash
this.current = this.builder.build()
this.current.then(function(directory) {
this.emit('change', directory)
return directory
}.bind(this), function(error) {
this.emit('error', error)
throw error
}.bind(this)).finally(this.check.bind(this))
} else {
setTimeout(this.check.bind(this), 100)
}
} catch (err) {
console.error('Uncaught error in Broccoli file watcher:')
console.error(err.stack)
console.error('Watcher quitting') // do not schedule check with setTimeout
}
}
Watcher.prototype.then = function(success, fail) {
return this.current.then(success, fail)
}
|
Annotate new methods with since 4.5
Part of gradle/gradle-native#191
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.vcs;
import org.gradle.api.Describable;
import org.gradle.api.Incubating;
/**
* Captures user-provided information about a version control system.
*
* @since 4.4
*/
@Incubating
public interface VersionControlSpec extends Describable {
/**
* Returns a {@link String} identifier which will be unique to this version
* control specification among other version control specifications.
*/
String getUniqueId();
/**
* Returns the name of the repository.
*/
String getRepoName();
/**
* Returns the relative path to the root of the build within the repository.
*
* @since 4.5
*/
String getRootDir();
/**
* Sets the relative path to the root of the build within the repository.
* <p>
* Defaults to an empty relative path, meaning the root of the repository.
*
* @since 4.5
*/
void setRootDir(String rootDir);
}
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.vcs;
import org.gradle.api.Describable;
import org.gradle.api.Incubating;
/**
* Captures user-provided information about a version control system.
*
* @since 4.4
*/
@Incubating
public interface VersionControlSpec extends Describable {
/**
* Returns a {@link String} identifier which will be unique to this version
* control specification among other version control specifications.
*/
String getUniqueId();
/**
* Returns the name of the repository.
*/
String getRepoName();
/**
* Returns the relative path to the root of the build within the repository.
*/
String getRootDir();
/**
* Sets the relative path to the root of the build within the repository.
* <p>
* Defaults to an empty relative path, meaning the root of the repository.
*/
void setRootDir(String rootDir);
}
|
Update the laravel 4 service provider so it is not deferred
This fixes issues with the config not loading correctly for laravel 4.
|
<?php
namespace Michaeljennings\Carpenter;
class Laravel4ServiceProvider extends CarpenterServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
* @codeCoverageIgnore
*/
public function boot()
{
$this->package('michaeljennings/carpenter', 'carpenter', realpath(__DIR__ . '/../'));
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('michaeljennings.carpenter', function ($app) {
return new Carpenter([
'store' => $app['config']['carpenter::store'],
'paginator' => $app['config']['carpenter::paginator'],
'session' => $app['config']['carpenter::session'],
'view' => $app['config']['carpenter::view'],
]);
});
$this->app->alias('michaeljennings.carpenter', 'Michaeljennings\Carpenter\Contracts\Carpenter');
}
}
|
<?php
namespace Michaeljennings\Carpenter;
class Laravel4ServiceProvider extends CarpenterServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
* @codeCoverageIgnore
*/
public function boot()
{
$this->package('michaeljennings/carpenter', 'carpenter', realpath(__DIR__ . '/../'));
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('michaeljennings.carpenter', function ($app) {
return new Carpenter([
'store' => $app['config']['carpenter::store'],
'paginator' => $app['config']['carpenter::paginator'],
'session' => $app['config']['carpenter::session'],
'view' => $app['config']['carpenter::view'],
]);
});
$this->app->alias('michaeljennings.carpenter', 'Michaeljennings\Carpenter\Contracts\Carpenter');
}
}
|
Rename master branch to main
|
import re
import subprocess
from datetime import datetime
def test_last_review_date():
statement_file_path = "app/templates/views/accessibility_statement.html"
# test local changes against main for a full diff of what will be merged
statement_diff = subprocess.run(
[f"git diff --exit-code origin/main -- {statement_file_path}"], stdout=subprocess.PIPE, shell=True
)
# if statement has changed, test the review date was part of those changes
if statement_diff.returncode == 1:
raw_diff = statement_diff.stdout.decode("utf-8")
today = datetime.now().strftime("%d %B %Y")
with open(statement_file_path, "r") as statement_file:
current_review_date = re.search(
(r'"Last updated": "(\d{1,2} [A-Z]{1}[a-z]+ \d{4})"'), statement_file.read()
).group(1)
# guard against changes that don't need to update the review date
if current_review_date != today:
assert '"Last updated": "' in raw_diff
|
import re
import subprocess
from datetime import datetime
def test_last_review_date():
statement_file_path = "app/templates/views/accessibility_statement.html"
# test local changes against master for a full diff of what will be merged
statement_diff = subprocess.run(
[f"git diff --exit-code origin/master -- {statement_file_path}"], stdout=subprocess.PIPE, shell=True
)
# if statement has changed, test the review date was part of those changes
if statement_diff.returncode == 1:
raw_diff = statement_diff.stdout.decode("utf-8")
today = datetime.now().strftime("%d %B %Y")
with open(statement_file_path, "r") as statement_file:
current_review_date = re.search(
(r'"Last updated": "(\d{1,2} [A-Z]{1}[a-z]+ \d{4})"'), statement_file.read()
).group(1)
# guard against changes that don't need to update the review date
if current_review_date != today:
assert '"Last updated": "' in raw_diff
|
Fix config to use yunity_swagger
|
"""yunity URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
import yunity.api.urls
import yunity.doc.yunity_swagger
urlpatterns = [
url(r'^api/', include(yunity.api.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^doc$', yunity.doc.yunity_swagger.doc),
]
|
"""wuppdays URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
import yunity.api.urls
import yunity.doc.flask_swagger
urlpatterns = [
url(r'^api/', include(yunity.api.urls)),
url(r'^admin/', include(admin.site.urls)),
url(r'^doc$', yunity.doc.flask_swagger.doc),
]
|
Make callable statements work again for JDK 1.5 builds. Any code
int the jdbc3/Jdbc3 classes also needs to get into the corresponding
jdbc3g/Jdbc3g class.
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.4 2005/01/11 08:25:47 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc3g;
import java.sql.*;
import java.util.Map;
class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement
{
Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
{
super(connection, sql, true, rsType, rsConcurrency, rsHoldability);
if ( !connection.haveMinimumServerVersion("8.1") || connection.getProtocolVersion() == 2)
{
adjustIndex = true;
}
}
public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
{
return getObjectImpl(i, map);
}
public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
{
return getObjectImpl(s, map);
}
}
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.3 2004/11/09 08:51:22 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc3g;
import java.sql.*;
import java.util.Map;
class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement
{
Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
{
super(connection, sql, true, rsType, rsConcurrency, rsHoldability);
}
public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
{
return getObjectImpl(i, map);
}
public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
{
return getObjectImpl(s, map);
}
}
|
Tweak logging configuration - record debug info, display info level
|
import sys
import logging
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
handler = logging.StreamHandler(sys.stderr)
fmt = logging.Formatter("%(asctime)-15s [%(name)5s:%(levelname)s] %(message)s")
handler.setFormatter(fmt)
handler.setLevel(logging.INFO)
logging.getLogger('hxntools').addHandler(handler)
logging.getLogger('hxnfly').addHandler(handler)
logging.getLogger('ppmac').addHandler(handler)
logging.getLogger('hxnfly').setLevel(logging.DEBUG)
logging.getLogger('hxntools').setLevel(logging.DEBUG)
logging.getLogger('ppmac').setLevel(logging.INFO)
import pandas as pd
# Flyscan results are shown using pandas. Maximum rows/columns to use when
# printing the table:
pd.options.display.width = 180
pd.options.display.max_rows = None
pd.options.display.max_columns = 10
|
import sys
import logging
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
handler = logging.StreamHandler(sys.stderr)
fmt = logging.Formatter("%(asctime)-15s [%(name)5s:%(levelname)s] %(message)s")
handler.setFormatter(fmt)
logging.getLogger('hxntools').addHandler(handler)
logging.getLogger('hxnfly').addHandler(handler)
logging.getLogger('ppmac').addHandler(handler)
logging.getLogger('hxnfly').setLevel(logging.INFO)
logging.getLogger('hxntools').setLevel(logging.INFO)
logging.getLogger('ppmac').setLevel(logging.INFO)
import pandas as pd
# Flyscan results are shown using pandas. Maximum rows/columns to use when
# printing the table:
pd.options.display.width = 180
pd.options.display.max_rows = None
pd.options.display.max_columns = 10
|
Make sure user is in group
|
// Includes
var setRank = require('../setRank.js').func;
var getRoles = require('./getRoles.js').func;
var getRankNameInGroup = require('./getRankNameInGroup.js').func;
// Args
exports.required = ['group', 'target', 'change'];
exports.optional = ['jar'];
// Define
exports.func = function (args) {
var group = args.group;
var target = args.target;
var amount = args.change;
var jar = args.jar;
return getRankNameInGroup({group: group, userId: target})
.then(function (rank) {
if (rank === 'Guest') {
throw new Error('Target user is not in group');
}
return getRoles({group: group})
.then(function (roles) {
for (var i = 0; i < roles.length; i++) {
var role = roles[i];
var thisRank = role.Name;
if (thisRank === rank) {
var change = i + amount;
var found = roles[change];
if (!found) {
throw new Error('Rank change is out of range');
}
return setRank({group: group, target: target, roleset: found.ID, jar: jar})
.then(function () {
return {newRole: found, oldRole: role};
});
}
}
});
});
};
|
// Includes
var setRank = require('../setRank.js').func;
var getRoles = require('./getRoles.js').func;
var getRankNameInGroup = require('./getRankNameInGroup.js').func;
// Args
exports.required = ['group', 'target', 'change'];
exports.optional = ['jar'];
// Define
exports.func = function (args) {
var group = args.group;
var target = args.target;
var amount = args.change;
var jar = args.jar;
return getRankNameInGroup({group: group, userId: target})
.then(function (rank) {
return getRoles({group: group})
.then(function (roles) {
for (var i = 0; i < roles.length; i++) {
var role = roles[i];
var thisRank = role.Name;
if (thisRank === rank) {
var change = i + amount;
var found = roles[change];
if (!found) {
throw new Error('Rank change is out of range');
}
return setRank({group: group, target: target, roleset: found.ID, jar: jar})
.then(function () {
return {newRole: found, oldRole: role};
});
}
}
});
});
};
|
Add username, email and phone on Apply serializer
|
from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
|
from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
|
Fix composer for inplace in dev mode
|
<?php
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';
if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');
set('default_stage', 'production');
set('keep_releases', 2);
set('writable_use_sudo', false); // Using sudo in writable commands?
set('shared_files', [
'config/db.php'
]);
task('deploy:configure_composer', function () {
$stage = env('app.stage');
if($stage == 'dev') {
env('composer_options', 'install --verbose --no-progress --no-interaction');
}
})->desc('Configure composer');
// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');
after('deploy:shared', 'deploy:configure');
before('inplace:vendors', 'deploy:configure_composer');
before('deploy:vendors', 'deploy:configure_composer');
|
<?php
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';
if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');
set('default_stage', 'production');
set('keep_releases', 2);
set('writable_use_sudo', false); // Using sudo in writable commands?
set('shared_files', [
'config/db.php'
]);
task('deploy:configure_composer', function () {
$stage = env('app.stage');
if($stage == 'dev') {
env('composer_options', 'install --verbose --no-progress --no-interaction');
}
})->desc('Configure composer');
// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');
after('deploy:shared', 'deploy:configure');
before('deploy:vendors', 'deploy:configure_composer');
|
Set flag to log process id in syslog
|
#!/usr/bin/env python
import pymysql
import os
import syslog
host = os.environ['DB_HOST']
user = os.environ['DB_USER']
password = os.environ['DB_PASSWORD']
db = os.environ['DB_DATABASE']
syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_USER)
syslog.syslog("Inserting new business data into database.")
connection = pymysql.connect(host=host,
user=user,
password=password,
db=db,
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "CALL insert_data({0})".format(1)
cursor.execute(sql)
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
finally:
connection.close()
|
#!/usr/bin/env python
import pymysql
import os
import syslog
host = os.environ['DB_HOST']
user = os.environ['DB_USER']
password = os.environ['DB_PASSWORD']
db = os.environ['DB_DATABASE']
syslog.openlog(facility=syslog.LOG_USER)
syslog.syslog("Inserting new business data into database.")
connection = pymysql.connect(host=host,
user=user,
password=password,
db=db,
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "CALL insert_data({0})".format(1)
cursor.execute(sql)
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
finally:
connection.close()
|
IPLookup: Add `moreAt: true` because it's false by default.
|
(function (env) {
"use strict";
env.ddg_spice_iplookup = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('iplookup');
}
Spice.add({
id: "iplookup",
name: "Answer",
data: api_result.ddg,
meta: {
sourceName: "RobTex",
sourceUrl: api_result.ddg.lnk
},
templates: {
group: 'base',
options: {
content: Spice.iplookup.content,
moreAt: true
}
},
relevancy: {
primary: [{
required: 'shortwho'
}]
}
});
};
}(this));
|
(function (env) {
"use strict";
env.ddg_spice_iplookup = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('iplookup');
}
Spice.add({
id: "iplookup",
name: "Answer",
data: api_result.ddg,
meta: {
sourceName: "RobTex",
sourceUrl: api_result.ddg.lnk
},
templates: {
group: 'base',
options: {
content: Spice.iplookup.content
}
},
relevancy: {
primary: [{
required: 'shortwho'
}]
}
});
};
}(this));
|
docs: Fix simple typo, transfered -> transferred
There is a small typo in queued_storage/signals.py.
Should read `transferred` rather than `transfered`.
|
"""
django-queued-storage ships with a signal fired after a file was transferred
by the Transfer task. It provides the name of the file, the local and the
remote storage backend instances as arguments to connected signal callbacks.
Imagine you'd want to post-process the file that has been transferred from
the local to the remote storage, e.g. add it to a log model to always know
what exactly happened. All you'd have to do is to connect a callback to
the ``file_transferred`` signal::
from django.dispatch import receiver
from django.utils.timezone import now
from queued_storage.signals import file_transferred
from mysite.transferlog.models import TransferLogEntry
@receiver(file_transferred)
def log_file_transferred(sender, name, local, remote, **kwargs):
remote_url = remote.url(name)
TransferLogEntry.objects.create(name=name, remote_url=remote_url, transfer_date=now())
# Alternatively, you can also use the signal's connect method to connect:
file_transferred.connect(log_file_transferred)
Note that this signal does **NOT** have access to the calling Model or even
the FileField instance that it relates to, only the name of the file.
As a result, this signal is somewhat limited and may only be of use if you
have a very specific usage of django-queued-storage.
"""
from django.dispatch import Signal
file_transferred = Signal(providing_args=["name", "local", "remote"])
|
"""
django-queued-storage ships with a signal fired after a file was transfered
by the Transfer task. It provides the name of the file, the local and the
remote storage backend instances as arguments to connected signal callbacks.
Imagine you'd want to post-process the file that has been transfered from
the local to the remote storage, e.g. add it to a log model to always know
what exactly happened. All you'd have to do is to connect a callback to
the ``file_transferred`` signal::
from django.dispatch import receiver
from django.utils.timezone import now
from queued_storage.signals import file_transferred
from mysite.transferlog.models import TransferLogEntry
@receiver(file_transferred)
def log_file_transferred(sender, name, local, remote, **kwargs):
remote_url = remote.url(name)
TransferLogEntry.objects.create(name=name, remote_url=remote_url, transfer_date=now())
# Alternatively, you can also use the signal's connect method to connect:
file_transferred.connect(log_file_transferred)
Note that this signal does **NOT** have access to the calling Model or even
the FileField instance that it relates to, only the name of the file.
As a result, this signal is somewhat limited and may only be of use if you
have a very specific usage of django-queued-storage.
"""
from django.dispatch import Signal
file_transferred = Signal(providing_args=["name", "local", "remote"])
|
Update documentation in weighttable.java to remove the non-relevant stuff anymore
|
import java.util.Hashtable;
import java.util.Random;
/**
* A weight table is used to have keys that contain an ordered set of N strings corresponding to values that are string-
* integer pairs.
* @author Alek Ratzloff
*
*/
public class Weighttable extends Hashtable<String, Integer> {
/**
* This is to kill the warnings
*/
private static final long serialVersionUID = 570882516693488244L;
private Random random = new Random();
public Weighttable() {
super();
}
public String getRandomWord() {
Object[] words = this.keySet().toArray();
int range = 0;
for(Object word : words) {
int weight = this.get(word);
range += weight;
}
int choice = random.nextInt(range);
int sum = 0;
for(Object word : words) {
int weight = this.get(word);
sum += weight;
if(sum > choice)
return (String)word;
}
return ".";
}
}
|
import java.util.Hashtable;
import java.util.Random;
/**
* A weight table is used to have keys that contain an ordered set of N strings corresponding to values that are string-
* integer pairs.
*
* [a, b, c, d] -> [(foo, 12), (bar, 7)]
* [b, c, d, foo] -> [(baz, 1)]
* [b, c, d, bar] -> [(foobar, 1), (foobaz, 2)];
* @author Alek Ratzloff
*
*/
public class Weighttable extends Hashtable<String, Integer> {
/**
* This is to kill the warnings
*/
private static final long serialVersionUID = 570882516693488244L;
private Random random = new Random();
public Weighttable() {
super();
}
public String getRandomWord() {
Object[] words = this.keySet().toArray();
int range = 0;
for(Object word : words) {
int weight = this.get(word);
range += weight;
}
int choice = random.nextInt(range);
int sum = 0;
for(Object word : words) {
int weight = this.get(word);
sum += weight;
if(sum > choice)
return (String)word;
}
return ".";
}
}
|
Add Django as a dependency
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import os
setup(
name = "django-powerdns",
version = "0.1",
url = 'http://bitbucket.org/peternixon/django-powerdns/',
download_url = 'http://bitbucket.org/peternixon/django-powerdns/downloads/',
license = 'BSD',
description = "PowerDNS administration module for Django",
author = 'Peter Nixon',
author_email = 'listuser@peternixon.net',
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: Name Service (DNS)',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries :: Python Modules',
]
install_requires=[
'Django>=1.2',
]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import os
setup(
name = "django-powerdns",
version = "0.1",
url = 'http://bitbucket.org/peternixon/django-powerdns/',
download_url = 'http://bitbucket.org/peternixon/django-powerdns/downloads/',
license = 'BSD',
description = "PowerDNS administration module for Django",
author = 'Peter Nixon',
author_email = 'listuser@peternixon.net',
packages = find_packages(),
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: Name Service (DNS)',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
|
Add key generation function to interface
|
package org.cryptonit.cloud.interfaces;
import java.security.PrivateKey;
import java.security.PublicKey;
public interface KeyStore {
public enum KeyParameters {
RSA_2048("RSA", null, 2048),
RSA_4096("RSA", null, 4096),
EC_P256("EC", "P-256", 256),
EC_P384("EC", "P-384", 384),
EC_P521("EC", "P-521", 521);
final private String algorithm;
final private String parameter;
final private int size;
KeyParameters(String algorithm, String parameter, int size) {
this.algorithm = algorithm;
this.parameter = parameter;
this.size = size;
}
public String getAlgorithm() {
return algorithm;
}
public String getParameter() {
return parameter;
}
public int getSize() {
return size;
}
};
String generateKey(String domain, KeyParameters params);
PrivateKey getPrivateKey(String domain, String keyIdentifier);
PublicKey getPublicKey(String domain, String keyIdentifier);
}
|
package org.cryptonit.cloud.interfaces;
import java.security.PrivateKey;
import java.security.PublicKey;
public interface KeyStore {
public enum KeyParameters {
RSA_2048("RSA", null, 2048),
RSA_4096("RSA", null, 4096),
EC_P256("EC", "P-256", 256),
EC_P384("EC", "P-384", 384),
EC_P521("EC", "P-521", 521);
final private String algorithm;
final private String parameter;
final private int size;
KeyParameters(String algorithm, String parameter, int size) {
this.algorithm = algorithm;
this.parameter = parameter;
this.size = size;
}
public String getAlgorithm() {
return algorithm;
}
public String getParameter() {
return parameter;
}
public int getSize() {
return size;
}
};
PrivateKey getPrivateKey(String domain, String keyIdentifier);
PublicKey getPublicKey(String domain, String keyIdentifier);
}
|
Make sure we are compatible with common 0.3
|
<?php
/*
* This file is part of php-cache\memcache-adapter package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\Memcache;
use Cache\Adapter\Common\AbstractCachePool;
use Memcache;
use Psr\Cache\CacheItemInterface;
class MemcacheCachePool extends AbstractCachePool
{
/**
* @type Memcache
*/
private $cache;
public function __construct(Memcache $cache)
{
$this->cache = $cache;
}
protected function fetchObjectFromCache($key)
{
if (false === $result = unserialize($this->cache->get($key))) {
return [false, null];
}
return $result;
}
protected function clearAllObjectsFromCache()
{
return $this->cache->flush();
}
protected function clearOneObjectFromCache($key)
{
$this->cache->delete($key);
return true;
}
protected function storeItemInCache($key, CacheItemInterface $item, $ttl)
{
$data = serialize([true, $item->get()]);
return $this->cache->set($key, $data, 0, $ttl ?: 0);
}
}
|
<?php
/*
* This file is part of php-cache\memcache-adapter package.
*
* (c) 2015-2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\Adapter\Memcache;
use Cache\Adapter\Common\AbstractCachePool;
use Memcache;
use Psr\Cache\CacheItemInterface;
class MemcacheCachePool extends AbstractCachePool
{
/**
* @type Memcache
*/
private $cache;
public function __construct(Memcache $cache)
{
$this->cache = $cache;
}
protected function fetchObjectFromCache($key)
{
return $this->cache->get($key);
}
protected function clearAllObjectsFromCache()
{
return $this->cache->flush();
}
protected function clearOneObjectFromCache($key)
{
$this->cache->delete($key);
return true;
}
protected function storeItemInCache($key, CacheItemInterface $item, $ttl)
{
return $this->cache->set($key, $item, 0, $ttl ?: 0);
}
}
|
Enable face culling by default
|
const Signal = require('signals')
let MaterialID = 0
function Material (opts) {
this.type = 'Material'
this.id = 'Material_' + MaterialID++
this.changed = new Signal()
this._uniforms = {}
const ctx = opts.ctx
this.baseColor = [0.95, 0.95, 0.95, 1]
this.emissiveColor = [0, 0, 0, 1]
this.metallic = 0.01
this.roughness = 0.5
this.displacement = 0
this.depthTest = true
this.depthWrite = true
this.depthFunc = opts.ctx.DepthFunc.LessEqual
this.blendEnabled = false
this.blendSrcRGBFactor = ctx.BlendFactor.ONE
this.blendSrcAlphaFactor = ctx.BlendFactor.ONE
this.blendDstRGBFactor = ctx.BlendFactor.ONE
this.blendDstAlphaFactor = ctx.BlendFactor.ONE
this.castShadows = false
this.receiveShadows = false
this.cullFaceEnabled = true
this.set(opts)
}
Material.prototype.init = function (entity) {
this.entity = entity
}
Material.prototype.set = function (opts) {
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new Material(opts)
}
|
const Signal = require('signals')
let MaterialID = 0
function Material (opts) {
this.type = 'Material'
this.id = 'Material_' + MaterialID++
this.changed = new Signal()
this._uniforms = {}
const ctx = opts.ctx
this.baseColor = [0.95, 0.95, 0.95, 1]
this.emissiveColor = [0, 0, 0, 1]
this.metallic = 0.01
this.roughness = 0.5
this.displacement = 0
this.depthTest = true
this.depthWrite = true
this.depthFunc = opts.ctx.DepthFunc.LessEqual
this.blendEnabled = false
this.blendSrcRGBFactor = ctx.BlendFactor.ONE
this.blendSrcAlphaFactor = ctx.BlendFactor.ONE
this.blendDstRGBFactor = ctx.BlendFactor.ONE
this.blendDstAlphaFactor = ctx.BlendFactor.ONE
this.castShadows = false
this.receiveShadows = false
this.set(opts)
}
Material.prototype.init = function (entity) {
this.entity = entity
}
Material.prototype.set = function (opts) {
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new Material(opts)
}
|
Exclude a parameter with default value equals to self::class to avoid crash on 5.6
See https://bugs.php.net/bug.php?id=70957 for detail
|
<?php
namespace ParserReflection\Stub;
/**
* @link https://bugs.php.net/bug.php?id=70957 self::class can not be resolved with reflection for abstract class
*/
abstract class AbstractClassWithMethods
{
const TEST = 5;
public function __construct(){}
public function __destruct(){}
public function explicitPublicFunc(){}
function implicitPublicFunc(){}
protected function protectedFunc(){}
private function privateFunc(){}
static function staticFunc(){}
abstract function abstractFunc();
final function finalFunc(){}
/**
* @return string
*/
public function funcWithDocAndBody()
{
static $a =5, $test = '1234';
return 'hello';
}
/**
* @return \Generator
*/
public function generatorYieldFunc()
{
$index = 0;
while ($index < 1e3) {
yield $index;
}
}
/**
* @return int
*/
public function noGeneratorFunc()
{
$gen = function () {
yield 10;
};
return 10;
}
private function testParam($a, $b = null, $d = self::TEST) {}
}
|
<?php
namespace ParserReflection\Stub;
abstract class AbstractClassWithMethods
{
const TEST = 5;
public function __construct(){}
public function __destruct(){}
public function explicitPublicFunc(){}
function implicitPublicFunc(){}
protected function protectedFunc(){}
private function privateFunc(){}
static function staticFunc(){}
abstract function abstractFunc();
final function finalFunc(){}
/**
* @return string
*/
public function funcWithDocAndBody()
{
static $a =5, $test = '1234';
return 'hello';
}
/**
* @return \Generator
*/
public function generatorYieldFunc()
{
$index = 0;
while ($index < 1e3) {
yield $index;
}
}
/**
* @return int
*/
public function noGeneratorFunc()
{
$gen = function () {
yield 10;
};
return 10;
}
private function testParam($a, $b = null, $c = self::class, $d = self::TEST) {}
}
|
Update app domain initial fixtures.
|
from django.core.management.base import BaseCommand
from us_ignite.apps.models import Feature, Domain
FEATURE_LIST = (
'SDN',
'OpenFlow',
'Ultra fast',
'Speed',
'Low-latency',
'Local cloud / edge computing',
'Advanced wireless',
'Ultra-fast/Gigabit to end-user',
'GENI/US Ignite Rack',
'Layer 2',
)
DOMAIN_LIST = (
'Healthcare',
'Education & Workforce',
'Energy',
'Transportation',
'Advanced Manufacturing',
'Public Safety',
'General / Platform / Other',
)
class Command(BaseCommand):
def handle(self, *args, **options):
for feature_name in FEATURE_LIST:
feature, is_new = Feature.objects.get_or_create(name=feature_name)
if is_new:
print "Imported feature: %s" % feature_name
for domain_name in DOMAIN_LIST:
domain, is_new = Domain.objects.get_or_create(name=domain_name)
if is_new:
print "Imported domain: %s" % domain_name
print "Done!"
|
from django.core.management.base import BaseCommand
from us_ignite.apps.models import Feature, Domain
FEATURE_LIST = (
'SDN',
'OpenFlow',
'Ultra fast',
'Speed',
'Low-latency',
'Local cloud / edge computing',
)
DOMAIN_LIST = (
'Healthcare',
'Education & Workforce',
'Energy',
'Transportation',
'Entrepreneurship',
'Advanced Manufacturing',
'Public Safety',
'General / Platform / Other',
)
class Command(BaseCommand):
def handle(self, *args, **options):
for feature_name in FEATURE_LIST:
feature, is_new = Feature.objects.get_or_create(name=feature_name)
if is_new:
print "Imported feature: %s" % feature_name
for domain_name in DOMAIN_LIST:
domain, is_new = Domain.objects.get_or_create(name=domain_name)
if is_new:
print "Imported domain: %s" % domain_name
print "Done!"
|
Update gfycat plugin for python3 support
|
import re
try:
import urllib.request as urllib
except:
import urllib # Python 2
def title(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
link = 'https://gfycat.com/cajax/get/' + gfyId
respond = urllib.urlopen(link).read().decode("utf8")
username = re.findall(r'\"userName\":\"(.+?)\",' ,respond)[0]
return username if username != "anonymous" else "gfycat " + gfyId
def redirect(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
respond = urllib.urlopen('https://gfycat.com/cajax/get/' + gfyId).read().decode("utf8")
webmurl = re.findall(r'\"webmUrl\":\"(.+?)\",' ,respond)[0]
# delete escape characters
webmurl = webmurl.replace("\\","")
# for some reason we can not connect via https
webmurl = webmurl.replace("https", "http")
return webmurl
same_filename = True
|
import re
try:
import urllib.request as urllib
except:
import urllib # Python 2
def title(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
link = 'https://gfycat.com/cajax/get/' + gfyId
respond = urllib.urlopen(link).read()
username = re.findall(r'\"userName\":\"(.+?)\",' ,respond)[0]
return username if username != "anonymous" else "gfycat " + gfyId
def redirect(source):
gfyId = re.findall(r'href=\".*gfycat.com/(\w+).*\">', source)[-1]
respond = urllib.urlopen('https://gfycat.com/cajax/get/' + gfyId).read()
webmurl = re.findall(r'\"webmUrl\":\"(.+?)\",' ,respond)[0]
# delete escape characters
webmurl = webmurl.replace("\\","")
# for some reason we can not connect via https
webmurl = webmurl.replace("https", "http")
return webmurl
same_filename = True
|
Allow parser options as param
|
var es = require('event-stream'),
gutil = require('gulp-util'),
PluginError = gutil.PluginError;
module.exports = function (ops) {
ops = ops || {};
var cheerio = ops.cheerio || require('cheerio');
return es.map(function (file, done) {
if (file.isNull()) return done(null, file);
if (file.isStream()) return done(new PluginError('gulp-cheerio', 'Streaming not supported.'));
var run = typeof ops === 'function' ? ops : ops.run;
if (run) {
var parserOptions = ops.parserOptions;
var $;
if (parserOptions) {
$ = cheerio.load(file.contents.toString(), parserOptions);
} else {
$ = cheerio.load(file.contents.toString());
}
if (run.length > 1) {
run($, next);
} else {
run($);
next();
}
} else {
done(null, file);
}
function next(err) {
file.contents = new Buffer($.html());
done(err, file);
}
});
};
|
var es = require('event-stream'),
gutil = require('gulp-util'),
PluginError = gutil.PluginError;
module.exports = function (ops) {
ops = ops || {};
var cheerio = ops.cheerio || require('cheerio');
return es.map(function (file, done) {
if (file.isNull()) return done(null, file);
if (file.isStream()) return done(new PluginError('gulp-cheerio', 'Streaming not supported.'));
var run = typeof ops === 'function' ? ops : ops.run;
if (run) {
var $ = cheerio.load(file.contents.toString());
if (run.length > 1) {
run($, next);
} else {
run($);
next();
}
} else {
done(null, file);
}
function next(err) {
file.contents = new Buffer($.html());
done(err, file);
}
});
};
|
Include package files when installing from PyPI
|
from setuptools import setup, find_packages
setup(
name='django-simple-history',
version='1.2.2.post1',
description='Store model history and view/revert changes from admin site.',
long_description='\n'.join((
open('README.rst').read(),
open('CHANGES.rst').read(),
)),
author='Corey Bertram',
author_email='corey@qr7.com',
mantainer='Trey Hunner',
url='https://github.com/treyhunner/django-simple-history',
packages=find_packages(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Framework :: Django",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: BSD License",
],
tests_require=["Django>=1.3", "webtest", "django-webtest"],
include_package_data=True,
test_suite='runtests.main',
)
|
from setuptools import setup, find_packages
setup(
name='django-simple-history',
version='1.2.2.post1',
description='Store model history and view/revert changes from admin site.',
long_description='\n'.join((
open('README.rst').read(),
open('CHANGES.rst').read(),
)),
author='Corey Bertram',
author_email='corey@qr7.com',
mantainer='Trey Hunner',
url='https://github.com/treyhunner/django-simple-history',
packages=find_packages(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Framework :: Django",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: BSD License",
],
tests_require=["Django>=1.3", "webtest", "django-webtest"],
test_suite='runtests.main',
)
|
Fix error getting login of the author of WorkItem
|
<?php
namespace YouTrack;
/**
* A class describing a youtrack workitem.
*
* @property string id
* @method string getId
* @method string setId(string $value)
* @property int date
* @method int getDate
* @method int setDate(int $value)
* @property int duration
* @method int getDuration
* @method int setDuration(int $value)
* @property string description
* @method string getDescription
* @method string setDescription(string $value)
* @property User author
* @method User getAuthor
* @method User setAuthor(int $value)
*
* @link https://confluence.jetbrains.com/display/YTD65/Get+Available+Work+Items+of+Issue
*/
class Workitem extends Object
{
public function __construct(\SimpleXMLElement $xml = NULL, Connection $youtrack = NULL)
{
parent::__construct($xml, $youtrack);
if (isset($xml->date)) {
$this->attributes['date'] = intval((string)$xml->date / 1000);
}
if (isset($xml->author)) {
$this->attributes['author'] = new User($xml->author, $youtrack);
}
}
protected function updateChildrenAttributes(\SimpleXMLElement $xml)
{
foreach ($xml->children() as $nodeName => $node) {
$this->attributes[$nodeName] = (string)$node;
}
}
}
|
<?php
namespace YouTrack;
/**
* A class describing a youtrack workitem.
*
* @property string id
* @method string getId
* @method string setId(string $value)
* @property int date
* @method int getDate
* @method int setDate(int $value)
* @property int duration
* @method int getDuration
* @method int setDuration(int $value)
* @property string description
* @method string getDescription
* @method string setDescription(string $value)
* @property User author
* @method User getAuthor
* @method User setAuthor(int $value)
*
* @link https://confluence.jetbrains.com/display/YTD65/Get+Available+Work+Items+of+Issue
*/
class Workitem extends Object
{
public function __construct(\SimpleXMLElement $xml = NULL, Connection $youtrack = NULL)
{
parent::__construct($xml, $youtrack);
if (isset($xml->date)) {
$this->attributes['date'] = intval((string)$xml->date / 1000);
}
if (isset($xml->author)) {
$this->attributes['author'] = new User(null, $youtrack);
$this->attributes['author']->__set('login', (string)$xml->author);
}
}
protected function updateChildrenAttributes(\SimpleXMLElement $xml)
{
foreach ($xml->children() as $nodeName => $node) {
$this->attributes[$nodeName] = (string)$node;
}
}
}
|
Fix API method names called by World.block_at
|
import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World):
self.world = world
elif isinstance(world, str):
self.world = minecraft.World(world)
else:
raise TypeError('Invalid world type: {}'.format(type(world)))
def block_at(self, x, y, z, dimension=Dimension.overworld):
chunk_x, block_x = divmod(x, 16)
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.api_chunk_info_overworld,
Dimension.nether: api.v2.api_chunk_info_nether,
Dimension.end: api.v2.api_chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
|
import alltheitems.__main__ as ati
import api.v2
import enum
import minecraft
class Dimension(enum.Enum):
overworld = 0
nether = -1
end = 1
class World:
def __init__(self, world=None):
if world is None:
self.world = minecraft.World()
elif isinstance(world, minecraft.World):
self.world = world
elif isinstance(world, str):
self.world = minecraft.World(world)
else:
raise TypeError('Invalid world type: {}'.format(type(world)))
def block_at(self, x, y, z, dimension=Dimension.overworld):
chunk_x, block_x = divmod(x, 16)
chunk_y, block_y = divmod(y, 16)
chunk_z, block_z = divmod(z, 16)
chunk = {
Dimension.overworld: api.v2.chunk_info_overworld,
Dimension.nether: api.v2.chunk_info_nether,
Dimension.end: api.v2.chunk_info_end
}[dimension](self.world, chunk_x, chunk_y, chunk_z)
return chunk[block_y][block_z][block_x]
|
Increase ack on broker to 4 hours.
Change-Id: I4a1f0fc6d1c07014896ef6b34336396d4b30bfdd
|
# Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Celery configuration values."""
BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
"visibility_timeout": 60*60*4,
"fanout_prefix": True,
"fanout_patterns": True
}
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_SERIALIZER = "json"
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"
|
# Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Celery configuration values."""
BROKER_URL = "redis://localhost"
BROKER_POOL_LIMIT = 20
BROKER_TRANSPORT_OPTIONS = {
"visibility_timeout": 10800,
"fanout_prefix": True,
"fanout_patterns": True
}
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_SERIALIZER = "json"
CELERY_TIMEZONE = "UTC"
CELERY_ENABLE_UTC = True
CELERY_IGNORE_RESULT = True
CELERY_DISABLE_RATE_LIMITS = True
# Use a different DB than the redis default one.
CELERY_RESULT_BACKEND = "redis://localhost/1"
|
[FIX] Update sequence of compile-all change command
|
<?php
class commands_CompileAll extends c_ChangescriptCommand
{
/**
* @return String
*/
function getUsage()
{
return "";
}
function getAlias()
{
return "ca";
}
/**
* @return String
*/
function getDescription()
{
return "compile all files that need to be compiled";
}
/**
* @param String[] $params
* @param array<String, String> $options where the option array key is the option name, the potential option value or true
* @see c_ChangescriptCommand::parseArgs($args)
*/
function _execute($params, $options)
{
$this->message("== Compile all ==");
$parent = $this->getParent();
$parent->executeCommand("compileConfig");
$parent->executeCommand("compileDocuments");
$parent->executeCommand("compileAop");
$parent->executeCommand("compileDocumentFilters");
$parent->executeCommand("compileRoles");
$parent->executeCommand("compilePermissions");
$parent->executeCommand("compileLocales");
$parent->executeCommand("compileTags");
$parent->executeCommand("compileListeners");
$parent->executeCommand("compileJsDependencies");
$parent->executeCommand("compilePhptal");
$parent->executeCommand("compileDbSchema");
$this->quitOk("All files were compiled");
}
}
|
<?php
class commands_CompileAll extends c_ChangescriptCommand
{
/**
* @return String
*/
function getUsage()
{
return "";
}
function getAlias()
{
return "ca";
}
/**
* @return String
*/
function getDescription()
{
return "compile all files that need to be compiled";
}
/**
* @param String[] $params
* @param array<String, String> $options where the option array key is the option name, the potential option value or true
* @see c_ChangescriptCommand::parseArgs($args)
*/
function _execute($params, $options)
{
$this->message("== Compile all ==");
$parent = $this->getParent();
$parent->executeCommand("compileConfig");
$parent->executeCommand("compileDocuments");
$parent->executeCommand("compileDocumentFilters");
$parent->executeCommand("compileRoles");
$parent->executeCommand("compilePermissions");
$parent->executeCommand("compileLocales");
$parent->executeCommand("compileTags");
$parent->executeCommand("compileListeners");
$parent->executeCommand("compileJsDependencies");
$parent->executeCommand("compilePhptal");
$parent->executeCommand("compileDbSchema");
$parent->executeCommand("compileAop");
$this->quitOk("All files were compiled");
}
}
|
Add a custom hashCode and equals for performance.
|
/*
* Copyright 2016 higherfrequencytrading.com
*
* 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 net.openhft.chronicle.wire;
/**
* Created by peter on 16/03/16.
*/
public abstract class AbstractMarshallable implements Marshallable {
@Override
public boolean equals(Object o) {
return Marshallable.$equals(this, o);
}
@Override
public int hashCode() {
assert false;
return Marshallable.$hashCode(this);
}
@Override
public String toString() {
return Marshallable.$toString(this);
}
}
|
/*
* Copyright 2016 higherfrequencytrading.com
*
* 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 net.openhft.chronicle.wire;
/**
* Created by peter on 16/03/16.
*/
public abstract class AbstractMarshallable implements Marshallable {
@Override
public boolean equals(Object o) {
return Marshallable.$equals(this, o);
}
@Override
public int hashCode() {
return Marshallable.$hashCode(this);
}
@Override
public String toString() {
return Marshallable.$toString(this);
}
}
|
Fix missing signedUrl for uploading compiled pkg
* We expect 2 signed urls from the director, one for
downloading the source uncompiled package, and one
for uploading the compiled package.
[#167582819]
Co-authored-by: Chris Tarazi <52172d1cc353fd06218578cc1e854d12546b9ed2@pivotal.io>
|
package action
import (
boshcomp "github.com/cloudfoundry/bosh-agent/agent/compiler"
boshcrypto "github.com/cloudfoundry/bosh-utils/crypto"
)
type CompilePackageWithSignedURLRequest struct {
PackageGetSignedURL string `json:"package_get_signed_url"`
UploadSignedUrl string `json:"upload_signed_url"`
MultiDigest boshcrypto.MultipleDigest `json:"multi_digest"`
Name string `json:"name"`
Version string `json:"version"`
Deps boshcomp.Dependencies `json:"deps"`
}
type CompilePackageWithSignedURLResponse struct {
SHA1Digest string `json:"sha1_digest"`
}
type CompilePackageWithSignedURL struct{}
func (a CompilePackageWithSignedURL) Run(request CompilePackageWithSignedURLRequest) (CompilePackageWithSignedURLResponse, error) {
return CompilePackageWithSignedURLResponse{}, nil
}
|
package action
import (
boshcomp "github.com/cloudfoundry/bosh-agent/agent/compiler"
boshcrypto "github.com/cloudfoundry/bosh-utils/crypto"
)
type CompilePackageWithSignedURLRequest struct {
SignedURL string `json:"signed_url"`
MultiDigest boshcrypto.MultipleDigest `json:"multi_digest"`
Name string `json:"name"`
Version string `json:"version"`
Deps boshcomp.Dependencies `json:"deps"`
}
type CompilePackageWithSignedURLResponse struct {
SHA1Digest string `json:"sha1_digest"`
}
type CompilePackageWithSignedURL struct{}
func (a CompilePackageWithSignedURL) Run(request CompilePackageWithSignedURLRequest) (CompilePackageWithSignedURLResponse, error) {
return CompilePackageWithSignedURLResponse{}, nil
}
|
Remove imports we don't need anymore.
|
"""
Define some common units, so users can import the objects directly.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
from dimensionful.dimensions import *
from dimensionful.units import Unit
# cgs base units
g = Unit("g")
cm = Unit("cm")
s = Unit("s")
K = Unit("K")
# other cgs
dyne = Unit("dyne")
erg = Unit("erg")
esu = Unit("esu")
# SI stuff
m = Unit("m")
# times
minute = Unit("min") # can't use `min` because of Python keyword :(
hr = Unit("hr")
day = Unit("day")
yr = Unit("yr")
# solar units
Msun = Unit("Msun")
Rsun = Unit("Rsun")
Lsun = Unit("Lsun")
Tsum = Unit("Tsun")
# astro distances
AU = Unit("AU")
pc = Unit("pc")
ly = Unit("ly")
gauss = Unit("gauss")
|
"""
Define some common units, so users can import the objects directly.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
from sympy.core import Integer
from dimensionful.dimensions import *
from dimensionful.units import Unit, unit_symbols_dict
# cgs base units
g = Unit("g")
cm = Unit("cm")
s = Unit("s")
K = Unit("K")
# other cgs
dyne = Unit("dyne")
erg = Unit("erg")
esu = Unit("esu")
# SI stuff
m = Unit("m")
# times
minute = Unit("min") # can't use `min` because of Python keyword :(
hr = Unit("hr")
day = Unit("day")
yr = Unit("yr")
# solar units
Msun = Unit("Msun")
Rsun = Unit("Rsun")
Lsun = Unit("Lsun")
Tsum = Unit("Tsun")
# astro distances
AU = Unit("AU")
pc = Unit("pc")
ly = Unit("ly")
gauss = Unit("gauss")
|
Improve API to return error if user doesn't exist
|
'use strict';
var connect = require( 'connect' );
var app = connect();
var PORT = 3000;
var connectRoute = require( 'connect-route' );
var bodyParser = require( 'body-parser' );
var users = require( './data/users' );
app.use( bodyParser.urlencoded({ extended: false }) );
app.use( bodyParser.json() );
app.use(function cors( req, res, next ) {
res.setHeader( 'Access-Control-Allow-Origin', '*' );
next();
});
app.use( connectRoute( function routes( router ) {
function postRequest( req, res, next ) {
var userRequested = req.params.slug || req.body.slug;
var user = users[ userRequested ];
if( !user )
res.statusCode = 404;
res.setHeader( 'Content-Type', 'application/json' );
res.end( JSON.stringify( user ) );
}
router.get( '/api/users', function( req, res, next ) {
res.setHeader( 'Content-Type', 'application/json' );
res.end( JSON.stringify( users ) );
});
router.post( '/api/user', postRequest );
router.post( '/api/user/:slug', postRequest );
router.put( '/api/user/:slug', postRequest );
router.delete( '/api/user/:slug', postRequest );
}));
app.listen( PORT );
console.log( 'Server listen on port ', PORT );
exports = module.exports = app;
|
'use strict';
var connect = require( 'connect' );
var app = connect();
var PORT = 3000;
var connectRoute = require( 'connect-route' );
var bodyParser = require( 'body-parser' );
var users = require( './data/users' );
app.use( bodyParser.urlencoded({ extended: false }) );
app.use( bodyParser.json() );
app.use(function( req, res, next ) {
res.setHeader( 'Access-Control-Allow-Origin', '*' );
next();
});
app.use( connectRoute( function( router ) {
function postRequest( req, res, next ) {
var user = req.params.slug || req.body.slug;
res.setHeader( 'Content-Type', 'application/json' );
res.end( JSON.stringify( users[ user ] ) );
}
router.get( '/api/users', function( req, res, next ) {
res.setHeader( 'Content-Type', 'application/json' );
res.end( JSON.stringify( users ) );
});
router.post( '/api/user', postRequest );
router.post( '/api/user/:slug', postRequest );
router.put( '/api/user/:slug', postRequest );
router.delete( '/api/user/:slug', postRequest );
}));
app.listen( PORT );
console.log( 'Server listen on port ', PORT );
exports = module.exports = app;
|
Work on thredds.catalog2: working on unit tests.
|
package thredds.catalog2;
import junit.framework.*;
import thredds.catalog2.simpleImpl.*;
import thredds.catalog2.xml.parser.TestCatalogParser;
/**
* _more_
*
* @author edavis
* @since 4.0
*/
public class TestAll extends TestCase
{
public TestAll( String name )
{
super( name );
}
public static Test suite()
{
TestSuite suite = new TestSuite();
// Tests in thredds.catalog2.simpleImpl
suite.addTestSuite( TestPropertyImpl.class );
suite.addTestSuite( TestPropertyContainer.class );
suite.addTestSuite( TestServiceImpl.class );
suite.addTestSuite( TestServiceContainer.class );
suite.addTestSuite( TestDatasetNodeImpl.class );
suite.addTestSuite( TestAccessImpl.class );
//suite.addTestSuite( TestCatalogRefImpl.class );
suite.addTestSuite( TestCatalogImpl.class );
// Tests in thredds.catalog2.xml
suite.addTestSuite( TestCatalogParser.class );
return suite;
}
}
|
package thredds.catalog2;
import junit.framework.*;
import thredds.catalog2.simpleImpl.*;
import thredds.catalog2.xml.parser.TestCatalogParser;
/**
* _more_
*
* @author edavis
* @since 4.0
*/
public class TestAll extends TestCase
{
public TestAll( String name )
{
super( name );
}
public static Test suite()
{
TestSuite suite = new TestSuite();
// Tests in thredds.catalog2.simpleImpl
suite.addTestSuite( TestPropertyImpl.class );
suite.addTestSuite( TestPropertyContainer.class );
suite.addTestSuite( TestServiceImpl.class );
suite.addTestSuite( TestServiceContainer.class );
suite.addTestSuite( TestAccessImpl.class );
suite.addTestSuite( TestCatalogImpl.class );
// Tests in thredds.catalog2.xml
suite.addTestSuite( TestCatalogParser.class );
return suite;
}
}
|
Fix order in icon preview.
|
import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def get_presets_for_lib(lib):
items = list(lib.presets)
for sub_group in lib.sub_groups:
items.extend(get_presets_for_lib(sub_group))
return items
def load_previews(lib):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
items = get_presets_for_lib(lib)
items = sorted(items, key=lambda item: item.label)
for i, asset in enumerate(items):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, i))
return enum_items if enum_items else [('', '', '')]
|
import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def load_previews(lib, start=0):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
for i,asset in enumerate(lib.presets):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, start + i))
start += len(enum_items)
for sub_group in lib.sub_groups:
enum_items.extend(load_previews(sub_group, start))
return enum_items if enum_items else [('', '', '')]
|
Fix a mistake in a git url
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sys, os
import django_throttling
setup(
name='django-throttling',
version=django_throttling.get_version(),
description="Basic throttling app for Django",
long_description=open('README.rst', 'r').read(),
keywords='django, throttling',
author='Igor',
author_email='lilo.panic@gmail.com',
url='http://github.com/night-crawler/django-throttling',
license='MIT',
package_dir={'django_throttling': 'django_throttling'},
include_package_data=True,
packages=find_packages(),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Topic :: Security",
"Topic :: Utilities",
]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sys, os
import django_throttling
setup(
name='django-throttling',
version=django_throttling.get_version(),
description="Basic throttling app for Django",
long_description=open('README.rst', 'r').read(),
keywords='django, throttling',
author='Igor',
author_email='lilo.panic@gmail.com',
url='http://github.com.org/night-crawler/django-throttling',
license='MIT',
package_dir={'django_throttling': 'django_throttling'},
include_package_data=True,
packages=find_packages(),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Topic :: Security",
"Topic :: Utilities",
]
)
|
Set release attr in correct place
|
import { init, captureException, configureScope } from '@sentry/browser';
import { LOG_ERRORS, RAVEN_ENDPT, RELEASE } from '../constants';
export const setup = () => {
if (LOG_ERRORS) {
/* eslint-disable no-underscore-dangle */
if (!window.__SENTRY_READY__) {
init({ dsn: RAVEN_ENDPT, release: RELEASE });
window.__SENTRY_READY__ = true;
}
/* eslint-enable no-underscore-dangle */
}
};
export default (ex, context) => {
if (LOG_ERRORS) {
setup(); // memoized, it is fine to call this on every log
if (context) {
configureScope(scope => scope.setExtra('context', context));
}
captureException(ex);
}
return window.console && console.error && console.error(ex);
};
|
import { init, captureException, configureScope } from '@sentry/browser';
import { LOG_ERRORS, RAVEN_ENDPT, RELEASE } from '../constants';
export const setup = () => {
if (LOG_ERRORS) {
/* eslint-disable no-underscore-dangle */
if (!window.__SENTRY_READY__) {
init({ dsn: RAVEN_ENDPT });
window.__SENTRY_READY__ = true;
}
/* eslint-enable no-underscore-dangle */
}
};
export default (ex, context) => {
if (LOG_ERRORS) {
setup(); // memoized, it is fine to call this on every log
configureScope(scope => scope.setExtra('release', RELEASE));
if (context) {
configureScope(scope => scope.setExtra('context', context));
}
captureException(ex);
}
return window.console && console.error && console.error(ex);
};
|
Remove unneeded comma from BoxGeometry test
|
(function () {
'use strict';
var parameters = {
width: 10,
height: 20,
depth: 30,
widthSegments: 2,
heightSegments: 3,
depthSegments: 4
};
var geometries;
var box, cube, boxWithSegments;
QUnit.module( "Extras - Geometries - BoxGeometry", {
beforeEach: function() {
box = new THREE.BoxGeometry( parameters.width, parameters.height, parameters.depth );
cube = new THREE.CubeGeometry( parameters.width, parameters.height, parameters.depth );
boxWithSegments = new THREE.BoxGeometry( parameters.width, parameters.height, parameters.depth,
parameters.widthSegments, parameters.heightSegments, parameters.depthSegments );
geometries = [ box, cube, boxWithSegments ];
}
});
QUnit.test( "standard geometry tests", function( assert ) {
runStdGeometryTests( assert, geometries );
});
})();
|
(function () {
'use strict';
var parameters = {
width: 10,
height: 20,
depth: 30,
widthSegments: 2,
heightSegments: 3,
depthSegments: 4,
};
var geometries;
var box, cube, boxWithSegments;
QUnit.module( "Extras - Geometries - BoxGeometry", {
beforeEach: function() {
box = new THREE.BoxGeometry( parameters.width, parameters.height, parameters.depth );
cube = new THREE.CubeGeometry( parameters.width, parameters.height, parameters.depth );
boxWithSegments = new THREE.BoxGeometry( parameters.width, parameters.height, parameters.depth,
parameters.widthSegments, parameters.heightSegments, parameters.depthSegments );
geometries = [ box, cube, boxWithSegments ];
}
});
QUnit.test( "standard geometry tests", function( assert ) {
runStdGeometryTests( assert, geometries );
});
})();
|
Use helper to create test strings
|
import fs from 'fs'
import test from 'tape'
import sinon from 'sinon'
import index, {formats} from '../src/commit-msg'
test('index', t => {
t.equal(typeof index, 'object', 'default export is an object')
t.end()
})
test('index.check()', t => {
const readFileSync = sinon.stub(fs, 'readFileSync')
const base = sinon.stub(formats, 'base')
index.check('base', './test/fixtures/COMMIT_EDITMSG')
t.throws(() => { index.check('nein')}, 'calls an existing format')
t.assert(readFileSync.calledOnce, 'calls fs.readFileSync')
t.assert(base.calledOnce, 'calls formats.base')
formats.base.restore()
t.end()
})
test('formats', t => {
t.equal(typeof formats, 'object', 'is an object')
t.end()
})
test('formats.base()', t => {
const under = buildString(10)
const equal = buildString(50)
const over = buildString(51)
t.equal(formats.base(under), true)
t.equal(formats.base(equal), true)
t.equal(formats.base(over), false)
t.assert(typeof formats.base, 'is a function')
t.end()
})
function buildString (length) {
let string = ''
for (let i = 0; i < length; i++) {
string += '_'
}
return string
}
|
import fs from 'fs'
import test from 'tape'
import sinon from 'sinon'
import index, {formats} from '../src/commit-msg'
test('index', t => {
t.equal(typeof index, 'object', 'default export is an object')
t.end()
})
test('index.check()', t => {
const readFileSync = sinon.stub(fs, 'readFileSync')
const base = sinon.stub(formats, 'base')
index.check('base', './test/fixtures/COMMIT_EDITMSG')
t.throws(() => { index.check('nein')}, 'calls an existing format')
t.assert(readFileSync.calledOnce, 'calls fs.readFileSync')
t.assert(base.calledOnce, 'calls formats.base')
formats.base.restore()
t.end()
})
test('formats', t => {
t.equal(typeof formats, 'object', 'is an object')
t.end()
})
test('formats.base()', t => {
const under = '..........' // 10
const equal = '..................................................' // 50
const over = '...................................................' // 51
t.equal(formats.base(under), true)
t.equal(formats.base(equal), true)
t.equal(formats.base(over), false)
t.assert(typeof formats.base, 'is a function')
t.end()
})
|
Remove stric standard notice far calling dynamic method statically.
|
<?php
require_once('Fiskalizator.php');
$fis = new Fiskalizator();
$fis->certPath = 'demo.pfx';
$fis->certPass = 'pass';
$fis->CisUrl = 'https://cistest.apis-it.hr:8449/FiskalizacijaServiceTest';
$doc = new DOMDocument();
$xml_string = file_get_contents('racun.xml');
$doc->loadXML($xml_string);
$response = $fis->doRequest($doc);
if ($errors = $fis->getErrors() or $response === false ) {
foreach ($errors as $error){
echo 'Error ==> "'.htmlspecialchars($error).'"<br>';
}
} else {
echo 'Zahtjev uspjeno izvren.<br>';
if ($jir = $fis->getJIR($response)){
echo 'JIR: '.$jir;
}
}
|
<?php
require_once('Fiskalizator.php');
$fis = new Fiskalizator();
$fis->certPath = 'path/to/demo/demo.pfx';
$fis->certPass = 'mypass';
$fis->CisUrl = 'https://cistest.apis-it.hr:8449/FiskalizacijaServiceTest';
$xml_string = file_get_contents('racun.xml');
$doc = DOMDocument::loadXML($xml_string);
$response = $fis->doRequest($doc);
if ($errors = $fis->getErrors() or $response === false ) {
foreach ($errors as $error){
echo 'Error ==> "'.htmlspecialchars($error).'"<br>';
}
} else {
echo 'Zahtjev uspjeno izvren.<br>';
if ($jir = $fis->getJIR($response)){
echo 'JIR: '.$jir;
}
}
|
Add API call to return service dialogs
https://trello.com/c/qfdnTNlk
|
(function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'marketplace.details': {
url: '/:serviceTemplateId',
templateUrl: 'app/states/marketplace/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Service Template Details',
resolve: {
dialogs: resolveDialogs,
serviceTemplate: resolveServiceTemplate
}
}
};
}
/** @ngInject */
function resolveServiceTemplate($stateParams, CollectionsApi) {
return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId);
}
/** @ngInject */
function resolveDialogs($stateParams, CollectionsApi) {
var options = {expand: true, attributes: 'content'};
return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options);
}
/** @ngInject */
function StateController(dialogs, serviceTemplate) {
var vm = this;
vm.title = 'Service Template Details';
vm.dialogs = dialogs.resources[0].content;
vm.serviceTemplate = serviceTemplate;
}
})();
|
(function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'marketplace.details': {
url: '/:serviceTemplateId',
templateUrl: 'app/states/marketplace/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Service Template Details',
resolve: {
serviceTemplate: resolveServiceTemplate
}
}
};
}
/** @ngInject */
function resolveServiceTemplate($stateParams, CollectionsApi) {
return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId);
}
/** @ngInject */
function StateController(serviceTemplate) {
var vm = this;
vm.title = 'Service Template Details';
vm.serviceTemplate = serviceTemplate;
}
})();
|
Stop truncating the DB for dev/demo pushes.
|
import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
base_update_assets = update_assets
base_database = database
@task
def database(ctx):
# only ever run this one on demo and dev.
base_database()
management_cmd(ctx, 'rnasync')
management_cmd(ctx, 'update_security_advisories --quiet', use_src_dir=True)
management_cmd(ctx, 'cron update_ical_feeds')
management_cmd(ctx, 'cron update_tweets')
management_cmd(ctx, 'runscript update_firefox_os_feeds')
@task
def update_assets(ctx):
"""Compile/compress static assets and fetch external data."""
base_update_assets()
# can't do this in `database` because it needs to run before
# the file sync from SRC -> WWW.
management_cmd(ctx, 'update_product_details', use_src_dir=True)
|
import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
base_update_assets = update_assets
base_database = database
@task
def database(ctx):
# only ever run this one on demo and dev.
management_cmd(ctx, 'bedrock_truncate_database --yes-i-am-sure')
base_database()
management_cmd(ctx, 'rnasync')
management_cmd(ctx, 'update_security_advisories --force --quiet', use_src_dir=True)
management_cmd(ctx, 'cron update_ical_feeds')
management_cmd(ctx, 'cron update_tweets')
management_cmd(ctx, 'runscript update_firefox_os_feeds')
@task
def update_assets(ctx):
"""Compile/compress static assets and fetch external data."""
base_update_assets()
# can't do this in `database` because it needs to run before
# the file sync from SRC -> WWW.
management_cmd(ctx, 'update_product_details', use_src_dir=True)
|
Remove erase of coverage file as it's needed by coveralls
|
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from config import BASE_DIR
app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig')
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
@manager.command
def test(coverage=False):
"""Run the unit tests."""
if coverage and not os.environ.get('FLASK_COVERAGE'):
import sys
os.environ['FLASK_COVERAGE'] = '1'
os.execvp(sys.executable, [sys.executable] + sys.argv)
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if COV:
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
covdir = os.path.join(BASE_DIR, 'htmlcov')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
if __name__ == '__main__':
manager.run()
|
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from config import BASE_DIR
app.config.from_object(os.getenv('BG_CONFIG') or 'config.DevelopmentConfig')
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
@manager.command
def test(coverage=False):
"""Run the unit tests."""
if coverage and not os.environ.get('FLASK_COVERAGE'):
import sys
os.environ['FLASK_COVERAGE'] = '1'
os.execvp(sys.executable, [sys.executable] + sys.argv)
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if COV:
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
covdir = os.path.join(BASE_DIR, 'htmlcov')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
COV.erase()
if __name__ == '__main__':
manager.run()
|
Define default value for tls authorization mode
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
import java.util.Arrays;
/**
* @author bjorncs
*/
public enum AuthorizationMode {
DISABLE("disable"),
LOG_ONLY("log_only"),
ENFORCE("enforce");
final String configValue;
AuthorizationMode(String configValue) {
this.configValue = configValue;
}
public String configValue() {
return configValue;
}
/**
* @return Default value when authorization mode is not explicitly specified
*/
public static AuthorizationMode defaultValue() {
return ENFORCE;
}
static AuthorizationMode fromConfigValue(String configValue) {
return Arrays.stream(values())
.filter(v -> v.configValue.equals(configValue))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
}
}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
import java.util.Arrays;
/**
* @author bjorncs
*/
public enum AuthorizationMode {
DISABLE("disable"),
LOG_ONLY("log_only"),
ENFORCE("enforce");
final String configValue;
AuthorizationMode(String configValue) {
this.configValue = configValue;
}
public String configValue() {
return configValue;
}
static AuthorizationMode fromConfigValue(String configValue) {
return Arrays.stream(values())
.filter(v -> v.configValue.equals(configValue))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
}
}
|
fix(umd): Use UMD as lib target
|
const webpack = require('webpack');
const path = require('path');
const entry = path.join(__dirname, './Sources/index.js');
const sourcePath = path.join(__dirname, './Sources');
const outputPath = path.join(__dirname, './dist');
const vtkRules = require('./Utilities/config/rules-vtk.js');
const linterRules = require('./Utilities/config/rules-linter.js');
module.exports = {
entry,
output: {
path: outputPath,
filename: 'vtk.js',
libraryTarget: 'umd',
},
module: {
rules: [
{ test: entry, loader: 'expose-loader?vtk' },
].concat(linterRules, vtkRules),
},
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
sourcePath,
],
alias: {
'vtk.js': __dirname,
},
},
};
|
const webpack = require('webpack');
const path = require('path');
const entry = path.join(__dirname, './Sources/index.js');
const sourcePath = path.join(__dirname, './Sources');
const outputPath = path.join(__dirname, './dist');
const vtkRules = require('./Utilities/config/rules-vtk.js');
const linterRules = require('./Utilities/config/rules-linter.js');
module.exports = {
entry,
output: {
path: outputPath,
filename: 'vtk.js',
},
module: {
rules: [
{ test: entry, loader: 'expose-loader?vtk' },
].concat(linterRules, vtkRules),
},
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
sourcePath,
],
alias: {
'vtk.js': __dirname,
},
},
};
|
Add the README as the long description to the package.
|
from setuptools import setup, find_packages
import wsgiservice
setup(
name='WsgiService',
version=wsgiservice.__version__,
description="A lean WSGI framework for easy creation of REST services",
long_description=open('README').read(),
author=", ".join(wsgiservice.__author__),
url='http://github.com/pneff/wsgiservice/tree/master',
download_url='http://pypi.python.org/pypi/WsgiService',
packages=find_packages(),
install_requires=[
'decorator',
'webob >= 0.9.7',
],
tests_require=[
'nose',
'mox',
],
test_suite='nose.collector',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.6',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
]
)
|
from setuptools import setup, find_packages
import wsgiservice
setup(
name='WsgiService',
version=wsgiservice.__version__,
description="A lean WSGI framework for easy creation of REST services",
author=", ".join(wsgiservice.__author__),
url='http://github.com/pneff/wsgiservice/tree/master',
download_url='http://pypi.python.org/pypi/WsgiService',
packages=find_packages(),
install_requires=[
'decorator',
'webob >= 0.9.7',
],
tests_require=[
'nose',
'mox',
],
test_suite='nose.collector',
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.6',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
]
)
|
Use OneToOneField on SecondaryStructure model
|
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.
"""
from django.db import models
class SecondaryStructure(models.Model):
id = models.AutoField(primary_key=True)
accession = models.OneToOneField(
'Accession',
db_column='rnc_accession_id',
to_field='accession',
related_name='secondary_structure',
)
secondary_structure = models.TextField()
md5 = models.CharField(max_length=32, db_index=True)
class Meta:
db_table = 'rnc_secondary_structure'
unique_together = (('accession', 'md5'),)
|
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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.
"""
from django.db import models
class SecondaryStructure(models.Model):
id = models.AutoField(primary_key=True)
accession = models.ForeignKey(
'Accession',
db_column='rnc_accession_id',
to_field='accession',
related_name='secondary_structure',
)
secondary_structure = models.TextField()
md5 = models.CharField(max_length=32, db_index=True)
class Meta:
db_table = 'rnc_secondary_structure'
unique_together = (('accession', 'md5'),)
|
Set up watch task in Gulp
|
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')();
gulp.task('sass', () => gulp
.src('css/quis.scss')
.pipe(plugins.sass({
outputStyle: 'compressed'
}))
.pipe(gulp.dest('css/'))
);
gulp.task('js', () => gulp
.src([
'js/constants.js',
'js/rateLimit.js',
'js/scrollPages.js',
'js/scrollPhotos.js',
'js/jquery.infinitescroll.js',
'js/jquery.viewportSelector.js',
'js/map.js',
'js/init.js',
])
.pipe(plugins.uglify({
outputStyle: 'compressed'
}))
.pipe(plugins.concat('quis.js'))
.pipe(gulp.dest('js/'))
);
gulp.task('watchForChanges', function() {
gulp.watch('js/**/*', ['js']);
gulp.watch('css/**/*', ['sass']);
});
gulp.task('build',
['sass', 'js']
);
gulp.task('default',
['build', 'watchForChanges']
);
|
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')();
gulp.task('sass', () => gulp
.src('css/quis.scss')
.pipe(plugins.sass({
outputStyle: 'compressed'
}))
.pipe(gulp.dest('css/'))
);
gulp.task('js', () => gulp
.src([
'js/constants.js',
'js/rateLimit.js',
'js/scrollPages.js',
'js/scrollPhotos.js',
'js/jquery.infinitescroll.js',
'js/jquery.viewportSelector.js',
'js/map.js',
'js/init.js',
])
.pipe(plugins.uglify({
outputStyle: 'compressed'
}))
.pipe(plugins.concat('quis.js'))
.pipe(gulp.dest('js/'))
);
gulp.task('default',
['sass', 'js']
);
|
Reformat on soap client test
|
<?php
class SoapClientTest extends PHPUnit_Framework_TestCase {
private $factory;
private $wsdlClassMapper;
protected function setUp() {
$this->wsdlClassMapper = \Mockery::mock('\Vmwarephp\WsdlClassMapper');
$this->factory = new \Vmwarephp\Factory\SoapClient($this->wsdlClassMapper);
}
function testMakesASoapClient() {
$vhost = $this->aVhost();
$aClassMap = $this->aClassMap();
$this->wsdlClassMapper->shouldReceive('getClassMap')->andReturn($aClassMap);
$soapClient = $this->factory->make($vhost);
$this->assertEquals(SOAP_SINGLE_ELEMENT_ARRAYS + SOAP_USE_XSI_ARRAY_TYPE, $soapClient->_features);
$this->assertEquals('https://' . $vhost->host . '/sdk', $soapClient->location);
$this->assertEquals($aClassMap, $soapClient->_classmap);
}
private function aVhost() {
$vhost = \Mockery::mock('\Vmwarephp\Vhost');
$vhost->host = 'a_host';
return $vhost;
}
private function aClassMap() {
return array('klass' => 'klass');
}
}
|
<?php
class SoapClientTest extends PHPUnit_Framework_TestCase {
private $factory;
private $wsdlClassMapper;
protected function setUp() {
$this->wsdlClassMapper = \Mockery::mock('\Vmwarephp\WsdlClassMapper');
$this->factory = new \Vmwarephp\Factory\SoapClient($this->wsdlClassMapper);
}
function testMakesASoapClient() {
$vhost = $this->aVhost();
$aClassMap = $this->aClassMap();
$this->wsdlClassMapper->shouldReceive('getClassMap')->andReturn($aClassMap);
$soapClient = $this->factory->make($vhost);
$this->assertEquals(SOAP_SINGLE_ELEMENT_ARRAYS + SOAP_USE_XSI_ARRAY_TYPE, $soapClient->_features);
$this->assertEquals('https://' . $vhost->host . '/sdk', $soapClient->location);
$this->assertEquals($aClassMap, $soapClient->_classmap);
}
private function aVhost() {
$vhost = \Mockery::mock('\Vmwarephp\Vhost');
$vhost->host = 'a_host';
return $vhost;
}
private function aClassMap() {
return array('klass' => 'klass');
}
}
|
Replace from ITEM not FILE
|
//Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
//Login to Discord
client.login(config.API.discord);
//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
items.forEach(function(item) {
var file = item.replace(/['"]+/g, '');
command[file] = require(file);
})
})
client.on('ready', function() {
console.log("Successfully connected to Discord!");
client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});
client.on('message', function(message) {
if (!message.content.startsWith(config.MSS.prefix)) return false;
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
if (input[0] === "eval" && message.author.id === "190519304972664832") {
eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
}
});
|
//Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
//Login to Discord
client.login(config.API.discord);
//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
items.forEach(function(item) {
var file = file.replace(/['"]+/g, '');
command[file] = require(file);
})
})
client.on('ready', function() {
console.log("Successfully connected to Discord!");
client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});
client.on('message', function(message) {
if (!message.content.startsWith(config.MSS.prefix)) return false;
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
if (input[0] === "eval" && message.author.id === "190519304972664832") {
eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
}
});
|
Comment out unfinished test in util
|
import unittest
from bencodepy import encode as bencode
from xirvik.util import verify_torrent_contents, VerificationError
def create_torrent(path, save_to=None, piece_length=256):
pass
def create_random_data_file(path, size=2306867):
"""size is intentionally a non-power of 2"""
pass
class TestTorrentVerfication(unittest.TestCase):
def setUp(self):
self.torrent_data = bencode({
b'info': {
b'name': 'Test torrent',
b'piece length': 20,
b'pieces': '',
b'files': [
{
b'path': '',
},
],
}
})
#def test_verify_torrent_contents(self):
#verify_torrent_contents()
if __name__ == '__main__':
unittest.main()
|
import unittest
from bencodepy import encode as bencode
from xirvik.util import verify_torrent_contents, VerificationError
def create_torrent(path, save_to=None, piece_length=256):
pass
def create_random_data_file(path, size=2306867):
"""size is intentionally a non-power of 2"""
pass
class TestTorrentVerfication(unittest.TestCase):
def setUp(self):
self.torrent_data = bencode({
b'info': {
b'name': 'Test torrent',
b'piece length': 20,
b'pieces': '',
b'files': [
{
b'path': '',
},
],
}
})
def test_verify_torrent_contents(self):
verify_torrent_contents()
if __name__ == '__main__':
unittest.main()
|
Switch to array for questionnaire list
|
// According to the swagger documentation, qrList is an object with
// questionnaire ids as key, and an object with `id`, `name`, `'label`,
// `agency` and `survey` as values. A survey is made of an `id`, a
// `name` and an `agency`
export function qListToState(model) {
return model.reduce((update, qr) => {
const {
id, name, label, agency,
survey: {
id: surveyId,
name: surveyName, //TODO investigate, survey name seems to be the only
//property not prefixed by ``
agency: surveyAgency
}
} = qr
update[id] = {
id: id,
name: name,
label: label[0], // in the questionnaire list, label is a string not
// an array
agency: agency,
survey: {
id: surveyId,
name: surveyName,
agency: surveyAgency
}
}
return update
}, {})
}
|
// According to the swagger documentation, qrList is an object with
// questionnaire ids as key, and an object with `id`, `name`, `'label`,
// `agency` and `survey` as values. A survey is made of an `id`, a
// `name` and an `agency`
export function qListToState(model) {
return Object.keys(model).reduce((update, qrId) => {
const {
id, name, label, agency,
survey: {
id: surveyId,
name: surveyName, //TODO investigate, survey name seems to be the only
//property not prefixed by ``
agency: surveyAgency
}
} = model[qrId]
update[qrId] = {
id: id,
name: name,
label: label[0], // in the questionnaire list, label is a string not
// an array
agency: agency,
survey: {
id: surveyId,
name: surveyName,
agency: surveyAgency
}
}
return update
}, {})
}
|
Make reachable depend on availability
|
package com.phonegap.demo;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.net.*;
import android.webkit.WebView;
public class NetworkManager {
Context mCtx;
WebView mView;
ConnectivityManager sockMan;
NetworkManager(Context ctx, WebView view)
{
mCtx = ctx;
mView = view;
sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
public boolean isAvailable()
{
NetworkInfo info = sockMan.getActiveNetworkInfo();
return info.isConnected();
}
public boolean isReachable(String uri)
{
boolean reached = isAvailable();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);
httpclient.execute(httpget);
} catch (Exception e) { reached = false;}
return reached;
}
}
|
package com.phonegap.demo;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.net.*;
import android.webkit.WebView;
public class NetworkManager {
Context mCtx;
WebView mView;
ConnectivityManager sockMan;
NetworkManager(Context ctx, WebView view)
{
mCtx = ctx;
mView = view;
sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
public boolean isAvailable()
{
NetworkInfo info = sockMan.getActiveNetworkInfo();
return info.isConnected();
}
public boolean isReachable(String uri)
{
boolean reached = true;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);
httpclient.execute(httpget);
} catch (Exception e) { reached = false;}
return reached;
}
}
|
Fix recursion issue with zip/rar files
|
import gzip
import bz2
import rarfile
import zipfile
import tarfile
class PackageHandler:
def __init__(self, buffer):
self.buffer = buffer
def __iter__(self):
for name in self.archive.namelist():
info = self.archive.getinfo(name)
if hasattr(info, 'isdir') and info.isdir():
continue
if name[-1] == "/":
continue
with self.archive.open(name) as ar:
# TODO: Handle archives
outbuf = ar.read(1000)
yield (name, outbuf)
class ZipHandler(PackageHandler):
MIMETYPES = ["application/zip"]
def __init__(self, buffer):
PackageHandler.__init__(self, buffer)
self.archive = zipfile.ZipFile(buffer)
class RarHandler(PackageHandler):
MIMETYPES = ["application/x-rar-compressed"]
def __init__(self, buffer):
PackageHandler.__init__(self, buffer)
self.archive = zipfile.RarFile(buffer)
package_handlers = {}
def register_handler(handler):
for mt in handler.MIMETYPES:
package_handlers[mt] = handler
register_handler(ZipHandler)
register_handler(RarHandler)
|
import gzip
import bz2
import rarfile
import zipfile
import tarfile
class PackageHandler:
def __init__(self, buffer):
self.buffer = buffer
def __iter__(self):
for name in self.archive.namelist():
with self.archive.open(name) as ar:
# TODO: Handle archives
outbuf = ar.read(1000)
yield (name, outbuf)
class ZipHandler(PackageHandler):
MIMETYPES = ["application/zip"]
def __init__(self, buffer):
PackageHandler.__init__(self, buffer)
self.archive = zipfile.ZipFile(buffer)
class RarHandler(PackageHandler):
MIMETYPES = ["application/x-rar-compressed"]
def __init__(self, buffer):
PackageHandler.__init__(self, buffer)
self.archive = zipfile.RarFile(buffer)
package_handlers = {}
def register_handler(handler):
for mt in handler.MIMETYPES:
package_handlers[mt] = handler
register_handler(ZipHandler)
register_handler(RarHandler)
|
Add generic Python 2 classifier.
|
from distutils.core import setup
from setuptools import find_packages
setup(
name='sendwithus',
version='1.0.12',
author='sendwithus',
author_email='us@sendwithus.com',
packages=find_packages(),
scripts=[],
url='https://github.com/sendwithus/sendwithus_python',
license='LICENSE.txt',
description='Python API client for sendwithus.com',
long_description=open('README.md').read(),
test_suite="sendwithus.test",
install_requires=[
"requests >= 1.1.0"
],
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: Apache Software License",
"Development Status :: 5 - Production/Stable",
"Topic :: Communications :: Email"
]
)
|
from distutils.core import setup
from setuptools import find_packages
setup(
name='sendwithus',
version='1.0.12',
author='sendwithus',
author_email='us@sendwithus.com',
packages=find_packages(),
scripts=[],
url='https://github.com/sendwithus/sendwithus_python',
license='LICENSE.txt',
description='Python API client for sendwithus.com',
long_description=open('README.md').read(),
test_suite="sendwithus.test",
install_requires=[
"requests >= 1.1.0"
],
classifiers=[
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: Apache Software License",
"Development Status :: 5 - Production/Stable",
"Topic :: Communications :: Email"
]
)
|
Use pysqlite2 when sqlite3 is not available
|
#! /usr/bin/python
from distutils.core import setup
setup(name = 'myproxy_oauth',
version = '0.12',
description = 'MyProxy OAuth Delegation Service',
author = 'Globus Toolkit',
author_email = 'support@globus.org',
packages = [
'myproxy',
'myproxyoauth',
'myproxyoauth.templates',
'myproxyoauth.static',
'oauth2'],
package_data = {
'myproxyoauth': [ 'templates/*.html', 'static/*.png', 'static/*.css' ]
},
scripts = [ 'wsgi.py', 'myproxy-oauth-setup' ],
data_files = [
('apache', [
'conf/myproxy-oauth',
'conf/myproxy-oauth-2.4',
'conf/myproxy-oauth-epel5' ])]
)
|
#! /usr/bin/python
from distutils.core import setup
setup(name = 'myproxy_oauth',
version = '0.11',
description = 'MyProxy OAuth Delegation Service',
author = 'Globus Toolkit',
author_email = 'support@globus.org',
packages = [
'myproxy',
'myproxyoauth',
'myproxyoauth.templates',
'myproxyoauth.static',
'oauth2'],
package_data = {
'myproxyoauth': [ 'templates/*.html', 'static/*.png', 'static/*.css' ]
},
scripts = [ 'wsgi.py', 'myproxy-oauth-setup' ],
data_files = [
('apache', [
'conf/myproxy-oauth',
'conf/myproxy-oauth-2.4',
'conf/myproxy-oauth-epel5' ])]
)
|
Add CCG replication - loading of ClassFile, RiskArray & Position
|
package com.easymargining.replication.ccg.market.parsers;
import com.easymargining.replication.ccg.market.ClassFileDatas;
import com.easymargining.replication.ccg.market.ClassFileItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.net.URL;
import java.util.List;
/**
* Created by Gilles Marchal on 07/12/2015.
*/
@Service
@Slf4j
public class CcgMarsClassFileLoader {
public List<ClassFileItem> readCCGClassFileFile(URL file) throws IOException, JAXBException {
log.info("Read CCG ClassFile file " + file);
JAXBContext jaxbContext = JAXBContext.newInstance(ClassFileDatas.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ClassFileDatas datas = (ClassFileDatas) jaxbUnmarshaller.unmarshal( file );
List<ClassFileItem> beans = datas.getClassFileDatas();
log.info("CCG ClassFile file " + file + ": " + beans.size() + " datas.");
return beans;
}
}
|
package com.easymargining.replication.ccg.market.parsers;
import com.easymargining.replication.ccg.market.ClassFileDatas;
import com.easymargining.replication.ccg.market.ClassFileItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.net.URL;
import java.util.List;
/**
* Created by Gilles Marchal on 07/12/2015.
*/
@Service
@Slf4j
class CcgMarsClassFileLoader {
public List<ClassFileItem> readCCGClassFileFile(URL file) throws IOException, JAXBException {
log.info("Read CCG ClassFile file " + file);
JAXBContext jaxbContext = JAXBContext.newInstance(ClassFileDatas.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ClassFileDatas datas = (ClassFileDatas) jaxbUnmarshaller.unmarshal( file );
List<ClassFileItem> beans = datas.getClassFileDatas();
log.info("CCG ClassFile file " + file + ": " + beans.size() + " datas.");
return beans;
}
}
|
Use functional JSX component. Update to `loaderUtils` to support options.
|
'use strict';
const setCase = require('case');
const fs = require('fs');
const loaderUtils = require('loader-utils');
const marked = require('marked');
const path = require('path');
const Renderer = require('./JsxRenderer');
marked.setOptions({
highlight: function(code, lang) {
const prism = require('./prism-jsx');
lang = lang && lang.indexOf('language-') === 0 ? lang.replace('language-', '') : lang;
return prism.highlight(code, prism.languages[lang]);
}
});
function defaultRender(contents, resourcePath, options) {
const prefix = setCase.pascal(path.basename(resourcePath, '.md').toLowerCase() + '/');
return `
var React = require('react');
${options.preamble || ''}
module.exports = function () {
return (<div>${contents}</div>)
});
module.exports.displayName = '${prefix}';
${options.postamble || ''}
`;
}
module.exports = function(contents) {
const options = loaderUtils.getOptions(this) || {};
this.cacheable();
const renderer = options.renderer || new Renderer();
const render = options.render || defaultRender;
return render(marked(contents, { renderer }), this.resourcePath, options)
}
module.exports.Renderer = Renderer
|
'use strict';
var fs = require('fs');
var path = require('path');
var marked = require('marked');
var setCase = require('case')
var Renderer = require('./JsxRenderer');
marked.setOptions({
xhtml: true,
highlight: function(code, lang) {
let prism = require('./prism-jsx');
lang = lang && lang.indexOf('language-') === 0 ? lang.replace('language-', '') : lang;
return prism.highlight(code, prism.languages[lang]);
}
});
function defaultRender(contents, resourcePath, options) {
let prefix = setCase.pascal(path.basename(resourcePath, '.md').toLowerCase() + '/');
return `
var React = require('react');
${options.preamble || ''}
module.exports = React.createClass({
displayName: '${prefix}',
render: function() {
return (
<div {...this.props}>
${contents}
</div>
)
}
});
${options.postamble || ''}
`;
}
module.exports = function(contents) {
var options = this.options.markdownJsxLoader || {}
this.cacheable();
Renderer = options.renderer || this.options.renderer || Renderer;
var render = options.render || defaultRender
return render(marked(contents, {
renderer: new Renderer()
}), this.resourcePath, options)
}
module.exports.Renderer = Renderer
|
Fix crash when checking for GPS availability denied on API lower than 21.
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import android.Manifest;
import android.content.Context;
import android.location.LocationManager;
import android.support.v4.content.PermissionChecker;
public class GpsUtils {
public static boolean isGpsEnabled(Context context) {
if (PermissionChecker.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
// to cover the case when permission denied on API lower than 21
return false;
}
public static boolean isGpsAvailable(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER));
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package info.zamojski.soft.towercollector.utils;
import android.content.Context;
import android.location.LocationManager;
public class GpsUtils {
public static boolean isGpsEnabled(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public static boolean isGpsAvailable(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER));
}
}
|
Handle early lines with no point spreads from Bovada
|
const crypto = require('crypto');
const jp = require('jsonpath');
const NFLWeek = require('./NFLWeek');
module.exports.call = json => jp
.query(JSON.parse(json), '$..items[?(@.type=="NFL")]')
.map((game) => {
const pointSpread = jp.query(game, '$..itemList[?(@.description=="Point Spread")]')[0];
if (!pointSpread) { return null; }
const home = pointSpread.outcomes.find(team => team.type === 'H');
const away = pointSpread.outcomes.find(team => team.type === 'A');
if (!home.price || !away.price) { return null; }
return {
id: crypto.createHash('md5')
.update(`${home.description}|${away.description}|${NFLWeek.seasonYear}|${NFLWeek.forGame(game)}`)
.digest('hex'),
homeTeam: home.description,
homeSpread: Number(home.price.handicap),
awayTeam: away.description,
awaySpread: Number(away.price.handicap),
startTime: game.startTime,
};
}).filter(game => game);
|
const crypto = require('crypto');
const jp = require('jsonpath');
const NFLWeek = require('./NFLWeek');
module.exports.call = json => jp
.query(JSON.parse(json), '$..items[?(@.type=="NFL")]')
.map((game) => {
const pointSpread = jp.query(game, '$..itemList[?(@.description=="Point Spread")]')[0];
if (!pointSpread) { return null; }
const home = pointSpread.outcomes.find(team => team.type === 'H');
const away = pointSpread.outcomes.find(team => team.type === 'A');
return {
id: crypto.createHash('md5')
.update(`${home.description}|${away.description}|${NFLWeek.seasonYear}|${NFLWeek.forGame(game)}`)
.digest('hex'),
homeTeam: home.description,
homeSpread: Number(home.price.handicap),
awayTeam: away.description,
awaySpread: Number(away.price.handicap),
startTime: game.startTime,
};
}).filter(game => game);
|
Append scripts to the load page
|
var webdriver = require('selenium-webdriver');
function loadAssets (driver) {
var s = '';
s += 'var s = document.createElement("script");';
s += 's.type = "text/javascript";'
s += 's.src = "http://localhost:7000/core.js";';
s += 'var domel = document.getElementsByTagName("head")[0];';
s += 'if (domel) domel.appendChild(s, domel);';
driver.get('http://quailpages/forms/simple-form.html');
driver.executeScript(s);
}
/**
* creates a webdriver client
* @param callBack or promise
*/
exports.createClient = function (callBack) {
var serverConfig = 'http://127.0.0.1:4444/wd/hub';
var capabilities = {
silent: true, // maybe output more for tests?
browserName: 'phantomjs',
javascriptEnabled: true,
takesScreenshot: true,
databaseEnabled: false,
cssSelectorsEnabled:true,
webStorageEnabled: true
};
var driver = new webdriver
.Builder()
.usingServer(serverConfig)
.withCapabilities(capabilities)
.build();
loadAssets(driver);
if (typeof callBack === 'function') {
return callBack (driver);
}
else if ( typeof callBack === 'object' && typeof callBack.resolve === 'function' ) {
return callBack.resolve(driver);
}
else {
return driver;
}
}
|
var webdriver = require('selenium-webdriver');
function loadAssets (driver) {
var s = '';
s += 'var s = document.createElement("script");';
s += 's.type = "text/javascript";'
s += 's.src = "http://localhost:7000/core.js";';
s += 'var domel = document.getElementsByTagName("script")[0];';
s += 'domel.parentNode.insertBefore(s, domel);';
driver.get('http://quailpages/forms/simple-form.html');
driver.executeScript(s);
}
/**
* creates a webdriver client
* @param callBack or promise
*/
exports.createClient = function (callBack) {
var serverConfig = 'http://127.0.0.1:4444/wd/hub';
var capabilities = {
silent: true, // maybe output more for tests?
browserName: 'phantomjs',
javascriptEnabled: true,
takesScreenshot: true,
databaseEnabled: false,
cssSelectorsEnabled:true,
webStorageEnabled: true
};
var driver = new webdriver
.Builder()
.usingServer(serverConfig)
.withCapabilities(capabilities)
.build();
loadAssets(driver);
if (typeof callBack === 'function') {
return callBack (driver);
}
else if ( typeof callBack === 'object' && typeof callBack.resolve === 'function' ) {
return callBack.resolve(driver);
}
else {
return driver;
}
}
|
Change email from contact@hedi-kestouri.tn to hedi@kastouri.com
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'hedi@kastouri.tn'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'contact@hedi-kestouri.tn'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Change script timeout for Travis
|
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/docs/referenceConf.js
/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 30000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['no-sandbox']
}
},
directConnect: false,
seleniumAddress: 'http://selenium:4444/wd/hub',
baseUrl: 'http://e2e:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
useAllAngular2AppRoots: true,
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e'
});
},
onPrepare: function() {
jasmine.getEnv().addReporter(new SpecReporter());
}
};
|
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/docs/referenceConf.js
/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['no-sandbox']
}
},
directConnect: false,
seleniumAddress: 'http://selenium:4444/wd/hub',
baseUrl: 'http://e2e:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
useAllAngular2AppRoots: true,
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e'
});
},
onPrepare: function() {
jasmine.getEnv().addReporter(new SpecReporter());
}
};
|
Introduce simple sorted slice as a leaderboard
|
// Real-time massively multiplayer online space strategy arcade browser game!
package main
import (
"os"
"os/signal"
"syscall"
"warcluster/config"
"warcluster/entities/db"
"warcluster/leaderboard"
"warcluster/server"
)
var cfg config.Config
func main() {
go final()
cfg.Load("config/config.gcfg")
db.InitPool(cfg.Database.Host, cfg.Database.Port, 8)
leaderboard.New().Init()
server.Start(cfg.Server.Host, cfg.Server.Port)
}
func final() {
exitChan := make(chan os.Signal, 1)
signal.Notify(exitChan, syscall.SIGINT)
signal.Notify(exitChan, syscall.SIGKILL)
signal.Notify(exitChan, syscall.SIGTERM)
<-exitChan
server.Stop()
os.Exit(0)
}
|
// Real-time massively multiplayer online space strategy arcade browser game!
package main
import (
"os"
"os/signal"
"syscall"
"warcluster/config"
"warcluster/entities/db"
"warcluster/leaderboard"
"warcluster/server"
)
var cfg config.Config
func main() {
go final()
cfg.Load("config/config.gcfg")
db.InitPool(cfg.Database.Host, cfg.Database.Port, 8)
server.Start(cfg.Server.Host, cfg.Server.Port)
}
func final() {
exitChan := make(chan os.Signal, 1)
signal.Notify(exitChan, syscall.SIGINT)
signal.Notify(exitChan, syscall.SIGKILL)
signal.Notify(exitChan, syscall.SIGTERM)
<-exitChan
server.Stop()
os.Exit(0)
}
|
Update package to version 1.1
|
#/usr/bin/env python
from setuptools import setup
try:
readme = open("README.rst")
long_description = str(readme.read())
finally:
readme.close()
setup(
name='pyziptax',
version='1.1',
description='Python API for accessing sales tax information from Zip-Tax.com',
long_description=long_description,
author='Albert Wang',
author_email='aywang31@gmail.com',
url='http://github.com/albertyw/pyziptax',
packages=['pyziptax', ],
install_requires=[
'requests>=1.1.0',
],
license='Apache',
test_suite="tests",
tests_require=[
'mock>=1.0.1',
'tox',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Localization',
'Topic :: Office/Business :: Financial :: Accounting',
],
)
|
#/usr/bin/env python
from setuptools import setup
try:
readme = open("README.rst")
long_description = str(readme.read())
finally:
readme.close()
setup(
name='pyziptax',
version='1.0',
description='Python API for accessing sales tax information from Zip-Tax.com',
long_description=long_description,
author='Albert Wang',
author_email='aywang31@gmail.com',
url='http://github.com/albertyw/pyziptax',
packages=['pyziptax', ],
install_requires=[
'requests>=1.1.0',
],
license='Apache',
test_suite="tests",
tests_require=[
'mock>=1.0.1',
'tox',
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Localization',
'Topic :: Office/Business :: Financial :: Accounting',
],
)
|
Use vaadin icon instead font awesome icon for home page
|
package com.github.yuri0x7c1.ofbiz.explorer.common.ui.view;
import org.vaadin.spring.sidebar.annotation.SideBarItem;
import org.vaadin.spring.sidebar.annotation.VaadinFontIcon;
import com.github.yuri0x7c1.ofbiz.explorer.common.ui.sidebar.Sections;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.VerticalLayout;
@SpringView(name = "")
@SideBarItem(sectionId = Sections.VIEWS, caption = "Home", order = 0)
@VaadinFontIcon(VaadinIcons.HOME)
public class HomeView extends VerticalLayout implements View {
public HomeView() {
setSpacing(true);
setMargin(true);
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
}
}
|
package com.github.yuri0x7c1.ofbiz.explorer.common.ui.view;
import org.vaadin.spring.sidebar.annotation.FontAwesomeIcon;
import org.vaadin.spring.sidebar.annotation.SideBarItem;
import com.github.yuri0x7c1.ofbiz.explorer.common.ui.sidebar.Sections;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.FontAwesome;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.VerticalLayout;
@SpringView(name = "")
@SideBarItem(sectionId = Sections.VIEWS, caption = "Home", order = 0)
@FontAwesomeIcon(FontAwesome.HOME)
public class HomeView extends VerticalLayout implements View {
public HomeView() {
setSpacing(true);
setMargin(true);
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
}
}
|
Use a waveshaper to hard limit samples
|
class VolumeEffect {
constructor (audioContext, volume, startSeconds, endSeconds) {
this.audioContext = audioContext;
this.input = this.audioContext.createGain();
this.output = this.audioContext.createGain();
this.gain = this.audioContext.createGain();
// Smoothly ramp the gain up before the start time, and down after the end time.
this.rampLength = 0.01;
this.gain.gain.setValueAtTime(1.0, Math.max(0, startSeconds - this.rampLength));
this.gain.gain.exponentialRampToValueAtTime(volume, startSeconds);
this.gain.gain.setValueAtTime(volume, endSeconds);
this.gain.gain.exponentialRampToValueAtTime(1.0, endSeconds + this.rampLength);
// Use a waveshaper node to prevent sample values from exceeding -1 or 1.
// Without this, gain can cause samples to exceed this range, then they
// are clipped on save, and the sound is distorted on load.
this.waveShaper = this.audioContext.createWaveShaper();
this.waveShaper.curve = new Float32Array([-1, 1]);
this.waveShaper.oversample = 'none';
this.input.connect(this.gain);
this.gain.connect(this.waveShaper);
this.waveShaper.connect(this.output);
}
}
export default VolumeEffect;
|
class VolumeEffect {
constructor (audioContext, volume, startSeconds, endSeconds) {
this.audioContext = audioContext;
this.input = this.audioContext.createGain();
this.output = this.audioContext.createGain();
this.gain = this.audioContext.createGain();
// Smoothly ramp the gain up before the start time, and down after the end time.
this.rampLength = 0.01;
this.gain.gain.setValueAtTime(1.0, Math.max(0, startSeconds - this.rampLength));
this.gain.gain.exponentialRampToValueAtTime(volume, startSeconds);
this.gain.gain.setValueAtTime(volume, endSeconds);
this.gain.gain.exponentialRampToValueAtTime(1.0, endSeconds + this.rampLength);
this.input.connect(this.gain);
this.gain.connect(this.output);
}
}
export default VolumeEffect;
|
chore: Add typehints to private function
|
<?php
namespace PhpPact\Standalone\Installer\Service;
use PhpPact\Standalone\Installer\Model\Scripts;
class InstallerPosixPreinstalled implements InstallerInterface
{
/**
* {@inheritdoc}
*/
public function isEligible(): bool
{
return in_array(PHP_OS, ['Linux', 'Darwin']) && !empty($this->getBinaryPath('pact-provider-verifier'));
}
/**
* {@inheritdoc}
*/
public function install(string $destinationDir): Scripts
{
$scripts = new Scripts(
'pact-mock-service',
'pact-stub-service',
'pact-provider-verifier',
'pact-message',
'pact-broker'
);
return $scripts;
}
private function getBinaryPath(string $binary): string
{
return trim(shell_exec('command -v ' . escapeshellarg($binary)));
}
}
|
<?php
namespace PhpPact\Standalone\Installer\Service;
use PhpPact\Standalone\Installer\Model\Scripts;
class InstallerPosixPreinstalled implements InstallerInterface
{
/**
* {@inheritdoc}
*/
public function isEligible(): bool
{
return in_array(PHP_OS, ['Linux', 'Darwin']) && !empty($this->getBinaryPath('pact-provider-verifier'));
}
/**
* {@inheritdoc}
*/
public function install(string $destinationDir): Scripts
{
$scripts = new Scripts(
'pact-mock-service',
'pact-stub-service',
'pact-provider-verifier',
'pact-message',
'pact-broker'
);
return $scripts;
}
private function getBinaryPath($binary)
{
return trim(shell_exec('command -v ' . escapeshellarg($binary)));
}
}
|
Fix JSCS in default blueprint
|
/* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return this.addBowerPackagesToProject([
{ name: 'localforage', target: '1.3.3' }
]).then(function() {
return _this.addAddonsToProject({
packages: [
'https://github.com/Flexberry/ember-localforage-adapter.git',
{ name: 'ember-browserify', target: '1.1.9' }
]
});
}).then(function () {
return _this.addPackagesToProject([
{ name: 'dexie', target: '1.3.6' }
]);
});
},
normalizeEntityName: function() {}
};
|
/* globals module */
module.exports = {
afterInstall: function() {
var _self = this;
return this.addBowerPackagesToProject([
{ name: 'localforage', target: '1.3.3' }
]).then(function() {
return _self.addAddonsToProject({
packages: [
'https://github.com/Flexberry/ember-localforage-adapter.git',
{ name: 'ember-browserify', target: '1.1.9' }
]
});
}).then(function () {
return _self.addPackagesToProject([
{ name: 'dexie', target: '1.3.6' }
]);
});
},
normalizeEntityName: function() {}
};
|
Move `django-brightcove` dependency into `brightcove` optional extra.
|
import setuptools
from icekit import __version__
setuptools.setup(
name='icekit',
version=__version__,
packages=setuptools.find_packages(),
install_requires=[
'coverage',
'django-bootstrap3',
'django-dynamic-fixture',
'django-fluent-pages[flatpage,fluentpage,redirectnode]',
'django-fluent-contents',
'django-nose',
'django-webtest',
'mkdocs',
'nose-progressive',
'Pillow',
'tox',
'WebTest',
],
extras_require={
'brightcove': ['django-brightcove'],
'search': ['django-haystack', ]
}
)
|
import setuptools
from icekit import __version__
setuptools.setup(
name='icekit',
version=__version__,
packages=setuptools.find_packages(),
install_requires=[
'coverage',
'django-bootstrap3',
'django-brightcove',
'django-dynamic-fixture',
'django-fluent-pages[flatpage,fluentpage,redirectnode]',
'django-fluent-contents',
'django-nose',
'django-webtest',
'mkdocs',
'nose-progressive',
'Pillow',
'tox',
'WebTest',
],
extras_require={
'search': ['django-haystack', ]
}
)
|
Make tests run with sqlite by default
|
from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
os.environ["INBOXEN_ADMIN_ACCESS"] = '1'
from inboxen.settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB', "sqlite")
postgres_user = os.environ.get('PG_USER', 'postgres')
SECRET_KEY = "This is a test, you don't need secrets"
ENABLE_REGISTRATION = True
SECURE_SSL_REDIRECT = False
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif db == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'inboxen',
'USER': postgres_user,
},
}
else:
raise NotImplementedError("Please check tests/settings.py for valid DB values")
|
from __future__ import absolute_import
import os
os.environ['INBOX_TESTING'] = '1'
os.environ["INBOXEN_ADMIN_ACCESS"] = '1'
from inboxen.settings import *
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
db = os.environ.get('DB')
postgres_user = os.environ.get('PG_USER', 'postgres')
SECRET_KEY = "This is a test, you don't need secrets"
ENABLE_REGISTRATION = True
SECURE_SSL_REDIRECT = False
if db == "sqlite":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
elif db == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'inboxen',
'USER': postgres_user,
},
}
else:
raise NotImplementedError("Please check tests/settings.py for valid DB values")
|
Prepend en_ to country code, this is a HACK, need to do a proper looked of ISO-3166-1 to locales
|
<?php
class LocaleProviderClientGeoIP extends AbstractLocaleProvider {
// path and filename of geoip data file relative to Director::baseFolder.
private static $geoip_data_file = '';
/**
* Return the locale as found by GeoIP lookup of clients REMOTE_ADDR
*
* - null (missing data value) can't find remote address in lookup file
* - false (no available data) no file or no remote address provided in request so can't do lookup
* - locale string in e.g. en_US format.
*
* @return string|null|boolean
*/
public static function get_locale()
{
if ($filePathAndName = self::config()->geoip_data_file) {
if ($gi = geoip_open(Director::baseFolder() . $filePathAndName, GEOIP_STANDARD)) {
$countryCode = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
return $countryCode ? "en_$countryCode" : null;
}
}
return false;
}
}
|
<?php
class LocaleProviderClientGeoIP extends AbstractLocaleProvider {
// path and filename of geoip data file relative to Director::baseFolder.
private static $geoip_data_file = '';
/**
* Return the locale as found by GeoIP lookup of clients REMOTE_ADDR
*
* - null (missing data value) can't find remote address in lookup file
* - false (no available data) no file or no remote address provided in request so can't do lookup
* - locale string in e.g. en_US format.
*
* @return string|null|boolean
*/
public static function get_locale()
{
if ($filePathAndName = self::config()->geoip_data_file) {
$gi = geoip_open(Director::baseFolder() . $filePathAndName, GEOIP_STANDARD);
$countryCode = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
return $countryCode ?: null;
}
return false;
}
}
|
Use a list for classifiers
|
from setuptools import find_packages, setup
version = '0.1.0'
setup(
name='django-user-deletion',
packages=find_packages(),
include_package_data=True,
version=version,
license='BSD',
description='Management commands to notify and delete inactive django users',
classifiers=[
'Development Status :: 1 - Planning',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
author='Incuna Ltd',
author_email='admin@incuna.com',
url='https://github.com/incuna/django-user-deletion',
)
|
from setuptools import find_packages, setup
version = '0.1.0'
setup(
name='django-user-deletion',
packages=find_packages(),
include_package_data=True,
version=version,
license='BSD',
description='Management commands to notify and delete inactive django users',
classifiers=(
'Development Status :: 1 - Planning',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
),
author='Incuna Ltd',
author_email='admin@incuna.com',
url='https://github.com/incuna/django-user-deletion',
)
|
Add `lodash.memoize` to benchmark suite
|
'use strict'
let Benchmark = require('benchmark')
let memoize1 = require('./1')
let underscore = require('underscore').memoize
let lodash = require('lodash').memoize
//
// Fibonacci suite
//
let fibonacci = (n) => {
return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2)
}
let memoized1 = memoize1(fibonacci)
let memoizedUnderscore = underscore(fibonacci)
let memoizedLodash = lodash(fibonacci)
let suiteFibonnaci = new Benchmark.Suite()
suiteFibonnaci
.add('vanilla', () => {
fibonacci(15)
})
.add('algorithm1', () => {
memoized1(15)
})
.add('underscore', () => {
memoizedUnderscore(15)
})
.add('lodash', () => {
memoizedLodash(15)
})
.on('cycle', (event) => {
console.log(String(event.target))
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'))
})
.run({'async': true})
|
'use strict'
let Benchmark = require('benchmark')
let memoize1 = require('./1')
let underscore = require('underscore').memoize
//
// Fibonacci suite
//
let fibonacci = (n) => {
return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2)
}
let memoized1 = memoize1(fibonacci)
let memoizedUnderscore = underscore(fibonacci)
let suiteFibonnaci = new Benchmark.Suite()
suiteFibonnaci
.add('vanilla', () => {
fibonacci(15)
})
.add('algorithm1', () => {
memoized1(15)
})
.add('underscore', () => {
memoizedUnderscore(15)
})
.on('cycle', (event) => {
console.log(String(event.target))
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'))
})
.run({'async': true})
|
Add `-rc.n` suffix to `rate-limit`.
|
Package.describe({
name: 'rate-limit',
version: '1.0.8-rc.4',
// Brief, one-line summary of the package.
summary: 'An algorithm for rate limiting anything',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.use('underscore');
api.use('random');
api.addFiles('rate-limit.js');
api.export("RateLimiter");
});
Package.onTest(function(api) {
api.use('test-helpers', ['client', 'server']);
api.use('underscore');
api.use('random');
api.use('ddp-rate-limiter');
api.use('tinytest');
api.use('rate-limit');
api.use('ddp-common');
api.addFiles('rate-limit-tests.js');
});
|
Package.describe({
name: 'rate-limit',
version: '1.0.8',
// Brief, one-line summary of the package.
summary: 'An algorithm for rate limiting anything',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.use('underscore');
api.use('random');
api.addFiles('rate-limit.js');
api.export("RateLimiter");
});
Package.onTest(function(api) {
api.use('test-helpers', ['client', 'server']);
api.use('underscore');
api.use('random');
api.use('ddp-rate-limiter');
api.use('tinytest');
api.use('rate-limit');
api.use('ddp-common');
api.addFiles('rate-limit-tests.js');
});
|
Fix db engine name for SQLAlchemy 1.4
|
import os
#: Database backend
SECRET_KEY = 'testkey'
SQLALCHEMY_DATABASE_URI = 'postgresql:///boxoffice_testing'
SERVER_NAME = 'boxoffice.travis.dev:6500'
BASE_URL = 'http://' + SERVER_NAME
RAZORPAY_KEY_ID = os.environ.get('RAZORPAY_KEY_ID')
RAZORPAY_KEY_SECRET = os.environ.get('RAZORPAY_KEY_SECRET')
ALLOWED_ORIGINS = [BASE_URL, 'http://boxoffice.travis.dev:6500/', 'http://shreyas-wlan.dev:8000']
LASTUSER_SERVER = 'https://auth.hasgeek.com'
LASTUSER_CLIENT_ID = ''
LASTUSER_CLIENT_SECRET = ''
TIMEZONE = 'Asia/Calcutta'
CACHE_TYPE = 'redis'
ASSET_MANIFEST_PATH = "static/build/manifest.json"
# no trailing slash
ASSET_BASE_PATH = '/static/build'
WTF_CSRF_ENABLED = False
|
import os
#: Database backend
SECRET_KEY = 'testkey'
SQLALCHEMY_DATABASE_URI = 'postgres:///boxoffice_testing'
SERVER_NAME = 'boxoffice.travis.dev:6500'
BASE_URL = 'http://' + SERVER_NAME
RAZORPAY_KEY_ID = os.environ.get('RAZORPAY_KEY_ID')
RAZORPAY_KEY_SECRET = os.environ.get('RAZORPAY_KEY_SECRET')
ALLOWED_ORIGINS = [BASE_URL, 'http://boxoffice.travis.dev:6500/', 'http://shreyas-wlan.dev:8000']
LASTUSER_SERVER = 'https://auth.hasgeek.com'
LASTUSER_CLIENT_ID = ''
LASTUSER_CLIENT_SECRET = ''
TIMEZONE = 'Asia/Calcutta'
CACHE_TYPE = 'redis'
ASSET_MANIFEST_PATH = "static/build/manifest.json"
# no trailing slash
ASSET_BASE_PATH = '/static/build'
WTF_CSRF_ENABLED = False
|
Update how mockMvc is created
|
package uk.ac.ebi.spot.goci.curation.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by emma on 14/10/2015.
*
* @author emma
* <p>
* Unit test for HomeController based on http://spring.io/guides/gs/spring-boot/
*/
@RunWith(MockitoJUnitRunner.class)
public class HomeControllerTest {
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
HomeController homeController = new HomeController();
mockMvc = MockMvcBuilders.standaloneSetup(homeController).build();
}
@Test
public void getHome() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/login"));
}
}
|
package uk.ac.ebi.spot.goci.curation.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Created by emma on 14/10/2015.
*
* @author emma
* <p>
* Unit test for HomeController based on http://spring.io/guides/gs/spring-boot/
*/
@RunWith(MockitoJUnitRunner.class)
public class HomeControllerTest {
private HomeController homeController;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
homeController = new HomeController();
mockMvc = MockMvcBuilders.standaloneSetup(homeController).build();
}
@Test
public void getHome() throws Exception {
mockMvc.perform(get("/").accept(MediaType.TEXT_HTML_VALUE))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/login"));
}
}
|
Fix typo & log chalk-version on initialization
|
import _ from 'lodash'
import l from 'chalk-log'
import cocos from '../cocos'
import leaves from '../leaves'
import pkg from '../../package.json'
export default class Palm {
constructor (params) {
this.cocos = cocos
this.leaf = params.talk
if (this.leaf === 'telegram') {
this.telegram = new leaves.Telegram(params.telegram)
} else if (this.leaf === 'cli') {
this.cli = new leaves.Cli()
}
}
listen () {
l.note(`Initialized palm v${pkg.version}`)
this[this.leaf].init()
this[this.leaf].on('message', text => {
this.respond({ text })
})
}
respond ({ text }) {
const getCoco = this.initCoco(text)
if (getCoco.ok) {
this[this.leaf].send({ text: getCoco.coco.exec(text) })
} else {
this[this.leaf].send({ text: this.cocos.idk.exec() })
}
}
initCoco (text) {
const a = { ok: false }
for (const key in this.cocos) {
_.forEach(this.cocos[key].keywords, keyword => {
if (text.match(new RegExp(keyword, 'i'))) {
a.ok = true
a.coco = this.cocos[key]
}
})
}
return a
}
}
|
import _ from 'lodash'
import cocos from '../cocos'
import leaves from '../leaves'
export class Palm {
constructor (params) {
this.cocos = cocos
this.leaf = params.talk
if (this.leaf === 'talegram') {
this.telegram = new leaves.Telegram(params.telegram)
} else if (this.leaf === 'cli') {
this.cli = new leaves.Cli()
}
}
listen () {
this[this.leaf].init()
this[this.leaf].on('message', text => {
this.respond({ text })
})
}
respond ({ text }) {
const getCoco = this.initCoco(text)
if (getCoco.ok) {
this[this.leaf].send({ text: getCoco.coco.exec(text) })
} else {
this[this.leaf].send({ text: this.cocos.idk.exec() })
}
}
initCoco (text) {
const a = { ok: false }
for (const key in this.cocos) {
_.forEach(this.cocos[key].keywords, keyword => {
if (text.match(new RegExp(keyword, 'i'))) {
a.ok = true
a.coco = this.cocos[key]
}
})
}
return a
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.