text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix cross domain request (CORS) issue | $(document).ready(function() {
//$.get('http://127.0.0.1:8000/output.csv', function (data) {
$.get('output.csv', function (data) {
Highcharts.setOptions({
global: {
useUTC: true
},
colors: ['#2222ff', '#ff2222']
});
$('#container').highcharts({
chart: {
defaultSeriesType: 'spline',
zoomType: 'x'
},
data: {
csv: data
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b %e',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: "Weight (lbs)"
}
},
plotOptions: {
series: {
shadow: true,
connectNulls: true,
marker: {
enabled: false
}
}
},
title: {
text: "Weight (lbs) vs. Time"
},
subtitle: {
text: null
}
});
});
});
| $(document).ready(function() {
//$.get('http://127.0.0.1:8000/output.csv', function (data) {
//$.get('https://github.com/kenyot/weight_log/blob/gh-pages/output.csv', function (data) {
$.get('output.csv', function (data) {
Highcharts.setOptions({
global: {
useUTC: true
},
colors: ['#2222ff', '#ff2222']
});
$('#container').highcharts({
chart: {
defaultSeriesType: 'spline',
zoomType: 'x'
},
data: {
csv: data
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b %e',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: "Weight (lbs)"
}
},
plotOptions: {
series: {
shadow: true,
connectNulls: true,
marker: {
enabled: false
}
}
},
title: {
text: "Weight (lbs) vs. Time"
},
subtitle: {
text: null
}
});
});
});
|
Change metadata type to map | package com.github.macrodata.skyprint.section;
import lombok.Setter;
import lombok.ToString;
import javax.xml.transform.stream.StreamSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
@ToString
public class RootSection extends Section {
@Setter
private Map<String, String> metadata;
@Setter
private String name;
@Setter
private List<ResourceSection> resources;
@Setter
private List<GroupSection> groups;
public Map<String, String> getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
}
public String getName() {
if (name == null)
lazy(this::setName, get(this, OverviewSection.class).getName());
return name;
}
@Override
public String getDescription() {
if (super.getDescription() == null)
lazy(this::setDescription, get(this, OverviewSection.class).getDescription());
return super.getDescription();
}
public List<ResourceSection> getResources() {
if (resources == null)
lazy(this::setResources, list(this, ResourceSection.class));
return resources;
}
public List<GroupSection> getGroups() {
if (groups == null)
lazy(this::setGroups, list(this, GroupSection.class));
return groups;
}
} | package com.github.macrodata.skyprint.section;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
import static com.github.macrodata.skyprint.section.SectionHelper.*;
@ToString
public class RootSection extends Section {
@Setter
private MetadataSection metadata;
@Setter
private String name;
@Setter
private List<ResourceSection> resources;
@Setter
private List<GroupSection> groups;
public MetadataSection getMetadata() {
if (metadata == null)
lazy(this::setMetadata, get(this, MetadataSection.class));
return metadata;
}
public String getName() {
if (name == null)
lazy(this::setName, get(this, OverviewSection.class).getName());
return name;
}
@Override
public String getDescription() {
if (super.getDescription() == null)
lazy(this::setDescription, get(this, OverviewSection.class).getDescription());
return super.getDescription();
}
public List<ResourceSection> getResources() {
if (resources == null)
lazy(this::setResources, list(this, ResourceSection.class));
return resources;
}
public List<GroupSection> getGroups() {
if (groups == null)
lazy(this::setGroups, list(this, GroupSection.class));
return groups;
}
} |
Fix process_voting_round to reflect contract model | # pylint: disable=W0613
from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
contract = Contract()
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
| # pylint: disable=W0613
from django.dispatch import receiver
from django.db.models.signals import post_save
from voting import constants
from source.models import Source
from voting.models import VotingRound
from source import constants as source_constants
from contracts.models import Contract
@receiver(signal=post_save, sender=Source)
def create_voting_round(instance, created, **kwargs):
"""
Creates a voting round after new Source is created.
"""
if created:
voting_round = VotingRound(source=instance)
voting_round.save()
@receiver(signal=post_save, sender=VotingRound)
def process_voting_round(instance, created, **kwargs):
"""
Edits Source according to decision made in voting round.
If source already has valid contract then we can switch directly
to running state.
"""
if not created:
source = instance.source
if instance.state == constants.VOTE_APPROVE:
if source.contract_set.valid():
source.state = source_constants.STATE_RUNNING
source.save()
return
else:
contract = Contract(source=source)
contract.publisher = source.publisher
contract.save()
contract.sources.add(source)
source.state = constants.VOTE_TO_SOURCE[instance.state]
source.save()
|
Add todo comment about work to be completed | /*
* Copyright 2014 Timothy Brooks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.uncontended.precipice.metrics;
import net.uncontended.precipice.Status;
public enum Metric {
SUCCESS(false),
ERROR(false),
TIMEOUT(false),
CIRCUIT_OPEN(true),
QUEUE_FULL(true),
MAX_CONCURRENCY_LEVEL_EXCEEDED(true),
ALL_SERVICES_REJECTED(true);
private final boolean actionRejected;
Metric(boolean actionRejected) {
this.actionRejected = actionRejected;
}
public boolean actionRejected() {
return actionRejected;
}
public static Metric statusToMetric(Status status) {
// TODO: Need to handle converting cancellation to Metric (and maybe pending)
switch (status) {
case SUCCESS:
return Metric.SUCCESS;
case ERROR:
return Metric.ERROR;
case TIMEOUT:
return Metric.TIMEOUT;
default:
throw new RuntimeException("Cannot convert Status to Metric: " + status);
}
}
}
| /*
* Copyright 2014 Timothy Brooks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.uncontended.precipice.metrics;
import net.uncontended.precipice.Status;
public enum Metric {
SUCCESS(false),
ERROR(false),
TIMEOUT(false),
CIRCUIT_OPEN(true),
QUEUE_FULL(true),
MAX_CONCURRENCY_LEVEL_EXCEEDED(true),
ALL_SERVICES_REJECTED(true);
private final boolean actionRejected;
Metric(boolean actionRejected) {
this.actionRejected = actionRejected;
}
public boolean actionRejected() {
return actionRejected;
}
public static Metric statusToMetric(Status status) {
switch (status) {
case SUCCESS:
return Metric.SUCCESS;
case ERROR:
return Metric.ERROR;
case TIMEOUT:
return Metric.TIMEOUT;
default:
throw new RuntimeException("Cannot convert Status to Metric: " + status);
}
}
}
|
Support using a module as a call back if it has an function attribute by the same name. | import traceback
import types
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: 'IDLE',
ST_BUSY: 'BUSY',
ST_STOP: 'STOP',
}
def __init__(self, proc, pipe):
self.proc = proc
self.pipe = pipe
self.fileno = self.pipe.fileno
self.count = 0
self.state = NurlyStatus.ST_IDLE
@staticmethod
def label(code, short=False):
return NurlyStatus.ST_MAP[code] if not short else NurlyStatus.ST_MAP[code][0]
class NurlyAction():
def __init__(self, func, path='/', verb='GET'):
self.func = func if type(func) is not types.ModuleType else getattr(func, func.__name__.split('.')[-1])
self.path = path
self.verb = verb
def __call__(self, env, res, parent):
if env['REQUEST_METHOD'] == self.verb and env['PATH_INFO'].startswith(self.path):
try:
self.func(env, res, parent)
except:
res.code = '500 Server Error'
res.body = traceback.format_exc()
return True
return False
| import traceback
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: 'IDLE',
ST_BUSY: 'BUSY',
ST_STOP: 'STOP',
}
def __init__(self, proc, pipe):
self.proc = proc
self.pipe = pipe
self.fileno = self.pipe.fileno
self.count = 0
self.state = NurlyStatus.ST_IDLE
@staticmethod
def label(code, short=False):
return NurlyStatus.ST_MAP[code] if not short else NurlyStatus.ST_MAP[code][0]
class NurlyAction():
def __init__(self, func, path='/', verb='GET'):
self.func = func
self.path = path
self.verb = verb
def __call__(self, env, res, parent):
if env['REQUEST_METHOD'] == self.verb and env['PATH_INFO'].startswith(self.path):
try:
self.func(env, res, parent)
except:
res.code = '500 Server Error'
res.body = traceback.format_exc()
return True
return False
|
Add input's name for future usage | import React from 'react';
import styles from 'stylesheets/components/common/typography';
class Kugel extends React.Component {
constructor(props) {
super(props);
this.state = {
radius: 0,
volumen: 0
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const r = event.target.value;
this.setState({
radius: r,
volumen: this.computeVolume(r)
});
}
computeVolume(radius) {
return 4 / 3 * Math.PI * Math.pow(radius, 2);
}
render() {
return (
<div>
<h1 className={styles.heading}>Kugel</h1>
<div>
<h2>Eingabe</h2>
<form>
<label>r:
<input
type="text"
name="radius"
value={this.state.radius}
onChange={this.handleChange}
/>
</label>
</form>
<h2>Volumen</h2>
<span>{this.state.volumen}</span>
</div>
</div>
);
};
}
export default Kugel;
| import React from 'react';
import styles from 'stylesheets/components/common/typography';
class Kugel extends React.Component {
constructor(props) {
super(props);
this.state = {
radius: 0,
volumen: 0
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const r = event.target.value;
this.setState({
radius: r,
volumen: this.computeVolume(r)
});
}
computeVolume(radius) {
return 4 / 3 * Math.PI * Math.pow(radius, 2);
}
render() {
return (
<div>
<h1 className={styles.heading}>Kugel</h1>
<div>
<h2>Eingabe</h2>
<form>
<label>r:
<input
type="text"
value={this.state.radius}
onChange={this.handleChange}
/>
</label>
</form>
<h2>Volumen</h2>
<span>{this.state.volumen}</span>
</div>
</div>
);
};
}
export default Kugel;
|
Fix embed=body to query string for eventstore in mono | var debug = require('debug')('geteventstore:getevents'),
req = require('request-promise'),
assert = require('assert'),
url = require('url'),
q = require('q');
var baseErr = 'Get Events - ';
module.exports = function(config) {
var buildUrl = function(stream, startPosition, length, direction) {
var urlObj = JSON.parse(JSON.stringify(config));
urlObj.pathname = '/streams/' + stream + '/' + startPosition + '/' + direction + '/' + length;
return url.format(urlObj);
};
return function(streamName, startPosition, length, direction) {
return q().then(function() {
assert(streamName, baseErr + 'Stream Name not provided');
startPosition = startPosition || 0;
length = length || 1000;
direction = direction || 'forward';
var options = {
uri: buildUrl(streamName, startPosition, length, direction),
method: 'GET',
headers: {
"Content-Type": "application/vnd.eventstore.events+json"
},
qs: {
embed: 'body'
},
json: true
};
debug('', 'Getting Events: ' + JSON.stringify(options));
return req(options).then(function(response) {
response.entries.forEach(function(entry) {
entry.data = JSON.parse(entry.data);
});
if (direction == 'forward')
return response.entries;
return response.entries.reverse();
});
});
};
}; | var debug = require('debug')('geteventstore:getevents'),
req = require('request-promise'),
assert = require('assert'),
url = require('url'),
q = require('q');
var baseErr = 'Get Events - ';
module.exports = function(config) {
var buildUrl = function(stream, startPosition, length, direction) {
var urlObj = JSON.parse(JSON.stringify(config));
urlObj.pathname = '/streams/' + stream + '/' + startPosition + '/' + direction + '/' + length + '?embed=body';
return url.format(urlObj);
};
return function(streamName, startPosition, length, direction) {
return q().then(function() {
assert(streamName, baseErr + 'Stream Name not provided');
startPosition = startPosition || 0;
length = length || 1000;
direction = direction || 'forward';
var options = {
uri: buildUrl(streamName, startPosition, length, direction),
headers: {
"Content-Type": "application/vnd.eventstore.events+json"
},
method: 'GET',
json: true
};
debug('', 'Getting Events: ' + JSON.stringify(options));
return req(options).then(function(response) {
response.entries.forEach(function(entry) {
entry.data = JSON.parse(entry.data);
});
if (direction == 'forward')
return response.entries;
return response.entries.reverse();
});
});
};
}; |
Use a private I/O thread pool for failure detector | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.failureDetector;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.ExportBinder;
import static io.airlift.configuration.ConfigurationModule.bindConfig;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
public class FailureDetectorModule
implements Module
{
@Override
public void configure(Binder binder)
{
httpClientBinder(binder)
.bindAsyncHttpClient("failure-detector", ForFailureDetector.class)
.withPrivateIoThreadPool()
.withTracing();
bindConfig(binder).to(FailureDetectorConfig.class);
binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON);
binder.bind(FailureDetector.class)
.to(HeartbeatFailureDetector.class)
.in(Scopes.SINGLETON);
ExportBinder.newExporter(binder)
.export(HeartbeatFailureDetector.class)
.withGeneratedName();
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.failureDetector;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.ExportBinder;
import static io.airlift.configuration.ConfigurationModule.bindConfig;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
public class FailureDetectorModule
implements Module
{
@Override
public void configure(Binder binder)
{
httpClientBinder(binder)
.bindAsyncHttpClient("failure-detector", ForFailureDetector.class)
.withTracing();
bindConfig(binder).to(FailureDetectorConfig.class);
binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON);
binder.bind(FailureDetector.class)
.to(HeartbeatFailureDetector.class)
.in(Scopes.SINGLETON);
ExportBinder.newExporter(binder)
.export(HeartbeatFailureDetector.class)
.withGeneratedName();
}
}
|
Change over to local email server in production | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', '[email protected]'),
)
SERVER_EMAIL = '[email protected]'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
#EMAIL_HOST = 'smtp.mandrillapp.com'
#EMAIL_PORT = '587'
EMAIL_HOST = 'localhost'
#EMAIL_USE_TLS = True
| from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', '[email protected]'),
)
SERVER_EMAIL = '[email protected]'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True |
Remove 3.5 for now. It's not added to PyPI yet. | #!/usr/bin/env python
from setuptools import setup, find_packages
from setuputils import find_version, read
setup(
name='astor',
version=find_version('astor/__init__.py'),
description='Read/rewrite/write Python ASTs',
long_description=read('README.rst'),
author='Patrick Maupin',
author_email='[email protected]',
platforms='Independent',
url='https://github.com/berkerpeksag/astor',
packages=find_packages(exclude=['tests']),
py_modules=['setuputils'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
],
keywords='ast, codegen',
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
from setuputils import find_version, read
setup(
name='astor',
version=find_version('astor/__init__.py'),
description='Read/rewrite/write Python ASTs',
long_description=read('README.rst'),
author='Patrick Maupin',
author_email='[email protected]',
platforms='Independent',
url='https://github.com/berkerpeksag/astor',
packages=find_packages(exclude=['tests']),
py_modules=['setuputils'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Code Generators',
'Topic :: Software Development :: Compilers',
],
keywords='ast, codegen',
)
|
Fix another bug which caused sorting not to work with new combined api results | var request = require('request');
var _und = require('underscore');
/* Get orders listing. */
exports.list = function(req, res){
var results = {
orders: [],
bitStampOrders: [],
btceOrders: []
};
request('https://www.bitstamp.net/api/transactions/', function(error, response, body){
if(!error && response.statusCode == 200) {
results.bitStampOrders = JSON.parse(body);
}
request('https://btc-e.com/api/2/btc_usd/trades', function(error, response, body) {
if(!error && response.statusCode == 200) {
results.btceOrders = JSON.parse(body);
}
var mappedBitStampOrders = _und.map(results.bitStampOrders, function(order){
return {
time: order.date,
quantity: order.amount,
price: order.price,
exchange: 'bitstamp.net'
};
});
var mappedBtceOrders = _und.map(results.btceOrders, function(order){
return {
time: order.date,
quantity: order.amount,
price: order.price,
exchange: 'btc-e.com'
};
});
var combinedOrders = _und.union(mappedBitStampOrders, mappedBtceOrders);
var sortedCombinedOrders = _und.sortBy(combinedOrders, function(order){ return -1 * order.time; });
results.orders = _und.first(sortedCombinedOrders, 10);
res.send(results);
});
});
};
| var request = require('request');
var _und = require('underscore');
/* Get orders listing. */
exports.list = function(req, res){
var results = {
orders: [],
bitStampOrders: [],
btceOrders: []
};
request('https://www.bitstamp.net/api/transactions/', function(error, response, body){
if(!error && response.statusCode == 200) {
results.bitStampOrders = JSON.parse(body);
}
request('https://btc-e.com/api/2/btc_usd/trades', function(error, response, body) {
if(!error && response.statusCode == 200) {
results.btceOrders = JSON.parse(body);
}
var mappedBitStampOrders = _und.map(results.bitStampOrders, function(order){
return {
time: order.date,
quantity: order.amount,
price: order.price,
exchange: 'bitstamp.net'
};
});
var mappedBtceOrders = _und.map(results.btceOrders, function(order){
return {
time: order.date,
quantity: order.amount,
price: order.price,
exchange: 'btc-e.com'
};
});
var combinedOrders = _und.union(mappedBitStampOrders, mappedBtceOrders);
var sortedCombinedOrders = _und.sortBy(combinedOrders, function(order){ return -1 * order.date; });
results.orders = _und.first(sortedCombinedOrders, 10);
res.send(results);
});
});
};
|
Add test for invalid email | import unittest
from flask import json
from api import db
from api.BucketListAPI import app
from instance.config import application_config
class AuthenticationTestCase(unittest.TestCase):
def setUp(self):
app.config.from_object(application_config['TestingEnv'])
self.client = app.test_client()
# Binds the app to current context
with app.app_context():
# Create all tables
db.create_all()
def test_index_route(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 201)
self.assertIn('Welcome Message', response.data.decode())
def test_registration_with_missing_dredentials(self):
"""Should throw error for missing credentials"""
user = json.dumps({
'name': '',
'email': '',
'password': ''
})
response = self.client.post('/auth/register', data=user)
self.assertEqual(response.status_code, 400)
self.assertIn('Missing', response.data.decode())
def test_registration_with_invalid_email(self):
"""Should return invalid email"""
user = json.dumps({
'name': 'Patrick',
'email': 'pato',
'password': 'pat'
})
response = self.client.post('/auth/register', data=user)
self.assertEqual(response.status_code, 400)
self.assertIn('Invalid Email', response.data.decode())
def tearDown(self):
# Drop all tables
with app.app_context():
# Drop all tables
db.session.remove()
db.drop_all()
if __name__ == '__main__':
unittest.main()
| import unittest
from flask import json
from api import db
from api.BucketListAPI import app
from instance.config import application_config
class AuthenticationTestCase(unittest.TestCase):
def setUp(self):
app.config.from_object(application_config['TestingEnv'])
self.client = app.test_client()
# Binds the app to current context
with app.app_context():
# Create all tables
db.create_all()
def test_index_route(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 201)
self.assertIn('Welcome Message', response.data.decode())
def test_registration_with_missing_dredentials(self):
"""Should throw error for missing credentials"""
user = json.dumps({
'name': '',
'email': '',
'password': ''
})
response = self.client.post('/auth/register', data=user)
self.assertEqual(response.status_code, 400)
self.assertIn('Missing', response.data.decode())
def tearDown(self):
# Drop all tables
with app.app_context():
# Drop all tables
db.session.remove()
db.drop_all()
if __name__ == '__main__':
unittest.main()
|
Remove auto branch name in commit | 'use strict';
var exec = require('child_process').exec;
var throwErr = require('../utils/throw-err');
function fastPush(commitMessage) {
exec('git --version', function(error) {
if(error) {
throwErr('You don\'t have git installed');
} else {
exec('git rev-parse --abbrev-ref HEAD', function(err, currentBranch) {
currentBranch = currentBranch.trim();
if(err) {
throwErr('Can\'t get your current branch. Are you sure this is a git repository?');
} else {
exec('git add --all', function(addErr) {
if(addErr) {
throwErr(addErr);
} else {
exec('git commit -m "' + commitMessage + '"', function(commitErr) {
if(commitErr) {
throwErr(commitErr);
} else {
exec('git push origin ' + currentBranch, function(pushErr) {
if(pushErr) {
throwErr(pushErr);
} else {
console.log('"' + commitMessage + '"\nPushed!');
}
});
}
});
}
});
}
});
}
});
}
module.exports = fastPush; | 'use strict';
var exec = require('child_process').exec;
var throwErr = require('../utils/throw-err');
function fastPush(commitMessage) {
exec('git --version', function(error) {
if(error) {
throwErr('You don\'t have git installed');
} else {
exec('git rev-parse --abbrev-ref HEAD', function(err, currentBranch) {
currentBranch = currentBranch.trim();
if(err) {
throwErr('Can\'t get your current branch. Are you sure this is a git repository?');
} else {
exec('git add --all', function(addErr) {
if(addErr) {
throwErr(addErr);
} else {
exec('git commit -m "[' + currentBranch + ']' + commitMessage + '"', function(commitErr) {
if(commitErr) {
throwErr(commitErr);
} else {
exec('git push origin ' + currentBranch, function(pushErr) {
if(pushErr) {
throwErr(pushErr);
} else {
console.log('"[' + currentBranch + ']' + commitMessage + '"\nPushed!');
}
});
}
});
}
});
}
});
}
});
}
module.exports = fastPush; |
Fix for AJAX cache bug in IE | # -*- coding: utf-8 -*-
from django.http import HttpResponse
from updateable import settings
class UpdateableMiddleware(object):
def process_request(self, request):
updateable = bool(request.GET.get(settings.UPDATEABLE_GET_VARIABLE))
hashvals = {}
if updateable:
ids = request.GET.getlist('ids[]')
hashes = request.GET.getlist('hash[]')
for id, hash in zip(ids, hashes):
hashvals[id] = hash
updateable_dict = {
'updateable': updateable,
'hashes': hashvals,
'contents': [],
}
setattr(request, settings.UPDATEABLE_REQUEST_OBJECT, updateable_dict)
def process_response(self, request, response):
updateable_dict = getattr(request, settings.UPDATEABLE_REQUEST_OBJECT)
if updateable_dict['updateable']:
contents = updateable_dict['contents']
content = ''.join(contents)
response['Content-length'] = str(len(content))
if getattr(response, 'streaming', False):
response.streaming_response = (content,)
else:
response.content = content
response['Cache-control'] = 'no-cache' # Preventing IE bug
return response
| # -*- coding: utf-8 -*-
from django.http import HttpResponse
from updateable import settings
class UpdateableMiddleware(object):
def process_request(self, request):
updateable = bool(request.GET.get(settings.UPDATEABLE_GET_VARIABLE))
hashvals = {}
if updateable:
ids = request.GET.getlist('ids[]')
hashes = request.GET.getlist('hash[]')
for id, hash in zip(ids, hashes):
hashvals[id] = hash
updateable_dict = {
'updateable': updateable,
'hashes': hashvals,
'contents': [],
}
setattr(request, settings.UPDATEABLE_REQUEST_OBJECT, updateable_dict)
def process_response(self, request, response):
updateable_dict = getattr(request, settings.UPDATEABLE_REQUEST_OBJECT)
if updateable_dict['updateable']:
contents = updateable_dict['contents']
content = ''.join(contents)
response['Content-length'] = str(len(content))
if getattr(response, 'streaming', False):
response.streaming_response = (content,)
else:
response.content = content
return response
|
Add error handling to random move. | var otherPlayers = require('../../../src/command_util.js').CommandUtil.otherPlayerInRoom;
exports.listeners = {
playerEnter: chooseRandomExit
};
function chooseRandomExit(room, rooms, player, players, npc) {
return function(room, rooms, player, players, npc) {
if (isCoinFlip()) {
var exits = room.getExits();
var chosen = getRandomFromArr(exits);
if (!chosen.hasOwnProperty('mob_locked')) {
var uid = npc.getUuid();
var chosenRoom = rooms.getAt(chosen.location);
try {
npc.setRoom(chosen.location);
chosenRoom.addNpc(uid);
room.removeNpc(uid);
player.say(npc.getShortDesc(player.getLocale()) + getLeaveMessage(
player, chosenRoom));
players.eachIf(
otherPlayers.bind(
null, player),
function(p) {
p.say(npc.getShortDesc(
p.getLocale()) + getLeaveMessage(p, chosenRoom))
});
} catch(e) {
console.log("EXCEPTION: ", e);
console.log("NPC: ", npc);
}
}
}
}
}
function getLeaveMessage(player, chosenRoom) {
if (chosenRoom && chosenRoom.title)
return ' leaves for ' + chosenRoom.title[player.getLocale()];
return ' leaves.'
}
//TODO: Candidates for utilification.
function isCoinFlip() {
return Math.round(Math.random());
}
function getRandomFromArr(arr) {
return arr[Math.floor(Math.random() * arr.length)];
} | var otherPlayers = require('../../../src/command_util.js').CommandUtil.otherPlayerInRoom;
exports.listeners = {
playerEnter: chooseRandomExit
};
//FIXME: Occasionally causes crash because of undefined.
function chooseRandomExit(room, rooms, player, players, npc) {
return function(room, rooms, player, players, npc) {
if (isCoinFlip()) {
var exits = room.getExits();
var chosen = getRandomFromArr(exits);
if (!chosen.hasOwnProperty('mob_locked')) {
var uid = npc.getUuid();
var chosenRoom = rooms.getAt(chosen.location);
npc.setRoom(chosen.location);
chosenRoom.addNpc(uid);
room.removeNpc(uid);
player.say(npc.getShortDesc(player.getLocale()) + getLeaveMessage(
player, chosenRoom));
players.eachIf(
otherPlayers.bind(
null, player),
function(p) {
p.say(npc.getShortDesc(
p.getLocale()) + getLeaveMessage(p, chosenRoom))
});
}
}
}
}
function getLeaveMessage(player, chosenRoom) {
if (chosenRoom && chosenRoom.title)
return ' leaves for ' + chosenRoom.title[player.getLocale()];
return ' leaves.'
}
//TODO: Candidates for utilification.
function isCoinFlip() {
return Math.round(Math.random());
}
function getRandomFromArr(arr) {
return arr[Math.floor(Math.random() * arr.length)];
} |
Add checks for invalid sources. | import matchbox from './lib/matcher';
import transactionFormatters from './lib/formatters/transactions';
import emailFormatters from './lib/formatters/emails';
import fs from 'fs';
import concat from 'concat-stream';
import os from 'os';
import emailSources from './lib/email-sources';
const match = function(msg, cb) {
const onconcat = function(transactions) {
cb(null, transactions);
};
const onemailsadded = function() {
fs.createReadStream(filename).pipe(csvFormatter())
.pipe(matcher.addMatches())
.pipe(concat(onconcat));
};
const ondates = function(daterange) {
emails(msg, daterange).pipe(emailFormatter(msg.email.auth.token))
.pipe(matcher.addEmails(onemailsadded));
};
const onwrite = function(err) {
if (err) return cb(err);
fs.createReadStream(filename).pipe(csvFormatter()).pipe(matcher.getLimitDates(ondates));
};
const matcher = matchbox();
const csvFormatter = transactionFormatters[msg.csv.source];
const emailFormatter = emailFormatters[msg.email.source];
const emails = emailSources[msg.email.source];
if (!emails || !emailFormatter || !csvFormatter) return cb(new Error('Invalid source.'));
const file = new Buffer(msg.csv.data, 'base64');
const filename = os.tmpDir() + '/match-csv' + Date.now() + Math.random() + '.csv'
fs.writeFile(filename, file, onwrite);
};
export default match;
| import matchbox from './lib/matcher';
import transactionFormatters from './lib/formatters/transactions';
import emailFormatters from './lib/formatters/emails';
import fs from 'fs';
import concat from 'concat-stream';
import os from 'os';
import emailSources from './lib/email-sources';
const match = function(msg, cb) {
const onconcat = function(transactions) {
cb(null, transactions);
};
const onemailsadded = function() {
fs.createReadStream(filename).pipe(transactionFormatters[msg.csv.source]())
.pipe(matcher.addMatches())
.pipe(concat(onconcat));
};
const ondates = function(daterange) {
emailSources[msg.email.source](msg, daterange).pipe(emailFormatters[msg.email.source](msg.email.auth.token))
.pipe(matcher.addEmails(onemailsadded));
};
const onwrite = function(err) {
if (err) return cb(err);
fs.createReadStream(filename).pipe(transactionFormatters[msg.csv.source]()).pipe(matcher.getLimitDates(ondates));
};
const matcher = matchbox();
const file = new Buffer(msg.csv.data, 'base64');
const filename = os.tmpDir() + '/match-csv' + Date.now() + Math.random() + '.csv'
fs.writeFile(filename, file, onwrite);
};
export default match;
|
Make tests runnable in WebStorm. | (function() {
/*global __karma__,require*/
"use strict";
var included = '';
var excluded = '';
var webglValidation = false;
var release = false;
if(__karma__.config.args){
included = __karma__.config.args[0];
excluded = __karma__.config.args[1];
webglValidation = __karma__.config.args[2];
release = __karma__.config.args[3];
}
var toRequire = ['Cesium'];
if (release) {
require.config({
baseUrl : '/base/Build/Cesium'
});
toRequire.push('../Stubs/paths');
} else {
require.config({
baseUrl : '/base/Source'
});
}
require(toRequire, function (Cesium, paths) {
if (release) {
paths.Specs = '../../Specs';
paths.Source = '../../Source';
paths.Stubs = '../Stubs';
require.config({
paths: paths,
shim: {
'Cesium': {
exports: 'Cesium'
}
}
});
} else {
require.config({
paths: {
'Specs': '../Specs',
'Source' : '.'
}
});
}
require([
'Specs/customizeJasmine'
],
function(customizeJasmine) {
customizeJasmine(jasmine.getEnv(), included, excluded, webglValidation, release);
var specFiles = Object.keys(__karma__.files).filter(function(file) {
return /Spec\.js$/.test(file);
});
require(specFiles, function() {
__karma__.start();
});
});
});
})();
| (function() {
/*global __karma__,require*/
"use strict";
var included = __karma__.config.args[0];
var excluded = __karma__.config.args[1];
var webglValidation = __karma__.config.args[2];
var release = __karma__.config.args[3];
var toRequire = ['Cesium'];
if (release) {
require.config({
baseUrl : '/base/Build/Cesium'
});
toRequire.push('../Stubs/paths');
} else {
require.config({
baseUrl : '/base/Source'
});
}
require(toRequire, function (Cesium, paths) {
if (release) {
paths.Specs = '../../Specs';
paths.Source = '../../Source';
paths.Stubs = '../Stubs';
require.config({
paths: paths,
shim: {
'Cesium': {
exports: 'Cesium'
}
}
});
} else {
require.config({
paths: {
'Specs': '../Specs',
'Source' : '.'
}
});
}
require([
'Specs/customizeJasmine'
],
function(customizeJasmine) {
customizeJasmine(jasmine.getEnv(), included, excluded, webglValidation, release);
var specFiles = Object.keys(__karma__.files).filter(function(file) {
return /Spec\.js$/.test(file);
});
require(specFiles, function() {
__karma__.start();
});
});
});
})(); |
Update regex to match underscore and be case insensitive; | "use strict";
;(function ( root, name, definition ) {
/*
* Exports
*/
if ( typeof define === 'function' && define.amd ) {
define( [], definition );
}
else if ( typeof module === 'object' && module.exports ) {
module.exports = definition();
}
else {
root[ name ] = definition();
}
})( this, 'crouch', function () {
/**
* RegExp to find placeholders in the template
*
* http://regexr.com/3eveu
* @type {RegExp}
*/
var _re = /{([0-9a-z_]+?)}/ig;
/**
* Micro template compiler
*
* @param {string} template
* @param {array|object} values
* @returns {string}
*/
var crouch = function ( template, values ) {
/*
* Default arguments
*/
var
template = template || "",
values = values || {};
var match;
/*
* Loop through all the placeholders that matched with regex
*/
while ( match = _re.exec( template ) ) {
/*
* Get value from given values and
* if it doesn't exist use empty string
*/
var _value = values[ match[ 1 ] ];
if ( !_value ) _value = "";
/*
* Replace the placeholder with a real value.
*/
template = template.replace( match[ 0 ], _value )
}
/*
* Return the template with filled in values
*/
return template;
};
/**
* 😎
*/
return crouch;
} );
| "use strict";
;(function ( root, name, definition ) {
/*
* Exports
*/
if ( typeof define === 'function' && define.amd ) {
define( [], definition );
}
else if ( typeof module === 'object' && module.exports ) {
module.exports = definition();
}
else {
root[ name ] = definition();
}
})( this, 'crouch', function () {
/**
* RegExp to find placeholders in the template
*
* http://regexr.com/3e1o7
* @type {RegExp}
*/
var _re = /{([0-9a-zA-Z]+?)}/g;
/**
* Micro template compiler
*
* @param {string} template
* @param {array|object} values
* @returns {string}
*/
var crouch = function ( template, values ) {
/*
* Default arguments
*/
var
template = template || "",
values = values || {};
var match;
/*
* Loop through all the placeholders that matched with regex
*/
while ( match = _re.exec( template ) ) {
/*
* Get value from given values and
* if it doesn't exist use empty string
*/
var _value = values[ match[ 1 ] ];
if ( !_value ) _value = "";
/*
* Replace the placeholder with a real value.
*/
template = template.replace( match[ 0 ], _value )
}
/*
* Return the template with filled in values
*/
return template;
};
/**
* 😎
*/
return crouch;
} );
|
Use auth.credentials.user for policy checks | const Boom = require('boom');
exports.register = function (server, options, next) {
if (!options) options = {};
const policies = options.policies || [];
// General check function
check = async(user, action, target) => {
if (!user || !action) return false;
try {
// Resolve check function
let check_fn = action;
if (!(check_fn instanceof Function)) check_fn = policies[action];
if (!(check_fn instanceof Function)) {
server.log(['warning', 'authorize'], {message: 'no policy defined for ' + action});
return false
}
// Test against check_fn
let result = check_fn(user, target);
// Support async policies
if (result instanceof Promise) result = await result;
// ensure result is true or false only
return !!result;
} catch (error) {
// Log and reject unhandled errors
server.log(['error', 'authorize'], {action, target, error});
return false;
}
};
// Adds request.can() decorator
function can(action, target) {
return check(this.auth.credentials && this.auth.credentials.user, action, target);
}
server.decorate('request', 'can', can);
// Adds request.authorize() decorator
async function authorize(action, target) {
let result = await check(this.auth.credentials && this.auth.credentials.user, action, target);
if (result !== true) throw Boom.unauthorized(action);
return true;
}
server.decorate('request', 'authorize', authorize);
next();
};
exports.register.attributes = {
name: 'bak-policy-authorize'
};
| const Boom = require('boom');
exports.register = function (server, options, next) {
if (!options) options = {};
const policies = options.policies || [];
// General check function
check = async(user, action, target) => {
if (!user || !action) return false;
try {
// Resolve check function
let check_fn = action;
if (!(check_fn instanceof Function)) check_fn = policies[action];
if (!(check_fn instanceof Function)) {
server.log(['warning', 'authorize'], {message: 'no policy defined for ' + action});
return false
}
// Test against check_fn
let result = check_fn(user, target);
// Support async policies
if (result instanceof Promise) result = await result;
// ensure result is true or false only
return !!result;
} catch (error) {
// Log and reject unhandled errors
server.log(['error', 'authorize'], {action, target, error});
return false;
}
};
// Adds request.can() decorator
function can(action, target) {
return check(this.auth.credentials, action, target);
}
server.decorate('request', 'can', can);
// Adds request.authorize() decorator
async function authorize(action, target) {
let result = await check(this.auth.credentials, action, target);
if (result !== true) throw Boom.unauthorized(action);
return true;
}
server.decorate('request', 'authorize', authorize);
next();
};
exports.register.attributes = {
name: 'bak-policy-authorize'
};
|
Modify an error handling when a command not specified for Which | """
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
raise ValueError("require a command")
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
| """
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
raise CommandError(
"invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL
)
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
|
Remove static import in this test. | package com.kickstarter.libs.utils;
import com.kickstarter.factories.CategoryFactory;
import com.kickstarter.factories.LocationFactory;
import com.kickstarter.libs.RefTag;
import com.kickstarter.services.DiscoveryParams;
import junit.framework.TestCase;
public class DiscoveryParamsUtilsTest extends TestCase {
public void testRefTag() {
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().category(CategoryFactory.artCategory()).build()),
RefTag.category()
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder()
.category(CategoryFactory.artCategory())
.sort(DiscoveryParams.Sort.POPULAR)
.build()),
RefTag.category(DiscoveryParams.Sort.POPULAR)
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().location(LocationFactory.germany()).build()),
RefTag.city()
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().staffPicks(true).build()),
RefTag.recommended()
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().staffPicks(true).sort(DiscoveryParams.Sort.POPULAR).build()),
RefTag.recommended(DiscoveryParams.Sort.POPULAR)
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().social(1).build()),
RefTag.social()
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().term("art").build()),
RefTag.search()
);
assertEquals(
DiscoveryParamsUtils.refTag(DiscoveryParams.builder().build()),
RefTag.discovery()
);
}
}
| package com.kickstarter.libs.utils;
import com.kickstarter.factories.CategoryFactory;
import com.kickstarter.factories.LocationFactory;
import com.kickstarter.libs.RefTag;
import com.kickstarter.services.DiscoveryParams;
import junit.framework.TestCase;
import static com.kickstarter.libs.utils.DiscoveryParamsUtils.refTag;
public class DiscoveryParamsUtilsTest extends TestCase {
public void testRefTag() {
assertEquals(
refTag(DiscoveryParams.builder().category(CategoryFactory.artCategory()).build()),
RefTag.category()
);
assertEquals(
refTag(DiscoveryParams.builder().category(CategoryFactory.artCategory()).sort(DiscoveryParams.Sort.POPULAR).build()),
RefTag.category(DiscoveryParams.Sort.POPULAR)
);
assertEquals(
refTag(DiscoveryParams.builder().location(LocationFactory.germany()).build()),
RefTag.city()
);
assertEquals(
refTag(DiscoveryParams.builder().staffPicks(true).build()),
RefTag.recommended()
);
assertEquals(
refTag(DiscoveryParams.builder().staffPicks(true).sort(DiscoveryParams.Sort.POPULAR).build()),
RefTag.recommended(DiscoveryParams.Sort.POPULAR)
);
assertEquals(
refTag(DiscoveryParams.builder().social(1).build()),
RefTag.social()
);
assertEquals(
refTag(DiscoveryParams.builder().term("art").build()),
RefTag.search()
);
assertEquals(
refTag(DiscoveryParams.builder().build()),
RefTag.discovery()
);
}
}
|
Add redirect middleware to heroku configs | import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
)
| import os
import urllib.parse
from gamecraft.settings_heroku_base import *
DEBUG = False
TEMPLATE_DEBUG = False
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
redis_parse_result = urllib.parse.urlparse(os.environ['REDISCLOUD_URL'])
CACHES = {
'default': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': '{redis.hostname}:{redis.port}:0'.format(redis=redis_parse_result),
'OPTIONS': {
'CLIENT_CLASS': 'redis_cache.client.DefaultClient',
'PASSWORD': redis_parse_result.password,
'PICKLE_VERSION': -1,
'IGNORE_EXCEPTIONS': True,
'CONNECTION_POOL_KWARGS': {'max_connections': 10}
}
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.gzip.GZipMiddleware',
'pipeline.middleware.MinifyHTMLMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
|
Remove a redundant if and fix a syntax error | import ircbotframe
import sys
class Handler:
def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
self.channels = channels
self.bot = ircbotframe.ircBot(host, port, name, description)
self.bot.bind("376", self.endMOTD)
self.bot.start()
def endMOTD(self, sender, headers, message):
for chan in self.channels:
self.bot.joinchan(chan)
def main(cmd, args):
args = args[:]
parsemode = ["host"]
host = None
name = "MediaWiki"
channels = []
while len(args) > 0:
if len(parsemode) < 1:
if args[0] == "-n":
parsemode.insert(0, "name")
else:
channels.append(args[0])
else:
if parsemode[0] == "name":
name = args[0]
elif parsemode[0] == "host":
host = args[0]
parsemode = parsemode[1:]
args = args[1:]
if host == None:
print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]")
return
else:
Handler(host=host, name=name, channels=channels)
if __name__ == "__main__":
main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
| import ircbotframe
import sys
class Handler:
def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]):
self.channels = channels
self.bot = ircbotframe.ircBot(host, port, name, description)
self.bot.bind("376", self.endMOTD)
self.bot.start()
def endMOTD(self, sender, headers, message):
for chan in self.channels:
self.bot.joinchan(chan)
def main(cmd, args):
args = args[:]
parsemode = ["host"]
host = None
name = "MediaWiki"
channels = []
while len(args) > 0:
if len(parsemode) < 1:
if args[0] == "-n":
parsemode.insert(0, "name")
else:
channels.append(args[0])
else:
if parsemode[0] == "name":
name = args[0]
elif parsemode[0] == "host":
host = args[0]
parsemode = parsemode[1:]
args = args[1:]
if host == None:
print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]")
return
else:
Handler(host=host, name=name channels=channels)
if __name__ == "__main__":
if __name__ == '__main__':
main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
|
Make CMS default interface language install correctly.
We could have a situation where:
* Language == Interface languages (so SameInterfaceLanguages is true)
* Default language != Default Interface language.
This wasn't possible anymore. This changes makes sure the
'sameInterfaceLanguages' check does not enforce the same default
language anymore. | <?php
namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
/**
* Validates and saves the data from the languages form
*
* @author Wouter Sioen <[email protected]>
*/
class LanguagesHandler
{
public function process(Form $form, Request $request)
{
if (!$request->isMethod('POST')) {
return false;
}
$form->handleRequest($request);
if ($form->isValid()) {
return $this->processValidForm($form, $request);
}
return false;
}
public function processValidForm(Form $form, $request)
{
$data = $form->getData();
// different fields for single and multiple language
$data->setLanguages(
($data->getLanguageType() === 'multiple')
? $data->getLanguages()
: array($data->getDefaultLanguage())
);
// take same_interface_language field into account
$data->setInterfaceLanguages(
($data->getSameInterfaceLanguage() === true)
? $data->getLanguages()
: $data->getInterfaceLanguages()
);
$request->getSession()->set('installation_data', $data);
return true;
}
}
| <?php
namespace ForkCMS\Bundle\InstallerBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
/**
* Validates and saves the data from the languages form
*
* @author Wouter Sioen <[email protected]>
*/
class LanguagesHandler
{
public function process(Form $form, Request $request)
{
if (!$request->isMethod('POST')) {
return false;
}
$form->handleRequest($request);
if ($form->isValid()) {
return $this->processValidForm($form, $request);
}
return false;
}
public function processValidForm(Form $form, $request)
{
$data = $form->getData();
// different fields for single and multiple language
$data->setLanguages(
($data->getLanguageType() === 'multiple')
? $data->getLanguages()
: array($data->getDefaultLanguage())
);
// take same_interface_language field into account
$data->setInterfaceLanguages(
($data->getSameInterfaceLanguage() === true)
? $data->getLanguages()
: $data->getInterfaceLanguages()
);
if ($data->getSameInterfaceLanguage() === true) {
$data->setDefaultInterfaceLanguage($data->getDefaultLanguage());
}
$request->getSession()->set('installation_data', $data);
return true;
}
}
|
Fix loading schedule from file | package linenux.control;
import java.nio.file.Paths;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import linenux.command.result.CommandResult;
import linenux.model.Schedule;
import linenux.storage.XmlScheduleStorage;
/**
* Controls data flow for the entire application.
*/
public class ControlUnit {
private Schedule schedule;
private XmlScheduleStorage scheduleStorage;
private CommandManager commandManager;
private ObjectProperty<CommandResult> lastCommandResult = new SimpleObjectProperty<>();
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
if (this.hasExistingSchedule() && getSchedule() != null) {
this.schedule = getSchedule();
} else {
this.schedule = new Schedule();
}
this.commandManager = new CommandManager(schedule);
}
public CommandResult execute(String userInput) {
CommandResult result = commandManager.delegateCommand(userInput);
lastCommandResult.setValue(result);
scheduleStorage.saveScheduleToFile(schedule);
return result;
}
private boolean hasExistingSchedule() {
return scheduleStorage.getFile().exists();
}
private Schedule getExistingSchedule() {
return scheduleStorage.loadScheduleFromFile();
}
private String getDefaultFilePath() {
return Paths.get(".").toAbsolutePath().toString();
}
public Schedule getSchedule() {
return this.schedule;
}
public ObjectProperty<CommandResult> getLastCommandResultProperty() {
return this.lastCommandResult;
}
}
| package linenux.control;
import java.nio.file.Paths;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import linenux.command.result.CommandResult;
import linenux.model.Schedule;
import linenux.storage.XmlScheduleStorage;
/**
* Controls data flow for the entire application.
*/
public class ControlUnit {
private Schedule schedule;
private XmlScheduleStorage scheduleStorage;
private CommandManager commandManager;
private ObjectProperty<CommandResult> lastCommandResult = new SimpleObjectProperty<>();
public ControlUnit() {
this.scheduleStorage = new XmlScheduleStorage(getDefaultFilePath());
this.schedule = (hasExistingSchedule()) ? getExistingSchedule() : new Schedule();
this.commandManager = new CommandManager(schedule);
}
public CommandResult execute(String userInput) {
CommandResult result = commandManager.delegateCommand(userInput);
lastCommandResult.setValue(result);
scheduleStorage.saveScheduleToFile(schedule);
return result;
}
private boolean hasExistingSchedule() {
return scheduleStorage.getFile().exists();
}
private Schedule getExistingSchedule() {
return scheduleStorage.loadScheduleFromFile();
}
private String getDefaultFilePath() {
return Paths.get(".").toAbsolutePath().toString();
}
public Schedule getSchedule() {
return this.schedule;
}
public ObjectProperty<CommandResult> getLastCommandResultProperty() {
return this.lastCommandResult;
}
}
|
Fix validation error in Firefox | import React, { PropTypes, Component } from 'react';
import shouldPureComponentUpdate from 'react-pure-render/function';
import Label from 'binary-components/lib/Label';
import NumericInput from 'binary-components/lib/NumericInput';
// const basises = ['payout', 'stake'];
const payouts = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000];
export default class StakeCard extends Component {
shouldComponentUpdate = shouldPureComponentUpdate;
static propTypes = {
amount: PropTypes.number.isRequired,
// basis: PropTypes.oneOf(basises).isRequired,
onAmountChange: PropTypes.func.isRequired, // both functions take the updated value instead of event object
onBasisChange: PropTypes.func.isRequired,
};
render() {
const { amount, onAmountChange } = this.props;
return (
<div className="param-row payout-picker">
{/* <RadioGroup
className="radio-selector"
name={'basis' + id}
options={basisOptions}
onChange={basises.map(i => ({ text: i, value: i }))}
value={basis}
/> */}
<Label text="Stake" />
<NumericInput
className="numeric-input param-field"
value={amount}
min={0}
max={100000}
valueList={payouts}
onChange={onAmountChange}
/>
</div>
);
}
}
| import React, { PropTypes, Component } from 'react';
import shouldPureComponentUpdate from 'react-pure-render/function';
import Label from 'binary-components/lib/Label';
import NumericInput from 'binary-components/lib/NumericInput';
// const basises = ['payout', 'stake'];
const payouts = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000];
export default class StakeCard extends Component {
shouldComponentUpdate = shouldPureComponentUpdate;
static propTypes = {
amount: PropTypes.number.isRequired,
// basis: PropTypes.oneOf(basises).isRequired,
onAmountChange: PropTypes.func.isRequired, // both functions take the updated value instead of event object
onBasisChange: PropTypes.func.isRequired,
};
render() {
const { amount, onAmountChange } = this.props;
return (
<div className="param-row payout-picker">
{/* <RadioGroup
className="radio-selector"
name={'basis' + id}
options={basisOptions}
onChange={basises.map(i => ({ text: i, value: i }))}
value={basis}
/> */}
<Label text="Stake" />
<NumericInput
className="numeric-input param-field"
value={amount}
min={0.35}
max={100000}
valueList={payouts}
onChange={onAmountChange}
/>
</div>
);
}
}
|
Fix display of code block language where none is given. | <?php
namespace FluxBB\Markdown\Node;
use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;
class CodeBlock extends Node implements NodeAcceptorInterface
{
/**
* @var Collection
*/
protected $lines;
/**
* @var string
*/
protected $language;
public function __construct(Text $text, $language = '')
{
$this->lines = new Collection([$text]);
$this->language = $language;
}
public function acceptBlankLine(BlankLine $blankLine)
{
$this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', ''));
return $this;
}
public function acceptCodeBlock(CodeBlock $codeBlock)
{
$codeBlock->lines->each(function (Text $line) {
$this->lines->add($line);
});
return $this;
}
public function getContent()
{
$content = new Text($this->lines->join("\n"));
// Just in case we added blank lines at the end, we remove them, and finally add back the trailing newline.
$content->replace('/(\n[ ]*)*$/', '')->append("\n");
return $content;
}
public function getLines()
{
return $this->lines;
}
public function hasLanguage()
{
return ! empty($this->language);
}
public function getLanguage()
{
return $this->language;
}
public function visit(NodeVisitorInterface $visitor)
{
$visitor->visitCodeBlock($this);
}
}
| <?php
namespace FluxBB\Markdown\Node;
use FluxBB\Markdown\Common\Collection;
use FluxBB\Markdown\Common\Text;
class CodeBlock extends Node implements NodeAcceptorInterface
{
/**
* @var Collection
*/
protected $lines;
/**
* @var string
*/
protected $language;
public function __construct(Text $text, $language = null)
{
$this->lines = new Collection([$text]);
$this->language = $language;
}
public function acceptBlankLine(BlankLine $blankLine)
{
$this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', ''));
return $this;
}
public function acceptCodeBlock(CodeBlock $codeBlock)
{
$codeBlock->lines->each(function (Text $line) {
$this->lines->add($line);
});
return $this;
}
public function getContent()
{
$content = new Text($this->lines->join("\n"));
// Just in case we added blank lines at the end, we remove them, and finally add back the trailing newline.
$content->replace('/(\n[ ]*)*$/', '')->append("\n");
return $content;
}
public function getLines()
{
return $this->lines;
}
public function hasLanguage()
{
return ! is_null($this->language);
}
public function getLanguage()
{
return $this->language;
}
public function visit(NodeVisitorInterface $visitor)
{
$visitor->visitCodeBlock($this);
}
}
|
Change class Baro to use timedelta_to_string, some fixes | from datetime import datetime
import utils
class Baro:
"""This class contains info about the Void Trader and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation']['sec'])
self.end = datetime.fromtimestamp(data['Expiry']['sec'])
self.location = data['Node']
self.manifest = data['Manifest']
def __str__(self):
"""Returns a string with all the information about Baro's offers
"""
baroItemString = ""
if datetime.now() < self.start:
return "None"
else:
for item in self.manifest:
baroItemString += ('== '+ str(item["ItemType"]) +' ==\n'
'- price: '+ str(item["PrimePrice"]) +' ducats + '+ str(item["RegularPrice"]) +'cr -\n\n' )
return baroItemString
def get_end_string(self):
"""Returns a string containing Baro's departure time
"""
return timedelta_to_string(self.end - datetime.now())
def get_start_string(self):
"""Returns a string containing Baro's arrival time
"""
return timedelta_to_string(self.start - datetime.now())
| from datetime import datetime
class Baro:
"""This class represents a Baro item and is initialized with
data in JSON format
"""
def __init__(self, data):
self.config = data['Config']
self.start = datetime.fromtimestamp(data['Activation']['sec'])
self.end = datetime.fromtimestamp(data['Expiry']['sec'])
self.location = data['Node']
self.manifest = data['Manifest']
def __str__(self):
"""Returns a string with all the information about Baro offer
"""
baroItemString = ""
if datetime.now() < self.start:
return "None"
else:
for item in self.manifest:
baroItemString += ('== '+ str(item["ItemType"]) +' ==\n'
'- price: '+ str(item["PrimePrice"]) +' ducats + '+ str(item["RegularPrice"]) +'cr -\n\n' )
return baroItemString
def get_eta_string(self):
"""Returns a string containing the Baro's ETA
"""
seconds = int((self.end - datetime.now()).total_seconds())
return '{} days, {} hrs, {} mins'.format((seconds // 86400), ((seconds % 86400) // 3600),
(seconds % 3600) // 60)
def get_start_string(self):
"""Returns a string containing the Baro's start
"""
seconds = int((self.start - datetime.now()).total_seconds())
return '{} days, {} hrs, {} mins'.format((seconds // 86400), ((seconds % 86400) // 3600),
(seconds % 3600) // 60) |
Fix UserCommentForm(), which got broken in the previous commit. | from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
try:
from django import newforms as forms
except ImportError:
from django import forms
from blango.models import Comment
# This violates the DRY principe, but it's the only
# way I found for editing staff comments from
# the Django admin application
class CommentForm(forms.ModelForm):
author = forms.CharField(label=_('Name'), max_length=16)
author_uri = forms.CharField(label=_('Website'), max_length=256, required=False)
author_email = forms.EmailField(label=_('Email'), help_text=mark_safe('<span class="small">%s</span>' % _('(Won\'t be published)')))
class Meta:
model = Comment
fields = ('author', 'author_uri', 'author_email', 'body')
def save(self, entry):
self.instance.entry = entry
super(CommentForm, self).save()
def clean_author(self):
author = self.cleaned_data['author']
try:
User.objects.get(username=author)
raise forms.ValidationError(_('This username belongs to a registered user'))
except User.DoesNotExist:
return author
class UserCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body', )
def save(self, entry, request):
self.instance.user = request.user
self.instance.entry = entry
super(UserCommentForm, self).save(entry)
| from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
from django.contrib.auth.models import User
try:
from django import newforms as forms
except ImportError:
from django import forms
from blango.models import Comment
# This violates the DRY principe, but it's the only
# way I found for editing staff comments from
# the Django admin application
class CommentForm(forms.ModelForm):
author = forms.CharField(label=_('Name'), max_length=16)
author_uri = forms.CharField(label=_('Website'), max_length=256, required=False)
author_email = forms.EmailField(label=_('Email'), help_text=mark_safe('<span class="small">%s</span>' % _('(Won\'t be published)')))
class Meta:
model = Comment
fields = ('author', 'author_uri', 'author_email', 'body')
def save(self, entry):
self.instance.entry = entry
super(CommentForm, self).save()
def clean_author(self):
author = self.cleaned_data['author']
try:
User.objects.get(username=author)
raise forms.ValidationError(_('This username belongs to a registered user'))
except User.DoesNotExist:
return author
class UserCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body', )
def save(self, entry, request):
self.instance.user = request.user
super(UserCommentForm, self).save(entry)
|
Read the file content, if it is not read when the request is multipart then the client get an error | """
@author: Ferdinand E. Silva
@email: [email protected]
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
| """
@author: Ferdinand E. Silva
@email: [email protected]
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(request.read(fileSize))
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
Build fails if lint fails | /*global desc, task, jake, fail, complete */
(function() {
"use strict";
desc("Build and test");
task("default", ["lint"]);
desc("Lint everything");
task("lint", [], function() {
var lint = require("./build/lint/lint_runner.js");
var files = new jake.FileList();
files.include("**/*.js");
files.exclude("node_modules");
var passed = lint.validateFileList(files.toArray(), nodeLintOptions(), {});
if (!passed) fail("Lint failed");
});
desc("Integrate");
task("integrate", ["default"], function() {
console.log("1. Make sure 'git status' is clean.");
console.log("2. Build on the integration box.");
console.log(" a. Walk over to integration box.");
console.log(" b. 'git pull'");
console.log(" c. 'jake'");
console.log(" d. 'If jake fails, stop! Try again after fixing the issue'");
console.log("3. 'git checkout integration'");
console.log("4. 'git merge master --no-ff --log");
console.log("5. 'git checkout master'");
});
function nodeLintOptions() {
return {
bitwise:true,
curly:false,
eqeqeq:true,
forin:true,
immed:true,
latedef:true,
newcap:true,
noarg:true,
noempty:true,
nonew:true,
regexp:true,
undef:true,
strict:true,
trailing:true,
node:true
};
}
}()); | /*global desc, task, jake, fail, complete */
(function() {
"use strict";
desc("Build and test");
task("default", ["lint"]);
desc("Lint everything");
task("lint", [], function() {
var lint = require("./build/lint/lint_runner.js");
var files = new jake.FileList();
files.include("**/*.js");
files.exclude("node_modules");
lint.validateFileList(files.toArray(), nodeLintOptions(), {});
});
desc("Integrate");
task("integrate", ["default"], function() {
console.log("1. Make sure 'git status' is clean.");
console.log("2. Build on the integration box.");
console.log(" a. Walk over to integration box.");
console.log(" b. 'git pull'");
console.log(" c. 'jake'");
console.log(" d. 'If jake fails, stop! Try again after fixing the issue'");
console.log("3. 'git checkout integration'");
console.log("4. 'git merge master --no-ff --log");
console.log("5. 'git checkout master'");
});
function nodeLintOptions() {
return {
bitwise:true,
curly:false,
eqeqeq:true,
forin:true,
immed:true,
latedef:true,
newcap:true,
noarg:true,
noempty:true,
nonew:true,
regexp:true,
undef:true,
strict:true,
trailing:true,
node:true
};
}
}()); |
Fix for Python 3.4 extension compilation.
An extra extension compilation option introduced in Python 3.4 collided with
-std=c99; added -Wno-declaration-after-statement negates this. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.core import Extension
#from Cython.Distutils import build_ext
import numpy
from numpy.distutils.system_info import get_info
mpfit_sources = [
'mpyfit/mpyfit.c',
'mpyfit/cmpfit/mpfit.c',
]
# Avoid some numpy warnings, dependent on the numpy version
npy_api_version = "NPY_{0}_{1}_API_VERSION".format(
*(numpy.__version__.split('.')[:2]))
setup(
name='mpyfit',
version='0.9.0',
license='BSD 2 part license',
maintainer='Evert Rol',
maintainer_email='[email protected]',
packages=['mpyfit'],
url='https://github.com/evertrol/mpyfit',
classifiers=[
'Intentended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Programing Language :: Python',
'Licence :: OSI Approved :: BSD License',
],
ext_modules=[
Extension(
'mpyfit.mpfit',
sources=mpfit_sources,
include_dirs=['mpyfit/cmpfit', numpy.get_include()],
extra_compile_args=['-std=c99',
'-Wno-declaration-after-statement',
'-DNPY_NO_DEPRECATED_API={0}'.format(
npy_api_version)]
),
]
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.extension import Extension
#from Cython.Distutils import build_ext
import numpy
from numpy.distutils.system_info import get_info
mpfit_sources = [
'mpyfit/mpyfit.c',
'mpyfit/cmpfit/mpfit.c',
]
# Avoid some numpy warnings, dependent on the numpy version
npy_api_version = "NPY_{0}_{1}_API_VERSION".format(
*(numpy.__version__.split('.')[:2]))
setup(
name='mpyfit',
version='0.9.0',
license='BSD 2 part license',
maintainer='Evert Rol',
maintainer_email='[email protected]',
packages=['mpyfit'],
url='https://github.com/evertrol/mpyfit',
classifiers=[
'Intentended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Programing Language :: Python',
'Licence :: OSI Approved :: BSD License',
],
ext_modules=[
Extension(
'mpyfit.mpfit',
sources=mpfit_sources,
include_dirs=['mpyfit/cmpfit', numpy.get_include()],
extra_compile_args=['-std=c99 '
'-DNPY_NO_DEPRECATED_API={0}'.format(
npy_api_version)]
),
]
)
|
Remove dependency on FirebaseNotification Contract | <?php
namespace DouglasResende\FCM\Channels;
use DouglasResende\FCM\Messages\FirebaseMessage;
use Illuminate\Contracts\Config\Repository as Config;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;
/**
* Class FirebaseChannel
* @package DouglasResende\FCM\Channels
*/
class FirebaseChannel
{
/**
* @const api uri
*/
const API_URI = 'https://fcm.googleapis.com/fcm/send';
/**
* @var Client
*/
private $client;
/**
* @var Config
*/
private $config;
/**
* FirebaseChannel constructor.
* @param Client $client
* @param Config $config
*/
public function __construct(Client $client, Config $config)
{
$this->client = $client;
$this->config = $config;
}
/**
* @param $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
$message = $notification->toFCM($notifiable, new FirebaseMessage);
$this->client->post(FirebaseChannel::API_URI, [
'headers' => [
'Authorization' => 'key=' . $this->getApiKey(),
'Content-Type' => 'application/json',
],
'body' => $message->serialize(),
]);
}
/**
* @return mixed
*/
private function getApiKey()
{
return $this->config->get('services.fcm.key');
}
} | <?php
namespace DouglasResende\FCM\Channels;
use DouglasResende\FCM\Messages\FirebaseMessage;
use Illuminate\Contracts\Config\Repository as Config;
use GuzzleHttp\Client;
use DouglasResende\FCM\Contracts\FirebaseNotification as Notification;
/**
* Class FirebaseChannel
* @package DouglasResende\FCM\Channels
*/
class FirebaseChannel
{
/**
* @const api uri
*/
const API_URI = 'https://fcm.googleapis.com/fcm/send';
/**
* @var Client
*/
private $client;
/**
* @var Config
*/
private $config;
/**
* FirebaseChannel constructor.
* @param Client $client
* @param Config $config
*/
public function __construct(Client $client, Config $config)
{
$this->client = $client;
$this->config = $config;
}
/**
* @param $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
$message = $notification->toFCM($notifiable, new FirebaseMessage);
$this->client->post(FirebaseChannel::API_URI, [
'headers' => [
'Authorization' => 'key=' . $this->getApiKey(),
'Content-Type' => 'application/json',
],
'body' => $message->serialize(),
]);
}
/**
* @return mixed
*/
private function getApiKey()
{
return $this->config->get('services.fcm.key');
}
} |
Remove shift that was supposed to remove the callback only when it existed
Signed-off-by: Henrique Vicente <[email protected]> | /*
* grunt-cli-config
* https://github.com/henvic/grunt-cli-config
*
* Copyright (c) 2014 Henrique Vicente
* Licensed under the MIT license.
*/
'use strict';
module.exports = function exports(grunt) {
function parseBooleanParam(option) {
return {
key: option,
value: grunt.option(option)
};
}
function parseStringParam(option, equals) {
return {
key: option.substring(0, equals),
value: option.substring(equals + 1)
};
}
function parse(option) {
var equals = option.lastIndexOf('=');
if (equals === -1) {
return parseBooleanParam(option);
}
return parseStringParam(option, equals);
}
/*
* normalize flags which have a --no prefix so we can extract them like negative booleans
*/
function normalize(option) {
return option.replace(/^--(no-)?/, '');
}
/**
* Apply the cli configs to the receiving task / subTask
* e.g., grunt.applyCliConfig(task, subTask);
* @param task
*/
grunt.applyCliConfig = function apply() {
var options = grunt.option.flags(),
params = [].slice.call(arguments);
options.forEach(function getOption(option) {
var choice = parse(normalize(option)),
key = params;
key.push(choice.key);
grunt.config(key, choice.value);
});
};
exports.normalize = normalize;
exports.parse = parse;
return exports;
};
| /*
* grunt-cli-config
* https://github.com/henvic/grunt-cli-config
*
* Copyright (c) 2014 Henrique Vicente
* Licensed under the MIT license.
*/
'use strict';
module.exports = function exports(grunt) {
function parseBooleanParam(option) {
return {
key: option,
value: grunt.option(option)
};
}
function parseStringParam(option, equals) {
return {
key: option.substring(0, equals),
value: option.substring(equals + 1)
};
}
function parse(option) {
var equals = option.lastIndexOf('=');
if (equals === -1) {
return parseBooleanParam(option);
}
return parseStringParam(option, equals);
}
/*
* normalize flags which have a --no prefix so we can extract them like negative booleans
*/
function normalize(option) {
return option.replace(/^--(no-)?/, '');
}
/**
* Apply the cli configs to the receiving task / subTask
* e.g., grunt.applyCliConfig(task, subTask);
* @param task
*/
grunt.applyCliConfig = function apply() {
var options = grunt.option.flags(),
params = [].slice.call(arguments);
params.shift();
options.forEach(function getOption(option) {
var choice = parse(normalize(option)),
key = params;
key.push(choice.key);
grunt.config(key, choice.value);
});
};
exports.normalize = normalize;
exports.parse = parse;
return exports;
};
|
fix(linter): Fix Arrow function should not return assignment | 'use strict';
const cheerio = require('cheerio');
const http = require('http');
const querystring = require('querystring');
const getZip = data => {
return new Promise((resolve, reject) => {
const qs = querystring.stringify({
calle: data.address,
numero: data.number,
comuna: data.commune
});
const url = `http://www.correos.cl/SitePages/codigo_postal/codigo_postal.aspx?${qs}`;
http.get(url, res => {
if (res.statusCode !== 200) {
res.resume();
reject(new Error(`Request Failed. Status Code: ${res.statusCode}`));
} else {
res.setEncoding('utf8');
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
try {
const $ = cheerio.load(rawData, {decodeEntities: false});
const zip = $('span[id$="CodigoPostal"]').text();
const address = $('span[id$="Calle"]').text();
const number = $('span[id$="Numero"]').text();
const commune = $('span[id$="Comuna"]').text();
if (!zip) throw new Error('Not found');
resolve({
zip: parseInt(zip, 10),
address: address,
number: number,
commune: commune
});
} catch (err) {
reject(err);
}
});
}
}).on('error', err => reject(err));
});
};
module.exports = getZip;
| 'use strict';
const cheerio = require('cheerio');
const http = require('http');
const querystring = require('querystring');
const getZip = data => {
return new Promise((resolve, reject) => {
const qs = querystring.stringify({
calle: data.address,
numero: data.number,
comuna: data.commune
});
const url = `http://www.correos.cl/SitePages/codigo_postal/codigo_postal.aspx?${qs}`;
http.get(url, res => {
if (res.statusCode !== 200) {
res.resume();
reject(new Error(`Request Failed. Status Code: ${res.statusCode}`));
} else {
res.setEncoding('utf8');
let rawData = '';
res.on('data', chunk => rawData += chunk);
res.on('end', () => {
try {
const $ = cheerio.load(rawData, {decodeEntities: false});
const zip = $('span[id$="CodigoPostal"]').text();
const address = $('span[id$="Calle"]').text();
const number = $('span[id$="Numero"]').text();
const commune = $('span[id$="Comuna"]').text();
if (!zip) throw new Error('Not found');
resolve({
zip: parseInt(zip, 10),
address: address,
number: number,
commune: commune
});
} catch (err) {
reject(err);
}
});
}
}).on('error', err => reject(err));
});
};
module.exports = getZip;
|
Correct error in theme:: layout path | <?php namespace Anomaly\SelectFieldType\Handler;
use Anomaly\SelectFieldType\SelectFieldType;
use Anomaly\Streams\Platform\Addon\Theme\ThemeCollection;
use Illuminate\Config\Repository;
use Illuminate\Filesystem\Filesystem;
/**
* Class Layouts
*
* @link http://anomaly.is/streams-platform
* @author AnomalyLabs, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
* @package Anomaly\SelectFieldType
*/
class Layouts
{
/**
* Handle the options.
*
* @param SelectFieldType $fieldType
* @param ThemeCollection $themes
* @param Repository $config
* @param Filesystem $files
*/
public function handle(SelectFieldType $fieldType, ThemeCollection $themes, Repository $config, Filesystem $files)
{
$theme = $themes->get($config->get('streams::themes.active.standard'));
$options = $files->files($theme->getPath('resources/views/layouts'));
$fieldType->setOptions(
array_combine(
array_map(
function ($path) use ($theme) {
return 'theme::' . ltrim(
str_replace($theme->getPath('resources/views'), '', $path),
'/'
);
},
$options
),
array_map(
function ($path) use ($theme) {
return ltrim(str_replace($theme->getPath('resources/views/layouts'), '', $path), '/');
},
$options
)
)
);
}
}
| <?php namespace Anomaly\SelectFieldType\Handler;
use Anomaly\SelectFieldType\SelectFieldType;
use Anomaly\Streams\Platform\Addon\Theme\ThemeCollection;
use Illuminate\Config\Repository;
use Illuminate\Filesystem\Filesystem;
/**
* Class Layouts
*
* @link http://anomaly.is/streams-platform
* @author AnomalyLabs, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
* @package Anomaly\SelectFieldType
*/
class Layouts
{
/**
* Handle the options.
*
* @param SelectFieldType $fieldType
* @param ThemeCollection $themes
* @param Repository $config
* @param Filesystem $files
*/
public function handle(SelectFieldType $fieldType, ThemeCollection $themes, Repository $config, Filesystem $files)
{
$theme = $themes->get($config->get('streams::themes.active.standard'));
$options = $files->files($theme->getPath('resources/views/layouts'));
$fieldType->setOptions(
array_combine(
array_map(
function ($path) use ($theme) {
return 'theme::' . ltrim(
str_replace($theme->getPath('resources/views/layouts'), '', $path),
'/'
);
},
$options
),
array_map(
function ($path) use ($theme) {
return ltrim(str_replace($theme->getPath('resources/views/layouts'), '', $path), '/');
},
$options
)
)
);
}
}
|
Allow to dd in cli | <?php
/*
+------------------------------------------------------------------------+
| dd |
+------------------------------------------------------------------------+
| Copyright (c) 2016 Phalcon Team (https://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to [email protected] so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Serghei Iakovlev <[email protected]> |
+------------------------------------------------------------------------+
*/
use Phalcon\Debug\Dump;
if (!function_exists('dd')) {
/**
* Dump the passed variables and end the script.
*
* @param mixed
* @return void
*/
function dd()
{
array_map(function ($x) {
$string = (new Dump(null, true))->variable($x);
echo (PHP_SAPI == 'cli' ? strip_tags($string) : $string);
}, func_get_args());
die(1);
}
}
| <?php
/*
+------------------------------------------------------------------------+
| dd |
+------------------------------------------------------------------------+
| Copyright (c) 2016 Phalcon Team (https://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to [email protected] so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Serghei Iakovlev <[email protected]> |
+------------------------------------------------------------------------+
*/
use Phalcon\Debug\Dump;
if (!function_exists('dd')) {
/**
* Dump the passed variables and end the script.
*
* @param mixed
* @return void
*/
function dd()
{
array_map(function ($x) {
echo (new Dump(null, true))->variable($x);
}, func_get_args());
die(1);
}
}
|
Correct implementation of joinParams() helper | export default {
/**
* Naive polyfill for Object.assign()
* Why I did it? Because even modular lodash adds too much code in final build
* @param {Object} target
* @return {Object}
*/
assign(target) {
for (let i = 1; i < arguments.length; i++) {
let obj = Object(arguments[i]),
keys = Object.keys(obj);
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
if (!obj.hasOwnProperty(key)) {
continue;
}
target[key] = obj[key];
}
}
return target;
},
/**
* Returns URL with query string
* @param {String} url
* @param {Object} params
* @return {String}
*/
joinParams(url, params = null) {
if (!params) {
return url;
}
let queryString = Object.keys(params)
.filter((key) => key && params[key])
.map((key) => {
let value = params[key].toString();
key = encodeURIComponent(key);
value = encodeURIComponent(value);
return `${key}=${value}`;
})
.join('&');
if (!queryString) {
return url;
}
// Trim trailing "?"
url = url.replace(/\?+$/, '');
return url +
(url.indexOf('?') === -1 ? '?' : '&') +
queryString;
}
};
| export default {
/**
* Naive polyfill for Object.assign()
* Why I did it? Because even modular lodash adds too much code in final build
* @param {Object} target
* @return {Object}
*/
assign(target) {
for (let i = 1; i < arguments.length; i++) {
let obj = Object(arguments[i]),
keys = Object.keys(obj);
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
if (!obj.hasOwnProperty(key)) {
continue;
}
target[key] = obj[key];
}
}
return target;
},
/**
* Returns URL with query string
* @param {String} url
* @param {Object} params
* @return {String}
*/
joinParams(url, params = null) {
if (!params) {
return url;
}
let queryString = Object.keys(params).reduce((query, key) => {
let value = params[key];
if (value) {
value = value.toString();
value = encodeURIComponent(value);
key = encodeURIComponent(key);
query.push(`${key}=${value}`);
}
return query;
}, []).join('&');
if (!queryString) {
return url;
}
// Trim trailing "?"
url = url.replace(/\?+$/, '');
return url +
(url.indexOf('?') === -1 ? '?' : '&') +
queryString;
}
};
|
Add user to error messages | package org.signaut.jetty.deploy.providers.couchdb;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.server.handler.ErrorHandler;
/**
* Display the error as a json object
*
*/
class JsonErrorHandler extends ErrorHandler {
@Override
protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
boolean showStacks) throws IOException {
// TODO Auto-generated method stub
final Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
final String user = request.getUserPrincipal()==null?null:request.getUserPrincipal().getName();
if (exception == null) {
message = String.format("{\"status\": %d, \"uri\":\"%s\", \"user\": %s, \"message\": %s}", code,
request.getRequestURI(), jsonStr(user), jsonStr(message));
} else {
message = String.format("{\"status\": %d, \"uri\":\"%s\", \"user\": %s, \"message\": %s, \"exception\": { "
+ "\"exception\": \"%s\", \"message\": %s} }", code,
request.getRequestURI(), jsonStr(user), jsonStr(message),
exception.getClass().getCanonicalName(), jsonStr(exception.getMessage()));
}
writer.write(message);
}
private final String jsonStr(String string) {
return string == null ? null : "\"" + string + "\"";
}
}
| package org.signaut.jetty.deploy.providers.couchdb;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.server.handler.ErrorHandler;
/**
* Display the error as a json object
*
*/
class JsonErrorHandler extends ErrorHandler {
@Override
protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
boolean showStacks) throws IOException {
// TODO Auto-generated method stub
final Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
if (exception == null) {
message = String.format("{\"status\": %d, \"uri\":\"%s\"," + "\"message\": %s}", code,
request.getRequestURI(), jsonStr(message));
} else {
message = String.format("{\"status\": %d, \"uri\":\"%s\"," + "\"message\": %s, " + "\"exception\": { "
+ "\"exception\": \"%s\", \"message\": %s} }", code,
request.getRequestURI(), jsonStr(message),
exception.getClass().getCanonicalName(), jsonStr(exception.getMessage()));
}
writer.write(message);
}
private final String jsonStr(String string) {
return string == null ? null : "\"" + string + "\"";
}
}
|
Rename is_connected method to connected | import uuid
class BaseTransport(object):
"""Base transport class."""
REQUEST_ID_KEY = 'requestId'
REQUEST_ACTION_KEY = 'action'
def __init__(self, data_format_class, data_format_options, handler_class,
handler_options, name):
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
self._name = name
@staticmethod
def _uuid():
return str(uuid.uuid1())
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode(self, obj):
return self._data_format.encode(obj)
def _decode(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def name(self):
return self._name
def connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, action, request, **params):
raise NotImplementedError
def request(self, action, request, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
class BaseTransportException(Exception):
"""Base transport exception."""
pass
| import uuid
class BaseTransport(object):
"""Base transport class."""
REQUEST_ID_KEY = 'requestId'
REQUEST_ACTION_KEY = 'action'
def __init__(self, data_format_class, data_format_options, handler_class,
handler_options, name):
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
self._name = name
@staticmethod
def _uuid():
return str(uuid.uuid1())
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode(self, obj):
return self._data_format.encode(obj)
def _decode(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def name(self):
return self._name
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, action, request, **params):
raise NotImplementedError
def request(self, action, request, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
class BaseTransportException(Exception):
"""Base transport exception."""
pass
|
Set type option to nodebuffer if in node environment. | var write = require('./write'),
geojson = require('./geojson'),
prj = require('./prj'),
JSZip = require('jszip');
module.exports = function(gj, options) {
var zip = new JSZip(),
layers = zip.folder(options && options.folder ? options.folder : 'layers');
[geojson.point(gj), geojson.line(gj), geojson.polygon(gj)]
.forEach(function(l) {
if (l.geometries.length) {
write(
// field definitions
l.properties,
// geometry type
l.type,
// geometries
l.geometries,
function(err, files) {
var fileName = options && options.types[l.type.toLowerCase()] ? options.types[l.type.toLowerCase()] : l.type;
layers.file(fileName + '.shp', files.shp.buffer, { binary: true });
layers.file(fileName + '.shx', files.shx.buffer, { binary: true });
layers.file(fileName + '.dbf', files.dbf.buffer, { binary: true });
layers.file(fileName + '.prj', prj);
});
}
});
var generateOptions = { compression:'STORE' };
if (typeof window === 'undefined') {
generateOptions.type = 'nodebuffer';
}
return zip.generate(generateOptions);
};
| var write = require('./write'),
geojson = require('./geojson'),
prj = require('./prj'),
JSZip = require('jszip');
module.exports = function(gj, options) {
var zip = new JSZip(),
layers = zip.folder(options && options.folder ? options.folder : 'layers');
[geojson.point(gj), geojson.line(gj), geojson.polygon(gj)]
.forEach(function(l) {
if (l.geometries.length) {
write(
// field definitions
l.properties,
// geometry type
l.type,
// geometries
l.geometries,
function(err, files) {
var fileName = options && options.types[l.type.toLowerCase()] ? options.types[l.type.toLowerCase()] : l.type;
layers.file(fileName + '.shp', files.shp.buffer, { binary: true });
layers.file(fileName + '.shx', files.shx.buffer, { binary: true });
layers.file(fileName + '.dbf', files.dbf.buffer, { binary: true });
layers.file(fileName + '.prj', prj);
});
}
});
return zip.generate({compression:'STORE'});
};
|
Add _isMounted check for setState | // @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { autocomplete } from 'app/actions/SearchActions';
import { debounce } from 'lodash';
type Props = {
filter: Array<string>
};
function withAutocomplete(WrappedComponent: any) {
return class extends Component {
state = {
searching: false,
result: [],
_isMounted: false
};
componentDidMount() {
this.setState({
_isMounted: true
});
}
componentWillUnmount() {
this.setState({
_isMounted: false
});
}
handleSearch = (query: string, filter): void => {
this.setState({
searching: true
});
this.props
.autocomplete(query, filter)
.then(result => {
if (this.state._isMounted) {
this.setState({
result,
searching: false
});
}
})
.catch(() => {
if (this.state._isMounted) {
this.setState({ searching: false });
}
});
};
render() {
const { filter, ...restProps }: Props = this.props;
return (
<WrappedComponent
{...restProps}
options={this.state.result}
onSearch={debounce(query => this.handleSearch(query, filter), 300)}
fetching={this.state.searching}
/>
);
}
};
}
const mapDispatchToProps = {
autocomplete
};
export default (WrappedComponent: any) =>
connect(null, mapDispatchToProps)(withAutocomplete(WrappedComponent));
| // @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { autocomplete } from 'app/actions/SearchActions';
import { debounce } from 'lodash';
type Props = {
filter: Array<string>
};
function withAutocomplete(WrappedComponent: any) {
return class extends Component {
state = {
searching: false,
result: []
};
handleSearch = (query: string, filter): void => {
this.setState({
searching: true
});
this.props
.autocomplete(query, filter)
.then(result =>
this.setState({
result,
searching: false
})
)
.catch(() => this.setState({ searching: false }));
};
render() {
const { filter, ...restProps }: Props = this.props;
return (
<WrappedComponent
{...restProps}
options={this.state.result}
onSearch={debounce(query => this.handleSearch(query, filter), 300)}
fetching={this.state.searching}
/>
);
}
};
}
const mapDispatchToProps = {
autocomplete
};
export default (WrappedComponent: any) =>
connect(null, mapDispatchToProps)(withAutocomplete(WrappedComponent));
|
Fix dot reporter not resetting the current line length | <?php
namespace pho\Reporter;
use pho\Console\Console;
use pho\Suite\Suite;
use pho\Runnable\Spec;
class DotReporter extends AbstractReporter implements ReporterInterface
{
private static $maxPerLine = 60;
private $lineLength;
/**
* Creates a SpecReporter object, used to render a nested view of test
* suites and specs.
*
* @param Console $console A console for writing output
*/
public function __construct(Console $console)
{
parent::__construct($console);
$this->lineLength = 0;
}
/**
* Ran before an individual spec.
*
* @param Spec $spec The spec before which to run this method
*/
public function beforeSpec(Spec $spec)
{
$this->specCount += 1;
if ($this->lineLength == self::$maxPerLine) {
$this->console->writeLn('');
$this->lineLength = 0;
}
}
/**
* Ran after an individual spec.
*
* @param Spec $spec The spec after which to run this method
*/
public function afterSpec(Spec $spec)
{
$this->lineLength += 1;
if (!$spec->passed()) {
$this->failedSpecs[] = $spec;
$failure = $this->formatter->red('F');
$this->console->write($failure);
} else {
$this->console->write('.');
}
}
}
| <?php
namespace pho\Reporter;
use pho\Console\Console;
use pho\Suite\Suite;
use pho\Runnable\Spec;
class DotReporter extends AbstractReporter implements ReporterInterface
{
private static $maxPerLine = 60;
private $lineLength;
/**
* Creates a SpecReporter object, used to render a nested view of test
* suites and specs.
*
* @param Console $console A console for writing output
*/
public function __construct(Console $console)
{
parent::__construct($console);
$this->lineLength = 0;
}
/**
* Ran before an individual spec.
*
* @param Spec $spec The spec before which to run this method
*/
public function beforeSpec(Spec $spec)
{
$this->specCount += 1;
if ($this->lineLength == self::$maxPerLine) {
$this->console->writeLn('');
}
}
/**
* Ran after an individual spec.
*
* @param Spec $spec The spec after which to run this method
*/
public function afterSpec(Spec $spec)
{
$this->lineLength += 1;
if (!$spec->passed()) {
$this->failedSpecs[] = $spec;
$failure = $this->formatter->red('F');
$this->console->write($failure);
} else {
$this->console->write('.');
}
}
}
|
CRM-4654: Modify standard step to skip extended merge field | <?php
namespace Oro\Bundle\EntityMergeBundle\Model\Step;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Event\FieldDataEvent;
use Oro\Bundle\EntityMergeBundle\MergeEvents;
use Oro\Bundle\EntityMergeBundle\Model\Strategy\StrategyInterface;
class MergeFieldsStep implements DependentMergeStepInterface
{
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @param StrategyInterface $strategy
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(StrategyInterface $strategy, EventDispatcherInterface $eventDispatcher)
{
$this->strategy = $strategy;
$this->eventDispatcher = $eventDispatcher;
}
/**
* Merge fields
*
* @param EntityData $data
*/
public function run(EntityData $data)
{
foreach ($data->getFields() as $field) {
$fieldMetadata = $field->getMetadata();
if ($fieldMetadata->has('is_virtual') && $fieldMetadata->get('is_virtual') === true) {
continue;
}
$this->eventDispatcher->dispatch(MergeEvents::BEFORE_MERGE_FIELD, new FieldDataEvent($field));
$this->strategy->merge($field);
$this->eventDispatcher->dispatch(MergeEvents::AFTER_MERGE_FIELD, new FieldDataEvent($field));
}
}
/**
* {@inheritdoc}
*/
public function getDependentSteps()
{
return array('Oro\\Bundle\\EntityMergeBundle\\Model\\Step\\ValidateStep');
}
}
| <?php
namespace Oro\Bundle\EntityMergeBundle\Model\Step;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Event\FieldDataEvent;
use Oro\Bundle\EntityMergeBundle\MergeEvents;
use Oro\Bundle\EntityMergeBundle\Model\Strategy\StrategyInterface;
class MergeFieldsStep implements DependentMergeStepInterface
{
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* @param StrategyInterface $strategy
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(StrategyInterface $strategy, EventDispatcherInterface $eventDispatcher)
{
$this->strategy = $strategy;
$this->eventDispatcher = $eventDispatcher;
}
/**
* Merge fields
*
* @param EntityData $data
*/
public function run(EntityData $data)
{
foreach ($data->getFields() as $field) {
$this->eventDispatcher->dispatch(MergeEvents::BEFORE_MERGE_FIELD, new FieldDataEvent($field));
$this->strategy->merge($field);
$this->eventDispatcher->dispatch(MergeEvents::AFTER_MERGE_FIELD, new FieldDataEvent($field));
}
}
/**
* {@inheritdoc}
*/
public function getDependentSteps()
{
return array('Oro\\Bundle\\EntityMergeBundle\\Model\\Step\\ValidateStep');
}
}
|
Reformat posts in seed data | import moment from 'moment';
import { Posts } from '../../api/collections';
const seedPosts = () => {
const post = Posts.findOne();
if (!post) {
for (let i = 0; i < 50; i++) {
Posts.insert({
userId: 'QBgyG7MsqswQmvm7J',
username: 'evancorl',
createdAt: moment().utc().toDate(),
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Video',
source: 'YouTube',
thumbnail: '/images/feeds.jpg',
url: 'https://www.meteor.com/',
},
likeCount: 14,
commentCount: 3,
});
Posts.insert({
userId: 'QBgyG7MsqswQmvm7J',
username: 'evancorl',
createdAt: moment().utc().toDate(),
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Photo',
thumbnail: '/images/feeds-2.jpg',
url: 'https://www.meteor.com/',
},
likeCount: 14,
commentCount: 3,
});
}
}
};
export default seedPosts;
| import moment from 'moment';
import { Posts } from '../../api/collections';
const seedPosts = () => {
const postCount = Posts.find().count();
if (postCount === 0) {
for (let i = 0; i < 50; i++) {
Posts.insert({
createdAt: moment().utc().toDate(),
userId: 'QBgyG7MsqswQmvm7J',
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Video',
source: 'Facebook',
thumb: '/images/feeds.jpg',
url: 'https://www.meteor.com/',
},
totalViews: 30,
totalLikes: 14,
totalShares: 3,
totalComments: 3,
});
Posts.insert({
createdAt: moment().utc().toDate(),
userId: 'QBgyG7MsqswQmvm7J',
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Photo',
source: 'Instagram',
thumb: '/images/feeds-2.jpg',
url: 'https://www.meteor.com/',
},
totalViews: 30,
totalLikes: 14,
totalShares: 3,
totalComments: 3,
});
}
}
};
export default seedPosts;
|
Fix doc string injection of deprecated wrapper | import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
"""
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use ``%s`` instead.' % self.alt_func
msg = 'Call to deprecated function ``%s``.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = '**Deprecated function**.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n ' + wrapped.__doc__
return wrapped
| import warnings
import functools
__all__ = ['deprecated']
class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated function: 'warn' = warn user that
function is deprecated; 'raise' = raise error.
"""
def __init__(self, alt_func=None, behavior='warn'):
self.alt_func = alt_func
self.behavior = behavior
def __call__(self, func):
alt_msg = ''
if self.alt_func is not None:
alt_msg = ' Use `%s` instead.' % self.alt_func
msg = 'Call to deprecated function `%s`.' % func.__name__
msg += alt_msg
@functools.wraps(func)
def wrapped(*args, **kwargs):
if self.behavior == 'warn':
warnings.warn_explicit(msg,
category=DeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise DeprecationWarning(msg)
return func(*args, **kwargs)
# modify doc string to display deprecation warning
doc = '**Deprecated function**.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n' + wrapped.__doc__
return wrapped
|
Fix import now that this is renamed. | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
logger.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
logger.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
logger.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
logger.info("Ending job: %s %s" % (script, args))
| import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
log.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
log.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
log.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
log.info("Ending job: %s %s" % (script, args))
|
Reformat tests to use spaces not tabs | /*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.rendering;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FontColorTest {
@Test
public void testResetColor() {
char resetColor = 0xF000;
assertTrue(FontColor.isValid(resetColor));
}
@Test
public void testFirstColor() {
char firstColor = 0xE000;
assertTrue(FontColor.isValid(firstColor));
}
@Test
public void testLastColor() {
char lastColor = 0xEFFF;
assertTrue(FontColor.isValid(lastColor));
}
@Test
public void testBetweenColor() {
char betweenColor = 0xEB8F;
assertTrue(FontColor.isValid(betweenColor));
}
@Test
public void testInvalidColor() {
char invalidColor = 0xA10F;
assertFalse(FontColor.isValid(invalidColor));
}
}
| /*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.rendering;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FontColorTest {
@Test
public void testResetColor() {
char resetColor = 0xF000;
assertTrue(FontColor.isValid(resetColor));
}
@Test
public void testFirstColor() {
char firstColor = 0xE000;
assertTrue(FontColor.isValid(firstColor));
}
@Test
public void testLastColor() {
char lastColor = 0xEFFF;
assertTrue(FontColor.isValid(lastColor));
}
@Test
public void testBetweenColor() {
char betweenColor = 0xEB8F;
assertTrue(FontColor.isValid(betweenColor));
}
@Test
public void testInvalidColor() {
char invalidColor = 0xA10F;
assertFalse(FontColor.isValid(invalidColor));
}
}
|
Make test output show natural sw. | package cz.crcs.ectester.reader.output;
import cz.crcs.ectester.common.util.CardUtil;
import cz.crcs.ectester.reader.response.Response;
import java.io.PrintStream;
/**
* @author Jan Jancar [email protected]
*/
public class ResponseWriter {
private PrintStream output;
public ResponseWriter(PrintStream output) {
this.output = output;
}
public String responseSuffix(Response r) {
StringBuilder suffix = new StringBuilder();
for (int j = 0; j < r.getNumSW(); ++j) {
short sw = r.getSW(j);
if (sw != 0) {
suffix.append(" ").append(CardUtil.getSWString(sw));
}
}
if (suffix.length() == 0) {
suffix.append(" [").append(CardUtil.getSW(r.getNaturalSW())).append(String.format(" 0x%04x", r.getNaturalSW())).append("]");
}
return String.format("%4d ms ┃ %s", r.getDuration() / 1000000, suffix);
}
public String responseString(Response r) {
String out = "";
out += String.format("%-70s", r.getDescription()) + " ┃ ";
out += responseSuffix(r);
return out;
}
public void outputResponse(Response r) {
output.println(responseString(r));
output.flush();
}
}
| package cz.crcs.ectester.reader.output;
import cz.crcs.ectester.common.util.CardUtil;
import cz.crcs.ectester.reader.response.Response;
import java.io.PrintStream;
/**
* @author Jan Jancar [email protected]
*/
public class ResponseWriter {
private PrintStream output;
public ResponseWriter(PrintStream output) {
this.output = output;
}
public String responseSuffix(Response r) {
StringBuilder suffix = new StringBuilder();
for (int j = 0; j < r.getNumSW(); ++j) {
short sw = r.getSW(j);
if (sw != 0) {
suffix.append(" ").append(CardUtil.getSWString(sw));
}
}
if (suffix.length() == 0) {
suffix.append(" [").append(CardUtil.getSW(r.getNaturalSW())).append("]");
}
return String.format("%4d ms ┃ %s", r.getDuration() / 1000000, suffix);
}
public String responseString(Response r) {
String out = "";
out += String.format("%-70s", r.getDescription()) + " ┃ ";
out += responseSuffix(r);
return out;
}
public void outputResponse(Response r) {
output.println(responseString(r));
output.flush();
}
}
|
Fix undeclared variable error and prevent event default | (function (){
var GOVUKDATEFIELDS = function (){
var $allDateGroupInstances = $(".form-date"),
init = function (){
$allDateGroupInstances.each(function (){
var $currentGroup = $(this);
var $inputs = $currentGroup.find('input');
var $todayButton = $currentGroup.find('a');
//Show Today Button if js is enabled
$todayButton.addClass('js-enabled');
$todayButton.on('click', function(event) {
//Set date and remove inputs from natural tab order
event.preventDefault();
setTodayDate($currentGroup, $inputs, $todayButton);
$inputs.attr('tabIndex', -1);
}).on('focus', function(){
$inputs.attr('tabIndex', 0);
})
})
},
setTodayDate = function($currentGroup, $inputs, $todayButton){
//Cache the input fields
var $dateField = $inputs.eq(0);
var $monthField = $inputs.eq(1);
var $yearField = $inputs.eq(2);
//Create and return todays date
var d = new Date();
var day = d.getUTCDate();
var month = d.getUTCMonth() + 1;
var year = d.getUTCFullYear();
if(month < 10 ){
month = '0' + month;
}
//Set the input fields
$dateField.val(day);
$monthField.val(month);
$yearField.val(year);
};
return {
init : function(){
init();
}
}
}();
GOVUKDATEFIELDS.init();
})();
| (function (){
var GOVUKDATEFIELDS = function (){
var $allDateGroupInstances = $(".form-date"),
init = function (){
$allDateGroupInstances.each(function (){
var $currentGroup = $(this);
var $inputs = $currentGroup.find('input');
var $todayButton = $currentGroup.find('a');
//Show Today Button if js is enabled
$todayButton.addClass('js-enabled');
$todayButton.on('click', function(e) {
//Set date and remove inputs from natural tab order
event.preventDefault();
setTodayDate($currentGroup, $inputs, $todayButton);
$inputs.attr('tabIndex', -1);
}).on('focus', function(){
$inputs.attr('tabIndex', 0);
})
})
},
setTodayDate = function($currentGroup, $inputs, $todayButton){
//Cache the input fields
var $dateField = $inputs.eq(0);
var $monthField = $inputs.eq(1);
var $yearField = $inputs.eq(2);
//Create and return todays date
var d = new Date();
var day = d.getUTCDate();
var month = d.getUTCMonth() + 1;
var year = d.getUTCFullYear();
if(month < 10 ){
month = '0' + month;
}
//Set the input fields
$dateField.val(day);
$monthField.val(month);
$yearField.val(year);
};
return {
init : function(){
init();
}
}
}();
GOVUKDATEFIELDS.init();
})();
|
Create test case for default currency | <?php
namespace Flagbit\Bundle\CurrencyBundle\Tests;
use Flagbit\Bundle\CurrencyBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
protected function process($config)
{
$processor = new Processor();
return $processor->processConfiguration(new Configuration(), $config);
}
public function provideValidCurrency()
{
return array(
array('EUR'),
array('USD'),
array('CHF'),
);
}
/**
* Test Default Currency to prevent BC breaks
*/
public function testProcessedDefaultCurrency()
{
$config = array(array());
$config = $this->process($config);
$this->assertEquals('EUR', $config['default_currency']);
}
/**
* @dataProvider provideValidCurrency
*/
public function testValidDefaultCurrency($currency)
{
$config = array(
array(
'default_currency' => $currency,
)
);
$config = $this->process($config);
$this->assertEquals($currency, $config['default_currency']);
}
public function provideInvalidCurrency()
{
return array(
array('foobar'),
array('eur'),
);
}
/**
* @dataProvider provideInvalidCurrency
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidDefaultCurrency($currency)
{
$config = array(
array(
'default_currency' => $currency,
)
);
$this->process($config);
}
}
| <?php
namespace Flagbit\Bundle\CurrencyBundle\Tests;
use Flagbit\Bundle\CurrencyBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
protected function process($config)
{
$processor = new Processor();
return $processor->processConfiguration(new Configuration(), $config);
}
public function provideValidCurrency()
{
return array(
array('EUR'),
array('USD'),
array('CHF'),
);
}
/**
* @dataProvider provideValidCurrency
*/
public function testValidDefaultCurrency($currency)
{
$config = array(
array(
'default_currency' => $currency,
)
);
$config = $this->process($config);
$this->assertEquals($currency, $config['default_currency']);
}
public function provideInvalidCurrency()
{
return array(
array('foobar'),
array('eur'),
);
}
/**
* @dataProvider provideInvalidCurrency
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testInvalidDefaultCurrency($currency)
{
$config = array(
array(
'default_currency' => $currency,
)
);
$this->process($config);
}
}
|
Improve classifiers, version and url | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-onmydesk',
version='0.1.0',
packages=find_packages(exclude=('tests*',)),
include_package_data=True,
license='MIT License',
description='A simple Django app to build reports.',
long_description=README,
url='https://github.com/knowledge4life/django-onmydesk/',
author='Alisson R. Perez',
author_email='[email protected]',
install_requires=[
'XlsxWriter==0.8.3', # Used by XLSXOutput
'filelock==2.0.6',
'awesome-slugify==1.6.5',
],
keywords=['report', 'reporting', 'django'],
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Office/Business :: Financial :: Spreadsheet',
],
)
| import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-onmydesk',
version='0.1',
packages=find_packages(exclude=('tests*',)),
include_package_data=True,
license='MIT License',
description='A simple Django app to build reports.',
long_description=README,
url='https://github.com/knowledge/knowledge4life/',
author='Alisson R. Perez',
author_email='[email protected]',
install_requires=[
'XlsxWriter==0.8.3', # Used by XLSXOutput
'filelock==2.0.6',
'awesome-slugify==1.6.5',
],
keywords=['report', 'reporting', 'django'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Join two lines in one | # encoding: utf-8
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
# Transform secs into ms
time = float(value) * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
| # encoding: utf-8
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
time = float(value)
# Transform secs into ms
time = value * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
|
Return correct value, remove unused props | import React, { Component, PropTypes } from 'react';
import DayPicker from 'react-day-picker';
import moment from 'moment';
import s from './DatePicker.css';
const weekdaysShort = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const weekdaysLong = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
const localeUtils = {
formatMonthTitle: date => moment(date).format('MMMM YYYY'),
formatWeekdayShort: dayIndex => weekdaysShort[dayIndex],
formatWeekdayLong: dayIndex => weekdaysLong[dayIndex],
getFirstDayOfWeek: () => 1,
};
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.renderDay = this.renderDay.bind(this);
this.onDayClick = this.onDayClick.bind(this);
}
renderDay(day) {
return (
<span>{day.getDate()}</span>
);
}
onDayClick(event, day) {
this.props.onChange(day);
}
render() {
return (
<div className={s.root}>
<DayPicker
locale="en-gb"
enableOutsideDays
localeUtils={localeUtils}
renderDay={this.renderDay}
onDayClick={this.onDayClick}
{...this.props}
/>
</div>
);
}
}
DatePicker.propTypes = {
onChange: PropTypes.func.isRequired,
};
| import React, { Component, PropTypes } from 'react';
import DayPicker from 'react-day-picker';
import moment from 'moment';
import s from './DatePicker.css';
const weekdaysShort = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const weekdaysLong = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
const localeUtils = {
formatMonthTitle: date => moment(date).format('MMMM YYYY'),
formatWeekdayShort: dayIndex => weekdaysShort[dayIndex],
formatWeekdayLong: dayIndex => weekdaysLong[dayIndex],
getFirstDayOfWeek: () => 1,
};
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.renderDay = this.renderDay.bind(this);
}
renderDay(day) {
return (
<span>{day.getDate()}</span>
);
}
render() {
return (
<div className={s.root}>
<DayPicker
locale="en-gb"
enableOutsideDays
localeUtils={localeUtils}
renderDay={this.renderDay}
onDayClick={this.props.onChange}
{...this.props}
/>
</div>
);
}
}
DatePicker.propTypes = {
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
onChange: PropTypes.func.isRequired,
};
|
Fix bug in sentiment calculation
Signed-off-by: Itai Koren <[email protected]> | // Include The 'require.async' Module
require("require.async")(require);
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize (input) {
return input
.replace(/[^a-zA-Z ]+/g, "")
.replace("/ {2,}/", " ")
.toLowerCase()
.split(" ");
}
/**
* Performs sentiment analysis on the provided input "term".
*
* @param {String} Input term
*
* @return {Object}
*/
module.exports = function (term, callback) {
// Include the AFINN Dictionary JSON asynchronously
require.async("./AFINN.json", function(afinn) {
// Split line term to letters only words array
var words = tokenize(term || "");
var score = 0;
var rate;
var i = 0;
function calculate(word) {
// Get the word rate from the AFINN dictionary
rate = afinn[word];
if (rate) {
// Add current word rate to the final calculated sentiment score
score += rate;
}
// Defer next turn execution (Etheration)
setImmediate(function() {
// Use callback for completion
if (i === (words.length - 1)) {
callback(null, score);
}
else {
// Invoke next turn
calculate(words[++i]);
}
});
}
// Start calculating
calculate(words[i]);
});
};
| // Include The 'require.async' Module
require("require.async")(require);
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize (input) {
return input
.replace(/[^a-zA-Z ]+/g, "")
.replace("/ {2,}/", " ")
.toLowerCase()
.split(" ");
}
/**
* Performs sentiment analysis on the provided input "term".
*
* @param {String} Input term
*
* @return {Object}
*/
module.exports = function (term, callback) {
// Include the AFINN Dictionary JSON asynchronously
require.async("./AFINN.json", function(afinn) {
// Split line term to letters only words array
var words = tokenize(term || "");
var score = 0;
var rate;
var i = 0;
function calculate(word) {
// Get the word rate from the AFINN dictionary
rate = afinn[word];
if (rate) {
// Add current word rate to the final calculated sentiment score
score += rate;
}
// Defer next turn execution (Etheration)
setImmediate(function() {
// Use callback for completion
if (i === (words.length - 1)) {
callback(null, score);
}
else {
// Invoke next turn
calculate(words[++i]);
}
});
}
// Start calculating
calculate(i);
});
};
|
Refactor episode details JavaScript functions. | var Cloudy = {
isEpisodePage: function() {
return $("#audioplayer").length == 1;
},
getEpisodeDetails: function() {
var episodeTitle = $(".titlestack .title").text();
var showTitle = $(".titlestack .caption2").text();
return {
show_title: showTitle,
episode_title: episodeTitle
};
},
installPlaybackHandlers: function() {
var player = $("#audioplayer")[0];
player.addEventListener("play", Cloudy.playerDidPlay);
player.addEventListener("pause", Cloudy.playerDidPause);
},
playerDidPlay: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"is_playing": true
});
},
playerDidPause: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"is_playing": false
});
},
togglePlaybackState: function() {
var player = $("#audioplayer")[0];
player.paused ? player.play() : player.pause();
},
installSpaceHandler: function() {
$(window).keypress(function(event) {
if (event.keyCode == 32) {
event.preventDefault();
Cloudy.togglePlaybackState();
}
});
}
};
$(function() {
if (Cloudy.isEpisodePage()) {
Cloudy.installPlaybackHandlers();
Cloudy.installSpaceHandler();
webkit.messageHandlers.episodeHandler.postMessage(Cloudy.getEpisodeDetails());
}
else {
webkit.messageHandlers.episodeHandler.postMessage(null);
}
});
| var Cloudy = {
isEpisodePage: function() {
return $("#audioplayer").length == 1;
},
sendEpisodeToCloudy: function() {
var episodeTitle = $(".titlestack .title").text();
var showTitle = $(".titlestack .caption2").text();
var details = {
"show_title": showTitle,
"episode_title": episodeTitle
};
webkit.messageHandlers.episodeHandler.postMessage(details);
},
installPlaybackHandlers: function() {
var player = $("#audioplayer")[0];
player.addEventListener("play", Cloudy.playerDidPlay);
player.addEventListener("pause", Cloudy.playerDidPause);
},
playerDidPlay: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"is_playing": true
});
},
playerDidPause: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"is_playing": false
});
},
togglePlaybackState: function() {
var player = $("#audioplayer")[0];
player.paused ? player.play() : player.pause();
},
installSpaceHandler: function() {
$(window).keypress(function(event) {
if (event.keyCode == 32) {
event.preventDefault();
Cloudy.togglePlaybackState();
}
});
}
};
$(function() {
if (Cloudy.isEpisodePage()) {
Cloudy.installPlaybackHandlers();
Cloudy.installSpaceHandler();
Cloudy.sendEpisodeToCloudy();
}
else {
webkit.messageHandlers.episodeHandler.postMessage(null);
}
});
|
:bug: Fix Punchcard JS and images compilation | const gulp = require('gulp');
const config = require('config');
const runner = require('punchcard-runner');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');
const path = require('path');
const options = runner.config({
application: {
library: {
src: [
'lib',
'config',
'content-types',
'input-plugins'
],
}
},
tasks: {
nodemon: {
extension: 'js html yml'
},
build: {
clean: [
'clean:public',
],
assets: [
'sass',
'imagemin',
'js',
'punchcard:js',
'punchcard:images'
],
}
},
server: {
port: config.env.port,
host: config.env.host
}
});
runner(gulp, options);
gulp.task('punchcard:js', () => {
return gulp.src('node_modules/punchcard-cms/src/js/**/*.js')
.pipe(concat('punchcard.js'))
.pipe(uglify())
.pipe(gulp.dest(path.join(options.assets._folders.public, options.assets.js.dest)));
});
gulp.task('punchcard:images', () => {
return gulp.src('node_modules/punchcard-cms/src/images/**/*')
.pipe(imagemin(options.tasks.images.build.options))
.pipe(gulp.dest(path.join(options.assets._folders.public, options.assets.images.dest)));
});
| const gulp = require('gulp');
const config = require('config');
const runner = require('punchcard-runner');
const options = runner.config({
application: {
library: {
src: [
'lib',
'config',
'content-types',
'input-plugins'
],
}
},
tasks: {
nodemon: {
extension: 'js html yml'
},
build: {
clean: [
'clean:public',
],
assets: [
'sass',
'imagemin',
'js',
'punchcard:js',
'punchcard:images'
],
}
},
server: {
port: config.env.port,
host: config.env.host
}
});
runner(gulp, options);
gulp.task('punchcard:js', () => {
return gulp.src('node_modules/punchcard-cms/src/js/**/*.js')
.pipe(concat('punchcard.js'))
.pipe(uglify())
.pipe(gulp.dest(path.join(options.assets._folders.public, options.assets.js.dest)));
});
gulp.task('punchcard:images', () => {
return gulp.src('node_modules/punchcard-cms/src/images/**/*')
.pipe(imagemin(options.tasks.images.build.options))
.pipe(gulp.dest(path.join(options.assets._folders.public, options.assets.images.dest)));
});
|
Fix bug wrong pageId in showAction | <?php
namespace Akhann\StaticPageBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
abstract class DefaultController extends Controller
{
abstract public function getIndexTemplate();
abstract public function getShowTemplateNamespace();
public function indexAction()
{
return $this->render($this->getIndexTemplate());
}
public function showAction($pageId)
{
$template = $this->getShowTemplate($pageId);
$templating = $this->get('templating');
if (!$templating->exists($template))
{
throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
}
return $this->render($template);
}
public function subShowAction($parentPageId, $pageId)
{
$template = $this->getShowTemplate($parentPageId, $pageId);
$templating = $this->get('templating');
if (!$templating->exists($template))
{
throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
}
return $this->render($template);
}
protected function getShowTemplate($parentPageId, $pageId=null)
{
if (is_null($pageId)) {
$pageId = $parentPageId;
}
else {
$pageId = sprintf('%s_%s', $parentPageId, $pageId);
}
return sprintf('%s:%s.html.twig', $this->getShowTemplateNamespace(), $pageId);
}
}
| <?php
namespace Akhann\StaticPageBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
abstract class DefaultController extends Controller
{
abstract public function getIndexTemplate();
abstract public function getShowTemplateNamespace();
public function indexAction()
{
return $this->render($this->getIndexTemplate());
}
public function showAction($pageId)
{
$template = $this->getShowTemplate($pageId);
$templating = $this->get('templating');
if (!$templating->exists($template))
{
throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
}
return $this->render($template);
}
public function subShowAction($parentPageId, $pageId)
{
$template = $this->getShowTemplate($parentPageId, $pageId);
$templating = $this->get('templating');
if (!$templating->exists($template))
{
throw $this->createNotFoundException(sprintf('Page not found. Create template %s', $template));
}
return $this->render($template);
}
protected function getShowTemplate($parentPageId, $pageId=null)
{
if (is_null($pageId)) {
$pageId = $parentPageId;
}
$pageId = sprintf('%s_%s', $parentPageId, $pageId);
return sprintf('%s:%s.html.twig', $this->getShowTemplateNamespace(), $pageId);
}
}
|
Prepare for making alpha release | from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.0.1a"
setup(name='backlash',
version=version,
description="Standalone WebOb port of the Werkzeug Debugger with Python3 support meant to replace WebError in future TurboGears2",
long_description=README,
classifiers=['Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: WSGI'],
keywords='wsgi',
author='Alessandro Molina',
author_email='[email protected]',
url='',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
"WebOb"
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import sys, os
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
except IOError:
README = ''
version = "0.0.1"
setup(name='backlash',
version=version,
description="standalone version of the Werkzeug Debugger based on WebOb",
long_description=README,
classifiers=['Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware',
'Topic :: Internet :: WWW/HTTP :: WSGI'],
keywords='wsgi',
author='Alessandro Molina',
author_email='[email protected]',
url='',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
"WebOb"
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Hide source input from create dialog | import React from 'react';
import { injectIntl } from 'react-intl';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import CreateMediaInput from './CreateMediaInput';
import globalStrings from '../../globalStrings';
class CreateMediaDialog extends React.Component {
handleSubmit = () => {
const submitButton = document.getElementById('create-media-submit');
if (submitButton) {
submitButton.click();
}
};
render() {
return (
<Dialog open={this.props.open} fullWidth>
<DialogTitle>{this.props.title}</DialogTitle>
<DialogContent>
<CreateMediaInput
message={this.props.message}
onSubmit={this.props.onSubmit}
submitHidden
noSource
/>
</DialogContent>
<DialogActions>
<Button id="create-media-dialog__dismiss-button" onClick={this.props.onDismiss}>
{this.props.intl.formatMessage(globalStrings.cancel)}
</Button>
<Button id="create-media-dialog__submit-button" onClick={this.handleSubmit} color="primary">
{this.props.intl.formatMessage(globalStrings.submit)}
</Button>
</DialogActions>
</Dialog>
);
}
}
export default injectIntl(CreateMediaDialog);
| import React from 'react';
import { injectIntl } from 'react-intl';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import CreateMediaInput from './CreateMediaInput';
import globalStrings from '../../globalStrings';
class CreateMediaDialog extends React.Component {
handleSubmit = () => {
const submitButton = document.getElementById('create-media-submit');
if (submitButton) {
submitButton.click();
}
};
render() {
return (
<Dialog open={this.props.open} fullWidth>
<DialogTitle>{this.props.title}</DialogTitle>
<DialogContent>
<CreateMediaInput
message={this.props.message}
onSubmit={this.props.onSubmit}
submitHidden
/>
</DialogContent>
<DialogActions>
<Button id="create-media-dialog__dismiss-button" onClick={this.props.onDismiss}>
{this.props.intl.formatMessage(globalStrings.cancel)}
</Button>
<Button id="create-media-dialog__submit-button" onClick={this.handleSubmit} color="primary">
{this.props.intl.formatMessage(globalStrings.submit)}
</Button>
</DialogActions>
</Dialog>
);
}
}
export default injectIntl(CreateMediaDialog);
|
Add HeaderArea into HeaderRow storybook subcomponents | import React from 'react';
import HeaderRow, { HeaderArea } from '@ichef/gypcrete/src/HeaderRow';
import Button from '@ichef/gypcrete/src/Button';
import TextLabel from '@ichef/gypcrete/src/TextLabel';
import TextEllipsis from '@ichef/gypcrete/src/TextEllipsis';
import DebugBox from 'utils/DebugBox';
export default {
title: '@ichef/gypcrete|HeaderRow',
component: HeaderRow,
subcomponents: {
HeaderArea,
},
};
export function BasicUsage() {
const leftBtn = <Button icon="prev" basic="Back" />;
const rightBtn = <Button align="reverse" icon="row-padding" basic="Save" />;
const centerLabel = (
<TextLabel
align="center"
basic={
<TextEllipsis>Lorem ipsum a slightly longer title</TextEllipsis>
} />
);
return (
<DebugBox>
<HeaderRow
left={leftBtn}
center={centerLabel}
right={rightBtn} />
</DebugBox>
);
}
export function OptionalArea() {
const rightBtn = <Button align="reverse" icon="row-padding" basic="Save" />;
const centerLabel = <TextLabel basic="Header Title" />;
return (
<DebugBox>
<HeaderRow
left={false}
center={centerLabel}
right={rightBtn} />
</DebugBox>
);
}
OptionalArea.story = {
parameters: {
docs: {
storyDescription: 'Remove an area from DOM by explictly setting it to false.',
},
},
};
| import React from 'react';
import HeaderRow from '@ichef/gypcrete/src/HeaderRow';
import Button from '@ichef/gypcrete/src/Button';
import TextLabel from '@ichef/gypcrete/src/TextLabel';
import TextEllipsis from '@ichef/gypcrete/src/TextEllipsis';
import DebugBox from 'utils/DebugBox';
export default {
title: '@ichef/gypcrete|HeaderRow',
component: HeaderRow,
};
export function BasicUsage() {
const leftBtn = <Button icon="prev" basic="Back" />;
const rightBtn = <Button align="reverse" icon="row-padding" basic="Save" />;
const centerLabel = (
<TextLabel
align="center"
basic={
<TextEllipsis>Lorem ipsum a slightly longer title</TextEllipsis>
} />
);
return (
<DebugBox>
<HeaderRow
left={leftBtn}
center={centerLabel}
right={rightBtn} />
</DebugBox>
);
}
export function OptionalArea() {
const rightBtn = <Button align="reverse" icon="row-padding" basic="Save" />;
const centerLabel = <TextLabel basic="Header Title" />;
return (
<DebugBox>
<HeaderRow
left={false}
center={centerLabel}
right={rightBtn} />
</DebugBox>
);
}
OptionalArea.story = {
parameters: {
docs: {
storyDescription: 'Remove an area from DOM by explictly setting it to false.',
},
},
};
|
Tag version 0.1, ready for upload to PyPI. | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# LICENSE = open(os.path.join(os.path.dirname(__file__), 'LICENSE.txt')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='djqgrid',
version='0.1',
packages=['djqgrid', 'djqgrid.templatetags'],
include_package_data=True,
license='MIT license',
description='A Django wrapper for jqGrid',
long_description=README,
url='https://github.com/zmbq/djqgrid/',
author='Itay Zandbank',
author_email='[email protected]',
install_requires=['django>=1.6'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'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',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Development Status :: 3 - Alpha',
],
keywords='django jqgrid client-side grid',
) | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# LICENSE = open(os.path.join(os.path.dirname(__file__), 'LICENSE.txt')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='djqgrid',
version='0.0.2',
packages=['djqgrid', 'djqgrid.templatetags'],
include_package_data=True,
license='MIT license',
description='A Django wrapper for jqGrid',
long_description=README,
url='https://github.com/zmbq/djqgrid/',
author='Itay Zandbank',
author_email='[email protected]',
install_requires=['django>=1.6'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'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',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Development Status :: 3 - Alpha',
],
keywords='django jqgrid client-side grid',
) |
Change to using threading.Lock instead of threading.Condition, and check lock state before trying to release it during the finally block | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.log = logging.getLogger('diamond')
# Initialize Data
self.config = config
# Initialize Lock
self.lock = threading.Lock()
def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
try:
try:
self.log.debug("Running Handler %s locked" % (self))
self.lock.acquire()
self.process(metric)
self.lock.release()
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release()
self.log.debug("Unlocked Handler %s" % (self))
def process(self, metric):
"""
Process a metric
Should be overridden in subclasses
"""
raise NotImplementedError
def flush(self):
"""
Flush metrics
Optional: Should be overridden in subclasses
"""
pass
| # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.log = logging.getLogger('diamond')
# Initialize Data
self.config = config
# Initialize Lock
self.lock = threading.Condition(threading.Lock())
def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
try:
try:
self.log.debug("Running Handler %s locked" % (self))
self.lock.acquire()
self.process(metric)
self.lock.release()
except Exception:
self.log.error(traceback.format_exc())
finally:
self.lock.release()
self.log.debug("Unlocked Handler %s" % (self))
def process(self, metric):
"""
Process a metric
Should be overridden in subclasses
"""
raise NotImplementedError
def flush(self):
"""
Flush metrics
Optional: Should be overridden in subclasses
"""
pass
|
Change dictionary name to avoid collision; fix dict.values() call | from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.graph = {}
def __repr__(self):
return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.graph]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
self.graph[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
self.graph[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
del self.graph[n]
for edgeset in self.graph.values():
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
self.graph[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
return n in self.graph
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
for node in self.graph:
if n in self.node:
neighbors.append(node)
return neighbors
| from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.nodes = {}
def __repr__(self):
pass
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.nodes]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
self.nodes[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
self.nodes[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
del self.nodes[n]
for edgeset in self.nodes.values:
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
self.nodes[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
return n in self.nodes
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
for node in self.nodes:
if n in self.node:
neighbors.append(node)
return neighbors
|
Modify filter to show new computational sample templates. | class MCWorkflowProcessTemplatesComponentController {
/*@ngInit*/
constructor(templates) {
this.templates = templates.get();
this.templateTypes = [
{
title: 'CREATE SAMPLES',
cssClass: 'mc-create-samples-color',
icon: 'fa-cubes',
margin: true,
templates: this.templates.filter(t => t.process_type === 'create')
},
{
title: 'TRANSFORMATION',
cssClass: 'mc-transform-color',
icon: 'fa-exclamation-triangle',
templates: this.templates.filter(t => t.process_type === 'transform')
},
{
title: 'MEASUREMENT',
cssClass: 'mc-measurement-color',
icon: 'fa-circle',
templates: this.templates.filter(t => t.process_type === 'measurement')
},
{
title: 'ANALYSIS',
cssClass: 'mc-analysis-color',
icon: 'fa-square',
templates: this.templates.filter(t => t.process_type === 'analysis')
}
];
}
chooseTemplate(t) {
if (this.onSelected) {
this.onSelected({templateId: t.name, processId: ''});
}
}
}
angular.module('materialscommons').component('mcWorkflowProcessTemplates', {
templateUrl: 'app/project/experiments/experiment/components/processes/mc-workflow-process-templates.html',
controller: MCWorkflowProcessTemplatesComponentController,
bindings: {
onSelected: '&'
}
});
| class MCWorkflowProcessTemplatesComponentController {
/*@ngInit*/
constructor(templates) {
this.templates = templates.get();
this.templateTypes = [
{
title: 'CREATE SAMPLES',
cssClass: 'mc-create-samples-color',
icon: 'fa-cubes',
margin: true,
templates: this.templates.filter(t => t.process_type === 'create' && t.name === 'Create Samples')
},
{
title: 'TRANSFORMATION',
cssClass: 'mc-transform-color',
icon: 'fa-exclamation-triangle',
templates: this.templates.filter(t => t.process_type === 'transform' && t.name !== 'Create Samples')
},
{
title: 'MEASUREMENT',
cssClass: 'mc-measurement-color',
icon: 'fa-circle',
templates: this.templates.filter(t => t.process_type === 'measurement')
},
{
title: 'ANALYSIS',
cssClass: 'mc-analysis-color',
icon: 'fa-square',
templates: this.templates.filter(t => t.process_type === 'analysis')
}
];
}
chooseTemplate(t) {
if (this.onSelected) {
this.onSelected({templateId: t.name, processId: ''});
}
}
}
angular.module('materialscommons').component('mcWorkflowProcessTemplates', {
templateUrl: 'app/project/experiments/experiment/components/processes/mc-workflow-process-templates.html',
controller: MCWorkflowProcessTemplatesComponentController,
bindings: {
onSelected: '&'
}
});
|
Remove new JS syntax usage
Add support for Node.js 4.x | /*eslint-env node*/
const _ = require('lodash');
const ERROR_SEVERITY = 2;
function logIssue(issue) {
const attributes = _.chain(_.toPairs(issue))
.map((pair) => ({ key: pair[0], value: pair[1], }))
.filter((pair) => pair.key !== 'message')
.filter((pair) => pair.value !== undefined)
.map((pair) => `${pair.key}=${pair.value};`)
.value();
return `##vso[task.logissue ${attributes.join('')}]${issue.message}`;
}
module.exports = (results) =>
_.chain(results)
.filter((result) => result.messages.length > 0)
.flatMap((result) => _.chain(result.messages)
.map((message) => logIssue({
type: (message.fatal || message.severity === ERROR_SEVERITY) ? 'error' : 'warning',
sourcepath: result.filePath,
linenumber: message.line,
columnnumber: message.column,
code: message.ruleId,
message: message.message,
}))
.value())
.value()
.join('\n');
| /*eslint-env node*/
const _ = require('lodash');
const ERROR_SEVERITY = 2;
function logIssue(issue) {
const attributes = _.chain(_.toPairs(issue))
.filter(([ key, ]) => key !== 'message')
.filter(([ , value, ]) => value !== undefined)
.map(([ key, value, ]) => `${key}=${value};`)
.value();
return `##vso[task.logissue ${attributes.join('')}]${issue.message}`;
}
module.exports = (results) =>
_.chain(results)
.filter((result) => result.messages.length > 0)
.flatMap((result) => _.chain(result.messages)
.map((message) => logIssue({
type: (message.fatal || message.severity === ERROR_SEVERITY) ? 'error' : 'warning',
sourcepath: result.filePath,
linenumber: message.line,
columnnumber: message.column,
code: message.ruleId,
message: message.message,
}))
.value())
.value()
.join('\n');
|
Address Python lint issue in unrelated file | # ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt for license information
# See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ===---------------------------------------------------------------------===#
class StageArgs(object):
def __init__(self, stage, args):
self.__dict__['postfix'] = stage.postfix
self.__dict__['stage'] = stage
self.__dict__['args'] = args
assert(not isinstance(self.args, StageArgs))
def _get_stage_prefix(self):
return self.__dict__['postfix']
def __getattr__(self, key):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
if not hasattr(args, real_key):
return None
return getattr(args, real_key)
def __setattr__(self, key, value):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
setattr(args, real_key, value)
class Stage(object):
def __init__(self, identifier, postfix=""):
self.identifier = identifier
self.postfix = postfix
STAGE_1 = Stage(1, "")
STAGE_2 = Stage(2, "_stage2")
| # ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt for license information
# See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ===---------------------------------------------------------------------===#
class StageArgs(object):
def __init__(self, stage, args):
self.__dict__['postfix'] = stage.postfix
self.__dict__['stage'] = stage
self.__dict__['args'] = args
assert(not isinstance(self.args, StageArgs))
def _get_stage_prefix(self):
return self.__dict__['postfix']
def __getattr__(self, key):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
if not hasattr(args, real_key):
return None
return getattr(args, real_key)
def __setattr__(self, key, value):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
setattr(args, real_key, value)
class Stage(object):
def __init__(self, identifier, postfix=""):
self.identifier = identifier
self.postfix = postfix
STAGE_1 = Stage(1, "")
STAGE_2 = Stage(2, "_stage2")
|
Fix to ensure we dont leave any open file handles laying around | /*
* Copyright 2012-2014 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import re
class FreeMemory:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = { }
with open("/proc/meminfo") as fd:
for line in fd:
if "MemFree" in line:
data['MemFree'] = int(re.findall('\d+', line)[0])
elif "Buffers" in line:
data['Buffers'] = int(re.findall('\d+', line)[0])
elif re.match('^Cached', line):
data['Cached'] = int(re.findall('\d+', line)[0])
data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached']
return data
| /*
* Copyright 2012-2014 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import re
class FreeMemory:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = { }
for line in open("/proc/meminfo"):
if "MemFree" in line:
data['MemFree'] = int(re.findall('\d+', line)[0])
elif "Buffers" in line:
data['Buffers'] = int(re.findall('\d+', line)[0])
elif re.match('^Cached', line):
data['Cached'] = int(re.findall('\d+', line)[0])
data['AvailableMemory'] = data['MemFree'] + data['Buffers'] + data['Cached']
return data
|
Fix errors reported by php-cs-fixer | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Code\Generator;
use Zend\Code\Generator\AbstractMemberGenerator;
use Zend\Code\Generator\Exception\InvalidArgumentException;
class AbstractMemberGeneratorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AbstractMemberGenerator
*/
private $fixture;
protected function setUp()
{
$this->fixture = $this->getMockForAbstractClass('Zend\Code\Generator\AbstractMemberGenerator');
}
public function testSetFlagsWithArray()
{
$this->fixture->setFlags(
array(
AbstractMemberGenerator::FLAG_FINAL,
AbstractMemberGenerator::FLAG_PUBLIC,
)
);
$this->assertEquals(AbstractMemberGenerator::VISIBILITY_PUBLIC, $this->fixture->getVisibility());
$this->assertEquals(true, $this->fixture->isFinal());
}
/**
* @expectedException InvalidArgumentException
*/
public function testSetDocBlockThrowsExceptionWithInvalidType()
{
$this->fixture->setDocBlock(new \stdClass());
}
}
| <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Code\Generator;
use Zend\Code\Generator\AbstractMemberGenerator;
use Zend\Code\Generator\Exception\InvalidArgumentException;
class AbstractMemberGeneratorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AbstractMemberGenerator
*/
private $fixture;
protected function setUp()
{
$this->fixture = $this->getMockForAbstractClass('Zend\Code\Generator\AbstractMemberGenerator');
}
public function testSetFlagsWithArray()
{
$this->fixture->setFlags(
array(
AbstractMemberGenerator::FLAG_FINAL,
AbstractMemberGenerator::FLAG_PUBLIC,
)
);
$this->assertEquals(AbstractMemberGenerator::VISIBILITY_PUBLIC, $this->fixture->getVisibility());
$this->assertEquals(true, $this->fixture->isFinal());
}
/**
* @expectedException InvalidArgumentException
*/
public function testSetDocBlockThrowsExceptionWithInvalidType()
{
$this->fixture->setDocBlock(new \stdClass());
}
} |
Fix a stupid bug in get_people_from_memberships
The rebinding of the function's election_data parameter was breaking
the listing of candidates for a post. | from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponseRedirect
from slugify import slugify
from ..election_specific import AREA_POST_DATA
from ..models import (
PopItPerson, membership_covers_date
)
def get_redirect_to_post(election, post_data):
short_post_label = AREA_POST_DATA.shorten_post_label(
election, post_data['label']
)
return HttpResponseRedirect(
reverse(
'constituency',
kwargs={
'election': election,
'post_id': post_data['id'],
'ignored_slug': slugify(short_post_label),
}
)
)
def get_people_from_memberships(election_data, memberships):
current_candidates = set()
past_candidates = set()
for membership in memberships:
if not membership.get('role') == election_data['candidate_membership_role']:
continue
person = PopItPerson.create_from_dict(membership['person_id'])
if membership_covers_date(
membership,
election_data['election_date']
):
current_candidates.add(person)
else:
for other_election, other_election_data in settings.ELECTIONS_BY_DATE:
if not other_election_data.get('use_for_candidate_suggestions'):
continue
if membership_covers_date(
membership,
other_election_data['election_date'],
):
past_candidates.add(person)
return current_candidates, past_candidates
| from django.core.urlresolvers import reverse
from django.conf import settings
from django.http import HttpResponseRedirect
from slugify import slugify
from ..election_specific import AREA_POST_DATA
from ..models import (
PopItPerson, membership_covers_date
)
def get_redirect_to_post(election, post_data):
short_post_label = AREA_POST_DATA.shorten_post_label(
election, post_data['label']
)
return HttpResponseRedirect(
reverse(
'constituency',
kwargs={
'election': election,
'post_id': post_data['id'],
'ignored_slug': slugify(short_post_label),
}
)
)
def get_people_from_memberships(election_data, memberships):
current_candidates = set()
past_candidates = set()
for membership in memberships:
if not membership.get('role') == election_data['candidate_membership_role']:
continue
person = PopItPerson.create_from_dict(membership['person_id'])
if membership_covers_date(
membership,
election_data['election_date']
):
current_candidates.add(person)
else:
for election, election_data in settings.ELECTIONS_BY_DATE:
if not election_data.get('use_for_candidate_suggestions'):
continue
if membership_covers_date(
membership,
election_data['election_date'],
):
past_candidates.add(person)
return current_candidates, past_candidates
|
Use the media id as notification id | package io.smartlogic.smartchat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("New SmartChat")
.setContentText("SmartChat from " + extras.getString("creator_email"));
Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
resultIntent.putExtras(extras);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(extras.getInt("id", 1), mBuilder.build());
}
}
| package io.smartlogic.smartchat;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("New SmartChat")
.setContentText("SmartChat from " + extras.getString("creator_email"));
Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
resultIntent.putExtras(extras);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
|
QS-1486: Enable hidden metadata option on other people´s profile | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ProfileData from './ProfileData'
export default class OtherProfileDataList extends Component {
static propTypes = {
profileWithMetadata: PropTypes.array.isRequired,
metadata : PropTypes.object.isRequired,
};
render() {
const {profileWithMetadata, metadata} = this.props;
let lines = [];
profileWithMetadata.forEach(
category => {
if (Object.keys(category.fields).length === 0 || !Object.keys(category.fields).some(profileDataKey => category.fields[profileDataKey].value)) {
return;
}
lines.push(<div key={category.label} className="profile-category"><h3>{category.label}</h3></div>);
Object.keys(category.fields).forEach(
profileDataKey => {
if (category.fields[profileDataKey].value && metadata[profileDataKey].hidden !== true) {
lines.push(<ProfileData key={profileDataKey} name={category.fields[profileDataKey].text} value={category.fields[profileDataKey].value} forceLong={category.fields[profileDataKey].type === 'textarea'}/>);
}
});
});
return (
<div className="profile-data-list">
{lines}
</div>
);
}
}
| import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ProfileData from './ProfileData'
export default class OtherProfileDataList extends Component {
static propTypes = {
profileWithMetadata: PropTypes.array.isRequired,
metadata : PropTypes.object.isRequired,
};
render() {
const {profileWithMetadata, metadata} = this.props;
let lines = [];
profileWithMetadata.forEach(
category => {
if (Object.keys(category.fields).length === 0 || !Object.keys(category.fields).some(profileDataKey => category.fields[profileDataKey].value)) {
return;
}
lines.push(<div key={category.label} className="profile-category"><h3>{category.label}</h3></div>);
Object.keys(category.fields).forEach(
profileDataKey => {
if (category.fields[profileDataKey].value && metadata[profileDataKey].visible !== false) {
lines.push(<ProfileData key={profileDataKey} name={category.fields[profileDataKey].text} value={category.fields[profileDataKey].value} forceLong={category.fields[profileDataKey].type === 'textarea'}/>);
}
});
});
return (
<div className="profile-data-list">
{lines}
</div>
);
}
}
|
Add test for index to cells | from support import lib,ffi
from qcgc_test import QCGCTest
class FitAllocatorTest(QCGCTest):
def test_macro_consistency(self):
self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1)
last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1
self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP)
self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP)
def test_small_free_list_index(self):
for i in range(1, lib.qcgc_small_free_lists + 1):
self.assertTrue(lib.is_small(i))
self.assertEqual(lib.small_index(i), i - 1);
self.assertTrue(lib.small_index_to_cells(i - 1), i);
def test_large_free_list_index(self):
index = -1;
for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP):
if (i & (i - 1) == 0):
# Check for power of two
index = index + 1
self.assertFalse(lib.is_small(i))
self.assertEqual(index, lib.large_index(i));
| from support import lib,ffi
from qcgc_test import QCGCTest
class FitAllocatorTest(QCGCTest):
def test_macro_consistency(self):
self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1)
last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1
self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP)
self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP)
def test_small_free_list_index(self):
for i in range(1, lib.qcgc_small_free_lists + 1):
self.assertTrue(lib.is_small(i))
self.assertEqual(lib.small_index(i), i - 1);
def test_large_free_list_index(self):
index = -1;
for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP):
if (i & (i - 1) == 0):
# Check for power of two
index = index + 1
self.assertFalse(lib.is_small(i))
self.assertEqual(index, lib.large_index(i));
|
BB-4080: Add CLI command to perform product reindex
- cr fixes | <?php
namespace Oro\Bundle\SearchBundle\Engine;
interface IndexerInterface
{
/**
* Save one of several entities to search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function save($entity, array $context = []);
/**
* Delete one or several entities from search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function delete($entity, array $context = []);
/**
* Returns classes required to reindex for one or several classes
* Returns all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return string[]
*/
public function getClassesForReindex($class = null, array $context = []);
/**
* Resets data for one or several classes in index
* Resets data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*/
public function resetIndex($class = null, array $context = []);
/**
* Reindex data for one or several classes in index
* Reindex data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return int Number of reindexed entities
*/
public function reindex($class = null, array $context = []);
}
| <?php
namespace Oro\Bundle\SearchBundle\Engine;
interface IndexerInterface
{
/**
* Save one of several entities to search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function save($entity, $context = []);
/**
* Delete one or several entities from search index
*
* @param object|array $entity
* @param array $context
*
* @return bool
*/
public function delete($entity, $context = []);
/**
* Returns classes required to reindex for one or several classes
* Returns all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*
* @return string[]
*/
public function getClassesForReindex($class = null, $context = []);
/**
* Resets data for one or several classes in index
* Resets data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*/
public function resetIndex($class = null, $context = []);
/**
* Reindex data for one or several classes in index
* Reindex data for all indexed classes if $class is null
*
* @param string|string[] $class
* @param array $context
*/
public function reindex($class = null, $context = []);
}
|
Add navbar prop to router. | const styles = require('../Style/style.js')
import React, { Component } from 'react'
import { Navigator } from 'react-native'
import HomeMap from './HomeMap'
import ParkingDetails from './ParkingDetails'
export default class Router extends Component {
constructor(props) {
super(props)
this.state = {}
this.renderScene = this.renderScene.bind(this)
}
renderScene(route, navigator) {
switch (route.name) {
case 'HomeMap':
return <HomeMap navigator={navigator} {...route} />
break
case 'Camera':
return <Camera navigator={navigator} {...route} />
break
case 'ParkingDetails':
return <ParkingDetails navigator={navigator} {...route} />
break
}
}
leftButton (route, navigator, index, navState) {
if (route.name !== 'HomeMap') {
} else {
return null
}
}
rightButton (route, navigator, index, navState) {
if (route.name !== 'HomeMap') {
} else {
return null
}
}
render () {
return (
<Navigator
initialRoute = {
{
name: 'HomeMap',
currentUser: this.props.currentUser,
userToken: this.props.userToken,
logOut: this.props.logOut,
reanimator: this.props.reanimator
}
}
renderScene={this.renderScene}
navigationBar={
<Navigation.NavigationBar
routeMapper={{
LeftButton: this.leftButton,
RightButton: this.rightButton,
Title: () => {}
}}
/>
}
/>
)
}
}
| const styles = require('../Style/style.js')
import React, { Component } from 'react'
import { Navigator } from 'react-native'
import HomeMap from './HomeMap'
import ParkingDetails from './ParkingDetails'
export default class Router extends Component {
constructor(props) {
super(props)
this.state = {}
this.renderScene = this.renderScene.bind(this)
}
renderScene(route, navigator) {
switch (route.name) {
case 'HomeMap':
return <HomeMap navigator={navigator} {...route} />
break
case 'Camera':
return <Camera navigator={navigator} {...route} />
break
case 'ParkingDetails':
return <ParkingDetails navigator={navigator} {...route} />
break
}
}
render () {
return (
<Navigator
initialRoute = {
{
name: 'HomeMap',
currentUser: this.props.currentUser,
userToken: this.props.userToken,
logOut: this.props.logOut,
reanimator: this.props.reanimator
}
}
renderScene= {this.renderScene}
/>
)
}
}
|
Remove const expression to attain php 5.5 support | <?php
namespace Asvae\ApiTester\Http\Controllers;
use DateTime;
use Illuminate\Routing\Controller;
class AssetsController extends Controller
{
public function index($file = '')
{
// Permit only safe characters in filename.
if (! preg_match('%^([a-z_\-\.]+?)$%', $file)) {
abort(404);
}
$contents = file_get_contents(__DIR__.'/../../../resources/assets/build/'.$file);
$response = response($contents, 200, [
'Content-Type' => $this->getFileContentType($file)
]);
// Browser will cache files for 1 year.
$secondsInYear = 60*60*24*365;
$response->setSharedMaxAge($secondsInYear);
$response->setMaxAge($secondsInYear);
$response->setExpires(new DateTime('+1 year'));
return $response;
}
/**
* Figure out appropriate "Content-Type" header
* by filename.
*
* @param $file
* @return mixed
*/
protected function getFileContentType($file)
{
$array = explode('.', $file);
$ext = end($array);
$contentTypes = [
'css' => 'text/css',
'js' => 'text/javascript',
'svg' => 'image/svg+xml',
];
return $contentTypes[$ext];
}
}
| <?php
namespace Asvae\ApiTester\Http\Controllers;
use DateTime;
use Illuminate\Routing\Controller;
class AssetsController extends Controller
{
const SECONDS_IN_YEAR = 60*60*24*365;
public function index($file = '')
{
// Permit only safe characters in filename.
if (! preg_match('%^([a-z_\-\.]+?)$%', $file)) {
abort(404);
}
$contents = file_get_contents(__DIR__.'/../../../resources/assets/build/'.$file);
$response = response($contents, 200, [
'Content-Type' => $this->getFileContentType($file)
]);
// Browser will cache files for 1 year.
$response->setSharedMaxAge(static::SECONDS_IN_YEAR);
$response->setMaxAge(static::SECONDS_IN_YEAR);
$response->setExpires(new DateTime('+1 year'));
return $response;
}
/**
* Figure out appropriate "Content-Type" header
* by filename.
*
* @param $file
* @return mixed
*/
protected function getFileContentType($file)
{
$array = explode('.', $file);
$ext = end($array);
$contentTypes = [
'css' => 'text/css',
'js' => 'text/javascript',
'svg' => 'image/svg+xml',
];
return $contentTypes[$ext];
}
}
|
Use readline() instead of next() to detect changes.
tilequeue/queue/file.py
-`readline()` will pick up new lines appended to the file,
whereas `next()` will not since the iterator will just hit
`StopIteration` and stop generating new lines. Use `readline()`
instead, then, since it might be desirable to append something
to the queue file and have tilequeue detect the new input
without having to restart. | from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = ''.join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
| from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
try:
coord = next(self.fp)
except StopIteration:
break
coords.append(CoordMessage(deserialize_coord(coord), None))
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = "".join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
|
Make last_jobid available for compatibility. | package io.digdag.standards.operator.gcp;
import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobConfiguration;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigFactory;
import io.digdag.client.config.ConfigKey;
import io.digdag.spi.OperatorContext;
import io.digdag.spi.TaskResult;
import java.nio.file.Path;
abstract class BaseBqJobOperator
extends BaseBqOperator
{
BaseBqJobOperator(OperatorContext context, BqClient.Factory clientFactory, GcpCredentialProvider credentialProvider)
{
super(context, clientFactory, credentialProvider);
}
@Override
protected TaskResult run(BqClient bq, String projectId)
{
BqJobRunner jobRunner = new BqJobRunner(request, bq, projectId);
Job completed = jobRunner.runJob(jobConfiguration(projectId));
return result(completed);
}
private TaskResult result(Job job)
{
ConfigFactory cf = request.getConfig().getFactory();
Config result = cf.create();
Config bq = result.getNestedOrSetEmpty("bq");
bq.set("last_job_id", job.getId());
bq.set("last_jobid", job.getId());
return TaskResult.defaultBuilder(request)
.storeParams(result)
.addResetStoreParams(ConfigKey.of("bq", "last_job_id"))
.addResetStoreParams(ConfigKey.of("bq", "last_jobid"))
.build();
}
protected abstract JobConfiguration jobConfiguration(String projectId);
}
| package io.digdag.standards.operator.gcp;
import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobConfiguration;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigFactory;
import io.digdag.client.config.ConfigKey;
import io.digdag.spi.OperatorContext;
import io.digdag.spi.TaskResult;
import java.nio.file.Path;
abstract class BaseBqJobOperator
extends BaseBqOperator
{
BaseBqJobOperator(OperatorContext context, BqClient.Factory clientFactory, GcpCredentialProvider credentialProvider)
{
super(context, clientFactory, credentialProvider);
}
@Override
protected TaskResult run(BqClient bq, String projectId)
{
BqJobRunner jobRunner = new BqJobRunner(request, bq, projectId);
Job completed = jobRunner.runJob(jobConfiguration(projectId));
return result(completed);
}
private TaskResult result(Job job)
{
ConfigFactory cf = request.getConfig().getFactory();
Config result = cf.create();
Config bq = result.getNestedOrSetEmpty("bq");
bq.set("last_job_id", job.getId());
return TaskResult.defaultBuilder(request)
.storeParams(result)
.addResetStoreParams(ConfigKey.of("bq", "last_job_id"))
.build();
}
protected abstract JobConfiguration jobConfiguration(String projectId);
}
|
Use dirname instead of realpath | <?php
declare(strict_types=1);
namespace WoohooLabs\Zen\Examples;
use WoohooLabs\Zen\Config\AbstractCompilerConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfigInterface;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfig;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfigInterface;
use WoohooLabs\Zen\Examples\Controller\AbstractController;
use WoohooLabs\Zen\Examples\Controller\ControllerInterface;
class CompilerConfig extends AbstractCompilerConfig
{
public function getContainerNamespace(): string
{
return "WoohooLabs\\Zen\\Examples";
}
public function getContainerClassName(): string
{
return "Container";
}
public function useConstructorInjection(): bool
{
return true;
}
public function usePropertyInjection(): bool
{
return true;
}
public function getAutoloadConfig(): AutoloadConfigInterface
{
;
return AutoloadConfig::enabledGlobally(dirname(__DIR__))
->setAlwaysAutoloadedClasses(
[
ControllerInterface::class,
]
)
->setExcludedClasses(
[
AbstractController::class
]
);
}
public function getFileBasedDefinitionConfig(): FileBasedDefinitionConfigInterface
{
return FileBasedDefinitionConfig::disabledGlobally("Definitions/");
}
public function getContainerConfigs(): array
{
return [
new ContainerConfig(),
];
}
}
| <?php
declare(strict_types=1);
namespace WoohooLabs\Zen\Examples;
use WoohooLabs\Zen\Config\AbstractCompilerConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfig;
use WoohooLabs\Zen\Config\Autoload\AutoloadConfigInterface;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfig;
use WoohooLabs\Zen\Config\FileBasedDefinition\FileBasedDefinitionConfigInterface;
use WoohooLabs\Zen\Examples\Controller\AbstractController;
use WoohooLabs\Zen\Examples\Controller\ControllerInterface;
class CompilerConfig extends AbstractCompilerConfig
{
public function getContainerNamespace(): string
{
return "WoohooLabs\\Zen\\Examples";
}
public function getContainerClassName(): string
{
return "Container";
}
public function useConstructorInjection(): bool
{
return true;
}
public function usePropertyInjection(): bool
{
return true;
}
public function getAutoloadConfig(): AutoloadConfigInterface
{
return AutoloadConfig::enabledGlobally(realpath(__DIR__ . "/.."))
->setAlwaysAutoloadedClasses(
[
ControllerInterface::class,
]
)
->setExcludedClasses(
[
AbstractController::class
]
);
}
public function getFileBasedDefinitionConfig(): FileBasedDefinitionConfigInterface
{
return FileBasedDefinitionConfig::disabledGlobally("Definitions/");
}
public function getContainerConfigs(): array
{
return [
new ContainerConfig(),
];
}
}
|
Use a non-routeable address for this URL.
We do not anticipate ever sending any traffic to this since this is the
in-memory-only implementation. | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
An in-memory implementation of the Kubernetes client interface.
"""
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . import IKubernetes, network_kubernetes
def memory_kubernetes():
"""
Create an in-memory Kubernetes-alike service.
This serves as a places to hold state for stateful Kubernetes interactions
allowed by ``IKubernetesClient``. Only clients created against the same
instance will all share state.
:return IKubernetes: The new Kubernetes-alike service.
"""
return _MemoryKubernetes()
@implementer(IKubernetes)
class _MemoryKubernetes(object):
"""
``_MemoryKubernetes`` maintains state in-memory which approximates
the state of a real Kubernetes deployment sufficiently to expose a
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://kubernetes.example.invalid./")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
credentials=None,
agent=RequestTraversalAgent(self._resource),
)
def client(self, *args, **kwargs):
"""
:return IKubernetesClient: A new client which interacts with this
object rather than a real Kubernetes deployment.
"""
return self._kubernetes.client(*args, **kwargs)
def _kubernetes_resource():
return Resource()
| # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
An in-memory implementation of the Kubernetes client interface.
"""
from zope.interface import implementer
from twisted.python.url import URL
from twisted.web.resource import Resource
from treq.testing import RequestTraversalAgent
from . import IKubernetes, network_kubernetes
def memory_kubernetes():
"""
Create an in-memory Kubernetes-alike service.
This serves as a places to hold state for stateful Kubernetes interactions
allowed by ``IKubernetesClient``. Only clients created against the same
instance will all share state.
:return IKubernetes: The new Kubernetes-alike service.
"""
return _MemoryKubernetes()
@implementer(IKubernetes)
class _MemoryKubernetes(object):
"""
``_MemoryKubernetes`` maintains state in-memory which approximates
the state of a real Kubernetes deployment sufficiently to expose a
subset of the external Kubernetes API.
"""
def __init__(self):
base_url = URL.fromText(u"https://localhost/")
self._resource = _kubernetes_resource()
self._kubernetes = network_kubernetes(
base_url=base_url,
credentials=None,
agent=RequestTraversalAgent(self._resource),
)
def client(self, *args, **kwargs):
"""
:return IKubernetesClient: A new client which interacts with this
object rather than a real Kubernetes deployment.
"""
return self._kubernetes.client(*args, **kwargs)
def _kubernetes_resource():
return Resource()
|
Fix for esquire.untli() not working with linked list nodes | 'use strict'
/*
* Assumes exclusive ownership of each removal
*/
function until(onRemove, removals) {
onRemove.listenOnce(function() {
removals.forEach(function(removal) {
if(typeof removal === 'function')
removal()
else
removal.remove()
})
})
}
function bind_until(func) {
var clear
var result = function func_with_until() {
if(clear) {
clear()
clear = undefined
}
func()
}
result.until = function until(onRemove) {
// ****************************************** TODO: it may become convenient to allow multiple calls but that's not really what this function is for right now
if(clear)
throw new Error('more than one call to until')
clear = onRemove.listenOnce(result)
}
return result
}
function setInterval_rm(callback, delay) {
var interval = setInterval(callback, delay)
return bind_until(function() { clearInterval(interval) })
}
function setTimeout_rm(callback, delay) {
function execute() {
var delay = dest - Date.now()
if(delay > 0)
timeout = setTimeout(execute, delay)
else {
timeout = undefined
callback()
}
}
var dest = Date.now() + delay
var timeout = setTimeout(execute, delay)
return bind_until(function() { if(timeout !== undefined) clearTimeout(timeout) })
}
if(typeof exports !== 'undefined') {
exports.bind_until = bind_until
exports.setInterval_rm = setInterval_rm
exports.setTimeout_rm = setTimeout_rm
exports.until = until
}
| 'use strict'
/*
* Assumes exclusive ownership of each removal
*/
function until(onRemove, removals) {
onRemove.listenOnce(function() {
removals.forEach(function(removal) {
removal()
})
})
}
function bind_until(func) {
var clear
var result = function func_with_until() {
if(clear) {
clear()
clear = undefined
}
func()
}
result.until = function until(onRemove) {
// ****************************************** TODO: it may become convenient to allow multiple calls but that's not really what this function is for right now
if(clear)
throw new Error('more than one call to until')
clear = onRemove.listenOnce(result)
}
return result
}
function setInterval_rm(callback, delay) {
var interval = setInterval(callback, delay)
return bind_until(function() { clearInterval(interval) })
}
function setTimeout_rm(callback, delay) {
function execute() {
var delay = dest - Date.now()
if(delay > 0)
timeout = setTimeout(execute, delay)
else {
timeout = undefined
callback()
}
}
var dest = Date.now() + delay
var timeout = setTimeout(execute, delay)
return bind_until(function() { if(timeout !== undefined) clearTimeout(timeout) })
}
if(typeof exports !== 'undefined') {
exports.bind_until = bind_until
exports.setInterval_rm = setInterval_rm
exports.setTimeout_rm = setTimeout_rm
exports.until = until
}
|
Add test to get an object out back as an object | var Assert = require('assert');
var CacheAllTheThings = require('../');
describe('CacheAllTheThings', function() {
it('When asked to boot a Redis instance, it should do so', function() {
var inst = new CacheAllTheThings('redis');
Assert(inst.name, 'RedisCache');
});
describe('Redis', function() {
it('Should set a key', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.set('lol', 'hai')
.then(function(e) {
Assert.equal(e, null);
done();
});
});
it('Should get a key that exists', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.get('lol')
.then(function(val) {
Assert(val, 'hai');
done();
}, function(e) {
Assert.notEqual(e, null);
done();
});
});
it('Should get a key that does not exist', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.get('lols')
.then(function(val) {
Assert(true);
done();
}, function(e) {
Assert.notEqual(e, null);
done();
});
});
it('Should set an object, and get back an object', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.set('obj', {
testing : true
})
.then(function() {
redisInst
.get('obj')
.then(function(val) {
Assert(val, {
testing : true
});
done();
}, function(e) {
done();
});
});
});
});
}); | var Assert = require('assert');
var CacheAllTheThings = require('../');
describe('CacheAllTheThings', function() {
it('When asked to boot a Redis instance, it should do so', function() {
var inst = new CacheAllTheThings('redis');
Assert(inst.name, 'RedisCache');
});
describe('Redis', function() {
it('Should set a key', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.set('lol', 'hai')
.then(function(e) {
Assert.equal(e, null);
done();
});
});
it('Should get a key that exists', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.get('lol')
.then(function(val) {
Assert(val, 'hai');
done();
}, function(e) {
Assert.notEqual(e, null);
done();
});
});
it('Should get a key that does not exist', function(done) {
var redisInst = new CacheAllTheThings('redis');
redisInst
.get('lols')
.then(function(val) {
Assert(true);
done();
}, function(e) {
Assert.notEqual(e, null);
done();
});
});
});
}); |
Use Laminas Doctrine Hydrator instead of DoctrineModule Hydrator | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace DoctrineORMModule\Service;
use Doctrine\Laminas\Hydrator\DoctrineObject;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\FactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;
class DoctrineObjectHydratorFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new DoctrineObject($container->get('doctrine.entitymanager.orm_default'));
}
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container->getServiceLocator(), DoctrineObject::class);
}
}
| <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license.
*/
namespace DoctrineORMModule\Service;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\FactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;
class DoctrineObjectHydratorFactory implements FactoryInterface
{
/**
* {@inheritDoc}
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new DoctrineObject($container->get('doctrine.entitymanager.orm_default'));
}
/**
* {@inheritDoc}
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container->getServiceLocator(), DoctrineObject::class);
}
}
|
Add support for proper relative files
Until now it only worked if the file.base matched the main sass file's
folder. |
'use strict';
var path = require('path');
var fs = require('fs');
var through = require('through2');
var glob = require('glob');
module.exports = function() {
var process = function(filename) {
var replaceString = '';
if (fs.statSync(filename).isDirectory()) {
// Ignore directories start with _
if (path.basename(filename).substring(0, 1) == '_') return '';
fs.readdirSync(filename).forEach(function (file) {
replaceString += process(filename + path.sep + file);
});
return replaceString;
} else {
if (filename.substr(-4).match(/sass|scss/i)) {
return '@import "' + filename + '";\n'
} else {
return '';
}
}
}
var transform = function(file, env, cb) {
// find all instances matching
var contents = file.contents.toString('utf-8');
var reg = /@import\s+[\"']([^\"']*\*[^\"']*)[\"'];?/;
var directory = path.dirname(file.path);
var result;
while((result = reg.exec(contents)) !== null) {
var sub = result[0];
var globName = result[1];
var files = glob.sync(path.join(directory, globName));
var replaceString = '';
files.forEach(function(filename){
replaceString += process(filename);
});
contents = contents.replace(sub, replaceString);
}
file.contents = new Buffer(contents);
cb(null, file);
};
return through.obj(transform);
};
|
'use strict';
var path = require('path');
var fs = require('fs');
var through = require('through2');
var glob = require('glob');
module.exports = function() {
var process = function(filename) {
var replaceString = '';
if (fs.statSync(filename).isDirectory()) {
// Ignore directories start with _
if (path.basename(filename).substring(0, 1) == '_') return '';
fs.readdirSync(filename).forEach(function (file) {
replaceString += process(filename + path.sep + file);
});
return replaceString;
} else {
if (filename.substr(-4).match(/sass|scss/i)) {
return '@import "' + filename + '";\n'
} else {
return '';
}
}
}
var transform = function(file, env, cb) {
// find all instances matching
var contents = file.contents.toString('utf-8');
var reg = /@import\s+[\"']([^\"']*\*[^\"']*)[\"'];?/;
var result;
while((result = reg.exec(contents)) !== null) {
var index = result.index;
var sub = result[0];
var globName = result[1];
var files = glob.sync(file.base + globName);
var replaceString = '';
files.forEach(function(filename){
replaceString += process(filename);
});
contents = contents.replace(sub, replaceString);
}
file.contents = new Buffer(contents);
cb(null, file);
};
return through.obj(transform);
};
|
Integrate `UserChangeForm` so we get nice password fields. | from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
base_fieldsets = (
('Meta', {
'classes': ('collapse', ),
'fields': ('last_login', )
}),
('Permissions', {
'fields': (
'is_active', 'is_staff', 'is_superuser', 'groups',
'user_permissions')
}),
)
base_form = UserChangeForm
base_model = User
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
| from django.conf import settings
from django.contrib import admin
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmin, PolymorphicChildModelAdmin
class UserChildAdmin(PolymorphicChildModelAdmin):
base_model = User
# base_form = forms.ProductAdminForm
class UserAdmin(PolymorphicParentModelAdmin):
base_model = User
list_filter = ('is_active', 'is_staff', 'is_superuser', 'created')
list_display = (
'__unicode__', 'is_active', 'is_staff', 'is_superuser', 'created')
polymorphic_list = True
def get_child_models(self):
from django_polymorphic_auth.usertypes.email.admin import \
EmailUserAdmin
from django_polymorphic_auth.usertypes.username.admin import \
UsernameUserAdmin
child_models = []
if 'django_polymorphic_auth.usertypes.email' in \
settings.INSTALLED_APPS:
child_models.append((EmailUser, EmailUserAdmin))
if 'django_polymorphic_auth.usertypes.username' in \
settings.INSTALLED_APPS:
child_models.append((UsernameUser, UsernameUserAdmin))
return child_models
admin.site.register(User, UserAdmin)
|
Fix a bug in OutputFileQueue.close().
tilequeue/queue/file.py
-01a8fcb made `OutputFileQueue.read()` use `readline()` instead
of `next()`, but didn't update `OutputFileQueue.close()`, which
uses a list comprehension to grab the rest of the file. Since
`.read()` no longer uses the iteration protocol, `.close()` will
start iterating from the beginning of the file. Use `.read()`
instead of a list comprehension to only grab everything after
what `.readline()` already picked up. | from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
self.clear()
self.fp.write(self.fp.read())
self.fp.close()
| from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = ''.join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
|
Fix path to config file
Get Can't locate path: </home/vagrant/Code/herbax.dev/vendor/wuifdesign/laravel-seo/src/config/wuifdesign-seo.php> when doing php artisan vendor:publish ... Config file name is seo.php not wuifdesign-seo.php | <?php
namespace WuifDesign\SEO;
use \Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/config/seo.php', 'seo'
);
$this->app->singleton('metaTags', function ($app) {
return new MetaTags($app);
});
$this->app->singleton('openGraph', function ($app) {
return new OpenGraph($app);
});
$this->app->singleton('twitterCard', function ($app) {
return new TwitterCard($app);
});
$this->app->singleton('schema', function ($app) {
return new Schema($app);
});
$this->app->singleton('seoTool', function ($app) {
return new SEOTool($app);
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/config/seo.php' => config_path('seo.php'),
]);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array(
'metaTags',
'openGraph',
'twitterCard',
'schema',
'seoTools'
);
}
}
| <?php
namespace WuifDesign\SEO;
use \Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
class ServiceProvider extends IlluminateServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/config/seo.php', 'seo'
);
$this->app->singleton('metaTags', function ($app) {
return new MetaTags($app);
});
$this->app->singleton('openGraph', function ($app) {
return new OpenGraph($app);
});
$this->app->singleton('twitterCard', function ($app) {
return new TwitterCard($app);
});
$this->app->singleton('schema', function ($app) {
return new Schema($app);
});
$this->app->singleton('seoTool', function ($app) {
return new SEOTool($app);
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/config/wuifdesign-seo.php' => config_path('seo.php'),
]);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array(
'metaTags',
'openGraph',
'twitterCard',
'schema',
'seoTools'
);
}
}
|
Set long description content type to markdown | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from setuptools import setup, find_packages
import os
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
setup(
name='python-hcalendar',
version=__import__('hcalendar').__version__,
author='Marc Hoersken',
author_email='[email protected]',
packages=find_packages(exclude=['unittests']),
include_package_data=True,
url='https://github.com/mback2k/python-hcalendar',
license='MIT',
description=' '.join(__import__('hcalendar').__doc__.splitlines()).strip(),
install_requires=['isodate>=0.5.0', 'beautifulsoup4>=4.3.2'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Software Development :: Libraries :: Python Modules',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
],
long_description=read_file('README.md'),
long_description_content_type='text/markdown',
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from setuptools import setup, find_packages
import os
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return ''
setup(
name='python-hcalendar',
version=__import__('hcalendar').__version__,
author='Marc Hoersken',
author_email='[email protected]',
packages=find_packages(exclude=['unittests']),
include_package_data=True,
url='https://github.com/mback2k/python-hcalendar',
license='MIT',
description=' '.join(__import__('hcalendar').__doc__.splitlines()).strip(),
install_requires=['isodate>=0.5.0', 'beautifulsoup4>=4.3.2'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Text Processing :: Markup :: HTML',
'Topic :: Software Development :: Libraries :: Python Modules',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
],
long_description=read_file('README.md'),
)
|
Reduce warning time to 5s | import logging
import time
from functools import wraps
from . import compat
compat.patch() # monkey-patch time.perf_counter
log = logging.getLogger('amqpy')
def synchronized(lock_name):
"""Decorator for automatically acquiring and releasing lock for method call
This decorator accesses the `lock_name` :class:`threading.Lock` attribute of the instance that
the wrapped method is bound to. The lock is acquired (blocks indefinitely) before the method is
called. After the method has executed, the lock is released.
Decorated methods should not be long-running operations, since the lock is held for the duration
of the method's execution.
:param lock_name: name of :class:`threading.Lock` object
"""
def decorator(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
lock = getattr(self, lock_name)
acquired = lock.acquire(False)
if not acquired:
# log.debug('> Wait to acquire lock for [{}]'.format(f.__qualname__))
start_time = time.perf_counter()
lock.acquire()
tot_time = time.perf_counter() - start_time
if tot_time > 5:
# only log if waited for more than 10s to acquire lock
log.warn('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time))
try:
retval = f(self, *args, **kwargs)
finally:
lock.release()
return retval
return wrapper
return decorator
| import logging
import time
from functools import wraps
from . import compat
compat.patch() # monkey-patch time.perf_counter
log = logging.getLogger('amqpy')
def synchronized(lock_name):
"""Decorator for automatically acquiring and releasing lock for method call
This decorator accesses the `lock_name` :class:`threading.Lock` attribute of the instance that
the wrapped method is bound to. The lock is acquired (blocks indefinitely) before the method is
called. After the method has executed, the lock is released.
Decorated methods should not be long-running operations, since the lock is held for the duration
of the method's execution.
:param lock_name: name of :class:`threading.Lock` object
"""
def decorator(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
lock = getattr(self, lock_name)
acquired = lock.acquire(False)
if not acquired:
# log.debug('> Wait to acquire lock for [{}]'.format(f.__qualname__))
start_time = time.perf_counter()
lock.acquire()
tot_time = time.perf_counter() - start_time
if tot_time > 10:
# only log if waited for more than 10s to acquire lock
log.warn('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time))
try:
retval = f(self, *args, **kwargs)
finally:
lock.release()
return retval
return wrapper
return decorator
|
Allow user to put in access token | $(function(){
var messages = [];
function process(data) {
if(data.data.length) {
messages = messages.concat(data.data);
}
if(data.paging && data.paging.next) {
console.log('Getting next page');
return $.getJSON(data.paging.next).then(process);
}
}
$('.submit-id').click(function(){
messages = [];
var messageId = $('.thread-id').val();
var token = $('.token').val();
$.getJSON(
'https://graph.facebook.com/' + messageId + '/comments' +
'?format=json&access_token=' + token
)
.then(process)
.then(function() {
return messages;
// location.href = URL.createObjectURL(blob);
})
.then(function(messages) {
var chart = c3.generate({
bindto: '.container',
data: {
x: 'count',
columns: [
countWords(messages).axis,
countWords(messages).columns,
],
groups: [
['count']
],
type: 'bar'
},
axis: {
x: {
type: 'categorized',
}
},
transition: {
duration: 1000
}
});
});
});
})
;
| $(function(){
var messages = [];
var token = 'CAACEdEose0cBAPsc5EojEPsnGCVpG05fBKSV1N2WrZAJJ8ngZB55cAkWQA82ZBSaGbiOUOcI9rpRxMxT5kAjGmhhSSieTjtXFEuMYYOEtVIrFYC9ZCkuSSdT5P45ZBBvuniyPGZCZCFPDxkZBFhiRr0BRKje0ZBG7ylmeiJ10ImU8k3mpY5DdoPNT5yZCc6qZBF5jUZD';
function process(data) {
if(data.data.length) {
messages = messages.concat(data.data);
}
if(data.paging && data.paging.next) {
console.log('Getting next page');
return $.getJSON(data.paging.next).then(process);
}
}
$('.submit-id').click(function(){
messages = [];
var messageId = $('.thread-id').val();
$.getJSON(
'https://graph.facebook.com/' + messageId + '/comments' +
'?format=json&access_token=' + token
)
.then(process)
.then(function() {
return messages;
// location.href = URL.createObjectURL(blob);
})
.then(function(messages) {
var chart = c3.generate({
bindto: '.container',
data: {
x: 'count',
columns: [
countWords(messages).axis,
countWords(messages).columns,
],
groups: [
['count']
],
type: 'bar'
},
axis: {
x: {
type: 'categorized',
}
},
transition: {
duration: 1000
}
});
});
});
})
;
|
Use resolver to resolve the table name | var resolver = require('../resolver');
function select(database, options, callback) {
var results = [];
database.command('select', options, function(error, data) {
if (error) {
callback(error);
} else {
var columnNames = [];
var i, j;
for (j = 0; j < data[0][1].length; j++) {
columnNames[j] = data[0][1][j][0];
}
for (i = 0; i < data[0].length - 2; i++) {
var row = data[0][i + 2];
var object = {};
for (j = 0; j < columnNames.length; j++) {
object[columnNames[j]] = row[j];
}
results[i] = object;
}
callback(null, results);
}
});
}
exports.createHandler = function(database) {
return function(request, response) {
var domain = request.query.DomainName || '';
var expr = request.query.q;
var options = {
table: resolver.getTableNameFromDomain(domain),
query: expr,
match_columns: 'address' // FIXME
};
select(database, options, function(error, data) {
if (error) {
throw error;
}
var info = {};
var result = {
rank: '-text_relevance', // FIXME
'match-expr': expr,
hits: {
found: data.length,
start: 0,
hit: data
},
info: info
};
response.json(result);
});
};
};
| function select(database, options, callback) {
var results = [];
database.command('select', options, function(error, data) {
if (error) {
callback(error);
} else {
var columnNames = [];
var i, j;
for (j = 0; j < data[0][1].length; j++) {
columnNames[j] = data[0][1][j][0];
}
for (i = 0; i < data[0].length - 2; i++) {
var row = data[0][i + 2];
var object = {};
for (j = 0; j < columnNames.length; j++) {
object[columnNames[j]] = row[j];
}
results[i] = object;
}
callback(null, results);
}
});
}
exports.createHandler = function(database) {
return function(request, response) {
var domain = request.query.DomainName || '';
var expr = request.query.q;
var options = {
table: domain,
query: expr,
match_columns: 'address' // FIXME
};
select(database, options, function(error, data) {
if (error) {
throw error;
}
var info = {};
var result = {
rank: '-text_relevance', // FIXME
'match-expr': expr,
hits: {
found: data.length,
start: 0,
hit: data
},
info: info
};
response.json(result);
});
};
};
|
Configure webpack so that `eval` is not used in the development mode
Using eval is not allowed by the CSP of newer Nextcloud versions. | /**
* ownCloud - Music app
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Pauli Järvinen <[email protected]>
* @copyright 2020 Pauli Järvinen
*
*/
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
entry: {
app: '../js/config/index.js',
files_music_player: '../js/embedded/index.js'
},
output: {
filename: 'webpack.[name].js',
path: path.resolve(__dirname, '../js/public'),
},
resolve: {
alias: {
'angular': path.resolve(__dirname, '../js/vendor/angular'),
'lodash': path.resolve(__dirname, '../js/vendor/lodash'),
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'webpack.app.css'}),
new ESLintPlugin({
files: '../js'
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'img/'
}
}
],
}
],
},
}; | /**
* ownCloud - Music app
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Pauli Järvinen <[email protected]>
* @copyright 2020 Pauli Järvinen
*
*/
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
mode: 'production',
entry: {
app: '../js/config/index.js',
files_music_player: '../js/embedded/index.js'
},
output: {
filename: 'webpack.[name].js',
path: path.resolve(__dirname, '../js/public'),
},
resolve: {
alias: {
'angular': path.resolve(__dirname, '../js/vendor/angular'),
'lodash': path.resolve(__dirname, '../js/vendor/lodash'),
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'webpack.app.css'}),
new ESLintPlugin({
files: '../js'
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'img/'
}
}
],
}
],
},
}; |
Set Python as default language. | <?php
namespace App\Units\Home\Http\Controllers;
use App\Domains\Graphics\FrameworkRadar;
use App\Domains\Graphics\LanguagesIndex;
use App\Domains\Graphics\LearningCurve;
use App\Domains\Graphics\LearningCurveAll;
use App\Domains\Graphics\Trend;
use Codecasts\Support\Http\Controller;
/**
* Class GraphicsController.
*/
class GraphicsController extends Controller
{
public function showGraphicsLcLang()
{
$languages = LearningCurveAll::getTopLanguages();
return view('home::Graphics.learning_curve.languages', compact(['languages']));
}
public function showGraphicsLearningCurve($language = 'python')
{
$learning = LearningCurve::getLearningCurveByLanguage($language);
if (!$learning) {
abort(404);
}
return view('home::Graphics.learning_curve.language', compact(['learning']));
}
public function showGraphicsStars()
{
$repositories = Trend::getMostStaredRepositories();
return view('home::Graphics.Trends.stars', compact(['repositories']));
}
public function showGraphicsForks()
{
$repositories = Trend::getMostForkedRepositories();
return view('home::Graphics.Trends.forks', compact(['repositories']));
}
public function showGraphicsFrameworks()
{
$radar = FrameworkRadar::getTrendingFrameworks();
return view('home::Graphics.radar', compact(['radar']));
}
public function showGraphicsLanguages()
{
$languages = LanguagesIndex::getIndexedLanguages();
return view('home::Graphics.tiobe', compact(['languages']));
}
}
| <?php
namespace App\Units\Home\Http\Controllers;
use App\Domains\Graphics\FrameworkRadar;
use App\Domains\Graphics\LanguagesIndex;
use App\Domains\Graphics\LearningCurve;
use App\Domains\Graphics\LearningCurveAll;
use App\Domains\Graphics\Trend;
use Codecasts\Support\Http\Controller;
/**
* Class GraphicsController.
*/
class GraphicsController extends Controller
{
public function showGraphicsLcLang()
{
$languages = LearningCurveAll::getTopLanguages();
return view('home::Graphics.learning_curve.languages', compact(['languages']));
}
public function showGraphicsLearningCurve($language = 'actionscript')
{
$learning = LearningCurve::getLearningCurveByLanguage($language);
if (!$learning) {
abort(404);
}
return view('home::Graphics.learning_curve.language', compact(['learning']));
}
public function showGraphicsStars()
{
$repositories = Trend::getMostStaredRepositories();
return view('home::Graphics.Trends.stars', compact(['repositories']));
}
public function showGraphicsForks()
{
$repositories = Trend::getMostForkedRepositories();
return view('home::Graphics.Trends.forks', compact(['repositories']));
}
public function showGraphicsFrameworks()
{
$radar = FrameworkRadar::getTrendingFrameworks();
return view('home::Graphics.radar', compact(['radar']));
}
public function showGraphicsLanguages()
{
$languages = LanguagesIndex::getIndexedLanguages();
return view('home::Graphics.tiobe', compact(['languages']));
}
}
|
Use binary scores to represent sentiment in map | package udacity.storm.tools;
import java.util.Properties;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;
public class SentimentAnalyzer {
static StanfordCoreNLP pipeline;
public static void init() {
Properties props = new Properties();
props.setProperty("annotators", "tokenize,ssplit,parse,sentiment");
pipeline = new StanfordCoreNLP(props);
}
public static int getBinarySentiment(int sentiment){
if(sentiment<=2)
return 0;
else
return 1;
}
public static int findSentiment(String tweet) {
int mainSentiment = 0;
if (tweet != null && tweet.length() > 0) {
int longest = 0;
Annotation annotation = pipeline.process(tweet);
for (CoreMap sentence : annotation
.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence
.get(SentimentCoreAnnotations.AnnotatedTree.class);
int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
String partText = sentence.toString();
if(partText.length() > longest){
mainSentiment = sentiment;
longest = partText.length();
}
}
}
return getBinarySentiment(mainSentiment);
}
}
| package udacity.storm.tools;
import java.util.Properties;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;
public class SentimentAnalyzer {
static StanfordCoreNLP pipeline;
public static void init() {
Properties props = new Properties();
props.setProperty("annotators", "tokenize,ssplit,parse,sentiment");
pipeline = new StanfordCoreNLP(props);
}
public static int findSentiment(String tweet) {
int mainSentiment = 0;
if (tweet != null && tweet.length() > 0) {
int longest = 0;
Annotation annotation = pipeline.process(tweet);
for (CoreMap sentence : annotation
.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence
.get(SentimentCoreAnnotations.AnnotatedTree.class);
int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
String partText = sentence.toString();
if (partText.length() > longest) {
mainSentiment = sentiment;
longest = partText.length();
}
}
}
return mainSentiment;
}
} |
Increment to minor version 1.1.0 | import os
import setuptools
def readme():
if os.path.isfile('README.md'):
try:
import requests
r = requests.post(
url='http://c.docverter.com/convert',
data={'from': 'markdown', 'to': 'rst'},
files={'input_files[]': open('README.md', 'r')}
)
if r.ok:
return r.content.decode()
else:
return 'ERROR CONVERTING README!'
except ImportError:
print('No `requests` module. No readme conversion applied.')
return '!!NO CONVERSION!!\n\n' + open('README.md', 'r').read()
else:
return 'No readme for local builds.'
setuptools.setup(
name='bitnigma',
version='1.1.0',
description='Python byte-enabled Enigma-like simulation.',
long_description=readme(),
keywords='enigma machine encrypt encryption rotor rotors',
author='Samuel P. Gillispie II',
author_email='[email protected]',
url='https://github.com/spgill/bitnigma',
license='MIT',
packages=['bitnigma'],
install_requires=[],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3'
]
)
| import os
import setuptools
def readme():
if os.path.isfile('README.md'):
try:
import requests
r = requests.post(
url='http://c.docverter.com/convert',
data={'from': 'markdown', 'to': 'rst'},
files={'input_files[]': open('README.md', 'r')}
)
if r.ok:
return r.content.decode()
else:
return 'ERROR CONVERTING README!'
except ImportError:
print('No `requests` module. No readme conversion applied.')
return '!!NO CONVERSION!!\n\n' + open('README.md', 'r').read()
else:
return 'No readme for local builds.'
setuptools.setup(
name='bitnigma',
version='1.0.4',
description='Python byte-enabled Enigma-like simulation.',
long_description=readme(),
keywords='enigma machine encrypt encryption rotor rotors',
author='Samuel P. Gillispie II',
author_email='[email protected]',
url='https://github.com/spgill/bitnigma',
license='MIT',
packages=['bitnigma'],
install_requires=[],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3'
]
)
|
Change version number to 0.1.x | /**
* Configuration for kort application
*/
Ext.define('Denkmap.util.Config', {
singleton: true,
config: {
/**
* @cfg {String} version Current version number of application
**/
version: '0.1.{BUILD_NR}',
leafletMap: {
zoom: 15,
getTileLayerUrl: function(isRetina) {
if(isRetina) {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}@2x/256/{z}/{x}/{y}.png';
} else {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}/256/{z}/{x}/{y}.png';
}
},
tileLayerAttribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> and © <a href="http://www.geolion.zh.ch/geodatenservice/show?nbid=691">Geodaten GIS-ZH</a>',
apiKey: '14f1a83f16604a708a4876a956f9dd35',
styleId: 997
}
},
/**
* @private
* initializes the configuration
*/
constructor: function(config) {
this.initConfig(config);
return this;
}
});
| /**
* Configuration for kort application
*/
Ext.define('Denkmap.util.Config', {
singleton: true,
config: {
/**
* @cfg {String} version Current version number of application
**/
version: '0.0.{BUILD_NR}',
leafletMap: {
zoom: 15,
getTileLayerUrl: function(isRetina) {
if(isRetina) {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}@2x/256/{z}/{x}/{y}.png';
} else {
return 'http://{s}.tile.cloudmade.com/{apikey}/{styleId}/256/{z}/{x}/{y}.png';
}
},
tileLayerAttribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> and © <a href="http://www.geolion.zh.ch/geodatenservice/show?nbid=691">Geodaten GIS-ZH</a>',
apiKey: '14f1a83f16604a708a4876a956f9dd35',
styleId: 997
}
},
/**
* @private
* initializes the configuration
*/
constructor: function(config) {
this.initConfig(config);
return this;
}
});
|
Fix compilation of macro example | var nodes = require('./nodes').nodes,
_ = require('underscore');
var macros = {};
var macroexpand = function(ast, env, opts) {
var compileNodeWithEnv = require('./compile').compileNodeWithEnv;
return _.map(ast, function(n) {
var replacement = n.accept({
visitMacro: function() {
var init = n.body.slice(0, n.body.length - 1);
var last = n.body[n.body.length - 1];
var code = _.map(init, function(node) {
return compileNodeWithEnv(node, env);
}).join('\n') + '\nreturn ' + compileNodeWithEnv(last, env) + ';';
macros[n.name] = code;
},
visitCall: function() {
if(!macros[n.func.value]) return;
var f = new Function('var nodes = this.nodes; ' + macros[n.func.value]);
var tree = f.apply({nodes: nodes}, n.args);
return tree;
}
});
return replacement || n;
});
};
exports.macroexpand = macroexpand;
| var nodes = require('./nodes').nodes,
_ = require('underscore');
var macros = {};
var macroexpand = function(ast, env, opts) {
var compileNodeWithEnv = require('./compile').compileNodeWithEnv;
return _.map(ast, function(n) {
var replacement = n.accept({
visitMacro: function() {
var init = n.body.slice(0, n.body.length - 1);
var last = n.body[n.body.length - 1];
var code = _.map(init, function(node) {
return compileNodeWithEnv(node, env);
}).join('\n') + '\nreturn ' + compileNodeWithEnv(last, env) + ';';
macros[n.name] = code;
},
visitCall: function() {
if(!macros[n.func.value]) return;
var f = new Function(macros[n.func.value]);
var tree = f.apply({}, n.args);
return tree;
}
});
return replacement || n;
});
};
exports.macroexpand = macroexpand;
|
Remove php7.1 iterable type hint from test | <?php
use PHPUnit\Framework\TestCase;
use Garp\Functional as f;
/**
* @package Garp\Functional
* @author Harmen Janssen <[email protected]>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
class IsAssocTest extends TestCase {
/**
* @dataProvider arrayProvider
* @param iterable $input
* @param bool $result
* @return void
*/
public function test_should_recognize_associative_arrays($input, bool $result) {
$this->assertSame($result, f\is_assoc($input));
}
public function arrayProvider(): array {
return [
[
[1, 2, 3],
false
],
[
[],
false
],
[
['foo' => 'bar', 1, 2, 3],
true
],
[
['foo' => 'boar', 'bar' => 'boaz'],
true
],
[
new ArrayIterator([1, 2, 3]),
false
],
[
new ArrayIterator(['foo' => 'bar', 'baz' => 'boaz']),
true
]
];
}
}
| <?php
use PHPUnit\Framework\TestCase;
use Garp\Functional as f;
/**
* @package Garp\Functional
* @author Harmen Janssen <[email protected]>
* @license https://github.com/grrr-amsterdam/garp-functional/blob/master/LICENSE.md BSD-3-Clause
*/
class IsAssocTest extends TestCase {
/**
* @dataProvider arrayProvider
* @param iterable $input
* @param bool $result
* @return void
*/
public function test_should_recognize_associative_arrays(iterable $input, bool $result) {
$this->assertSame($result, f\is_assoc($input));
}
public function arrayProvider(): array {
return [
[
[1, 2, 3],
false
],
[
[],
false
],
[
['foo' => 'bar', 1, 2, 3],
true
],
[
['foo' => 'boar', 'bar' => 'boaz'],
true
],
[
new ArrayIterator([1, 2, 3]),
false
],
[
new ArrayIterator(['foo' => 'bar', 'baz' => 'boaz']),
true
]
];
}
}
|
Print all jslint errors before exiting. | var path = require('path');
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
function failLintBuild() {
process.exit(1);
}
function scssLintExists() {
return shelljs.which('scss-lint');
}
module.exports = function(gulp, options) {
var scssLintPath = path.resolve(__dirname, 'scss-lint.yml');
var esLintPath = path.resolve(__dirname, 'eslintrc');
var customEslint = options.customEslintPath ?
require(options.customEslintPath) : {};
gulp.task('scsslint', function() {
if (options.scsslint) {
if (scssLintExists()) {
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
})).pipe(scsslint.failReporter()).on('error', failLintBuild);
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.');
}
}
});
gulp.task('jslint', function() {
var eslintRules = merge({
configFile: esLintPath
}, customEslint);
return gulp.src(options.jsAssets || [])
.pipe(eslint(eslintRules))
.pipe(eslint.formatEach())
.pipe(eslint.failOnError());
});
};
| var path = require('path');
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
function failLintBuild() {
process.exit(1);
}
function scssLintExists() {
return shelljs.which('scss-lint');
}
module.exports = function(gulp, options) {
var scssLintPath = path.resolve(__dirname, 'scss-lint.yml');
var esLintPath = path.resolve(__dirname, 'eslintrc');
var customEslint = options.customEslintPath ?
require(options.customEslintPath) : {};
gulp.task('scsslint', function() {
if (options.scsslint) {
if (scssLintExists()) {
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
})).pipe(scsslint.failReporter()).on('error', failLintBuild);
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.');
}
}
});
gulp.task('jslint', function() {
var eslintRules = merge({
configFile: esLintPath
}, customEslint);
return gulp.src(options.jsAssets || [])
.pipe(eslint(eslintRules))
.pipe(eslint.formatEach())
.pipe(eslint.failOnError()).on('error', failLintBuild);
});
};
|
Change a way of generating session ids | <?php
namespace Perfumer\Component\Session;
use Perfumer\Helper\Text;
use Stash\Pool as Cache;
class Core
{
/**
* @var \Stash\Pool
*/
protected $cache;
protected $items = [];
protected $lifetime = 3600;
public function __construct(Cache $cache, array $options = [])
{
$this->cache = $cache;
if (isset($options['lifetime']))
$this->lifetime = (int) $options['lifetime'];
}
public function get($id = null)
{
if ($id === null)
$id = $this->generateId();
if (isset($this->items[$id]))
return $this->items[$id];
$this->items[$id] = new Item($this, $this->cache, [
'id' => $id,
'lifetime' => $this->lifetime
]);
return $this->items[$id];
}
public function has($id)
{
return !$this->cache->getItem('_session/' . $id)->isMiss();
}
public function destroy($id)
{
$this->get($id)->destroy();
}
protected function generateId()
{
do
{
$id = Text::generateString(20);
$item = $this->cache->getItem('_session/' . $id);
}
while (!$item->isMiss() || isset($this->items[$id]));
return $id;
}
} | <?php
namespace Perfumer\Component\Session;
use Stash\Pool as Cache;
class Core
{
/**
* @var \Stash\Pool
*/
protected $cache;
protected $items = [];
protected $lifetime = 3600;
public function __construct(Cache $cache, array $options = [])
{
$this->cache = $cache;
if (isset($options['lifetime']))
$this->lifetime = (int) $options['lifetime'];
}
public function get($id = null)
{
if ($id === null)
$id = $this->generateId();
if (isset($this->items[$id]))
return $this->items[$id];
$this->items[$id] = new Item($this, $this->cache, [
'id' => $id,
'lifetime' => $this->lifetime
]);
return $this->items[$id];
}
public function has($id)
{
return !$this->cache->getItem('_session/' . $id)->isMiss();
}
public function destroy($id)
{
$this->get($id)->destroy();
}
protected function generateId()
{
$id = uniqid('', true);
do
{
$id = md5($id);
$item = $this->cache->getItem('_session/' . $id);
}
while (!$item->isMiss() || isset($this->items[$id]));
return $id;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.