text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Clean up the logging ofr PAWS | import logging
from tornado.websocket import WebSocketHandler
from zmq.eventloop.zmqstream import ZMQStream
clients = []
class PanWebSocket(WebSocketHandler):
def open(self, channel):
""" Client opening connection to unit """
if channel is None:
channel = self.settings['name']
logging.info("Setting up subscriber for channel: {}".format(channel))
try:
self.stream = ZMQStream(self.settings['msg_subscriber'].subscriber)
# Register the callback
self.stream.on_recv(self.on_data)
logging.info("WS opened for channel {}".format(channel))
# Add this client to our list
clients.append(self)
except Exception as e:
logging.warning("Problem establishing websocket for {}: {}".format(self, e))
def on_data(self, data):
""" From the PANOPTES unit """
msg = data[0].decode('UTF-8')
logging.debug("WS Received: {}".format(msg))
for client in clients:
client.write_message(msg)
def on_message(self, message):
""" From the client """
logging.info("WS Sent: {}".format(message))
# cmd_publisher = self.settings['cmd_publisher']
# try:
# cmd_publisher.send_message('PAWS', message)
# except Exception as e:
# print("Problem sending message from PAWS", e)
def on_close(self):
""" When client closes """
clients.remove(self)
logging.info("WS Closed")
| from tornado.websocket import WebSocketHandler
from zmq.eventloop.zmqstream import ZMQStream
from pocs.utils.logger import get_logger
clients = []
class PanWebSocket(WebSocketHandler):
logger = get_logger(self)
def open(self, channel):
""" Client opening connection to unit """
if channel is None:
channel = self.settings['name']
self.logger.info("Setting up subscriber for channel: {}".format(channel))
try:
self.stream = ZMQStream(self.settings['msg_subscriber'].subscriber)
# Register the callback
self.stream.on_recv(self.on_data)
self.logger.info("WS opened for channel {}".format(channel))
# Add this client to our list
clients.append(self)
except Exception as e:
self.logger.warning("Problem establishing websocket for {}: {}".format(self, e))
def on_data(self, data):
""" From the PANOPTES unit """
msg = data[0].decode('UTF-8')
self.logger.debug("WS Received: {}".format(msg))
for client in clients:
client.write_message(msg)
def on_message(self, message):
""" From the client """
self.logger.info("WS Sent: {}".format(message))
# cmd_publisher = self.settings['cmd_publisher']
# try:
# cmd_publisher.send_message('PAWS', message)
# except Exception as e:
# print("Problem sending message from PAWS", e)
def on_close(self):
""" When client closes """
clients.remove(self)
self.logger.info("WS Closed")
|
Fix logic of enrollment actions | <div class="btn-group">
{{-- Show button to exchange shift, if exchanges period is active --}}
@if ($settings->withinExchangePeriod())
<button type="button" class="btn btn-secondary btn-sm">Exchange shift</button>
@endif
{{-- Show enrollment actions, if enrollments period is active --}}
@if ($settings->withinEnrollmentPeriod())
@if (! Auth::user()->student->isEnrolledInCourse($course))
{{-- Show button to enroll in course. --}}
<form action="{{ route('enrollments.create') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="course_id" value="{{ $course->id }}">
<button type="submit" class="btn btn-success btn-sm">Enroll in course</button>
</form>
@else
<button type="button" class="btn btn-secondary btn-sm disabled">Enrolled</button>
<button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu dropdown-menu-right">
<button class="dropdown-item btn btn-sm text-danger">Delete enrollment</button>
</ul>
@endif
@endif
</div>
| <div class="btn-group">
@if (! Auth::user()->student->isEnrolledInCourse($course))
{{-- Show button to enroll in course. --}}
<form action="{{ route('enrollments.create') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="course_id" value="{{ $course->id }}">
<button type="submit" class="btn btn-success btn-sm">Enroll in course</button>
</form>
@else
{{-- Show button to exchange shift, if exchanges period is active --}}
@if ($settings->withinExchangePeriod())
<button type="button" class="btn btn-secondary btn-sm">Exchange shift</button>
@endif
{{-- Show dropdown to delete enrollment, if enrollments period is active --}}
@if ($settings->withinEnrollmentPeriod())
<button type="button" class="btn btn-secondary btn-sm disabled">Enrolled</button>
<button type="button" class="btn btn-secondary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu dropdown-menu-right">
<button class="dropdown-item btn btn-sm text-danger">Delete enrollment</button>
</ul>
@endif
@endif
</div>
|
Fix quarkus.test.arg-line multiple args handling
The split is intended to happen on a whitespace character,
not the comma character used by properties
Fixes: #19623 | package io.quarkus.test.junit.launcher;
import static io.quarkus.test.junit.IntegrationTestUtil.DEFAULT_WAIT_TIME_SECONDS;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.OptionalLong;
import org.eclipse.microprofile.config.Config;
public final class ConfigUtil {
private ConfigUtil() {
}
public static List<String> argLineValue(Config config) {
String strValue = config.getOptionalValue("quarkus.test.arg-line", String.class)
.orElse(config.getOptionalValue("quarkus.test.argLine", String.class) // legacy value
.orElse(null));
if (strValue == null) {
return Collections.emptyList();
}
String[] parts = strValue.split("\\s+");
List<String> result = new ArrayList<>(parts.length);
for (String s : parts) {
String trimmed = s.trim();
if (trimmed.isEmpty()) {
continue;
}
result.add(trimmed);
}
return result;
}
public static Duration waitTimeValue(Config config) {
return Duration.ofSeconds(config.getValue("quarkus.test.wait-time", OptionalLong.class)
.orElse(config.getValue("quarkus.test.jar-wait-time", OptionalLong.class) // legacy value
.orElse(DEFAULT_WAIT_TIME_SECONDS)));
}
}
| package io.quarkus.test.junit.launcher;
import static io.quarkus.test.junit.IntegrationTestUtil.DEFAULT_WAIT_TIME_SECONDS;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.OptionalLong;
import org.eclipse.microprofile.config.Config;
public final class ConfigUtil {
private ConfigUtil() {
}
public static List<String> argLineValue(Config config) {
List<String> strings = config.getOptionalValues("quarkus.test.arg-line", String.class)
.orElse(config.getOptionalValues("quarkus.test.argLine", String.class) // legacy value
.orElse(Collections.emptyList()));
if (strings.isEmpty()) {
return strings;
}
List<String> sanitizedString = new ArrayList<>(strings.size());
for (String s : strings) {
String trimmed = s.trim();
if (trimmed.isEmpty()) {
continue;
}
sanitizedString.add(trimmed);
}
return sanitizedString;
}
public static Duration waitTimeValue(Config config) {
return Duration.ofSeconds(config.getValue("quarkus.test.wait-time", OptionalLong.class)
.orElse(config.getValue("quarkus.test.jar-wait-time", OptionalLong.class) // legacy value
.orElse(DEFAULT_WAIT_TIME_SECONDS)));
}
}
|
Use prepared data, rather than the object last action date, to determine boost | from datetime import datetime
from councilmatic_core.haystack_indexes import BillIndex
from django.conf import settings
from haystack import indexes
import pytz
from chicago.models import ChicagoBill
app_timezone = pytz.timezone(settings.TIME_ZONE)
class ChicagoBillIndex(BillIndex, indexes.Indexable):
topics = indexes.MultiValueField(faceted=True)
def get_model(self):
return ChicagoBill
def prepare(self, obj):
data = super(ChicagoBillIndex, self).prepare(obj)
boost = 0
if data['last_action_date']:
today = app_timezone.localize(datetime.now()).date()
# data['last_action_date'] can be in the future
weeks_passed = (today - data['last_action_date']).days / 7 + 1
boost = 1 + 1.0 / max(weeks_passed, 1)
data['boost'] = boost
return data
def prepare_topics(self, obj):
return obj.topics
def prepare_last_action_date(self, obj):
if not obj.last_action_date:
action_dates = [a.date for a in obj.actions.all()]
if action_dates:
last_action_date = max(action_dates)
return datetime.strptime(last_action_date, '%Y-%m-%d').date()
return obj.last_action_date.date()
| from datetime import datetime
from councilmatic_core.haystack_indexes import BillIndex
from django.conf import settings
from haystack import indexes
import pytz
from chicago.models import ChicagoBill
app_timezone = pytz.timezone(settings.TIME_ZONE)
class ChicagoBillIndex(BillIndex, indexes.Indexable):
topics = indexes.MultiValueField(faceted=True)
def get_model(self):
return ChicagoBill
def prepare(self, obj):
data = super(ChicagoBillIndex, self).prepare(obj)
boost = 0
if obj.last_action_date:
now = app_timezone.localize(datetime.now())
# obj.last_action_date can be in the future
weeks_passed = (now - obj.last_action_date).days / 7 + 1
boost = 1 + 1.0 / max(weeks_passed, 1)
data['boost'] = boost
return data
def prepare_topics(self, obj):
return obj.topics
def prepare_last_action_date(self, obj):
if not obj.last_action_date:
action_dates = [a.date for a in obj.actions.all()]
if action_dates:
last_action_date = max(action_dates)
return datetime.strptime(last_action_date, '%Y-%m-%d').date()
return obj.last_action_date.date()
|
Update URL patterns for Django >= 1.8 | # pylint: disable=no-value-for-parameter
from django.conf import settings
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.views.generic import RedirectView
# Enable admin.
admin.autodiscover()
ADMIN_URLS = False
urlpatterns = patterns('') # pylint: disable=C0103
if ADMIN_URLS:
urlpatterns += [
# Admin URLs. Note: Include ``urls_admin`` **before** admin.
url(r'^$', RedirectView.as_view(url='/admin/'), name='index'),
url(r'^admin/cb/', include('cloud_browser.urls_admin')),
]
else:
urlpatterns += [
# Normal URLs.
url(r'^$', RedirectView.as_view(url='/cb/'), name='index'),
url(r'^cb/', include('cloud_browser.urls')),
]
urlpatterns += [
# Hack in the bare minimum to get accounts support.
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^accounts/$', RedirectView.as_view(url='/login/')),
url(r'^accounts/profile', RedirectView.as_view(url='/')),
]
if settings.DEBUG:
# Serve up static media.
urlpatterns += [
url(r'^' + settings.MEDIA_URL.strip('/') + '/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
]
| # pylint: disable=no-value-for-parameter
from django.conf import settings
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.views.generic import RedirectView
# Enable admin.
admin.autodiscover()
ADMIN_URLS = False
urlpatterns = patterns('') # pylint: disable=C0103
if ADMIN_URLS:
urlpatterns += patterns(
'',
# Admin URLs. Note: Include ``urls_admin`` **before** admin.
url(r'^$', RedirectView.as_view(url='/admin/'), name='index'),
url(r'^admin/cb/', include('cloud_browser.urls_admin')),
)
else:
urlpatterns += patterns(
'',
# Normal URLs.
url(r'^$', RedirectView.as_view(url='/cb/'), name='index'),
url(r'^cb/', include('cloud_browser.urls')),
)
urlpatterns += patterns(
'',
# Hack in the bare minimum to get accounts support.
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^accounts/$', RedirectView.as_view(url='/login/')),
url(r'^accounts/profile', RedirectView.as_view(url='/')),
)
if settings.DEBUG:
# Serve up static media.
urlpatterns += patterns(
'',
url(r'^' + settings.MEDIA_URL.strip('/') + '/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
|
Use full pathname to perf_expectations in test.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/266055
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@28770 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
UNIT_TESTS = [
'tests.perf_expectations_unittest',
]
PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
return output
def CheckChangeOnCommit(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == path:
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api,
output_api))
return output
| #!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
UNIT_TESTS = [
'tests.perf_expectations_unittest',
]
PERF_EXPECTATIONS = 'perf_expectations.json'
def CheckChangeOnUpload(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
return output
def CheckChangeOnCommit(input_api, output_api):
run_tests = False
for path in input_api.LocalPaths():
if PERF_EXPECTATIONS == input_api.os_path.basename(path):
run_tests = True
output = []
if run_tests:
output.extend(input_api.canned_checks.RunPythonUnitTests(input_api,
output_api,
UNIT_TESTS))
output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api,
output_api))
return output
|
Fix off-by-one error in match highlighter | function MatchHighlighter() {
'use strict';
const mergeRanges = function(indexes) {
return indexes.reduce(function(obj, index, pos) {
const prevIndex = indexes[pos - 1] || 0;
const currentIndex = indexes[pos];
const nextIndex = indexes[pos + 1] || 0;
if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) {
obj.ranges[obj.rangeIndex].push(currentIndex);
} else if (currentIndex > 0 && indexes.length > 1) {
obj.rangeIndex = obj.ranges.push([currentIndex]) - 1;
}
return obj;
}, {
ranges:[[]],
rangeIndex: 0
}).ranges;
};
const wrapHighlight = function(letter) {
return '<b>' + letter + '</b>';
};
this.highlight = function(input, result) {
const matched = FuzzaldrinPlus.match(result, input);
const substrings = mergeRanges(matched).map(function(range) {
return range.map(function(index) {
return result.charAt(index);
}).join('');
});
return substrings.reduce(function(res, substring) {
return res.replace(substring, wrapHighlight(substring));
}, result);
};
return this;
}
| function MatchHighlighter() {
'use strict';
const mergeRanges = function(indexes) {
return indexes.reduce(function(obj, index, pos) {
const prevIndex = indexes[pos - 1] || 0;
const currentIndex = indexes[pos];
const nextIndex = indexes[pos + 1] || 0;
if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) {
obj.ranges[obj.rangeIndex].push(currentIndex);
} else if (currentIndex > 0 && indexes.length > 1) {
obj.rangeIndex = obj.ranges.push([currentIndex]);
}
return obj;
}, {
ranges:[[]],
rangeIndex: 0
}).ranges;
};
const wrapHighlight = function(letter) {
return '<b>' + letter + '</b>';
};
this.highlight = function(input, result) {
const matched = FuzzaldrinPlus.match(result, input);
const substrings = mergeRanges(matched).map(function(range) {
return range.map(function(index) {
return result.charAt(index);
}).join('');
});
return substrings.reduce(function(res, substring) {
return res.replace(substring, wrapHighlight(substring));
}, result);
};
return this;
}
|
[improve] Use a logger instead of System.out, display the class name | package com.nokia.springboot.training.d04.s01.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Service
public class ProductService {
private static final Logger LOGGER = LoggerFactory.getLogger(ProductService.class);
private final AsyncComponent asyncComponent;
@Autowired
public ProductService(final AsyncComponent asyncComponent) {
this.asyncComponent = asyncComponent;
}
public void voidAsyncCall() {
asyncComponent.voidAsyncCall();
}
public void getFuture() {
final Future<String> future = asyncComponent.getFuture();
try {
getAndDisplayValue(future, "Future");
} catch (final ExecutionException | InterruptedException e) {
handleException(e);
}
}
public void getCompletableFuture() {
final CompletableFuture<String> completableFuture = asyncComponent.getCompletableFuture();
try {
getAndDisplayValue(completableFuture, "CompletableFuture");
} catch (final ExecutionException | InterruptedException e) {
handleException(e);
}
}
private void getAndDisplayValue(final Future<String> futureValue, final String className)
throws ExecutionException, InterruptedException {
if (futureValue.isDone()) {
final String theValue = futureValue.get();
LOGGER.info("The {} value is '{}'", className, theValue);
}
}
private void handleException(final Exception ex) {
ex.printStackTrace();
}
}
| package com.nokia.springboot.training.d04.s01.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Service
public class ProductService {
private final AsyncComponent asyncComponent;
@Autowired
public ProductService(final AsyncComponent asyncComponent) {
this.asyncComponent = asyncComponent;
}
public void voidAsyncCall() {
asyncComponent.voidAsyncCall();
}
public void getFuture() {
final Future<String> future = asyncComponent.getFuture();
try {
getAndDisplayValue(future);
} catch (final ExecutionException | InterruptedException e) {
handleException(e);
}
}
public void getCompletableFuture() {
final CompletableFuture<String> completableFuture = asyncComponent.getCompletableFuture();
try {
getAndDisplayValue(completableFuture);
} catch (final ExecutionException | InterruptedException e) {
handleException(e);
}
}
private void getAndDisplayValue(final Future<String> futureValue)
throws ExecutionException, InterruptedException {
if (futureValue.isDone()) {
final String theValue = futureValue.get();
System.out.println("The " + futureValue.getClass().getSimpleName() + " value is '" + theValue + "'");
}
}
private void handleException(final Exception ex) {
ex.printStackTrace();
}
}
|
Add some Czech character to test, too | # -*- coding: utf-8 -*-
from ella.articles.models import Article
from example_project.tests.test_newman.helpers import NewmanTestCase
class TestArticleBasics(NewmanTestCase):
def test_article_template_saving(self):
s = self.selenium
# go to article adding
s.click(self.elements['navigation']['articles'])
s.click(self.elements['controls']['add'])
# wait for the page to fully load
s.wait_for_element_present(self.elements['controls']['suggester'])
# fill the form
data = {
'title' : u'马 žš experiment',
'upper_title' : u'vyšší',
'description' : u'Article description',
'slug' : 'title',
}
self.fill_fields(data)
# fill in the suggesters
suggest_data = {
'category': ('we',),
'authors': ('Bar', 'Kin',),
}
self.fill_suggest_fiels(suggest_data)
self.save_form()
# verify save
self.assert_equals(1, Article.objects.count())
a = Article.objects.all()[0]
self.assert_equals(data['title'], a.title)
# FIXME: hack, use django-markup
self.assert_equals('<p>%s</p>\n' % data['description'], a.description)
self.assert_equals(2, a.authors.count())
| # -*- coding: utf-8 -*-
from ella.articles.models import Article
from example_project.tests.test_newman.helpers import NewmanTestCase
class TestArticleBasics(NewmanTestCase):
def test_article_template_saving(self):
s = self.selenium
# go to article adding
s.click(self.elements['navigation']['articles'])
s.click(self.elements['controls']['add'])
# wait for the page to fully load
s.wait_for_element_present(self.elements['controls']['suggester'])
# fill the form
data = {
'title' : u'马 experiment',
'upper_title' : u'vyšší',
'description' : u'Article description',
'slug' : 'title',
}
self.fill_fields(data)
# fill in the suggesters
suggest_data = {
'category': ('we',),
'authors': ('Bar', 'Kin',),
}
self.fill_suggest_fiels(suggest_data)
self.save_form()
# verify save
self.assert_equals(1, Article.objects.count())
a = Article.objects.all()[0]
self.assert_equals(data['title'], a.title)
# FIXME: hack, use django-markup
self.assert_equals('<p>%s</p>\n' % data['description'], a.description)
self.assert_equals(2, a.authors.count())
|
Fix for Pokedex defaulting to [], not {} | FullScreenPokemon.FullScreenPokemon.settings.statistics = {
"prefix": "FullScreenPokemon::",
"defaults": {
"storeLocally": true
},
"values": {
"gameStarted": {
"valueDefault": false
},
"map": {
"valueDefault": ""
},
"area": {
"valueDefault": ""
},
"location": {
"valueDefault": ""
},
"lastPokecenter": {
"valueDefault": {
"map": "Pallet Town",
"location": "Player's House Door"
}
},
"badges": {
"valueDefault": {
"Brock": false,
"Misty": false,
"LtSurge": false,
"Erika": false,
"Koga": false,
"Sabrina": false,
"Blaine": false,
"Giovanni": false
}
},
"items": {
"valueDefault": []
},
"money": {
"valueDefault": 0,
"minimum": 0
},
"time": {
"valueDefault": 0
},
"name": {},
"nameRival": {},
"starter": {},
"starterRival": {},
"hasPokedex": {
"valueDefault": false
},
"Pokedex": {
"valueDefault": {}
},
"PokemonInParty": {
"valueDefault": []
},
"PokemonInPC": {
"valueDefault": []
}
}
}; | FullScreenPokemon.FullScreenPokemon.settings.statistics = {
"prefix": "FullScreenPokemon::",
"defaults": {
"storeLocally": true
},
"values": {
"gameStarted": {
"valueDefault": false
},
"map": {
"valueDefault": ""
},
"area": {
"valueDefault": ""
},
"location": {
"valueDefault": ""
},
"lastPokecenter": {
"valueDefault": {
"map": "Pallet Town",
"location": "Player's House Door"
}
},
"badges": {
"valueDefault": {
"Brock": false,
"Misty": false,
"LtSurge": false,
"Erika": false,
"Koga": false,
"Sabrina": false,
"Blaine": false,
"Giovanni": false
}
},
"items": {
"valueDefault": []
},
"money": {
"valueDefault": 0,
"minimum": 0
},
"time": {
"valueDefault": 0
},
"name": {},
"nameRival": {},
"starter": {},
"starterRival": {},
"hasPokedex": {
"valueDefault": false
},
"Pokedex": {
"valueDefault": []
},
"PokemonInParty": {
"valueDefault": []
},
"PokemonInPC": {
"valueDefault": []
}
}
}; |
Fix get authentication type failed | <?php
namespace Concrete\Core\Authentication;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerAwareInterface;
use Concrete\Core\Logging\LoggerAwareTrait;
use Concrete\Core\User\User;
use Page;
use Controller;
use Concrete\Core\Support\Facade\Application;
abstract class AuthenticationTypeController extends Controller implements LoggerAwareInterface,
AuthenticationTypeControllerInterface
{
protected $authenticationType;
protected $app;
use LoggerAwareTrait;
public function getLoggerChannel()
{
return Channels::CHANNEL_AUTHENTICATION;
}
abstract public function getAuthenticationTypeIconHTML();
abstract public function view();
/**
* @param AuthenticationType $type This type may be null only for access points that do not rely on the type.
*/
public function __construct(AuthenticationType $type = null)
{
$this->authenticationType = $type;
$this->app = Application::getFacadeApplication();
}
public function getAuthenticationType()
{
if (!$this->authenticationType || !$this->authenticationType->getAuthenticationTypeID()) {
$this->authenticationType = AuthenticationType::getByHandle($this->getHandle());
}
return $this->authenticationType;
}
public function completeAuthentication(User $u)
{
$c = Page::getByPath('/login');
$controller = $c->getPageController();
return $controller->finishAuthentication($this->getAuthenticationType(), $u);
}
/**
* @return string
*/
abstract public function getHandle();
}
| <?php
namespace Concrete\Core\Authentication;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerAwareInterface;
use Concrete\Core\Logging\LoggerAwareTrait;
use Concrete\Core\User\User;
use Page;
use Controller;
use Concrete\Core\Support\Facade\Application;
abstract class AuthenticationTypeController extends Controller implements LoggerAwareInterface,
AuthenticationTypeControllerInterface
{
protected $authenticationType;
protected $app;
use LoggerAwareTrait;
public function getLoggerChannel()
{
return Channels::CHANNEL_AUTHENTICATION;
}
abstract public function getAuthenticationTypeIconHTML();
abstract public function view();
/**
* @param AuthenticationType $type This type may be null only for access points that do not rely on the type.
*/
public function __construct(AuthenticationType $type = null)
{
$this->authenticationType = $type;
$this->app = Application::getFacadeApplication();
}
public function getAuthenticationType()
{
if (!$this->authenticationType) {
$this->authenticationType = AuthenticationType::getByHandle($this->getHandle());
}
return $this->authenticationType;
}
public function completeAuthentication(User $u)
{
$c = Page::getByPath('/login');
$controller = $c->getPageController();
return $controller->finishAuthentication($this->getAuthenticationType(), $u);
}
/**
* @return string
*/
abstract public function getHandle();
}
|
Add fuzzywuzzy and python-Levenshtein as depends | """Config for PyPI."""
from setuptools import find_packages
from setuptools import setup
setup(
author='Kyle P. Johnson',
author_email='[email protected]',
classifiers=[
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: Chinese (Traditional)',
'Natural Language :: English',
'Natural Language :: Greek',
'Natural Language :: Latin',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Text Processing',
'Topic :: Text Processing :: General',
'Topic :: Text Processing :: Linguistic',
],
description='NLP for the ancient world',
install_requires=['nltk',
'gitpython',
'regex',
'whoosh',
'fuzzywuzzy',
'python-Levenshtein'],
keywords=['nlp', 'nltk', 'greek', 'latin'],
license='MIT',
long_description="The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.", # pylint: disable=C0301
name='cltk',
packages=find_packages(),
url='https://github.com/cltk/cltk',
version='0.1.32',
zip_safe=True,
test_suite='cltk.tests.test_cltk',
)
| """Config for PyPI."""
from setuptools import find_packages
from setuptools import setup
setup(
author='Kyle P. Johnson',
author_email='[email protected]',
classifiers=[
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: Chinese (Traditional)',
'Natural Language :: English',
'Natural Language :: Greek',
'Natural Language :: Latin',
'Operating System :: POSIX',
'Programming Language :: Python :: 3.5',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Text Processing',
'Topic :: Text Processing :: General',
'Topic :: Text Processing :: Linguistic',
],
description='NLP for the ancient world',
install_requires=['nltk',
'gitpython',
'regex',
'whoosh'],
keywords=['nlp', 'nltk', 'greek', 'latin'],
license='MIT',
long_description="The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.", # pylint: disable=C0301
name='cltk',
packages=find_packages(),
url='https://github.com/cltk/cltk',
version='0.1.32',
zip_safe=True,
test_suite='cltk.tests.test_cltk',
)
|
CRM-341: Create workflow widget for entity page - fixed JS minification | var Oro = Oro || {};
Oro.widget = Oro.widget || {};
Oro.widget.Buttons = Oro.widget.Abstract.extend({
options: _.extend(
_.extend({}, Oro.widget.Abstract.prototype.options),
{
cssClass: 'pull-left btn-group icons-holder',
type: 'buttons'
}
),
initialize: function(options) {
options = options || {};
this.initializeWidget(options);
this.widget = this.$el;
this.widget.addClass(this.options.cssClass);
},
setTitle: function(title) {
this.widget.attr('title', title);
},
getActionsElement: function() {
return null;
},
show: function() {
if (!this.$el.data('wid')) {
if (this.$el.parent().length) {
this._showStatic();
} else {
this._showRemote();
}
}
Oro.widget.Abstract.prototype.show.apply(this);
},
_showStatic: function() {
var anchorDiv = Backbone.$('<div/>');
var parent = this.widget.parent();
anchorDiv.insertAfter(parent);
anchorDiv.replaceWith(this.widget);
parent.remove();
},
_showRemote: function() {
this.widget.empty();
this.widget.append(this.$el);
this.setElement(this.widget);
}
});
Oro.widget.Manager.registerWidgetContainer('buttons', Oro.widget.Buttons);
| var Oro = Oro || {};
Oro.widget = Oro.widget || {};
Oro.widget.Buttons = Oro.widget.Abstract.extend({
options: _.extend(
_.extend({}, Oro.widget.Abstract.prototype.options),
{
class: 'pull-left btn-group icons-holder',
type: 'buttons'
}
),
initialize: function(options) {
options = options || {};
this.initializeWidget(options);
this.widget = this.$el;
this.widget.addClass(this.options.class);
},
setTitle: function(title) {
this.widget.attr('title', title);
},
getActionsElement: function() {
return null;
},
show: function() {
if (!this.$el.data('wid')) {
if (this.$el.parent().length) {
this._showStatic();
} else {
this._showRemote();
}
}
Oro.widget.Abstract.prototype.show.apply(this);
},
_showStatic: function() {
var anchorDiv = Backbone.$('<div/>');
var parent = this.widget.parent();
anchorDiv.insertAfter(parent);
anchorDiv.replaceWith(this.widget);
parent.remove();
},
_showRemote: function() {
this.widget.empty();
this.widget.append(this.$el);
this.setElement(this.widget);
}
});
Oro.widget.Manager.registerWidgetContainer('buttons', Oro.widget.Buttons);
|
Enable ending pg pool, and some tidying | 'use strict';
const pg = require('pg');
function transaction(client) {
return {
commit() {
return client.query('COMMIT;').then(() => {
client.release();
}).catch((err) => this.rollback().then(() => {
throw err;
}));
},
rollback() {
return client.query('ROLLBACK;').then(() => {
// if there was a problem rolling back the query
// something is seriously messed up. Return the error
// to the done function to close & remove this client from
// the pool. If you leave a client in the pool with an unaborted
// transaction weird, hard to diagnose problems might happen.
client.release();
});
},
query(...args) {
return client.query(...args)
.catch((err) => this.rollback().then(() => {
throw err;
}));
},
};
}
module.exports = (conf) => {
const pool = (conf instanceof pg.Pool) ? conf : new pg.Pool(conf);
return {
end(...args) {
return pool.end(...args);
},
query(...args) {
return pool.query(...args);
},
connect(...args) {
return pool.connect(...args);
},
begin() {
return pool.connect().then((client) => {
const t = transaction(client);
return t.query('BEGIN;')
.then(() => t)
.catch((err) => t.rollback().then(() => {
throw err;
}));
});
},
};
};
| 'use strict';
const _ = require('lodash');
const pg = require('pg');
function transaction(client) {
return {
commit() {
return client.query('COMMIT;').then(() => {
client.release();
}).catch((err) => {
return this.rollback().then(() => {
throw err;
});
});
},
rollback() {
return client.query('ROLLBACK;').then(() => {
// if there was a problem rolling back the query
// something is seriously messed up. Return the error
// to the done function to close & remove this client from
// the pool. If you leave a client in the pool with an unaborted
// transaction weird, hard to diagnose problems might happen.
client.release();
});
},
query(...args) {
return client.query(...args).catch((err) => {
return this.rollback().then(() => {
throw err;
});
});
},
};
}
module.exports = (conf) => {
const pool = (conf instanceof pg.Pool) ? conf : new pg.Pool(conf);
return {
query(...args) {
return pool.query(...args);
},
connect(...args) {
return pool.connect(...args);
},
begin() {
return pool.connect().then((client, done) => {
const t = transaction(client);
return t.query('BEGIN;').then(() => t).catch((err) => {
return t.rollback().then(() => {
throw err;
});
});
});
},
};
};
|
Exclude tests and devtools when packaging | #!/usr/bin/env python
from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(name='subvenv',
version='1.0.0',
description=('A tool for creating virtualenv-friendly '
'Sublime Text project files'),
long_description=readme(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
url='http://github.com/Railslide/subvenv',
author='Giulia Vergottini',
author_email='[email protected]',
license='MIT',
packages=find_packages('subvenv', exclude=['tests']),
install_requires=[
'click',
],
test_suite='subvenv.tests',
tests_require='nose',
entry_points={
'virtualenvwrapper.project.post_mkproject': [
'subvenv = subvenv.core:post_mkproject',
],
'console_scripts': [
'subvenv = subvenv.core:cli'
],
},
include_package_data=True,
zip_safe=False)
| from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(name='subvenv',
version='1.0.0',
description=('A tool for creating virtualenv-friendly '
'Sublime Text project files'),
long_description=readme(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
url='http://github.com/Railslide/subvenv',
author='Giulia Vergottini',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=[
'click',
],
test_suite='subvenv.tests',
tests_require='nose',
entry_points={
'virtualenvwrapper.project.post_mkproject': [
'subvenv = subvenv.core:post_mkproject',
],
'console_scripts': [
'subvenv = subvenv.core:cli'
],
},
include_package_data=True,
zip_safe=False)
|
Fix exception when SSH key is not found | <?php
namespace Platformsh\Cli\Command\SshKey;
use Platformsh\Cli\Command\CommandBase;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SshKeyDeleteCommand extends CommandBase
{
protected function configure()
{
$this
->setName('ssh-key:delete')
->setDescription('Delete an SSH key')
->addArgument(
'id',
InputArgument::OPTIONAL,
'The ID of the SSH key to delete'
);
$this->addExample('Delete the key 123', '123');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument('id');
if (empty($id) || !is_numeric($id)) {
$this->stdErr->writeln("<error>You must specify the ID of the SSH key to delete.</error>");
$this->stdErr->writeln("List your SSH keys with: <info>" . self::$config->get('application.executable') . " ssh-keys</info>");
return 1;
}
$key = $this->api()->getClient()
->getSshKey($id);
if (!$key) {
$this->stdErr->writeln("SSH key not found: <error>$id</error>");
return 1;
}
$key->delete();
$this->stdErr->writeln("The SSH key <info>$id</info> has been deleted from your " . self::$config->get('service.name') . " account.");
return 0;
}
}
| <?php
namespace Platformsh\Cli\Command\SshKey;
use Platformsh\Cli\Command\CommandBase;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SshKeyDeleteCommand extends CommandBase
{
protected function configure()
{
$this
->setName('ssh-key:delete')
->setDescription('Delete an SSH key')
->addArgument(
'id',
InputArgument::OPTIONAL,
'The ID of the SSH key to delete'
);
$this->addExample('Delete the key 123', '123');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument('id');
if (empty($id) || !is_numeric($id)) {
$this->stdErr->writeln("<error>You must specify the ID of the SSH key to delete.</error>");
$this->stdErr->writeln("List your SSH keys with: <info>" . self::$config->get('application.executable') . " ssh-keys</info>");
return 1;
}
$key = $this->api()->getClient()
->getSshKey($id);
if (!$key) {
$this->stdErr->writeln("SSH key not found: <error>$id</error>");
}
$key->delete();
$this->stdErr->writeln("The SSH key <info>$id</info> has been deleted from your " . self::$config->get('service.name') . " account.");
return 0;
}
}
|
Implement ShuweeAdmin help extension example | <?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* Class PostType
* @package AppBundle\Form
*/
class PostType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add(
'summary',
'textarea',
array(
'help' => 'Short introduction. Keep it simple and short.'
)
)
->add(
'content',
'textarea',
array(
'attr' => array('rows' => 20),
)
)
->add(
'file',
'file',
array(
'label' => 'Image',
'required' => false,
'preview_base_path' => 'WebPath',
)
)
->add('authorEmail', 'email')
->add(
'publishedAt',
'datetime',
array(
'widget' => 'choice',
)
)
->add(
'status',
'checkbox',
array(
'label' => 'Published',
'required' => false,
)
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'AppBundle\Entity\Post',
)
);
}
/**
* @return string
*/
public function getName()
{
return 'post';
}
} | <?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* Class PostType
* @package AppBundle\Form
*/
class PostType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('summary', 'textarea')
->add(
'content',
'textarea',
array(
'attr' => array('rows' => 20),
)
)
->add(
'file',
'file',
array(
'label' => 'Image',
'required' => false,
'preview_base_path' => 'WebPath',
)
)
->add('authorEmail', 'email')
->add(
'publishedAt',
'datetime',
array(
'widget' => 'choice',
)
)
->add(
'status',
'checkbox',
array(
'label' => 'Published',
'required' => false,
)
);
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'AppBundle\Entity\Post',
)
);
}
/**
* @return string
*/
public function getName()
{
return 'post';
}
} |
Fix next activities on start date and not end date | (function ($) {
'use strict';
setNextActivities();
function setNextActivities() {
$.ajax({
url: "/next_activities"
}).done(function (data) {
var count = 0;
var str = '';
$.each(data, function (index, activity) {
if(new Date(activity.field_date_1+"Z")>new Date() && count <10) {
str += '<tr>';
str += '<td class="date">' + activity.field_date + '</td>';
if (activity.field_lien && activity.field_lien != '') {
str += '<td class="title"><a href="' + activity.field_lien + '">' + activity.title + '</a></td>';
} else {
str += '<td class="title">' + activity.title + '</td>';
}
str += '<td class="room">' + activity.field_room + '</td>';
str += '</tr>';
count ++;
}
});
$('.tournaments-home-next table').html(str);
setTimeout(setNextActivities, 10 * 60 * 1000); //each 10 min
});
}
})(jQuery);
| (function ($) {
'use strict';
setNextActivities();
function setNextActivities() {
$.ajax({
url: "/next_activities"
}).done(function (data) {
var count = 0;
var str = '';
$.each(data, function (index, activity) {
if(new Date(activity.field_date_1)>new Date() && count <10) {
str += '<tr>';
str += '<td class="date">' + activity.field_date + '</td>';
if (activity.field_lien && activity.field_lien != '') {
str += '<td class="title"><a href="' + activity.field_lien + '">' + activity.title + '</a></td>';
} else {
str += '<td class="title">' + activity.title + '</td>';
}
str += '<td class="room">' + activity.field_room + '</td>';
str += '</tr>';
count ++;
}
});
$('.tournaments-home-next table').html(str);
setTimeout(setNextActivities, 10 * 60 * 1000); //each 10 min
});
}
})(jQuery);
|
Remove trailing slash from comment blocks | var _ = require('lodash');
var COMMENT_START = /^\s*\/\*\*/,
COMMENT_END = /^\s*\*\//;
/**
* This service reads LESS files and extract jsdoc styles comments.
* It doesn't parse tags inside comments.
*/
module.exports = function lessFileReader(log) {
return {
name: 'lessFileReader',
defaultPattern: /\.less$/,
getDocs: function(fileInfo) {
var isComment = false;
var commentLines = String(fileInfo.content)
.trim()
.replace(/\r\n|\r|\n *\n/g, '\n')
.split('\n');
/**
* Reduce lines to comment blocks
*/
fileInfo.comments = _.reduce(commentLines, function (commentBlocks, commentLine) {
if (COMMENT_START.test(commentLine)) {
isComment = true;
commentBlocks.push(['*']);
return commentBlocks;
}
if (isComment) {
if (COMMENT_END.test(commentLine)) {
commentBlocks[commentBlocks.length - 1].push('*');
isComment = false;
} else {
commentBlocks[commentBlocks.length - 1].push(commentLine);
}
}
return commentBlocks;
}, []).map(function (block) {
return {
type: 'Block',
value: block.join('\n')
};
});
return [{
docType: 'lessFile'
}];
}
};
};
| var _ = require('lodash');
var COMMENT_START = /^\s*\/\*\*/,
COMMENT_END = /^\s*\*\//;
/**
* This service reads LESS files and extract jsdoc styles comments.
* It doesn't parse tags inside comments.
*/
module.exports = function lessFileReader(log) {
return {
name: 'lessFileReader',
defaultPattern: /\.less$/,
getDocs: function(fileInfo) {
var isComment = false;
var commentLines = String(fileInfo.content)
.trim()
.replace(/\r\n|\r|\n *\n/g, '\n')
.split('\n');
/**
* Reduce comment lines to comment blocks
*/
fileInfo.comments = _.reduce(commentLines, function (commentBlocks, commentLine) {
if (COMMENT_START.test(commentLine)) {
isComment = true;
commentBlocks.push(['*']);
return commentBlocks;
}
if (isComment) {
commentBlocks[commentBlocks.length - 1].push(commentLine);
if (COMMENT_END.test(commentLine)) {
isComment = false;
}
}
return commentBlocks;
}, []).map(function (block) {
return {
type: 'Block',
value: block.join('\n')
};
});
return [{
docType: 'lessFile'
}];
}
};
};
|
Make the WS URL configurable
Also store it outside of the state. | import React, { Component } from 'react';
import './App.css';
import Table from './Table';
class App extends Component {
constructor () {
super();
let ws_url = process.env.REACT_APP_WS_URL
if (!ws_url) {
const proto = (location.protocol === "https:")? "wss://" : "ws://"
ws_url = proto + location.host + "/websocket"
}
this.ws = new WebSocket(ws_url)
this.ws.onopen = () => console.log("OPENED")
};
login = (event) => {
let name = this.nameInput.value
if (!name) {
console.log("No name supplied");
return
}
console.log("Logging in as " + name);
let msg = {
method: "login",
name: name
}
this.ws.send(JSON.stringify(msg))
}
render() {
return (
<div>
<div className="App">
<div className="App-header">
<h2>Welcome to Tarabish Online</h2>
</div>
<div>
<input type="text" placeholder="Name"
ref={(ref) => this.nameInput = ref}
/>
<input type="button" value="Login" onClick={this.login} />
</div>
<div><Table name="Test Table 1"/></div>
</div>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import './App.css';
import Table from './Table';
class App extends Component {
constructor () {
super();
const ws = new WebSocket('ws://localhost:42745/websocket')
this.state = {
ws: ws
}
ws.onopen = () => console.log("OPENED")
};
login = (event) => {
let name = this.nameInput.value
if (!name) {
console.log("No name supplied");
return
}
console.log("Logging in as " + name);
let msg = {
method: "login",
name: name
}
this.state.ws.send(JSON.stringify(msg))
}
render() {
return (
<div>
<div className="App">
<div className="App-header">
<h2>Welcome to Tarabish Online</h2>
</div>
<div>
<input type="text" placeholder="Name"
ref={(ref) => this.nameInput = ref}
/>
<input type="button" value="Login" onClick={this.login} />
</div>
<div><Table name="Test Table 1"/></div>
</div>
</div>
);
}
}
export default App;
|
Refactor to use DOM API instead of embedded HTML strings | var autocompleter = {
look_up: function(value) {
if(value == "") {
this.clear_popup();
}
else {
var self = this;
$.ajax("/autocomplete", {
data: { "query":value }
}).done(function(data) {
if(data.length > 0) {
var container = $("#autocomplete").empty();
var $input = $('#input');
for(var i=0; i<data.length; i++) {
container.append(self.format_autocomplete_entry(data[i]));
};
var new_cmd_el = document.createElement("li");
new_cmd_el.className = "item new"
new_cmd_el.addEventListener('click', function(e) {
statement_list.new();
});
new_cmd_el.title="Create a new command and add it to this test";
new_cmd_el.innerText = "[Add new command]";
container.append(new_cmd_el);
container.attr('top', $input.attr('bottom')).show();
}
else {
self.clear_popup();
}
}).fail(function() {
console.log("AJAX fail:", arguments);
});
}
},
clear_popup: function() {
$("#autocomplete").hide();
},
format_autocomplete_entry: function(entry) {
var el = document.createElement("li");
el.className = "item";
el.addEventListener('click', function(e) {
statement_list.add(this.innerText);
});
el.title = entry.examples.slice(0,3).join(" ");
el.innerText = entry.function;
el.innerHTML = el.innerHTML.replace(/\{([^}]+)\}/g, '<span class="var">$1</span>');
return el;
}
};
| var autocompleter = {
look_up: function(value) {
if(value == "") {
this.clear_popup();
}
else {
var self = this;
$.ajax("/autocomplete", {
data: { "query":value }
}).done(function(data) {
if(data.length > 0) {
var html = "", $input = $('#input');
for(var i=0; i<data.length; i++) {
html += self.format_autocomplete_entry(data[i]);
};
html += '<li class="item new" onclick="statement_list.new();" title="Create a new command and add it to this test">[Add new command]</li>'
$("#autocomplete").html(html).attr('top', $input.attr('bottom')).show();
}
else {
self.clear_popup();
}
}).fail(function() {
console.log("AJAX fail:", arguments);
});
}
},
clear_popup: function() {
$("#autocomplete").hide();
},
format_autocomplete_entry: function(entry) {
return '<li class="item" onclick="statement_list.add(this.innerText);" title="'+entry.examples.slice(0,3).join(" ").replace(/"/g, '"')+'">'+entry.function.replace(/\{([^}]+)\}/g, '<span class="var">$1</span>')+'</li>';
}
};
|
Add iteration to log message | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;
import java.time.Duration;
/**
* Removes expired sessions and locks
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
private int iteration = 0;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
super(applicationRepository, curator, flagSource, Duration.ofMinutes(1), interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected boolean maintain() {
if (iteration % 10 == 0)
log.log(LogLevel.INFO, () -> "Running " + SessionsMaintainer.class.getSimpleName() + ", iteration " + iteration);
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofMinutes(90);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(LogLevel.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
}
iteration++;
return true;
}
}
| // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;
import java.time.Duration;
/**
* Removes expired sessions and locks
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
private int iteration = 0;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
super(applicationRepository, curator, flagSource, Duration.ofMinutes(1), interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected boolean maintain() {
if (iteration % 10 == 0)
log.log(LogLevel.INFO, () -> "Running " + SessionsMaintainer.class.getSimpleName());
applicationRepository.deleteExpiredLocalSessions();
if (hostedVespa) {
Duration expiryTime = Duration.ofMinutes(90);
int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
log.log(LogLevel.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
}
iteration++;
return true;
}
}
|
Allow optional callbacks for Listeners | from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False, callback=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
callback (function taking msg_type): optional callback to be called on the data as we receive it
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.custom_callback = callback
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
if self.custom_callback is not None:
self.custom_callback(self.data)
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
| from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
|
Update Schedule endpoints to use mock data | package ulcrs.scheduler;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import ulcrs.data.DataStore;
import ulcrs.models.schedule.Schedule;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.List;
public class Scheduler {
private static List<Schedule> generatedSchedules;
private static boolean isScheduling = false;
private static LocalDateTime schedulingStart;
public static boolean generateSchedule() {
// TODO implement
// This is where the algorithm's entry point will be. This will call the scheduling algorithm with the
// specified tutors, courses, and shifts from DataStore, and return the list of schedules generated from
// those constraints
// TODO we want to spin off a thread here to do our scheduling likely.
// The scheduling should not be done on the same thread as the thread handling the HTTP request, as we need
// to return data for the request to avoid a timeout
isScheduling = true;
schedulingStart = LocalDateTime.now();
// Start scheduling algorithm
// For now, return mock data
InputStream is = DataStore.class.getClassLoader().getResourceAsStream("mockSchedule_FrontendExpects.json");
JsonReader reader = new JsonReader(new InputStreamReader(is));
generatedSchedules = new Gson().fromJson(reader, new TypeToken<List<Schedule>>() {}.getType());
isScheduling = false;
return true;
}
public static List<Schedule> fetchGeneratedSchedules() {
if (!isComplete()) {
return null;
}
return generatedSchedules;
}
private static boolean isComplete() {
return schedulingStart != null && !isScheduling;
}
public static boolean verifySchedule(Schedule schedule) {
// TODO implement
return false;
}
}
| package ulcrs.scheduler;
import ulcrs.models.schedule.Schedule;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class Scheduler {
private static List<Schedule> generatedSchedules;
private static boolean isScheduling = false;
private static LocalDateTime schedulingStart;
public static boolean generateSchedule() {
// TODO implement
// This is where the algorithm's entry point will be. This will call the scheduling algorithm with the
// specified tutors, courses, and shifts from DataStore, and return the list of schedules generated from
// those constraints
// TODO we want to spin off a thread here to do our scheduling likely.
// The scheduling should not be done on the same thread as the thread handling the HTTP request, as we need
// to return data for the request to avoid a timeout
isScheduling = true;
schedulingStart = LocalDateTime.now();
// Start scheduling algorithm
isScheduling = false;
generatedSchedules = new ArrayList<>();
return true;
}
public static List<Schedule> fetchGeneratedSchedules() {
if (!isComplete()) {
return null;
}
return generatedSchedules;
}
private static boolean isComplete() {
return schedulingStart != null && !isScheduling;
}
public static boolean verifySchedule(Schedule schedule) {
// TODO implement
return false;
}
}
|
Change TimeStampType to not accept negative values
This is to work around a Python bug (http://bugs.python.org/issue1777412) | from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType, ConversionError
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
MESSAGES = {
'negative': u'Timestamp cannot be negative.',
}
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
if value < 0:
raise ConversionError(self.messages['negative'])
return TimeStampType.timestamp_to_date(value)
except ConversionError as e:
raise e
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
| from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
Fix adv-meta custum values ignored | <?php
include '../../passwd/analytics-key.inc.php';
// Override any of the default settings below:
$config['site_title'] = 'schmitt.co'; // Site title
$config['theme'] = 'pico-pure'; // Set the theme (defaults to "default")
$config['pages_order_by'] = 'date '; // Order pages by "alpha" or "date"
$config['pages_order'] = 'desc'; // Order pages "asc" or "desc"
// adv-meta
$config['custom_meta_values'] = array('description' => 'Description',
'exclude' => 'Exclude',
//'tags' => 'Tags'
);
// Google Analytics
$config['google_tracking_id'] = $ANALYTICS_TRACKING_ID;
/*
$config['base_url'] = ''; // Override base URL (e.g. http://example.com)
$config['date_format'] = 'jS M Y'; // Set the PHP date format
$config['twig_config'] = array( // Twig settings
'cache' => false, // To enable Twig caching change this to CACHE_DIR
'autoescape' => false, // Autoescape Twig vars
'debug' => true // Enable Twig debug
);
$config['excerpt_length'] = 50; // The pages excerpt length (in words)
// To add a custom config setting:
$config['custom_setting'] = 'Hello'; // Can be accessed by {{ config.custom_setting }} in a theme
*/
?>
| <?php
include '../../passwd/analytics-key.inc.php';
// Override any of the default settings below:
$config['site_title'] = 'schmitt.co'; // Site title
$config['theme'] = 'pico-pure'; // Set the theme (defaults to "default")
$config['pages_order_by'] = 'date '; // Order pages by "alpha" or "date"
$config['pages_order'] = 'desc'; // Order pages "asc" or "desc"
// adv-meta
$config['adv_meta_values'] = array('description' => 'Description');
// Google Analytics
$config['google_tracking_id'] = $ANALYTICS_TRACKING_ID;
/*
$config['base_url'] = ''; // Override base URL (e.g. http://example.com)
$config['date_format'] = 'jS M Y'; // Set the PHP date format
$config['twig_config'] = array( // Twig settings
'cache' => false, // To enable Twig caching change this to CACHE_DIR
'autoescape' => false, // Autoescape Twig vars
'debug' => false // Enable Twig debug
);
$config['excerpt_length'] = 50; // The pages excerpt length (in words)
// To add a custom config setting:
$config['custom_setting'] = 'Hello'; // Can be accessed by {{ config.custom_setting }} in a theme
*/
?>
|
Add setup-db and setup-doc targets. | var cly = require('cly'),
Couchpenter = require('./couchpenter').Couchpenter,
p = require('path');
function exec() {
var options = {
url: {
string: '-u url',
help: 'CouchDB URL, default: http://localhost:5984'
},
file: {
string: '-f file',
help: 'Path to configuration file, default: ./couchpenter.json'
}
};
function _cb(taskNames) {
return function (args) {
args.url = args.url || 'http://localhost:5984';
args.file = args.file || 'couchpenter.json';
console.log('Using CouchDB ' + args.url);
new Couchpenter(args.url, args.file, execDir).does(taskNames, cly.exit);
};
}
var couchpenterDir = __dirname,
execDir = process.cwd(),
commands = {
init: {
callback: function (args) {
console.log('Creating Couchpenter configuration file');
cly.copyDir(p.join(couchpenterDir, '../examples'), '.', cly.exit);
}
},
setup: {
options: options,
callback: _cb(['setUpDatabases', 'setUpDocuments'])
},
"setup-db": {
options: options,
callback: _cb(['setUpDatabases'])
},
"setup-doc": {
options: options,
callback: _cb(['setUpDocuments'])
},
teardown: {
options: options,
callback: _cb(['tearDownDatabases'])
}
};
cly.parse(couchpenterDir, 'couchpenter', commands);
}
exports.exec = exec; | var cly = require('cly'),
Couchpenter = require('./couchpenter').Couchpenter,
p = require('path');
function exec() {
var options = {
url: {
string: '-u url',
help: 'CouchDB URL, default: http://localhost:5984'
},
file: {
string: '-f file',
help: 'Path to configuration file, default: ./couchpenter.json'
}
};
function _cb(taskNames) {
return function (args) {
args.url = args.url || 'http://localhost:5984';
args.file = args.file || 'couchpenter.json';
console.log('Using CouchDB ' + args.url);
new Couchpenter(args.url, args.file, execDir).does(taskNames, cly.exit);
};
}
var couchpenterDir = __dirname,
execDir = process.cwd(),
commands = {
init: {
callback: function (args) {
console.log('Creating Couchpenter configuration file');
cly.copyDir(p.join(couchpenterDir, '../examples'), '.', cly.exit);
}
},
setup: {
options: options,
callback: _cb(['setUpDatabases', 'setUpDocuments'])
},
teardown: {
options: options,
callback: _cb(['tearDownDatabases'])
}
};
cly.parse(couchpenterDir, 'couchpenter', commands);
}
exports.exec = exec; |
Update coverage values to match current | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 100,
statements: 100
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
| 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 100,
statements: 99
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
}
|
UPDATE: Throw exception if we are going to divide by 0 | <?php
/**
* This file is part of the Statistical Classifier package.
*
* (c) Cam Spiers <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Camspiers\StatisticalClassifier\Transform;
/**
* @author Cam Spiers <[email protected]>
* @package Statistical Classifier
*/
class DocumentLength
{
public function __invoke($tfidf)
{
$transform = $tfidf;
foreach ($tfidf as $category => $documents) {
foreach ($documents as $documentIndex => $document) {
$denominator = 0;
foreach ($document as $count) {
$denominator += $count * $count;
}
$denominator = sqrt($denominator);
if ($denominator !== 0) {
foreach ($document as $token => $count) {
$transform
[$category]
[$documentIndex]
[$token] = $count / $denominator;
}
} else {
throw new \RuntimeException("Cannot divide by 0 in DocumentLength transform");
}
}
}
return $transform;
}
}
| <?php
/**
* This file is part of the Statistical Classifier package.
*
* (c) Cam Spiers <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Camspiers\StatisticalClassifier\Transform;
/**
* @author Cam Spiers <[email protected]>
* @package Statistical Classifier
*/
class DocumentLength
{
public function __invoke($tfidf)
{
$transform = $tfidf;
foreach ($tfidf as $category => $documents) {
foreach ($documents as $documentIndex => $document) {
$denominator = 0;
foreach ($document as $count) {
$denominator += $count * $count;
}
$denominator = sqrt($denominator);
foreach ($document as $token => $count) {
$transform
[$category]
[$documentIndex]
[$token] = $count / $denominator;
}
}
}
return $transform;
}
}
|
Update code to use new classes | <?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use Grav\Common\Grav;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use RocketTheme\Toolbox\Event\Event;
class ErrorPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents() {
return [
'onPageNotFound' => ['onPageNotFound', 0]
];
}
/**
* Display error page if no page was found for the current route.
*
* @param Event $event
*/
public function onPageNotFound(Event $event)
{
$this->enable([
'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10]
]);
/** @var Pages $pages */
$pages = $this->grav['pages'];
// Try to load user error page.
$page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);
if (!$page) {
// If none provided use built in error page.
$page = new Page;
$page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
}
$event->page = $page;
$event->stopPropagation();
}
/**
* Add current directory to twig lookup paths.
*/
public function onTwigTemplatePaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
}
}
| <?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use Grav\Common\Grav;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Component\EventDispatcher\Event;
class ErrorPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents() {
return [
'onPageNotFound' => ['onPageNotFound', 0]
];
}
/**
* Display error page if no page was found for the current route.
*
* @param Event $event
*/
public function onPageNotFound(Event $event)
{
$this->enable([
'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10]
]);
/** @var Pages $pages */
$pages = $this->grav['pages'];
// Try to load user error page.
$page = $pages->dispatch($this->config->get('plugins.error.routes.404', '/error'), true);
if (!$page) {
// If none provided use built in error page.
$page = new Page;
$page->init(new \SplFileInfo(__DIR__ . '/pages/error.md'));
}
$event->page = $page;
$event->stopPropagation();
}
/**
* Add current directory to twig lookup paths.
*/
public function onTwigTemplatePaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
}
}
|
Fix typo in methods example. | # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.description} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
| # Example: How to get the currently activated payment methods.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
#
# Get the all the activated methods for this API key.
#
params = {
"amount": {
"currency": "EUR",
"value": "100.00",
}
}
methods = mollie_client.methods.list(**params)
body = f"Your API key has {len(methods)} activated payment methods:<br>"
for method in methods:
body += '<div style="line-height:40px; vertical-align:top">'
body += f'<img src="{method.image_svg}"> {method.desciption} ({method.id})'
body += "</div>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
|
system: Add require statement for the abstract L10nProvider | <?php
/**
* Factory class for providing Localization implementations
* @author M2Mobi, Heinz Wiesinger
*/
class L10nFactory
{
/**
* Instance of the L10nProvider
* @var array
*/
private static $lprovider;
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* This method returns an object with the appropriate localization
* implementation provider
* @param String $provider The localization implementation requested
* @param String $language POSIX locale definition
* @return L10nProvider $return Instance of the localization provider requested
*/
public static function get_localization($provider, $language)
{
require_once("class.l10nprovider.inc.php");
switch($provider)
{
case "php":
if (!isset(self::$lprovider[$provider]))
{
require_once("class.l10nproviderphp.inc.php");
self::$lprovider[$provider] = new L10nProviderPHP($language);
}
return self::$lprovider[$provider];
break;
case "gettext":
default:
if (!isset(self::$lprovider[$provider]))
{
require_once("class.l10nprovidergettext.inc.php");
self::$lprovider[$provider] = new L10nProviderGettext($language);
}
return self::$lprovider[$provider];
break;
}
}
}
?>
| <?php
/**
* Factory class for providing Localization implementations
* @author M2Mobi, Heinz Wiesinger
*/
class L10nFactory
{
/**
* Instance of the L10nProvider
* @var array
*/
private static $lprovider;
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* This method returns an object with the appropriate localization
* implementation provider
* @param String $provider The localization implementation requested
* @param String $language POSIX locale definition
* @return L10nProvider $return Instance of the localization provider requested
*/
public static function get_localization($provider, $language)
{
switch($provider)
{
case "php":
if (!isset(self::$lprovider[$provider]))
{
require_once("class.l10nproviderphp.inc.php");
self::$lprovider[$provider] = new L10nProviderPHP($language);
}
return self::$lprovider[$provider];
break;
case "gettext":
default:
if (!isset(self::$lprovider[$provider]))
{
require_once("class.l10nprovidergettext.inc.php");
self::$lprovider[$provider] = new L10nProviderGettext($language);
}
return self::$lprovider[$provider];
break;
}
}
}
?>
|
Fix "Trying to get property of non-object" when mentioning at your own submission | <?php
namespace App\Traits;
use App\Notifications\UsernameMentioned;
use App\User;
use Auth;
trait UsernameMentions
{
/**
* Handles all the mentions in the comment. (sends notifications to mentioned usernames).
*
* @param \App\Comment $comment
* @param \App\Submission $submission
* @param \App\User $notifiableUser
*
* @return void
*/
protected function handleMentions($comment, $submission, $notifiableUser = null)
{
if (!preg_match_all('/@([A-Za-z0-9\._]+)/', $comment->body, $mentionedUsernames)) {
return;
}
foreach ($mentionedUsernames[1] as $key => $username) {
// set a limit so they can't just mention the whole website!
if ($key === 5) {
return;
}
if ($user = User::whereUsername($username)->first()) {
if (optional($notifiableUser)->id === $user->id) {
continue;
}
$user->notify(new UsernameMentioned(Auth::user(), $submission));
}
}
}
}
| <?php
namespace App\Traits;
use App\Notifications\UsernameMentioned;
use App\User;
use Auth;
trait UsernameMentions
{
/**
* Handles all the mentions in the comment. (sends notifications to mentioned usernames).
*
* @param \App\Comment $comment
* @param \App\Submission $submission
* @param \App\User $notifiableUser
*
* @return void
*/
protected function handleMentions($comment, $submission, $notifiableUser = null)
{
if (!preg_match_all('/@([A-Za-z0-9\._]+)/', $comment->body, $mentionedUsernames)) {
return;
}
foreach ($mentionedUsernames[1] as $key => $username) {
// set a limit so they can't just mention the whole website!
if ($key === 5) {
return;
}
if ($user = User::whereUsername($username)->first()) {
if ($notifiableUser->id === $user->id) {
continue;
}
$user->notify(new UsernameMentioned(Auth::user(), $submission));
}
}
}
}
|
Implement remainder of the write plugin | var File = require('vinyl');
var mix = require('mix');
var path = require('path');
var rimraf = require('rimraf');
var vfs = require('vinyl-fs');
module.exports = function (dir) {
var pending = [];
function schedule(work) {
pending.push(work);
if (pending.length === 1) {
performNext();
}
}
function performNext() {
var work = pending[0];
work(function () {
pending.splice(0, 1);
if (pending.length > 0) {
performNext();
}
});
}
function nodeToVinyl(node) {
return new File({
cwd: node.base,
base: node.base,
path: path.join(node.base, node.name),
stat: node.stat,
contents: node.data
});
}
return function (tree) {
return new mix.Stream(function (sink) {
schedule(function (done) {
rimraf(dir, function (error) {
if (error) {
console.log(error);
sink.close();
done();
}
var stream = vfs.dest(dir);
tree.nodes.map(nodeToVinyl).forEach(function (file) {
stream.write(file);
});
stream.end();
stream.on('finish', function () {
sink.close(tree);
done();
});
stream.on('error', function (error) {
console.log(error);
sink.close();
done();
});
});
});
});
}
};
| var File = require('vinyl');
var mix = require('mix');
var path = require('path');
var rimraf = require('rimraf');
var vfs = require('vinyl-fs');
module.exports = function (dir) {
var pending = [];
function schedule(work) {
pending.push(work);
if (pending.length === 1) {
performNext();
}
}
function performNext() {
var work = pending[0];
work(function () {
pending.splice(0, 1);
if (pending.length > 0) {
performNext();
}
});
}
function nodeToVinyl(node) {
return new File({
cwd: node.base,
base: node.base,
path: path.join(node.base, node.name),
stat: node.stat,
contents: node.data
});
}
return function (tree) {
return new mix.Stream(function (sink) {
schedule(function (done) {
rimraf(dir, function (error) {
if (!error) {
var stream = vfs.dest(dir);
tree.nodes.map(nodeToVinyl).forEach(function (file) {
stream.write(file);
});
stream.end();
console.log('TODO');
} else {
console.log(error);
sink.close();
done();
}
});
});
});
}
};
|
Change argument names for thenable for clarity | 'use strict';
var Promise = require('bluebird');
var sinon = require('sinon');
function thenable (promiseFactory) {
return Object.getOwnPropertyNames(Promise.prototype)
.filter(function (method) {
return method !== 'then';
})
.reduce(function (acc, method) {
acc[method] = function () {
var args = arguments;
var promise = this.then();
return promise[method].apply(promise, args);
};
return acc;
},
{
then: function (onFulfill, onReject) {
return promiseFactory().then(onFulfill, onReject);
}
});
}
function resolves (value) {
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve) {
resolve(value);
});
}));
}
sinon.stub.resolves = resolves;
sinon.behavior.resolves = resolves;
function rejects (err) {
if (typeof err === 'string') {
err = new Error(err);
}
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve, reject) {
reject(err);
});
}));
}
sinon.stub.rejects = rejects;
sinon.behavior.rejects = rejects;
module.exports = function (_Promise_) {
if (typeof _Promise_ !== 'function') {
throw new Error('A Promise constructor must be provided');
}
else {
Promise = _Promise_;
}
return sinon;
};
| 'use strict';
var Promise = require('bluebird');
var sinon = require('sinon');
function thenable (promiseFactory) {
return Object.getOwnPropertyNames(Promise.prototype)
.filter(function (method) {
return method !== 'then';
})
.reduce(function (acc, method) {
acc[method] = function () {
var args = arguments;
var promise = this.then();
return promise[method].apply(promise, args);
};
return acc;
},
{
then: function (resolve, reject) {
return promiseFactory().then(resolve, reject);
}
});
}
function resolves (value) {
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve) {
resolve(value);
});
}));
}
sinon.stub.resolves = resolves;
sinon.behavior.resolves = resolves;
function rejects (err) {
if (typeof err === 'string') {
err = new Error(err);
}
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve, reject) {
reject(err);
});
}));
}
sinon.stub.rejects = rejects;
sinon.behavior.rejects = rejects;
module.exports = function (_Promise_) {
if (typeof _Promise_ !== 'function') {
throw new Error('A Promise constructor must be provided');
}
else {
Promise = _Promise_;
}
return sinon;
};
|
Use more descriptive variable name | import View from 'girder/views/View';
import { SORT_ASC, SORT_DESC } from 'girder/constants';
import SortCollectionWidgetTemplate from 'girder/templates/widgets/sortCollectionWidget.pug';
import 'bootstrap/js/dropdown';
/**
* This widget is used to provide a consistent widget for sorting
* pages of a Collection by a choosen field.
*/
var SortCollectionWidget = View.extend({
events: {
'click a.g-collection-sort-link': function (event) {
var sortField = $(event.currentTarget).attr('g-sort');
this.collection.sortField = sortField;
this.collection.fetch({}, true);
},
'click a.g-sort-order-button': function (event) {
if (this.collection.sortDir === SORT_ASC) {
this.collection.sortDir = SORT_DESC;
} else {
this.collection.sortDir = SORT_ASC;
}
this.collection.fetch({}, true);
}
},
initialize: function (settings) {
this.collection = settings.collection;
this.fields = settings.fields;
},
/**
* Do not call render() until the collection has been fetched once.
*/
render: function () {
this.$el.html(SortCollectionWidgetTemplate({
collection: this.collection,
fields: this.fields
}));
if (this.collection.sortDir === SORT_ASC) {
this.$('.g-down').addClass('hide');
} else {
this.$('.g-up').addClass('hide');
}
return this;
}
});
export default SortCollectionWidget;
| import View from 'girder/views/View';
import { SORT_ASC, SORT_DESC } from 'girder/constants';
import SortCollectionWidgetTemplate from 'girder/templates/widgets/sortCollectionWidget.pug';
import 'bootstrap/js/dropdown';
/**
* This widget is used to provide a consistent widget for sorting
* pages of a Collection by a choosen field.
*/
var SortCollectionWidget = View.extend({
events: {
'click a.g-collection-sort-link': function (event) {
var cid = $(event.currentTarget).attr('g-sort');
this.collection.sortField = cid;
this.collection.fetch({}, true);
},
'click a.g-sort-order-button': function (event) {
if (this.collection.sortDir === SORT_ASC) {
this.collection.sortDir = SORT_DESC;
} else {
this.collection.sortDir = SORT_ASC;
}
this.collection.fetch({}, true);
}
},
initialize: function (settings) {
this.collection = settings.collection;
this.fields = settings.fields;
},
/**
* Do not call render() until the collection has been fetched once.
*/
render: function () {
this.$el.html(SortCollectionWidgetTemplate({
collection: this.collection,
fields: this.fields
}));
if (this.collection.sortDir === SORT_ASC) {
this.$('.g-down').addClass('hide');
} else {
this.$('.g-up').addClass('hide');
}
return this;
}
});
export default SortCollectionWidget;
|
Replace boolean "forcexunit" with string "test-command" | package org.eobjects.build;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
public abstract class AbstractDotnetTestMojo extends AbstractDotnetMojo {
@Parameter(property = "dotnet.test.outputxml", required = false)
private File outputXml;
@Parameter(property = "dotnet.test.test-command", required = false, defaultValue = "test")
private String testCommand;
@Parameter(property = "dotnet.test.logger", required = false)
private String logger;
public void executeInternal() throws MojoFailureException {
final PluginHelper helper = getPluginHelper();
ArrayList<String> argsList = new ArrayList<String>(Arrays.asList("dotnet", testCommand, "-c", helper.getBuildConfiguration()));
if(outputXml != null) {
outputXml.getParentFile().mkdirs();
argsList.add("-xml");
argsList.add(outputXml.getPath());
}
if(logger != null) {
argsList.add("-l");
argsList.add(logger);
}
for (File subDirectory : helper.getProjectDirectories()) {
if (isTestRunnable(subDirectory)) {
helper.executeCommand(subDirectory, argsList.toArray(new String[argsList.size()]));
}
}
}
private boolean isTestRunnable(File subDirectory) {
return getPluginHelper().getProjectFile(subDirectory).isTestProject();
}
}
| package org.eobjects.build;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
public abstract class AbstractDotnetTestMojo extends AbstractDotnetMojo {
@Parameter(property = "dotnet.test.outputxml", required = false)
private File outputXml;
@Parameter(property = "dotnet.test.forcexunit", required = false)
private Boolean forceXUnit;
@Parameter(property = "dotnet.test.logger", required = false)
private String logger;
public void executeInternal() throws MojoFailureException {
final PluginHelper helper = getPluginHelper();
ArrayList<String> argsList = new ArrayList<String>(Arrays.asList("dotnet", forceXUnit ? "xunit" : "test", "-c", helper.getBuildConfiguration()));
if(outputXml != null) {
outputXml.getParentFile().mkdirs();
argsList.add("-xml");
argsList.add(outputXml.getPath());
}
if(logger != null) {
argsList.add("-l");
argsList.add(logger);
}
for (File subDirectory : helper.getProjectDirectories()) {
if (isTestRunnable(subDirectory)) {
helper.executeCommand(subDirectory, argsList.toArray(new String[argsList.size()]));
}
}
}
private boolean isTestRunnable(File subDirectory) {
return getPluginHelper().getProjectFile(subDirectory).isTestProject();
}
}
|
TST: Make sure there is an error field | import pytest
import log_parser
import os
@pytest.fixture
def parsed_log():
logname = os.path.join(os.path.split(os.path.abspath(__file__))[0],
'build.log')
gen = list(log_parser.read_log_from_script(logname))
parsed = {built_name: log_parser.parse_conda_build(lines)
for name, built_name, lines in gen}
return parsed
def test_parse_conda_build(parsed_log):
# make sure that we have at least one thing that was parsed
assert len(parsed_log) >= 1
def test_parse_init(parsed_log):
# make sure we are getting the build command out of every single entry
for pkg_name, parsed in parsed_log.items():
parsed_init = log_parser.parse_init(parsed['init'])
assert 'build_command' in parsed_init
assert 'err' in parsed_init
def test_parse_build(parsed_log):
# make sure we are getting either an error or the build string out of the
# build section
for pkg_name, parsed in parsed_log.items():
if 'build' not in parsed:
# not all packages will successfully build
continue
# if there is a build section, then parse it
parsed_build = log_parser.parse_build(parsed['build'])
if parsed_build['built_name'] == 'failed':
assert parsed_build['error'] != []
else:
assert parsed_build['error'] == []
| import pytest
import log_parser
import os
@pytest.fixture
def parsed_log():
logname = os.path.join(os.path.split(os.path.abspath(__file__))[0],
'build.log')
gen = list(log_parser.read_log_from_script(logname))
parsed = {built_name: log_parser.parse_conda_build(lines)
for name, built_name, lines in gen}
return parsed
def test_parse_conda_build(parsed_log):
# make sure that we have at least one thing that was parsed
assert len(parsed_log) >= 1
def test_parse_init(parsed_log):
# make sure we are getting the build command out of every single entry
for pkg_name, parsed in parsed_log.items():
parsed_init = log_parser.parse_init(parsed['init'])
assert 'build_command' in parsed_init
def test_parse_build(parsed_log):
# make sure we are getting either an error or the build string out of the
# build section
for pkg_name, parsed in parsed_log.items():
if 'build' not in parsed:
# not all packages will successfully build
continue
# if there is a build section, then parse it
parsed_build = log_parser.parse_build(parsed['build'])
if parsed_build['built_name'] == 'failed':
assert parsed_build['error'] != []
else:
assert parsed_build['error'] == []
|
Add Dependencies and Dependents formula | (function (env) {
"use strict";
env.ddg_spice_homebrew = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('homebrew');
}
Spice.add({
id: "homebrew",
name: "Formula",
data: api_result,
meta: {
sourceName: "Homebrew Formulas",
sourceUrl: 'http://brewformulas.org/' + api_result.formula
},
normalize: function(item) {
var boxData = [{heading: 'Formula Information:'}];
if (item.homepage) {
boxData.push({
label: "Homepage",
value: item.homepage,
url: item.homepage
});
}
if (item.version) {
boxData.push({
label: "Version",
value: item.version
})
}
if (item.dependencies) {
if (item.dependencies.length > 0) {
boxData.push({
label: "Dependencies",
value: item.dependencies.join(", ").toLowerCase()
});
}
}
if (item.dependents) {
if (item.dependents.length > 0) {
boxData.push({
label: "Dependents formula",
value: item.dependents.join(", ").toLowerCase()
});
}
}
if (item.reference) {
boxData.push({
label: "Reference",
value: item.reference
})
}
return {
title: item.formula,
subtitle: item.description,
infoboxData: boxData
}
},
templates: {
group: 'text',
options: {
content: Spice.homebrew.content,
moreAt: true
}
}
});
};
}(this));
| (function (env) {
"use strict";
env.ddg_spice_homebrew = function(api_result){
if (!api_result || api_result.error) {
return Spice.failed('homebrew');
}
Spice.add({
id: "homebrew",
name: "Formula",
data: api_result,
meta: {
sourceName: "Homebrew Formulas",
sourceUrl: 'http://brewformulas.org/' + api_result.formula
},
normalize: function(item) {
var boxData = [{heading: 'Formula Information:'}];
if (item.homepage) {
boxData.push({
label: "Homepage",
value: item.homepage,
url: item.homepage
});
}
if (item.version) {
boxData.push({
label: "Version",
value: item.version
})
}
if (item.reference) {
boxData.push({
label: "Reference",
value: item.reference
})
}
return {
title: item.formula,
subtitle: item.description,
infoboxData: boxData
}
},
templates: {
group: 'text',
options: {
content: Spice.homebrew.content,
moreAt: true
}
}
});
};
}(this));
|
Change _connect to connect, so that it can be used from within other modules | '''
Module to provide MySQL compatibility to salt.
In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs
might look like:
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
'''
import MySQLdb
__opts__ = {}
def connect():
'''
wrap authentication credentials here
'''
hostname = __opts__['mysql.host']
username = __opts__['mysql.user']
password = __opts__['mysql.pass']
dbport = __opts__['mysql.port']
dbname = __opts__['mysql.db']
db = MySQLdb.connect(
hostname,
username,
password,
dbname,
dbport,
)
db.autocommit(True)
return db
def status():
'''
Return the status of a MySQL server using the output
from the SHOW STATUS query.
CLI Example:
salt '*' mysql.status
'''
ret = {}
db = connect()
cur = db.cursor()
cur.execute('SHOW STATUS')
for i in xrange(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version():
'''
Return the version of a MySQL server using the output
from the SELECT VERSION() query.
CLI Example:
salt '*' mysql.version
'''
db = connect()
cur = db.cursor()
cur.execute('SELECT VERSION()')
row = cur.fetchone()
return row
| '''
Module to provide MySQL compatibility to salt.
In order to connect to MySQL, certain configuration is required
in /etc/salt/minion on the relevant minions. Some sample configs
might look like:
mysql.host: 'localhost'
mysql.port: 3306
mysql.user: 'root'
mysql.pass: ''
mysql.db: 'mysql'
'''
import MySQLdb
__opts__ = {}
def _connect():
'''
wrap authentication credentials here
'''
hostname = __opts__['mysql.host']
username = __opts__['mysql.user']
password = __opts__['mysql.pass']
dbport = __opts__['mysql.port']
dbname = __opts__['mysql.db']
db = MySQLdb.connect(
hostname,
username,
password,
dbname,
dbport,
)
db.autocommit(True)
return db
def status():
'''
Return the status of a MySQL server using the output
from the SHOW STATUS query.
CLI Example:
salt '*' mysql.status
'''
ret = {}
db = _connect()
cur = db.cursor()
cur.execute('SHOW STATUS')
for i in xrange(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
def version():
'''
Return the version of a MySQL server using the output
from the SELECT VERSION() query.
CLI Example:
salt '*' mysql.version
'''
db = _connect()
cur = db.cursor()
cur.execute('SELECT VERSION()')
row = cur.fetchone()
return row
|
Remove question, and minor correction | var data = {
"title": "Programmeringspraxis",
"questions": [
{
"description": "En funktion som har bieffekter kan ej anses vara korrekt",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}, {
"description": "En enradskommentar ska beskriva vad koden gör, inte varför",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}, {
"description": "En docstring ska sammanfatta vad funktionen gör, inte varför funktionen gör det",
"alternatives": ["Sant", "Falskt"],
"answer": "Sant"
}, {
"description": "Samtliga kommentarer i en funktion utgör funktionens kontrakt",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}, {
"description": "Alla kommentarer ska skrivas med fullständiga meningar",
"alternatives": ["Sant", "Falskt"],
"answer": "Sant"
}
]
}
| var data = {
"title": "Programmeringspraxis",
"questions": [
{
"description": "En funktion som har bieffekter kan ej anses vara korrekt",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}, {
"description": "Något annat än indata, utdata och bieffekter behöver ej beskrivas i funktionens kontrakt",
"alternatives": ["Sant", "Falskt"],
"answer": "Sant"
}, {
"description": "En 'single line'-kommentar ska beskriva vad koden gör, inte varför",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}, {
"description": "En docstring ska sammanfatta vad funktionen gör, inte varför funktionen gör det",
"alternatives": ["Sant", "Falskt"],
"answer": "Sant"
}, {
"description": "Samtliga kommentarer i en funktion utgör funktionens kontrakt",
"alternatives": ["Sant", "Falskt"],
"answer": "Falskt"
}, {
"description": "Alla kommentarer ska skrivas med fullständiga meningar",
"alternatives": ["Sant", "Falskt"],
"answer": "Sant"
}
]
}
|
Change all js to point to krisk repo |
from collections import OrderedDict
from IPython.display import Javascript
import json
from krisk.util import join_current_dir
ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/'
ECHARTS_FILE = 'echarts.min'
d_paths = OrderedDict({})
THEMES = ['dark','vintage','roma','shine','infographic','macarons']
THEMES_URL='//echarts.baidu.com/asset/theme/'
PATH_LOCAL = join_current_dir('static')
# PATH_LOCAL = 'pandas-echarts/krisk/static'
#TODO FIX LOCAL PATH! NEED TO DO nbextension install
# def init_notebook():
# """Inject Javascript to notebook, default using local js.
# """
# return Javascript("""
# require.config({
# baseUrl : '%s',
# paths: {
# echarts: 'echarts.min'
# }
# });
# """ % PATH_LOCAL)
def init_notebook():
"""Inject Javascript to notebook, default using local js.
"""
return Javascript("""
require.config({
baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static",
waitSeconds: 15
});
""")
def get_paths():
return ['echarts'] + THEMES |
from collections import OrderedDict
from IPython.display import Javascript
import json
from krisk.util import join_current_dir
ECHARTS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/3.2.0/'
ECHARTS_FILE = 'echarts.min'
d_paths = OrderedDict({})
THEMES = ['dark','vintage','roma','shine','infographic','macarons']
THEMES_URL='//echarts.baidu.com/asset/theme/'
PATH_LOCAL = join_current_dir('static')
# PATH_LOCAL = 'pandas-echarts/krisk/static'
#TODO FIX LOCAL PATH! NEED TO DO nbextension install
# def init_notebook():
# """Inject Javascript to notebook, default using local js.
# """
# return Javascript("""
# require.config({
# baseUrl : '%s',
# paths: {
# echarts: 'echarts.min'
# }
# });
# """ % PATH_LOCAL)
def init_notebook():
"""Inject Javascript to notebook, default using local js.
"""
return Javascript("""
require.config({
baseUrl : "//rawgit.com/napjon/krisk/master/krisk/static",
paths: {
echarts: "//cdnjs.cloudflare.com/ajax/libs/echarts/3.2.1/echarts.min"
},
waitSeconds: 15
});
""")
def get_paths():
return ['echarts'] + THEMES
|
Fix JSON encoding of empty field | function submit_item_form(controls, url) {
var data = { };
for(var i=0; i<controls.length; ++i) {
var control = controls[i];
var element = $("#"+control);
var encoder = window["encode_"+element.data("rm-type")];
var value = null;
if(typeof(encoder) != "undefined") {
value = encoder(element.val());
}
else {
value = element.val();
}
data[control] = value;
}
$.ajax({
type: "PATCH", url: url,
data: JSON.stringify(data), contentType: "application/json",
dataType: "json",
success: function (data, text, xhr) {
window.location.href = window.location;
},
error: function (xhr, status, error) {
$("html").html(xhr.responseText);
}
});
}
function encode_list(data) {
if(data != "") {
return data.split(/[\s,]+/);
}
else {
return [];
}
}
function format_dates(dates) {
for(var i=0; i<dates.length; ++i) {
var element = $(dates[i]);
var content = element.html();
if(content != "") {
var date = new Date(content);
element.html(date.toLocaleString());
}
}
}
| function submit_item_form(controls, url) {
var data = { };
for(var i=0; i<controls.length; ++i) {
var control = controls[i];
var element = $("#"+control);
var encoder = window["encode_"+element.data("rm-type")];
var value = null;
if(typeof(encoder) != "undefined") {
value = encoder(element.val());
}
else {
value = element.val();
}
data[control] = value;
}
$.ajax({
type: "PATCH", url: url,
data: JSON.stringify(data), contentType: "application/json",
dataType: "json",
success: function (data, text, xhr) {
window.location.href = window.location;
},
error: function (xhr, status, error) {
$("html").html(xhr.responseText);
}
});
}
function encode_list(data) {
return data.split(/[\s,]+/);
}
function format_dates(dates) {
for(var i=0; i<dates.length; ++i) {
var element = $(dates[i]);
var content = element.html();
if(content != "") {
var date = new Date(content);
element.html(date.toLocaleString());
}
}
}
|
Deploy Travis CI build 717 to GitHub | #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = NotImplemented
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
setuptools.setup(
name=__project__,
version=__version__,
description="A sample project templated from jacebrowning/template-python.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=LONG_DESCRIPTION,
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
| #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = "Coming soon..."
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
setuptools.setup(
name=__project__,
version=__version__,
description="A sample project templated from jacebrowning/template-python.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='[email protected]',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=LONG_DESCRIPTION,
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
|
Add text domain to translatable string | <?php
/**
* NOTE: Keep code in this file compatible with PHP 5.2
*/
define('MINIMUM_PHP', '7.0');
define('MINIMUM_WP', '4.7');
if (version_compare(PHP_VERSION, MINIMUM_PHP, '<') ||
version_compare(get_bloginfo('version'), MINIMUM_WP, '<')
) {
add_action('admin_notices', 'printJentilReqNotice');
deactivateJentil();
} else {
require __DIR__.'/vendor/autoload.php';
add_action('after_setup_theme', 'runJentil', 0);
}
function runJentil()
{
Jentil()->run();
}
function printJentilReqNotice()
{
echo '<div class="notice notice-error">
<p>'.
sprintf(
esc_html__(
'%1$s theme has been deactivated as it requires PHP >= %2$s and WordPress >= %3$s',
'jentil'
),
'<code>jentil</code>',
'<strong>'.MINIMUM_PHP.'</strong>',
'<strong>'.MINIMUM_WP.'</strong>'
).
'</p>
</div>';
}
function deactivateJentil()
{
$themes = wp_get_themes(['allowed' => true]);
unset($themes['jentil']);
$theme = reset($themes);
$name = null === key($themes) ? '' : $theme->get_stylesheet();
$parent = $name ? $theme->get_template() : '';
update_option('stylesheet', $name);
update_option('template', $parent);
}
| <?php
/**
* NOTE: Keep code in this file compatible with PHP 5.2
*/
define('MINIMUM_PHP', '7.0');
define('MINIMUM_WP', '4.7');
if (version_compare(PHP_VERSION, MINIMUM_PHP, '<') ||
version_compare(get_bloginfo('version'), MINIMUM_WP, '<')
) {
add_action('admin_notices', 'printJentilReqNotice');
deactivateJentil();
} else {
require __DIR__.'/vendor/autoload.php';
add_action('after_setup_theme', 'runJentil', 0);
}
function runJentil()
{
Jentil()->run();
}
function printJentilReqNotice()
{
echo '<div class="notice notice-error">
<p>'.
sprintf(
__(
'%1$s theme has been deactivated as it requires PHP >= %2$s and WordPress >= %3$s'
),
'<code>jentil</code>',
'<strong>'.MINIMUM_PHP.'</strong>',
'<strong>'.MINIMUM_WP.'</strong>'
).
'</p>
</div>';
}
function deactivateJentil()
{
$themes = wp_get_themes(['allowed' => true]);
unset($themes['jentil']);
$theme = reset($themes);
$name = null === key($themes) ? '' : $theme->get_stylesheet();
$parent = $name ? $theme->get_template() : '';
update_option('stylesheet', $name);
update_option('template', $parent);
}
|
Update to use chronicle bytes - there are a number of tests that are failing and are marked with ignore. | /*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.bytes;
/**
* @author peter.lawrey
*/
public enum StopCharTesters implements StopCharTester {
COMMA_STOP {
@Override
public boolean isStopChar(int ch) {
return ch < ' ' || ch == ',';
}
}, CONTROL_STOP {
@Override
public boolean isStopChar(int ch) {
return ch < ' ';
}
},
SPACE_STOP {
@Override
public boolean isStopChar(int ch) {
return Character.isWhitespace(ch) || ch == 0;
}
},
QUOTES {
@Override
public boolean isStopChar(int ch) throws IllegalStateException {
return ch == '"' || ch <= 0;
}
},
ALL {
@Override
public boolean isStopChar(int ch) {
return ch < 0;
}
};
}
| /*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.chronicle.bytes;
/**
* @author peter.lawrey
*/
public enum StopCharTesters implements StopCharTester {
COMMA_STOP {
@Override
public boolean isStopChar(int ch) {
return ch < ' ' || ch == ',';
}
}, CONTROL_STOP {
@Override
public boolean isStopChar(int ch) {
return ch < ' ';
}
},
SPACE_STOP {
@Override
public boolean isStopChar(int ch) {
return Character.isWhitespace(ch) || ch == 0;
}
},
QUOTES {
@Override
public boolean isStopChar(int ch) throws IllegalStateException {
return ch == '"' || ch <= 0;
}
};
}
|
Make code compatible with PHP < 8 | <?php
declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\Console;
use Rebing\GraphQL\Console\SchemaConfigMakeCommand;
use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait;
use Rebing\GraphQL\Tests\TestCase;
class SchemaConfigMakeCommandTest extends TestCase
{
use MakeCommandAssertionTrait;
/**
* @dataProvider dataForMakeCommand
*/
public function testCommand(
string $inputName,
string $expectedFilename,
string $expectedClassDefinition
): void {
$this->assertMakeCommand(
'Schema',
SchemaConfigMakeCommand::class,
$inputName,
$expectedFilename,
'App\\\\GraphQL\\\\Schemas',
$expectedClassDefinition
);
}
public function dataForMakeCommand(): array
{
return [
'Example' => [
'inputName' => 'Example',
'expectedFilename' => 'GraphQL/Schemas/Example.php',
'expectedClassDefinition' => 'Example implements ConfigConvertible',
],
'ExampleSchema' => [
'inputName' => 'ExampleSchema',
'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php',
'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible',
],
];
}
}
| <?php
declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\Console;
use Rebing\GraphQL\Console\SchemaConfigMakeCommand;
use Rebing\GraphQL\Tests\Support\Traits\MakeCommandAssertionTrait;
use Rebing\GraphQL\Tests\TestCase;
class SchemaConfigMakeCommandTest extends TestCase
{
use MakeCommandAssertionTrait;
/**
* @dataProvider dataForMakeCommand
*/
public function testCommand(
string $inputName,
string $expectedFilename,
string $expectedClassDefinition
): void {
$this->assertMakeCommand(
'Schema',
SchemaConfigMakeCommand::class,
$inputName,
$expectedFilename,
'App\\\\GraphQL\\\\Schemas',
$expectedClassDefinition,
);
}
public function dataForMakeCommand(): array
{
return [
'Example' => [
'inputName' => 'Example',
'expectedFilename' => 'GraphQL/Schemas/Example.php',
'expectedClassDefinition' => 'Example implements ConfigConvertible',
],
'ExampleSchema' => [
'inputName' => 'ExampleSchema',
'expectedFilename' => 'GraphQL/Schemas/ExampleSchema.php',
'expectedClassDefinition' => 'ExampleSchema implements ConfigConvertible',
],
];
}
}
|
Modify the people role enum | /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.huntering.common.plugin.entity;
/**
* <p>实体实现该接口,表示需要进行状态管理
*/
public interface Stateable<T extends Enum<? extends Stateable.Status>> {
public void setStatus(T status);
public T getStatus();
/**
* 标识接口,所有状态实现,需要实现该状态接口
*/
public static interface Status {
}
/**
* 审核状态
*/
public static enum RegisterStatus implements Status {
waiting("等待审核"), fail("审核失败"), success("审核成功");
private final String info;
private RegisterStatus(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
}
/**
* 是否显示
*/
public static enum ShowStatus implements Status {
hide("不显示"), show("显示");
private final String info;
private ShowStatus(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
}
public static enum AuditStatus implements Status {
ACTIVE,
DELETED,
DISABLED
}
public static enum MessageType implements Status {
RESUME,
ACTIVITY
}
public static enum PeopleRole implements Status {
INTERVIEWER,
INTERVIEWEE,
PARTICIPANT
}
}
| /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.huntering.common.plugin.entity;
/**
* <p>实体实现该接口,表示需要进行状态管理
*/
public interface Stateable<T extends Enum<? extends Stateable.Status>> {
public void setStatus(T status);
public T getStatus();
/**
* 标识接口,所有状态实现,需要实现该状态接口
*/
public static interface Status {
}
/**
* 审核状态
*/
public static enum RegisterStatus implements Status {
waiting("等待审核"), fail("审核失败"), success("审核成功");
private final String info;
private RegisterStatus(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
}
/**
* 是否显示
*/
public static enum ShowStatus implements Status {
hide("不显示"), show("显示");
private final String info;
private ShowStatus(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
}
public static enum AuditStatus implements Status {
ACTIVE,
DELETED,
DISABLED
}
public static enum MessageType implements Status {
RESUME,
ACTIVITY
}
public static enum PeopleRole implements Status {
INTERVIEWER,
INTERVIEE,
PARTICIPANT
}
}
|
Disable SSL verification in requests.get | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
# disable SSL verification
__get = requests.get
def getNoSLL(*args, **kwargs):
kwargs["verify"] = False
return __get(*args, **kwargs)
requests.get = getNoSLL
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
| # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
|
Add event smoke test, not automated (yet) | var window = Ti.UI.createWindow({
theme: "Theme.AppCompat.Light"
});
var section = Ti.UI.createListSection({});
var list = require('power-templates').createListView({
templates: {
"simple": {
properties: {
// use functions for property evaluation!
itemId: '[ id ]',
},
childTemplates: [
{
type: 'Ti.UI.Label',
if: "[ true ]",
properties: {
text: '[ name ]',
top: 10,
backgroundColor: '#109F',
right: '[ valid ? 40 : 10 ]',
bottom: 10,
left: 10
},
events: {
"click": function (event) {
alert('You clicked item №' + event.itemId);
}
}
},
{
type: 'Ti.UI.Label',
if: "[ valid ]",
properties: {
text: '✔︎',
top: 10,
right: 10,
bottom: 10
}
}
]
}
},
sections: [ section ]
});
var data = [
{
id: 1,
valid: true,
name: 'Lorem'
},
{
id: 2,
valid: false,
name: 'Ipsum'
},
{
id: 3,
valid: true,
name: 'Dolor'
}
];
section.items = data.map(list.powerTemplates.simple.parse);
window.add(list);
window.open();
| var window = Ti.UI.createWindow({
theme: "Theme.AppCompat.Light"
});
var section = Ti.UI.createListSection({});
var list = require('power-templates').createListView({
templates: {
"simple": {
properties: {
// use functions for property evaluation!
itemId: '[ id ]',
},
childTemplates: [
{
type: 'Ti.UI.Label',
if: "[ true ]",
properties: {
text: '[ name ]',
top: 10,
backgroundColor: '#109F',
right: '[ valid ? 40 : 10 ]',
bottom: 10,
left: 10
}
},
{
type: 'Ti.UI.Label',
if: "[ valid ]",
properties: {
text: '✔︎',
top: 10,
right: 10,
bottom: 10
}
}
]
}
},
sections: [ section ]
});
var data = [
{
id: 1,
valid: true,
name: 'Lorem'
},
{
id: 2,
valid: false,
name: 'Ipsum'
},
{
id: 3,
valid: true,
name: 'Dolor'
}
];
section.items = data.map(list.powerTemplates.simple.parse);
window.add(list);
window.open();
|
Use Norwegian 'og', not 'and' | const Job = ({ locations, deadline, companyImage, companyName, jobTitle, ingress, jobName }) => {
if (locations.length >= 2) {
locations = `${locations.slice(0, -1).join(', ')} og ${locations[locations.length - 1]}`;
} else if (locations.length === 0) {
locations = 'Ikke spesifisert';
}
return (
<article className="row">
<div className="col-xs-12 col-md-4">
<a href="/careeropportunity/4/">
<picture>
<source srcSet={companyImage.lg} media="(max-width: 992px)" />
<img src={companyImage.md} alt="Firmalogo" />
</picture>
</a>
</div>
<div className="col-xs-12 col-md-8">
<h1>
<a href="/careeropportunity/4/">{companyName} - {jobTitle}</a>
</h1>
<div className="ingress">{ingress}</div>
<div className="meta">
<div className="col-md-4">
<p>Type: {jobName}</p>
</div>
<div className="col-md-4">
<p>Sted: {locations}</p>
</div>
<div className="col-md-4">
<p>Frist: {deadline}</p>
</div>
</div>
</div>
</article>
);
};
export default Job;
| const Job = ({ locations, deadline, companyImage, companyName, jobTitle, ingress, jobName }) => {
if (locations.length >= 2) {
locations = `${locations.slice(0, -1).join(', ')} and ${locations[locations.length - 1]}`;
} else if (locations.length === 0) {
locations = 'Ikke spesifisert';
}
return (
<article className="row">
<div className="col-xs-12 col-md-4">
<a href="/careeropportunity/4/">
<picture>
<source srcSet={companyImage.lg} media="(max-width: 992px)" />
<img src={companyImage.md} alt="Firmalogo" />
</picture>
</a>
</div>
<div className="col-xs-12 col-md-8">
<h1>
<a href="/careeropportunity/4/">{companyName} - {jobTitle}</a>
</h1>
<div className="ingress">{ingress}</div>
<div className="meta">
<div className="col-md-4">
<p>Type: {jobName}</p>
</div>
<div className="col-md-4">
<p>Sted: {locations}</p>
</div>
<div className="col-md-4">
<p>Frist: {deadline}</p>
</div>
</div>
</div>
</article>
);
};
export default Job;
|
Add "lib" to typescript defs | var gulp = require('gulp');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var header = require('gulp-header');
var merge = require('merge2');
var pkg = require('./package.json');
var headerTemplate = '// <%= pkg.name %> v<%= pkg.version %>\n';
gulp.task('default', tscTask);
function tscTask() {
var tsResult = gulp
.src([
// this solves the 'cannot resolve Promise' issue
'node_modules/@types/core-js/index.d.ts',
'src/**/*.ts'
])
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
noEmitOnError: false,
lib: ["dom","es2015"]
}));
return merge([
tsResult.dts
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib')),
tsResult.js
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib'))
])
}
| var gulp = require('gulp');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var header = require('gulp-header');
var merge = require('merge2');
var pkg = require('./package.json');
var headerTemplate = '// <%= pkg.name %> v<%= pkg.version %>\n';
gulp.task('default', tscTask);
function tscTask() {
var tsResult = gulp
.src([
// this solves the 'cannot resolve Promise' issue
'node_modules/@types/core-js/index.d.ts',
'src/**/*.ts'
])
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
noEmitOnError: false
}));
return merge([
tsResult.dts
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib')),
tsResult.js
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib'))
])
}
|
Remove the source maps link from the bundles
We don’t serve the maps, and their absence generates a 404 error sometimes | /* eslint-env node */
const webpack = require('webpack');
const packageJson = require('./package.json');
const isProduction = process.env.NODE_ENV === 'production';
function getLicenseComment(version) {
return [
'Likely $version by Ilya Birman (ilyabirman.net)',
'Rewritten sans jQuery by Evgeny Steblinsky (volter9.github.io)',
'Supported by Ivan Akulov (iamakulov.com), Viktor Karpov (vitkarpov.com), and contributors',
'Inspired by Social Likes by Artem Sapegin (sapegin.me)',
].join('\n').replace(/\$version/g, version);
}
module.exports = {
entry: {
likely: './source/likely.js',
// [] is a workaround, see https://github.com/webpack/webpack/issues/300
'likely-commonjs': ['./source/index.js'],
},
output: {
filename: '[name].js',
library: 'likely',
libraryTarget: 'umd',
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
}],
},
devtool: false,
watch: !isProduction,
plugins: isProduction ? [
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compressor: {
// eslint-disable-next-line camelcase
screw_ie8: true,
},
}),
new webpack.BannerPlugin(getLicenseComment(packageJson.version)),
] : [],
};
| /* eslint-env node */
const webpack = require('webpack');
const packageJson = require('./package.json');
const isProduction = process.env.NODE_ENV === 'production';
function getLicenseComment(version) {
return [
'Likely $version by Ilya Birman (ilyabirman.net)',
'Rewritten sans jQuery by Evgeny Steblinsky (volter9.github.io)',
'Supported by Ivan Akulov (iamakulov.com), Viktor Karpov (vitkarpov.com), and contributors',
'Inspired by Social Likes by Artem Sapegin (sapegin.me)',
].join('\n').replace(/\$version/g, version);
}
module.exports = {
entry: {
likely: './source/likely.js',
// [] is a workaround, see https://github.com/webpack/webpack/issues/300
'likely-commonjs': ['./source/index.js'],
},
output: {
filename: '[name].js',
library: 'likely',
libraryTarget: 'umd',
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
}],
},
devtool: 'source-map',
watch: !isProduction,
plugins: isProduction ? [
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compressor: {
// eslint-disable-next-line camelcase
screw_ie8: true,
},
}),
new webpack.BannerPlugin(getLicenseComment(packageJson.version)),
] : [],
};
|
Add trigger to navigate() calls | define(['jquery', 'underscore', 'backbone', 'views'],
function($ , _ , Backbone , View ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showHome',
'about': 'showAbout',
'projects': 'showProjects',
'resume': 'showResume',
':string': 'showError'
},
showHome: function() {
var homeView = new View['home'];
homeView.render();
},
showAbout: function() {
var aboutView = new View['about'];
aboutView.render();
},
showProjects: function() {
var projectsView = new View['projects'];
projectsView.render();
},
showResume: function() {
var resumeView = new View['resume'];
resumeView.render();
},
showError: function(string) {
var errorView = new View['error'];
errorView.render();
}
});
function initialize() {
var appRouter = new AppRouter;
Backbone.history.start({ pushstate: true });
$('#toggle-menu').click(function() {
$('.navbar-content').toggleClass('expanded');
});
$(document).on('click', 'a', function(evt) {
if (this.host == location.host) {
evt.preventDefault();
var href = $(this).attr('href');
$('.navbar-content').removeClass('animate expanded');
Backbone.history.navigate(href, { trigger: true });
_.delay(function() {
$('.navbar-content').addClass('animate');
}, 50);
}
});
return appRouter;
}
return {
initialize: initialize
};
}); | define(['jquery', 'underscore', 'backbone', 'views'],
function($ , _ , Backbone , View ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showHome',
'about': 'showAbout',
'projects': 'showProjects',
'resume': 'showResume',
':string': 'showError'
},
showHome: function() {
var homeView = new View['home'];
homeView.render();
},
showAbout: function() {
var aboutView = new View['about'];
aboutView.render();
},
showProjects: function() {
var projectsView = new View['projects'];
projectsView.render();
},
showResume: function() {
var resumeView = new View['resume'];
resumeView.render();
},
showError: function(string) {
var errorView = new View['error'];
errorView.render();
}
});
function initialize() {
var appRouter = new AppRouter;
Backbone.history.start({ pushstate: true });
$('#toggle-menu').click(function() {
$('.navbar-content').toggleClass('expanded');
});
$(document).on('click', 'a', function(evt) {
if (this.host == location.host) {
evt.preventDefault();
var href = $(this).attr('href');
$('.navbar-content').removeClass('animate expanded');
Backbone.history.navigate(href, true);
_.delay(function() {
$('.navbar-content').addClass('animate');
}, 50);
}
});
return appRouter;
}
return {
initialize: initialize
};
}); |
Add docs to the ConfigCache. | import json
import threading
import uuid
class ConfigCache(object):
"""
The ConfigCache class stores an in-memory version of each
feed's configuration. As there may be multiple systems using
Thoonk with the same Redis server, and each with its own
ConfigCache instance, each ConfigCache has a self.instance
field to uniquely identify itself.
Attributes:
thoonk -- The main Thoonk object.
instance -- A hex string for uniquely identifying this
ConfigCache instance.
Methods:
invalidate -- Force a feed's config to be retrieved from
Redis instead of in-memory.
"""
def __init__(self, thoonk):
"""
Create a new configuration cache.
Arguments:
thoonk -- The main Thoonk object.
"""
self._feeds = {}
self.thoonk = thoonk
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
"""
Return a feed object for a given feed name.
Arguments:
feed -- The name of the requested feed.
"""
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.thoonk.feed_exists(feed):
raise FeedDoesNotExist
config = self.thoonk.redis.get('feed.config:%s' % feed)
config = json.loads(config)
feed_type = config.get(u'type', u'feed')
feed_class = self.thoonk.feedtypes[feed_type]
self._feeds[feed] = feed_class(self.thoonk, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
"""
Delete a configuration so that it will be retrieved from Redis
instead of from the cache.
Arguments:
feed -- The name of the feed to invalidate.
instance -- A UUID identifying the cache which made the
invalidation request.
delete -- Indicates if the entire feed object should be
invalidated, or just its configuration.
"""
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
| import json
import threading
import uuid
from thoonk.consts import *
class ConfigCache(object):
def __init__(self, pubsub):
self._feeds = {}
self.pubsub = pubsub
self.lock = threading.Lock()
self.instance = uuid.uuid4().hex
def __getitem__(self, feed):
with self.lock:
if feed in self._feeds:
return self._feeds[feed]
else:
if not self.pubsub.feed_exists(feed):
raise FeedDoesNotExist
config = json.loads(self.pubsub.redis.get(FEEDCONFIG % feed))
self._feeds[feed] = self.pubsub.feedtypes[config.get(u'type', u'feed')](self.pubsub, feed, config)
return self._feeds[feed]
def invalidate(self, feed, instance, delete=False):
if instance != self.instance:
with self.lock:
if feed in self._feeds:
if delete:
del self._feeds[feed]
else:
del self._feeds[feed].config
|
Check for null while checking for rows in grid children
If grid contains falsy children, i should be skipped | /* @flow */
'use strict';
import React, {Component} from 'react';
import {View, TouchableOpacity} from 'react-native';
import computeProps from '../Utils/computeProps';
import _ from 'lodash';
import Col from './Col';
import Row from './Row';
export default class GridNB extends Component {
prepareRootProps() {
var type = {
flex: 1,
flexDirection: this.ifRow() ? 'column' : 'row'
}
var defaultProps = {
style: type
}
return computeProps(this.props, defaultProps);
}
ifRow() {
var row = false;
React.Children.forEach(this.props.children, function (child) {
if(child && child.type == Row)
row = true;
})
return row;
}
setNativeProps(nativeProps) {
this._root.setNativeProps(nativeProps);
}
render() {
if(this.props.onPress){
return(
<TouchableOpacity onPress={this.props.onPress}>
<View
ref={component => this._root = component}
{...this.props}
{...this.prepareRootProps()}
>{this.props.children}</View>
</TouchableOpacity>
);
}
else{
return(
<View
ref={component => this._root = component}
{...this.props}
{...this.prepareRootProps()}
>{this.props.children}</View>
);
}
}
}
| /* @flow */
'use strict';
import React, {Component} from 'react';
import {View, TouchableOpacity} from 'react-native';
import computeProps from '../Utils/computeProps';
import _ from 'lodash';
import Col from './Col';
import Row from './Row';
export default class GridNB extends Component {
prepareRootProps() {
var type = {
flex: 1,
flexDirection: this.ifRow() ? 'column' : 'row'
}
var defaultProps = {
style: type
}
return computeProps(this.props, defaultProps);
}
ifRow() {
var row = false;
React.Children.forEach(this.props.children, function (child) {
if(child.type == Row)
row = true;
})
return row;
}
setNativeProps(nativeProps) {
this._root.setNativeProps(nativeProps);
}
render() {
if(this.props.onPress){
return(
<TouchableOpacity onPress={this.props.onPress}>
<View
ref={component => this._root = component}
{...this.props}
{...this.prepareRootProps()}
>{this.props.children}</View>
</TouchableOpacity>
);
}
else{
return(
<View
ref={component => this._root = component}
{...this.props}
{...this.prepareRootProps()}
>{this.props.children}</View>
);
}
}
}
|
Refactor to call getDetail on componentDidMount rather than on constructor | import React from 'react';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
class ConferenceDetail extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount(){
// Initialize
this.props.getDetail(model =>{
this.setState(model);
});
// Listen to watcher event.
this.props.eventEmitter.on('change', model => {
this.setState(model);
});
}
toEther(value){
return this.props.web3.fromWei(value, "ether").toString();
}
toNumber(value){
if(value) return value.toNumber();
}
render() {
return (
<div>
<Subheader>Party Info</Subheader>
<List>
<ListItem primaryText="Name" secondaryText={this.state.name} />
<ListItem primaryText="Deposit" secondaryText={this.toEther(this.state.deposit)} />
</List>
<Divider />
<Subheader>Current stake</Subheader>
<List>
<ListItem primaryText="Pot" secondaryText={this.toEther(this.state.pot)} />
<ListItem primaryText="Balance" secondaryText={this.toEther(this.state.balance)} />
<ListItem primaryText="Registered" secondaryText={this.toNumber(this.state.registered)} />
<ListItem primaryText="Attended" secondaryText={this.toNumber(this.state.attended)} />
</List>
</div>
);
}
}
export default ConferenceDetail;
| import React from 'react';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
class ConferenceDetail extends React.Component {
constructor(props) {
super(props);
this.state = {};
// Initialize
this.props.getDetail(model =>{
this.setState(model);
});
// Listen to watcher event.
this.props.eventEmitter.on('change', model => {
this.setState(model);
});
}
toEther(value){
return this.props.web3.fromWei(value, "ether").toString();
}
toNumber(value){
if(value) return value.toNumber();
}
render() {
return (
<div>
<Subheader>Party Info</Subheader>
<List>
<ListItem primaryText="Name" secondaryText={this.state.name} />
<ListItem primaryText="Deposit" secondaryText={this.toEther(this.state.deposit)} />
</List>
<Divider />
<Subheader>Current stake</Subheader>
<List>
<ListItem primaryText="Pot" secondaryText={this.toEther(this.state.pot)} />
<ListItem primaryText="Balance" secondaryText={this.toEther(this.state.balance)} />
<ListItem primaryText="Registered" secondaryText={this.toNumber(this.state.registered)} />
<ListItem primaryText="Attended" secondaryText={this.toNumber(this.state.attended)} />
</List>
</div>
);
}
}
export default ConferenceDetail;
|
Improve loading of payload from json | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload')
try:
payload_data = json.loads(payload)
except (ValueError, TypeError):
return 'Bad request', 400
hook_data = parse_hook_data(payload_data)
repository = db.session.query(Repository).filter_by(
name=hook_data['repo_name'], user=hook_data['repo_user']
).first()
if repository is None:
repository = Repository(
name=hook_data['repo_name'],
user=hook_data['repo_user'],
url=hook_data['repo_url']
)
db.session.add(repository)
db.session.commit()
commit = db.session.query(Commit).filter_by(
hash=hook_data['hash'], repository_id=repository.id
).first()
if commit is None:
commit = Commit(
repository_id=repository.id,
hash=hook_data['hash'],
ref=hook_data['ref'],
compare_url=hook_data['compare_url'],
committer_name=hook_data['committer_name'],
committer_email=hook_data['committer_email'],
message=hook_data['message']
)
db.session.add(commit)
db.session.commit()
return 'OK'
| from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
payload_data = json.loads(payload)
except ValueError:
return 'Bad request', 400
hook_data = parse_hook_data(payload_data)
repository = db.session.query(Repository).filter_by(
name=hook_data['repo_name'], user=hook_data['repo_user']
).first()
if repository is None:
repository = Repository(
name=hook_data['repo_name'],
user=hook_data['repo_user'],
url=hook_data['repo_url']
)
db.session.add(repository)
db.session.commit()
commit = db.session.query(Commit).filter_by(
hash=hook_data['hash'], repository_id=repository.id
).first()
if commit is None:
commit = Commit(
repository_id=repository.id,
hash=hook_data['hash'],
ref=hook_data['ref'],
compare_url=hook_data['compare_url'],
committer_name=hook_data['committer_name'],
committer_email=hook_data['committer_email'],
message=hook_data['message']
)
db.session.add(commit)
db.session.commit()
return 'OK'
|
Allow commands to define internal options
So those options don't appear in the help output | var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function (options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function (selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
for (const option of commandHelp.options) {
if (option.internal) {
continue;
}
console.log(` ${option.option}`);
console.log(` ${option.description}`);
}
}
console.log("");
}
};
module.exports = command;
| var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function(options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function(selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
commandHelp.options.forEach(option => {
console.log(` ${option.option}`);
console.log(` ${option.description}`);
});
}
console.log("");
}
};
module.exports = command;
|
Add default prop for page | /**
* @jsx React.DOM
*/
var React = require('react');
var Pdf = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
var self = this;
PDFJS.getDocument(this.props.file).then(function(pdf) {
pdf.getPage(self.props.page).then(function(page) {
self.setState({pdfPage: page, pdf: pdf});
});
});
},
componentWillReceiveProps: function(newProps) {
var self = this;
if (newProps.page) {
self.state.pdf.getPage(newProps.page).then(function(page) {
self.setState({pdfPage: page, pageId: newProps.page});
});
}
this.setState({
pdfPage: null
});
},
getDefaultProps: function() {
return {page: 1};
},
render: function() {
var self = this;
this.state.pdfPage && setTimeout(function() {
var canvas = self.getDOMNode(),
context = canvas.getContext('2d'),
scale = 1.0,
viewport = self.state.pdfPage.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
self.state.pdfPage.render(renderContext);
});
return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>;
}
});
module.exports = Pdf;
| /**
* @jsx React.DOM
*/
var React = require('react');
var Pdf = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
var self = this;
PDFJS.getDocument(this.props.file).then(function(pdf) {
pdf.getPage(self.props.page).then(function(page) {
self.setState({pdfPage: page, pdf: pdf});
});
});
},
componentWillReceiveProps: function(newProps) {
var self = this;
if (newProps.page) {
self.state.pdf.getPage(newProps.page).then(function(page) {
self.setState({pdfPage: page, pageId: newProps.page});
});
}
this.setState({
pdfPage: null
});
},
render: function() {
var self = this;
this.state.pdfPage && setTimeout(function() {
var canvas = self.getDOMNode(),
context = canvas.getContext('2d'),
scale = 1.0,
viewport = self.state.pdfPage.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
self.state.pdfPage.render(renderContext);
});
return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>;
}
});
module.exports = Pdf;
|
Add a comment (Test commit for codecov) | package com.smp.rxplayround.sample;
import com.smp.rxplayround.BasePlayground;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.Observer;
/**
* Created by myungpyo.shim on 2016. 4. 25..
* Simple observable test. just emit some strings.
*/
@Slf4j
public class Play1_EmitFromStringArray extends BasePlayground {
@Test
public void printStrings() throws Exception {
Observable.from(new String[]{"test1", "test2", "test3"})
.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
log.debug("onCompleted");
}
@Override
public void onError(Throwable e) {
log.debug("onError : {}", e.getMessage());
}
@Override
public void onNext(String s) {
log.debug("onNext : {}", s);
}
});
}
}
| package com.smp.rxplayround.sample;
import com.smp.rxplayround.BasePlayground;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.Observer;
/**
* Created by myungpyo.shim on 2016. 4. 25..
*/
@Slf4j
public class Play1_EmitFromStringArray extends BasePlayground {
@Test
public void printStrings() throws Exception {
Observable.from(new String[]{"test1", "test2", "test3"})
.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
log.debug("onCompleted");
}
@Override
public void onError(Throwable e) {
log.debug("onError : {}", e.getMessage());
}
@Override
public void onNext(String s) {
log.debug("onNext : {}", s);
}
});
}
}
|
Remove json_encode() on array keys | <?php
namespace LiteCQRS\Plugin\Doctrine\EventStore;
use LiteCQRS\DomainEvent;
use LiteCQRS\EventStore\EventStoreInterface;
use LiteCQRS\EventStore\SerializerInterface;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;
/**
* Store events in a database table using Doctrine DBAL.
*/
class TableEventStore implements EventStoreInterface
{
private $conn;
private $table;
private $serializer;
public function __construct(Connection $conn, SerializerInterface $serializer, $table = 'litecqrs_events')
{
$this->conn = $conn;
$this->serializer = $serializer;
$this->table = $table;
}
public function store(DomainEvent $event)
{
$header = $event->getMessageHeader();
$aggregateId = $header->aggregateId;
$this->conn->insert($this->table, array(
'event_id' => $header->id,
'aggregate_type' => $header->aggregateType,
'aggregate_id' => $aggregateId,
'event' => $event->getEventName(),
'event_date' => $header->date->format('Y-m-d H:i:s'),// looses microseconds precision
'command_id' => $header->commandId,
'session_id' => $header->sessionId,
'data' => $this->serializer->serialize($event, 'json'),
));
}
}
| <?php
namespace LiteCQRS\Plugin\Doctrine\EventStore;
use LiteCQRS\DomainEvent;
use LiteCQRS\EventStore\EventStoreInterface;
use LiteCQRS\EventStore\SerializerInterface;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;
/**
* Store events in a database table using Doctrine DBAL.
*/
class TableEventStore implements EventStoreInterface
{
private $conn;
private $table;
private $serializer;
public function __construct(Connection $conn, SerializerInterface $serializer, $table = 'litecqrs_events')
{
$this->conn = $conn;
$this->serializer = $serializer;
$this->table = $table;
}
public function store(DomainEvent $event)
{
$header = $event->getMessageHeader();
$aggregateId = $header->aggregateId;
if (is_array($aggregateId)) {
$aggregateId = json_encode($aggregateId);
}
$this->conn->insert($this->table, array(
'event_id' => $header->id,
'aggregate_type' => $header->aggregateType,
'aggregate_id' => $aggregateId,
'event' => $event->getEventName(),
'event_date' => $header->date->format('Y-m-d H:i:s'),// looses microseconds precision
'command_id' => $header->commandId,
'session_id' => $header->sessionId,
'data' => $this->serializer->serialize($event, 'json'),
));
}
}
|
Support fallback for restPrefix blueprint configuration
This will look for restPrefix first, then prefix if defined | /**
* Adds support for count blueprint and binds :model/count route for each RESTful model.
*/
var _ = require('lodash');
var actionUtil = require('./actionUtil');
var pluralize = require('pluralize');
const defaultCountBlueprint = function(req, res) {
var Model = actionUtil.parseModel(req);
var countQuery = Model.count(actionUtil.parseCriteria(req));
countQuery
.then(function(count) {
return res.ok({count : count})
});
};
module.exports = function (sails) {
return {
initialize: function(cb) {
var config = sails.config.blueprints;
var countFn = _.get(sails.middleware, 'blueprints.count') || defaultCountBlueprint;
sails.on('router:before', function() {
_.forEach(sails.models, function(model) {
var controller = sails.middleware.controllers[model.identity];
if (!controller) return;
var prefix = config.restPrefix || config.prefix;
var baseRoute = [prefix, model.identity].join('/');
if (config.pluralize && _.get(controller, '_config.pluralize', true)) {
baseRoute = pluralize(baseRoute);
}
var route = baseRoute + '/count';
sails.router.bind(route, countFn, null, {controller: model.identity});
});
});
cb();
}
}
};
| /**
* Adds support for count blueprint and binds :model/count route for each RESTful model.
*/
var _ = require('lodash');
var actionUtil = require('./actionUtil');
var pluralize = require('pluralize');
const defaultCountBlueprint = function(req, res) {
var Model = actionUtil.parseModel(req);
var countQuery = Model.count(actionUtil.parseCriteria(req));
countQuery
.then(function(count) {
return res.ok({count : count})
});
};
module.exports = function (sails) {
return {
initialize: function(cb) {
var config = sails.config.blueprints;
var countFn = _.get(sails.middleware, 'blueprints.count') || defaultCountBlueprint;
sails.on('router:before', function() {
_.forEach(sails.models, function(model) {
var controller = sails.middleware.controllers[model.identity];
if (!controller) return;
var baseRoute = [config.prefix, model.identity].join('/');
if (config.pluralize && _.get(controller, '_config.pluralize', true)) {
baseRoute = pluralize(baseRoute);
}
var route = baseRoute + '/count';
sails.router.bind(route, countFn, null, {controller: model.identity});
});
});
cb();
}
}
};
|
Add annotations to document some changes between 2.0.1 and 2.0.2
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14479 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3 | package bugIdeas;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Ideas_2009_01_14 {
@NoWarning("SF")
static String getNameCorrect(int value) {
String result = "";
switch (value) {
case 0:
result = "zero";
break;
case 1:
result = "one";
break;
case 2:
result = "two";
break;
case 3:
result = "three";
break;
case 4:
result = "four";
break;
default:
throw new IllegalArgumentException("Illegal agrument: " + value);
}
return "Answer is " + result;
}
@ExpectWarning("SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW")
@NoWarning("SF_SWITCH_NO_DEFAULT")
static String getNameBroken(int value) {
String result = "";
switch (value) {
case 0:
result = "zero";
break;
case 1:
result = "one";
break;
case 2:
result = "two";
break;
case 3:
result = "three";
break;
case 4:
result = "four";
default:
throw new IllegalArgumentException("Illegal argument: " + value);
}
return "Answer is " + result;
}
@ExpectWarning("VA_FORMAT_STRING_BAD_CONVERSION")
public static void main(String args[]) {
System.out.printf("%d%n", 100.0);
}
}
| package bugIdeas;
public class Ideas_2009_01_14 {
// static String getNameCorrect(int value) {
// String result = "";
// switch (value) {
// case 0:
// result = "zero";
// break;
// case 1:
// result = "one";
// break;
// case 2:
// result = "two";
// break;
// case 3:
// result = "three";
// break;
// case 4:
// result = "four";
// break;
// default:
// throw new IllegalArgumentException("Illegal agrument: " + value);
//
// }
// return "Answer is " + result;
// }
static String getNameBroken(int value) {
String result = "";
switch (value) {
case 0:
result = "zero";
break;
case 1:
result = "one";
break;
case 2:
result = "two";
break;
case 3:
result = "three";
break;
case 4:
result = "four";
default:
throw new IllegalArgumentException("Illegal agrument: " + value);
}
return "Answer is " + result;
}
public static void main(String args[]) {
System.out.printf("%d\n", 100.0);
}
}
|
Put a blank line among main suites | # -*- coding: utf-8 -*-
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
puts()
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
| # -*- coding: utf-8 -*-
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
|
Add support for minLength and limit in AutoComplete | import {bindable, customAttribute} from 'aurelia-templating';
import {inject} from 'aurelia-dependency-injection';
import {fireEvent} from '../common/events';
@customAttribute('md-autocomplete')
@inject(Element)
export class MdAutoComplete {
input = null;
@bindable() values = {};
@bindable() minLength = 1;
@bindable() limit = 20;
constructor(element) {
this.element = element;
}
attached() {
if (this.element.tagName.toLowerCase() === 'input') {
this.input = this.element;
} else if (this.element.tagName.toLowerCase() === 'md-input') {
this.input = this.element.au.controller.viewModel.input;
} else {
throw new Error('md-autocomplete must be attached to either an input or md-input element');
}
this.refresh();
}
detached() {
// remove .autocomplete-content children
$(this.input).siblings('.autocomplete-content').off('click');
$(this.input).siblings('.autocomplete-content').remove();
}
refresh() {
this.detached();
$(this.input).autocomplete({
data: this.values,
minLength: this.minLength,
limit: this.limit
});
// $('.autocomplete-content', this.element).on('click', () => {
// fireEvent(this.input, 'change');
// });
$(this.input).siblings('.autocomplete-content').on('click', () => {
fireEvent(this.input, 'change');
});
}
valuesChanged(newValue) {
this.refresh();
}
}
| import {bindable, customAttribute} from 'aurelia-templating';
import {inject} from 'aurelia-dependency-injection';
import {fireEvent} from '../common/events';
@customAttribute('md-autocomplete')
@inject(Element)
export class MdAutoComplete {
input = null;
@bindable() values = {};
constructor(element) {
this.element = element;
}
attached() {
if (this.element.tagName.toLowerCase() === 'input') {
this.input = this.element;
} else if (this.element.tagName.toLowerCase() === 'md-input') {
this.input = this.element.au.controller.viewModel.input;
} else {
throw new Error('md-autocomplete must be attached to either an input or md-input element');
}
this.refresh();
}
detached() {
// remove .autocomplete-content children
$(this.input).siblings('.autocomplete-content').off('click');
$(this.input).siblings('.autocomplete-content').remove();
}
refresh() {
this.detached();
$(this.input).autocomplete({
data: this.values
});
// $('.autocomplete-content', this.element).on('click', () => {
// fireEvent(this.input, 'change');
// });
$(this.input).siblings('.autocomplete-content').on('click', () => {
fireEvent(this.input, 'change');
});
}
valuesChanged(newValue) {
this.refresh();
}
}
|
Increase waiting time for MapR standalone | package com.splicemachine.test;
import com.splicemachine.concurrent.Threads;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
/**
* Waits for connections on a given host+port to be available.
*/
public class SpliceTestPlatformWait {
private static final long MAX_WAIT_SECS = TimeUnit.SECONDS.toSeconds(120);
/**
* argument 0 - hostname
* argument 1 - port
*/
public static void main(String[] arguments) throws IOException {
String hostname = arguments[0];
int port = Integer.valueOf(arguments[1]);
long startTime = System.currentTimeMillis();
long elapsedSecs = 0;
while (elapsedSecs < MAX_WAIT_SECS) {
try {
new Socket(hostname, port);
System.out.println("\nStarted\n");
break;
} catch (Exception e) {
System.out.println(format("SpliceTestPlatformWait: Not started, still waiting for '%s:%s'. %s of %s seconds elapsed.",
hostname, port, elapsedSecs, MAX_WAIT_SECS));
Threads.sleep(1, TimeUnit.SECONDS);
}
elapsedSecs = (long) ((System.currentTimeMillis() - startTime) / 1000d);
}
if (elapsedSecs >= MAX_WAIT_SECS) {
System.out.println(format("Waited %s seconds without success", MAX_WAIT_SECS));
System.exit(-1);
}
}
}
| package com.splicemachine.test;
import com.splicemachine.concurrent.Threads;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
/**
* Waits for connections on a given host+port to be available.
*/
public class SpliceTestPlatformWait {
private static final long MAX_WAIT_SECS = TimeUnit.SECONDS.toSeconds(90);
/**
* argument 0 - hostname
* argument 1 - port
*/
public static void main(String[] arguments) throws IOException {
String hostname = arguments[0];
int port = Integer.valueOf(arguments[1]);
long startTime = System.currentTimeMillis();
long elapsedSecs = 0;
while (elapsedSecs < MAX_WAIT_SECS) {
try {
new Socket(hostname, port);
System.out.println("\nStarted\n");
break;
} catch (Exception e) {
System.out.println(format("SpliceTestPlatformWait: Not started, still waiting for '%s:%s'. %s of %s seconds elapsed.",
hostname, port, elapsedSecs, MAX_WAIT_SECS));
Threads.sleep(1, TimeUnit.SECONDS);
}
elapsedSecs = (long) ((System.currentTimeMillis() - startTime) / 1000d);
}
if (elapsedSecs >= MAX_WAIT_SECS) {
System.out.println(format("Waited %s seconds without success", MAX_WAIT_SECS));
System.exit(-1);
}
}
}
|
Add lazy flag to avoid circular reference | <?php
namespace Finite\Bundle\FiniteBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class FiniteFiniteExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$factoryDefinition = $container->getDefinition('finite.factory');
foreach ($config as $key => $stateMachineConfig) {
$definition = clone $container->getDefinition('finite.array_loader');
$definition->addArgument($stateMachineConfig);
$definition->addTag('finite.loader');
$definition->setLazy(true);
$serviceId = 'finite.loader.'.$key;
$container->setDefinition($serviceId, $definition);
$factoryDefinition->addMethodCall('addLoader', array(new Reference($serviceId)));
}
$container->removeDefinition('finite.array_loader');
}
}
| <?php
namespace Finite\Bundle\FiniteBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class FiniteFiniteExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
$factoryDefinition = $container->getDefinition('finite.factory');
foreach ($config as $key => $stateMachineConfig) {
$definition = clone $container->getDefinition('finite.array_loader');
$definition->addArgument($stateMachineConfig);
$definition->addTag('finite.loader');
$serviceId = 'finite.loader.'.$key;
$container->setDefinition($serviceId, $definition);
$factoryDefinition->addMethodCall('addLoader', array(new Reference($serviceId)));
}
$container->removeDefinition('finite.array_loader');
}
}
|
Fix nierozpoznawania bledu gracza w pierwszym ruchu | from game import Game
from input_con import InputCon
from output_con import OutputCon
class Harness():
def __init__(self, output, inputs):
self._game = Game()
self._output = output
self._inputs = inputs
def Start(self):
self._output.show_welcome()
while True:
self._output.show_board(self._game.get_board())
player_id = self._game.get_turn_no()
player = self._game.get_turn()
self._output.show_player_turn(player)
while True:
move = self._inputs[player_id].get_move()
if move is False:
self._output.show_move_error(player)
continue
if self._game.make_move(move) is False:
self._output.show_move_error(player)
break
break
if not self._game.get_end():
continue
# End of game.
self._output.show_board(self._game.get_board())
w = self._game.get_winner()
if w is None:
# Draw.
self._output.show_draw()
else:
self._output.show_winner(w)
break
def main():
inputcon1 = InputCon()
inputcon2 = InputCon()
outputcon = OutputCon()
player_inputs = [ inputcon1, inputcon2 ]
player_output = outputcon
h = Harness(player_output, player_inputs)
h.Start()
if __name__ == "__main__":
main()
| from game import Game
from input_con import InputCon
from output_con import OutputCon
class Harness():
def __init__(self, output, inputs):
self._game = Game()
self._output = output
self._inputs = inputs
def Start(self):
self._output.show_welcome()
while True:
self._output.show_board(self._game.get_board())
player_id = self._game.get_turn_no()
player = self._game.get_turn()
self._output.show_player_turn(player)
while True:
move = self._inputs[player_id].get_move()
if move is None:
self._output.show_move_error(player)
continue
if self._game.make_move(move) is False:
self._output.show_move_error(player)
continue
break
if not self._game.get_end():
continue
# End of game.
self._output.show_board(self._game.get_board())
w = self._game.get_winner()
if w is None:
# Draw.
self._output.show_draw()
else:
self._output.show_winner(w)
break
def main():
inputcon1 = InputCon()
inputcon2 = InputCon()
outputcon = OutputCon()
player_inputs = [ inputcon1, inputcon2 ]
player_output = outputcon
h = Harness(player_output, player_inputs)
h.Start()
if __name__ == "__main__":
main()
|
Set callback param to false | <?php
use Proud\Core;
class AgencyMenu extends Core\ProudWidget {
function __construct() {
parent::__construct(
'agency_menu', // Base ID
__( 'Agency menu', 'wp-agency' ), // Name
array( 'description' => __( "Display an agency menu", 'wp-agency' ), ) // Args
);
}
function initialize() {
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function printWidget( $args, $instance ) {
$args = array(
'menu_class' => 'nav nav-pills nav-stacked submenu',
'fallback_cb' => false,
);
if ('agency' === get_post_type()) {
if ( $menu = get_post_meta( get_the_ID(), 'post_menu', true ) ) {
$args['menu'] = $menu;
wp_nav_menu( $args );
}
}
else {
global $pageInfo;
print_r($pageInfo);die();
$args = array(
'menu' => $pageInfo['menu'],
'menu_class' => 'nav nav-pills nav-stacked',
);
wp_nav_menu( $args );
}
}
}
// register Foo_Widget widget
function register_agency_menu_widget() {
register_widget( 'AgencyMenu' );
}
add_action( 'widgets_init', 'register_agency_menu_widget' ); | <?php
use Proud\Core;
class AgencyMenu extends Core\ProudWidget {
function __construct() {
parent::__construct(
'agency_menu', // Base ID
__( 'Agency menu', 'wp-agency' ), // Name
array( 'description' => __( "Display an agency menu", 'wp-agency' ), ) // Args
);
}
function initialize() {
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function printWidget( $args, $instance ) {
$args = array(
'menu_class' => 'nav nav-pills nav-stacked',
);
if ('agency' === get_post_type()) {
if ( $menu = get_post_meta( get_the_ID(), 'post_menu', true ) ) {
$args['menu'] = $menu;
wp_nav_menu( $args );
}
}
else {
global $pageInfo;
$args = array(
'menu' => $pageInfo['menu'],
'menu_class' => 'nav nav-pills nav-stacked',
);
wp_nav_menu( $args );
}
}
}
// register Foo_Widget widget
function register_agency_menu_widget() {
register_widget( 'AgencyMenu' );
}
add_action( 'widgets_init', 'register_agency_menu_widget' ); |
Change function name to Camel | #!/usr/bin/env python
def Parser(roman):
'''
This function receives a Roman Numeral String and convert it to an
Arabic Number.
parameters:
---------------------------------
roman: Roman Numearl string input'''
roman_dic = {'M': 1000, 'C': 100, 'L': 50, 'D': 500,
'X': 10, 'V': 5, 'I': 1}
if roman:
if not all(numeral in roman_dic for numeral in roman):
print 'Illegal letter(s).'
else:
num_ls = [roman_dic.get(numeral, None) for numeral in roman]
prev = num_ls[0]
total = 0
for val in num_ls:
if val <= prev:
total += val
prev = val
else:
total = total + val - (2 * prev)
prev = val
return total
else:
print 'Empty String!'
def main():
roman = raw_input('Input the Roman Numeral:\n')
print '{roman} is {arabic}.'.format(roman=roman,
arabic=Parser(roman))
if __name__ == '__main__':
main()
| #!/usr/bin/env python
def parser(roman):
'''
This function receives a Roman Numeral String and convert it to an
Arabic Number.
parameters:
---------------------------------
roman: Roman Numearl string input'''
roman_dic = {'M': 1000, 'C': 100, 'L': 50, 'D': 500,
'X': 10, 'V': 5, 'I': 1}
if roman:
if not all(numeral in roman_dic for numeral in roman):
print 'Illegal letter(s).'
else:
num_ls = [roman_dic.get(numeral, None) for numeral in roman]
prev = num_ls[0]
total = 0
for val in num_ls:
if val <= prev:
total += val
prev = val
else:
total = total + val - (2 * prev)
prev = val
return total
else:
print 'Empty String!'
def main():
roman = raw_input('Input the Roman Numeral:\n')
print '{roman} is {arabic}.'.format(roman=roman,
arabic=parser(roman))
if __name__ == '__main__':
main()
|
Update job properties in sendJobState | 'use strict';
var url = require('url');
var lodash = require('lodash');
var Promise = require('digdug/node_modules/dojo/Promise');
var DigdugSauceLabsTunnel = require('digdug/SauceLabsTunnel');
module.exports = function(options) {
return {
_tunnel: null,
updateCapabilities: function(caps) {
return lodash.merge({}, this._tunnel.extraCapabilities, caps);
},
start: function(callback) {
var tunnel = this._tunnel = new DigdugSauceLabsTunnel({
accessKey: options.sauceKey,
username: options.sauceUser,
tunnelId: +new Date()
});
tunnel.start().then(function(error) {
console.log('Using SauceLabs selenium server at: ' + tunnel.clientUrl);
callback(null, tunnel.clientUrl);
}, function(error) {
callback(error);
});
},
stop: function(results, callback) {
var sendJobStates = [];
var tunnel = this._tunnel;
results.forEach(function(result) {
result.clientIds.forEach(function(clientId) {
sendJobStates.push(tunnel.sendJobState(clientId, {
success: result.passed,
name: options.name,
buildId: options.buildId,
tags: options.tags
}));
});
});
Promise.all(sendJobStates).then(function() {
return tunnel.stop();
}).then(callback, callback);
}
};
};
| 'use strict';
var url = require('url');
var lodash = require('lodash');
var Promise = require('digdug/node_modules/dojo/Promise');
var DigdugSauceLabsTunnel = require('digdug/SauceLabsTunnel');
module.exports = function(options) {
return {
_tunnel: null,
updateCapabilities: function(caps) {
return lodash.merge({
name: options.sauceName,
build: options.sauceBuild,
tags: options.sauceTags
}, this._tunnel.extraCapabilities, caps);
},
start: function(callback) {
var tunnel = this._tunnel = new DigdugSauceLabsTunnel({
accessKey: options.sauceKey,
username: options.sauceUser,
tunnelId: +new Date()
});
tunnel.start().then(function(error) {
console.log('Using SauceLabs selenium server at: ' + tunnel.clientUrl);
callback(null, tunnel.clientUrl);
}, function(error) {
callback(error);
});
},
stop: function(results, callback) {
var sendJobStates = [];
var tunnel = this._tunnel;
results.forEach(function(result) {
result.clientIds.forEach(function(clientId) {
sendJobStates.push(tunnel.sendJobState(clientId, {passed: result.passed}));
});
});
Promise.all(sendJobStates).then(function() {
return tunnel.stop();
}).then(callback, callback);
}
};
};
|
Add locales link for project show | import React, { PropTypes } from 'react'
import { List, ListItem } from 'material-ui/List';
import { Link } from 'react-router';
export default class Project extends React.Component {
static propTypes = {
project: PropTypes.object.isRequired,
locales: PropTypes.array.isRequired
}
render() {
const project = this.props.project;
const locales = this.props.locales;
return (
<div>
{project &&
<div>
<h1>{project.name}</h1>
<List>
{locales.map(function(locale, index) {
return (
<Link
key={locale.locale}
to={`/projects/${project.id}/locales/${locale.locale}`}
>
<ListItem
primaryText={locale.locale}
/>
</Link>
);
})}
</List>
</div>
}
</div>
);
}
} | import React, { PropTypes } from 'react'
import { List, ListItem } from 'material-ui/List';
export default class Project extends React.Component {
static propTypes = {
project: PropTypes.object.isRequired,
locales: PropTypes.array.isRequired
}
render() {
return (
<div>
{this.props.project &&
<div>
<h1>{this.props.project.name}</h1>
<List>
{this.props.locales.map(function(locale, index) {
return <ListItem
key={locale.id.toString()}
primaryText={locale.locale}
/>
})}
</List>
</div>
}
</div>
);
}
} |
Return /api/endpoints data as array instead of dict | <?php
namespace OParl\Website\API\Controllers;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Symfony\Component\Yaml\Yaml;
class EndpointApiController
{
public function index(Request $request, Filesystem $fs)
{
$page = 0;
$itemsPerPage = 25;
if ($request->has('page')) {
$page = intval($request->get('page'));
}
$endpoints = collect(Yaml::parse($fs->get('live/endpoints.yml')))
->sortBy('name')
->map(function ($endpoint) {
return [
'url' => $endpoint['url'],
'title' => $endpoint['title'],
'description' => isset($endpoint['description']) ? $endpoint['description'] : null,
];
})
->values();
$data = $endpoints->forPage($page, $itemsPerPage);
$pageCount = floor($endpoints->count() / $itemsPerPage);
return response()->json([
'data' => $data,
'meta' => [
'page' => $page,
'total' => $pageCount,
'next' => ($pageCount > $page) ? route('api.endpoints.index', ['page' => ++$page]) : null,
],
]);
}
}
| <?php
namespace OParl\Website\API\Controllers;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Symfony\Component\Yaml\Yaml;
class EndpointApiController
{
public function index(Request $request, Filesystem $fs)
{
$page = 0;
$itemsPerPage = 25;
if ($request->has('page')) {
$page = intval($request->get('page'));
}
$endpoints = collect(Yaml::parse($fs->get('live/endpoints.yml')))
->sortBy('name')
->map(function ($endpoint) {
return [
'url' => $endpoint['url'],
'title' => $endpoint['title'],
'description' => isset($endpoint['description']) ? $endpoint['description'] : null,
];
});
$data = $endpoints->forPage($page, $itemsPerPage);
$pageCount = floor($endpoints->count() / $itemsPerPage);
return response()->json([
'data' => $data,
'meta' => [
'page' => $page,
'total' => $pageCount,
'next' => ($pageCount > $page) ? route('api.endpoints.index', ['page' => ++$page]) : null,
],
]);
}
}
|
Add trial period days option to initial plans. | import decimal
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
price = settings.PAYMENTS_PLANS[plan]["price"]
if isinstance(price, decimal.Decimal):
amount = int(100 * price)
else:
amount = int(100 * decimal.Decimal(str(price)))
stripe.Plan.create(
amount=amount,
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency=settings.PAYMENTS_PLANS[plan]["currency"],
trial_period_days=settings.PAYMENTS_PLANS[plan].get("trial_period_days"),
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for {0}".format(plan)
| import decimal
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
price = settings.PAYMENTS_PLANS[plan]["price"]
if isinstance(price, decimal.Decimal):
amount = int(100 * price)
else:
amount = int(100 * decimal.Decimal(str(price)))
stripe.Plan.create(
amount=amount,
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency=settings.PAYMENTS_PLANS[plan]["currency"],
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for {0}".format(plan)
|
Add use_decimal=True for json encoding | from urlparse import parse_qs
import DQXUtils
import simplejson
import responders
def application(environ, start_response):
returndata = dict((k,v[0]) for k,v in parse_qs(environ['QUERY_STRING']).items())
request_type = returndata['datatype']
tm = DQXUtils.Timer()
try:
resp_func = getattr(responders, request_type)#Fetch the handfler by request type, using some introspection magic in responders/__init__.py
except AttributeError:
raise Exception("Unknown request {0}".format(request_type))
response = resp_func(returndata)
#todo: make the response handling part of the handler, to avoid this branching
#This will become necessary when we have more handlers with different response types (e.g. other downloads)
if request_type == "downloadtable":#Respond to a download request with a text attachment
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),('Content-Disposition','attachment; filename=download.txt')]
start_response(status, response_headers)
for item in response:
yield item
else:#respond to any other event with json
response = simplejson.dumps(response, use_decimal=True)
status = '200 OK'
response_headers = [('Content-type', 'application/json'),
('Content-Length', str(len(response)))]
start_response(status, response_headers)
yield response
print('@@@@ Responded to {0} in {1}s'.format(request_type, tm.Elapsed())) | from urlparse import parse_qs
import DQXUtils
import simplejson
import responders
def application(environ, start_response):
returndata = dict((k,v[0]) for k,v in parse_qs(environ['QUERY_STRING']).items())
request_type = returndata['datatype']
tm = DQXUtils.Timer()
try:
resp_func = getattr(responders, request_type)#Fetch the handfler by request type, using some introspection magic in responders/__init__.py
except AttributeError:
raise Exception("Unknown request {0}".format(request_type))
response = resp_func(returndata)
#todo: make the response handling part of the handler, to avoid this branching
#This will become necessary when we have more handlers with different response types (e.g. other downloads)
if request_type == "downloadtable":#Respond to a download request with a text attachment
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),('Content-Disposition','attachment; filename=download.txt')]
start_response(status, response_headers)
for item in response:
yield item
else:#respond to any other event with json
response = simplejson.dumps(response)
status = '200 OK'
response_headers = [('Content-type', 'application/json'),
('Content-Length', str(len(response)))]
start_response(status, response_headers)
yield response
print('@@@@ Responded to {0} in {1}s'.format(request_type, tm.Elapsed())) |
Increase timeout of CLI tests to let the update notifier do the job. | var cp = require('child_process');
var expect = require('expect.js');
module.exports = function () {
describe('CLI', function () {
this.timeout(10000); // Increase the timeout to let the update-notifier do it's job
it('should error if task file does not exist', function (done) {
cp.exec('node bin/automaton something-that-will-never-exist', function (err, stdout, stderr) {
expect(stderr).to.match(/could not find/i);
}).on('exit', function (code) {
expect(code).to.equal(1);
done();
});
});
it('should exit with an appropriate code if a task fails', function (done) {
cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory', function (err, stdout) {
expect(stdout).to.match(/mandatory/);
}).on('exit', function (code) {
expect(code).to.equal(1);
cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory --mandatory=foo')
.on('exit', function (code) {
expect(code).to.equal(0);
done();
});
});
});
});
}; | var cp = require('child_process');
var expect = require('expect.js');
module.exports = function () {
describe('CLI', function () {
it('should error if task file does not exist', function (done) {
cp.exec('node bin/automaton something-that-will-never-exist', function (err, stdout, stderr) {
expect(stderr).to.match(/could not find/i);
}).on('exit', function (code) {
expect(code).to.equal(1);
done();
});
});
it('should exit with an appropriate code if a task fails', function (done) {
cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory', function (err, stdout) {
expect(stdout).to.match(/mandatory/);
}).on('exit', function (code) {
expect(code).to.equal(1);
cp.exec('node bin/automaton test/helpers/tasks/dummy-mandatory --mandatory=foo')
.on('exit', function (code) {
expect(code).to.equal(0);
done();
});
});
});
});
}; |
Revert "fix ES5 shim test"
This reverts commit ae8728dc7bbdec7109b70c07a97333ffac4662a3. | define('implementations', [], function () {
'use strict';
return {
'es5': [
{
isAvailable: function () {
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es5/array.js
return !(Array.prototype &&
Array.prototype.every &&
Array.prototype.filter &&
Array.prototype.forEach &&
Array.prototype.indexOf &&
Array.prototype.lastIndexOf &&
Array.prototype.map &&
Array.prototype.some &&
Array.prototype.reduce &&
Array.prototype.reduceRight &&
Array.isArray &&
Function.prototype.bind);
},
implementation: 'es5-shim'
},
{
isAvailable: function () { return true; },
module: function () {
return {};
}
}
],
promises: [
{
// native ES6 Promises
isAvailable: function () {
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es6/promises.js
return 'Promise' in window &&
'resolve' in window.Promise &&
'reject' in window.Promise &&
'all' in window.Promise &&
'race' in window.Promise &&
(function() {
var resolve;
new window.Promise(function(r) { resolve = r; });
return typeof resolve === 'function';
}());
},
module: function () {
return Promise;
}
},
{
// fallback to Bluebird
isAvailable: function () { return true; },
implementation: 'bluebird'
}
]
};
});
| define('implementations', [], function () {
'use strict';
return {
'es5': [
{
isAvailable: function () {
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es5/array.js
return !!(Array.prototype &&
Array.prototype.every &&
Array.prototype.filter &&
Array.prototype.forEach &&
Array.prototype.indexOf &&
Array.prototype.lastIndexOf &&
Array.prototype.map &&
Array.prototype.some &&
Array.prototype.reduce &&
Array.prototype.reduceRight &&
Array.isArray &&
Function.prototype.bind);
},
implementation: 'es5-shim'
},
{
isAvailable: function () { return true; },
module: function () {
return {};
}
}
],
promises: [
{
// native ES6 Promises
isAvailable: function () {
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es6/promises.js
return 'Promise' in window &&
'resolve' in window.Promise &&
'reject' in window.Promise &&
'all' in window.Promise &&
'race' in window.Promise &&
(function() {
var resolve;
new window.Promise(function(r) { resolve = r; });
return typeof resolve === 'function';
}());
},
module: function () {
return Promise;
}
},
{
// fallback to Bluebird
isAvailable: function () { return true; },
implementation: 'bluebird'
}
]
};
});
|
FIX return format of client
Fixed a bug which ignored the 'fmt' parameter. Therefore the response of this interface were always json. | <?php
namespace xeased\giphy;
/**
* The Client sends the request to the giphy api. If no "api_key" is set, the public beta key will be used.
*/
class Client
{
const GIPHY_API_URL = 'http://api.giphy.com';
const API_KEY = 'dc6zaTOxFJmzC'; // public beta key
/**
* Performs a call to giphy.
* @param string $endpoint The api endpoint
* @param array $params Request parameter
* @return mixed JSON decoded response
*/
public function call($endpoint, $params)
{
try
{
// set public beta api_key if none is set
if(!isset($params['api_key']) || strlen($params['api_key']) <= 0)
{
$params['api_key'] = self::API_KEY;
}
$query = http_build_query($params);
$url = self::GIPHY_API_URL . $endpoint . ($query ? "?$query" : '');
$result = file_get_contents($url);
if(!isset($params['fmt']) || $params['fmt'] == 'json')
{
return json_decode($result);
}
return $result;
}
catch (Exception $e)
{
// TODO: Implement exception handling
return $e;
}
}
}
| <?php
namespace xeased\giphy;
/**
* The Client sends the request to the giphy api. If no "api_key" is set, the public beta key will be used.
*/
class Client
{
const GIPHY_API_URL = 'http://api.giphy.com';
const API_KEY = 'dc6zaTOxFJmzC'; // public beta key
/**
* Performs a call to giphy.
* @param string $endpoint The api endpoint
* @param array $params Request parameter
* @return mixed JSON decoded response
*/
public function call($endpoint, $params)
{
try
{
// set public beta api_key if none is set
if(!isset($params['api_key']) || strlen($params['api_key']) <= 0)
{
$params['api_key'] = self::API_KEY;
}
$query = http_build_query($params);
$url = self::GIPHY_API_URL . $endpoint . ($query ? "?$query" : '');
$result = file_get_contents($url);
return json_decode($result);
}
catch (Exception $e)
{
// TODO: Implement exception handling
return $e;
}
}
}
|
Remove the observer on $destroy
Thanks @heavysixer! | angular.module('eee-c.angularBindPolymer', []).
directive('bindPolymer', function() {
'use strict';
return {
restrict: 'A',
link: function(scope, element, attrs) {
var attrMap = {};
for (var prop in attrs.$attr) {
if (prop != 'bindPolymer') {
var _attr = attrs.$attr[prop];
var _match = element.attr(_attr).match(/\{\{\s*([\.\w]+)\s*\}\}/);
if (_match) {
attrMap[_attr] = _match[1];
}
}
}
// When Polymer sees a change to the bound variable,
// $apply / $digest the changes here in Angular
var observer = new MutationObserver(function(){ scope.$apply(); });
observer.observe(element[0], {attributes: true});
scope.$on('$destroy', function(){ observer.disconnect(); });
for (var _attr in attrMap) { watch (_attr); }
function watch(attr) {
scope.$watch(
function() { return element.attr(attr); },
function(value) {
var tokens = attrMap[attr].split(/\./);
var parent = scope;
for (var i=0; i<tokens.length-1; i++) {
if (typeof(parent[tokens[i]]) == 'undefined') {
parent[tokens[i]] = {};
}
parent = parent[tokens[i]];
}
parent[tokens[tokens.length - 1]] = value;
}
);
}
}
};
});
| angular.module('eee-c.angularBindPolymer', []).
directive('bindPolymer', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var attrMap = {};
for (var prop in attrs.$attr) {
if (prop != 'bindPolymer') {
var _attr = attrs.$attr[prop];
var _match = element.attr(_attr).match(/\{\{\s*([\.\w]+)\s*\}\}/);
if (_match) {
attrMap[_attr] = _match[1];
}
}
}
// When Polymer sees a change to the bound variable,
// $apply / $digest the changes here in Angular
new MutationObserver(function() { scope.$apply(); }).
observe(element[0], {attributes: true});
for (var _attr in attrMap) { watch (_attr); }
function watch(attr) {
scope.$watch(
function() { return element.attr(attr); },
function(value) {
var tokens = attrMap[attr].split(/\./);
var parent = scope;
for (var i=0; i<tokens.length-1; i++) {
if (typeof(parent[tokens[i]]) == 'undefined') {
parent[tokens[i]] = {};
}
parent = parent[tokens[i]];
}
parent[tokens[tokens.length - 1]] = value;
}
);
}
}
};
});
|
Add site number and application type to properties. For better filtering of new and old biz. | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%m/%d/%Y').date()
def _get_date_or_cast(self, s, attr):
if getattr(self, attr) is None:
setattr(self, attr, self._cast_date(s))
return getattr(self, attr)
@property
def start_date(self):
return self._get_date_or_cast(
self['DATE ISSUED'],
'_start_date',
)
@property
def end_date(self):
return self._get_date_or_cast(
self['LICENSE TERM EXPIRATION DATE'],
'_end_date',
)
@property
def application_type(self):
return self['APPLICATION TYPE']
@property
def account_number(self):
return self['ACCOUNT NUMBER']
@property
def site_number(self):
return self['SITE NUMBER']
@property
def neighborhood(self):
return self['NEIGHBORHOOD']
class RawReader(csv.DictReader):
def __iter__(self, *args, **kwargs):
row = self.next()
while row:
yield Row(row)
row = self.next()
class RawWriter(csv.DictWriter):
pass
| import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%m/%d/%Y').date()
def _get_date_or_cast(self, s, attr):
if getattr(self, attr) is None:
setattr(self, attr, self._cast_date(s))
return getattr(self, attr)
@property
def start_date(self):
return self._get_date_or_cast(
self['DATE ISSUED'],
'_start_date',
)
@property
def end_date(self):
return self._get_date_or_cast(
self['LICENSE TERM EXPIRATION DATE'],
'_end_date',
)
@property
def account_number(self):
return self['ACCOUNT NUMBER']
@property
def neighborhood(self):
return self['NEIGHBORHOOD']
class RawReader(csv.DictReader):
def __iter__(self, *args, **kwargs):
row = self.next()
while row:
yield Row(row)
row = self.next()
class RawWriter(csv.DictWriter):
pass
|
[Admin] Set an Invalid message for ChangePassword confirmation | <?php
// src/Corvus/AdminBundle/Form/Type/ChangePasswordType.php
namespace Corvus\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\Security\Core\Validator\Constraints\UserPassword,
Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ChangePasswordType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('currentPassword', 'password', array(
'required' => true,
'label' => 'Current Password',
'attr' => array('class' => 'form-control'),
'mapped' => false,
'constraints' => new UserPassword(),
));
$builder->add('plainPassword', 'repeated', array(
'required' => true,
'type' => 'password',
'first_options' => array(
'label' => 'New Password',
'attr' => array('class' => 'form-control')
),
'second_options' => array(
'label' => 'Confirm New Password',
'attr' => array('class' => 'form-control')
),
'invalid_message' => 'Passwords must match'
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Corvus\AdminBundle\Entity\User',
));
}
public function getName()
{
return 'changePassword';
}
} | <?php
// src/Corvus/AdminBundle/Form/Type/ChangePasswordType.php
namespace Corvus\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\Security\Core\Validator\Constraints\UserPassword,
Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ChangePasswordType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('currentPassword', 'password', array(
'required' => true,
'label' => 'Current Password',
'attr' => array('class' => 'form-control'),
'mapped' => false,
'constraints' => new UserPassword(),
));
$builder->add('plainPassword', 'repeated', array(
'required' => true,
'type' => 'password',
'first_options' => array(
'label' => 'New Password',
'attr' => array('class' => 'form-control')
),
'second_options' => array(
'label' => 'Confirm New Password',
'attr' => array('class' => 'form-control')
)
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Corvus\AdminBundle\Entity\User',
));
}
public function getName()
{
return 'changePassword';
}
} |
Fix issue with HP ProCurve stacks and multiple hit enter to continue messages | from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
| from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
Break up 'default' task into 'default' and 'watch', so that traditional build processes can work | module.exports = function(grunt){
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
coffee:{
compileJoined: {
options: {
join: true
},
files: {
'js/main.js': [
'coffee/*'
]
}
},
},
watch: {
coffee: {
files: ['coffee/*.coffee', 'example/coffee/*.coffee'],
tasks: 'coffee'
}
},
bower: {
target: {
rjsConfig: 'app/config.js'
}
}
});
grunt.loadNpmTasks('grunt-bower-requirejs');
grunt.registerTask('default', [
'coffee', 'bower'
]);
grunt.registerTask('develop', [
'default', 'watch'
]);
};
| module.exports = function(grunt){
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
coffee:{
compileJoined: {
options: {
join: true
},
files: {
'js/main.js': [
'coffee/*'
]
}
},
},
watch: {
coffee: {
files: ['coffee/*.coffee', 'example/coffee/*.coffee'],
tasks: 'coffee'
}
},
bower: {
target: {
rjsConfig: 'app/config.js'
}
}
});
grunt.loadNpmTasks('grunt-bower-requirejs');
grunt.registerTask('default', [
'coffee', 'bower'
]);
};
|
Handle null case for client id | "use strict";
var restify = require('restify');
var async = require('async');
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
if(!req.query.context) {
return next(new restify.ConflictError("Missing query parameter"));
}
async.waterfall([
function getDocuments(cb) {
var params = {
search: req.query.context,
render_templates: true,
sort: "-modificationDate",
strict: true,
fields: "data",
};
if(req.query.limit) {
params.limit = req.query.limit;
}
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocuments(params, cb);
},
function remapDocuments(documentsRes, cb) {
res.set("Cache-Control", "max-age=3600");
res.send(200, documentsRes.body.data.map(function mapDocuments(document) {
return {
documentId: document.id,
typeId: document.document_type.id,
providerId: document.provider.client ? document.provider.client.id : "",
date: document.modification_date,
snippet: document.rendered_snippet,
title: document.rendered_title
};
}));
cb();
}
], next);
};
| "use strict";
var restify = require('restify');
var async = require('async');
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
if(!req.query.context) {
return next(new restify.ConflictError("Missing query parameter"));
}
async.waterfall([
function getDocuments(cb) {
var params = {
search: req.query.context,
render_templates: true,
sort: "-modificationDate",
strict: true,
fields: "data",
};
if(req.query.limit) {
params.limit = req.query.limit;
}
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocuments(params, cb);
},
function remapDocuments(documentsRes, cb) {
res.set("Cache-Control", "max-age=3600");
res.send(200, documentsRes.body.data.map(function mapDocuments(document) {
return {
documentId: document.id,
typeId: document.document_type.id,
providerId: document.provider.client ? document.provider.client.id : null,
date: document.modification_date,
snippet: document.rendered_snippet,
title: document.rendered_title
};
}));
cb();
}
], next);
};
|
Update of sorted merge step test case
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@4016 5fb7f6ec-07c1-534a-b4ca-9155e429e800 | package org.pentaho.di.run.sortedmerge;
import junit.framework.TestCase;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;
public class RunSortedMerge extends TestCase
{
public void test_SORTED_MERGE_00() {
System.out.println();
System.out.println("SORTED MERGE");
System.out.println("==================");
}
public void test_SORTED_MERGE_01_SIMPLE() throws Exception {
TimedTransRunner timedTransRunner = new TimedTransRunner(
"test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
LogWriter.LOG_LEVEL_ERROR,
AllRunTests.getOldTargetDatabase(),
AllRunTests.getNewTargetDatabase(),
1000000
);
timedTransRunner.runOldAndNew();
be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
assertTrue(oldResult.getNrErrors()==0);
Result newResult = timedTransRunner.getNewResult();
assertTrue(newResult.getNrErrors()==0);
}
}
| package org.pentaho.di.run.sortedmerge;
import junit.framework.TestCase;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;
public class RunSortedMerge extends TestCase
{
public void test_SORTED_MERGE_00()
{
System.out.println();
System.out.println("SORTED MERGE");
System.out.println("==================");
}
public void test_SORTED_MERGE_01_SIMPLE() throws Exception
{
TimedTransRunner timedTransRunner = new TimedTransRunner(
"test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
LogWriter.LOG_LEVEL_ERROR,
AllRunTests.getOldTargetDatabase(),
AllRunTests.getNewTargetDatabase(),
1000000
);
timedTransRunner.runOldAndNew();
be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
assertTrue(oldResult.getNrErrors()==0);
Result newResult = timedTransRunner.getNewResult();
assertTrue(newResult.getNrErrors()==0);
}
}
|
Use f.read() instead of filter() for reading requirements
filter() has changed in Python 3 which breaks this. | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
readme = f.read()
with open(os.path.join(here, 'requirements.txt')) as f:
requires = f.read().split('\n')
with open(os.path.join(here, 'requirements-dev.txt')) as f:
requires_dev = f.read().split('\n')
with open(os.path.join(here, 'VERSION')) as f:
version = f.read().strip()
setup(name='molo.commenting',
version=version,
description=('Comments helpers for sites built with Molo.'),
long_description=readme,
classifiers=[
"Programming Language :: Python",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.commenting',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
| import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
readme = f.read()
with open(os.path.join(here, 'requirements.txt')) as f:
requires = filter(None, f.readlines())
with open(os.path.join(here, 'requirements-dev.txt')) as f:
requires_dev = filter(None, f.readlines())
with open(os.path.join(here, 'VERSION')) as f:
version = f.read().strip()
setup(name='molo.commenting',
version=version,
description=('Comments helpers for sites built with Molo.'),
long_description=readme,
classifiers=[
"Programming Language :: Python",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Praekelt Foundation',
author_email='[email protected]',
url='http://github.com/praekelt/molo.commenting',
license='BSD',
keywords='praekelt, mobi, web, django',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
namespace_packages=['molo'],
install_requires=requires,
tests_require=requires_dev,
entry_points={})
|
Fix undefined window in worker. | var version = function () { return '(loading)'; };
var compileJSON = function () { return ''; };
var missingInputs = [];
module.exports = function (self) {
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'loadVersion':
delete self.Module;
version = null;
compileJSON = null;
self.importScripts(data.data);
var Module = self.Module;
version = Module.cwrap('version', 'string', []);
if ('_compileJSONCallback' in Module) {
var compileJSONInternal = Module.cwrap('compileJSONCallback', 'string', ['string', 'number', 'number']);
var missingInputCallback = Module.Runtime.addFunction(function (path) {
missingInputs.push(Module.Pointer_stringify(path));
});
compileJSON = function (input, optimize) {
return compileJSONInternal(input, optimize, missingInputCallback);
};
} else if ('_compileJSONMulti' in Module) {
compileJSON = Module.cwrap('compileJSONMulti', 'string', ['string', 'number']);
} else {
compileJSON = Module.cwrap('compileJSON', 'string', ['string', 'number']);
}
self.postMessage({
cmd: 'versionLoaded',
data: version(),
acceptsMultipleFiles: ('_compileJSONMulti' in Module)
});
break;
case 'compile':
missingInputs.length = 0;
self.postMessage({cmd: 'compiled', data: compileJSON(data.source, data.optimize), missingInputs: missingInputs});
break;
}
}, false);
};
| var version = function () { return '(loading)'; };
var compileJSON = function () { return ''; };
var missingInputs = [];
module.exports = function (self) {
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'loadVersion':
delete window.Module;
version = null;
compileJSON = null;
self.importScripts(data.data);
var Module = window.Module;
version = Module.cwrap('version', 'string', []);
if ('_compileJSONCallback' in Module) {
var compileJSONInternal = Module.cwrap('compileJSONCallback', 'string', ['string', 'number', 'number']);
var missingInputCallback = Module.Runtime.addFunction(function (path) {
missingInputs.push(Module.Pointer_stringify(path));
});
compileJSON = function (input, optimize) {
return compileJSONInternal(input, optimize, missingInputCallback);
};
} else if ('_compileJSONMulti' in Module) {
compileJSON = Module.cwrap('compileJSONMulti', 'string', ['string', 'number']);
} else {
compileJSON = Module.cwrap('compileJSON', 'string', ['string', 'number']);
}
self.postMessage({
cmd: 'versionLoaded',
data: version(),
acceptsMultipleFiles: ('_compileJSONMulti' in Module)
});
break;
case 'compile':
missingInputs.length = 0;
self.postMessage({cmd: 'compiled', data: compileJSON(data.source, data.optimize), missingInputs: missingInputs});
break;
}
}, false);
};
|
Add example of test instructions in sample plugin | var hydra = require('hydra'),
HydraHeadStatic = hydra.heads.HydraHeadStatic,
HydraHead = hydra.heads.HydraHead;
exports.getBodyParts = function(config, modules) {
var assert = modules.assert;
return {
name: "testBasic",
tests: {
firstTestFoo: {
heads: [
new HydraHeadStatic({path: '/foo',
content: "fixed content"}),
new HydraHeadStatic({content: "more fixed content"})
]
},
secondTestBar: {
instructions: "Optional, Markdown format instructions.\n\n" +
"You can go to [/bar](/bar) for a failure, " +
"or to [/bar2](/bar2) for a pass. Then go " +
"back to " +
"[/hydra-admin/tests](/hydra-admin/tests) " +
"to see the results.",
heads: [
new HydraHead({
path: '/bar',
handler: function(req, res) {
assert.equal(1, 1, "1 should be 1");
res.write("trying assertion...");
assert.equal(1, 0, "1 should be 0 (!)");
res.send("fixed content");
}
}),
new HydraHead({
path: '/bar2',
handler: function(req, res) {
assert.equal(1, 1, "1 should be 1 (still)");
res.send("always works");
}
})
]
}
}
};
};
| var hydra = require('hydra'),
HydraHeadStatic = hydra.heads.HydraHeadStatic,
HydraHead = hydra.heads.HydraHead;
exports.getBodyParts = function(config, modules) {
var assert = modules.assert;
return {
name: "testBasic",
tests: {
firstTestFoo: {
heads: [
new HydraHeadStatic({path: '/foo',
content: "fixed content"}),
new HydraHeadStatic({content: "more fixed content"})
]
},
secondTestBar: {
heads: [
new HydraHead({
path: '/bar',
handler: function(req, res) {
assert.equal(1, 1, "1 should be 1");
res.write("trying assertion...");
assert.equal(1, 0, "1 should be 0 (!)");
res.send("fixed content");
}
}),
new HydraHead({
path: '/bar2',
handler: function(req, res) {
assert.equal(1, 1, "1 should be 1 (still)");
res.send("always works");
}
})
]
}
}
};
};
|
Update API URLs in web UI | var default_settings = {
/* Topology settings */
show_unused_interfaces: true,
show_disconnected_hosts: true,
show_topology: true,
topology_transformation: 'translate(0,0) scale(1)',
/* Map settings */
show_map: true,
map_opacity: 0.4,
map_center: [-97.8445676, 35.3437248],
map_zoom: 4,
/* Switch carousel and card settings */
switches_carousel: {
margin: 10,
nav: true,
owlNrow: true, // enable plugin
owlNrowTarget: 'item', // class for items in carousel div
owlNrowContainer: 'owlNrow-item', // class for items container
owlNrowDirection: 'ltr', // utd or ltr : directions
owlNrowNumberOfRows: 1,
responsive: {
0: {
items: 3 // 3 items on the screen per row
}
}
},
/* Other settings */
enable_log: false,
},
server_host = window.location.hostname,
api_url = "http://" + server_host + ":8181/api/",
api_stats = api_url + 'kytos/of_stats/',
api_status = api_url + 'kytos/core/status/',
layouts_url = api_url + "kytos/web_topology_layout/layouts/",
topology_url = api_url + "kytos/of_topology",
log_server_url = "ws://" + server_host + ":8765",
mustache_dir = '/static/js/templates/';
| var default_settings = {
/* Topology settings */
show_unused_interfaces: true,
show_disconnected_hosts: true,
show_topology: true,
topology_transformation: 'translate(0,0) scale(1)',
/* Map settings */
show_map: true,
map_opacity: 0.4,
map_center: [-97.8445676, 35.3437248],
map_zoom: 4,
/* Switch carousel and card settings */
switches_carousel: {
margin: 10,
nav: true,
owlNrow: true, // enable plugin
owlNrowTarget: 'item', // class for items in carousel div
owlNrowContainer: 'owlNrow-item', // class for items container
owlNrowDirection: 'ltr', // utd or ltr : directions
owlNrowNumberOfRows: 1,
responsive: {
0: {
items: 3 // 3 items on the screen per row
}
}
},
/* Other settings */
enable_log: false,
},
server_host = window.location.hostname,
api_url = "http://" + server_host + ":8181/kytos/",
api_stats = api_url + 'stats/',
api_status = api_url + 'status/',
layouts_url = api_url + "web/topology/layouts/",
topology_url = api_url + "topology",
log_server_url = "ws://" + server_host + ":8765",
mustache_dir = '/static/js/templates/';
|
Use the Python 3 print function. | #!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import sys
def build(pkgpath):
os.chdir(pkgpath)
targets = [
'build',
'package',
'install',
'clean',
'clean-depends',
]
for target in targets:
p = subprocess.Popen(
['bmake', target],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
log = 'bmake-' + target + '-log.txt'
with open(log, 'w+') as f:
f.write(out)
f.write(err)
assert p.returncode == 0, '%s %s' % (pkg, target)
if __name__ == '__main__':
home = os.environ['HOME']
localbase = os.path.join(home, 'usr', 'pkgsrc')
lines = sys.stdin.readlines()
pkgs = [line.rstrip('\n') for line in lines]
pkgpaths = [pkg.split(' ')[0] for pkg in pkgs]
for pkgpath in pkgpaths:
print(pkgpath)
os.chdir(localbase)
assert os.path.exists(os.path.join(localbase, pkgpath))
build(pkgpath)
| #!/usr/bin/env python
import os
import subprocess
import sys
def build(pkgpath):
os.chdir(pkgpath)
targets = [
'build',
'package',
'install',
'clean',
'clean-depends',
]
for target in targets:
p = subprocess.Popen(
['bmake', target],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
log = 'bmake-' + target + '-log.txt'
with open(log, 'w+') as f:
f.write(out)
f.write(err)
assert p.returncode == 0, '%s %s' % (pkg, target)
if __name__ == '__main__':
home = os.environ['HOME']
localbase = os.path.join(home, 'usr', 'pkgsrc')
lines = sys.stdin.readlines()
pkgs = [line.rstrip('\n') for line in lines]
pkgpaths = [pkg.split(' ')[0] for pkg in pkgs]
for pkgpath in pkgpaths:
print pkgpath
os.chdir(localbase)
assert os.path.exists(os.path.join(localbase, pkgpath))
build(pkgpath)
|
Add previous exception to the stack | <?php
/*
* This file is part of the shopery/error-bundle package.
*
* Copyright (c) 2015 Shopery.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Shopery\Bundle\ErrorBundle\Listener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class ExceptionListener
*
* @author Berny Cantos <[email protected]>
*/
class ExceptionListener
{
/**
* @var array
*/
private $exceptions;
/**
* @param array $exceptions
*/
public function __construct(array $exceptions)
{
$this->exceptions = $exceptions;
}
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof HttpException) {
return;
}
foreach ($this->exceptions as $className => $settings) {
if (is_a($exception, $className)) {
$code = $settings['code'];
$message = $settings['expose_message']
? $exception->getMessage()
: Response::$statusTexts[$code];
throw new HttpException($code, $message, $exception);
}
}
}
}
| <?php
/*
* This file is part of the shopery/error-bundle package.
*
* Copyright (c) 2015 Shopery.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Shopery\Bundle\ErrorBundle\Listener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class ExceptionListener
*
* @author Berny Cantos <[email protected]>
*/
class ExceptionListener
{
/**
* @var array
*/
private $exceptions;
/**
* @param array $exceptions
*/
public function __construct(array $exceptions)
{
$this->exceptions = $exceptions;
}
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof HttpException) {
return;
}
foreach ($this->exceptions as $className => $settings) {
if (is_a($exception, $className)) {
$code = $settings['code'];
$message = $settings['expose_message']
? $exception->getMessage()
: Response::$statusTexts[$code];
throw new HttpException($code, $message);
}
}
}
}
|
TEST allink_apps subtree - pulling | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from parler.admin import TranslatableTabularInline
from adminsortable.admin import SortableTabularInline
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from allink_core.allink_base.admin import AllinkBaseAdminSortable
from allink_apps.work.models import Work, Highlights
class HighlightsInline(SortableTabularInline, TranslatableTabularInline):
model = Highlights
extra = 1
max_num = 10
verbose_name = _(u'Highlight')
verbose_name_plural = _(u'Highlights')
@admin.register(Work)
class WorkAdmin(PlaceholderAdminMixin, AllinkBaseAdminSortable):
inlines = [HighlightsInline, ]
list_filter = ('is_active', 'categories',)
def get_fieldsets(self, request, obj=None):
fieldsets = (
(None, {
'fields': (
'is_active',
'title',
'slug',
'lead',
'preview_image',
),
}),
)
fieldsets += self.get_base_fieldsets()
return fieldsets
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'lead':
kwargs['widget'] = forms.Textarea
return super(WorkAdmin, self).formfield_for_dbfield(db_field, **kwargs)
| # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.utils.translation import ugettext_lazy as _
from parler.admin import TranslatableTabularInline
from adminsortable.admin import SortableTabularInline
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from allink_core.allink_base.admin import AllinkBaseAdminSortable
from allink_apps.work.models import Work, Highlights
class HighlightsInline(SortableTabularInline, TranslatableTabularInline):
model = Highlights
extra = 1
max_num = 10
verbose_name = _(u'Highlight')
verbose_name_plural = _(u'Highlights')
@admin.register(Work)
class WorkAdmin(PlaceholderAdminMixin, AllinkBaseAdminSortable):
inlines = [HighlightsInline, ]
list_filter = ('is_active', 'categories',)
def get_fieldsets(self, request, obj=None):
fieldsets = (
(None, {
'fields': (
'is_active',
'title',
'slug',
'lead',
'preview_image',
),
}),
)
fieldsets += self.get_base_fieldsets()
return fieldsets
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'lead':
kwargs['widget'] = forms.Textarea
return super(WorkAdmin, self).formfield_for_dbfield(db_field, **kwargs)
|
Add bodytemplate.md to build artifacts | from setuptools import setup, find_packages
if __name__ == "__main__":
import falafel
setup(
name=falafel.NAME,
version=falafel.VERSION,
description="Insights Application Programming Interface",
packages=find_packages(),
package_data={"": ["*.json", "RELEASE", "COMMIT", "*.md"]},
install_requires=[
'pyyaml',
],
extras_require={
'develop': [
'flake8',
'coverage',
'numpydoc',
'pytest',
'pytest-cov',
'Sphinx',
'sphinx_rtd_theme',
'Jinja2'
],
'optional': [
'python-cjson'
],
'test': [
'flake8',
'coverage',
'pytest',
'pytest-cov'
]
},
entry_points={
'console_scripts': [
'insights-run = falafel.core:main',
'gen_api = falafel.tools.generate_api_config:main',
'compare_api = falafel.tools.compare_uploader_configs:main'
]
}
)
| from setuptools import setup, find_packages
if __name__ == "__main__":
import falafel
setup(
name=falafel.NAME,
version=falafel.VERSION,
description="Insights Application Programming Interface",
packages=find_packages(),
package_data={"": ["*.json", "RELEASE", "COMMIT"]},
install_requires=[
'pyyaml',
],
extras_require={
'develop': [
'flake8',
'coverage',
'numpydoc',
'pytest',
'pytest-cov',
'Sphinx',
'sphinx_rtd_theme',
'Jinja2'
],
'optional': [
'python-cjson'
],
'test': [
'flake8',
'coverage',
'pytest',
'pytest-cov'
]
},
entry_points={
'console_scripts': [
'insights-run = falafel.core:main',
'gen_api = falafel.tools.generate_api_config:main',
'compare_api = falafel.tools.compare_uploader_configs:main'
]
}
)
|
Fix for localized dates (month names with unicode) | <?php
class CRM_Logviewer_Page_LogViewer extends CRM_Core_Page {
public function run() {
$this->assign('currentTime', date('Y-m-d H:i:s'));
$file_log = CRM_Core_Error::createDebugLogger();
$logFileName = $file_log->_filename;
$file_log->close();
$this->assign('fileName', $logFileName);
$entries = array();
if ($handle = @fopen($logFileName,'r')) {
$line = 0;
while (!feof($handle)) {
$line++;
$dd = fgets($handle);
if (strlen($dd) >= 15 && (' ' != $dd[0])) {
// Also support localized dates such as: "fév 14 12:51:13"
$date = mb_substr($dd,0,15);
if (preg_match("/^\w{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/u",$date)) {
$entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
$entries[$line] = array('lineNumber' => '<a href="'.$entry_url.'">'.$line.'</a>', 'dateTime' => $date, 'message' => substr($dd,16));
}
}
}
fclose($handle);
krsort($entries);
$this->assign('logEntries', $entries);
}
parent::run();
}
}
| <?php
class CRM_Logviewer_Page_LogViewer extends CRM_Core_Page {
public function run() {
$this->assign('currentTime', date('Y-m-d H:i:s'));
$file_log = CRM_Core_Error::createDebugLogger();
$logFileName = $file_log->_filename;
$file_log->close();
$this->assign('fileName', $logFileName);
$entries = array();
if ($handle = @fopen($logFileName,'r')) {
$line = 0;
while (!feof($handle)) {
$line++;
$dd = fgets($handle);
if (strlen($dd) >= 15 && (' ' != $dd[0])) {
$date = substr($dd,0,15);
if (preg_match("/^[A-Za-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/",$date)) {
$entry_url = CRM_Utils_System::url('civicrm/admin/logviewer/logentry', $query = 'lineNumber='.$line);
$entries[$line] = array('lineNumber' => '<a href="'.$entry_url.'">'.$line.'</a>', 'dateTime' => $date, 'message' => substr($dd,16));
}
}
}
fclose($handle);
krsort($entries);
$this->assign('logEntries', $entries);
}
parent::run();
}
}
|
Fix not swapping global plugin anonymous consumer id to username | import invariant from 'invariant';
const getConsumerById = (id, consumers) => {
const consumer = consumers.find(x => x._info.id === id);
invariant(consumer, `Unable to find a consumer for ${id}`);
return consumer;
};
export default state => {
const fixPluginAnonymous = ({ name, attributes: { config, ...attributes }, ...plugin }) => {
if (config && config.anonymous) {
const { anonymous, ...restOfConfig } = config;
const { username } = getConsumerById(anonymous, state.consumers);
return { name, attributes: { ...attributes, config: { anonymous_username: username, ...restOfConfig } }, ...plugin };
}
return { name, attributes: { ...attributes, config }, ...plugin };
}
const fixPluginUsername = ({ name, attributes: { consumer_id, ...attributes }, ...plugin }) => {
if (!consumer_id) {
return { name, attributes, ...plugin };
}
const { username } = getConsumerById(consumer_id, state.consumers);
return { name, attributes: { username, ...attributes }, ...plugin };
};
const fixApiPluginUsername = api => ({
...api,
plugins: (api.plugins || []).map(fixPluginUsername).map(fixPluginAnonymous),
});
return {
...state,
apis: state.apis && state.apis.map(fixApiPluginUsername),
plugins: state.plugins && state.plugins.map(fixPluginUsername).map(fixPluginAnonymous),
};
};
| import invariant from 'invariant';
const getConsumerById = (id, consumers) => {
const consumer = consumers.find(x => x._info.id === id);
invariant(consumer, `Unable to find a consumer for ${id}`);
return consumer;
};
export default state => {
const fixPluginAnonymous = ({ name, attributes: { config, ...attributes }, ...plugin }) => {
if (config && config.anonymous) {
const { anonymous, ...restOfConfig } = config;
const { username } = getConsumerById(anonymous, state.consumers);
return { name, attributes: { ...attributes, config: { anonymous_username: username, ...restOfConfig } }, ...plugin };
}
return { name, attributes: { ...attributes, config }, ...plugin };
}
const fixPluginUsername = ({ name, attributes: { consumer_id, ...attributes }, ...plugin }) => {
if (!consumer_id) {
return { name, attributes, ...plugin };
}
const { username } = getConsumerById(consumer_id, state.consumers);
return { name, attributes: { username, ...attributes }, ...plugin };
};
const fixApiPluginUsername = api => ({
...api,
plugins: (api.plugins || []).map(fixPluginUsername).map(fixPluginAnonymous),
});
return {
...state,
apis: state.apis && state.apis.map(fixApiPluginUsername),
plugins: state.plugins && state.plugins.map(fixPluginUsername),
};
};
|
Fix sourcemaps when in a directory | var autoprefixer = require('autoprefixer-core');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
// setting from = input filename works unless there is a directory,
// then autoprefixer adds the directory onto the source filename twice.
// setting to to anything else causes an un-necessary extra file to be
// added to the map, but its better than it failing
processOptions.from = sourceMap.getOutputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = autoprefixer(options).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
| var autoprefixer = require('autoprefixer-core');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
processOptions.from = sourceMap.getInputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = autoprefixer(options).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
|
Add Inject to default task. | 'use strict';
require('dotenv').load();
var pkg = require('./package.json'),
path = require('path');
var gulp = require('gulp'),
gutil = require('gulp-util'),
inject = require('gulp-inject'),
plumber = require('gulp-plumber'),
pgbuild = require('gulp-phonegap-build'),
bowerFiles = require('main-bower-files');
var dir = {
out: path.join(__dirname, './out'),
dist: path.join(__dirname, './dist'),
assets: path.join(__dirname, './public'),
};
gulp.task('default', ['inject', 'build'], function () {
gutil.log('Building... This might take a while.');
});
gulp.task('build', function () {
gulp.src(dir.assets + '/**')
.pipe(plumber())
.pipe(pgbuild({
appId: process.env.PG_BUILD_APP_ID,
download: {
android: dir.out + '/onesquare-' + pkg.version + '.apk'
},
user: {
token: process.env.PG_BUILD_AUTH_TOKEN
}
}));
});
gulp.task('inject', function () {
var sources = [
dir.assets + '/lib/**/*.html'
];
return gulp.src(dir.assets + '/index.html')
.pipe(inject(gulp.src(sources, {read: false})))
.pipe(inject(gulp.src(bowerFiles(), {read: false}), {name: 'bower'}))
.pipe(gulp.dest(dir.dist));
});
| 'use strict';
require('dotenv').load();
var pkg = require('./package.json'),
path = require('path');
var gulp = require('gulp'),
gutil = require('gulp-util'),
inject = require('gulp-inject'),
plumber = require('gulp-plumber'),
pgbuild = require('gulp-phonegap-build'),
bowerFiles = require('main-bower-files');
var dir = {
out: path.join(__dirname, './out'),
dist: path.join(__dirname, './dist'),
assets: path.join(__dirname, './public'),
};
gulp.task('default', ['build'], function () {
gutil.log('Building... This might take a while.');
});
gulp.task('build', function () {
gulp.src(dir.assets + '/**')
.pipe(plumber())
.pipe(pgbuild({
appId: process.env.PG_BUILD_APP_ID,
download: {
android: dir.out + '/onesquare-' + pkg.version + '.apk'
},
user: {
token: process.env.PG_BUILD_AUTH_TOKEN
}
}));
});
gulp.task('inject', function () {
var sources = [
dir.assets + '/lib/**/*.html'
];
return gulp.src(dir.assets + '/index.html')
.pipe(inject(gulp.src(sources, {read: false})))
.pipe(inject(gulp.src(bowerFiles(), {read: false}), {name: 'bower'}))
.pipe(gulp.dest(dir.dist));
});
|
Fix IDEA warning about unchecked assignment | package com.nirima.jenkins.plugins.docker;
import hudson.Extension;
import hudson.model.Describable;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
/**
* A simple template storage.
*/
public class DockerSimpleTemplate extends DockerTemplateBase implements Describable<DockerSimpleTemplate> {
public DockerSimpleTemplate(String image,
String dnsString,
String dockerCommand,
String volumesString,
String volumesFrom,
String environmentsString,
String lxcConfString,
String hostname,
Integer memoryLimit,
Integer cpuShares,
String bindPorts,
boolean bindAllPorts,
boolean privileged,
boolean tty) {
super(image,
dnsString,
dockerCommand,
volumesString,
volumesFrom,
environmentsString,
lxcConfString,
hostname,
memoryLimit,
cpuShares,
bindPorts,
bindAllPorts,
privileged,
tty);
}
public Descriptor<DockerSimpleTemplate> getDescriptor() {
return (DescriptorImpl) Jenkins.getInstance().getDescriptor(getClass());
}
@Extension
public static final class DescriptorImpl extends Descriptor<DockerSimpleTemplate> {
@Override
public String getDisplayName() {
return "Docker Template";
}
}
}
| package com.nirima.jenkins.plugins.docker;
import hudson.Extension;
import hudson.model.Describable;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
/**
* A simple template storage.
*/
public class DockerSimpleTemplate extends DockerTemplateBase implements Describable<DockerSimpleTemplate> {
public DockerSimpleTemplate(String image,
String dnsString,
String dockerCommand,
String volumesString,
String volumesFrom,
String environmentsString,
String lxcConfString,
String hostname,
Integer memoryLimit,
Integer cpuShares,
String bindPorts,
boolean bindAllPorts,
boolean privileged,
boolean tty) {
super(image,
dnsString,
dockerCommand,
volumesString,
volumesFrom,
environmentsString,
lxcConfString,
hostname,
memoryLimit,
cpuShares,
bindPorts,
bindAllPorts,
privileged,
tty);
}
public Descriptor<DockerSimpleTemplate> getDescriptor() {
return Jenkins.getInstance().getDescriptor(getClass());
}
@Extension
public static final class DescriptorImpl extends Descriptor<DockerSimpleTemplate> {
@Override
public String getDisplayName() {
return "Docker Template";
}
}
}
|
Fix userinfo api command (send ok=True) | from twisted.internet import defer
import bnw_core.bnw_objects as objs
@defer.inlineCallbacks
def cmd_userinfo(request, user=''):
if not user:
defer.returnValue(dict(ok=False, desc='Username required.'))
user_obj = yield objs.User.find_one({'name': user})
subscribers = yield objs.Subscription.find(dict(
target=user, type='sub_user'))
subscribers = set([x['user'] for x in subscribers])
subscriptions = yield objs.Subscription.find(dict(
user=user, type='sub_user'))
subscriptions = set([x['target'] for x in subscriptions])
friends = list(subscribers & subscriptions)
friends.sort()
subscribers_only = list(subscribers - subscriptions)
subscribers_only.sort()
subscriptions_only = list(subscriptions - subscribers)
subscriptions_only.sort()
messages_count = int((yield objs.Message.count({'user': user})))
comments_count = int((yield objs.Comment.count({'user': user})))
vcard = user_obj.get('vcard', {})
about = user_obj.get('settings', {}).get('about', '')
if not about:
about = vcard.get('desc', '')
defer.returnValue({
'ok': True,
'user': user,
'regdate': user_obj.get('regdate', 0),
'messages_count': messages_count,
'comments_count': comments_count,
'subscribers': subscribers_only,
'subscriptions': subscriptions_only,
'friends': friends,
'vcard': vcard,
'about': about,
})
| from twisted.internet import defer
import bnw_core.bnw_objects as objs
@defer.inlineCallbacks
def cmd_userinfo(request, user=''):
if not user:
defer.returnValue(dict(ok=False, desc='Username required.'))
user_obj = yield objs.User.find_one({'name': user})
subscribers = yield objs.Subscription.find(dict(
target=user, type='sub_user'))
subscribers = set([x['user'] for x in subscribers])
subscriptions = yield objs.Subscription.find(dict(
user=user, type='sub_user'))
subscriptions = set([x['target'] for x in subscriptions])
friends = list(subscribers & subscriptions)
friends.sort()
subscribers_only = list(subscribers - subscriptions)
subscribers_only.sort()
subscriptions_only = list(subscriptions - subscribers)
subscriptions_only.sort()
messages_count = int((yield objs.Message.count({'user': user})))
comments_count = int((yield objs.Comment.count({'user': user})))
vcard = user_obj.get('vcard', {})
about = user_obj.get('settings', {}).get('about', '')
if not about:
about = vcard.get('desc', '')
defer.returnValue({
'user': user,
'regdate': user_obj.get('regdate', 0),
'messages_count': messages_count,
'comments_count': comments_count,
'subscribers': subscribers_only,
'subscriptions': subscriptions_only,
'friends': friends,
'vcard': vcard,
'about': about,
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.