text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add requirements to package definition. | import os
import setuptools
requirements = [
"fnmatch",
"future",
"six",
"numpy",
"scipy",
"lasagne",
"theano",
]
def readme():
base_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base_dir, 'README.md')) as f:
return f.read()
def setup():
setuptools.setup(
name="nn_patterns",
version="0.1",
description=("Implementation of PatternNet and PatternLRP:"
" https://arxiv.org/abs/1705.05598"),
long_description=readme(),
classifiers=[
"License :: OSI Approved :: ",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
url="https://github.com/pikinder/nn-patterns",
author="Pieter-Jan Kindermans, Maxmilian Alber",
author_email="[email protected]",
license="MIT",
packages=setuptools.find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
)
pass
if __name__ == "__main__":
setup()
| import os
import setuptools
requirements = [
"numpy",
"scipy",
"lasagne",
]
def readme():
base_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base_dir, 'README.md')) as f:
return f.read()
def setup():
setuptools.setup(
name="nn_patterns",
version="0.1",
description=("Implementation of PatternNet and PatternLRP:"
" https://arxiv.org/abs/1705.05598"),
long_description=readme(),
classifiers=[
"License :: OSI Approved :: ",
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Science/Research",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
url="https://github.com/pikinder/nn-patterns",
author="Pieter-Jan Kindermans, Maxmilian Alber",
author_email="[email protected]",
license="MIT",
packages=setuptools.find_packages(),
install_requires=requirements,
include_package_data=True,
zip_safe=False,
)
pass
if __name__ == "__main__":
setup()
|
Store `Y-m-d H:i:s` into a readable constant name | <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2017-2019, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Class
*/
namespace PH7;
use stdClass;
class VisitorCore
{
const DATETIME_FORMAT = 'Y-m-d H:i:s';
/**
* @return void
*/
public function updateViews()
{
$oVisitorModel = new VisitorCoreModel(
$this->iProfileId,
$this->iVisitorId,
$this->dateTime->get()->dateTime(self::DATETIME_FORMAT)
);
if (!$oVisitorModel->already()) {
// Add a new visit
$oVisitorModel->set();
} else {
// Update the date of last visit
$oVisitorModel->update();
}
unset($oVisitorModel);
}
public function isViewUpdateEligible(
stdClass $oPrivacyViewsUser,
stdClass $oPrivacyViewsVisitor,
ProfileBaseController $oProfile
)
{
return $oPrivacyViewsUser->userSaveViews === PrivacyCore::YES &&
$oPrivacyViewsVisitor->userSaveViews === PrivacyCore::YES &&
!$oProfile->isOwnProfile();
}
}
| <?php
/**
* @author Pierre-Henry Soria <[email protected]>
* @copyright (c) 2017-2019, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Core / Class
*/
namespace PH7;
use stdClass;
class VisitorCore
{
/**
* @return void
*/
public function updateViews()
{
$oVisitorModel = new VisitorCoreModel(
$this->iProfileId,
$this->iVisitorId,
$this->dateTime->get()->dateTime('Y-m-d H:i:s')
);
if (!$oVisitorModel->already()) {
// Add a new visit
$oVisitorModel->set();
} else {
// Update the date of last visit
$oVisitorModel->update();
}
unset($oVisitorModel);
}
public function isViewUpdateEligible(
stdClass $oPrivacyViewsUser,
stdClass $oPrivacyViewsVisitor,
ProfileBaseController $oProfile
)
{
return $oPrivacyViewsUser->userSaveViews === PrivacyCore::YES &&
$oPrivacyViewsVisitor->userSaveViews === PrivacyCore::YES &&
!$oProfile->isOwnProfile();
}
}
|
Use new progressba interface, fixed console error, changed severity to notice, fixed error which caused empty urls to get fetched | <?php namespace Crawler\Flickr;
use Crawler\Crawler;
use Console\Console;
use Console\Progressbar;
class Flickr extends Crawler
{
public function getOriginalImageUrls($images)
{
$original_images = [];
Console::info("Getting original image urls for " . count($images) . " flickr links...");
$progress = new Progressbar(count($images));
foreach ($images as $url) {
$original_url = $this->getOriginalImageUrl($url);
if ($original_url) {
$original_images[] = $original_url;
}
$progress->increase();
}
return array_unique($original_images);
}
public function getOriginalImageUrl($url)
{
$url = $this->getSizesUrl($url);
$contents = $this->fetchUrl($url, false, true);
$original_url = $this->findOriginalImage($contents);
if ($original_url === false) {
Console::notice('No flickr image found for ' . $url);
}
return $original_url;
}
private function getSizesUrl($url)
{
return trim($url, '/') . '/sizes/o';
}
private function findOriginalImage($content)
{
preg_match('#<img src="(http://[^\.]*.staticflickr.[^"]*)">#', $content, $matches);
if (!isset($matches[1])) {
return false;
}
return $matches[1];
}
} | <?php namespace Crawler\Flickr;
use Crawler\Crawler;
use Console\Console;
use Console\Progressbar;
class Flickr extends Crawler
{
public function getOriginalImageUrls($images)
{
$original_images = [];
Console::info("Getting original image urls for " . count($images) . " flickr links...");
$progress = new Progressbar();
$counter = 0;
foreach ($images as $url) {
$percent = (++$counter / count($images)) * 100;
$original_images[] = $this->getOriginalImageUrl($url);
$progress->setProgress($percent);
}
return array_unique($original_images);
}
public function getOriginalImageUrl($url)
{
$url = $this->getSizesUrl($url);
$contents = $this->fetchUrl($url);
$url = $this->findOriginalImage($contents);
if ($url === false) {
Console::warning('No flickr image found on url ' . $url);
}
return $url;
}
private function getSizesUrl($url)
{
return trim($url, '/') . '/sizes/o';
}
private function findOriginalImage($content)
{
preg_match('#<img src="(http://[^\.]*.staticflickr.[^"]*)">#', $content, $matches);
if (!isset($matches[1])) {
return false;
}
return $matches[1];
}
} |
BAP-1194: Implement wrapper for Translator.get() call
- CR-changes | (function(Translator, _, Oro) {
var dict = {},
add = Translator.add,
get = Translator.get;
/**
* Adds a translation to Translator object and stores
* translation id in protected dictionary
* @param {string} id
*/
Translator.add = function(id) {
dict[id] = 1;
add.apply(Translator, arguments);
};
/**
* Fetches translation by its id,
* but before checks if the id was registered in dictionary
* @param {string} id
* @returns {string}
*/
Translator.get = function(id) {
checkTranslation(id);
return get.apply(Translator, arguments);
};
/**
* Checks if translation for passed id exist, if it's Oro.debug mode
* and there's no translation - output error message in console
* @param {string} id
*/
function checkTranslation(id) {
if (!Oro.debug) {
return;
}
var domains = Translator.defaultDomains,
checker = function (domain){
return dict.hasOwnProperty(domain ? domain + ':' + id : id);
};
domains = _.union([undefined], _.isArray(domains) ? domains : [domains]);
if (!_.some(domains, checker)) {
console.error('Untranslated: %s', id);
}
}
_.mixin({
/**
* Shortcut for Translator.get() method call,
* Due to it's underscore mixin, it can be used inside templates
* @returns {string}
*/
__: _.bind(Translator.get, Translator)
});
}) (Translator, _, Oro);
| (function(Translator, _, Oro) {
var dict = {},
add = Translator.add;
/**
* Store all translation ids which were added to Translator
* @param id
*/
Translator.add = function(id) {
dict[id] = 1;
add.apply(Translator, arguments);
};
/**
* Checks if translation for passed id exist, if it's Oro.debug mode
* and there's no translation - output error message in console
* @param id
*/
function checkTranslation(id) {
if (!Oro.debug) {
return;
}
var domains = Translator.defaultDomains,
checker = function (domain){
return dict.hasOwnProperty(domain ? domain + ':' + id : id);
};
domains = _.union([undefined], _.isArray(domains) ? domains : [domains]);
if (!_.some(domains, checker)) {
console.error('Translation "%s" does not exist!', id);
}
}
_.mixin({
/**
* Shortcut for Translator.get() method call,
* Due to it's underscore mixin, it can be used inside templates
* @param id
* @returns {string}
*/
__: function(id) {
checkTranslation(id);
return Translator.get.apply(Translator, arguments);
}
});
}) (Translator, _, Oro);
|
Configure JS linter warnings for Ember deprecations | 'use strict';
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true
}
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
"no-control-regex": "off",
"no-console": ["error", { allow: ["warn", "debug", "error"] }],
"ember/no-observers": "warn",
"ember/no-jquery": "error",
"ember/no-string-prototype-extensions": "warn",
"ember/no-controller-access-in-routes": "warn",
"ember/no-classic-classes": "warn",
"ember/no-computed-properties-in-native-classes": "warn",
"ember/require-tagless-components": "warn",
"ember/no-assignment-of-untracked-properties-used-in-tracking-contexts": "warn",
"ember/no-side-effects": "warn"
},
overrides: [
// node files
{
files: [
'.eslintrc.js',
'.template-lintrc.js',
'ember-cli-build.js',
'testem.js',
'config/**/*.js',
'lib/*/index.js',
'server/**/*.js'
],
parserOptions: {
sourceType: 'script'
},
env: {
browser: false,
node: true
},
rules: {
// this can be removed once the following is fixed
// https://github.com/mysticatea/eslint-plugin-node/issues/77
'node/no-unpublished-require': 'off'
}
}
]
};
| 'use strict';
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true
}
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {
"no-control-regex": "off",
"no-console": ["error", { allow: ["warn", "debug", "error"] }],
"ember/no-observers": 1,
'ember/no-jquery': 'error'
},
overrides: [
// node files
{
files: [
'.eslintrc.js',
'.template-lintrc.js',
'ember-cli-build.js',
'testem.js',
'config/**/*.js',
'lib/*/index.js',
'server/**/*.js'
],
parserOptions: {
sourceType: 'script'
},
env: {
browser: false,
node: true
},
rules: {
// this can be removed once the following is fixed
// https://github.com/mysticatea/eslint-plugin-node/issues/77
'node/no-unpublished-require': 'off'
}
}
]
};
|
Fix link un approbation alert email | 'use strict';
const util = require('util');
const Mail = require('../mail');
const getViewUrl = function(request) {
if (request.absence.distribution.length > 0) {
return '/admin/requests/absences/'+request._id;
}
if (request.workperiod_recover.length > 0) {
return '/admin/requests/workperiod-recovers/'+request._id;
}
if (request.time_saving_deposit.length > 0) {
return '/admin/requests/time-saving-deposits/'+request._id;
}
};
/**
* Notification for admin about the approval list
*
* @param {Object} app Express
* @param {Request} request
* @param {User} user
*
* @return {Promise}
*/
exports = module.exports = function getMail(app, request, user) {
const gt = app.utility.gettext;
let mail = new Mail(app);
mail.setSubject(util.format(
gt.gettext('The approval status of the %s request has not been modified in %d days'),
request.getDispType(),
app.config.company.approb_alert
));
let requestLink = app.config.url +'/#'+getViewUrl(request);
mail.addTo(user);
let body = {
title: gt.gettext('Pending request'),
intro: util.format(
gt.gettext('%s is waiting for a response on the %s'),
request.user.name,
request.getDispType()
),
action: {
instructions: gt.gettext('Please, check the request status'),
button: {
text: gt.gettext('View request'),
link: requestLink
}
},
signature: gt.gettext('Yours truly')
};
mail.setMailgenData({
body: body
});
return Promise.resolve(mail);
};
| 'use strict';
const util = require('util');
const Mail = require('../mail');
/**
* Notification for admin about the approval list
*
* @param {Object} app Express
* @param {Request} request
* @param {User} user
*
* @return {Promise}
*/
exports = module.exports = function getMail(app, request, user) {
const gt = app.utility.gettext;
let mail = new Mail(app);
mail.setSubject(util.format(
gt.gettext('The approval status of the %s request has not been modified in %d days'),
request.getDispType(),
app.config.company.approb_alert
));
let requestLink = app.config.url +'/#/admin/requests/'+ request._id;
mail.addTo(user);
let body = {
title: gt.gettext('Pending request'),
intro: util.format(
gt.gettext('%s is waiting for a response on the %s'),
request.user.name,
request.getDispType()
),
action: {
instructions: gt.gettext('Please, check the request status'),
button: {
text: gt.gettext('View request'),
link: requestLink
}
},
signature: gt.gettext('Yours truly')
};
mail.setMailgenData({
body: body
});
return Promise.resolve(mail);
};
|
Throw a 404 header on user w/o post crud role | <?php
$userInfo = get_userdata( get_query_var('author'));
$isAuthor = true;
if (
!in_array('contributor', $userInfo -> roles) &&
!in_array('administrator', $userInfo -> roles) &&
!in_array('author', $userInfo -> roles) &&
!in_array('editor', $userInfo -> roles)
) {
$isAuthor = false;
wp_redirect(get_bloginfo('url').'/404', 404);
}
?>
<?php get_header(); ?>
<div class="container">
<div class="row">
<div class="col-sm-8">
<header class="page-header">
<?php if ($isAuthor === true): ?>
<h1>
<?php echo sprintf(__('Author %s', 'b4st'), '<strong>' . get_the_author_meta('user_nicename', $userInfo -> data -> ID) . '</strong>'); ?>
</h1>
<?php endif; ?>
</header><!-- .page-header -->
<?php if(have_posts()): ?>
<?php get_template_part('loops/content', get_post_format()); ?>
<?php else: ?>
<?php get_template_part('loops/content', 'none'); ?>
<?php endif; ?>
</div>
<div class="col-sm-4" id="sidebar">
<?php get_sidebar(); ?>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php get_footer(); ?>
| <?php
$userInfo = get_userdata( get_query_var('author'));
$isAuthor = true;
if (
!in_array('contributor', $userInfo -> roles) &&
!in_array('administrator', $userInfo -> roles) &&
!in_array('author', $userInfo -> roles) &&
!in_array('editor', $userInfo -> roles)
) {
$isAuthor = false;
}
?>
<?php get_header(); ?>
<div class="container">
<div class="row">
<div class="col-sm-8">
<header class="page-header">
<?php if ($isAuthor === true): ?>
<h1>
<?php echo sprintf(__('Author %s', 'b4st'), '<strong>' . get_the_author_meta('user_nicename', $userInfo -> data -> ID) . '</strong>'); ?>
</h1>
<?php endif; ?>
</header><!-- .page-header -->
<?php if(have_posts()): ?>
<?php get_template_part('loops/content', get_post_format()); ?>
<?php else: ?>
<?php get_template_part('loops/content', 'none'); ?>
<?php endif; ?>
</div>
<div class="col-sm-4" id="sidebar">
<?php get_sidebar(); ?>
</div>
</div><!-- /.row -->
</div><!-- /.container -->
<?php get_footer(); ?>
|
Add debug method to Retrofit process service | package util;
import com.google.gson.JsonObject;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;
/**
* Retrofit interfaces wrapping Filestack API.
*/
public class FilestackService {
public interface Api {
String URL = "https://www.filestackapi.com/api/file/";
@POST("{handle}")
Call<ResponseBody> overwrite(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature, @Body RequestBody body);
@DELETE("{handle}")
Call<ResponseBody> delete(@Path("handle") String handle, @Query("key") String key,
@Query("policy") String policy, @Query("signature") String signature);
}
public interface Cdn {
String URL = "https://cdn.filestackcontent.com/";
@GET("{handle}")
@Streaming
Call<ResponseBody> get(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature);
}
public interface Process {
String URL = "https://process.filestackapi.com/";
@Streaming
@GET("{tasks}/{handle}")
Call<ResponseBody> get(@Path("tasks") String tasks, @Path("handle") String handle);
@GET("debug/{tasks}/{handle}")
Call<JsonObject> debug(@Path("tasks") String tasks, @Path("handle") String handle);
}
}
| package util;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;
/**
* Retrofit interfaces wrapping Filestack API.
*/
public class FilestackService {
public interface Api {
String URL = "https://www.filestackapi.com/api/file/";
@POST("{handle}")
Call<ResponseBody> overwrite(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature, @Body RequestBody body);
@DELETE("{handle}")
Call<ResponseBody> delete(@Path("handle") String handle, @Query("key") String key,
@Query("policy") String policy, @Query("signature") String signature);
}
public interface Cdn {
String URL = "https://cdn.filestackcontent.com/";
@GET("{handle}")
@Streaming
Call<ResponseBody> get(@Path("handle") String handle, @Query("policy") String policy,
@Query("signature") String signature);
}
public interface Process {
String URL = "https://process.filestackapi.com/";
@Streaming
@GET("{tasks}/{handle}")
Call<ResponseBody> get(@Path("tasks") String tasks, @Path("handle") String handle);
}
}
|
fix(kakao): Change field name from 'nickname' to 'username' | from allauth.account.models import EmailAddress
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class KakaoAccount(ProviderAccount):
@property
def properties(self):
return self.account.extra_data.get('properties')
def get_avatar_url(self):
return self.properties.get('profile_image')
def to_str(self):
dflt = super(KakaoAccount, self).to_str()
return self.properties.get('nickname', dflt)
class KakaoProvider(OAuth2Provider):
id = 'kakao'
name = 'Kakao'
account_class = KakaoAccount
def extract_uid(self, data):
return str(data['id'])
def extract_common_fields(self, data):
email = data['kakao_account'].get('email')
nickname = data['properties'].get('nickname')
return dict(email=email, username=nickname)
def extract_email_addresses(self, data):
ret = []
data = data['kakao_account']
email = data.get('email')
if email:
verified = data.get('is_email_verified')
# data['is_email_verified'] imply the email address is
# verified
ret.append(EmailAddress(email=email,
verified=verified,
primary=True))
return ret
provider_classes = [KakaoProvider]
| from allauth.account.models import EmailAddress
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class KakaoAccount(ProviderAccount):
@property
def properties(self):
return self.account.extra_data.get('properties')
def get_avatar_url(self):
return self.properties.get('profile_image')
def to_str(self):
dflt = super(KakaoAccount, self).to_str()
return self.properties.get('nickname', dflt)
class KakaoProvider(OAuth2Provider):
id = 'kakao'
name = 'Kakao'
account_class = KakaoAccount
def extract_uid(self, data):
return str(data['id'])
def extract_common_fields(self, data):
email = data['kakao_account'].get('email')
nickname = data['properties'].get('nickname')
return dict(email=email, nickname=nickname)
def extract_email_addresses(self, data):
ret = []
data = data['kakao_account']
email = data.get('email')
if email:
verified = data.get('is_email_verified')
# data['is_email_verified'] imply the email address is
# verified
ret.append(EmailAddress(email=email,
verified=verified,
primary=True))
return ret
provider_classes = [KakaoProvider]
|
Use the UK locale for parsing | package uk.co.alynn.games.suchrobot;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Scanner;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
public abstract class NodeSetReader {
public static NodeSet readNodeSet(String file) throws IOException {
FileHandle handle = Gdx.files.external(file);
if (handle.exists()) {
System.err.println("USING OVERLOADED NODES");
} else {
handle = Gdx.files.internal(file);
}
InputStream rdr = handle.read();
NodeSet nodes = new NodeSet();
Scanner scan = new Scanner(rdr);
scan.useLocale(Locale.UK);
while (scan.hasNext()) {
String command = scan.next();
if (command.equals("node")) {
String type = scan.next();
String name = scan.next();
int x = scan.nextInt();
int y = scan.nextInt();
int reserves = scan.nextInt();
nodes.addNode(type, name, x, y, reserves);
} else if (command.equals("conn")) {
String source = scan.next();
String dest = scan.next();
nodes.addConnection(source, dest);
}
}
scan.close();
nodes.compile();
return nodes;
}
}
| package uk.co.alynn.games.suchrobot;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
public abstract class NodeSetReader {
public static NodeSet readNodeSet(String file) throws IOException {
FileHandle handle = Gdx.files.external(file);
if (handle.exists()) {
System.err.println("USING OVERLOADED NODES");
} else {
handle = Gdx.files.internal(file);
}
InputStream rdr = handle.read();
NodeSet nodes = new NodeSet();
Scanner scan = new Scanner(rdr);
while (scan.hasNext()) {
String command = scan.next();
if (command.equals("node")) {
String type = scan.next();
String name = scan.next();
int x = scan.nextInt();
int y = scan.nextInt();
int reserves = scan.nextInt();
nodes.addNode(type, name, x, y, reserves);
} else if (command.equals("conn")) {
String source = scan.next();
String dest = scan.next();
nodes.addConnection(source, dest);
}
}
scan.close();
nodes.compile();
return nodes;
}
}
|
Add condition to webMvcMetricsFilter bean
Co-authored-by: Marco Geweke <[email protected]> | package de.otto.edison.metricsconfiguration;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import javax.servlet.DispatcherType;
/* TODO: Remove this when Spring Boot 2.7.1 is there */
@Component
public class WebMvcMetricsFilterWorkaroundForBugInSpringBoot2_7_0 {
@Bean
@ConditionalOnMissingBean
public FilterRegistrationBean<WebMvcMetricsFilter> webMvcMetricsFilter(MetricsProperties properties,
MeterRegistry registry, WebMvcTagsProvider tagsProvider) {
MetricsProperties.Web.Server.ServerRequest request = properties.getWeb().getServer().getRequest();
WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, request.getMetricName(),
request.getAutotime());
FilterRegistrationBean<WebMvcMetricsFilter> registration = new FilterRegistrationBean<>(filter);
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
return registration;
}
}
| package de.otto.edison.metricsconfiguration;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter;
import org.springframework.boot.actuate.metrics.web.servlet.WebMvcTagsProvider;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import javax.servlet.DispatcherType;
@Component
public class WebMvcMetricsFilterWorkaroundForBugInSpringBoot2_7_0 {
@Bean
public FilterRegistrationBean<WebMvcMetricsFilter> webMvcMetricsFilter(MetricsProperties properties,
MeterRegistry registry, WebMvcTagsProvider tagsProvider) {
MetricsProperties.Web.Server.ServerRequest request = properties.getWeb().getServer().getRequest();
WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, request.getMetricName(),
request.getAutotime());
FilterRegistrationBean<WebMvcMetricsFilter> registration = new FilterRegistrationBean<>(filter);
registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
return registration;
}
}
|
Rename image_pub to image_publisher; change docstring. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/Subscriber.
"""
def __init__(self):
self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
Image, self.image_callback,
queue_size=1)
self.image_publisher = rospy.Publisher("/output/slow_image_raw",
Image, queue_size=1)
rospy.logdebug("Subscribed to /ardrone/image_raw")
self.count = 0
def frame_callback(self, frame):
"""
Callback function of subscribed topic.
"""
# Publish every fifteenth frame
if not self.count % 15:
self.image_publisher.publish(frame)
self.count += 1
def main():
"""Initialize ROS node."""
rospy.init_node("framerate_reducer", anonymous=True)
ImageFeature()
rospy.loginfo("Reducing framerate")
rospy.spin()
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (C) 2015 Jean Nassar
# Released under BSD version 4
"""
Reduce /ardrone/image_raw framerate from 30 Hz to 2 Hz.
"""
import rospy
from sensor_msgs.msg import Image
class ImageFeature(object):
"""
A ROS image Publisher/Subscriber.
"""
def __init__(self):
self.image_subscriber = rospy.Subscriber("/ardrone/image_raw",
Image, self.image_callback,
queue_size=1)
self.image_pub = rospy.Publisher("/output/slow_image_raw",
Image, queue_size=1)
rospy.logdebug("Subscribed to /ardrone/image_raw")
self.count = 0
def frame_callback(self, frame):
"""
Callback function of subscribed topic.
"""
# Publish every fifteenth frame
if not self.count % 15:
self.image_pub.publish(frame)
self.count += 1
def main():
"""Initialize and cleanup ROS node."""
rospy.init_node("framerate_reducer", anonymous=True)
ImageFeature()
rospy.loginfo("Reducing framerate")
rospy.spin()
if __name__ == "__main__":
main()
|
Implement the interface specification in two easy lines (plus an import). | from functools import wraps
import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not accept * nor ** args.'.format(p))
i = -len(spec.defaults or ())
if i == 0:
appargs, closureargs = spec.args, []
else:
appargs, closureargs = spec.args[:i], spec.args[i:]
precinfo.append( (appargs, closureargs, p) )
def decorate(f):
fspec = inspect.getargspec(f)
for (appargs, closureargs, p) in precinfo:
for apparg in appargs:
if apparg not in fspec.args:
raise PreconditionError(
('Precondition {!r} specifies non-default arg {!r}' +
' which is not one of the known application args:' +
' {!s}')
.format(p, apparg, ', '.join(fspec.args)))
for carg in closureargs:
if carg in fspec.args:
raise PreconditionError(
('Precondition {!r} specifies default arg {!r}' +
' which masks one of the known application args:' +
' {!s}')
.format(p, carg, ', '.join(fspec.args)))
@wraps(f)
def g(*a, **kw):
return f(*a, **kw)
g.nopre = f
return g
return decorate
| import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not accept * nor ** args.'.format(p))
i = -len(spec.defaults or ())
if i == 0:
appargs, closureargs = spec.args, []
else:
appargs, closureargs = spec.args[:i], spec.args[i:]
precinfo.append( (appargs, closureargs, p) )
def decorate(f):
fspec = inspect.getargspec(f)
for (appargs, closureargs, p) in precinfo:
for apparg in appargs:
if apparg not in fspec.args:
raise PreconditionError(
('Precondition {!r} specifies non-default arg {!r}' +
' which is not one of the known application args:' +
' {!s}')
.format(p, apparg, ', '.join(fspec.args)))
for carg in closureargs:
if carg in fspec.args:
raise PreconditionError(
('Precondition {!r} specifies default arg {!r}' +
' which masks one of the known application args:' +
' {!s}')
.format(p, carg, ', '.join(fspec.args)))
def g(*a, **kw):
return f(*a, **kw)
return g
return decorate
|
Add fallback for older PHPUnit versions | <?php /** @noinspection PhpUnhandledExceptionInspection */
namespace Amp\Redis;
use Amp\PHPUnit\AsyncTestCase;
class AuthTest extends AsyncTestCase
{
public static function setUpBeforeClass(): void
{
print \shell_exec('redis-server --daemonize yes --port 25325 --timeout 3 --pidfile /tmp/amp-redis.pid --requirepass secret');
\sleep(2);
}
public static function tearDownAfterClass(): void
{
$pid = @\file_get_contents('/tmp/amp-redis.pid');
@\unlink('/tmp/amp-redis.pid');
if (!empty($pid)) {
print \shell_exec("kill $pid");
\sleep(2);
}
}
public function testSuccess(): \Generator
{
$redis = new Redis(new RemoteExecutor(Config::fromUri('tcp://127.0.0.1:25325?password=secret')));
$this->assertSame('PONG', yield $redis->echo('PONG'));
yield $redis->quit();
}
public function testFailure(): \Generator
{
$redis = new Redis(new RemoteExecutor(Config::fromUri('tcp://127.0.0.1:25325?password=wrong')));
$this->expectException(QueryException::class);
if (\method_exists($this, 'expectExceptionMessageMatches')) {
$this->expectExceptionMessageMatches('(ERR invalid password|WRONGPASS invalid username-password pair)');
} else {
$this->expectExceptionMessageRegExp('(ERR invalid password|WRONGPASS invalid username-password pair)');
}
yield $redis->echo('PONG');
}
}
| <?php /** @noinspection PhpUnhandledExceptionInspection */
namespace Amp\Redis;
use Amp\PHPUnit\AsyncTestCase;
class AuthTest extends AsyncTestCase
{
public static function setUpBeforeClass(): void
{
print \shell_exec('redis-server --daemonize yes --port 25325 --timeout 3 --pidfile /tmp/amp-redis.pid --requirepass secret');
\sleep(2);
}
public static function tearDownAfterClass(): void
{
$pid = @\file_get_contents('/tmp/amp-redis.pid');
@\unlink('/tmp/amp-redis.pid');
if (!empty($pid)) {
print \shell_exec("kill $pid");
\sleep(2);
}
}
public function testSuccess(): \Generator
{
$redis = new Redis(new RemoteExecutor(Config::fromUri('tcp://127.0.0.1:25325?password=secret')));
$this->assertSame('PONG', yield $redis->echo('PONG'));
yield $redis->quit();
}
public function testFailure(): \Generator
{
$redis = new Redis(new RemoteExecutor(Config::fromUri('tcp://127.0.0.1:25325?password=wrong')));
$this->expectException(QueryException::class);
$this->expectExceptionMessageMatches('(ERR invalid password|WRONGPASS invalid username-password pair)');
yield $redis->echo('PONG');
}
}
|
Fix coding standard errors introduced in b18d30c | 'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const deviceService = require('./src/devices')
const PORT = process.env.PORT || 8080
const app = express()
const error = (code, res) => (e) =>
res.status(code).end(e.message)
app.use(bodyParser.json())
app.get(
'/devices',
(req, res) =>
deviceService.getDevices()
.then((devices) => res.json(devices))
.catch(error(500, res)) // Internal Server Error
)
app.get(
'/devices/:mac',
(req, res) =>
deviceService.getDevice(req.params.mac)
.then((device) => {
if (!device) {
return res.status(404) // Not Found
.end()
}
res.json(device)
})
.catch(error(500, res)) // Internal Server Error
)
app.put(
'/devices/:mac',
(req, res) =>
deviceService.getDevice(req.params.mac)
.then((device) => {
if (!req.body.profile) {
return res.status(400) // Bad Request
.end()
}
return deviceService.setDeviceProfile(device, req.body.profile)
})
.then(() =>
res.status(204).end() // No Content
)
.catch(error(400, res)) // Bad Request
)
app.listen(PORT)
| 'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const deviceService = require('./src/devices')
const PORT = process.env.PORT || 8080
const app = express()
const error = (code, res) => (e) =>
res.status(code).end(e.message)
app.use(bodyParser.json())
app.get(
'/devices',
(req, res) =>
deviceService.getDevices()
.then((devices) => res.json(devices))
.catch(error(500 /* Server Error */, res))
)
app.get(
'/devices/:mac',
(req, res) =>
deviceService.getDevice(req.params.mac)
.then((device) => {
if (!device) {
return res.status(404 /* Not Found */)
.end()
}
res.json(device)
})
.catch(error(500 /* Server Error */, res))
)
app.put(
'/devices/:mac',
(req, res) =>
deviceService.getDevice(req.params.mac)
.then((device) => {
if (!req.body.profile) {
return res.status(400 /* Bad Request */)
.end()
}
return deviceService.setDeviceProfile(device, req.body.profile)
})
.then(() =>
res.status(204 /* No Content */).end()
)
.catch(error(400 /* Bad Request */, res))
)
app.listen(PORT)
|
Fix property name in twig extension | <?php
namespace Knplabs\MenuBundle\Twig;
use Knplabs\MenuBundle\Templating\Helper\MenuHelper;
class MenuExtension extends \Twig_Extension
{
/**
* @var MenuHelper
*/
protected $helper;
/**
* @param MenuHelper
*/
public function __construct(MenuHelper $helper)
{
$this->helper = $helper;
}
/**
* @return array
*/
public function getFunctions()
{
return array(
'menu' => new \Twig_Function_Method($this, 'render', array(
'is_safe' => array('html'),
)),
'menu_get' => new \Twig_Function_Method($this, 'get', array(
'is_safe' => array('html'),
)),
);
}
/**
* @param string $name
* @return \Knplabs\MenuBundle\Menu
* @throws \InvalidArgumentException
*/
public function get($name)
{
return $this->helper->get($name);
}
/**
* @param string $name
* @param integer $depth (optional)
* @return string
*/
public function render($name, $path = null, $depth = null, $template = null)
{
return $this->helper->render($name, $path, $depth, $template);
}
/**
* @return string
*/
public function getName()
{
return 'menu';
}
}
| <?php
namespace Knplabs\MenuBundle\Twig;
use Knplabs\MenuBundle\Templating\Helper\MenuHelper;
class MenuExtension extends \Twig_Extension
{
/**
* @var MenuHelper
*/
protected $provider;
/**
* @param MenuHelper
*/
public function __construct(MenuHelper $helper)
{
$this->helper = $helper;
}
/**
* @return array
*/
public function getFunctions()
{
return array(
'menu' => new \Twig_Function_Method($this, 'render', array(
'is_safe' => array('html'),
)),
'menu_get' => new \Twig_Function_Method($this, 'get', array(
'is_safe' => array('html'),
)),
);
}
/**
* @param string $name
* @return \Knplabs\MenuBundle\Menu
* @throws \InvalidArgumentException
*/
public function get($name)
{
return $this->helper->get($name);
}
/**
* @param string $name
* @param integer $depth (optional)
* @return string
*/
public function render($name, $path = null, $depth = null, $template = null)
{
return $this->helper->render($name, $path, $depth, $template);
}
/**
* @return string
*/
public function getName()
{
return 'menu';
}
}
|
Adjust help request to conform to new spec format. | var http = require('http');
var r = require('request');
var config = require('./config.json');
var doneUrl;
var userUrl;
http.createServer(function(request, response) {
if (!isEvent(request)) return;
r.post({
url: doneUrl
}, function(error, response, body) {
if (error !== null) {
throw error;
}
r.post({
url: doneUrl,
form: {
authUrl: userUrl
}
}, function(error, response, body) {
if (error !== null) {
throw error;
}
});
});
}).listen(config.port);
var isEvent = function(request) {
return request.url === config.eventsUrl && request.method === 'POST';
};
var helperUrl = config.helper.host + config.helper.endpoint;
r.post({
url: helperUrl,
body: {
media: {
type: "url",
content: config.sampleImageUrl
},
eventsURL: config.eventsUrl
},
json: true
}, function(error, response, body) {
if (error !== null) {
throw error;
}
var bodyInJson = JSON.parse(body);
doneUrl = bodyInJson.doneUrl;
userUrl = bodyInJson.userUrl;
});
| var http = require('http');
var r = require('request');
var config = require('./config.json');
var doneUrl;
var userUrl;
http.createServer(function(request, response) {
if (!isEvent(request)) return;
r.post({
url: doneUrl
}, function(error, response, body) {
if (error !== null) {
throw error;
}
r.post({
url: doneUrl,
form: {
authUrl: userUrl
}
}, function(error, response, body) {
if (error !== null) {
throw error;
}
});
});
}).listen(config.port);
var isEvent = function(request) {
return request.url === config.eventsUrl && request.method === 'POST';
};
var helperUrl = config.helper.host + config.helper.endpoint;
r.post({
url: helperUrl,
form: {
media: config.sampleImageUrl,
eventsUrl: config.eventsUrl
}
}, function(error, response, body) {
if (error !== null) {
throw error;
}
var bodyInJson = JSON.parse(body);
doneUrl = bodyInJson.doneUrl;
userUrl = bodyInJson.userUrl;
});
|
Make LoadTestShape a proper abstract class. | from __future__ import annotations
import time
from typing import Optional, Tuple, List, Type
from abc import ABC, abstractmethod
from . import User
from .runners import Runner
class LoadTestShape(ABC):
"""
Base class for custom load shapes.
"""
runner: Optional[Runner] = None
"""Reference to the :class:`Runner <locust.runners.Runner>` instance"""
def __init__(self):
self.start_time = time.perf_counter()
def reset_time(self):
"""
Resets start time back to 0
"""
self.start_time = time.perf_counter()
def get_run_time(self):
"""
Calculates run time in seconds of the load test
"""
return time.perf_counter() - self.start_time
def get_current_user_count(self):
"""
Returns current actual number of users from the runner
"""
return self.runner.user_count
@abstractmethod
def tick(self) -> Tuple[int, float] | Tuple[int, float, Optional[List[Type[User]]]] | None:
"""
Returns a tuple with 2 elements to control the running load test:
user_count -- Total user count
spawn_rate -- Number of users to start/stop per second when changing number of users
user_classes -- None or a List of userclasses to be spawned in it tick
If `None` is returned then the running load test will be stopped.
"""
...
| from __future__ import annotations
import time
from typing import Optional, Tuple, List, Type
from . import User
from .runners import Runner
class LoadTestShape:
"""
A simple load test shape class used to control the shape of load generated
during a load test.
"""
runner: Optional[Runner] = None
"""Reference to the :class:`Runner <locust.runners.Runner>` instance"""
def __init__(self):
self.start_time = time.perf_counter()
def reset_time(self):
"""
Resets start time back to 0
"""
self.start_time = time.perf_counter()
def get_run_time(self):
"""
Calculates run time in seconds of the load test
"""
return time.perf_counter() - self.start_time
def get_current_user_count(self):
"""
Returns current actual number of users from the runner
"""
return self.runner.user_count
def tick(self) -> Tuple[int, float] | Tuple[int, float, Optional[List[Type[User]]]] | None:
"""
Returns a tuple with 2 elements to control the running load test:
user_count -- Total user count
spawn_rate -- Number of users to start/stop per second when changing number of users
user_classes -- None or a List of userclasses to be spawned in it tick
If `None` is returned then the running load test will be stopped.
"""
return None
|
[DDW-160] Use role instead of selector in macOS menu | export const osxMenu = (app, window, openAbout) => (
[{
label: 'Daedalus',
submenu: [{
label: 'About',
click() {
openAbout();
},
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => app.quit()
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Command+Z',
role: 'undo'
}, {
label: 'Redo',
accelerator: 'Shift+Command+Z',
role: 'redo'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Command+X',
role: 'cut'
}, {
label: 'Copy',
accelerator: 'Command+C',
role: 'copy'
}, {
label: 'Paste',
accelerator: 'Command+V',
role: 'paste'
}, {
label: 'Select All',
accelerator: 'Command+A',
role: 'selectall'
}]
}, {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Command+R',
click: () => window.webContents.reload()
},
{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click: () => window.setFullScreen(!window.isFullScreen())
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Command+I',
click: () => window.toggleDevTools()
}
]
}]
);
| export const osxMenu = (app, window, openAbout) => (
[{
label: 'Daedalus',
submenu: [{
label: 'About',
click() {
openAbout();
},
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => app.quit()
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Command+Z',
selector: 'undo:'
}, {
label: 'Redo',
accelerator: 'Shift+Command+Z',
selector: 'redo:'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Command+X',
selector: 'cut:'
}, {
label: 'Copy',
accelerator: 'Command+C',
selector: 'copy:'
}, {
label: 'Paste',
accelerator: 'Command+V',
selector: 'paste:'
}, {
label: 'Select All',
accelerator: 'Command+A',
selector: 'selectAll:'
}]
}, {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Command+R',
click: () => window.webContents.reload()
},
{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click: () => window.setFullScreen(!window.isFullScreen())
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Command+I',
click: () => window.toggleDevTools()
}
]
}]
);
|
Use PhantomJS instead of Chrome | const path = require('path');
const webpackConfig = {
devtool: 'inline-source-map',
module: {
rules: [{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/,
enforce: 'pre'
}, {
test: /\.js$/,
exclude: /(node_modules|\.spec\.js$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post',
options: {
esModules: true
}
}]
}
};
module.exports = function (config) {
config.set({
frameworks: ['jasmine'],
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-chrome-launcher',
'karma-jasmine-html-reporter',
'karma-coverage-istanbul-reporter'
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
'./src/**/*.js',
'./test/**/*.js'
],
preprocessors: {
'./src/**/*.js': ['webpack', 'sourcemap'],
'./test/**/*.js': ['webpack', 'sourcemap'],
},
webpack: webpackConfig,
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
dir: path.join(__dirname, 'coverage'),
fixWebpackSourcePaths: true
},
reporters: ['progress', 'coverage-istanbul', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
});
}; | const path = require('path');
const webpackConfig = {
devtool: 'inline-source-map',
module: {
rules: [{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/,
enforce: 'pre'
}, {
test: /\.js$/,
exclude: /(node_modules|\.spec\.js$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post',
options: {
esModules: true
}
}]
}
};
module.exports = function (config) {
config.set({
frameworks: ['jasmine'],
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-chrome-launcher',
'karma-jasmine-html-reporter',
'karma-coverage-istanbul-reporter'
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
'./src/**/*.js',
'./test/**/*.js'
],
preprocessors: {
'./src/**/*.js': ['webpack', 'sourcemap'],
'./test/**/*.js': ['webpack', 'sourcemap'],
},
webpack: webpackConfig,
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
dir: path.join(__dirname, 'coverage'),
fixWebpackSourcePaths: true
},
reporters: ['progress', 'coverage-istanbul', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
}; |
Fix the deletion of sector objects | const functions = require('firebase-functions');
const admin = require('firebase-admin');
const BATCH_SIZE = 500;
const deleteBatch = (query, resolve, reject) =>
query
.limit(BATCH_SIZE)
.get()
.then(snapshot => {
if (snapshot.size === 0) {
return 0;
}
const batch = admin.firestore().batch();
snapshot.docs.forEach(doc => batch.delete(doc.ref));
return batch.commit().then(() => snapshot.size);
})
.then(numDeleted => {
if (numDeleted === 0) {
return resolve();
}
return process.nextTick(() => {
deleteBatch(query, resolve, reject);
});
})
.catch(reject);
module.exports = functions.firestore
.document('entities/sector/entity/{sectorId}')
.onDelete((snapshot, context) => {
const { sectorId } = context.params;
const navigationQuery = admin
.firestore()
.collection('navigation')
.doc(sectorId)
.collection('routes');
const layerQuery = admin
.firestore()
.collection('layers')
.doc(sectorId)
.collection('layer');
return Promise.all([
new Promise((resolve, reject) =>
deleteBatch(navigationQuery, resolve, reject)
),
new Promise((resolve, reject) =>
deleteBatch(layerQuery, resolve, reject)
),
]).catch(
error => new functions.https.HttpsError('unknown', error.message, error)
);
});
| const functions = require('firebase-functions');
const admin = require('firebase-admin');
const BATCH_SIZE = 500;
const deleteBatch = (query, resolve, reject) =>
query
.limit(BATCH_SIZE)
.get()
.then(snapshot => {
if (snapshot.size === 0) {
return 0;
}
const batch = admin.firestore().batch();
snapshot.docs.forEach(doc => batch.delete(doc.ref));
return batch.commit().then(() => snapshot.size);
})
.then(numDeleted => {
if (numDeleted === 0) {
return resolve();
}
return process.nextTick(() => {
deleteBatch(query, resolve, reject);
});
})
.catch(reject);
module.exports = functions.firestore
.document('entities/sector/entity/{sectorId}')
.onDelete((snapshot, context) => {
const { sectorId } = context.params;
const navigationQuery = admin
.firestore()
.collection('navigation')
.doc(sectorId)
.collection('routes');
const layerQuery = admin
.firestore()
.collection('layer')
.doc(sectorId)
.collection('layers');
return Promise.all([
new Promise((resolve, reject) =>
deleteBatch(navigationQuery, resolve, reject)
),
new Promise((resolve, reject) =>
deleteBatch(layerQuery, resolve, reject)
),
]).catch(
error => new functions.https.HttpsError('unknown', error.message, error)
);
});
|
Fix controller name after merge | 'use strict';
// This file contains controllers of base pages attributes: header, footer, body, common menu and so on
(function() {
angular.module('ncsaas')
.controller('HeaderController', ['$scope', 'currentStateService', 'customersService', HeaderController]);
function HeaderController($scope, currentStateService, customersService) {
var vm = this;
vm.customers = customersService.getCustomersList();
vm.getUser = currentStateService.getUser;
vm.getCustomer = currentStateService.getCustomer;
vm.menuToggle = menuToggle;
vm.setCurrentCustomer = currentStateService.setCustomer;
// top-level menu
vm.menuState = {
addSomethingMenu : false,
combineMenu : false,
customerMenu : false,
profileMenu : false
};
function menuToggle(active) {
for (var property in vm.menuState) {
if (vm.menuState.hasOwnProperty(property)) {
if (property !== active) {
vm.menuState[property] = false;
}
}
}
event.stopPropagation();
vm.menuState[active] = !vm.menuState[active];
}
window.onclick = function() {
for (var property in vm.menuState) {
if (vm.menuState.hasOwnProperty(property)) {
vm.menuState[property] = false;
}
}
$scope.$apply();
};
}
})();
| 'use strict';
// This file contains controllers of base pages attributes: header, footer, body, common menu and so on
(function() {
angular.module('ncsaas')
.controller('HeaderContoller', ['$scope', 'currentStateService', 'customersService', HeaderContoller]);
function HeaderContoller($scope, currentStateService, customersService) {
var vm = this;
vm.customers = customersService.getCustomersList();
vm.getUser = currentStateService.getUser;
vm.getCustomer = currentStateService.getCustomer;
vm.menuToggle = menuToggle;
vm.setCurrentCustomer = currentStateService.setCustomer;
// top-level menu
vm.menuState = {
addSomethingMenu : false,
combineMenu : false,
customerMenu : false,
profileMenu : false
};
function menuToggle(active) {
for (var property in vm.menuState) {
if (vm.menuState.hasOwnProperty(property)) {
if (property !== active) {
vm.menuState[property] = false;
}
}
}
event.stopPropagation();
vm.menuState[active] = !vm.menuState[active];
}
window.onclick = function() {
for (var property in vm.menuState) {
if (vm.menuState.hasOwnProperty(property)) {
vm.menuState[property] = false;
}
}
$scope.$apply();
};
}
})();
|
Update to work with new API | 'use strict';
var consolidate = require('consolidate');
var path = require('path');
var _ = require('lodash');
module.exports = function(source, config){
config = _defaultsDeep(config || {}, {
engine: 'handlebars'
});
const partials = {};
function loadViews(source) {
for (let item of source.flatten(true)) {
partials[item.handle] = item.content;
if (item.alias) {
partials[item.alias] = item.content;
}
}
viewsLoaded = true;
}
source.on('loaded', loadViews);
source.on('changed', loadViews);
return {
engine: consolidate[config.engine],
render: function(tplPath, str, context, meta){
if (!viewsLoaded) loadViews(source);
context.partials = {};
_.each(partials, function(partialPath, partialKey){
if (tplPath != partialPath) {
const relPath = path.relative(tplPath, partialPath).replace('../', '');
const parts = path.parse(relPath);
if ( !_.isEmpty(parts.name) && (path.extname(tplPath) == path.extname(partialPath))) {
context.partials[partialKey] = path.join(parts.dir, parts.name);
}
}
});
return Promise.resolve(consolidate[config.engine](tplPath, context));
}
}
};
| 'use strict';
var consolidate = require('consolidate');
var path = require('path');
var _ = require('lodash');
module.exports = {
partials: {},
defaults: {
ext: '.hbs',
name: 'handlebars'
},
config: null,
configure: function(config){
this.config = config;
},
/**
* Register component view templates as partials.
* Called every time the component file tree changes.
*/
registerViews: function(views) {
var self = this;
views.forEach(function(view){
self.partials[view.handle] = view.path;
if (view.alias) {
self.partials[view.alias] = view.path;
}
});
},
/**
* Render the component view contents.
* More work than it should be because it needs some skanky
* partial path rewriting to make them play nicely with consolidate.
*/
render: function(str, context, meta) {
context.partials = {};
var tplPath = meta.path;
_.each(this.partials, function(partialPath, partialKey){
if (tplPath != partialPath) {
var relPath = path.relative(tplPath, partialPath).replace('../', '');
var parts = path.parse(relPath);
if ( !_.isEmpty(parts.name) && (path.extname(tplPath) == path.extname(partialPath))) {
context.partials[partialKey] = path.join(parts.dir, parts.name);
}
}
});
return consolidate[this.config.name](meta.path, context);
}
};
|
Fix deprecation for symfony/config 4.2 | <?php
/*
* This file is part of the StampieBundle package.
*
* (c) Henrik Bjornskov <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Stampie\StampieBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Henrik Bjornskov <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
private $debug;
/**
* @param bool $debug The kernel.debug value
*/
public function __construct($debug)
{
$this->debug = (bool) $debug;
}
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder('stampie');
if (\method_exists($builder, 'getRootNode')) {
$root = $builder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$root = $builder->root('stampie');
}
$root
->children()
->scalarNode('mailer')->isRequired()->end()
->scalarNode('server_token')->isRequired()->end()
->scalarNode('http_client')->defaultValue('httplug.client')->end()
->arrayNode('extra')
->children()
->scalarNode('delivery_address')->defaultNull()->end()
->scalarNode('logging')->defaultValue($this->debug)->end()
->end()
->end()
->end();
return $builder;
}
}
| <?php
/*
* This file is part of the StampieBundle package.
*
* (c) Henrik Bjornskov <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Stampie\StampieBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* @author Henrik Bjornskov <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
private $debug;
/**
* @param bool $debug The kernel.debug value
*/
public function __construct($debug)
{
$this->debug = (bool) $debug;
}
public function getConfigTreeBuilder()
{
$builder = new TreeBuilder();
$root = $builder->root('stampie');
$root
->children()
->scalarNode('mailer')->isRequired()->end()
->scalarNode('server_token')->isRequired()->end()
->scalarNode('http_client')->defaultValue('httplug.client')->end()
->arrayNode('extra')
->children()
->scalarNode('delivery_address')->defaultNull()->end()
->scalarNode('logging')->defaultValue($this->debug)->end()
->end()
->end()
->end();
return $builder;
}
}
|
Update factory voter ACTIVE_RELATION statement | <?php
namespace Furniture\FactoryBundle\Security\Voter;
use Furniture\UserBundle\Entity\User;
use Furniture\FactoryBundle\Entity\Factory;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;
class ViewFactoryVoter extends AbstractVoter
{
/**
* {@inheritDoc}
*/
protected function getSupportedClasses()
{
return [Factory::class];
}
/**
* {@inheritDoc}
*/
protected function getSupportedAttributes()
{
return ['ACTIVE_RELATION'];
}
/**
* {@inheritDoc}
*/
protected function isGranted($attribute, $factory, $user = null)
{
/** @var \Furniture\FactoryBundle\Entity\Factory $factory */
if (!$user || !$user instanceof User) {
return false;
}
switch ($attribute) {
case 'ACTIVE_RELATION':
if (!$user->isRetailer()) {
return false;
}
$factoryRetailerRelation = $factory->getRetailerRelationByRetailer(
$user
->getRetailerUserProfile()
->getRetailerProfile()
);
if ($factory->isEnabled() && (($factoryRetailerRelation
&& $factoryRetailerRelation->isActive()
&& $factoryRetailerRelation->isFactoryAccept()
&& $factoryRetailerRelation->isAccessProducts())
|| $factory->getDefaultRelation()->isAccessProducts())
) {
return true;
}
return false;
default:
return false;
}
}
} | <?php
namespace Furniture\FactoryBundle\Security\Voter;
use Furniture\UserBundle\Entity\User;
use Furniture\FactoryBundle\Entity\Factory;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;
class ViewFactoryVoter extends AbstractVoter
{
/**
* {@inheritDoc}
*/
protected function getSupportedClasses()
{
return [Factory::class];
}
/**
* {@inheritDoc}
*/
protected function getSupportedAttributes()
{
return ['ACTIVE_RELATION'];
}
/**
* {@inheritDoc}
*/
protected function isGranted($attribute, $factory, $user = null)
{
/** @var \Furniture\FactoryBundle\Entity\Factory $factory */
if (!$user || !$user instanceof User) {
return false;
}
switch ($attribute) {
case 'ACTIVE_RELATION':
if (!$user->isRetailer()) {
return false;
}
$factoryRetailerRelation = $factory->getRetailerRelationByRetailer(
$user
->getRetailerUserProfile()
->getRetailerProfile()
);
if ($factory->isEnabled() && (($factoryRetailerRelation
&& $factoryRetailerRelation->isActive()
&& $factoryRetailerRelation->isFactoryAccept())
|| $factory->getDefaultRelation()->isAccessProducts())
) {
return true;
}
return false;
default:
return false;
}
}
} |
Add self to list of filtered users for editors
Closes #4412 | import AuthenticatedRoute from 'ghost/routes/authenticated';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
import styleBody from 'ghost/mixins/style-body';
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor') || user === currentUser;
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
export default UsersIndexRoute;
| import AuthenticatedRoute from 'ghost/routes/authenticated';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
import styleBody from 'ghost/mixins/style-body';
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor');
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
export default UsersIndexRoute;
|
Disable attempts for the cometd lib to try wss connections
wss connections are not yet valid in Lightning context | ({
doInit: function(component, event, helper) {
var action = component.get("c.getSessionId");
action.setCallback(this, function(response) {
// Configure CometD
var sessionId = response.getReturnValue();
var cometd = new window.org.cometd.CometD();
cometd.configure({
url: window.location.protocol + '//' + window.location.hostname + '/cometd/40.0/',
requestHeaders: { Authorization: 'OAuth ' + sessionId},
appendMessageTypeToURL : false
});
cometd.websocketEnabled = false;
// Connect to
cometd.handshake($A.getCallback(function(status) {
if (status.successful) {
var eventName = component.get("v.channel");
cometd.subscribe(eventName, $A.getCallback(function(message) {
var messageEvent = component.getEvent("onMessage");
if(messageEvent!=null) {
messageEvent.setParam("payload", message.data.payload);
messageEvent.fire();
}
}
));
} else {
// TODO: Handle errors
console.log(status);
}
}));
});
$A.enqueueAction(action);
}
})
| ({
doInit: function(component, event, helper) {
var action = component.get("c.getSessionId");
action.setCallback(this, function(response) {
// Configure CometD
var sessionId = response.getReturnValue();
var cometd = new window.org.cometd.CometD();
cometd.configure({
url: window.location.protocol + '//' + window.location.hostname + '/cometd/40.0/',
requestHeaders: { Authorization: 'OAuth ' + sessionId},
appendMessageTypeToURL : false
});
// Connect to
cometd.handshake($A.getCallback(function(status) {
if (status.successful) {
var eventName = component.get("v.channel");
cometd.subscribe(eventName, $A.getCallback(function(message) {
var messageEvent = component.getEvent("onMessage");
if(messageEvent!=null) {
messageEvent.setParam("payload", message.data.payload);
messageEvent.fire();
}
}
));
} else {
// TODO: Handle errors
console.log(status);
}
}));
});
$A.enqueueAction(action);
}
})
|
Make "is_saveable" a staticmethod of SaveSession | import sublime
import sublime_plugin
from datetime import datetime
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
def plugin_loaded():
settings.load()
def error_message(errno):
sublime.error_message(messages.error(errno))
class SaveSession(sublime_plugin.ApplicationCommand):
def run(self):
sublime.active_window().show_input_panel(
messages.dialog("session_name"),
self.generate_name(),
on_done=self.save_session,
on_change=None,
on_cancel=None
)
def generate_name(self):
nameformat = settings.get('session_name_dateformat')
return datetime.now().strftime(nameformat)
def save_session(self, session_name):
session = Session.save(session_name, sublime.windows())
try:
serialize.dump(session_name, session)
except OSError as e:
error_message(e.errno)
def is_enabled(self):
windows = sublime.windows()
for window in windows:
if self.is_saveable(window):
return True
return False
@staticmethod
def is_saveable(window):
return bool(window.views()) or bool(window.project_data())
| import sublime
import sublime_plugin
from datetime import datetime
from .modules import messages
from .modules import serialize
from .modules import settings
from .modules.session import Session
def plugin_loaded():
settings.load()
def error_message(errno):
sublime.error_message(messages.error(errno))
class SaveSession(sublime_plugin.ApplicationCommand):
def run(self):
sublime.active_window().show_input_panel(
messages.dialog("session_name"),
self.generate_name(),
on_done=self.save_session,
on_change=None,
on_cancel=None
)
def generate_name(self):
nameformat = settings.get('session_name_dateformat')
return datetime.now().strftime(nameformat)
def save_session(self, session_name):
session = Session.save(session_name, sublime.windows())
try:
serialize.dump(session_name, session)
except OSError as e:
error_message(e.errno)
def is_enabled(self):
windows = sublime.windows()
for window in windows:
if is_saveable(window):
return True
return False
def is_saveable(window):
return bool(window.views()) or bool(window.project_data())
|
Add STATUS_UPDATE, remove header actions from status reducer | import initialState from './initialState';
import {
LOGO_SPIN_STARTED,
LOGO_SPIN_ENDED,
PAGE_SCROLL_STARTED,
SCROLL_ENDED,
APP_INIT,
STATUS_UPDATE,
PROVIDER_CHANGE,
BOARD_CHANGE,
THREAD_REQUESTED,
BOARD_REQUESTED,
} from '../constants';
export default function (state = initialState.status, action) {
switch (action.type) {
case APP_INIT:
return Object.assign({}, state, {
isMainPage: true
})
case PAGE_SCROLL_STARTED:
return Object.assign({}, state, {
isScrolling: true
})
case SCROLL_ENDED:
return Object.assign({}, state, {
isScrolling: false,
})
case LOGO_SPIN_STARTED:
return Object.assign({}, state, {
isLogoSpinning: true
})
case LOGO_SPIN_ENDED:
return Object.assign({}, state, {
isLogoSpinning: false
})
case PROVIDER_CHANGE:
return Object.assign({}, state, {
provider: action.payload
})
case BOARD_REQUESTED:
return Object.assign({}, state, {
boardID: action.payload
})
case THREAD_REQUESTED:
return Object.assign({}, state, {
threadID: action.payload
})
case STATUS_UPDATE:
return Object.assign({}, state, {
statusMessage: action.payload
})
default:
return state
}
}
| import initialState from './initialState';
import {
HEADER_SHRINKING,
HEADER_EXPANDING,
HEADER_ANIMATION_ENDED,
LOGO_SPIN_STARTED,
LOGO_SPIN_ENDED,
SCROLL_STARTED,
SCROLL_ENDED,
APP_INIT
} from '../constants';
export default function (state = initialState.status, action) {
switch (action.type) {
case APP_INIT:
return Object.assign({}, state, {
isMainPage: true
})
case HEADER_EXPANDING:
case HEADER_SHRINKING:
return Object.assign({}, state, {
isAnimating: true
})
case HEADER_ANIMATION_ENDED:
return Object.assign({}, state, {
isAnimating: false,
isMainPage: !state.isMainPage
})
case SCROLL_STARTED:
return Object.assign({}, state, {
isScrolling: false,
loadingMessage: action.type
})
case SCROLL_ENDED:
return Object.assign({}, state, {
isScrolling: false,
})
case LOGO_SPIN_STARTED:
return Object.assign({}, state, {
isLogoSpinning: true,
loadingMessage: action.payload
})
case LOGO_SPIN_ENDED:
return Object.assign({}, state, {
isLogoSpinning: false,
loadingMessage: null
})
default:
return state
}
}
|
Fix reload page when scrolling upwards | import angular from 'angular';
export default function maDatagridInfinitePagination($window, $document) {
var windowElement = angular.element($window);
var offset = 100,
body = $document[0].body;
return {
restrict: 'E',
scope: {
perPage: '@',
totalItems: '@',
nextPage: '&'
},
link: function(scope) {
var perPage = parseInt(scope.perPage, 10) || 1,
totalItems = parseInt(scope.totalItems, 10),
nbPages = Math.ceil(totalItems / perPage) || 1,
page = 1,
loadedPages = [];
function handler() {
if (body.offsetHeight - $window.innerHeight - $window.scrollY < offset) {
if (page >= nbPages) {
return;
}
page++;
if(loadedPages.includes(page)){
return;
}
loadedPages.push(page);
scope.nextPage()(page);
}
}
windowElement.bind('scroll', handler);
scope.$on('$destroy', function destroy() {
windowElement.unbind('scroll', handler);
});
}
};
}
maDatagridInfinitePagination.$inject = ['$window', '$document'];
| import angular from 'angular';
export default function maDatagridInfinitePagination($window, $document) {
var windowElement = angular.element($window);
var offset = 100,
body = $document[0].body;
return {
restrict: 'E',
scope: {
perPage: '@',
totalItems: '@',
nextPage: '&'
},
link: function(scope) {
var perPage = parseInt(scope.perPage, 10) || 1,
totalItems = parseInt(scope.totalItems, 10),
nbPages = Math.ceil(totalItems / perPage) || 1,
page = 1;
function handler() {
if (body.offsetHeight - $window.innerHeight - $window.scrollY < offset) {
if (page >= nbPages) {
return;
}
page++;
scope.nextPage()(page);
}
}
windowElement.bind('scroll', handler);
scope.$on('$destroy', function destroy() {
windowElement.unbind('scroll', handler);
});
}
};
}
maDatagridInfinitePagination.$inject = ['$window', '$document'];
|
Use promises for looping through pathes to check authentication |
'use strict';
var test = require('selenium-webdriver/testing'),
application_host = 'http://localhost:3000/',
new_user_email,
webdriver = require('selenium-webdriver'),
By = require('selenium-webdriver').By,
expect = require('chai').expect,
_ = require('underscore'),
Promise = require("bluebird");
describe('Try to access private pages with guest user', function(){
// The app is really slow and does not manage to handle request in
// default 2 seconds, so be more patient.
this.timeout(50000);
test.it('Check logout page', function(done) {
Promise.all(_.map(
['logout/', 'settings/company/'],
function(path) {
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
// Open front page
driver.get( application_host + path);
driver.getCurrentUrl()
.then(function(url){
expect(url).to.be.equal(application_host);
});
return driver.quit();
}))
.then(function(){ done(); });
});
test.it('Check main (dashboard) page', function(done) {
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
// Open front page
driver.get( application_host);
driver.getTitle()
.then(function(title){
expect(title).to.be.equal('Time off management');
});
driver.quit().then(function(){ done(); });
});
});
|
'use strict';
var test = require('selenium-webdriver/testing'),
application_host = 'http://localhost:3000/',
new_user_email,
webdriver = require('selenium-webdriver'),
By = require('selenium-webdriver').By,
expect = require('chai').expect;
describe('Try to access private pages with guest user', function(){
// The app is really slow and does not manage to handle request in
// default 2 seconds, so be more patient.
this.timeout(50000);
test.it('Check logout page', function(done) {
['logout/', 'settings/company/']
.map(function(path){
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
// Open front page
driver.get( application_host + path);
driver.getCurrentUrl()
.then(function(url){
expect(url).to.be.equal(application_host);
});
driver.quit().then(function(){ done(); });
});
});
test.it('Check main (dashboard) page', function(done) {
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
// Open front page
driver.get( application_host);
driver.getTitle()
.then(function(title){
expect(title).to.be.equal('Time off management');
});
driver.quit().then(function(){ done(); });
});
});
|
BUG-633: Rewrite test to how IReference actually works | import lxml.objectify
import zeit.cms.content.interfaces
import zeit.content.article.edit.volume
import zeit.content.volume.testing
import zope.component
class VolumeReferenceTest(zeit.content.volume.testing.FunctionalTestCase):
def setUp(self):
from zeit.content.volume.volume import Volume
super(VolumeReferenceTest, self).setUp()
self.repository['testvolume'] = Volume()
self.volume = self.repository['testvolume']
def test_volume_can_be_adapted_to_IXMLReference(self):
result = zope.component.getAdapter(
self.volume,
zeit.cms.content.interfaces.IXMLReference,
name='related')
self.assertEqual('volume', result.tag)
self.assertEqual(self.volume.uniqueId, result.get('href'))
def test_volume_can_be_adapted_to_IReference(self):
from zeit.content.volume.interfaces import IVolumeReference
node = zope.component.getAdapter(
self.volume, zeit.cms.content.interfaces.IXMLReference,
name='related')
source = zeit.content.article.edit.volume.Volume(
None, lxml.objectify.XML('<volume/>'))
reference = zope.component.getMultiAdapter(
(source, node),
zeit.cms.content.interfaces.IReference, name='related')
reference.teaserText = 'Test teaser'
self.assertEqual(True, IVolumeReference.providedBy(reference))
self.assertEqual('Test teaser', reference.xml.teaserText.text)
| import zeit.cms.content.interfaces
import zeit.content.article.edit.volume
import zeit.content.volume.testing
import zope.component
class VolumeReferenceTest(zeit.content.volume.testing.FunctionalTestCase):
def setUp(self):
from zeit.content.volume.volume import Volume
super(VolumeReferenceTest, self).setUp()
self.repository['testvolume'] = Volume()
self.volume = self.repository['testvolume']
self.reference_container = zeit.content.article.edit.volume.Volume(
self.volume, self.volume.xml)
def test_volume_can_be_adapted_to_IXMLReference(self):
result = zope.component.getAdapter(
self.volume,
zeit.cms.content.interfaces.IXMLReference,
name='related')
self.assertEqual('volume', result.tag)
self.assertEqual(self.volume.uniqueId, result.get('href'))
def test_volume_can_be_adapted_to_IReference(self):
from zeit.content.volume.interfaces import IVolumeReference
result = zope.component.getMultiAdapter(
(self.reference_container, self.volume.xml),
zeit.cms.content.interfaces.IReference, name='related')
result.teaserText = 'Test teaser'
self.assertEqual(True, IVolumeReference.providedBy(result))
self.assertEqual('Test teaser', result.xml.teaserText.text)
|
Add expiry fields on card model | # -*- coding: utf-8 -*-
"""Checkout Models"""
import functools
from flask import redirect, url_for
from fulfil_client.model import ModelType, StringType
from shop.fulfilio import Model
from shop.globals import current_cart, current_channel
def not_empty_cart(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
cart = current_cart
if cart.is_empty:
return redirect(url_for('cart.view_cart'))
return function(*args, **kwargs)
return wrapper
def sale_has_non_guest_party(function):
"""
Ensure that the sale has a party who is not guest.
The sign-in method authomatically changes the party to a party based on the
session.
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
cart = current_cart
if cart.sale and cart.sale.party and \
cart.sale.party.id == current_channel.anonymous_customer.id:
return redirect(url_for('checkout.sign_in'))
return function(*args, **kwargs)
return wrapper
class PaymentGateway(Model):
__model_name__ = 'payment_gateway.gateway'
provider = StringType()
stripe_publishable_key = StringType()
class PaymentProfile(Model):
__model_name__ = 'party.payment_profile'
party = ModelType('party.party')
gateway = ModelType('payment_gateway.gateway')
last_4_digits = StringType()
expiry_month = StringType()
expiry_year = StringType()
rec_name = StringType()
| # -*- coding: utf-8 -*-
"""Checkout Models"""
import functools
from flask import redirect, url_for
from fulfil_client.model import ModelType, StringType
from shop.fulfilio import Model
from shop.globals import current_cart, current_channel
def not_empty_cart(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
cart = current_cart
if cart.is_empty:
return redirect(url_for('cart.view_cart'))
return function(*args, **kwargs)
return wrapper
def sale_has_non_guest_party(function):
"""
Ensure that the sale has a party who is not guest.
The sign-in method authomatically changes the party to a party based on the
session.
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
cart = current_cart
if cart.sale and cart.sale.party and \
cart.sale.party.id == current_channel.anonymous_customer.id:
return redirect(url_for('checkout.sign_in'))
return function(*args, **kwargs)
return wrapper
class PaymentGateway(Model):
__model_name__ = 'payment_gateway.gateway'
provider = StringType()
stripe_publishable_key = StringType()
class PaymentProfile(Model):
__model_name__ = 'party.payment_profile'
party = ModelType('party.party')
gateway = ModelType('payment_gateway.gateway')
last_4_digits = StringType()
rec_name = StringType()
|
[tests] Enable also the Script panel to get proper stack traces | function runTest()
{
FBTest.sysout("issue2914.START");
FBTest.openNewTab(basePath + "console/2914/issue2914.html", function(win)
{
FBTest.openFirebug();
FBTest.enableScriptPanel();
FBTest.enableConsolePanel(function(win)
{
var panelNode = FBTest.selectPanel("console").panelNode;
var errorNode = panelNode.querySelector(".objectBox.objectBox-errorMessage");
var titleNode = errorNode.querySelector(".errorTitle");
// Verify the error message
FBTest.compare(titleNode.textContent, "iframe error",
"An error message must be displayed");
// The expandable button must be displayed.
FBTest.ok(FW.FBL.hasClass(errorNode, "hasTwisty"),
"The error must be expandable.");
// Open stack trace info.
FBTest.click(titleNode);
// Verify stack trace.
var traceNode = errorNode.querySelector(".errorTrace");
FBTest.compare(
"logError()" + FW.FBL.$STRF("Line", ["issue2...me.html", 11]) +
"issue2914-innerFrame.html()" + FW.FBL.$STRF("Line", ["issue2...me.html", 13]),
traceNode.textContent,
"The stack trace must be properly displayed.");
FBTest.testDone("issue2914.DONE");
});
});
}
| function runTest()
{
FBTest.sysout("issue2914.START");
FBTest.openNewTab(basePath + "console/2914/issue2914.html", function(win)
{
FBTest.openFirebug();
FBTest.enableConsolePanel(function(win)
{
var panelNode = FW.Firebug.chrome.selectPanel("console").panelNode;
var errorNode = panelNode.querySelector(".objectBox.objectBox-errorMessage");
var titleNode = errorNode.querySelector(".errorTitle");
// Verify the error message
FBTest.compare(titleNode.textContent, "iframe error",
"An error message must be displayed");
// The expandable button must be displayed.
FBTest.ok(FW.FBL.hasClass(errorNode, "hasTwisty"),
"The error must be expandable.");
// Open stack trace info.
FBTest.click(titleNode);
// Verify stack trace.
var traceNode = errorNode.querySelector(".errorTrace");
FBTest.compare(
"logError()" + FW.FBL.$STRF("Line", ["issue2...me.html", 11]) +
"issue2914-innerFrame.html()" + FW.FBL.$STRF("Line", ["issue2...me.html", 13]),
traceNode.textContent,
"The stack trace must be properly displayed.");
FBTest.testDone("issue2914.DONE");
});
});
}
|
Upgrade if the user's file matches the previous | import fs from "fs-extra";
import path from "path";
import inquirer from "inquirer";
import sha1 from "sha1";
import readFileSyncStrip from "../lib/readFileSyncStrip";
import logger from "../lib/logger";
import { warn } from "../lib/logsColorScheme";
function doUpdate(from, to) {
logger.info("Updating .babelrc file...");
fs.copySync(from, to);
}
export default function updateBabelConfig() {
return new Promise(resolve => {
const projectConfigPath = path.join(process.cwd(), ".babelrc");
const latestConfigPath = path.join(__dirname, "../..", "new", ".babelrc");
const projectSha = sha1(readFileSyncStrip(projectConfigPath));
const previousSha = sha1(readFileSyncStrip(path.join(__dirname, "previous", ".babelrc")));
const latestSha = sha1(readFileSyncStrip(latestConfigPath));
if (projectSha === latestSha) {
return resolve();
}
else if (projectSha !== previousSha) {
const question = {
type: "confirm",
name: "confirm",
message: `${warn("The format of .babelrc is out of date. Would you like to automatically update it?")}`
};
inquirer.prompt([question], function (answers) {
if (!answers.confirm) {
const latestConfig = fs.readFileSync(latestConfigPath);
logger.info(`It is recommended that you update your .babelrc file. Here is an example file:\n${latestConfig}`);
return resolve();
}
doUpdate(latestConfigPath, projectConfigPath);
return resolve();
});
}
doUpdate(latestConfigPath, projectConfigPath);
return resolve();
});
}
| import fs from "fs-extra";
import path from "path";
import inquirer from "inquirer";
import sha1 from "sha1";
import readFileSyncStrip from "../lib/readFileSyncStrip";
import logger from "../lib/logger";
import { warn } from "../lib/logsColorScheme";
function doUpdate(from, to) {
logger.info("Updating .babelrc file...");
fs.copySync(from, to);
}
export default function updateBabelConfig() {
return new Promise(resolve => {
const projectConfigPath = path.join(process.cwd(), ".babelrc");
const latestConfigPath = path.join(__dirname, "../..", "new", ".babelrc");
const projectSha = sha1(readFileSyncStrip(projectConfigPath));
const previousSha = sha1(readFileSyncStrip(path.join(__dirname, "previous", ".babelrc")));
const latestSha = sha1(readFileSyncStrip(latestConfigPath));
if (projectSha === latestSha) {
return resolve();
}
else if (projectSha !== previousSha) {
const question = {
type: "confirm",
name: "confirm",
message: `${warn("The format of .babelrc is out of date. Would you like to automatically update it?")}`
};
inquirer.prompt([question], function (answers) {
if (!answers.confirm) {
const latestConfig = fs.readFileSync(latestConfigPath);
logger.info(`It is recommended that you update your .babelrc file. Here is an example file:\n${latestConfig}`);
return resolve();
}
doUpdate(latestConfigPath, projectConfigPath);
resolve();
});
}
});
}
|
Add viewport meta data and use small button | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sligen Online Demo</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<style>
body {
font-size: 1.5em;
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>SliGen</h1>
<hr>
<h4>Generate slide and pitch like a boss! </h4>
<?php
error_reporting(0);
if($_POST['generate']) {
$pwd = dirname(__FILE__);
system("cd '{$pwd}' && python3 src/generate.py");
echo '<p class="text-success">Enjoy your slide!</p>';
}
?>
<form action="." method="POST">
<input type="hidden" name="generate" value="1">
<a href="public/" class="btn btn-success" target="_blank">
<span class="glyphicon glyphicon-film"></span> Preview
</a>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-random"></span> Generate
</button>
<a href="https://github.com/Inndy/sligen" class="btn btn-info">
<span class="glyphicon glyphicon-download-alt"></span> GitHub
</a>
</form>
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sligen Online Demo</title>
<style>
body {
font-size: 1.5em;
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>SliGen</h1>
<hr>
<h4>Generate slide and pitch like a boss! </h4>
<?php
error_reporting(0);
if($_POST['generate']) {
$pwd = dirname(__FILE__);
system("cd '{$pwd}' && python3 src/generate.py");
echo '<p class="text-success">Enjoy your slide!</p>';
}
?>
<form action="." method="POST">
<input type="hidden" name="generate" value="1">
<a href="public/" class="btn btn-lg btn-success" target="_blank">
<span class="glyphicon glyphicon-film"></span> Preview
</a>
<button type="submit" class="btn btn-lg btn-primary">
<span class="glyphicon glyphicon-random"></span> Generate
</button>
<a href="https://github.com/Inndy/sligen" class="btn btn-lg btn-info">
<span class="glyphicon glyphicon-download-alt"></span> GitHub
</a>
</form>
</div>
</body>
</html>
|
Change __exit__arg names to not be built ins | IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __enter__(self):
self.before = self.__apply()
if not self.expected_before is IRRELEVANT:
check = self.before == self.expected_before
assert check, self.__precondition_failure_msg_for('before')
def __exit__(self, exec_type, exac_value, traceback):
self.after = self.__apply()
if not self.expected_after is IRRELEVANT:
check = self.after == self.expected_after
assert check, self.__precondition_failure_msg_for('after')
assert self.before != self.after, self.__equality_failure_message
def __apply(self):
return self.thing(*self.args, **self.kwargs)
@property
def __equality_failure_message(self):
return 'Expected before %r != %r after' % (self.before, self.after)
def __precondition_failure_msg_for(self, condition):
return '%s value did not change (%s)' % (
condition,
getattr(self, condition)
)
class AssertsMixin(object):
assertChanges = ChangeWatcher
| IRRELEVANT = object()
class ChangeWatcher(object):
def __init__(self, thing, *args, **kwargs):
self.thing = thing
self.args = args
self.kwargs = kwargs
self.expected_before = kwargs.pop('before', IRRELEVANT)
self.expected_after = kwargs.pop('after', IRRELEVANT)
def __enter__(self):
self.before = self.__apply()
if not self.expected_before is IRRELEVANT:
check = self.before == self.expected_before
assert check, self.__precondition_failure_msg_for('before')
def __exit__(self, type, value, traceback):
self.after = self.__apply()
if not self.expected_after is IRRELEVANT:
check = self.after == self.expected_after
assert check, self.__precondition_failure_msg_for('after')
assert self.before != self.after, self.__equality_failure_message
def __apply(self):
return self.thing(*self.args, **self.kwargs)
@property
def __equality_failure_message(self):
return 'Expected before %r != %r after' % (self.before, self.after)
def __precondition_failure_msg_for(self, condition):
return '%s value did not change (%s)' % (
condition,
getattr(self, condition)
)
class AssertsMixin(object):
assertChanges = ChangeWatcher
|
Introduce a library of the xtend. | import Promise from 'bluebird'
import extend from 'xtend'
import * as gitlabClient from './gitlabClient'
// MRのユーザを表示します。
module.exports = function(objectKind, body) {
if (objectKind === 'merge_request' || objectKind === 'issue') {
var objectAttributes = body.object_attributes;
var projectId = objectKind === 'merge_request' ? objectAttributes.target_project_id : objectAttributes.project_id;
var project = gitlabClient.project({
id: projectId
}),
author = gitlabClient.user({
user_id: objectAttributes.author_id
}),
assignee = objectAttributes.assignee_id ? gitlabClient.user({
user_id: objectAttributes.assignee_id
}) : Promise.resolve({
name: ''
});
return Promise.all([project, author, assignee])
.then(function(results) {
// ディープコピー
var newBody = extend(body, {
objectAttributes: extend(objectAttributes)
});
// URLを追加します。
// URLに指定するIDはプロジェクト毎のiidです。
newBody.objectAttributes.url = results[0].web_url + '/' + objectKind + 's/' + objectAttributes.iid;
// authorを追加します。
newBody.objectAttributes.author_name = results[1].name;
// assigneeを追加します。
newBody.objectAttributes.assignee_name = results[2].name;
return Promise.resolve(newBody);
});
} else {
return Promise.resolve(body);
}
};
| import Promise from 'bluebird'
import extend from 'xtend'
import * as gitlabClient from './gitlabClient'
// MRのユーザを表示します。
module.exports = function(objectKind, body) {
if (objectKind === 'merge_request' || objectKind === 'issue') {
var objectAttributes = body.object_attributes;
var projectId = objectKind === 'merge_request' ? objectAttributes.target_project_id : objectAttributes.project_id;
var project = gitlabClient.project({
id: projectId
}),
author = gitlabClient.user({
user_id: objectAttributes.author_id
}),
assignee = objectAttributes.assignee_id ? gitlabClient.user({
user_id: objectAttributes.assignee_id
}) : Promise.resolve({
name: ''
});
return Promise.all([project, author, assignee])
.then(function(results) {
// ディープコピー
var newBody = extend({}, body, {
objectAttributes: extend({}, objectAttributes)
});
// URLを追加します。
// URLに指定するIDはプロジェクト毎のiidです。
newBody.objectAttributes.url = results[0].web_url + '/' + objectKind + 's/' + objectAttributes.iid;
// authorを追加します。
newBody.objectAttributes.author_name = results[1].name;
// assigneeを追加します。
newBody.objectAttributes.assignee_name = results[2].name;
return Promise.resolve(newBody);
});
} else {
return Promise.resolve(body);
}
};
|
Update UserSuForm to enhance compatibility with custom user models.
In custom user models, we cannot rely on there being a 'username'
field. Instead, we should use whichever field has been specified as
the username field. | # -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from . import get_user_model
class UserSuForm(forms.Form):
username_field = get_user_model().USERNAME_FIELD
user = forms.ModelChoiceField(
label=_('Users'), queryset=get_user_model()._default_manager.order_by(
username_field), required=True) # pylint: disable=W0212
use_ajax_select = False
def __init__(self, *args, **kwargs):
super(UserSuForm, self).__init__(*args, **kwargs)
if 'ajax_select' in settings.INSTALLED_APPS and getattr(
settings, 'AJAX_LOOKUP_CHANNELS', None):
from ajax_select.fields import AutoCompleteSelectField
lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None)
if lookup is not None:
old_field = self.fields['user']
self.fields['user'] = AutoCompleteSelectField(
'django_su',
required=old_field.required,
label=old_field.label,
)
self.use_ajax_select = True
def get_user(self):
return self.cleaned_data.get('user', None)
def __str__(self):
if 'formadmin' in settings.INSTALLED_APPS:
try:
from formadmin.forms import as_django_admin
return as_django_admin(self)
except ImportError:
pass
return super(UserSuForm, self).__str__()
| # -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from . import get_user_model
class UserSuForm(forms.Form):
user = forms.ModelChoiceField(
label=_('Users'), queryset=get_user_model()._default_manager.order_by(
'username'), required=True) # pylint: disable=W0212
use_ajax_select = False
def __init__(self, *args, **kwargs):
super(UserSuForm, self).__init__(*args, **kwargs)
if 'ajax_select' in settings.INSTALLED_APPS and getattr(
settings, 'AJAX_LOOKUP_CHANNELS', None):
from ajax_select.fields import AutoCompleteSelectField
lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None)
if lookup is not None:
old_field = self.fields['user']
self.fields['user'] = AutoCompleteSelectField(
'django_su',
required=old_field.required,
label=old_field.label,
)
self.use_ajax_select = True
def get_user(self):
return self.cleaned_data.get('user', None)
def __str__(self):
if 'formadmin' in settings.INSTALLED_APPS:
try:
from formadmin.forms import as_django_admin
return as_django_admin(self)
except ImportError:
pass
return super(UserSuForm, self).__str__()
|
Fix injectable service due to rc.7 changes. | "use strict";
(function () {
angular
.module("dummy", []);
var fooS = ng.core
.Class({
constructor: [ng.http.Http, function FooService(http) {
this.http = http;
}],
getFoo: function () {
return this.http.get("/src/client/app/greetings.json").map(
function (res) {
return res.json();
}
).toPromise();
}
});
var module2 = ng.core.NgModule({
imports: [ng.platformBrowser.BrowserModule, ng.http.HttpModule],
providers: [fooS]
})
.Class({
constructor: function () {}
});
var upgradeAdapter = new ng.upgrade.UpgradeAdapter(module2);
angular.element(document.body).ready(function () {
upgradeAdapter.bootstrap(document.body, ["dummy"]);
});
angular.module("dummy")
.factory("FooService",
upgradeAdapter.downgradeNg2Provider(fooS));
angular.module("dummy")
.component("foo", {
template: "<p>{{ $ctrl.hello }} from mix Angular 1 and Angular 2</p>",
controller: function (FooService) {
var vm = this;
FooService.getFoo().then(function (foos) {
vm.hello = foos.hello;
});
}
});
}());
| "use strict";
(function () {
angular
.module("dummy", []);
var fooS = ng.core
.Injectable()
.Class({
constructor: [ng.http.Http, function FooService(http) {
this.http = http;
}],
getFoo: function () {
return this.http.get("/src/client/app/greetings.json").map(
function (res) {
return res.json();
}
).toPromise();
}
});
var module2 = ng.core.NgModule({
imports: [ng.platformBrowser.BrowserModule, ng.http.HttpModule],
providers: [fooS]
})
.Class({
constructor: function () {}
});
var upgradeAdapter = new ng.upgrade.UpgradeAdapter(module2);
angular.element(document.body).ready(function () {
upgradeAdapter.bootstrap(document.body, ["dummy"]);
});
angular.module("dummy")
.factory("FooService",
upgradeAdapter.downgradeNg2Provider(fooS));
angular.module("dummy")
.component("foo", {
template: "<p>{{ $ctrl.hello }} from mix Angular 1 and Angular 2</p>",
controller: function (FooService) {
var vm = this;
FooService.getFoo().then(function (foos) {
vm.hello = foos.hello;
});
}
});
}());
|
Add --all to push option | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
"""
:param repo_dir: Directory in which to pull into
"""
self.repo_dir = repo_dir
self.repo = None
def pull(self, origin):
"""
Pulls from a remote repository and stores it in the directory.
:param origin: URL of the remote git repository
"""
#TODO Catch possible exceptions: source_repo not defined
self.repo = git.Repo.clone_from(origin, self.repo_dir)
def set_remote_url(self, new_url):
"""
Changes the target url of the previously pulled repo.
:param new_url: New remote url of the repository
"""
#TODO Catch possible exceptions: Repo not initialized
origin = self.repo.remotes.origin
cw = origin.config_writer
cw.set("url", new_url)
cw.release()
def push(self, target):
"""
Pushes the previously pulled repo to the target repository.
:param target_repo: Url of the target remote repository
"""
#TODO Catch possible exceptions: Repo not initialized
self.set_remote_url(target)
self.repo.git.push('--all')
| #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
"""
:param repo_dir: Directory in which to pull into
"""
self.repo_dir = repo_dir
self.repo = None
def pull(self, origin):
"""
Pulls from a remote repository and stores it in the directory.
:param origin: URL of the remote git repository
"""
#TODO Catch possible exceptions: source_repo not defined
self.repo = git.Repo.clone_from(origin, self.repo_dir)
def set_remote_url(self, new_url):
"""
Changes the target url of the previously pulled repo.
:param new_url: New remote url of the repository
"""
#TODO Catch possible exceptions: Repo not initialized
origin = self.repo.remotes.origin
cw = origin.config_writer
cw.set("url", new_url)
cw.release()
def push(self, target):
"""
Pushes the previously pulled repo to the target repository.
:param target_repo: Url of the target remote repository
"""
#TODO Catch possible exceptions: Repo not initialized
self.set_remote_url(target)
self.repo.git.push()
|
Fix following testing, add instructions for uploading | package com.google.cloud.pubsub.sql.providers;
import com.google.auto.service.AutoService;
import com.google.cloud.pubsub.sql.Rows;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
@AutoService({StandardSourceProvider.class, StandardSinkProvider.class})
public class PubsubLiteProvider implements StandardSourceProvider, StandardSinkProvider {
@Override
public StandardSink getSink() {
return new StandardSqlSink() {
@Override
public Schema nativeSchema() {
return Rows.STANDARD_SCHEMA;
}
@Override
public String query() {
return "SELECT * FROM PCOLLECTION";
}
};
}
private static final Schema READ_SCHEMA = Schema.builder()
.addByteArrayField(Rows.PAYLOAD_FIELD)
.addByteArrayField(Rows.MESSAGE_KEY_FIELD)
.addDateTimeField("publish_timestamp")
.addField(Rows.EVENT_TIMESTAMP_FIELD, FieldType.DATETIME.withNullable(true))
.addArrayField(Rows.ATTRIBUTES_FIELD, Schema.FieldType.row(Rows.ATTRIBUTES_ENTRY_SCHEMA))
.build();
@Override
public StandardSource getSource() {
return new StandardSqlSource() {
@Override
public String query() {
return "SELECT payload, message_key, attributes, IFNULL(event_timestamp, publish_timestamp) FROM PCOLLECTION";
}
@Override
public Schema nativeSchema() {
return READ_SCHEMA;
}
};
}
@Override
public String identifier() {
return "pubsublite";
}
}
| package com.google.cloud.pubsub.sql.providers;
import com.google.auto.service.AutoService;
import com.google.cloud.pubsub.sql.Rows;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
@AutoService({StandardSourceProvider.class, StandardSinkProvider.class})
public class PubsubLiteProvider implements StandardSourceProvider, StandardSinkProvider {
@Override
public StandardSink getSink() {
return new StandardSqlSink() {
@Override
public Schema nativeSchema() {
return Rows.STANDARD_SCHEMA;
}
@Override
public String query() {
return "SELECT * FROM PCOLLECTION";
}
};
}
private static final Schema READ_SCHEMA = Schema.builder()
.addByteArrayField(Rows.PAYLOAD_FIELD)
.addByteArrayField(Rows.MESSAGE_KEY_FIELD)
.addDateTimeField("publish_timestamp")
.addField(Rows.EVENT_TIMESTAMP_FIELD, FieldType.DATETIME.withNullable(true))
.addArrayField(Rows.ATTRIBUTES_FIELD, Schema.FieldType.row(Rows.ATTRIBUTES_ENTRY_SCHEMA))
.build();
@Override
public StandardSource getSource() {
return new StandardSqlSource() {
@Override
public String query() {
return "SELECT payload, message_key, attributes, IFNULL(event_timestamp, publish_timestamp) FROM PCOLLECTION";
}
@Override
public Schema nativeSchema() {
return READ_SCHEMA;
}
}; // Pub/Sub lite uses the standard schema.
}
@Override
public String identifier() {
return "pubsublite";
}
}
|
Fix removing the order of inventory | 'use strict';
angular.module('inventory.controllers')
.controller('OrderTableCtrl', ['$scope', 'orderService', 'formService',
function ($scope, orderService, formService) {
$scope.inventoryOrders = $scope.parts.inventoryOrders;
$scope.deliveredOrders = function (orders) {
return orderService.selectDelivered(orders);
};
$scope.isDelivered = function (order) {
return orderService.isDelivered(order.status);
};
$scope.openEditOrderForm = function (inventoryOrder) {
var modalInstance = null;
$scope.orderFormInputs = {
id: inventoryOrder.id,
statusChangedDate: new Date()
};
$scope.statusList = orderService.nextStatusList(inventoryOrder.status);
$scope.editOrder = function () {
orderService.edit($scope.orderFormInputs)
.then(function () {
$scope.reloadProduct();
modalInstance.close();
});
};
$scope.removeOrderAlert = function () {
var removeAlertInstance = null;
modalInstance.close();
$scope.removeAlertMessage = 'Are you sure to remove the order?';
$scope.removeAlertFunc = function () {
orderService.remove($scope.orderFormInputs.id)
.then(function () {
$scope.reloadProduct();
removeAlertInstance.close();
});
};
removeAlertInstance = formService.openRemoveAlert($scope);
};
modalInstance = formService.openForm({
templateUrl: '/views/inventories/modals/edit-order-form.html',
scope: $scope
});
};
}]);
| 'use strict';
angular.module('inventory.controllers')
.controller('OrderTableCtrl', ['$scope', 'orderService', 'formService',
function ($scope, orderService, formService) {
$scope.inventoryOrders = $scope.parts.inventoryOrders;
$scope.deliveredOrders = function (orders) {
return orderService.selectDelivered(orders);
};
$scope.isDelivered = function (order) {
return orderService.isDelivered(order.status);
};
$scope.openEditOrderForm = function (inventoryOrder) {
var modalInstance = null;
$scope.orderFormInputs = {
id: inventoryOrder.id,
statusChangedDate: new Date()
};
$scope.statusList = orderService.nextStatusList(inventoryOrder.status);
$scope.editOrder = function () {
orderService.edit($scope.orderFormInputs)
.then(function () {
$scope.reloadProduct();
modalInstance.close();
});
};
$scope.removeOrderAlert = function () {
var removeAlertInstance = null;
removeAlertInstance.close();
$scope.removeAlertMessage = 'Are you sure to remove the order?';
$scope.removeAlertFunc = function () {
orderService.remove($scope.orderFormInputs.id)
.then(function () {
$scope.reloadProduct();
removeAlertInstance.close();
});
};
modalInstance = formService.openRemoveAlert($scope);
};
modalInstance = formService.openForm({
templateUrl: '/views/inventories/modals/edit-order-form.html',
scope: $scope
});
};
}]);
|
Add a corrected spectral regridding function that smooths before interpolating to a new spectral axis | # Licensed under an MIT open source license - see LICENSE
import numpy as np
from astropy import units as u
from spectral_cube import SpectralCube
from astropy.convolution import Gaussian1DKernel
def spectral_regrid_cube(cube, channel_width):
fwhm_factor = np.sqrt(8 * np.log(2))
current_resolution = np.diff(cube.spectral_axis[:2])[0]
target_resolution = channel_width.to(current_resolution.unit)
diff_factor = np.abs(target_resolution / current_resolution).value
pixel_scale = np.abs(current_resolution)
gaussian_width = ((target_resolution**2 - current_resolution**2)**0.5 /
pixel_scale / fwhm_factor)
kernel = Gaussian1DKernel(gaussian_width)
new_cube = cube.spectral_smooth(kernel)
# Now define the new spectral axis at the new resolution
num_chan = int(np.floor_divide(cube.shape[0], diff_factor))
new_specaxis = np.linspace(cube.spectral_axis.min().value,
cube.spectral_axis.max().value,
num_chan) * current_resolution.unit
# Keep the same order (max to min or min to max)
if current_resolution.value < 0:
new_specaxis = new_specaxis[::-1]
return new_cube.spectral_interpolate(new_specaxis,
suppress_smooth_warning=True)
| # Licensed under an MIT open source license - see LICENSE
import numpy as np
def change_slice_thickness(cube, slice_thickness=1.0):
'''
Degrades the velocity resolution of a data cube. This is to avoid
shot noise by removing velocity fluctuations at small thicknesses.
Parameters
----------
cube : numpy.ndarray
3D data cube to degrade
slice_thickness : float, optional
Thicknesses of the new slices. Minimum is 1.0
Thickness must be integer multiple of the original cube size
Returns
-------
degraded_cube : numpy.ndarray
Data cube degraded to new slice thickness
'''
assert isinstance(slice_thickness, float)
if slice_thickness < 1:
slice_thickness == 1
print "Slice Thickness must be at least 1.0. Returning original cube."
if slice_thickness == 1:
return cube
if cube.shape[0] % slice_thickness != 0:
raise TypeError("Slice thickness must be integer multiple of dimension"
" size % s" % (cube.shape[0]))
slice_thickness = int(slice_thickness)
# Want to average over velocity channels
new_channel_indices = np.arange(0, cube.shape[0] / slice_thickness)
degraded_cube = np.ones(
(cube.shape[0] / slice_thickness, cube.shape[1], cube.shape[2]))
for channel in new_channel_indices:
old_index = int(channel * slice_thickness)
channel = int(channel)
degraded_cube[channel, :, :] = \
np.nanmean(cube[old_index:old_index + slice_thickness], axis=0)
return degraded_cube
|
Fix typo: route has been renamed, rename in config | <?php
/**
* ZfcAdmin Configuration
*
* If you have a ./config/autoload/ directory set up for your project, you can
* drop this config file in it and change the values as you wish.
*/
$settings = array(
/**
* Flag to use layout/admin as the admin layout
*
* The layout when ZfcAdmin is accessed will be set to an alternative layout,
* to distinguish the admin from the normal site. The layout is modified when
* the "admin" route or any subroute from "admin" is dispatched. Default is
* this setting true.
*
* Accepted is true or false
*/
//'use_admin_layout' => true,
/**
* Layout template for ZfcAdmin
*
* When use_admin_layout is set to true, this value will be used as template
* name for the admin layout. Default is 'layout/admin'
*
* Accepted is a string that resolves to a view script
*/
//'admin_layout_template' => 'layout/admin',
/**
* End of ZfcAdmin configuration
*/
);
/**
* You do not need to edit below this line
*/
return array(
'zfcadmin' => $settings,
'bjyauthorize' => array(
/* Enable Route Guard
*/
'guards' => array(
'BjyAuthorize\Guard\Route' => array(
array('route' => 'zfcadmin', 'roles' => array('admin')),
),
),
),
);
| <?php
/**
* ZfcAdmin Configuration
*
* If you have a ./config/autoload/ directory set up for your project, you can
* drop this config file in it and change the values as you wish.
*/
$settings = array(
/**
* Flag to use layout/admin as the admin layout
*
* The layout when ZfcAdmin is accessed will be set to an alternative layout,
* to distinguish the admin from the normal site. The layout is modified when
* the "admin" route or any subroute from "admin" is dispatched. Default is
* this setting true.
*
* Accepted is true or false
*/
//'use_admin_layout' => true,
/**
* Layout template for ZfcAdmin
*
* When use_admin_layout is set to true, this value will be used as template
* name for the admin layout. Default is 'layout/admin'
*
* Accepted is a string that resolves to a view script
*/
//'admin_layout_template' => 'layout/admin',
/**
* End of ZfcAdmin configuration
*/
);
/**
* You do not need to edit below this line
*/
return array(
'zfcadmin' => $settings,
'bjyauthorize' => array(
/* Enable Route Guard
*/
'guards' => array(
'BjyAuthorize\Guard\Route' => array(
array('route' => 'admin', 'roles' => array('admin')),
),
),
),
);
|
[CoreBundle] Update getEm function in the core controller to use the getDoctrine function instead | <?php
/*
* This file is part of the CSBillCoreBundle package.
*
* (c) Pierre du Plessis <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CSBill\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as Base;
abstract class BaseController extends Base
{
/**
* Return a instance of the doctrine entity manager
*
* @return \Doctrine\Common\Persistence\ObjectManager
*/
public function getEm()
{
return $this->getDoctrine()->getManager();
}
/**
* Get a doctrine repository
*
* @param string $repository
* @return \Doctrine\Common\Persistence\ObjectRepository
*/
public function getRepository($repository)
{
return $this->getEm()->getRepository($repository);
}
/**
* Adds a message to the session flash
*
* @param string $message The message to add to the session flash
* @param string $type The flash message type (notice, success, error etc)
*
* @return $this
*/
public function flash($message, $type = 'notice')
{
$this->get('session')->getFlashBag()->add($type, $message);
return $this;
}
/**
* Translates a message
*
* @param string $message
* @return string
*/
public function trans($message)
{
return $this->get('translator')->trans($message);
}
}
| <?php
/*
* This file is part of the CSBillCoreBundle package.
*
* (c) Pierre du Plessis <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CSBill\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller as Base;
abstract class BaseController extends Base
{
/**
* Return a instance of the doctrine entity manager
*
* @return \Doctrine\Common\Persistence\ObjectManager
*/
public function getEm()
{
return $this->get('doctrine')->getManager();
}
/**
* Get a doctrine repository
*
* @param string $repository
* @return \Doctrine\Common\Persistence\ObjectRepository
*/
public function getRepository($repository)
{
return $this->getEm()->getRepository($repository);
}
/**
* Adds a message to the session flash
*
* @param string $message The message to add to the session flash
* @param string $type The flash message type (notice, success, error etc)
*
* @return $this
*/
public function flash($message, $type = 'notice')
{
$this->get('session')->getFlashBag()->add($type, $message);
return $this;
}
/**
* Translates a message
*
* @param string $message
* @return string
*/
public function trans($message)
{
return $this->get('translator')->trans($message);
}
}
|
Tidy up layout and remove redundant code | from typing import Sequence
import pulp
def variables(events: Sequence, rooms: Sequence, slots: Sequence):
"""Defines the required instances of pulp.LpVariable
Parameters
----------
events : List or Tuple
of resources.Event
rooms : List or Tuple
of resources.Room
slots : List or Tuple
of resources.Slot
Returns
-------
dict
mapping an instance of resource.ScheduledItem to an instance of
pulp.LpVariable
"""
variables = {
(events.index(event), rooms.index(room), slots.index(slot)):
pulp.LpVariable(
f'{event.name}_{room.name}_slot_{slots.index(slot)}',
cat='Binary'
)
for event in events for room in rooms for slot in slots
}
return variables
def constraints(variables, events, rooms, slots):
constraints = []
# Each event should be scheduled once and once only
for event in events:
constraints.append(
sum(
variables[(
events.index(event),
rooms.index(room),
slots.index(slot)
)]
for room in rooms for slot in slots
) == 1
)
return constraints
| from typing import NamedTuple, Callable, List, Dict, Sequence
import pulp
from .resources import ScheduledItem
def variables(events: Sequence, rooms: Sequence, slots: Sequence):
"""Defines the required instances of pulp.LpVariable
Parameters
----------
events : List or Tuple
of resources.Event
rooms : List or Tuple
of resources.Room
slots : List or Tuple
of resources.Slot
Returns
-------
dict
mapping an instance of resource.ScheduledItem to an instance of
pulp.LpVariable
"""
variables = {
(events.index(event), rooms.index(room), slots.index(slot)):
pulp.LpVariable(
f'{event.name}_{room.name}_slot_{slots.index(slot)}',
cat='Binary'
)
for event in events for room in rooms for slot in slots
}
return variables
def constraints(variables, events, rooms, slots):
constraints = []
# Each event should be scheduled once and once only
for event in events:
constraints.append(
sum(
variables[(
events.index(event),
rooms.index(room),
slots.index(slot)
)]
for room in rooms for slot in slots
) == 1
)
return constraints
class Constraint(NamedTuple):
function: Callable
args: List
kwargs: Dict
operator: Callable
value: int
|
Fix XHR login on Firebase hosting | import { ValidationError } from '../lib/validation';
export const LOGIN_ERROR = 'LOGIN_ERROR';
export const LOGIN_START = 'LOGIN_START';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGOUT = 'LOGOUT';
export function login(fields) {
return ({ fetch, validate }) => {
const getPromise = async () => {
try {
await validate(fields)
.prop('email').required().email()
.prop('password').required().simplePassword()
.promise;
// Simulate response for server-less (Firebase hosting) example.
if (process.env.IS_SERVERLESS) {
return {
email: fields.email,
id: Date.now()
};
}
// Sure we can use smarter api than raw fetch.
const response = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(fields)
});
if (response.status !== 200) throw response;
// Return JSON response.
return response.json();
} catch (error) {
// Transform error status to custom error.
if (error.status === 401) {
throw new ValidationError('wrongPassword', { prop: 'password' });
}
throw error;
}
};
return {
type: 'LOGIN',
payload: {
promise: getPromise()
}
};
};
}
export function logout() {
return ({ engine, firebase }) => {
engine.save({});
firebase.unauth();
return {
type: LOGOUT
};
};
}
| import { ValidationError } from '../lib/validation';
export const LOGIN_ERROR = 'LOGIN_ERROR';
export const LOGIN_START = 'LOGIN_START';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGOUT = 'LOGOUT';
export function login(fields) {
return ({ fetch, validate }) => {
const getPromise = async () => {
try {
await validate(fields)
.prop('email').required().email()
.prop('password').required().simplePassword()
.promise;
// Sure we can use smarter api than raw fetch.
const response = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(fields)
});
if (response.status !== 200) throw response;
// Return JSON response.
return response.json();
} catch (error) {
// Transform error status to custom error.
if (error.status === 401) {
throw new ValidationError('wrongPassword', { prop: 'password' });
}
throw error;
}
};
return {
type: 'LOGIN',
payload: {
promise: getPromise()
}
};
};
}
export function logout() {
return ({ engine, firebase }) => {
engine.save({});
firebase.unauth();
return {
type: LOGOUT
};
};
}
|
OEE-1073: Create field in Multicurrency for fixed rate
- add field to entity
- add migration | <?php
namespace Oro\Bundle\CurrencyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Oro\Bundle\DataAuditBundle\Metadata\Annotation as Oro;
class MultiCurrency
{
use CurrencyAwareTrait;
protected $value;
protected $rate;
protected $baseCurrencyValue;
/**
* @param string $value
* @param string $currency
* @param float $rate | null
* @return MultiCurrency
*/
public static function create($value, $currency, $rate = null)
{
/* @var $multiCurrency self */
$multiCurrency = new static();
$multiCurrency->setValue($value)
->setCurrency($currency)
->setRate($rate);
return $multiCurrency;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* @param string $value
* @return $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* @return float
*/
public function getRate()
{
return $this->rate;
}
/**
* @param float $rate
* @return $this
*/
public function setRate($rate)
{
$this->rate = $rate;
return $this;
}
/**
* @return mixed
*/
public function getBaseCurrencyValue()
{
return $this->baseCurrencyValue;
}
/**
* @param $baseCurrencyValue
* @return $this
*/
public function setBaseCurrencyValue($baseCurrencyValue)
{
$this->baseCurrencyValue = $baseCurrencyValue;
return $this;
}
}
| <?php
namespace Oro\Bundle\CurrencyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Oro\Bundle\DataAuditBundle\Metadata\Annotation as Oro;
class MultiCurrency
{
use CurrencyAwareTrait;
protected $value;
protected $rate;
/**
* @param string $value
* @param string $currency
* @param float $rate | null
* @return MultiCurrency
*/
public static function create($value, $currency, $rate = null)
{
/* @var $multiCurrency self */
$multiCurrency = new static();
$multiCurrency->setValue($value)
->setCurrency($currency)
->setRate($rate);
return $multiCurrency;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* @param string $value
* @return $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* @return float
*/
public function getRate()
{
return $this->rate;
}
/**
* @param float $rate
* @return $this
*/
public function setRate($rate)
{
$this->rate = $rate;
return $this;
}
}
|
Fix a bug that we didn't properly close our physical connections. | package net.nanopool;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import net.nanopool.cas.CasArray;
public class Connector {
private final ConnectionPoolDataSource source;
private final CasArray<Connector> connectors;
private final int idx;
private final long timeToLive;
private PooledConnection connection;
private long deadTime;
public Connector(ConnectionPoolDataSource source,
CasArray<Connector> connectors, int idx, long timeToLive) {
this.source = source;
this.connectors = connectors;
this.idx = idx;
this.timeToLive = timeToLive;
}
Connector() {
this(null, null, 0, 0);
}
public Connection getConnection() throws SQLException {
long now = System.currentTimeMillis();
if (deadTime < now) {
PooledConnection con = connection;
connection = null;
con.close();
}
if (connection == null) {
connection = source.getPooledConnection();
connection.addConnectionEventListener(new ConnectionListener(this));
deadTime = now + timeToLive;
}
return connection.getConnection();
}
public void returnToPool() {
Connector ticket = connectors.get(idx);
connectors.cas(idx, this, ticket);
}
public void invalidate() {
connection = null;
}
}
| package net.nanopool;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import net.nanopool.cas.CasArray;
public class Connector {
private final ConnectionPoolDataSource source;
private final CasArray<Connector> connectors;
private final int idx;
private final long timeToLive;
private PooledConnection connection;
private long deadTime;
public Connector(ConnectionPoolDataSource source,
CasArray<Connector> connectors, int idx, long timeToLive) {
this.source = source;
this.connectors = connectors;
this.idx = idx;
this.timeToLive = timeToLive;
}
Connector() {
this(null, null, 0, 0);
}
public Connection getConnection() throws SQLException {
long now = System.currentTimeMillis();
if (deadTime < now)
connection = null;
if (connection == null) {
connection = source.getPooledConnection();
connection.addConnectionEventListener(new ConnectionListener(this));
deadTime = now + timeToLive;
}
return connection.getConnection();
}
public void returnToPool() {
Connector ticket = connectors.get(idx);
connectors.cas(idx, this, ticket);
}
public void invalidate() {
connection = null;
}
}
|
Fix LAG Admin extension test | <?php
namespace LAG\AdminBundle\Tests\DependencyInjection;
use LAG\AdminBundle\DependencyInjection\LAGAdminExtension;
use LAG\AdminBundle\Tests\AdminTestBase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class LAGAdminExtensionTest extends AdminTestBase
{
/**
* The load should allow the container to compile without errors.
*/
public function testLoad()
{
$builder = $this->getMockWithoutConstructor(ContainerBuilder::class);
$builder
->expects($this->atLeastOnce())
->method('setParameter')
->willReturnCallback(function ($parameter, $value) {
$this->assertContains($parameter, [
'lag.admin.enable_extra_configuration',
'lag.admin.application_configuration',
'lag.admins',
'lag.menus',
]);
if ('lag.admin.enable_extra_configuration' === $parameter) {
$this->assertContains($value, [
true,
]);
}
})
;
$extension = new LAGAdminExtension();
$extension->load([
'enable_extra_configuration' => true,
], $builder);
}
/**
* The load should allow the container to compile without errors.
*/
public function testLoadWithoutConfiguration()
{
$builder = $this->getMockWithoutConstructor(ContainerBuilder::class);
$extension = new LAGAdminExtension();
$extension->load([], $builder);
// Every thing went fine
$this->assertTrue(true);
}
}
| <?php
namespace LAG\AdminBundle\Tests\DependencyInjection;
use LAG\AdminBundle\DependencyInjection\LAGAdminExtension;
use LAG\AdminBundle\Tests\AdminTestBase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class LAGAdminExtensionTest extends AdminTestBase
{
/**
* The load should allow the container to compile without errors.
*/
public function testLoad()
{
$builder = $this->getMockWithoutConstructor(ContainerBuilder::class);
$builder
->expects($this->exactly(3))
->method('setParameter')
->willReturnCallback(function ($parameter, $value) {
$this->assertContains($parameter, [
'lag.admin.enable_extra_configuration',
'lag.admin.application_configuration',
'lag.admins',
]);
if ('lag.admin.enable_extra_configuration' === $parameter) {
$this->assertContains($value, [
true,
]);
}
})
;
$extension = new LAGAdminExtension();
$extension->load([
'enable_extra_configuration' => true,
], $builder);
}
/**
* The load should allow the container to compile without errors.
*/
public function testLoadWithoutConfiguration()
{
$builder = $this->getMockWithoutConstructor(ContainerBuilder::class);
$extension = new LAGAdminExtension();
$extension->load([], $builder);
// Every thing went fine
$this->assertTrue(true);
}
}
|
Switch to using a button group for the context selector. | import React from "react"
import { Button, ButtonGroup, NavItem, Collapse } from "react-bootstrap"
export default React.createClass({
getInitialState: function() {
return {}
},
render: function() {
var { title, ...other } = this.props;
return (
<NavItem {...other}>
<span>
{ this.props.title }
</span>
<Collapse in={this.props.active}>
<div>
<ButtonGroup vertical block>
<Button bsStyle="info">
Thread 1 - src/main.c:1234
</Button>
<Button>
Thread 2 - src/events.c:120
</Button>
</ButtonGroup>
</div>
</Collapse>
</NavItem>
);
}
});
| import React from "react"
import { Nav, NavItem, Collapse } from "react-bootstrap"
var threadNavStyle = {
backgroundColor: 'rgb(220, 220, 220)',
color: 'black'
};
export default React.createClass({
getInitialState: function() {
return {}
},
render: function() {
var { title, ...other } = this.props;
return (
<NavItem {...other}>
<span>
{ this.props.title }
</span>
<Collapse in={this.props.active}>
<div>
<Nav bsStyle="link" activeKey={1} style={threadNavStyle}>
<NavItem eventKey={1}>
Thread 1 - src/main.c:1234
</NavItem>
<NavItem eventKey={2}>
Thread 2 - src/events.c:120
</NavItem>
</Nav>
</div>
</Collapse>
</NavItem>
);
}
});
|
Set local worker as default for SyftTensor owner | import random
from syft.frameworks.torch.tensors import PointerTensor
import syft
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = syft.local_worker
def create_pointer(
self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None
):
if owner is None:
owner = self.owner
if location is None:
location = self.owner.id
owner = self.owner.get_worker(owner)
location = self.owner.get_worker(location)
if id_at_location is None:
id_at_location = self.id
if ptr_id is None:
if location != self.owner.id:
ptr_id = self.id
else:
ptr_id = int(10e10 * random.random())
# previous_pointer = owner.get_pointer_to(location, id_at_location)
previous_pointer = None
if previous_pointer is None:
ptr = PointerTensor(
parent=self,
location=location,
id_at_location=id_at_location,
register=register,
owner=owner,
id=ptr_id,
)
else:
ptr = previous_pointer
return ptr
| import random
from syft.frameworks.torch.tensors import PointerTensor
class TorchTensor:
"""
This tensor is simply a more convenient way to add custom functions to
all Torch tensor types.
"""
def __init__(self):
self.id = None
self.owner = None
def create_pointer(
self, location=None, id_at_location=None, register=False, owner=None, ptr_id=None
):
if owner is None:
owner = self.owner
if location is None:
location = self.owner.id
owner = self.owner.get_worker(owner)
location = self.owner.get_worker(location)
if id_at_location is None:
id_at_location = self.id
if ptr_id is None:
if location != self.owner.id:
ptr_id = self.id
else:
ptr_id = int(10e10 * random.random())
# previous_pointer = owner.get_pointer_to(location, id_at_location)
previous_pointer = None
if previous_pointer is None:
ptr = PointerTensor(
parent=self,
location=location,
id_at_location=id_at_location,
register=register,
owner=owner,
id=ptr_id,
)
else:
ptr = previous_pointer
return ptr
|
Disable `console` warnings for test harness | 'use strict';
/* eslint-disable no-console */
const { EventEmitter } = require('events');
const { Server } = require('http');
const handler = require('serve-handler');
const childProcess = require('child_process');
const sauceConnect = require('sauce-connect-launcher');
EventEmitter.defaultMaxListeners = 0;
const port = Number(process.env.npm_package_config_port);
const server = new Server((request, response) => {
handler(request, response, {
public: 'dist',
directoryListing: false,
});
});
let sauceProcess;
module.exports = {
asyncHookTimeout: 60000,
isSauce: true,
'chrome-local': {
isSauce: false,
},
before(done) {
childProcess.execSync('npm run build');
server.listen(port, () => {
if (this.isSauce && !process.env.TRAVIS) {
console.log('Starting Sauce Connect proxy...');
sauceConnect((err, res) => {
if (err) {
console.error(err.message);
} else {
sauceProcess = res;
done();
}
});
} else {
done();
}
});
},
after(done) {
server.close(() => {
if (sauceProcess) {
sauceProcess.close(done);
} else {
done();
}
});
},
};
| 'use strict';
const { EventEmitter } = require('events');
const { Server } = require('http');
const handler = require('serve-handler');
const childProcess = require('child_process');
const sauceConnect = require('sauce-connect-launcher');
EventEmitter.defaultMaxListeners = 0;
const port = Number(process.env.npm_package_config_port);
const server = new Server((request, response) => {
handler(request, response, {
public: 'dist',
directoryListing: false,
});
});
let sauceProcess;
module.exports = {
asyncHookTimeout: 60000,
isSauce: true,
'chrome-local': {
isSauce: false,
},
before(done) {
childProcess.execSync('npm run build');
server.listen(port, () => {
if (this.isSauce && !process.env.TRAVIS) {
console.log('Starting Sauce Connect proxy...');
sauceConnect((err, res) => {
if (err) {
console.error(err.message);
} else {
sauceProcess = res;
done();
}
});
} else {
done();
}
});
},
after(done) {
server.close(() => {
if (sauceProcess) {
sauceProcess.close(done);
} else {
done();
}
});
},
};
|
Make sure HH:MM values are allowed | import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
'10:00',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
| import datetime
import time
from graphite_api.render.attime import parseATTime
from . import TestCase
class AtTestCase(TestCase):
def test_parse(self):
for value in [
str(int(time.time())),
'20140319',
'20130319+1y',
'20130319+1mon',
'20130319+1w',
'12:12_20130319',
'3:05am_20130319',
'3:05pm_20130319',
'noon20130319',
'midnight20130319',
'teatime20130319',
'yesterday',
'tomorrow',
'03/19/2014',
'03/19/1800',
'03/19/1950',
'feb 27',
'mar 5',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
'sun',
]:
self.assertIsInstance(parseATTime(value), datetime.datetime)
for value in [
'20130319+1foo',
'mar',
'wat',
]:
with self.assertRaises(Exception):
parseATTime(value)
|
Fix parse refactor - this passed to the plugin manager must be less | var PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise;
module.exports = function(environment, ParseTree, ImportManager) {
var render = function (input, options, callback) {
if (typeof(options) === 'function') {
callback = options;
options = {};
}
if (!callback) {
var self = this;
return new PromiseConstructor(function (resolve, reject) {
render.call(self, input, options, function(err, output) {
if (err) {
reject(err);
} else {
resolve(output);
}
});
});
} else {
this.parse(input, options, function(err, root, imports, options) {
if (err) { return callback(err); }
var result;
try {
var parseTree = new ParseTree(root, imports);
result = parseTree.toCSS(options);
}
catch (err) { return callback(err); }
callback(null, result);
});
}
};
return render;
};
| var PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise;
module.exports = function(environment, ParseTree, ImportManager) {
var render = function (input, options, callback) {
var parse = require('./parse')(environment, ParseTree, ImportManager);
if (typeof(options) === 'function') {
callback = options;
options = {};
}
if (!callback) {
var self = this;
return new PromiseConstructor(function (resolve, reject) {
render.call(self, input, options, function(err, output) {
if (err) {
reject(err);
} else {
resolve(output);
}
});
});
} else {
parse(input, options, function(err, root, imports, options) {
if (err) { return callback(err); }
var result;
try {
var parseTree = new ParseTree(root, imports);
result = parseTree.toCSS(options);
}
catch (err) { return callback(err); }
callback(null, result);
});
}
};
return render;
};
|
Refactor to change the comparator of dict | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = message
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/recommender/', methods=['POST'])
def recommender():
content = request.get_json()
if content is not None:
doc = content.get('doc', {})
docs = content.get('docs', [])
_verify_parameters(doc, docs)
result = recommend(doc, docs)
return jsonify(result)
else:
msg = 'You need to send the parameters: doc and docs'
raise InvalidUsage(msg)
def _verify_parameters(doc, docs):
if bool(doc) is False:
msg = 'The parameter `doc` is missing or empty'
raise InvalidUsage(msg)
if not isinstance(doc, dict):
msg = 'The parameter `doc` should be a dict'
raise InvalidUsage(msg)
if len(docs) == 0:
msg = 'The parameter `docs` is missing or empty'
raise InvalidUsage(msg)
| from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = message
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/recommender/', methods=['POST'])
def recommender():
content = request.get_json()
if content is not None:
doc = content.get('doc', {})
docs = content.get('docs', [])
_verify_parameters(doc, docs)
result = recommend(doc, docs)
return jsonify(result)
else:
msg = 'You need to send the parameters: doc and docs'
raise InvalidUsage(msg)
def _verify_parameters(doc, docs):
if doc == {}:
msg = 'The parameter `doc` is missing or empty'
raise InvalidUsage(msg)
if not isinstance(doc, dict):
msg = 'The parameter `doc` should be a dict'
raise InvalidUsage(msg)
if len(docs) == 0:
msg = 'The parameter `docs` is missing or empty'
raise InvalidUsage(msg)
|
Add automatic upgrade portal url from http to https where appropriate
Adding an upgrade of portal urls from http to https in the url
validation check whenever the hosting ArcGIS Online Assistant is hosted
on https. | define(["jquery"], function(jquery) {
return {
// Convert an array to a comma separated string.
arrayToString: function(array) {
var arrayString;
jquery.each(array, function(index, arrayValue) {
if (index === 0) {
arrayString = arrayValue;
} else if (index > 0) {
arrayString = arrayString + "," + arrayValue;
}
});
return arrayString;
},
// Clean up common issues with user entered portal URLs.
fixUrl: function(portalUrl) {
var deferred = jquery.Deferred();
if (portalUrl === "") {
// Default to ArcGIS Online.
portalUrl = "https://www.arcgis.com/";
} else if (portalUrl.search("/home/") > 0) {
// Strip the /home endpoint.
portalUrl = portalUrl.
substr(0, portalUrl.search("/home/")) + "/";
} else if (portalUrl.search("/sharing/") > 0) {
// Strip the /sharing endpoint.
portalUrl = portalUrl.
substr(0, portalUrl.search("/sharing/")) + "/";
} else if (portalUrl.charAt(portalUrl.length - 1) !== "/") {
// Add the trailing slash.
portalUrl = portalUrl + "/";
}
if (portalUrl.indexOf("http://") === 0 && window.location.href.indexOf("https://") === 0) {
portalUrl = portalUrl.replace("http://", "https://");
}
deferred.resolve(portalUrl);
return deferred.promise();
}
};
});
| define(["jquery"], function(jquery) {
return {
// Convert an array to a comma separated string.
arrayToString: function(array) {
var arrayString;
jquery.each(array, function(index, arrayValue) {
if (index === 0) {
arrayString = arrayValue;
} else if (index > 0) {
arrayString = arrayString + "," + arrayValue;
}
});
return arrayString;
},
// Clean up common issues with user entered portal URLs.
fixUrl: function(portalUrl) {
var deferred = jquery.Deferred();
if (portalUrl === "") {
// Default to ArcGIS Online.
portalUrl = "https://www.arcgis.com/";
} else if (portalUrl.search("/home/") > 0) {
// Strip the /home endpoint.
portalUrl = portalUrl.
substr(0, portalUrl.search("/home/")) + "/";
} else if (portalUrl.search("/sharing/") > 0) {
// Strip the /sharing endpoint.
portalUrl = portalUrl.
substr(0, portalUrl.search("/sharing/")) + "/";
} else if (portalUrl.charAt(portalUrl.length - 1) !== "/") {
// Add the trailing slash.
portalUrl = portalUrl + "/";
}
deferred.resolve(portalUrl);
return deferred.promise();
}
};
});
|
[Android] Destroy containes when they are not visible
Whatever I've tried so far ends up failing in really weird ways, so let's admit
defeat, for now. Destroy containers only on Android.
This shall be revisited when we update RN to version >= 0.43 and we have
"display: 'none'" available. | /* @flow */
import React from 'react';
import {
TouchableHighlight,
TouchableWithoutFeedback,
View
} from 'react-native';
import { Platform } from '../../';
import AbstractContainer from '../AbstractContainer';
/**
* Represents a container of React Native/mobile {@link Component} children.
*
* @extends AbstractContainer
*/
export default class Container extends AbstractContainer {
/**
* {@code Container} component's property types.
*
* @static
*/
static propTypes = AbstractContainer.propTypes;
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
onClick,
touchFeedback = onClick,
visible = true,
...props
} = this.props;
// visible
if (!visible) {
// FIXME: Whatever I try ends up failing somehow on Android, give up
// for now, hoping display: 'none' solves this.
if (Platform.OS === 'android') {
return null;
}
// Intentionally hide this Container without destroying it.
// TODO Replace with display: 'none' supported in RN >= 0.43.
props.style = {
...props.style,
height: 0,
width: 0
};
}
let element = super._render(View, props);
// onClick & touchFeedback
if (visible && (onClick || touchFeedback)) {
element = React.createElement(
touchFeedback ? TouchableHighlight : TouchableWithoutFeedback,
{ onPress: onClick },
element
);
}
return element;
}
}
| /* @flow */
import React from 'react';
import {
TouchableHighlight,
TouchableWithoutFeedback,
View
} from 'react-native';
import AbstractContainer from '../AbstractContainer';
/**
* Represents a container of React Native/mobile {@link Component} children.
*
* @extends AbstractContainer
*/
export default class Container extends AbstractContainer {
/**
* {@code Container} component's property types.
*
* @static
*/
static propTypes = AbstractContainer.propTypes;
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
onClick,
touchFeedback = onClick,
visible = true,
...props
} = this.props;
// visible
if (!visible) {
// Intentionally hide this Container without destroying it.
// TODO Replace with display: 'none' supported in RN >= 0.43.
props.style = {
...props.style,
height: 0,
width: 0
};
}
let element = super._render(View, props);
// onClick & touchFeedback
if (visible && (onClick || touchFeedback)) {
element = React.createElement(
touchFeedback ? TouchableHighlight : TouchableWithoutFeedback,
{ onPress: onClick },
element
);
}
return element;
}
}
|
Change global in btoa segment to refer to exports instead of this for consistency (and so it works on Titanium android) | (function (global) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
/**
* Base64 encode a string
* @param string {string} the string to be base64 encoded
*/
global.btoa = global.btoa || function (string) {
var i = 0, length = string.length, ascii, index, output = '';
for (; i < length; i+=3) {
ascii = [
string.charCodeAt(i),
string.charCodeAt(i+1),
string.charCodeAt(i+2)
];
index = [
ascii[0] >> 2,
((ascii[0] & 3) << 4) | ascii[1] >> 4,
((ascii[1] & 15) << 2) | ascii[2] >> 6,
ascii[2] & 63
];
if (isNaN(ascii[1])) {
index[2] = 64;
}
if (isNaN(ascii[2])) {
index[3] = 64;
}
output += b64.charAt(index[0]) + b64.charAt(index[1]) + b64.charAt(index[2]) + b64.charAt(index[3]);
}
return output;
};
})(exports);
| (function (global) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
/**
* Base64 encode a string
* @param string {string} the string to be base64 encoded
*/
global.btoa = global.btoa || function (string) {
var i = 0, length = string.length, ascii, index, output = '';
for (; i < length; i+=3) {
ascii = [
string.charCodeAt(i),
string.charCodeAt(i+1),
string.charCodeAt(i+2)
];
index = [
ascii[0] >> 2,
((ascii[0] & 3) << 4) | ascii[1] >> 4,
((ascii[1] & 15) << 2) | ascii[2] >> 6,
ascii[2] & 63
];
if (isNaN(ascii[1])) {
index[2] = 64;
}
if (isNaN(ascii[2])) {
index[3] = 64;
}
output += b64.charAt(index[0]) + b64.charAt(index[1]) + b64.charAt(index[2]) + b64.charAt(index[3]);
}
return output;
};
})(this);
|
Use the latest version of openstax-accounts | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.6',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='[email protected]',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='[email protected]',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
|
Fix bug with Markdown Previewer where it wouldn't load up correct data initially | (function( $ ) {
$.fn.markdownPreview = function( options ) {
var settings = {
'insert-preview-div': true,
'location': 'below',
'preview-class-name': 'preview',
'preview-element': null
};
if( options ) {
$.extend( settings, options );
}
return this.each(function() {
if(!settings['insert-preview-div'] && $(settings['preview-element']).length == 0) {
throw "Either insert preview div should be set to true or an existing preview element needs to be provided";
}
$this = $(this);
var previewElement = $(settings['preview-element']);
if(settings['insert-preview-div']) {
var previewElementHtml = '<div class="' + settings['preview-class-name'] + '" />';
switch(settings['location']) {
case 'below':
$this.after(previewElementHtml);
previewElement = $this.next();
break;
case 'above':
$this.before(previewElementHtml);
previewElement = $this.prev();
break;
default:
throw settings['location'] + " is not a valid option for location";
}
}
var converter = new Showdown.converter();
var updatePreview = function() {
if(this.nodeName !== undefined) {
previewElement.html(converter.makeHtml($(this).val()));
} else {
previewElement.html(converter.makeHtml($this.val()));
}
};
updatePreview();
$this.bind('keyup.markdown-preview', updatePreview);
$this.bind('change.markdown-preview', updatePreview);
});
};
})( jQuery );
| (function( $ ) {
$.fn.markdownPreview = function( options ) {
var settings = {
'insert-preview-div': true,
'location': 'below',
'preview-class-name': 'preview',
'preview-element': null
};
if( options ) {
$.extend( settings, options );
}
return this.each(function() {
if(!settings['insert-preview-div'] && $(settings['preview-element']).length == 0) {
throw "Either insert preview div should be set to true or an existing preview element needs to be provided";
}
$this = $(this);
var previewElement = $(settings['preview-element']);
if(settings['insert-preview-div']) {
var previewElementHtml = '<div class="' + settings['preview-class-name'] + '" />';
switch(settings['location']) {
case 'below':
$this.after(previewElementHtml);
previewElement = $this.next();
break;
case 'above':
$this.before(previewElementHtml);
previewElement = $this.prev();
break;
default:
throw settings['location'] + " is not a valid option for location";
}
}
var converter = new Showdown.converter();
var updatePreview = function() {
previewElement.html(converter.makeHtml($(this).val()));
};
updatePreview();
$this.bind('keyup.markdown-preview', updatePreview);
$this.bind('change.markdown-preview', updatePreview);
});
};
})( jQuery );
|
Use regular send() instead of our writev()
Buffering is apparently more rewarding performance-wise than using
zero-copy vectorised I/O ala writev(), hence there's no point to keep
using our homemade write() extension. | # -*- coding: utf-8 -*-
import errno
import collections
from savate import writev
# FIXME: should this be a method of BufferEvent below ?
# FIXME: handle Python2.x/Python3k compat here
def buffer_slice(buff, offset, size):
return buffer(buff, offset, size)
class BufferOutputHandler(object):
def __init__(self, sock, initial_buffer_queue = ()):
self.sock = sock
self.ready = True
self.buffer_queue = collections.deque(initial_buffer_queue)
def add_buffer(self, buff):
self.buffer_queue.append(buff)
def empty(self):
return len(self.buffer_queue) == 0
def flush(self):
self.ready = True
total_sent_bytes = 0
try:
while self.buffer_queue:
sent_bytes = self.sock.send(self.buffer_queue[0])
total_sent_bytes += sent_bytes
if sent_bytes < len(self.buffer_queue[0]):
# One of the buffers was partially sent
self.buffer_queue[0] = self.buffer_queue[0][sent_bytes:]
else:
self.buffer_queue.popleft()
except IOError, exc:
if exc.errno == errno.EAGAIN:
self.ready = False
else:
raise
return total_sent_bytes
| # -*- coding: utf-8 -*-
import errno
import collections
from savate import writev
# FIXME: should this be a method of BufferEvent below ?
# FIXME: handle Python2.x/Python3k compat here
def buffer_slice(buff, offset, size):
return buffer(buff, offset, size)
class BufferOutputHandler(object):
def __init__(self, sock, initial_buffer_queue = ()):
self.sock = sock
self.ready = True
self.buffer_queue = collections.deque(initial_buffer_queue)
def add_buffer(self, buff):
self.buffer_queue.append(buff)
def empty(self):
return len(self.buffer_queue) == 0
def flush(self):
self.ready = True
total_sent_bytes = 0
try:
while self.buffer_queue:
sent_bytes = writev.writev(self.sock.fileno(),
self.buffer_queue)
total_sent_bytes += sent_bytes
while (self.buffer_queue and sent_bytes and
len(self.buffer_queue[0]) <= sent_bytes):
sent_bytes -= len(self.buffer_queue.popleft())
if sent_bytes:
# One of the buffers was partially sent
self.buffer_queue[0] = self.buffer_queue[0][sent_bytes:]
except IOError, exc:
if exc.errno == errno.EAGAIN:
self.ready = False
else:
raise
return total_sent_bytes
|
Add colour map by type | 'use strict';
angular.module('interfaceApp')
.constant('configuration', {
'development': 'https://service.esrc.info',
'production': 'https://cnex.esrc.unimelb.edu.au',
'service': 'development',
'solr': 'https://solr.esrc.unimelb.edu.au/ESRC/select',
'colours': {
'person': '#d62728',
'corporatebody': '#ffbb78',
'event': '#1f77b4',
'concept': '#aec7e8',
'place': '#ff9896',
'culturalartefact': '#9467bd',
'published': '#98df8a',
'archival': '#2ca02c',
'digitalObject': '#ff7f0e'
},
'fill': {
'contextNode': 'green',
'contextNeighbourDefault': 'orange',
'contextNeighbourHighlight': 'red',
'default': '#c8c8c8'
},
'opacity': {
'default': '1',
'unselected': '0.3'
},
'stroke': {
'link': {
'selected': 'orange',
'unselected': '#c8c8c8'
},
'date': {
'selected': 'black',
'unselected': '#c8c8c8'
}
},
'height': {
'selected': '10',
'default': '3'
},
'radius': {
'node': {
'selected': '30',
'unselected': '10'
},
'date': {
'selected': '6',
'default': '3'
}
}
});
| 'use strict';
angular.module('interfaceApp')
.constant('configuration', {
'development': 'https://service.esrc.info',
'production': 'https://cnex.esrc.unimelb.edu.au',
'service': 'development',
'solr': 'https://solr.esrc.unimelb.edu.au/ESRC/select',
'fill': {
'contextNode': 'green',
'contextNeighbourDefault': 'orange',
'contextNeighbourHighlight': 'red',
'default': '#c8c8c8'
},
'opacity': {
'default': '1',
'unselected': '0.5'
},
'stroke': {
'link': {
'selected': 'orange',
'unselected': '#c8c8c8'
},
'date': {
'selected': 'black',
'unselected': '#c8c8c8'
}
},
'height': {
'selected': '10',
'default': '3'
},
'radius': {
'node': {
'selected': '30',
'unselected': '10'
},
'date': {
'selected': '6',
'default': '3'
}
}
});
|
Enable to call gc() in performance tests of BlinkGC.
In case of GCController cannot be used.
BUG=465997,457982,438074
TEST=./tools/perf/run_benchmark run oilpan_gc_times.blink_perf_stress --browser=content-shell-release
Review URL: https://codereview.chromium.org/971683002
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@191755 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | if (!window.PerfTestRunner)
console.log("measure-gc.js requires PerformanceTests/resources/runner.js to be loaded.");
if (!window.internals)
console.log("measure-gc.js requires window.internals.");
if (!window.GCController && !window.gc)
console.log("measure-gc.js requires GCController or exposed gc().");
(function (PerfTestRunner) {
PerfTestRunner.measureBlinkGCTime = function(test) {
if (!test.unit)
test.unit = 'ms';
if (!test.warmUpCount)
test.warmUpCount = 3;
PerfTestRunner.prepareToMeasureValuesAsync(test);
// Force a V8 GC before running Blink GC test to avoid measuring marking from stale V8 wrappers.
if (window.GCController)
GCController.collectAll();
else if (window.gc) {
for (var i = 0; i < 7; i++)
gc();
}
setTimeout(runTest, 0);
}
var NumberOfGCRunsPerForceBlinkGC = 5;
function runTest() {
// forceBlinkGCWithoutV8GC will schedule 5 Blink GCs at the end of event loop.
// setTimeout function runs on next event loop, so assuming that event loop is not busy,
// we can estimate GC time by measuring the delay of setTimeout function.
internals.forceBlinkGCWithoutV8GC();
var start = PerfTestRunner.now();
setTimeout(function() {
var end = PerfTestRunner.now();
PerfTestRunner.measureValueAsync((end - start) / NumberOfGCRunsPerForceBlinkGC);
setTimeout(runTest, 0);
}, 0);
}
})(window.PerfTestRunner);
| if (!window.PerfTestRunner)
console.log("measure-gc.js requires PerformanceTests/resources/runner.js to be loaded.");
if (!window.internals)
console.log("measure-gc.js requires window.internals.");
if (!window.GCController)
console.log("measure-gc.js requires GCController.");
(function (PerfTestRunner) {
PerfTestRunner.measureBlinkGCTime = function(test) {
if (!test.unit)
test.unit = 'ms';
if (!test.warmUpCount)
test.warmUpCount = 3;
PerfTestRunner.prepareToMeasureValuesAsync(test);
// Force a V8 GC before running Blink GC test to avoid measuring marking from stale V8 wrappers.
GCController.collectAll();
setTimeout(runTest, 0);
}
var NumberOfGCRunsPerForceBlinkGC = 5;
function runTest() {
// forceBlinkGCWithoutV8GC will schedule 5 Blink GCs at the end of event loop.
// setTimeout function runs on next event loop, so assuming that event loop is not busy,
// we can estimate GC time by measuring the delay of setTimeout function.
internals.forceBlinkGCWithoutV8GC();
var start = PerfTestRunner.now();
setTimeout(function() {
var end = PerfTestRunner.now();
PerfTestRunner.measureValueAsync((end - start) / NumberOfGCRunsPerForceBlinkGC);
setTimeout(runTest, 0);
}, 0);
}
})(window.PerfTestRunner);
|
Increase Nightwatch.js check_process_delay to 5 seconds | var seleniumServer = require('selenium-server');
var chromedriver = require('chromedriver');
var geckodriver = require('geckodriver');
module.exports = {
src_folders: ['tests'],
selenium: {
start_process: true,
server_path: seleniumServer.path,
port: 4444,
cli_args: {
'webdriver.chrome.driver': chromedriver.path,
'webdriver.gecko.driver': geckodriver.path,
},
check_process_delay: 5000,
},
test_settings: {
'chrome': {
desiredCapabilities: {
browserName: 'chrome',
},
},
'chrome-headless': {
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
'--headless',
'--no-sandbox',
'--disable-gpu',
],
},
},
},
'firefox': {
desiredCapabilities: {
browserName: 'firefox',
},
},
'firefox-headless': {
desiredCapabilities: {
browserName: 'firefox',
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
},
},
};
| var seleniumServer = require('selenium-server');
var chromedriver = require('chromedriver');
var geckodriver = require('geckodriver');
module.exports = {
src_folders: ['tests'],
selenium: {
start_process: true,
server_path: seleniumServer.path,
port: 4444,
cli_args: {
'webdriver.chrome.driver': chromedriver.path,
'webdriver.gecko.driver': geckodriver.path,
},
check_process_delay: 1000,
},
test_settings: {
'chrome': {
desiredCapabilities: {
browserName: 'chrome',
},
},
'chrome-headless': {
desiredCapabilities: {
browserName: 'chrome',
chromeOptions: {
args: [
'--headless',
'--no-sandbox',
'--disable-gpu',
],
},
},
},
'firefox': {
desiredCapabilities: {
browserName: 'firefox',
},
},
'firefox-headless': {
desiredCapabilities: {
browserName: 'firefox',
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
},
},
};
|
Support for static pages added | # View for semi-static templatized content.
#
# List of valid templates is explicitly managed for (short-term)
# security reasons.
from mitxmako.shortcuts import render_to_response, render_to_string
from django.shortcuts import redirect
from django.core.context_processors import csrf
from django.conf import settings
#valid_templates=['index.html', 'staff.html', 'info.html', 'credits.html']
valid_templates=['index.html',
'tos.html',
'privacy.html',
'honor.html',
'copyright.html',
'404.html']
print "!!",settings.__dict__
if settings.STATIC_GRAB:
valid_templates = valid_templates+['server-down.html',
'server-error.html'
'server-overloaded.html',
'mitx_global.html',
'mitx-overview.html',
'6002x-faq.html',
'6002x-press-release.html'
]
def index(request, template):
csrf_token = csrf(request)['csrf_token']
if template in valid_templates:
return render_to_response(template, {'error' : '',
'csrf': csrf_token })
else:
return redirect('/')
valid_auth_templates=['help.html']
def auth_index(request, template):
if not request.user.is_authenticated():
return redirect('/')
if template in valid_auth_templates:
return render_to_response(template,{})
else:
return redirect('/')
| # View for semi-static templatized content.
#
# List of valid templates is explicitly managed for (short-term)
# security reasons.
from mitxmako.shortcuts import render_to_response, render_to_string
from django.shortcuts import redirect
from django.core.context_processors import csrf
from django.conf import settings
#valid_templates=['index.html', 'staff.html', 'info.html', 'credits.html']
valid_templates=['mitx_global.html',
'index.html',
'tos.html',
'privacy.html',
'honor.html',
'copyright.html',
'404.html']
print "!!",settings.__dict__
if settings.STATIC_GRAB:
valid_templates = valid_templates+['server-down.html',
'server-error.html'
'server-overloaded.html']
def index(request, template):
csrf_token = csrf(request)['csrf_token']
if template in valid_templates:
return render_to_response(template, {'error' : '',
'csrf': csrf_token })
else:
return redirect('/')
valid_auth_templates=['help.html']
def auth_index(request, template):
if not request.user.is_authenticated():
return redirect('/')
if template in valid_auth_templates:
return render_to_response(template,{})
else:
return redirect('/')
|
Test case two for comment contents | var cmm = require("__buttercup/classes/commands/command.cmm.js");
module.exports = {
setUp: function(cb) {
this.command = new cmm();
(cb)();
},
callbackInjected: {
callsToCallback: function(test) {
var callbackCalled = false;
var callback = function(comment) {
callbackCalled = true;
};
this.command.injectCommentCallback(callback);
this.command.execute({}, "");
test.strictEqual(callbackCalled, true, "Calls into callback");
test.done();
},
callsToCallbackWithCommentTestCaseOne: function(test) {
var providedComment = "I am the first test case";
var callbackCalled = false;
var callback = function(comment) {
if (comment === providedComment) {
callbackCalled = true;
}
};
this.command.injectCommentCallback(callback);
this.command.execute({}, providedComment);
test.strictEqual(callbackCalled, true, "Calls into callback with correct comment (test case one)");
test.done();
},
callsToCallbackWithCommentTestCaseTwo: function(test) {
var providedComment = "The second test case, that is what I am";
var callbackCalled = false;
var callback = function(comment) {
if (comment === providedComment) {
callbackCalled = true;
}
};
this.command.injectCommentCallback(callback);
this.command.execute({}, providedComment);
test.strictEqual(callbackCalled, true, "Calls into callback with correct comment (test case two)");
test.done();
}
}
};
| var cmm = require("__buttercup/classes/commands/command.cmm.js");
module.exports = {
setUp: function(cb) {
this.command = new cmm();
(cb)();
},
callbackInjected: {
callsToCallback: function(test) {
var callbackCalled = false;
var callback = function(comment) {
callbackCalled = true;
};
this.command.injectCommentCallback(callback);
this.command.execute({}, "");
test.strictEqual(callbackCalled, true, "Calls into callback");
test.done();
},
callsToCallbackWithCommentTestCaseOne: function(test) {
var providedComment = "I am the first test case";
var callbackCalled = false;
var callback = function(comment) {
if (comment === providedComment) {
callbackCalled = true;
}
};
this.command.injectCommentCallback(callback);
this.command.execute({}, providedComment);
test.strictEqual(callbackCalled, true, "Calls into callback with correct comment (test case one)");
test.done();
}
}
};
|
Update django to use latest security release | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-oscar-fancypages',
version=":versiontools:fancypages:",
url='https://github.com/tangentlabs/django-oscar-fancypages',
author="Sebastian Vetter",
author_email="[email protected]",
description="Adding fancy CMS-style pages to Oscar",
long_description=open('README.rst').read(),
keywords="django, oscar, e-commerce, cms, pages, flatpages",
license='BSD',
platforms=['linux'],
packages=find_packages(exclude=["sandbox*", "tests*"]),
include_package_data=True,
install_requires=[
'versiontools>=1.9.1',
'Django>=1.4.2',
'django-oscar>=0.3',
'django-model-utils>=1.1.0',
'django-compressor>=1.2',
],
dependency_links=[
'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4'
],
# See http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
#'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-oscar-fancypages',
version=":versiontools:fancypages:",
url='https://github.com/tangentlabs/django-oscar-fancypages',
author="Sebastian Vetter",
author_email="[email protected]",
description="Adding fancy CMS-style pages to Oscar",
long_description=open('README.rst').read(),
keywords="django, oscar, e-commerce, cms, pages, flatpages",
license='BSD',
platforms=['linux'],
packages=find_packages(exclude=["sandbox*", "tests*"]),
include_package_data=True,
install_requires=[
'versiontools>=1.9.1',
'Django>=1.4.1',
'django-oscar>=0.3',
'django-model-utils>=1.1.0',
'django-compressor>=1.2',
],
dependency_links=[
'http://github.com/tangentlabs/django-oscar/tarball/master#egg=django-oscar-0.4'
],
# See http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
#'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Programming Language :: Python'
]
)
|
Update Bincrafters config url for tests
Signed-off-by: Uilian Ries <[email protected]> | import unittest
from conans.errors import ConanException
from cpt.config import ConfigManager
from cpt.printer import Printer
from cpt.test.integration.base import BaseTest
from cpt.test.unit.packager_test import MockConanAPI
class RemotesTest(unittest.TestCase):
def setUp(self):
self.conan_api = MockConanAPI()
def test_valid_config(self):
manager = ConfigManager(self.conan_api, Printer())
manager.install('https://github.com/bincrafters/bincrafters-config.git')
def test_valid_config_with_args(self):
manager = ConfigManager(self.conan_api, Printer())
manager.install('https://github.com/bincrafters/bincrafters-config.git', '-b master')
class RemotesTestRealApi(BaseTest):
def test_valid_config(self):
manager = ConfigManager(self.api, Printer())
profiles = self.api.profile_list()
self.assertEquals(len(profiles), 0)
manager.install("https://github.com/bincrafters/bincrafters-config.git", "-b master")
profiles = self.api.profile_list()
self.assertGreater(len(profiles), 3)
def test_invalid_config(self):
manager = ConfigManager(self.api, Printer())
profiles = self.api.profile_list()
self.assertEquals(len(profiles), 0)
try:
manager.install("https://github.com/")
self.fail("Could not accept wrong URL")
except ConanException:
pass
| import unittest
from conans.errors import ConanException
from cpt.config import ConfigManager
from cpt.printer import Printer
from cpt.test.integration.base import BaseTest
from cpt.test.unit.packager_test import MockConanAPI
class RemotesTest(unittest.TestCase):
def setUp(self):
self.conan_api = MockConanAPI()
def test_valid_config(self):
manager = ConfigManager(self.conan_api, Printer())
manager.install('https://github.com/bincrafters/conan-config.git')
def test_valid_config_with_args(self):
manager = ConfigManager(self.conan_api, Printer())
manager.install('https://github.com/bincrafters/conan-config.git', '-b master')
class RemotesTestRealApi(BaseTest):
def test_valid_config(self):
manager = ConfigManager(self.api, Printer())
profiles = self.api.profile_list()
self.assertEquals(len(profiles), 0)
manager.install("https://github.com/bincrafters/conan-config.git", "-b master")
profiles = self.api.profile_list()
self.assertGreater(len(profiles), 3)
def test_invalid_config(self):
manager = ConfigManager(self.api, Printer())
profiles = self.api.profile_list()
self.assertEquals(len(profiles), 0)
try:
manager.install("https://github.com/")
self.fail("Could not accept wrong URL")
except ConanException:
pass
|
Set Django requirement to the last LTS | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-bitfield',
version='1.9.0',
author='DISQUS',
author_email='[email protected]',
url='https://github.com/disqus/django-bitfield',
description='BitField in Django',
packages=find_packages(),
zip_safe=False,
install_requires=[
'Django>=1.8',
'six',
],
extras_require={
'tests': [
'flake8',
'mysqlclient',
'psycopg2>=2.3',
'pytest-django',
],
},
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development',
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-bitfield',
version='1.9.0',
author='DISQUS',
author_email='[email protected]',
url='https://github.com/disqus/django-bitfield',
description='BitField in Django',
packages=find_packages(),
zip_safe=False,
install_requires=[
'Django>=1.10',
'six',
],
extras_require={
'tests': [
'flake8',
'mysqlclient',
'psycopg2>=2.3',
'pytest-django',
],
},
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development',
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
],
)
|
Change BaseWorker to new style class. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module define base class of mass worker.
"""
# built-in modules
from functools import wraps
import sys
import traceback
# local modules
from mass.exception import TaskError
class BaseWorker(object):
"""Base class of mass worker.
"""
role_functions = {}
def role(self, name):
"""Registers a role to execute relative action.
"""
def decorator(func):
self.role_functions[name] = func
@wraps(func)
def wrapper(*args, **kwargs):
func(*args, **kwargs)
return wrapper
return decorator
def execute(self, action):
"""Execute action by relative registered function.
"""
role = action['Action'].get('_role', None)
if not role:
inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()])
print('Action(%s)' % inputs)
return
else:
kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')}
try:
return self.role_functions[role](**kwargs)
except:
_, error, _ = sys.exc_info()
raise TaskError(repr(error), traceback.format_exc())
def start(self, farm):
"""Start worker
"""
raise NotImplementedError
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module define base class of mass worker.
"""
# built-in modules
from functools import wraps
import sys
import traceback
# local modules
from mass.exception import TaskError
class BaseWorker:
"""Base class of mass worker.
"""
role_functions = {}
def role(self, name):
"""Registers a role to execute relative action.
"""
def decorator(func):
self.role_functions[name] = func
@wraps(func)
def wrapper(*args, **kwargs):
func(*args, **kwargs)
return wrapper
return decorator
def execute(self, action):
"""Execute action by relative registered function.
"""
role = action['Action'].get('_role', None)
if not role:
inputs = ', '.join(['%s=%r' % (k, v) for k, v in action['Action'].items()])
print('Action(%s)' % inputs)
return
else:
kwargs = {k: v for k, v in action['Action'].items() if not k.startswith('_')}
try:
return self.role_functions[role](**kwargs)
except:
_, error, _ = sys.exc_info()
raise TaskError(repr(error), traceback.format_exc())
def start(self, farm):
"""Start worker
"""
raise NotImplementedError
|
Fix NPE in applying wolf entity data from config | package com.elmakers.mine.bukkit.entity;
import org.bukkit.DyeColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Wolf;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class EntityWolfData extends EntityAnimalData {
private boolean isAngry;
private DyeColor collarColor;
public EntityWolfData() {
}
public EntityWolfData(ConfigurationSection parameters, MageController controller) {
super(parameters, controller);
String colorString = parameters.getString("color");
if (colorString != null) {
try {
collarColor = DyeColor.valueOf(colorString.toUpperCase());
} catch (Exception ex) {
collarColor = null;
}
}
isAngry = parameters.getBoolean("angry", false);
}
public EntityWolfData(Entity entity) {
super(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
collarColor = wolf.getCollarColor();
isAngry = wolf.isAngry();
sitting = wolf.isSitting();
}
}
@Override
public void apply(Entity entity) {
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
if (collarColor != null) {
wolf.setCollarColor(collarColor);
}
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
}
}
| package com.elmakers.mine.bukkit.entity;
import org.bukkit.DyeColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Wolf;
import com.elmakers.mine.bukkit.api.magic.MageController;
public class EntityWolfData extends EntityAnimalData {
private boolean isAngry;
private DyeColor collarColor;
public EntityWolfData() {
}
public EntityWolfData(ConfigurationSection parameters, MageController controller) {
super(parameters, controller);
String colorString = parameters.getString("color");
if (colorString != null) {
try {
collarColor = DyeColor.valueOf(colorString.toUpperCase());
} catch (Exception ex) {
collarColor = null;
}
}
isAngry = parameters.getBoolean("angry", false);
}
public EntityWolfData(Entity entity) {
super(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
collarColor = wolf.getCollarColor();
isAngry = wolf.isAngry();
sitting = wolf.isSitting();
}
}
@Override
public void apply(Entity entity) {
super.apply(entity);
if (entity instanceof Wolf) {
Wolf wolf = (Wolf)entity;
wolf.setCollarColor(collarColor);
wolf.setAngry(isAngry);
wolf.setSitting(sitting);
}
}
}
|
[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date)) | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models
class StockMove(models.Model):
_inherit = 'stock.move'
def _find_moves_from_stock_planning(
self, company, to_date, from_date=None, category=None, template=None,
product=None, location_id=None, location_dest_id=None):
cond = [('company_id', '=', company.id),
('date', '<=', to_date),
('state', 'not in', ('done', 'cancel'))]
if from_date:
cond.append(('date', '>=', from_date))
if product:
cond.append(('product_id', '=', product.id))
if location_id:
cond.append(('location_id', '=', location_id.id))
if location_dest_id:
cond.append(('location_dest_id', '=', location_dest_id.id))
moves = self.search(cond)
if category:
moves = moves.filtered(
lambda x: x.product_id.product_tmpl_id.categ_id.id ==
category.id)
if template:
moves = moves.filtered(
lambda x: x.product_id.product_tmpl_id.id ==
template.id)
return moves
| # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models
class StockMove(models.Model):
_inherit = 'stock.move'
def _find_moves_from_stock_planning(
self, company, to_date, from_date=None, category=None, template=None,
product=None, location_id=None, location_dest_id=None):
cond = [('company_id', '=', company.id),
('date', '<=', to_date),
('state', 'not in', ('done', 'cancel'))]
if from_date:
cond.append(('date', '=>', from_date))
if product:
cond.append(('product_id', '=', product.id))
if location_id:
cond.append(('location_id', '=', location_id.id))
if location_dest_id:
cond.append(('location_dest_id', '=', location_dest_id.id))
moves = self.search(cond)
if category:
moves = moves.filtered(
lambda x: x.product_id.product_tmpl_id.categ_id.id ==
category.id)
if template:
moves = moves.filtered(
lambda x: x.product_id.product_tmpl_id.id ==
template.id)
return moves
|
Add additional trove classifiers for supported Pythons | #!/usr/bin/env python
"""Setup script for the pyparsing module distribution."""
# Setuptools depends on pyparsing (via packaging) as of version 34, so allow
# installing without it to avoid bootstrap problems.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
import os
from pyparsing import __version__ as pyparsing_version
modules = ["pyparsing",]
setup(# Distribution meta-data
name = "pyparsing",
version = pyparsing_version,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "[email protected]",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = modules,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
]
)
| #!/usr/bin/env python
"""Setup script for the pyparsing module distribution."""
# Setuptools depends on pyparsing (via packaging) as of version 34, so allow
# installing without it to avoid bootstrap problems.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
import os
from pyparsing import __version__ as pyparsing_version
modules = ["pyparsing",]
setup(# Distribution meta-data
name = "pyparsing",
version = pyparsing_version,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "[email protected]",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = modules,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Switch to use Schedule for identifying campus. | from myuw_mobile.dao.gws import Member
from myuw_mobile.dao.sws import Schedule
from myuw_mobile.logger.logback import log_time
def log_response_time(logger, message, timer):
log_time(logger, message, timer)
def log_success_response(logger, timer):
log_time(logger,
get_identity() + 'fulfilled',
timer)
def log_data_not_found_response(logger, timer):
log_time(logger,
get_identity() + ' data not found',
timer)
def log_invalid_netid_response(logger, timer):
log_time(logger, 'invalid netid, abort', timer)
def log_invalid_regid_response(logger, timer):
log_time(logger, 'invalid regid, abort', timer)
def get_identity():
"""
Return "(<affiliations>, <campus codes>)"
"""
res = "("
member = Member()
campuses = Schedule().get_cur_quarter_campuses()
if member.is_grad_student():
res += ' Grad'
if member.is_undergrad_student():
res += ' Undergrad'
if member.is_pce_student():
res += ' Pce'
if member.is_student_employee():
res += ' StudEmployee'
res += ','
if campuses['seattle']:
res += ' Seattle'
if campuses['bothell']:
res += ' Bothell'
if campuses['tacoma']:
res += ' Tacoma'
res += ') '
return res
| from myuw_mobile.dao.gws import Member
from myuw_mobile.logger.logback import log_time
def log_response_time(logger, message, timer):
log_time(logger, message, timer)
def log_success_response(logger, timer):
log_time(logger,
get_identity() + 'fulfilled',
timer)
def log_data_not_found_response(logger, timer):
log_time(logger,
get_identity() + ' data not found',
timer)
def log_invalid_netid_response(logger, timer):
log_time(logger, 'invalid netid, abort', timer)
def log_invalid_regid_response(logger, timer):
log_time(logger, 'invalid regid, abort', timer)
def get_identity():
"""
Return "(<affiliations>, <campus codes>)"
"""
res = "("
member = Member()
if member.is_grad_student():
res += ' Grad'
if member.is_undergrad_student():
res += ' Undergrad'
if member.is_pce_student():
res += ' Pce'
if member.is_student_employee():
res += ' StudEmployee'
res += ','
if member.is_seattle_student():
res += ' Seattle'
if member.is_bothell_student():
res += ' Bothell'
if member.is_tacoma_student():
res += ' Tacoma'
res += ') '
return res
|
Check before attempting to init image cropping | if ($('#uploadPreview').length) {
let $uploadCrop;
let $preview = $('#uploadPreview');
function readFile(input) {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function (evt) {
$uploadCrop.croppie('bind', {
url: evt.target.result
});
};
reader.readAsDataURL(input.files[0]);
}
}
$uploadCrop = $preview.croppie({
viewport: {
width: $preview.width() || 300,
height: $preview.height() || 300,
type: $preview.hasClass('crop-circle') ? 'circle' : 'square'
},
boundary: {
width: $preview.width() || 300,
height: $preview.height() || 300
},
update: function (data) {
$("#x1").val(Math.floor(data.points[0]));
$("#y1").val(Math.floor(data.points[1]));
$("#x2").val(Math.floor(data.points[2]));
$("#y2").val(Math.floor(data.points[3]));
}
});
$('#avatar').on('change', function () { readFile(this); });
} | $( document ).ready(function() {
let $uploadCrop;
let $preview = $('#uploadPreview');
function readFile(input) {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function (evt) {
$uploadCrop.croppie('bind', {
url: evt.target.result
});
};
reader.readAsDataURL(input.files[0]);
}
}
$uploadCrop = $preview.croppie({
viewport: {
width: $preview.width() || 300,
height: $preview.height() || 300,
type: $preview.hasClass('crop-circle') ? 'circle' : 'square'
},
boundary: {
width: $preview.width() || 300,
height: $preview.height() || 300
},
update: function (data) {
$("#x1").val(Math.floor(data.points[0]));
$("#y1").val(Math.floor(data.points[1]));
$("#x2").val(Math.floor(data.points[2]));
$("#y2").val(Math.floor(data.points[3]));
}
});
$('#avatar').on('change', function () { readFile(this); });
}); |
Fix if no profiles are found | @extends('partials.content-area')
@section('content')
<h1 class="page-title">{{ $page['title'] }}</h1>
{!! $page['content']['main'] !!}
@forelse($profiles as $key => $profiles)
<h1>{{ $key }}</h1>
<div class="row small-up-2 medium-up-3">
@foreach((array)$profiles as $profile)
<div class="columns profile">
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}" class="profile-img" style="background-image: url('{{ $profile['data']['Picture']['url'] or '/_resources/images/no-photo.svg' }}');" alt="{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}"></a>
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}">{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}</a>
@if(isset($profile['data']['Title']))
<span>{{ $profile['data']['Title'] }}</span>
@endif
</div>
@endforeach
</div>
@empty
<p>No profiles found.</p>
@endforelse
@endsection
| @extends('partials.content-area')
@section('content')
<h1 class="page-title">{{ $page['title'] }}</h1>
{!! $page['content']['main'] !!}
@foreach($profiles as $key => $profiles)
<h1>{{ $key }}</h1>
<div class="row small-up-2 medium-up-3">
@forelse((array)$profiles as $profile)
<div class="columns profile">
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}" class="profile-img" style="background-image: url('{{ $profile['data']['Picture']['url'] or '/_resources/images/no-photo.svg' }}');" alt="{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}"></a>
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}">{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}</a>
@if(isset($profile['data']['Title']))
<span>{{ $profile['data']['Title'] }}</span>
@endif
</div>
@empty
<p>No profiles found.</p>
@endforelse
</div>
@endforeach
@endsection
|
Refactor AddGradeController to work with two factor authentification | package at.ac.tuwien.inso.controller.lecturer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
import at.ac.tuwien.inso.entity.Grade;
import at.ac.tuwien.inso.service.GradeService;
@Controller
@RequestMapping(value = "/lecturer/addGrade")
public class LecturerAddGradeController {
@Autowired
private GradeService gradeService;
@GetMapping
public String getPage(@RequestParam("courseId") Long courseId,
@RequestParam("studentId") Long studentId,
Model model) {
model.addAttribute("gradeAuthorizationDTO",
gradeService.getDefaultGradeAuthorizationDTOForStudentAndCourse(studentId, courseId));
model.addAttribute("markOptions", gradeService.getMarkOptions());
return "lecturer/addGrade";
}
@PostMapping
public String saveGrade(@Valid @ModelAttribute("gradeAuthorizationDTO")
GradeAuthorizationDTO gradeAuthorizationDTO,
RedirectAttributes redirectAttributes) {
Grade grade = gradeService.saveNewGradeForStudentAndCourse(gradeAuthorizationDTO);
redirectAttributes.addFlashAttribute("addedGrade", grade);
return "redirect:/lecturer/courses";
}
}
| package at.ac.tuwien.inso.controller.lecturer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.validation.Valid;
import at.ac.tuwien.inso.entity.Grade;
import at.ac.tuwien.inso.service.GradeService;
@Controller
@RequestMapping(value = "/lecturer/addGrade")
public class LecturerAddGradeController {
@Autowired
private GradeService gradeService;
@GetMapping
public String getPage(@RequestParam("courseId") Long courseId,
@RequestParam("studentId") Long studentId,
Model model) {
model.addAttribute("grade",
gradeService.getDefaultGradeForStudentAndCourse(studentId, courseId));
return "lecturer/addGrade";
}
@PostMapping
public String saveGrade(@Valid @ModelAttribute("grade") Grade grade,
RedirectAttributes redirectAttributes) {
grade = gradeService.saveNewGradeForStudentAndCourse(grade);
redirectAttributes.addFlashAttribute("addedGrade", grade);
return "redirect:/lecturer/courses";
}
}
|
Update path fonts gulp task | // imports
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
// build src
gulp.task('browserify', function(cb){
return browserify('./src/app.js', {
debug: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./www/'));
cb();
});
// build in release mode
gulp.task('browserify:release', function(cb){
return browserify('./src/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./www/'));
cb();
});
// copy fonts
gulp.task('fonts', function(cb){
return gulp.src('node_modules/ionic-npm/fonts/**')
.pipe(gulp.dest('./www/fonts/'));
cb();
});
// copy assets
gulp.task('assets', function(cb){
return gulp.src('./assets/**')
.pipe(gulp.dest('./www/'));
cb();
});
// copy templates
gulp.task('templates', function(cb){
return gulp.src('./src/**/*.html')
.pipe(gulp.dest('./www/'));
cb();
});
| // imports
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
// build src
gulp.task('browserify', function(cb){
return browserify('./src/app.js', {
debug: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./www/'));
cb();
});
// build in release mode
gulp.task('browserify:release', function(cb){
return browserify('./src/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./www/'));
cb();
});
// copy fonts
gulp.task('fonts', function(cb){
return gulp.src('node_modules/ionic-framework/release/fonts/**')
.pipe(gulp.dest('./www/fonts/'));
cb();
});
// copy assets
gulp.task('assets', function(cb){
return gulp.src('./assets/**')
.pipe(gulp.dest('./www/'));
cb();
});
// copy templates
gulp.task('templates', function(cb){
return gulp.src('./src/**/*.html')
.pipe(gulp.dest('./www/'));
cb();
}); |
Add python 3.6 to support array | import sys
from setuptools import setup
setup_requires = ['setuptools_scm']
if sys.argv[-1] in ('sdist', 'bdist_wheel'):
setup_requires.append('setuptools-markdown')
setup(
name='tldr',
author='Felix Yan',
author_email='[email protected]',
url='https://github.com/tldr-pages/tldr-python-client',
description='command line client for tldr',
long_description_markdown_filename='README.md',
license='MIT',
py_modules=['tldr'],
scripts=['tldr.py'],
install_requires=['six', 'termcolor', 'colorama'],
tests_require=[
'pytest-runner',
],
setup_requires=setup_requires,
use_scm_version=True,
entry_points={
'console_scripts': ['tldr = tldr:main']
},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: SunOS/Solaris",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Utilities",
"Topic :: System"
]
)
| import sys
from setuptools import setup
setup_requires = ['setuptools_scm']
if sys.argv[-1] in ('sdist', 'bdist_wheel'):
setup_requires.append('setuptools-markdown')
setup(
name='tldr',
author='Felix Yan',
author_email='[email protected]',
url='https://github.com/tldr-pages/tldr-python-client',
description='command line client for tldr',
long_description_markdown_filename='README.md',
license='MIT',
py_modules=['tldr'],
scripts=['tldr.py'],
install_requires=['six', 'termcolor', 'colorama'],
tests_require=[
'pytest-runner',
],
setup_requires=setup_requires,
use_scm_version=True,
entry_points={
'console_scripts': ['tldr = tldr:main']
},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: SunOS/Solaris",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
"Topic :: System"
]
)
|
Fix [IQSLDSH-107] - the MongoDB server date was used as default, now user date is used. | /*jslint nomen: true, vars: true*/
/*global _, angular, ApplicationConfiguration*/
(function () {
'use strict';
angular.module('blueprints').controller('SlideBlueprintsController', ['$scope', 'Tags', 'SlideBlueprints',
function ($scope, Tags, SlideBlueprints) {
$scope.bluePrintInstance = SlideBlueprints.get({slideId: $scope.Slide._id});
$scope.possibleTags = [];
$scope.refreshTags = function (text) {
return Tags.query({tag: text}, function (result) {
$scope.possibleTags = _.map(result, 'value');
});
};
$scope.errMessage = '';
$scope.save = function () {
$scope.errMessage = '';
$scope.bluePrintInstance.slide = [$scope.Slide];
$scope.bluePrintInstance.created = Date.now();
$scope.bluePrintInstance.$save().then(function () {
$scope.$close();
}, function (err) {
$scope.errMessage = err.data.message;
});
};
}]);
}());
| /*jslint nomen: true, vars: true*/
/*global _, angular, ApplicationConfiguration*/
(function () {
'use strict';
angular.module('blueprints').controller('SlideBlueprintsController', ['$scope', 'Tags', 'SlideBlueprints',
function ($scope, Tags, SlideBlueprints) {
$scope.bluePrintInstance = SlideBlueprints.get({slideId: $scope.Slide._id});
$scope.possibleTags = [];
$scope.refreshTags = function (text) {
return Tags.query({tag: text}, function (result) {
$scope.possibleTags = _.map(result, 'value');
});
};
$scope.errMessage = '';
$scope.save = function () {
$scope.errMessage = '';
$scope.bluePrintInstance.slide = [$scope.Slide];
$scope.bluePrintInstance.$save().then(function () {
$scope.$close();
}, function (err) {
$scope.errMessage = err.data.message;
});
};
}]);
}());
|
Make the failing test pass | <?php
namespace fennecweb;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'listingProjectsTestUser';
const USERID = 'listingProjectsTestUser';
const PROVIDER = 'listingProjectsTestUser';
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);
$this->assertEquals($expected, $results);
//Test for correct project
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'listingProjectsTestUserToken'
);
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
array(
"id" => "table_1",
"import_date" => "2016-05-17 10:00:52.627236+00",
"rows" => 10,
"columns" => 5
)
);
$this->assertEquals($expected, $results);
}
}
| <?php
namespace fennecweb;
class ProjectsTest extends \PHPUnit_Framework_TestCase
{
const NICKNAME = 'listingProjectsTestUser';
const USERID = 'listingProjectsTestUser';
const PROVIDER = 'listingProjectsTestUser';
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array("error" => \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN);
$this->assertEquals($expected, $results);
//Test for correct project
$_SESSION['user'] = array(
'nickname' => ProjectsTest::NICKNAME,
'id' => ProjectsTest::USERID,
'provider' => ProjectsTest::PROVIDER,
'token' => 'listingProjectsTestUserToken'
);
list($service) = WebService::factory('listing/Projects');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION)));
$expected = array(
array(
"id" => "This is a Table ID",
"import_date" => "2016-05-17 10:00:52.627236+00",
"rows" => 10,
"columns" => 5
)
);
$this->assertEquals($expected, $results);
}
}
|
Add restriction to allowed types in base type extension | <?php
/**
* This file is part of the BootstrapBundle project.
*
* (c) 2013 Philipp Boes <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace P2\Bundle\BootstrapBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* Class BaseTypeExtension
* @package P2\Bundle\BootstrapBundle\Form\Extension
*/
abstract class BaseTypeExtension extends AbstractTypeExtension
{
/**
* {@inheritDoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['horizontal'] = $options['horizontal'];
$view->vars['inline'] = $options['inline'];
$view->vars['grid'] = $options['grid'];
}
/**
* {@inheritDoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'horizontal' => true,
'inline' => false,
'grid' => array('sm' => array(4,8)),
)
);
$resolver->setAllowedTypes(array('horizontal' => 'bool', 'inline' => 'bool', 'grid' => 'array'));
}
}
| <?php
/**
* This file is part of the BootstrapBundle project.
*
* (c) 2013 Philipp Boes <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace P2\Bundle\BootstrapBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* Class BaseTypeExtension
* @package P2\Bundle\BootstrapBundle\Form\Extension
*/
abstract class BaseTypeExtension extends AbstractTypeExtension
{
/**
* {@inheritDoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['horizontal'] = $options['horizontal'];
$view->vars['inline'] = $options['inline'];
$view->vars['grid'] = $options['grid'];
}
/**
* {@inheritDoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'horizontal' => true,
'inline' => false,
'grid' => array('sm' => array(4,8)),
)
);
$resolver->setAllowedValues(
array(
'horizontal' => array(true, false),
'inline' => array(true, false)
)
);
}
}
|
Include templates in assets pipeline for plugins. | var path = require('path');
var cwd = process.cwd();
var filter = require('../../api/hooks/pluginloader/pluginhelper').filter;
module.exports = function(grunt) {
grunt.registerTask('pluginassets', 'Links assets from plugins into the assets folder', function() {
var options = this.options({
modlabConfig: 'config/',
assetsDir: 'assets/',
jsDir: 'js/',
cssDir: 'styles/',
templatesDir: 'templates/'
});
var files = grunt.config.get('copy.dev.files');
var pluginConfig = require(path.join(cwd, options.modlabConfig, 'plugins.js')).plugins;
var filtered = filter(pluginConfig);
filtered.forEach(function(plugin) {
var pluginAssetDir = path.join('.', plugin.path, options.assetsDir);
files.push({
expand: true,
cwd: path.join(pluginAssetDir, options.jsDir),
src: [ '*.js' ],
dest: path.join('.tmp/public/js/plugin', plugin.name)
});
files.push({
expand: true,
cwd: path.join(pluginAssetDir, options.cssDir),
src: [ '*.css' ],
dest: path.join('.tmp/public/styles/plugin', plugin.name)
});
files.push({
expand: true,
cwd: path.join(pluginAssetDir, options.templatesDir),
src: [ '*.html' ],
dest: path.join('.tmp/public/templates/plugin', plugin.name)
});
});
grunt.config.set('copy.dev.files', files);
});
};
| var path = require('path');
var cwd = process.cwd();
var filter = require('../../api/hooks/pluginloader/pluginhelper').filter;
module.exports = function(grunt) {
grunt.registerTask('pluginassets', 'Links assets from plugins into the assets folder', function() {
var options = this.options({
modlabConfig: 'config/',
assetsDir: 'assets/',
jsDir: 'js/',
cssDir: 'styles/'
});
var files = grunt.config.get('copy.dev.files');
var pluginConfig = require(path.join(cwd, options.modlabConfig, 'plugins.js')).plugins;
var filtered = filter(pluginConfig);
filtered.forEach(function(plugin) {
var pluginAssetDir = path.join('.', plugin.path, options.assetsDir);
files.push({
expand: true,
cwd: path.join(pluginAssetDir, options.jsDir),
src: [ '*.js' ],
dest: path.join('.tmp/public/js/plugin', plugin.name)
});
files.push({
expand: true,
cwd: path.join(pluginAssetDir, options.cssDir),
src: [ '*.css' ],
dest: path.join('.tmp/public/styles/plugin', plugin.name)
});
});
grunt.config.set('copy.dev.files', files);
});
};
|
Fix some more unittest assert methods for Python 2.6 | import unittest
import cybox.bindings.cybox_common_types_1_0 as common_types_binding
import cybox.bindings.mutex_object_1_3 as mutex_binding
from cybox.objects.mutex_object import Mutex
class MutexTest(unittest.TestCase):
def setUp(self):
self.test_dict = {'named': True, 'name': {'value': 'test_name'}}
self.mutex_obj = Mutex.object_from_dict(self.test_dict)
self.mutex_dict = Mutex.dict_from_object(self.mutex_obj)
def test_obj_from_dict(self):
#Make sure it's an instance of the right class
self.assertTrue(isinstance(self.mutex_obj,
mutex_binding.MutexObjectType))
#Test the named attribute
self.assertEqual(self.mutex_obj.get_named(), True)
#Test the name element
self.assertTrue(isinstance(self.mutex_obj.get_Name(),
common_types_binding.StringObjectAttributeType))
self.assertEqual(self.mutex_obj.get_Name().get_valueOf_(), 'test_name')
def test_dict_from_obj(self):
#Make sure it's an instance of the right class
self.assertTrue(isinstance(self.mutex_dict, dict))
#Test the dictionary values
self.assertEqual(self.mutex_dict['named'], True)
self.assertEqual(self.mutex_dict['name']['value'], 'test_name')
if __name__ == "__main__":
unittest.main()
| import unittest
import cybox.bindings.cybox_common_types_1_0 as common_types_binding
import cybox.bindings.mutex_object_1_3 as mutex_binding
from cybox.objects.mutex_object import Mutex
class MutexTest(unittest.TestCase):
def setUp(self):
self.test_dict = {'named': True, 'name': {'value': 'test_name'}}
self.mutex_obj = Mutex.object_from_dict(self.test_dict)
self.mutex_dict = Mutex.dict_from_object(self.mutex_obj)
def test_obj_from_dict(self):
#Make sure it's an instance of the right class
self.assertIsInstance(self.mutex_obj, mutex_binding.MutexObjectType)
#Test the named attribute
self.assertEqual(self.mutex_obj.get_named(), True)
#Test the name element
self.assertIsInstance(self.mutex_obj.get_Name(),
common_types_binding.StringObjectAttributeType)
self.assertEqual(self.mutex_obj.get_Name().get_valueOf_(), 'test_name')
def test_dict_from_obj(self):
#Make sure it's an instance of the right class
self.assertIsInstance(self.mutex_dict, dict)
#Test the dictionary values
self.assertEqual(self.mutex_dict['named'], True)
self.assertEqual(self.mutex_dict['name']['value'], 'test_name')
if __name__ == "__main__":
unittest.main()
|
Check for element before tryign to retrive an attibiute of that element | module.exports = {
sortChildren (data) {
data.forEach((el) => {
if (el.parent) {
if (this.findNestedObject(data, el.parent[0].admin.uid)) {
this.findNestedObject(data, el.parent[0].admin.uid).children.push(el);
}
}
});
return this.arrangeChildren(data[0]);
},
findNestedObject (objects, id) {
var found;
for (var i = 0; i < objects.length; i++) {
if (objects[i].id === id) {
found = objects[i];
break;
} else if (objects[i].children) {
found = this.findNestedObject(objects[i].children, id);
if (found) {
break;
}
}
}
if (found) {
if (!found.children) found.children = [];
return found;
}
},
arrangeChildren (item) {
if (item.children) {
for (var i = 0; i < item.children.length; i++) {
this.arrangeChildren(item.children[i]);
}
item.children = item.children.sort(sortByIdentifier);
}
return item;
}
};
function sortByIdentifier (a, b) {
var aIdentifier = a.identifier;
var bIdentifier = b.identifier;
if (aIdentifier < bIdentifier) {
return -1;
}
if (aIdentifier > bIdentifier) {
return 1;
}
return 0;
}
| module.exports = {
sortChildren (data) {
data.forEach((el) => {
if (el.parent) {
this.findNestedObject(data, el.parent[0].admin.uid).children.push(el);
}
});
return this.arrangeChildren(data[0]);
},
findNestedObject (objects, id) {
var found;
for (var i = 0; i < objects.length; i++) {
if (objects[i].id === id) {
found = objects[i];
break;
} else if (objects[i].children) {
found = this.findNestedObject(objects[i].children, id);
if (found) {
break;
}
}
}
if (found) {
if (!found.children) found.children = [];
return found;
}
},
arrangeChildren (item) {
if (item.children) {
for (var i = 0; i < item.children.length; i++) {
this.arrangeChildren(item.children[i]);
}
item.children = item.children.sort(sortByIdentifier);
}
return item;
}
};
function sortByIdentifier (a, b) {
var aIdentifier = a.identifier;
var bIdentifier = b.identifier;
if (aIdentifier < bIdentifier) {
return -1;
}
if (aIdentifier > bIdentifier) {
return 1;
}
return 0;
}
|
Remove the obsolte comment, library is licensed under BSD. | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| # -*- coding: utf-8 -*-
#!/usr/bin/env python
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re.search(line)
if match:
version = eval(match.group(1))
break
else:
raise Exception('Cannot find version in __init__.py')
fp.close()
setup(name='face_client',
version='.' . join(map(str, version)),
description='face.com face recognition Python API client library',
author='Tomaž Muraus',
author_email='[email protected]',
license='BSD',
url='http://github.com/Kami/python-face-client',
download_url='http://github.com/Kami/python-face-client/',
packages=['face_client'],
provides=['face_client'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Security',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Use url rather than file-loader to base64 encode images | const path = require('path');
module.exports = {
mode: 'development', // TODO: production mode
entry: path.resolve('src', 'index.js'),
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
library: 'stockflux-components',
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src')
],
use: [
{ loader: 'babel-loader' }
]
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src')
],
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
},
{
test: /\.png$/,
include: [
path.resolve(__dirname, 'src')
],
use: [
{ loader: 'url-loader' }
]
}
],
},
externals: {
react: 'react',
'openfin-react-hooks': 'openfin-react-hooks',
'openfin-layouts': 'openfin-layouts',
}
};
| const path = require('path');
module.exports = {
mode: 'development', // TODO: production mode
entry: path.resolve('src', 'index.js'),
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
library: 'stockflux-components',
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src')
],
use: [
{ loader: 'babel-loader' }
]
},
{
test: /\.css$/,
include: [
path.resolve(__dirname, 'src')
],
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
},
{
test: /\.png$/,
include: [
path.resolve(__dirname, 'src')
],
use: [
{ loader: 'file-loader' }
]
}
],
},
externals: {
react: 'react',
'openfin-react-hooks': 'openfin-react-hooks',
'openfin-layouts': 'openfin-layouts',
}
};
|
Fix issue where parent slug was not being included on NEW entries | <?php namespace Anomaly\PagesModule\Page\Form;
use Anomaly\PagesModule\Page\Command\GetRealPath;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;
/**
* Class PageFormFields
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
* @package Anomaly\PagesModule\Page\Form
*/
class PageFormFields implements SelfHandling
{
use DispatchesJobs;
/**
* Handle the page fields.
*
* @param PageFormBuilder $builder
*/
public function handle(PageFormBuilder $builder)
{
$type = $builder->getType();
$parent = $builder->getParent();
/* @var PageInterface $entry */
if (!$parent && $entry = $builder->getFormEntry()) {
$parent = $entry->getParent();
}
$builder->setFields(
[
'*',
'slug' => [
'config' => [
'prefix' => ($parent ? url($this->dispatch(new GetRealPath($parent))) : url()) . '/'
]
],
'theme_layout' => [
'config' => [
'default_value' => $type ? $type->getThemeLayout() : null
]
]
]
);
}
}
| <?php namespace Anomaly\PagesModule\Page\Form;
use Anomaly\PagesModule\Page\Command\GetRealPath;
use Anomaly\PagesModule\Page\Contract\PageInterface;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;
/**
* Class PageFormFields
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
* @package Anomaly\PagesModule\Page\Form
*/
class PageFormFields implements SelfHandling
{
use DispatchesJobs;
public function handle(PageFormBuilder $builder)
{
$type = $builder->getType();
$parent = $builder->getParent();
/* @var PageInterface $entry */
if ($entry = $builder->getFormEntry()) {
$parent = $entry->getParent();
}
$builder->setFields(
[
'*',
'slug' => [
'config' => [
'prefix' => ($parent ? url($this->dispatch(new GetRealPath($parent))) : url()) . '/'
]
],
'theme_layout' => [
'config' => [
'default_value' => $type ? $type->getThemeLayout() : null
]
]
]
);
}
}
|
Fix detection of Nuxeo SDK folder | package org.nuxeo.intellij.ui;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
/**
* Utility class to show a
* {@link com.intellij.openapi.fileChooser.FileChooserDialog} to select only
* Nuxeo SDKs.
*/
public final class NuxeoSDKChooser {
public static final String NXSERVER_FOLDER_NAME = "nxserver";
public static final String SDK_FOLDER_NAME = "sdk";
public static final String COMPONENTS_INDEX_NAME = "components.index";
private static final NuxeoSDKChooserDescriptor descriptor = new NuxeoSDKChooserDescriptor();
private NuxeoSDKChooser() {
// utility class
}
public static VirtualFile chooseNuxeoSDK(Project project) {
return FileChooser.chooseFile(descriptor, project, null);
}
public static class NuxeoSDKChooserDescriptor extends FileChooserDescriptor {
public NuxeoSDKChooserDescriptor() {
super(false, true, false, false, false, false);
setTitle("Choose a Nuxeo SDK Folder");
}
@Override
public boolean isFileSelectable(VirtualFile file) {
VirtualFile nxserverFolder = file.findChild(NXSERVER_FOLDER_NAME);
VirtualFile sdkFolder = file.findChild(SDK_FOLDER_NAME);
return file.isDirectory() && file.isValid()
&& nxserverFolder != null && sdkFolder != null
&& sdkFolder.findChild(COMPONENTS_INDEX_NAME) != null;
}
}
}
| package org.nuxeo.intellij.ui;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
/**
* Utility class to show a
* {@link com.intellij.openapi.fileChooser.FileChooserDialog} to select only
* Nuxeo SDKs.
*/
public final class NuxeoSDKChooser {
public static final String NXSERVER_FOLDER_NAME = "nxserver";
public static final String SDK_FOLDER_NAME = "sdk";
public static final String COMPONENTS_INDEX_NAME = "components.index";
private static final NuxeoSDKChooserDescriptor descriptor = new NuxeoSDKChooserDescriptor();
private NuxeoSDKChooser() {
// utility class
}
public static VirtualFile chooseNuxeoSDK(Project project) {
return FileChooser.chooseFile(descriptor, project, null);
}
public static class NuxeoSDKChooserDescriptor extends FileChooserDescriptor {
public NuxeoSDKChooserDescriptor() {
super(false, true, false, false, false, false);
setTitle("Choose a Nuxeo SDK Folder");
}
@Override
public boolean isFileSelectable(VirtualFile file) {
return file.isDirectory() && file.isValid()
&& file.findChild(NXSERVER_FOLDER_NAME) != null
&& file.findChild(SDK_FOLDER_NAME) != null
&& file.findChild(COMPONENTS_INDEX_NAME) != null;
}
}
}
|
Remove phantom header on splash screen on android | import React, { Component } from 'react';
import { View, Text, Image, ActivityIndicator, AppRegistry, StyleSheet } from 'react-native';
export default class SpalshScreen extends Component {
constructor(props) {
super(props)
}
componentWillUpdate() {
const { navigate } = this.props.navigation;
if ((this.props.screenProps.muralsloaded == true) && (this.props.screenProps.artistsloaded == true)) {
navigate("HomePage");
}
}
static navigationOptions = {
header: null
};
render () {
return (
<View style={{flex:1}}>
<Image style={{flex:1, resizeMode: 'cover', position: 'absolute', height: '100%', width: '100%'}} source={require('./assets/images/splash-background.jpg')} />
<View style={[styles.container, styles.horizontal]}>
<ActivityIndicator size="large" color="gray" />
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
horizontal: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 100,
marginTop: '80%',
}
})
| import React, { Component } from 'react';
import { View, Text, Image, ActivityIndicator, AppRegistry, StyleSheet } from 'react-native';
export default class SpalshScreen extends Component {
constructor(props) {
super(props)
}
componentWillUpdate() {
const { navigate } = this.props.navigation;
if ((this.props.screenProps.muralsloaded == true) && (this.props.screenProps.artistsloaded == true)) {
navigate("HomePage");
}
}
static navigationOptions = ({ navigation }) => ({
headerStyle:{ position: 'absolute', backgroundColor: 'transparent', zIndex: 100, top: 0, left: 0, right: 0, borderBottomColor: 'transparent' }
});
render () {
return (
<View style={{flex:1}}>
<Image style={{flex:1, resizeMode: 'cover', position: 'absolute', height: '100%', width: '100%'}} source={require('./assets/images/splash-background.jpg')} />
<View style={[styles.container, styles.horizontal]}>
<ActivityIndicator size="large" color="gray" />
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
horizontal: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 100,
marginTop: '80%',
}
})
|
Use console.groupCollapsed() in the logger plugin, where available. | /* istanbul ignore next */
/*eslint no-console: 0*/
const noop = () => {};
function loggerPlugin() {
let startGroup, endGroup;
if (console.groupCollapsed) {
startGroup = label => console.groupCollapsed(label);
endGroup = () => console.groupEnd();
} else if (console.group) {
startGroup = label => console.group(label);
endGroup = () => console.groupEnd();
} else {
startGroup = noop;
endGroup = noop;
}
console.info('Router started');
return {
onStop() {
console.info('Router stopped');
},
onTransitionStart(toState, fromState) {
endGroup();
startGroup('Router transition');
console.log('Transition started from state');
console.log(fromState);
console.log('To state');
console.log(toState);
},
onTransitionCancel() {
console.warn('Transition cancelled');
},
onTransitionError(toState, fromState, err) {
console.warn('Transition error with code ' + err.code);
endGroup();
},
onTransitionSuccess() {
console.log('Transition success');
endGroup();
}
};
}
loggerPlugin.pluginName = 'LOGGER_PLUGIN';
export default loggerPlugin;
| /* istanbul ignore next */
/*eslint no-console: 0*/
const noop = () => {};
function loggerPlugin() {
const supportsGroups = console.group && console.groupEnd;
const startGroup = supportsGroups
? () => console.group('Router transition')
: noop;
const endGroup = supportsGroups
? () => console.groupEnd('Router transition')
: noop;
console.info('Router started');
return {
onStop() {
console.info('Router stopped');
},
onTransitionStart(toState, fromState) {
endGroup();
startGroup();
console.log('Transition started from state');
console.log(fromState);
console.log('To state');
console.log(toState);
},
onTransitionCancel() {
console.warn('Transition cancelled');
},
onTransitionError(toState, fromState, err) {
console.warn('Transition error with code ' + err.code);
endGroup();
},
onTransitionSuccess() {
console.log('Transition success');
endGroup();
}
};
}
loggerPlugin.pluginName = 'LOGGER_PLUGIN';
export default loggerPlugin;
|
Set webpack to fallback to history on mismatched route | const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src',
module: {
rules: [
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1
}
},
'postcss-loader',
'sass-loader'
]
}, {
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
'eslint-loader'
]
}
]
},
devServer: {
publicPath: '/assets/',
contentBase: path.resolve(__dirname, 'dist'),
compress: true,
port: process.env.PORT || 3000,
open: true,
filename: 'bundle.js',
overlay: {
warnings: false,
errors: true
},
watchContentBase: true,
clientLogLevel: 'none',
historyApiFallback: true
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/assets/',
filename: 'assets/bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Boilerplate',
template: 'src/templates/index.html',
inject: 'body',
cache: false
})
]
}
| const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src',
module: {
rules: [
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1
}
},
'postcss-loader',
'sass-loader'
]
}, {
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
'eslint-loader'
]
}
]
},
devServer: {
publicPath: '/assets/',
contentBase: path.resolve(__dirname, 'dist'),
compress: true,
port: process.env.PORT || 3000,
open: true,
filename: 'bundle.js',
overlay: {
warnings: false,
errors: true
},
watchContentBase: true,
clientLogLevel: 'none'
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/assets/',
filename: 'assets/bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Boilerplate',
template: 'src/templates/index.html',
inject: 'body',
cache: false
})
]
}
|
Allow plugins to specify permissible update frequencies.
Fixed #2. | import pkg_resources
import logging
log = logging.getLogger("fedmsg")
def find_stats_consumer(hub):
for cons in hub.consumers:
if 'StatsConsumer' in str(type(cons)):
return cons
raise ValueError('StatsConsumer not found.')
class memoized(object):
def __init__(self, func):
self.func = func
self.results = {}
def __call__(self, *args, **kwargs):
key = hash(str(args)) + hash(str(kwargs))
if self.results.get(key) is None:
self.results[key] = self.func(*args, **kwargs)
return self.results[key]
@memoized
def load_plugins(frequency, config):
plugins = []
entry_points = pkg_resources.iter_entry_points('statscache.plugin')
for entry_point in entry_points:
try:
module = entry_point.load()
module_frequencies = getattr(module, 'FREQUENCIES')
if module_frequencies is not None and \
frequency not in module_frequencies:
continue
model = module.make_model(frequency)
plugin = module.Plugin(config, model)
plugins.append(plugin)
except Exception:
log.exception("Failed to load plugin %r" % entry_point)
return plugins
def get_model(idx, frequency, config):
plugins = load_plugins(frequency, config)
for plugin in reversed(plugins):
if plugin.idx == idx:
return plugin.model
raise KeyError("No such model for %r %r" % (idx, frequency))
| import pkg_resources
import logging
log = logging.getLogger("fedmsg")
def find_stats_consumer(hub):
for cons in hub.consumers:
if 'StatsConsumer' in str(type(cons)):
return cons
raise ValueError('StatsConsumer not found.')
class memoized(object):
def __init__(self, func):
self.func = func
self.results = {}
def __call__(self, *args, **kwargs):
key = hash(str(args)) + hash(str(kwargs))
if self.results.get(key) is None:
self.results[key] = self.func(*args, **kwargs)
return self.results[key]
@memoized
def load_plugins(frequency, config):
plugins = []
entry_points = pkg_resources.iter_entry_points('statscache.plugin')
for entry_point in entry_points:
try:
module = entry_point.load()
model = module.make_model(frequency)
plugin = module.Plugin(config, model)
plugins.append(plugin)
except Exception:
log.exception("Failed to load plugin %r" % entry_point)
return plugins
def get_model(idx, frequency, config):
plugins = load_plugins(frequency, config)
for plugin in reversed(plugins):
if plugin.idx == idx:
return plugin.model
raise KeyError("No such model for %r %r" % (idx, frequency))
|
Allow files to be exlcuded | /*jslint node:true */
var RequireAll = (function () {
'use strict';
var fs = require('fs'),
exclude = function (excludeRegexp, name) {
return excludeRegexp && name.match(excludeRegexp);
},
loadAllModules = function (options) {
var files = fs.readdirSync(options.dirname),
modules = {};
files.forEach(function (file) {
if (exclude(options.exclude, file)) {
return;
}
var filepath = options.dirname + '/' + file;
if (fs.statSync(filepath).isDirectory()) {
modules[file] = loadAllModules({
dirname : filepath,
filter : options.filter,
exclude : options.exclude,
dependencies : options.dependencies
});
} else {
if (file.match(options.filter)) {
modules[file.split('.')[0]] = require(filepath).apply(this, options.dependencies);
}
}
});
};
return {
loadAllModules : loadAllModules
};
}());
module.exports = RequireAll; | /*jslint node:true */
var RequireAll = (function () {
'use strict';
var fs = require('fs'),
excludeDirectory = function (excludeDirs, dirname) {
return excludeDirs && dirname.match(excludeDirs);
},
loadAllModules = function (options) {
var files = fs.readdirSync(options.dirname),
modules = {};
files.forEach(function (file) {
if (excludeDirectory(options.excludeDirs, file)) {
return;
}
var filepath = options.dirname + '/' + file;
if (fs.statSync(filepath).isDirectory()) {
modules[file] = loadAllModules({
dirname : filepath,
filter : options.filter,
excludeDirs : options.excludeDirs,
dependencies : options.dependencies
});
} else {
if (file.match(options.filter)) {
modules[file.split('.')[0]] = require(filepath).apply(this, options.dependencies);
}
}
});
};
return {
loadAllModules : loadAllModules
};
}());
module.exports = RequireAll; |
Replace accent with apostrophe for consistency. | define ({
title: 'Titre',
format: 'Format',
layout: 'Disposition',
settings: 'Paramètres',
mapScaleExtent: 'Échelle/étendue de la carte',
preserve: 'Préserver',
mapScale: 'échelle de la carte',
mapExtent: 'étendue de la carte',
fullLayoutOptions: 'Options complètes de mise en page',
scaleBarUnits: 'Unités de la barre d\'échelle',
miles: 'Miles',
kilometers: 'Kilomètres',
meters: 'Mètres',
feet: 'Pieds',
includeLegend: 'Inclure la légende',
printQualityOptions: 'Qualité d\'impression',
dpiInput: {
label: 'DPI',
invalidMessage: 'S\\\'il vous plaît entrer une valeur numérique.',
rangeMessage: 'S\\\'il vous plaît entrer une valeur entre 100 et 300.'
},
mapOnlyOptions: 'Options MAP_ONLY',
width: 'Largeur',
height: 'Hauteur',
printButton: {
busyLabel: 'Impression',
label: 'Imprimer'
},
clearHistoryButton: {
label: 'Effacer l\'historique d\'impression'
},
printResults: {
progressBar: {
label: 'Création de l\\\'impression'
},
errorMessage: 'Erreur, réessayez'
}
});
| define ({
title: 'Titre',
format: 'Format',
layout: 'Disposition',
settings: 'Paramètres',
mapScaleExtent: 'Échelle/étendue de la carte',
preserve: 'Préserver',
mapScale: 'échelle de la carte',
mapExtent: 'étendue de la carte',
fullLayoutOptions: 'Options complètes de mise en page',
scaleBarUnits: 'Unités de la barre d\'échelle',
miles: 'Miles',
kilometers: 'Kilomètres',
meters: 'Mètres',
feet: 'Pieds',
includeLegend: 'Inclure la légende',
printQualityOptions: 'Qualité d`impression',
dpiInput: {
label: 'DPI',
invalidMessage: 'S\\\'il vous plaît entrer une valeur numérique.',
rangeMessage: 'S\\\'il vous plaît entrer une valeur entre 100 et 300.'
},
mapOnlyOptions: 'Options MAP_ONLY',
width: 'Largeur',
height: 'Hauteur',
printButton: {
busyLabel: 'Impression',
label: 'Imprimer'
},
clearHistoryButton: {
label: 'Effacer l\'historique d\'impression'
},
printResults: {
progressBar: {
label: 'Création de l\\\'impression'
},
errorMessage: 'Erreur, réessayez'
}
});
|
Use get_config instead of CONFIG_DICT | import logging
import requests
from indra.config import get_config
logger = logging.getLogger(__name__)
dart_uname = get_config('DART_WM_USERNAME')
dart_pwd = get_config('DART_WM_PASSWORD')
dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \
'/dart/api/v1/readers/query'
def query_dart_notifications(readers=None, versions=None, document_ids=None,
timestamp=None):
"""
Parameters
----------
readers : list
versions : list
document_ids : list
timestamp : dict("on"|"before"|"after",str)
Returns
-------
dict
"""
if all(v is None for v in [readers, versions, document_ids, timestamp]):
return {}
pd = {}
if readers:
pd['readers'] = readers
if versions:
pd['versions'] = versions
if document_ids:
pd['document_ids'] = document_ids
if isinstance(timestamp, dict):
pass # Check
res = requests.post(
dart_url,
data={'metadata':
None
},
auth=(dart_uname, dart_pwd)
)
if res.status_code != 200:
logger.warning(f'Dart Notifications Endpoint returned with status'
f' {res.status_code}: {res.text}')
return {}
return res.json()
| import logging
import requests
from indra.config import CONFIG_DICT
logger = logging.getLogger(__name__)
dart_uname = CONFIG_DICT['DART_WM_USERNAME']
dart_pwd = CONFIG_DICT['DART_WM_PASSWORD']
dart_url = 'https://indra-ingest-pipeline-rest-1.prod.dart.worldmodelers.com' \
'/dart/api/v1/readers/query'
def query_dart_notifications(readers=None, versions=None, document_ids=None,
timestamp=None):
"""
Parameters
----------
readers : list
versions : list
document_ids : list
timestamp : dict("on"|"before"|"after",str)
Returns
-------
dict
"""
if all(v is None for v in [readers, versions, document_ids, timestamp]):
return {}
pd = {}
if readers:
pd['readers'] = readers
if versions:
pd['versions'] = versions
if document_ids:
pd['document_ids'] = document_ids
if isinstance(timestamp, dict):
pass # Check
res = requests.post(
dart_url,
data={'metadata':
None
},
auth=(dart_uname, dart_pwd)
)
if res.status_code != 200:
logger.warning(f'Dart Notifications Endpoint returned with status'
f' {res.status_code}: {res.text}')
return {}
return res.json()
|
Enable pretty printing in the git_log_json task | /*
* grunt-git-log-json
* https://github.com/nlaplante/grunt-git-log-json
*
* Copyright (c) 2014 Nicolas Laplante
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// load all npm grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
git_log_json: {
options: {
dest: 'tmp/CHANGELOG.json',
shortHash: true,
pretty: true
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'git_log_json', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
| /*
* grunt-git-log-json
* https://github.com/nlaplante/grunt-git-log-json
*
* Copyright (c) 2014 Nicolas Laplante
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// load all npm grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
git_log_json: {
options: {
dest: 'tmp/CHANGELOG.json',
shortHash: true
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'git_log_json', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
Fix a typo in how aux name is printed. | // Copyright 2013 Judson D Neer
package com.singledsoftware.mixmaestro;
import java.io.Serializable;
/**
* Stores data for an individual channel.
*
* @see Serializable
* @author Judson D Neer
*/
public class Channel implements Serializable, Comparable<Channel> {
// Unique serializable version ID
private static final long serialVersionUID = -3705403776567370897L;
// Unique identifier for the channel
private final String id;
// Single character that identifies a channel type
// TODO make this an enumeration
private final char type;
// User-assigned name for the channel
private final String name;
/**
* Constructor.
*
* @param i New id
* @param t New type
* @param n New name
*/
public Channel(String i, char t, String n) {
id = i;
type = t;
name = n;
}
/**
* @return The channel identifier
*/
public String getId() {
return id;
}
/**
* @see java.io.Serializable#toString()
*/
@Override
public String toString() {
if (type == 'A') {
return name + " (Aux " + id + ")";
}
else {
return name;
}
}
/**
* @see java.lang.Comparable#compareTo()
*/
@Override
public int compareTo(Channel channel) {
// TODO enhance this once types are fully implemented
return Integer.parseInt(id) - Integer.parseInt(channel.getId());
}
}
| // Copyright 2013 Judson D Neer
package com.singledsoftware.mixmaestro;
import java.io.Serializable;
/**
* Stores data for an individual channel.
*
* @see Serializable
* @author Judson D Neer
*/
public class Channel implements Serializable, Comparable<Channel> {
// Unique serializable version ID
private static final long serialVersionUID = -3705403776567370897L;
// Unique identifier for the channel
private final String id;
// Single character that identifies a channel type
// TODO make this an enumeration
private final char type;
// User-assigned name for the channel
private final String name;
/**
* Constructor.
*
* @param i New id
* @param t New type
* @param n New name
*/
public Channel(String i, char t, String n) {
id = i;
type = t;
name = n;
}
/**
* @return The channel identifier
*/
public String getId() {
return id;
}
/**
* @see java.io.Serializable#toString()
*/
@Override
public String toString() {
// TODO put id and type in parens?
if (type == 'A') {
return name + "(Aux " + id + ")";
}
else {
return name;
}
}
/**
* @see java.lang.Comparable#compareTo()
*/
@Override
public int compareTo(Channel channel) {
// TODO enhance this once types are fully implemented
return Integer.parseInt(id) - Integer.parseInt(channel.getId());
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.