text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
[Test] Fix unit test following merge of maintenance/1.2.0 changes. | /* ============================================================================
Copyright (C) 2006-2016 Talend Inc. - www.talend.com
This source code is available under agreement available at
https://github.com/Talend/data-prep/blob/master/LICENSE
You should have received a copy of the agreement
along with this program; if not, write to Talend SA
9 rue Pages 92150 Suresnes, France
============================================================================*/
class DatasetsFiltersCtrl {
constructor() {
'ngInject';
// The order is important
this.datasetsFilters = [
{
value: 'RECENT_DATASETS',
imageUrl: '/assets/images/inventory/recent-datasets.png',
description: 'RECENT_DATASETS_DESCRIPTION',
isSelected: true
},
{
value: 'FAVORITE_DATASETS',
icon: 'f',
description: 'FAVORITE_DATASETS_DESCRIPTION'
},
{
value: 'ALL_DATASETS',
imageUrl: '/assets/images/inventory/all-datasets.png',
description: 'ALL_DATASETS_DESCRIPTION'
}
];
this.selectedFilter = this.datasetsFilters[0];
}
selectFilter(filter) {
if (this.importing) {
return;
}
this.selectedFilter.isSelected = false;
this.selectedFilter = filter;
this.selectedFilter.isSelected = true;
this.onFilterSelect({ filter: filter.value });
}
}
export default DatasetsFiltersCtrl;
| /* ============================================================================
Copyright (C) 2006-2016 Talend Inc. - www.talend.com
This source code is available under agreement available at
https://github.com/Talend/data-prep/blob/master/LICENSE
You should have received a copy of the agreement
along with this program; if not, write to Talend SA
9 rue Pages 92150 Suresnes, France
============================================================================*/
class DatasetsFiltersCtrl {
constructor() {
'ngInject';
// The order is important
this.datasetsFilters = [
{
value: 'RECENT_DATASETS',
imageUrl: '/assets/images/inventory/recent-datasets.png',
description: 'RECENT_DATASETS_DESCRIPTION',
isSelected: true
},
{
value: 'FAVORITE_DATASETS',
icon: 'f',
description: 'FAVORITE_DATASETS_DESCRIPTION'
},
{
value: 'CERTIFIED_DATASETS',
imageUrl: '/assets/images/inventory/certified_no_shadow.png',
description: 'CERTIFIED_DATASETS_DESCRIPTION'
},
{
value: 'ALL_DATASETS',
imageUrl: '/assets/images/inventory/all-datasets.png',
description: 'ALL_DATASETS_DESCRIPTION'
}
];
this.selectedFilter = this.datasetsFilters[0];
}
selectFilter(filter) {
if (this.importing) {
return;
}
this.selectedFilter.isSelected = false;
this.selectedFilter = filter;
this.selectedFilter.isSelected = true;
this.onFilterSelect({ filter: filter.value });
}
}
export default DatasetsFiltersCtrl;
|
Make non-link ColumnLinks behave as links | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
const ColumnLink = ({ icon, text, to, onClick, href, method, badge }) => {
const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null;
if (href) {
return (
<a href={href} className='column-link' data-method={method}>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</a>
);
} else if (to) {
return (
<Link to={to} className='column-link'>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</Link>
);
} else {
const handleOnClick = (e) => {
e.preventDefault();
e.stopPropagation();
return onClick(e);
}
return (
<a href='#' onClick={onClick && handleOnClick} className='column-link' tabIndex='0'>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</a>
);
}
};
ColumnLink.propTypes = {
icon: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
to: PropTypes.string,
onClick: PropTypes.func,
href: PropTypes.string,
method: PropTypes.string,
badge: PropTypes.node,
};
export default ColumnLink;
| import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
const ColumnLink = ({ icon, text, to, onClick, href, method, badge }) => {
const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null;
if (href) {
return (
<a href={href} className='column-link' data-method={method}>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</a>
);
} else if (to) {
return (
<Link to={to} className='column-link'>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</Link>
);
} else {
return (
<a onClick={onClick} className='column-link' role='button' tabIndex='0' data-method={method}>
<i className={`fa fa-fw fa-${icon} column-link__icon`} />
{text}
{badgeElement}
</a>
);
}
};
ColumnLink.propTypes = {
icon: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
to: PropTypes.string,
onClick: PropTypes.func,
href: PropTypes.string,
method: PropTypes.string,
badge: PropTypes.node,
};
export default ColumnLink;
|
Add 'og' before last element in location list. | class Job extends React.Component {
constructor() {
super();
}
render() {
let data = this.props.jobData;
let locations = data.location.map((location) => location.name);
if (locations.length >= 2) {
locations = `${locations.slice(0, -1).join(', ')} and ${locations[locations.length - 1]}`;
}
return (
<article className="row">
<div className="col-xs-12 col-md-4">
<a href="/careeropportunity/4/">
<picture>
<source srcset={data.company.image.lg} media="(max-width: 992px)" />
<img src={data.company.image.md} alt="Firmalogo" />
</picture>
</a>
</div>
<div className="col-xs-12 col-md-8">
<h1>
<a href="/careeropportunity/4/">{data.company.name} - {data.title}</a>
</h1>
<div className="ingress">{data.ingress}</div>
<div className="meta">
<div className="col-md-4">
<p>Type: {data.employment.name}</p>
</div>
<div className="col-md-4">
<p>Sted: {locations}</p>
</div>
<div className="col-md-4">
<p>Frist: {data.deadline || 'Ikke spesifisert'}</p>
</div>
</div>
</div>
</article>
);
}
}
export default Job;
| class Job extends React.Component {
constructor() {
super();
}
render() {
let data = this.props.jobData;
return (
<article className="row">
<div className="col-xs-12 col-md-4">
<a href="/careeropportunity/4/">
<picture>
<source srcset={data.company.image.lg} media="(max-width: 992px)" />
<img src={data.company.image.md} alt="Firmalogo" />
</picture>
</a>
</div>
<div className="col-xs-12 col-md-8">
<h1>
<a href="/careeropportunity/4/">{data.company.name} - {data.title}</a>
</h1>
<div className="ingress">{data.ingress}</div>
<div className="meta">
<div className="col-md-4">
<p>Type: {data.employment.name}</p>
</div>
<div className="col-md-4">
<p>Sted: {data.location.map((location) => location.name).join(', ')}</p>
</div>
<div className="col-md-4">
<p>Frist: {data.deadline || 'Ikke spesifisert'}</p>
</div>
</div>
</div>
</article>
);
}
}
export default Job;
|
Set mEnabled using site property. | package alluxio.master.audit;
import alluxio.Configuration;
import alluxio.PropertyKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import javax.annotation.concurrent.ThreadSafe;
@ThreadSafe
public final class AsyncUserAccessAuditLogWriter {
private static final int QUEUE_SIZE = 10000;
private static final Logger LOG = LoggerFactory.getLogger(AsyncUserAccessAuditLogWriter.class);
private boolean mEnabled;
private ArrayBlockingQueue<AuditContext> mAuditLogEntries;
public AsyncUserAccessAuditLogWriter() {
mEnabled = Boolean.parseBoolean(Configuration.get(PropertyKey.MASTER_AUDIT_LOGGING_ENABLED));
mAuditLogEntries = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
public boolean isEnabled() { return mEnabled; }
public boolean append(AuditContext context) {
try {
mAuditLogEntries.put(context);
} catch (InterruptedException e) {
// Reset the interrupted flag and return because some other thread has
// told us not to wait any more.
Thread.currentThread().interrupt();
return false;
}
return true;
}
public void commit(AuditContext context) {
synchronized (context) {
context.setCommitted(true);
context.notify();
}
AuditContext headContext = mAuditLogEntries.poll();
if (headContext == null) { return; }
synchronized (headContext) {
while (!headContext.isCommitted()) {
try {
headContext.wait();
} catch (InterruptedException e) {
// TODO
return;
}
}
}
LOG.info(headContext.toString());
}
}
| package alluxio.master.audit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import javax.annotation.concurrent.ThreadSafe;
@ThreadSafe
public final class AsyncUserAccessAuditLogWriter {
private static final int QUEUE_SIZE = 10000;
private static final Logger LOG = LoggerFactory.getLogger(AsyncUserAccessAuditLogWriter.class);
private boolean mEnabled;
private ArrayBlockingQueue<AuditContext> mAuditLogEntries;
public AsyncUserAccessAuditLogWriter() {
mEnabled = true;
mAuditLogEntries = new ArrayBlockingQueue<>(QUEUE_SIZE);
}
public boolean isEnabled() { return mEnabled; }
public boolean append(AuditContext context) {
try {
mAuditLogEntries.put(context);
} catch (InterruptedException e) {
// Reset the interrupted flag and return because some other thread has
// told us not to wait any more.
Thread.currentThread().interrupt();
return false;
}
return true;
}
public void commit(AuditContext context) {
synchronized (context) {
context.setCommitted(true);
context.notify();
}
AuditContext headContext = mAuditLogEntries.poll();
if (headContext == null) { return; }
synchronized (headContext) {
while (!headContext.isCommitted()) {
try {
headContext.wait();
} catch (InterruptedException e) {
// TODO
return;
}
}
}
LOG.info(headContext.toString());
}
}
|
Fix bug with Overleaf commits swapping name and email. | package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;
import uk.ac.ic.wlgitbridge.util.Util;
/**
* Created by Winston on 06/11/14.
*/
public class SnapshotInfo implements Comparable<SnapshotInfo> {
private int versionId;
private String comment;
private WLUser user;
private String createdAt;
public SnapshotInfo(int versionID, String createdAt, String name, String email) {
this(versionID, "Update on " + Util.getServiceName() + ".", email, name, createdAt);
}
public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) {
versionId = versionID;
this.comment = comment;
user = new WLUser(name, email);
this.createdAt = createdAt;
}
public int getVersionId() {
return versionId;
}
public String getComment() {
return comment;
}
public WLUser getUser() {
return user;
}
public String getCreatedAt() {
return createdAt;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SnapshotInfo)) {
return false;
}
SnapshotInfo that = (SnapshotInfo) obj;
return versionId == that.versionId;
}
@Override
public int compareTo(SnapshotInfo o) {
return Integer.compare(versionId, o.versionId);
}
}
| package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;
import uk.ac.ic.wlgitbridge.util.Util;
/**
* Created by Winston on 06/11/14.
*/
public class SnapshotInfo implements Comparable<SnapshotInfo> {
private int versionId;
private String comment;
private WLUser user;
private String createdAt;
public SnapshotInfo(int versionID, String createdAt, String name, String email) {
this(versionID, "Update on " + Util.getServiceName() + ".", name, email, createdAt);
}
public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) {
versionId = versionID;
this.comment = comment;
user = new WLUser(name, email);
this.createdAt = createdAt;
}
public int getVersionId() {
return versionId;
}
public String getComment() {
return comment;
}
public WLUser getUser() {
return user;
}
public String getCreatedAt() {
return createdAt;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SnapshotInfo)) {
return false;
}
SnapshotInfo that = (SnapshotInfo) obj;
return versionId == that.versionId;
}
@Override
public int compareTo(SnapshotInfo o) {
return Integer.compare(versionId, o.versionId);
}
}
|
Clean exit from the command line client
- 'bye' keyword exits the client | package net.bourgau.philippe.concurrency.kata;
import java.util.Scanner;
public class Client implements Broadcast {
private final ChatRoom chatRoom;
private final String name;
private final Output out;
public Client(String name, ChatRoom chatRoom, Output out) {
this.chatRoom = chatRoom;
this.name = name;
this.out = out;
}
public void enter() {
chatRoom.enter(this);
chatRoom.broadcast(welcomeMessage(name));
}
public void write(String message) {
chatRoom.broadcast(message(name, message));
}
@Override
public void broadcast(String message) {
out.write(message);
}
public void leave() {
chatRoom.broadcast(exitMessage(name));
chatRoom.leave(this);
}
public static String welcomeMessage(String name) {
return "Welcome " + name + " !";
}
public static String message(String name, String message) {
return name + " > " + message;
}
static String exitMessage(String name) {
return name + " left";
}
public static void main(String[] args) {
Client client = new Client(args[0], new ChatRoom(), new Output() {
public void write(String line) {
System.out.println(line);
}
});
try {
client.enter();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String message = scanner.nextLine();
if (message.equals("bye")) {
break;
}
client.broadcast(message);
}
} finally {
client.leave();
}
}
}
| package net.bourgau.philippe.concurrency.kata;
import java.util.Scanner;
public class Client implements Broadcast {
private final ChatRoom chatRoom;
private final String name;
private final Output out;
public Client(String name, ChatRoom chatRoom, Output out) {
this.chatRoom = chatRoom;
this.name = name;
this.out = out;
}
public void enter() {
chatRoom.enter(this);
chatRoom.broadcast(welcomeMessage(name));
}
public void write(String message) {
chatRoom.broadcast(message(name, message));
}
@Override
public void broadcast(String message) {
out.write(message);
}
public void leave() {
chatRoom.broadcast(exitMessage(name));
chatRoom.leave(this);
}
public static String welcomeMessage(String name) {
return "Welcome " + name + " !";
}
public static String message(String name, String message) {
return name + " > " + message;
}
static String exitMessage(String name) {
return name + " left";
}
public static void main(String[] args) {
Client client = new Client(args[0], new ChatRoom(), new Output() {
public void write(String line) {
System.out.println(line);
}
});
client.enter();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
client.broadcast(scanner.nextLine());
}
}
}
|
Add support for weekend animations | from control_milight.models import LightAutomation
from control_milight.views import update_lightstate
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from ledcontroller import LedController
import datetime
import redis
class Command(BaseCommand):
args = ''
help = 'Run timed transitions'
def handle(self, *args, **options):
redis_instance = redis.StrictRedis()
led = LedController(settings.MILIGHT_IP)
time = datetime.datetime.now()
hour = datetime.time(time.hour, time.minute)
for item in LightAutomation.objects.filter(running=True):
if not item.is_running(time):
continue
percent_done = item.percent_done(time)
if item.action == "evening" or item.action == "evening-weekend":
print "Setting evening brightness to", ((1-percent_done)*100)
led.set_brightness(int((1-percent_done)*100))
elif item.action == "morning" or item.action == "morning-weekend":
print "Setting morning brightness to", ((percent_done)*100)
led.set_brightness(int((percent_done)*100))
led.white()
# update_lightstate(transition.group.group_id, transition.to_brightness, transition.to_color)
| from control_milight.models import LightAutomation
from control_milight.views import update_lightstate
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from ledcontroller import LedController
import datetime
import redis
class Command(BaseCommand):
args = ''
help = 'Run timed transitions'
def handle(self, *args, **options):
redis_instance = redis.StrictRedis()
led = LedController(settings.MILIGHT_IP)
time = datetime.datetime.now()
hour = datetime.time(time.hour, time.minute)
for item in LightAutomation.objects.filter(running=True):
if not item.is_running(time):
continue
percent_done = item.percent_done(time)
if item.action == "evening":
print "Setting evening brightness to", ((1-percent_done)*100)
led.set_brightness(int((1-percent_done)*100))
elif item.action == "morning":
print "Setting morning brightness to", ((percent_done)*100)
led.set_brightness(int((percent_done)*100))
led.white()
# update_lightstate(transition.group.group_id, transition.to_brightness, transition.to_color)
|
Add sensible defaults for ElasticSearch settings | MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DATABASE = 'pupa'
SCRAPELIB_RPM = 60
SCRAPELIB_TIMEOUT = 60
SCRAPELIB_RETRY_ATTEMPTS = 3
SCRAPELIB_RETRY_WAIT_SECONDS = 20
ENABLE_ELASTICSEARCH = False
ELASTICSEARCH_HOST = 'localhost'
ELASTICSEARCH_TIMEOUT = 2
BILL_FILTERS = {}
LEGISLATOR_FILTERS = {}
EVENT_FILTERS = {}
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
'datefmt': '%H:%M:%S'
}
},
'handlers': {
'default': {'level': 'DEBUG',
'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
'formatter': 'standard'},
},
'loggers': {
'': {
'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
},
'scrapelib': {
'handlers': ['default'], 'level': 'INFO', 'propagate': False
},
'requests': {
'handlers': ['default'], 'level': 'WARN', 'propagate': False
},
'boto': {
'handlers': ['default'], 'level': 'WARN', 'propagate': False
},
},
}
| MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DATABASE = 'pupa'
SCRAPELIB_RPM = 60
SCRAPELIB_TIMEOUT = 60
SCRAPELIB_RETRY_ATTEMPTS = 3
SCRAPELIB_RETRY_WAIT_SECONDS = 20
ENABLE_ELASTICSEARCH = False
BILL_FILTERS = {}
LEGISLATOR_FILTERS = {}
EVENT_FILTERS = {}
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
'datefmt': '%H:%M:%S'
}
},
'handlers': {
'default': {'level': 'DEBUG',
'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
'formatter': 'standard'},
},
'loggers': {
'': {
'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
},
'scrapelib': {
'handlers': ['default'], 'level': 'INFO', 'propagate': False
},
'requests': {
'handlers': ['default'], 'level': 'WARN', 'propagate': False
},
'boto': {
'handlers': ['default'], 'level': 'WARN', 'propagate': False
},
},
}
|
Test commit to see if a failing unit test breaks the build | 'use strict';
describe('loginController tests', function () {
var scope, ctrl, authServices, location;
function authServicesMock() {
var mock = {
succeed: true
};
mock.login = function() {
return {
then: function(r, e) {
if (mock.succeed) {
r();
} else {
e({ error_description: 'Error' });
}
}
}
};
return mock;
};
beforeEach(function() {
module('AzureLinkboardApp');
module('linkboardControllers');
inject(function ($rootScope, $injector, $controller) {
authServices = authServicesMock();
location = $injector.get('$location');
scope = $rootScope.$new();
ctrl = $controller("loginController", {
$scope: scope,
$location: location,
authService: authServices
});
});
});
it("should have empty login data", function () {
expect(scope.loginData).toBeDefined();
expect(scope.loginData.userName).toBe("");
expect(scope.loginData.password).toBe("");
});
it("should start with an empty message", function () {
expect(scope.message).toBe("");
});
it("login should go to links page", function () {
scope.login();
expect(location.path()).toBe('/links');
});
it("failed login should set message", function () {
authServices.succeed = false;
scope.login();
expect(scope.message).toBe("Error");
});
it("should break the build", function() {
expect(false).toBeTruthy();
});
}); | 'use strict';
describe('loginController tests', function () {
var scope, ctrl, authServices, location;
function authServicesMock() {
var mock = {
succeed: true
};
mock.login = function() {
return {
then: function(r, e) {
if (mock.succeed) {
r();
} else {
e({ error_description: 'Error' });
}
}
}
};
return mock;
};
beforeEach(function() {
module('AzureLinkboardApp');
module('linkboardControllers');
inject(function ($rootScope, $injector, $controller) {
authServices = authServicesMock();
location = $injector.get('$location');
scope = $rootScope.$new();
ctrl = $controller("loginController", {
$scope: scope,
$location: location,
authService: authServices
});
});
});
it("should have empty login data", function () {
expect(scope.loginData).toBeDefined();
expect(scope.loginData.userName).toBe("");
expect(scope.loginData.password).toBe("");
});
it("should start with an empty message", function () {
expect(scope.message).toBe("");
});
it("login should go to links page", function () {
scope.login();
expect(location.path()).toBe('/links');
});
it("failed login should set message", function () {
authServices.succeed = false;
scope.login();
expect(scope.message).toBe("Error");
});
}); |
Fix charts() test (now there are only 174 charts) | # -*- coding: utf-8 -*-
import billboard
import unittest
from nose.tools import raises
from requests.exceptions import ConnectionError
import six
class MiscTest(unittest.TestCase):
@raises(ConnectionError)
def testTimeout(self):
"""Checks that using a very small timeout prevents connection."""
billboard.ChartData("hot-100", timeout=1e-9)
@raises(billboard.BillboardNotFoundException)
def testNonExistentChart(self):
"""Checks that requesting a non-existent chart fails."""
billboard.ChartData("does-not-exist")
def testUnicode(self):
"""Checks that the Billboard website does not use Unicode characters."""
chart = billboard.ChartData("hot-100", date="2018-01-27")
self.assertEqual(
chart[97].title, six.text_type("El Bano")
) # With Unicode this should be "El Baño"
def testDifficultTitleCasing(self):
"""Checks that a difficult chart title receives proper casing."""
chart = billboard.ChartData("greatest-r-b-hip-hop-songs")
self.assertEqual(chart.title, "Greatest of All Time Hot R&B/Hip-Hop Songs")
def testCharts(self):
"""Checks that the function for listing all charts returns reasonable
results."""
charts = billboard.charts()
self.assertTrue("hot-100" in charts)
self.assertTrue(100 <= len(charts) <= 400)
| # -*- coding: utf-8 -*-
import billboard
import unittest
from nose.tools import raises
from requests.exceptions import ConnectionError
import six
class MiscTest(unittest.TestCase):
@raises(ConnectionError)
def testTimeout(self):
"""Checks that using a very small timeout prevents connection."""
billboard.ChartData("hot-100", timeout=1e-9)
@raises(billboard.BillboardNotFoundException)
def testNonExistentChart(self):
"""Checks that requesting a non-existent chart fails."""
billboard.ChartData("does-not-exist")
def testUnicode(self):
"""Checks that the Billboard website does not use Unicode characters."""
chart = billboard.ChartData("hot-100", date="2018-01-27")
self.assertEqual(
chart[97].title, six.text_type("El Bano")
) # With Unicode this should be "El Baño"
def testDifficultTitleCasing(self):
"""Checks that a difficult chart title receives proper casing."""
chart = billboard.ChartData("greatest-r-b-hip-hop-songs")
self.assertEqual(chart.title, "Greatest of All Time Hot R&B/Hip-Hop Songs")
def testCharts(self):
"""Checks that the function for listing all charts returns reasonable
results."""
charts = billboard.charts()
self.assertTrue("hot-100" in charts)
self.assertTrue(200 <= len(charts) <= 400)
|
Add semi-compatibility with Java 9+ | package xyz.upperlevel.uppercore.util;
import java.io.File;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public final class ExternalJarUtil {
private static final MethodHandle addPath;
static {//void addURL(URL var1)
ClassLoader classLoader = ExternalJarUtil.class.getClassLoader();
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
MethodHandle tmp = MethodHandles.lookup().unreflect(method);
addPath = tmp.bindTo(classLoader);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Unsupported class loader: " + classLoader.getClass().getName(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot get addUrl method", e);
}
}
public static void addUrl(URL url) {
try {
addPath.invoke(url);
} catch (Throwable t) {
throw new RuntimeException("Error while loading external jar", t);
}
}
public static void addUrl(File file) throws MalformedURLException {
addUrl(file.toURI().toURL());
}
private ExternalJarUtil() {
}
}
| package xyz.upperlevel.uppercore.util;
import java.io.File;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public final class ExternalJarUtil {
private static final MethodHandle addPath;
static {//void addURL(URL var1)
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
MethodHandle tmp = MethodHandles.lookup().unreflect(method);
addPath = tmp.bindTo(classLoader);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Unsupported class loader: " + classLoader.getClass().getName(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot get addUrl method", e);
}
}
public static void addUrl(URL url) {
try {
addPath.invoke(url);
} catch (Throwable t) {
throw new RuntimeException("Error while loading external jar", t);
}
}
public static void addUrl(File file) throws MalformedURLException {
addUrl(file.toURI().toURL());
}
private ExternalJarUtil() {
}
}
|
Add more data to the api | from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
'setup_tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
'short_message',
'message',
'color',
'pull_request_url',
'commit_url',
)
| from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'private',
'approved',
)
class BuildResultSerializer(serializers.ModelSerializer):
class Meta:
model = BuildResult
fields = (
'id',
'coverage',
'succeeded',
'tasks',
)
class BuildInlineSerializer(serializers.ModelSerializer):
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'build_number',
'branch',
'sha',
'pull_request_id',
'start_time',
'end_time',
'result'
)
class BuildSerializer(serializers.ModelSerializer):
project = ProjectInlineSerializer(read_only=True)
result = BuildResultSerializer(read_only=True)
class Meta:
model = Build
fields = (
'id',
'project',
'result',
'build_number',
'branch',
'pull_request_id',
'sha',
'start_time',
'end_time',
)
|
Move Django out of `install_requires` to to `requires` block. | #!/usr/bin/env python
from setuptools import setup, find_packages
from os.path import dirname, join
import sys, os
# When creating the sdist, make sure the django.mo file also exists:
if 'sdist' in sys.argv:
try:
os.chdir('fluent_comments')
from django.core.management.commands.compilemessages import compile_messages
compile_messages(sys.stderr)
finally:
os.chdir('..')
setup(
name='django-fluent-comments',
version='0.8.0',
license='Apache License, Version 2.0',
install_requires=[
'django-crispy-forms>=1.1.1',
'akismet>=0.2',
],
requires=[
'Django (>=1.2)',
],
description='A modern, ajax-based appearance for django.contrib.comments',
long_description=open('README.rst').read(),
author='Diederik van der Boor',
author_email='[email protected]',
url='https://github.com/edoburu/django-fluent-comments',
download_url='https://github.com/edoburu/django-fluent-comments/zipball/master',
packages=find_packages(exclude=('example*',)),
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
from os.path import dirname, join
import sys, os
# When creating the sdist, make sure the django.mo file also exists:
if 'sdist' in sys.argv:
try:
os.chdir('fluent_comments')
from django.core.management.commands.compilemessages import compile_messages
compile_messages(sys.stderr)
finally:
os.chdir('..')
setup(
name='django-fluent-comments',
version='0.8.0',
license='Apache License, Version 2.0',
install_requires=[
'Django>=1.2.0',
'django-crispy-forms>=1.1.1',
'akismet>=0.2',
],
description='A modern, ajax-based appearance for django.contrib.comments',
long_description=open('README.rst').read(),
author='Diederik van der Boor',
author_email='[email protected]',
url='https://github.com/edoburu/django-fluent-comments',
download_url='https://github.com/edoburu/django-fluent-comments/zipball/master',
packages=find_packages(exclude=('example*',)),
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Fix reload command for projects where each chrom is in a different vcf | from django.core.management.base import BaseCommand
from xbrowse_server import xbrowse_controls
from xbrowse_server.base.models import Project
from xbrowse_server.mall import get_datastore
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
parser.add_argument('-p', "--project-id")
def handle(self, *args, **options):
project_id = options["project_id"]
family_ids = args
project = Project.objects.get(project_id=project_id)
already_deleted_once = set() # set of family ids for which get_datastore(project_id).delete_family has already been called once
for vcf_file, families in project.families_by_vcf().items():
families_to_load = []
for family in families:
family_id = family.family_id
print("Checking id: " + family_id)
if not family_ids or family.family_id not in family_ids:
continue
# delete this family
if family_id not in already_deleted_once:
get_datastore(project_id).delete_family(project_id, family_id)
already_deleted_once.add(family_id)
families_to_load.append(family)
# reload family
print("Loading %(project_id)s %(families_to_load)s" % locals())
xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
| from django.core.management.base import BaseCommand
from xbrowse_server import xbrowse_controls
from xbrowse_server.base.models import Project
from xbrowse_server.mall import get_datastore
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
parser.add_argument('-p', "--project-id")
def handle(self, *args, **options):
project_id = options["project_id"]
family_ids = args
project = Project.objects.get(project_id=project_id)
for vcf_file, families in project.families_by_vcf().items():
families_to_load = []
for family in families:
family_id = family.family_id
print("Checking id: " + family_id)
if not family_ids or family.family_id not in family_ids:
continue
# delete this family
get_datastore(project_id).delete_family(project_id, family_id)
families_to_load.append(family)
# reload family
print("Loading %(project_id)s %(families_to_load)s" % locals())
xbrowse_controls.load_variants_for_family_list(project, families_to_load, vcf_file)
|
Use map to loop instead of mapping a list | from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
list_of_trigrams = list([' '.join(s) for s in trigrams(negated_tokens)])
return list_of_trigrams
| from nltk.sentiment.util import mark_negation
from nltk.util import trigrams
import re
import validators
from .happy_tokenizer import Tokenizer
class SentimentTokenizer(object):
def __init__(self):
self.tknzr = Tokenizer()
@staticmethod
def reduce_lengthening(text):
"""
Replace repeated character sequences of length 3 or greater with sequences
of length 3.
"""
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1\1", text)
@staticmethod
def replace_username(token):
return '@__user__' if token.startswith('@') else token
@staticmethod
def replace_link(token):
return '__url__' if validators.url(token) else token
def __call__(self, t):
t = self.reduce_lengthening(t)
tokens = t.split(' ')
cleaned_tokens = []
for token in tokens:
token = self.replace_username(token)
token = self.replace_link(token)
cleaned_tokens.append(token)
rebuild_str = ' '.join(cleaned_tokens)
negated_tokens = mark_negation(list(self.tknzr.tokenize(rebuild_str)))
list_of_trigrams = list(trigrams(negated_tokens))
return list([' '.join(s) for s in list_of_trigrams])
|
Test JSON mime type correctly | <?php
/**
* Get information about QGIS Server.
*
* @author 3liz
* @copyright 2012 3liz
*
* @see http://3liz.com
*
* @license Mozilla Public License : http://www.mozilla.org/MPL/
*/
class qgisServer
{
// QGIS Server version
public $qgisServerVersion;
// List of activated server plugins
public $plugins = array();
// constructor
public function __construct()
{
$services = lizmap::getServices();
$this->qgisServerVersion = $services->qgisServerVersion;
}
public function getPlugins($project)
{
$plugins = array();
// Check for atlasprint plugin
$params = array(
'service' => 'WMS',
'request' => 'GetCapabilitiesAtlas',
'map' => $project->getRelativeQgisPath()
);
$url = lizmapProxy::constructUrl($params);
list($data, $mime, $code) = lizmapProxy::getRemoteData($url);
if (strpos($mime, 'text/json') === 0 || strpos($mime, 'application/json') === 0) {
$json = json_decode($data);
$metadata = $json->metadata;
$plugins[$metadata->name] = array('version' => $metadata->version);
}
return $plugins;
}
}
| <?php
/**
* Get information about QGIS Server.
*
* @author 3liz
* @copyright 2012 3liz
*
* @see http://3liz.com
*
* @license Mozilla Public License : http://www.mozilla.org/MPL/
*/
class qgisServer
{
// QGIS Server version
public $qgisServerVersion;
// List of activated server plugins
public $plugins = array();
// constructor
public function __construct()
{
$services = lizmap::getServices();
$this->qgisServerVersion = $services->qgisServerVersion;
//$this->getPlugins();
}
public function getPlugins($project)
{
$plugins = array();
// Check for atlasprint plugin
$params = array(
'service' => 'WMS',
'request' => 'GetCapabilitiesAtlas',
'map' => $project->getRelativeQgisPath()
);
$url = lizmapProxy::constructUrl($params);
list($data, $mime, $code) = lizmapProxy::getRemoteData($url);
if ($mime == 'text/json') {
$json = json_decode($data);
$metadata = $json->metadata;
$plugins[$metadata->name] = array('version' => $metadata->version);
}
return $plugins;
}
}
|
Add feature vector size calculation method to mapper interface | import math
import numpy
class FeatureMapper(object):
def __init__(self, features):
self.features = features
def map(self, fv):
raise NotImplementedError
def __call__(self, doc):
for chain in doc.chains:
for c in chain.candidates:
c.fv = self.map(numpy.array([c.features[f] for f in self.features]))
return doc
def feature_vector_length(self):
raise NotImplementedError
class ZeroMeanUnitVarianceMapper(FeatureMapper):
def __init__(self, features, means, stds):
super(ZeroMeanUnitVarianceMapper,self).__init__(features)
self.mean = means
self.std = stds
def map(self, fv):
return (fv - self.mean) / self.std
def feature_vector_length(self):
return len(self.features)
class PolynomialMapper(ZeroMeanUnitVarianceMapper):
def __init__(self, features, means, stds):
super(PolynomialMapper,self).__init__(features, means, stds)
def map(self, fv):
fv = list(super(PolynomialMapper, self).map(fv))
sz = len(fv)
for i in xrange(0, sz):
for j in xrange(i, sz):
weight = 1.0 if i != j else math.sqrt(2.0)
fv.append(weight * fv[i]*fv[j])
return numpy.array(fv)
def feature_vector_length(self):
n = len(self.features)
return n + n*(n+1)/2
FEATURE_MAPPERS = {cls.__name__:cls for cls in [ZeroMeanUnitVarianceMapper,PolynomialMapper]}
| import math
import numpy
class FeatureMapper(object):
def __init__(self, features):
self.features = features
def map(self, fv):
raise NotImplementedError
def __call__(self, doc):
for chain in doc.chains:
for c in chain.candidates:
c.fv = self.map(numpy.array([c.features[f] for f in self.features]))
return doc
class ZeroMeanUnitVarianceMapper(FeatureMapper):
def __init__(self, features, means, stds):
super(ZeroMeanUnitVarianceMapper,self).__init__(features)
self.mean = means
self.std = stds
def map(self, fv):
return (fv - self.mean) / self.std
class PolynomialMapper(ZeroMeanUnitVarianceMapper):
def __init__(self, features, means, stds):
super(PolynomialMapper,self).__init__(features, means, stds)
def map(self, fv):
fv = list(super(PolynomialMapper, self).map(fv))
sz = len(fv)
for i in xrange(0, sz):
for j in xrange(i, sz):
weight = 1.0 if i != j else math.sqrt(2.0)
fv.append(weight * fv[i]*fv[j])
return numpy.array(fv)
FEATURE_MAPPERS = {cls.__name__:cls for cls in [ZeroMeanUnitVarianceMapper,PolynomialMapper]}
|
[feat]: Add placeholder text to resumer header | import React, {PropTypes} from 'react';
import Paper from 'material-ui/lib/paper';
export default class ResumeHeader extends React.Component {
static propTypes = {
body: PropTypes.string
}
static contextTypes = {
store: React.PropTypes.object
}
render() {
const userInput = this.context.store.getState().userFormReducer;
const styles = {
name: {
fontWeight: '700',
fontSize: '28px',
textAlign: 'center',
marginLeft: '10px'
},
email: {
color: 'blue',
fontSize: '16px',
marginLeft: '10px'
},
phone: {
fontSize: '16px',
marginLeft: '10px'
},
city: {
marginLeft: '10px'
},
url: {
textAlign: 'right',
marginRight: '10px'
}
};
return (
<div>
<Paper zDepth={1}>
<div style={styles.name}>
Your Name Here
</div>
<div style={styles.email}>
[email protected]
</div>
<div style={styles.phone}>
123-456-7890
</div>
<div style={styles.city}>
San Francisco, CA
</div>
<div style={styles.url}>
linkedin.com/michaeljordan
</div>
<div style={styles.url}>
github.com/number23
</div>
</Paper>
</div>
);
}
}
| import React, {PropTypes} from 'react';
import Paper from 'material-ui/lib/paper';
export default class ResumeHeader extends React.Component {
static propTypes = {
body: PropTypes.string
}
static contextTypes = {
store: React.PropTypes.object
}
render() {
const userInput = this.context.store.getState().userFormReducer;
const styles = {
name: {
fontWeight: '700',
fontSize: '28px',
textAlign: 'center',
marginLeft: '10px'
},
email: {
color: 'blue',
fontSize: '16px',
marginLeft: '10px'
},
phone: {
fontSize: '16px',
marginLeft: '10px'
},
city: {
marginLeft: '10px'
},
url: {
textAlign: 'right',
marginRight: '10px'
}
};
return (
<div>
<Paper zDepth={1}>
<div style={styles.name}>
{userInput.name}
</div>
<div style={styles.email}>
{userInput.email}
</div>
<div style={styles.phone}>
{userInput.phone}
</div>
<div style={styles.city}>
{userInput.city}, {userInput.state}
</div>
<div style={styles.url}>
{userInput.linkedinUrl}
</div>
<div style={styles.url}>
{userInput.githubUrl}
</div>
</Paper>
</div>
);
}
}
|
Fix version list validation check.
[#152092418] | import subprocess
from command import Command
from list_versions_command import ListVersionsCommand
from ..git_tools import git_base_command
class UpdateSoftwareCommand(Command):
def __init__(self, flow, cmd_name, params):
Command.__init__(self, flow, cmd_name, params)
def exec_impl(self):
release = self.params['release']
list_cmd = ListVersionsCommand(None, None, {})
list_cmd.exec_cmd()
if list_cmd.get_response()['success'] is False:
self.response = {
'success': False,
'message': 'Unable to list available versions.' }
return
if not release in list_cmd.get_response()['version_list']:
self.response = {
'success': False,
'message': 'Version %s is not available' % (release) }
return
self.shell_helper(git_base_command() + ['checkout', 'tags/'+release])
if self.flow is not None:
self.flow.set_operational_status(self.flow.OP_STATUS_UPDATING)
self.response = {
'success': True,
'message': 'Software version updating to %s' % (tag) }
def post_exec(self):
if self.flow is not None:
self.flow.send_status()
self.shell_helper(['sudo', 'reboot'])
| import subprocess
from command import Command
from . import ListVersionsCommand
from ..git_tools import git_base_command
class UpdateSoftwareCommand(Command):
def __init__(self, flow, cmd_name, params):
Command.__init__(self, flow, cmd_name, params)
def exec_impl(self):
release = self.params['release']
list_cmd = ListVersionsCommand(None, None, {})
list_cmd.exec_cmd()
if list_cmd.get_response().success is False:
self.response = {
'success': False,
'message': 'Unable to list available versions.' }
return
if not release in list_cmd.get_response()['version_list']:
self.response = {
'success': False,
'message': 'Version %s is not available' % (release) }
return
self.shell_helper(git_base_command() + ['checkout', 'tags/'+release])
if self.flow is not None:
self.flow.set_operational_status(self.flow.OP_STATUS_UPDATING)
self.response = {
'success': True,
'message': 'Software version updating to %s' % (tag) }
def post_exec(self):
if self.flow is not None:
self.flow.send_status()
self.shell_helper(['sudo', 'reboot'])
|
Stop watching movies while editing code! | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from flask import jsonify
from flask import current_app
from influxdb import InfluxDBClient
from app.base import ApiResource
class InfluxResource(ApiResource):
endpoint = 'influxdb'
url_prefix = '/influxdb'
url_rules = {
'index': {
'rule': '/',
}
}
def get(self):
config = current_app.config['USER_CONFIG'].get('influxdb', {})
client = InfluxDBClient.from_DSN(config['uri'], timeout=5)
results = []
for metric in config.get('metrics', []):
collection = []
for index, query in enumerate(metric.get('queries', [])):
result = client.query(query, epoch='ms')
if result:
for dataset in result.raw['series']:
series = {}
series['data'] = dataset['values']
series['label'] = metric['labels'][index] if 'labels' in metric else None
series['lines'] = dict(fill=True)
series['mode'] = metric['mode'] if 'mode' in metric else None
series['color'] = metric['colors'][index] if 'colors' in metric else None
collection.append(series)
results.append(collection)
return jsonify(results=results)
| #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from flask import jsonify
from flask import current_app
from influxdb import InfluxDBClient
from app.base import ApiResource
class InfluxResource(ApiResource):
endpoint = 'influxdb'
url_prefix = '/influxdb'
url_rules = {
'index': {
'rule': '/',
}
}
def get(self):
config = current_app.config['USER_CONFIG'].get('influxdb', {})
client = InfluxDBClient.from_DSN(config['uri'], timeout=5)
results = []
for metric in config.get('metrics', []):
collection = []
for index, query in enumerate(metric.get('queries', [])):
result = client.query(query, epoch='ms')
if result:
for dataset in result.raw['series']:
series = {}
series['data'] = dataset['values']
series['label'] = metric['labels'][index] if 'labels' in metric else None
series['lines'] = dict(fill=True)
series['mode'] = metric['mode'] if 'mode' in metric else None
series['color'] = metric['colors'][index] if 'colors' in metric else None
collection.append(series)
results.append(collection)
return jsonify(results=results)
|
Fix typo error.
Typo on copyright comment. | <?php
/**
* This file is part of the Bruery Platform.
*
* (c) Viktore Zara <[email protected]>
* (c) Mell Zamora <[email protected]>
*
* Copyright (c) 2016. For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Bruery\UserBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class TemplateCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('bruery_core.template_loader');
$templates = $container->getParameter('bruery_user.templates');
$bunldeTemplates = [];
foreach($templates as $key => $templates) {
if(is_array($templates)) {
foreach ($templates as $id=>$template) {
$bunldeTemplates[sprintf('bruery_user.template.%s.%s', $key, $id)] = $template;
}
} else {
$bunldeTemplates[sprintf('bruery_user.template.%s', $key)] = $templates;
}
}
$definition->addMethodCall('setTemplates', array($bunldeTemplates));
}
}
| <?php
/**
* This file is part of the Bruery Platform.
*
* (c) Viktore Zara <[email protected]>
* (c) Mell Zamora <[email protected]>
*
* Copyright (c) 2016. For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
*/
namespace Bruery\UserBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class TemplateCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('bruery_core.template_loader');
$templates = $container->getParameter('bruery_user.templates');
$bunldeTemplates = [];
foreach($templates as $key => $templates) {
if(is_array($templates)) {
foreach ($templates as $id=>$template) {
$bunldeTemplates[sprintf('bruery_user.template.%s.%s', $key, $id)] = $template;
}
} else {
$bunldeTemplates[sprintf('bruery_user.template.%s', $key)] = $templates;
}
}
$definition->addMethodCall('setTemplates', array($bunldeTemplates));
}
}
|
Add fade in animation to underlabel validator. | package com.strohwitwer.awesomevalidation.validators;
import android.content.Context;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.utility.ValidationCallback;
import java.util.ArrayList;
import java.util.regex.Matcher;
public class UnderlabelValidator extends Validator {
private Context mContext;
private ArrayList<TextView> mTextViews = new ArrayList<>();
public void setContext(Context context) {
mContext = context;
}
@Override
public boolean trigger() {
halt();
return checkFields(new ValidationCallback() {
@Override
public void execute(ValidationHolder validationHolder, Matcher matcher) {
EditText editText = validationHolder.getEditText();
ViewGroup parent = (ViewGroup) editText.getParent();
int index = parent.indexOfChild(editText);
TextView textView = new TextView(mContext);
textView.setText(validationHolder.getErrMsg());
textView.setTextColor(mContext.getResources().getColor(android.R.color.holo_red_light));
textView.startAnimation(AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in));
mTextViews.add(textView);
parent.addView(textView, index + 1);
}
});
}
@Override
public void halt() {
for (TextView textView : mTextViews) {
ViewGroup parent = (ViewGroup) textView.getParent();
parent.removeView(textView);
}
mTextViews.clear();
}
} | package com.strohwitwer.awesomevalidation.validators;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.utility.ValidationCallback;
import java.util.ArrayList;
import java.util.regex.Matcher;
public class UnderlabelValidator extends Validator {
private Context mContext;
private ArrayList<TextView> mTextViews = new ArrayList<>();
public void setContext(Context context) {
mContext = context;
}
@Override
public boolean trigger() {
halt();
return checkFields(new ValidationCallback() {
@Override
public void execute(ValidationHolder validationHolder, Matcher matcher) {
EditText editText = validationHolder.getEditText();
ViewGroup parent = (ViewGroup) editText.getParent();
int index = parent.indexOfChild(editText);
TextView textView = new TextView(mContext);
textView.setText(validationHolder.getErrMsg());
textView.setTextColor(mContext.getResources().getColor(android.R.color.holo_red_light));
mTextViews.add(textView);
parent.addView(textView, index + 1);
}
});
}
@Override
public void halt() {
for (TextView textView : mTextViews) {
ViewGroup parent = (ViewGroup) textView.getParent();
parent.removeView(textView);
}
mTextViews.clear();
}
} |
Change topic keys to match new naming scheme | var Q = require('q'),
utils = require('./utils'),
EventEmitter = require('events').EventEmitter,
actions = require('../static/actions.json');
module.exports.create = function (id, client) {
var instance = new EventEmitter(),
logger = utils.logger(__filename);
instance.id = 'radio.' + id;
/*
This creates methods to send commands, as listed
in `../static/actions.json`.
*/
Object.keys(actions).forEach(function(key, index){
var action = actions[key];
instance[key] = function (params) {
return sendCommandForAction(action, params);
};
});
instance.sendCommandForAction = sendCommandForAction;
client.createAndBindToExchange({
exchangeName: 'radiodan',
topicsKey: 'event.' + instance.id + '.#'
});
client.on('message', function (data) {
instance.emit('message', data);
});
/*
Sends an action to the 'radio.<id>.command' channel
Returns a Promise that resolves on command success or
rejects with an error.
*/
function sendCommandForAction(action, params) {
params = params || {};
params.action = action;
return client.createExchange({ exchangeName: 'radiodan' })
.then(function () {
return sendCommandToExchange(params);
})
.then(null, utils.failedPromiseHandler());
}
function sendCommandToExchange(params) {
return client.sendCommand({
exchangeName : 'radiodan',
topicKey : 'command.' + instance.id,
command : params
});
}
return instance;
};
| var Q = require('q'),
utils = require('./utils'),
EventEmitter = require('events').EventEmitter,
actions = require('../static/actions.json');
module.exports.create = function (id, client) {
var instance = new EventEmitter(),
logger = utils.logger(__filename);
instance.id = 'radio.' + id;
/*
This creates methods to send commands, as listed
in `../static/actions.json`.
*/
Object.keys(actions).forEach(function(key, index){
var action = actions[key];
instance[key] = function (params) {
return sendCommandForAction(action, params);
};
});
instance.sendCommandForAction = sendCommandForAction;
client.createAndBindToExchange({
exchangeName: 'radiodan',
topicsKey: instance.id + '.#'
});
client.on('message', function (data) {
instance.emit('message', data);
});
/*
Sends an action to the 'radio.<id>.command' channel
Returns a Promise that resolves on command success or
rejects with an error.
*/
function sendCommandForAction(action, params) {
params = params || {};
params.action = action;
return client.createExchange({ exchangeName: 'radiodan' })
.then(function () {
return sendCommandToExchange(params);
})
.then(null, utils.failedPromiseHandler());
}
function sendCommandToExchange(params) {
return client.sendCommand({
exchangeName : 'radiodan',
topicKey : instance.id + '.command',
command : params
});
}
return instance;
};
|
Check for the response class | <?php
namespace Plinth\Response;
use Plinth\Dictionary;
class Parser
{
/**
* @param Response $self
* @param string $template
* @param array $templateData
* @param string $path
* @param string $tplExt
* @param Dictionary $dictionary
* @return string
*/
public static function parse($self, $template, $templateData = array(), $path = "", $tplExt = __EXTENSION_PHP, Dictionary $dictionary = null)
{
$fullPath = $path . $template . $tplExt;
if (!file_exists($fullPath)) return false;
/*
* Create shorthand for translating string via the dictionary
*/
if ($dictionary !== null) {
$__ = function () use ($dictionary) {
return call_user_func_array(array($dictionary, 'get'), func_get_args());
};
}
/*
* Push data into variables
*/
if ($self instanceof Response && $self->hasData()) {
$templateData = array_merge($templateData, $self->getData());
}
foreach ($templateData as $cantoverride_key => $cantoverride_value) {
${$cantoverride_key} = $cantoverride_value;
}
unset($cantoverride_key);
unset($cantoverride_value);
ob_start();
require $fullPath;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
} | <?php
namespace Plinth\Response;
use Plinth\Dictionary;
class Parser
{
/**
* @param Response $self
* @param string $template
* @param array $templateData
* @param string $path
* @param string $tplExt
* @param Dictionary $dictionary
* @return string
*/
public static function parse($self, $template, $templateData = array(), $path = "", $tplExt = __EXTENSION_PHP, Dictionary $dictionary = null)
{
$fullPath = $path . $template . $tplExt;
if (!file_exists($fullPath)) return false;
/*
* Create shorthand for translating string via the dictionary
*/
if ($dictionary !== null) {
$__ = function () use ($dictionary) {
return call_user_func_array(array($dictionary, 'get'), func_get_args());
};
}
/*
* Push data into variables
*/
if (method_exists($self, 'hasData') && $self->hasData()) {
$templateData = array_merge($templateData, $self->getData());
}
foreach ($templateData as $cantoverride_key => $cantoverride_value) {
${$cantoverride_key} = $cantoverride_value;
}
unset($cantoverride_key);
unset($cantoverride_value);
ob_start();
require $fullPath;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
} |
Add type markers for ctx objects | import discord
from discord.ext import commands
class Misc:
@commands.command()
async def highfive(self, ctx: commands.Context):
"""
Give Yutu a high-five
"""
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@commands.command()
async def cute(self, ctx: commands.Context, user: discord.Member = None):
"""
Tell someone they are cute!
Tells a user that you think they are cute, if you don't give a user, then Yutu will let you know that you are cute.
"""
if user is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = user
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first,
second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post) | import discord
from discord.ext import commands
class Misc:
@commands.command()
async def highfive(self, ctx):
"""
Give Yutu a high-five
"""
await ctx.send('{0.mention} :pray: {1.mention}'.format(ctx.me, ctx.author))
@commands.command()
async def cute(self, ctx, user: discord.Member = None):
"""
Tell someone they are cute!
Tells a user that you think they are cute, if you don't give a user, then Yutu will let you know that you are cute.
"""
if user is None:
first = ctx.me
second = ctx.author
else:
first = ctx.author
second = user
post = discord.Embed(description='**{0.display_name}** thinks that **{1.display_name}** is cute!'.format(first,
second))
post.set_image(url="https://i.imgur.com/MuVAkV2.gif")
await ctx.send(embed=post) |
Add missing max_length on temporary thumbnail_url migration
Fixes #7323 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailembeds", "0007_populate_hash"),
]
operations = [
migrations.AlterField(
model_name="embed",
name="hash",
field=models.CharField(db_index=True, max_length=32, unique=True),
),
# MySQL needs max length on the unique together fields.
# Drop unique together before alter char to text.
migrations.AlterUniqueTogether(
name="embed",
unique_together=set(),
),
migrations.AlterField(
model_name="embed",
name="url",
field=models.TextField(),
),
# Converting URLField to TextField with a default specified (even with preserve_default=False)
# fails with Django 3.0 and MySQL >=8.0.13 (see https://code.djangoproject.com/ticket/32503) -
# work around this by altering in two stages, first making the URLField non-null then converting
# to TextField
migrations.AlterField(
model_name="embed",
name="thumbnail_url",
field=models.URLField(
blank=True,
default="",
max_length=255,
),
preserve_default=False,
),
migrations.AlterField(
model_name="embed",
name="thumbnail_url",
field=models.TextField(
blank=True,
),
),
]
| from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailembeds", "0007_populate_hash"),
]
operations = [
migrations.AlterField(
model_name="embed",
name="hash",
field=models.CharField(db_index=True, max_length=32, unique=True),
),
# MySQL needs max length on the unique together fields.
# Drop unique together before alter char to text.
migrations.AlterUniqueTogether(
name="embed",
unique_together=set(),
),
migrations.AlterField(
model_name="embed",
name="url",
field=models.TextField(),
),
# Converting URLField to TextField with a default specified (even with preserve_default=False)
# fails with Django 3.0 and MySQL >=8.0.13 (see https://code.djangoproject.com/ticket/32503) -
# work around this by altering in two stages, first making the URLField non-null then converting
# to TextField
migrations.AlterField(
model_name="embed",
name="thumbnail_url",
field=models.URLField(
blank=True,
default="",
),
preserve_default=False,
),
migrations.AlterField(
model_name="embed",
name="thumbnail_url",
field=models.TextField(
blank=True,
),
),
]
|
Remove a check that is probably useless | var replaceAll = function( oldToken ) {
var configs = this;
return {
from: function( string ) {
return {
to: function( newToken ) {
var _token;
var index = -1;
if ( configs.ignoringCase ) {
_token = oldToken.toLowerCase();
while((
index = string
.toLowerCase()
.indexOf(
_token,
index === -1 ? 0 : index + newToken.length
)
) !== -1 ) {
string = string
.substring( 0, index ) +
newToken +
string.substring( index + newToken.length );
}
return string;
}
return string.split( oldToken ).join( newToken );
}
};
},
ignoreCase: function() {
return replaceAll.call({
ignoringCase: true
}, oldToken );
}
};
};
module.exports = {
all: replaceAll
};
| var replaceAll = function( oldToken ) {
var configs = this;
return {
from: function( string ) {
return {
to: function( newToken ) {
var _token;
var index = -1;
if ( configs.ignoringCase ) {
_token = oldToken.toLowerCase();
while((
index = string
.toLowerCase()
.indexOf(
_token,
index >= 0 ?
index + newToken.length : 0
)
) !== -1 ) {
string = string
.substring( 0, index ) +
newToken +
string.substring( index + newToken.length );
}
return string;
}
return string.split( oldToken ).join( newToken );
}
};
},
ignoreCase: function() {
return replaceAll.call({
ignoringCase: true
}, oldToken );
}
};
};
module.exports = {
all: replaceAll
};
|
Use start of month/year dates instead of end. | def get_monthly_anomaly(ts, start, end):
"""
Get monthly anomaly.
Monthly anomalies calculated from the mean of the data between the specified start and end dates.
:param ts: Pandas timeseries, will be converted to monthly.
:type ts: pandas.TimeSeries
:param start: Start date to calculated mean from.
:type start: datetime.datetime
:param end: End date to calculated mean from.
:type end: datetime.datetime
:returns: pandas.TimeSeries -- Monthly anomalies.
"""
monthly = ts.resample('MS')
base = monthly.ix[start:end]
mean = base.groupby(base.index.month).mean()
for month in range(1,13):
monthly.ix[monthly.index.month == month] -= mean.ix[mean.index == month].values[0]
return monthly
def get_annual_anomaly(ts, start, end):
"""
Get annual anomaly.
Annual anomalies calculated from the mean of the data between the specified start and end dates.
:param ts: Pandas timeseries, will be converted to annual.
:type ts: pandas.TimeSeries
:param start: Start date to calculated mean from.
:type start: datetime.datetime
:param end: End date to calculated mean from.
:type end: datetime.datetime
:returns: pandas.TimeSeries -- Annual anomalies.
"""
annual = ts.resample('AS')
base = annual.ix[start:end]
mean = base.groupby(base.index.year).mean().mean()
annual -= mean
return annual
| def get_monthly_anomaly(ts, start, end):
"""
Get monthly anomaly.
Monthly anomalies calculated from the mean of the data between the specified start and end dates.
:param ts: Pandas timeseries, will be converted to monthly.
:type ts: pandas.TimeSeries
:param start: Start date to calculated mean from.
:type start: datetime.datetime
:param end: End date to calculated mean from.
:type end: datetime.datetime
:returns: pandas.TimeSeries -- Monthly anomalies.
"""
monthly = ts.asfreq('M')
base = monthly.ix[start:end]
mean = base.groupby(base.index.month).mean()
for month in range(1,13):
monthly.ix[monthly.index.month == month] -= mean.ix[mean.index == month].values[0]
return monthly
def get_annual_anomaly(ts, start, end):
"""
Get annual anomaly.
Annual anomalies calculated from the mean of the data between the specified start and end dates.
:param ts: Pandas timeseries, will be converted to annual.
:type ts: pandas.TimeSeries
:param start: Start date to calculated mean from.
:type start: datetime.datetime
:param end: End date to calculated mean from.
:type end: datetime.datetime
:returns: pandas.TimeSeries -- Annual anomalies.
"""
annual = ts.asfreq('A')
base = annual.ix[start:end]
mean = base.groupby(base.index.year).mean().mean()
annual -= mean
return annual
|
Update paramiko dependency for vulnerability | from setuptools import setup
setup(
name='cb-event-duplicator',
version='1.2.0',
packages=['cbopensource', 'cbopensource.tools', 'cbopensource.tools.eventduplicator'],
url='https://github.com/carbonblack/cb-event-duplicator',
license='MIT',
author='Bit9 + Carbon Black Developer Network',
author_email='[email protected]',
description='Extract events from one Carbon Black server and send them to another server ' +
'- useful for demo/testing purposes',
install_requires=[
'requests==2.7.0',
'paramiko<2.0',
'psycopg2==2.6.1'
],
entry_points={
'console_scripts': ['cb-event-duplicator=cbopensource.tools.eventduplicator.data_migration:main']
},
classifiers=[
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
],
keywords='carbonblack',
)
| from setuptools import setup
setup(
name='cb-event-duplicator',
version='1.2.0',
packages=['cbopensource', 'cbopensource.tools', 'cbopensource.tools.eventduplicator'],
url='https://github.com/carbonblack/cb-event-duplicator',
license='MIT',
author='Bit9 + Carbon Black Developer Network',
author_email='[email protected]',
description='Extract events from one Carbon Black server and send them to another server ' +
'- useful for demo/testing purposes',
install_requires=[
'requests==2.7.0',
'paramiko==1.15.2',
'psycopg2==2.6.1'
],
entry_points={
'console_scripts': ['cb-event-duplicator=cbopensource.tools.eventduplicator.data_migration:main']
},
classifiers=[
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
],
keywords='carbonblack',
)
|
Fix Logout Dialog Recreating Home
The logout dialog was launching a new instance of the home
activity every time it was dismissed by touching outside the
dialog instead of through the proper Cancel button. This
commit is just a quick fix to fix that. | package net.somethingdreadful.MAL;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import com.actionbarsherlock.app.SherlockDialogFragment;
public class LogoutConfirmationDialogFragment extends SherlockDialogFragment {
public LogoutConfirmationDialogFragment() {}
public interface LogoutConfirmationDialogListener {
void onLogoutConfirmed();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog));
builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
((Home) getActivity()).onLogoutConfirmed();
dismiss();
}
})
.setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismiss();
}
})
.setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message);
return builder.create();
}
@Override
public void onDismiss(DialogInterface dialog) {}
@Override
public void onCancel(DialogInterface dialog) {
// startActivity(new Intent(getActivity(), Home.class)); //Relaunching Home without needing to, causes bad things
this.dismiss();
}
}
| package net.somethingdreadful.MAL;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import com.actionbarsherlock.app.SherlockDialogFragment;
public class LogoutConfirmationDialogFragment extends SherlockDialogFragment {
public LogoutConfirmationDialogFragment() {}
public interface LogoutConfirmationDialogListener {
void onLogoutConfirmed();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialog));
builder.setPositiveButton(R.string.dialog_logout_label_confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
((Home) getActivity()).onLogoutConfirmed();
dismiss();
}
})
.setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismiss();
}
})
.setTitle(R.string.dialog_logout_title).setMessage(R.string.dialog_logout_message);
return builder.create();
}
@Override
public void onDismiss(DialogInterface dialog) {}
@Override
public void onCancel(DialogInterface dialog) {
startActivity(new Intent(getActivity(), Home.class));
this.dismiss();
}
}
|
Add plugin count ip using mongo aggregation framework | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
sys.path.insert(0, "..")
from libs.manager import Plugin
from bson.code import Code
class CountIPNew(Plugin):
def __init__(self, **kwargs):
self.keywords = ['counter', 'ip']
self.result = {}
def process(self, **kwargs):
collection = kwargs['collection']
condition = {}
if 'condition' in kwargs:
condition = kwargs['condition']
reducer = Code("""
function(curr,result){
result.count++;
}
""")
host_result = collection.group(
key = {"host":1},
condition = condition,
initial = {"count":0},
reduce = reducer)
self.result[collection.name] = host_result
# mongo shell command
#db.runCommand({group:{ ns:"www_ename_cn_access", key:{host:1}, $reduce:function(curr,result){result.times += 1}, initial:{"times":0}}})
#db.news_ename_cn_access.group({key:{host:1},reduce:function(curr,result){result.times += 1;},initial:{times:0}})
def report(self, **kwargs):
print '== IP counter =='
print self.result
| #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
sys.path.insert(0, "..")
from libs.manager import Plugin
class CountIPNew(Plugin):
def __init__(self, **kwargs):
self.keywords = ['counter', 'ip']
self.total_ip = 0
self.ip_dict = {}
def __process_doc(self, **kwargs):
if 'host' in kwargs:
if self.ip_dict.has_key(kwargs['host']):
self.ip_dict[kwargs['host']] += 1
else:
self.ip_dict[kwargs['host']] = 1
self.total_ip += 1
def process(self, **kwargs):
collection = kwargs['collection']
condition = {}
if 'condition' in kwargs:
condition = kwargs['condition']
# Do more HERE
for log_doc in collection.find(condition):
self.__process_doc(**log_doc)
def report(self, **kwargs):
print '== IP counter =='
print "HTTP IPs: %d" % self.total_ip
for ip in self.ip_dict.keys():
print "%s: %d" % (ip, self.ip_dict[ip])
|
Replace real typograph with mock | <?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;
use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
class TextareaTypeExtensionTest extends TypeTestCase
{
public function testSubmitWithTypography()
{
$form = $this->factory->create('textarea', null, array(
'typography' => true
));
$form->submit('Типограф - это здорово!');
$this->assertEquals('Типограф — это здорово!', $form->getData());
}
public function testSubmitWithoutTypography()
{
$form = $this->factory->create('textarea');
$form->submit('Типограф - это здорово!');
$this->assertEquals('Типограф - это здорово!', $form->getData());
}
protected function getExtensions()
{
$typograph = $this->getMock('Fsv\TypographyBundle\Typograph\TypographInterface');
$typograph
->expects($this->any())
->method('apply')
->with('Типограф - это здорово!')
->will($this->returnValue('Типограф — это здорово!'))
;
return array(
new PreloadedExtension(
array(),
array(
'textarea' => array(new TextareaTypeExtension($typograph))
)
)
);
}
}
| <?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;
use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension;
use Fsv\TypographyBundle\Typograph\MdashTypograph;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
class TextareaTypeExtensionTest extends TypeTestCase
{
public function testSubmitWithTypography()
{
$form = $this->factory->create('textarea', null, array(
'typography' => true
));
$form->submit('Типограф - это здорово!');
$this->assertEquals('Типограф — это здорово!', $form->getData());
}
public function testSubmitWithoutTypography()
{
$form = $this->factory->create('textarea');
$form->submit('Типограф - это здорово!');
$this->assertEquals('Типограф - это здорово!', $form->getData());
}
protected function getExtensions()
{
return array(
new PreloadedExtension(
array(),
array(
'textarea' => array(
new TextareaTypeExtension(new MdashTypograph(array('Text.paragraphs' => 'off')))
)
)
)
);
}
}
|
Fix mistake in Dynamo table name | 'use strict';
const Bluebird = require('bluebird');
const Dynasty = require('../model');
module.exports = {
findTrigger: function (currentIntent) {
if (!currentIntent) {
return Bluebird.reject(new Error('currentIntent is required'));
}
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-triggers`).find(currentIntent.name)
.tap(triggers => {
if (!triggers) {
return Bluebird.reject(new Error('ObjectNotFoundError'));
}
});
},
findLevel: function (level) {
if (!level) {
return Bluebird.reject(new Error('event and callback are required'));
}
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-feeling-score`).find(level)
.tap(feeling => {
if (!feeling) {
return Bluebird.reject(new Error('ObjectNotFoundError'));
}
});
},
findAllDistractions: function (event) {
if (!event) {
return Bluebird.reject(new Error('event is required'));
}
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-distractions`).scan()
.tap(distractions => {
if (!distractions) {
return Bluebird.reject(new Error('ObjectNotFoundError'));
}
});
},
findDynamic: function (type) {
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-dynamic-message`).find(type);
}
};
| 'use strict';
const Bluebird = require('bluebird');
const Dynasty = require('../model');
module.exports = {
findTrigger: function (currentIntent) {
if (!currentIntent) {
return Bluebird.reject(new Error('currentIntent is required'));
}
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-triggers`).find(currentIntent.name)
.tap(triggers => {
if (!triggers) {
return Bluebird.reject(new Error('ObjectNotFoundError'));
}
});
},
findLevel: function (level) {
if (!level) {
return Bluebird.reject(new Error('event and callback are required'));
}
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-feeling`).find(level)
.tap(feeling => {
if (!feeling) {
return Bluebird.reject(new Error('ObjectNotFoundError'));
}
});
},
findAllDistractions: function (event) {
if (!event) {
return Bluebird.reject(new Error('event is required'));
}
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-distractions`).scan()
.tap(distractions => {
if (!distractions) {
return Bluebird.reject(new Error('ObjectNotFoundError'));
}
});
},
findDynamic: function (type) {
return Dynasty.table(`${process.env.NODE_ENV}-nicbot-dynamic-message`).find(type);
}
};
|
Move zoom height functionality to separate function. | # Sample extension: zoom a window to maximum height
import re
import sys
class ZoomHeight:
menudefs = [
('windows', [
('_Zoom Height', '<<zoom-height>>'),
])
]
windows_keydefs = {
'<<zoom-height>>': ['<Alt-F2>'],
}
unix_keydefs = {
'<<zoom-height>>': ['<Control-x><Control-z>'],
}
def __init__(self, editwin):
self.editwin = editwin
def zoom_height_event(self, event):
top = self.editwin.top
zoom_height(top)
def zoom_height(top):
geom = top.wm_geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
if not m:
top.bell()
return
width, height, x, y = map(int, m.groups())
newheight = top.winfo_screenheight()
if sys.platform == 'win32':
newy = 0
newheight = newheight - 72
else:
newy = 24
newheight = newheight - 96
if height >= newheight:
newgeom = ""
else:
newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
top.wm_geometry(newgeom)
| # Sample extension: zoom a window to maximum height
import re
import sys
class ZoomHeight:
menudefs = [
('windows', [
('_Zoom Height', '<<zoom-height>>'),
])
]
windows_keydefs = {
'<<zoom-height>>': ['<Alt-F2>'],
}
unix_keydefs = {
'<<zoom-height>>': ['<Control-x><Control-z>'],
}
def __init__(self, editwin):
self.editwin = editwin
def zoom_height_event(self, event):
top = self.editwin.top
geom = top.wm_geometry()
m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
if not m:
top.bell()
return
width, height, x, y = map(int, m.groups())
newheight = top.winfo_screenheight()
if sys.platform == 'win32':
newy = 0
newheight = newheight - 72
else:
newy = 24
newheight = newheight - 96
if height >= newheight:
newgeom = ""
else:
newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
top.wm_geometry(newgeom)
|
Fix ImportError when loading change_(prev|next) module on windows | import sublime_plugin
try:
from .view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class VcsGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
for line in lines:
if line > last_line+1:
blocks.append(line)
last_line = line
return blocks
def run(self):
view = self.window.active_view()
inserted, modified, deleted = ViewCollection.diff(view)
inserted = self.lines_to_blocks(inserted)
modified = self.lines_to_blocks(modified)
all_changes = sorted(inserted + modified + deleted)
if all_changes:
row, col = view.rowcol(view.sel()[0].begin())
current_row = row + 1
line = self.jump(all_changes, current_row)
self.window.active_view().run_command("goto_line", {"line": line})
class VcsGutterNextChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in all_changes
if change > current_row), all_changes[0])
class VcsGutterPrevChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in reversed(all_changes)
if change < current_row), all_changes[-1])
| import sublime_plugin
try:
from VcsGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class VcsGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
for line in lines:
if line > last_line+1:
blocks.append(line)
last_line = line
return blocks
def run(self):
view = self.window.active_view()
inserted, modified, deleted = ViewCollection.diff(view)
inserted = self.lines_to_blocks(inserted)
modified = self.lines_to_blocks(modified)
all_changes = sorted(inserted + modified + deleted)
if all_changes:
row, col = view.rowcol(view.sel()[0].begin())
current_row = row + 1
line = self.jump(all_changes, current_row)
self.window.active_view().run_command("goto_line", {"line": line})
class VcsGutterNextChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in all_changes
if change > current_row), all_changes[0])
class VcsGutterPrevChangeCommand(VcsGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in reversed(all_changes)
if change < current_row), all_changes[-1])
|
Revert "Improve wording and add comment for realm switching." | 'use strict';
const {remote} = require('electron');
document.getElementById('close-button').addEventListener('click', function (e) {
let window = remote.getCurrentWindow();
window.close();
});
// document.getElementById('pic').style.display ='block';
function addDomain() {
const request = require('request');
const ipcRenderer = require('electron').ipcRenderer;
const JsonDB = require('node-json-db');
const db = new JsonDB('domain', true, true);
document.getElementById('main').innerHTML = 'checking...'
document.getElementById('pic').style.display ='block';
let newDomain = document.getElementById('url').value;
newDomain = newDomain.replace(/^https?:\/\//,'')
const domain = 'https://' + newDomain;
const checkDomain = domain + '/static/audio/zulip.ogg';
request(checkDomain, function (error, response, body) {
if (!error && response.statusCode !== 404) {
document.getElementById('pic').style.display ='none';
document.getElementById('main').innerHTML = 'Add'
document.getElementById('urladded').innerHTML = newDomain + ' Added';
db.push('/domain', domain);
ipcRenderer.send('new-domain', domain);
}
else {
document.getElementById('pic').style.display ='none';
document.getElementById('main').innerHTML = 'Add'
document.getElementById('urladded').innerHTML = "Not a vaild Zulip server";
}
})
}
| 'use strict';
const {remote} = require('electron');
document.getElementById('close-button').addEventListener('click', function (e) {
let window = remote.getCurrentWindow();
window.close();
});
// document.getElementById('pic').style.display ='block';
function addDomain() {
const request = require('request');
const ipcRenderer = require('electron').ipcRenderer;
const JsonDB = require('node-json-db');
const db = new JsonDB('domain', true, true);
document.getElementById('main').innerHTML = 'checking...'
document.getElementById('pic').style.display ='block';
let newDomain = document.getElementById('url').value;
newDomain = newDomain.replace(/^https?:\/\//,'')
const domain = 'https://' + newDomain;
const checkDomain = domain + '/static/audio/zulip.ogg';
// Dialog box for the user to switch realms.
request(checkDomain, function (error, response, body) {
if (!error && response.statusCode !== 404) {
document.getElementById('pic').style.display ='none';
document.getElementById('main').innerHTML = 'Switch'
document.getElementById('urladded').innerHTML = 'Switched to ' + newDomain;
db.push('/domain', domain);
ipcRenderer.send('new-domain', domain);
}
else {
document.getElementById('pic').style.display ='none';
document.getElementById('main').innerHTML = 'Switch'
document.getElementById('urladded').innerHTML = "Not a valid Zulip server.";
}
})
}
|
Refactoring: Replace single quotes -> double quotes, var -> const | const loaders = require("./loaders");
const preloaders = require("./preloaders");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
module.exports = {
context: path.join(__dirname, ".."),
entry: ["./src/index.ts"],
output: {
filename: "build.js",
path: "dist"
},
devtool: "",
resolve: {
root: __dirname,
extensions: [".ts", ".js", ".json"]
},
resolveLoader: {
modulesDirectories: ["node_modules"]
},
plugins: [
new webpack.optimize.UglifyJsPlugin(
{
warning: false,
mangle: true,
comments: false
}
),
new HtmlWebpackPlugin({
template: "./src/index.html",
inject: "body",
hash: true
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"window.jquery": "jquery"
})
],
module:{
preLoaders:preloaders,
loaders: loaders
},
tslint: {
emitErrors: true,
failOnHint: true
}
};
| var loaders = require("./loaders");
var preloaders = require("./preloaders");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: ['./src/index.ts'],
output: {
filename: 'build.js',
path: 'dist'
},
devtool: '',
resolve: {
root: __dirname,
extensions: ['', '.ts', '.js', '.json']
},
resolveLoader: {
modulesDirectories: ["node_modules"]
},
plugins: [
new webpack.optimize.UglifyJsPlugin(
{
warning: false,
mangle: true,
comments: false
}
),
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body',
hash: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.jquery': 'jquery'
})
],
module:{
preLoaders:preloaders,
loaders: loaders
},
tslint: {
emitErrors: true,
failOnHint: true
}
};
|
Use execute script to reload page rather than chrome.tabs.reload() as chrome.runtime.reload() causes the previous operation to abort. | const filesInDirectory = dir => new Promise (resolve =>
dir.createReader ().readEntries (entries =>
Promise.all (entries.filter (e => e.name[0] !== '.').map (e =>
e.isDirectory
? filesInDirectory (e)
: new Promise (resolve => e.file (resolve))
))
.then (files => [].concat (...files))
.then (resolve)
)
)
const timestampForFilesInDirectory = dir =>
filesInDirectory (dir).then (files =>
files.map (f => f.name + f.lastModifiedDate).join ())
const reload = () => {
chrome.tabs.query ({ active: true, currentWindow: true }, tabs => { // NB: see https://github.com/xpl/crx-hotreload/issues/5
if (tabs[0]) {
chrome.tabs.executeScript(tabs[0].id, {code: 'setTimeout(function () { location.reload(); }, 300)'}, function() {});
}
chrome.runtime.reload ()
})
}
const watchChanges = (dir, lastTimestamp) => {
timestampForFilesInDirectory (dir).then (timestamp => {
if (!lastTimestamp || (lastTimestamp === timestamp)) {
setTimeout (() => watchChanges (dir, timestamp), 1000) // retry after 1s
} else {
reload ()
}
})
}
chrome.management.getSelf (self => {
if (self.installType === 'development') {
chrome.runtime.getPackageDirectoryEntry (dir => watchChanges (dir))
}
})
| const filesInDirectory = dir => new Promise (resolve =>
dir.createReader ().readEntries (entries =>
Promise.all (entries.filter (e => e.name[0] !== '.').map (e =>
e.isDirectory
? filesInDirectory (e)
: new Promise (resolve => e.file (resolve))
))
.then (files => [].concat (...files))
.then (resolve)
)
)
const timestampForFilesInDirectory = dir =>
filesInDirectory (dir).then (files =>
files.map (f => f.name + f.lastModifiedDate).join ())
const reload = () => {
chrome.tabs.query ({ active: true, currentWindow: true }, tabs => { // NB: see https://github.com/xpl/crx-hotreload/issues/5
if (tabs[0]) { chrome.tabs.reload (tabs[0].id) }
{
setTimeout(function () {
chrome.runtime.reload ()
}, 500)
}
})
}
const watchChanges = (dir, lastTimestamp) => {
timestampForFilesInDirectory (dir).then (timestamp => {
if (!lastTimestamp || (lastTimestamp === timestamp)) {
setTimeout (() => watchChanges (dir, timestamp), 1000) // retry after 1s
} else {
reload ()
}
})
}
chrome.management.getSelf (self => {
if (self.installType === 'development') {
chrome.runtime.getPackageDirectoryEntry (dir => watchChanges (dir))
}
})
|
Sort projects on /docs page by name vs. id
Allows for a more natural, intuitive ordering.
See #367 | package sagan.docs.support;
import sagan.projects.Project;
import sagan.projects.support.ProjectMetadataService;
import sagan.support.nav.NavSection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@Controller
@RequestMapping("/docs")
@NavSection("docs")
class DocsController {
private ProjectMetadataService service;
@Autowired
public DocsController(ProjectMetadataService service) {
this.service = service;
}
@RequestMapping(value = "", method = { GET, HEAD })
public String listProjects(Model model) {
model.addAttribute("activeProjects", nonAggregatorsForCategory("active"));
model.addAttribute("atticProjects", nonAggregatorsForCategory("attic"));
model.addAttribute("incubatorProjects", nonAggregatorsForCategory("incubator"));
return "docs/index";
}
private List<Project> nonAggregatorsForCategory(String category) {
return service.getProjectsForCategory(category).stream()
.filter(project -> !project.isAggregator())
.sorted((p1, p2) -> p1.getName().compareToIgnoreCase(p2.getName()))
.collect(Collectors.toList());
}
}
| package sagan.docs.support;
import sagan.projects.Project;
import sagan.projects.support.ProjectMetadataService;
import sagan.support.nav.NavSection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@Controller
@RequestMapping("/docs")
@NavSection("docs")
class DocsController {
private ProjectMetadataService service;
@Autowired
public DocsController(ProjectMetadataService service) {
this.service = service;
}
@RequestMapping(value = "", method = { GET, HEAD })
public String listProjects(Model model) {
model.addAttribute("activeProjects", nonAggregatorsForCategory("active"));
model.addAttribute("atticProjects", nonAggregatorsForCategory("attic"));
model.addAttribute("incubatorProjects", nonAggregatorsForCategory("incubator"));
return "docs/index";
}
private List<Project> nonAggregatorsForCategory(String category) {
return service.getProjectsForCategory(category).stream()
.filter(project -> !project.isAggregator())
.sorted((p1, p2) -> p1.getId().compareToIgnoreCase(p2.getId()))
.collect(Collectors.toList());
}
}
|
Add bigautofield default in app conf | import importlib
from typing import List, Tuple, Union
from django.utils.translation import gettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
default_auto_field = "django.db.models.BigAutoField"
verbose_name = _("Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from .tracking import mqueue_tracker
registered_models: Union[
Tuple[str, List[str]], List[Union[str, List[str]]]
] = getattr(settings, "MQUEUE_AUTOREGISTER", [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split(".")
path = ".".join(modsplit[:-1])
modname = ".".join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level) # type: ignore
except ImportError as e:
msg = "ERROR from Django Mqueue : can not import model "
msg += modpath
print(msg)
raise (e)
# watchers
from .watchers import init_watchers
from .conf import WATCH
init_watchers(WATCH)
| import importlib
from typing import List, Tuple, Union
from django.utils.translation import ugettext_lazy as _
from django.apps import AppConfig
class MqueueConfig(AppConfig):
name = "mqueue"
verbose_name = _(u"Events queue")
def ready(self):
# models registration from settings
from django.conf import settings
from .tracking import mqueue_tracker
registered_models: Union[
Tuple[str, List[str]], List[Union[str, List[str]]]
] = getattr(settings, "MQUEUE_AUTOREGISTER", [])
for modtup in registered_models:
modpath = modtup[0]
level = modtup[1]
modsplit = modpath.split(".")
path = ".".join(modsplit[:-1])
modname = ".".join(modsplit[-1:])
try:
module = importlib.import_module(path)
model = getattr(module, modname)
mqueue_tracker.register(model, level) # type: ignore
except ImportError as e:
msg = "ERROR from Django Mqueue : can not import model "
msg += modpath
print(msg)
raise (e)
# watchers
from .watchers import init_watchers
from .conf import WATCH
init_watchers(WATCH)
|
Use request.data in DRF >= 3 | from distutils.version import StrictVersion
import rest_framework
from rest_framework import serializers
from django.forms import widgets
DRF_VERSION_INFO = StrictVersion(rest_framework.VERSION).version
DRF2 = DRF_VERSION_INFO[0] == 2
DRF3 = DRF_VERSION_INFO[0] == 3
if DRF2:
class Serializer(serializers.Serializer):
pass
class PasswordField(serializers.CharField):
widget = widgets.PasswordInput
else:
class Serializer(serializers.Serializer):
@property
def object(self):
return self.validated_data
class PasswordField(serializers.CharField):
def __init__(self, *args, **kwargs):
if 'style' not in kwargs:
kwargs['style'] = {'input_type': 'password'}
else:
kwargs['style']['input_type'] = 'password'
super(PasswordField, self).__init__(*args, **kwargs)
def get_user_model():
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return User
def get_username_field():
try:
username_field = get_user_model().USERNAME_FIELD
except:
username_field = 'username'
return username_field
def get_username(user):
try:
username = user.get_username()
except AttributeError:
username = user.username
return username
def get_request_data(request):
if DRF2:
data = request.DATA
else:
data = request.data
return data
| from distutils.version import StrictVersion
import rest_framework
from rest_framework import serializers
from django.forms import widgets
if StrictVersion(rest_framework.VERSION) < StrictVersion('3.0.0'):
class Serializer(serializers.Serializer):
pass
class PasswordField(serializers.CharField):
widget = widgets.PasswordInput
else:
class Serializer(serializers.Serializer):
@property
def object(self):
return self.validated_data
class PasswordField(serializers.CharField):
def __init__(self, *args, **kwargs):
if 'style' not in kwargs:
kwargs['style'] = {'input_type': 'password'}
else:
kwargs['style']['input_type'] = 'password'
super(PasswordField, self).__init__(*args, **kwargs)
def get_user_model():
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return User
def get_username_field():
try:
username_field = get_user_model().USERNAME_FIELD
except:
username_field = 'username'
return username_field
def get_username(user):
try:
username = user.get_username()
except AttributeError:
username = user.username
return username
def get_request_data(request):
if getattr(request, 'data', None):
data = request.data
else:
# DRF < 3.2
data = request.DATA
return data
|
Enable pretty Forge checkbox fields. | <!DOCTYPE html>
<html lang="en" class="modernizr-label-click modernizr-checked">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rogue</title>
<link rel="icon" type="image/png" href="http://twooter.biz/Gifs/tonguecat.png">
<link rel="stylesheet" href="{{ elixir('app.css', 'dist') }}">
</head>
<body>
@if (Session::has('status'))
<div class="messages">{{ Session::get('status') }}</div>
@endif
@if ($errors->any())
<div class="messages">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="chrome">
<div class="wrapper">
@include('layouts.nav')
<div class="container">
@yield('main_content')
</div>
</div>
</div>
{{ isset($state) ? scriptify($state) : scriptify() }}
<script src="{{ elixir('app.js', 'dist') }}"></script>
</body>
{{ scriptify($auth, 'AUTH') }}
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Rogue</title>
<link rel="icon" type="image/png" href="http://twooter.biz/Gifs/tonguecat.png">
<link rel="stylesheet" href="{{ elixir('app.css', 'dist') }}">
</head>
<body>
@if (Session::has('status'))
<div class="messages">{{ Session::get('status') }}</div>
@endif
@if ($errors->any())
<div class="messages">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="chrome">
<div class="wrapper">
@include('layouts.nav')
<div class="container">
@yield('main_content')
</div>
</div>
</div>
{{ isset($state) ? scriptify($state) : scriptify() }}
<script src="{{ elixir('app.js', 'dist') }}"></script>
</body>
{{ scriptify($auth, 'AUTH') }}
</html>
|
Validate with sequential random state | import sklearn.cross_validation
class Backend(object):
def __init__(self):
self.dataset_id = 0
self.random_id = 0
self.dataset = None
self.model = None
def load(self, dataset):
self.model = None
self.dataset_id += 1
self.dataset = dataset
self._data = dataset['data']
self._target = dataset['target']
return True
def loaded(self):
return (self.dataset is not None)
def fit(self):
if not self.loaded():
return False
model = self.classifier()
model.fit(self._data, self._target)
self.model = model
return True
def trained(self):
return (self.model is not None)
def validate(self, test_size = 0.2):
if not self.loaded():
return
self.random_id += 1
model = self.classifier()
X_train, X_test, y_train, y_test = sklearn.cross_validation.train_test_split(
self._data, self._target, test_size = test_size, random_state = self.random_id
)
model.fit(X_train, y_train)
return [model.score(X_test, y_test)]
def predict(self, value):
return self.model.predict(value)
| import sklearn.cross_validation
class Backend(object):
def __init__(self):
self.dataset_id = 0
self.dataset = None
self.model = None
def load(self, dataset):
self.model = None
self.dataset_id += 1
self.dataset = dataset
self._data = dataset['data']
self._target = dataset['target']
return True
def loaded(self):
return (self.dataset is not None)
def fit(self):
if not self.loaded():
return False
model = self.classifier()
model.fit(self._data, self._target)
self.model = model
return True
def trained(self):
return (self.model is not None)
def validate(self, test_size = 0.2, random_state = 0):
if not self.loaded():
return
model = self.classifier()
X_train, X_test, y_train, y_test = sklearn.cross_validation.train_test_split(
self._data, self._target, test_size = test_size, random_state = random_state
)
model.fit(X_train, y_train)
return [model.score(X_test, y_test)]
def predict(self, value):
return self.model.predict(value)
|
Add more test cases to verify transformer behavior | """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError raised when no basestring value is passed."""
self.assertRaises(AssertionError, degree_decimal_str_transform, 0)
self.assertRaises(AssertionError, degree_decimal_str_transform, 1.23)
self.assertRaises(AssertionError, degree_decimal_str_transform, True)
def test_no_digit(self):
"""AssertionError raised when other characters than digits."""
self.assertRaises(AssertionError, degree_decimal_str_transform, '.')
self.assertRaises(AssertionError, degree_decimal_str_transform, '+')
self.assertRaises(AssertionError, degree_decimal_str_transform, '-')
def test_length(self):
"""AssertionError when more characters than expected passed."""
self.assertRaises(
AssertionError, degree_decimal_str_transform, '123456789')
def test_point_insertion(self):
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
'12.345678',
)
self.assertEqual(
degree_decimal_str_transform('1234567'),
'1.234567',
)
self.assertEqual(
degree_decimal_str_transform('123456'),
'0.123456',
)
self.assertEqual(
degree_decimal_str_transform('12345'),
'0.012345',
)
| """Data transformation utilities test cases."""
import unittest
from datagrid_gtk3.utils.transformations import degree_decimal_str_transform
class DegreeDecimalStrTransformTest(unittest.TestCase):
"""Degree decimal string transformation test case."""
def test_no_basestring(self):
"""AssertionError raised when no basestring value is passed."""
self.assertRaises(AssertionError, degree_decimal_str_transform, 0)
self.assertRaises(AssertionError, degree_decimal_str_transform, 1.23)
self.assertRaises(AssertionError, degree_decimal_str_transform, True)
def test_no_digit(self):
"""AssertionError raised when other characters than digits."""
self.assertRaises(AssertionError, degree_decimal_str_transform, '.')
self.assertRaises(AssertionError, degree_decimal_str_transform, '+')
self.assertRaises(AssertionError, degree_decimal_str_transform, '-')
def test_length(self):
"""AssertionError when more characters than expected passed."""
self.assertRaises(
AssertionError, degree_decimal_str_transform, '123456789')
def test_point_insertion(self):
"""Decimal point is inserted in the expected location."""
self.assertEqual(
degree_decimal_str_transform('12345678'),
'12.345678',
)
self.assertEqual(
degree_decimal_str_transform('123456'),
'0.123456',
)
|
Save output for every run | import os
import statistics
from cref.structure import rmsd
from cref.app.terminal import download_pdb, download_fasta, predict_fasta
pdbs = ['1zdd', '1gab']
runs = 5
fragment_sizes = range(5, 13, 2)
number_of_clusters = range(4, 20, 1)
for pdb in pdbs:
output_dir = 'predictions/evaluation/{}/'.format(pdb)
try:
os.mkdir(output_dir)
except FileExistsError as e:
print(e)
for fragment_size in fragment_sizes:
fasta_file = output_dir + pdb + '.fasta'
download_fasta(pdb, fasta_file)
for n in number_of_clusters:
rmsds = []
for run in range(runs):
params = {
'pdb': pdb,
'fragment_size': fragment_size,
'number_of_clusters': n
}
prediction_output = output_dir + str(run)
os.mkdir(prediction_output)
output_files = predict_fasta(fasta_file, prediction_output, params)
predicted_structure = output_files[0]
filepath = os.path.join(
os.path.dirname(predicted_structure),
'experimental_structure.pdb'
)
experimental_structure = download_pdb(pdb, filepath)
rmsds.append(rmsd(predicted_structure, experimental_structure))
print(pdb, fragment_size, n, statistics.mean(rmsds), statistics.pstdev(rmsds))
| import os
import statistics
from cref.structure import rmsd
from cref.app.terminal import download_pdb, download_fasta, predict_fasta
pdbs = ['1zdd', '1gab']
runs = 100
fragment_sizes = range(5, 13, 2)
number_of_clusters = range(4, 20, 1)
for pdb in pdbs:
output_dir = 'predictions/evaluation/{}/'.format(pdb)
try:
os.mkdir(output_dir)
except FileExistsError as e:
print(e)
for fragment_size in fragment_sizes:
fasta_file = output_dir + pdb + '.fasta'
download_fasta(pdb, fasta_file)
for n in number_of_clusters:
rmsds = []
for run in range(runs):
params = {
'pdb': pdb,
'fragment_size': fragment_size,
'number_of_clusters': n
}
output_files = predict_fasta(fasta_file, output_dir, params)
predicted_structure = output_files[0]
filepath = os.path.join(
os.path.dirname(predicted_structure),
'experimental_structure.pdb'
)
experimental_structure = download_pdb(pdb, filepath)
rmsds.append(rmsd(predicted_structure, experimental_structure))
print(pdb, fragment_size, n, statistics.mean(rmsds), statistics.pstdev(rmsds))
|
Fix delete method on RateLimiter's cache storage | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\RateLimiter\Storage;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\RateLimiter\LimiterStateInterface;
/**
* @author Wouter de Jong <[email protected]>
*
* @experimental in 5.2
*/
class CacheStorage implements StorageInterface
{
private $pool;
public function __construct(CacheItemPoolInterface $pool)
{
$this->pool = $pool;
}
public function save(LimiterStateInterface $limiterState): void
{
$cacheItem = $this->pool->getItem(sha1($limiterState->getId()));
$cacheItem->set($limiterState);
if (null !== ($expireAfter = $limiterState->getExpirationTime())) {
$cacheItem->expiresAfter($expireAfter);
}
$this->pool->save($cacheItem);
}
public function fetch(string $limiterStateId): ?LimiterStateInterface
{
$cacheItem = $this->pool->getItem(sha1($limiterStateId));
$value = $cacheItem->get();
if ($value instanceof LimiterStateInterface) {
return $value;
}
return null;
}
public function delete(string $limiterStateId): void
{
$this->pool->deleteItem(sha1($limiterStateId));
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\RateLimiter\Storage;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\RateLimiter\LimiterStateInterface;
/**
* @author Wouter de Jong <[email protected]>
*
* @experimental in 5.2
*/
class CacheStorage implements StorageInterface
{
private $pool;
public function __construct(CacheItemPoolInterface $pool)
{
$this->pool = $pool;
}
public function save(LimiterStateInterface $limiterState): void
{
$cacheItem = $this->pool->getItem(sha1($limiterState->getId()));
$cacheItem->set($limiterState);
if (null !== ($expireAfter = $limiterState->getExpirationTime())) {
$cacheItem->expiresAfter($expireAfter);
}
$this->pool->save($cacheItem);
}
public function fetch(string $limiterStateId): ?LimiterStateInterface
{
$cacheItem = $this->pool->getItem(sha1($limiterStateId));
$value = $cacheItem->get();
if ($value instanceof LimiterStateInterface) {
return $value;
}
return null;
}
public function delete(string $limiterStateId): void
{
$this->pool->deleteItem($limiterStateId);
}
}
|
Fix error with invalid error message while sending e-mail | var util = require('util'),
_ = require('lodash'),
vow = require('vow'),
nm = require('nodemailer'),
transport = require('nodemailer-smtp-transport'),
errors = require('../errors').Mailer,
logger = require('./../logger'),
mailer;
module.exports = {
/**
* Initialize mailer module
*/
init: function (options) {
logger.info('Initialize e-mail sending module', module);
if (!options) {
errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn');
return vow.resolve();
}
mailer = new nm.createTransport(transport({
host: options.host,
port: options.port
}));
return vow.resolve(mailer);
},
/**
* Email sending
* @param {Object} options - e-mail options object
* @returns {*}
*/
send: function (options) {
var base = { encoding: 'utf-8' };
logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module);
if (!mailer) {
errors.createError(errors.CODES.NOT_INITIALIZED).log();
return vow.resolve();
}
var def = vow.defer();
mailer.sendMail(_.extend({}, base, options), function (err) {
if (err) {
errors.createError(errors.CODES.COMMON, { err: err }).log();
def.reject(err);
} else {
def.resolve();
}
});
return def.promise();
}
};
| var util = require('util'),
_ = require('lodash'),
vow = require('vow'),
nm = require('nodemailer'),
transport = require('nodemailer-smtp-transport'),
errors = require('../errors').Mailer,
logger = require('./../logger'),
mailer;
module.exports = {
/**
* Initialize mailer module
*/
init: function (options) {
logger.info('Initialize e-mail sending module', module);
if (!options) {
errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn');
return vow.resolve();
}
mailer = new nm.createTransport(transport({
host: options.host,
port: options.port
}));
return vow.resolve(mailer);
},
/**
* Email sending
* @param {Object} options - e-mail options object
* @returns {*}
*/
send: function (options) {
var base = { encoding: 'utf-8' };
logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module);
if (!mailer) {
errors.createError(errors.CODES.NOT_INITIALIZED).log();
return vow.resolve();
}
var def = vow.defer();
mailer.sendMail(_.extend({}, base, options), function (err) {
errors.createError(errors.CODES.COMMON, { err: err }).log();
err ? def.reject(err) : def.resolve();
});
return def.promise();
}
};
|
Define abstract base method as abstract | <?php
/**
* abstract compiler pass for extref things
*/
namespace Graviton\DocumentBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
abstract class AbstractExtRefCompilerPass implements CompilerPassInterface
{
/**
* load services
*
* @param ContainerBuilder $container container builder
*
* @return void
*/
final public function process(ContainerBuilder $container)
{
$gravitonServices = array_filter(
$container->getServiceIds(),
function ($id) {
return substr($id, 0, 8) == 'graviton' &&
strpos($id, 'controller') !== false &&
$id !== 'graviton.rest.controller';
}
);
$this->processServices($container, $gravitonServices);
}
/**
* abstract process method
*
* @param ContainerBuilder $container container
* @param array $services services
*
* @return void
*/
abstract public function processServices(ContainerBuilder $container, $services);
}
| <?php
/**
* abstract compiler pass for extref things
*/
namespace Graviton\DocumentBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
abstract class AbstractExtRefCompilerPass implements CompilerPassInterface
{
/**
* load services
*
* @param ContainerBuilder $container container builder
*
* @return void
*/
final public function process(ContainerBuilder $container)
{
$gravitonServices = array_filter(
$container->getServiceIds(),
function ($id) {
return substr($id, 0, 8) == 'graviton' &&
strpos($id, 'controller') !== false &&
$id !== 'graviton.rest.controller';
}
);
$this->processServices($container, $gravitonServices);
}
/**
* null implementation of method
*
* @param ContainerBuilder $container container
* @param array $services services
*
* @return void
*/
public function processServices(ContainerBuilder $container, $services)
{
}
}
|
Make zip code input numeric | import React, { Component } from 'react';
import { Grid, Col, Form, Item, Label, Input, Card, CardItem } from 'native-base';
import CardHeader from '../../common/card-header/cardHeader';
// Temporary constants. These will be moved and implemented in another way in the future!
const ADDRESS_STRING = 'Adress';
const CITY_STRING = 'Stad';
const ZIP_CODE_STRING = 'Postnummer';
// Card with input fields to specify the location of the job.
export default class PlaceCard extends Component {
render() {
return (
<Card>
<CardHeader icon="pin" title="Plats" subtitle="Var ska uppdraget utföras?" />
<Form>
<Item floatingLabel>
<Label>{ADDRESS_STRING}</Label>
<Input />
</Item>
<Grid>
<Col>
<Item floatingLabel>
<Label>{CITY_STRING}</Label>
<Input />
</Item>
</Col>
<Col>
<Item floatingLabel>
<Label>{ZIP_CODE_STRING}</Label>
<Input keyboardType="numeric" />
</Item>
</Col>
</Grid>
</Form>
<CardItem footer />
</Card>
);
}
}
| import React, { Component } from 'react';
import { Grid, Col, Form, Item, Label, Input, Card, CardItem } from 'native-base';
import CardHeader from '../../common/card-header/cardHeader';
// Temporary constants. These will be moved and implemented in another way in the future!
const ADDRESS_STRING = 'Adress';
const CITY_STRING = 'Stad';
const ZIP_CODE_STRING = 'Postnummer';
// Card with input fields to specify the location of the job.
export default class PlaceCard extends Component {
render() {
return (
<Card>
<CardHeader icon="pin" title="Plats" subtitle="Var ska uppdraget utföras?" />
<Form>
<Item floatingLabel>
<Label>{ADDRESS_STRING}</Label>
<Input />
</Item>
<Grid>
<Col>
<Item floatingLabel>
<Label>{CITY_STRING}</Label>
<Input />
</Item>
</Col>
<Col>
<Item floatingLabel>
<Label>{ZIP_CODE_STRING}</Label>
<Input />
</Item>
</Col>
</Grid>
</Form>
<CardItem footer />
</Card>
);
}
}
|
Fix initialization of Smtp Mailer | <?php
namespace Remp\MailerModule\Mailer;
use Nette\Mail\IMailer;
use Nette\Mail\Message;
use Remp\MailerModule\Config\Config;
use Remp\MailerModule\Repository\ConfigsRepository;
class SmtpMailer extends Mailer implements IMailer
{
private $mailer;
protected $alias = 'remp-smtp';
protected $options = [
'host' => [
'required' => true,
'label' => 'SMTP host',
],
'port' => [
'required' => true,
'label' => 'SMTP Port',
],
'username' => [
'required' => false,
'label' => 'SMTP Username',
],
'password' => [
'required' => false,
'label' => 'SMTP Password',
],
'secure' => [
'required' => false,
'label' => 'SMTP Secure',
],
];
public function __construct(
Config $config,
ConfigsRepository $configsRepository
) {
parent::__construct($config, $configsRepository);
// SMTP Mailer expects plain options
$options = [];
foreach ($this->options as $name => $option) {
if (isset($option['value'])) {
$options[$name] = $option['value'];
}
}
$this->mailer = new \Nette\Mail\SmtpMailer($options);
}
public function send(Message $message)
{
$this->mailer->send($message);
}
}
| <?php
namespace Remp\MailerModule\Mailer;
use Nette\Mail\IMailer;
use Nette\Mail\Message;
use Remp\MailerModule\Config\Config;
use Remp\MailerModule\Repository\ConfigsRepository;
class SmtpMailer extends Mailer implements IMailer
{
private $mailer;
protected $alias = 'remp-smtp';
protected $options = [
'host' => [
'required' => true,
'label' => 'SMTP host',
],
'port' => [
'required' => true,
'label' => 'SMTP Port',
],
'username' => [
'required' => false,
'label' => 'SMTP Username',
],
'password' => [
'required' => false,
'label' => 'SMTP Password',
],
'secure' => [
'required' => false,
'label' => 'SMTP Secure',
],
];
public function __construct(
Config $config,
ConfigsRepository $configsRepository
) {
parent::__construct($config, $configsRepository);
$this->mailer = new \Nette\Mail\SmtpMailer($this->options);
}
public function send(Message $message)
{
$this->mailer->send($message);
}
}
|
Use relocated Destiny 1 endpoints. | import request from 'request';
class BungiePlatformService {
get(endpoint) {
let options = {
url: `https://www.bungie.net/d1/Platform${endpoint}`,
headers: {
'X-API-Key': process.env.BUNGIE_API_KEY
}
};
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
try {
if (error || response.statusCode !== 200) {
throw error;
}
let data = JSON.parse(body);
if (data.ErrorCode === 1) {
resolve(data.Response);
}
else {
throw new Error(`${data.ErrorStatus}: ${data.Message}`);
}
} catch (e) {
reject(new Error(`Bungie.net Error: ${e.message}`));
}
});
});
}
getManifest() {
return this.get('/Destiny/Manifest');
}
getPublicAdvisorsV2() {
return this.get('/Destiny/Advisors/V2/?definitions=true');
}
getXur() {
return this.get('/Destiny/Advisors/Xur/?definitions=true');
}
getVendor(vendorHash) {
return this.get(`/Destiny/Vendors/${vendorHash}/?definitions=true`);
}
};
export default new BungiePlatformService(); | import request from 'request';
class BungiePlatformService {
get(endpoint) {
let options = {
url: `https://www.bungie.net/Platform${endpoint}`,
headers: {
'X-API-Key': process.env.BUNGIE_API_KEY
}
};
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
try {
if (error || response.statusCode !== 200) {
throw error;
}
let data = JSON.parse(body);
if (data.ErrorCode === 1) {
resolve(data.Response);
}
else {
throw new Error(`${data.ErrorStatus}: ${data.Message}`);
}
} catch (e) {
reject(new Error(`Bungie.net Error: ${e.message}`));
}
});
});
}
getManifest() {
return this.get('/Destiny/Manifest');
}
getPublicAdvisorsV2() {
return this.get('/Destiny/Advisors/V2/?definitions=true');
}
getXur() {
return this.get('/Destiny/Advisors/Xur/?definitions=true');
}
getVendor(vendorHash) {
return this.get(`/Destiny/Vendors/${vendorHash}/?definitions=true`);
}
};
export default new BungiePlatformService(); |
fix(webpack): Fix source map generation in dist | var webpack = require("webpack");
// Builds bundle usable <script>. Includes RGL and all deps, excluding React.
module.exports = {
context: __dirname,
entry: {
"react-grid-layout": "./index-dev.js"
},
output: {
path: __dirname + "/dist",
filename: "[name].min.js",
libraryTarget: "umd",
library: "ReactGridLayout"
},
devtool: "source-map",
externals: {
"react": {
"commonjs": "react",
"commonjs2": "react",
"amd": "react",
// React dep should be available as window.React, not window.react
"root": "React"
},
"react-dom": {
"commonjs": "react-dom",
"commonjs2": "react-dom",
"amd": "react-dom",
// React dep should be available as window.React, not window.react
"root": "ReactDOM"
}
},
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader"}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
// Compress, but don't print warnings to console
new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}, sourceMap: true})
],
resolve: {
extensions: [".webpack.js", ".web.js", ".js", ".jsx"]
}
};
| var webpack = require("webpack");
// Builds bundle usable <script>. Includes RGL and all deps, excluding React.
module.exports = {
context: __dirname,
entry: {
"react-grid-layout": "./index-dev.js"
},
output: {
path: __dirname + "/dist",
filename: "[name].min.js",
libraryTarget: "umd",
library: "ReactGridLayout"
},
devtool: "source-map",
externals: {
"react": {
"commonjs": "react",
"commonjs2": "react",
"amd": "react",
// React dep should be available as window.React, not window.react
"root": "React"
},
"react-dom": {
"commonjs": "react-dom",
"commonjs2": "react-dom",
"amd": "react-dom",
// React dep should be available as window.React, not window.react
"root": "ReactDOM"
}
},
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader"}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
// Compress, but don't print warnings to console
new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}})
],
resolve: {
extensions: [".webpack.js", ".web.js", ".js", ".jsx"]
}
};
|
Update zstd version in test
To reflect the recent upgrade to 1.1.0. | from __future__ import unicode_literals
try:
import unittest2 as unittest
except ImportError:
import unittest
import zstd
class TestModuleAttributes(unittest.TestCase):
def test_version(self):
self.assertEqual(zstd.ZSTD_VERSION, (1, 1, 0))
def test_constants(self):
self.assertEqual(zstd.MAX_COMPRESSION_LEVEL, 22)
self.assertEqual(zstd.FRAME_HEADER, b'\x28\xb5\x2f\xfd')
def test_hasattr(self):
attrs = (
'COMPRESSION_RECOMMENDED_INPUT_SIZE',
'COMPRESSION_RECOMMENDED_OUTPUT_SIZE',
'DECOMPRESSION_RECOMMENDED_INPUT_SIZE',
'DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE',
'MAGIC_NUMBER',
'WINDOWLOG_MIN',
'WINDOWLOG_MAX',
'CHAINLOG_MIN',
'CHAINLOG_MAX',
'HASHLOG_MIN',
'HASHLOG_MAX',
'HASHLOG3_MAX',
'SEARCHLOG_MIN',
'SEARCHLOG_MAX',
'SEARCHLENGTH_MIN',
'SEARCHLENGTH_MAX',
'TARGETLENGTH_MIN',
'TARGETLENGTH_MAX',
'STRATEGY_FAST',
'STRATEGY_DFAST',
'STRATEGY_GREEDY',
'STRATEGY_LAZY',
'STRATEGY_LAZY2',
'STRATEGY_BTLAZY2',
'STRATEGY_BTOPT',
)
for a in attrs:
self.assertTrue(hasattr(zstd, a))
| from __future__ import unicode_literals
try:
import unittest2 as unittest
except ImportError:
import unittest
import zstd
class TestModuleAttributes(unittest.TestCase):
def test_version(self):
self.assertEqual(zstd.ZSTD_VERSION, (1, 0, 0))
def test_constants(self):
self.assertEqual(zstd.MAX_COMPRESSION_LEVEL, 22)
self.assertEqual(zstd.FRAME_HEADER, b'\x28\xb5\x2f\xfd')
def test_hasattr(self):
attrs = (
'COMPRESSION_RECOMMENDED_INPUT_SIZE',
'COMPRESSION_RECOMMENDED_OUTPUT_SIZE',
'DECOMPRESSION_RECOMMENDED_INPUT_SIZE',
'DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE',
'MAGIC_NUMBER',
'WINDOWLOG_MIN',
'WINDOWLOG_MAX',
'CHAINLOG_MIN',
'CHAINLOG_MAX',
'HASHLOG_MIN',
'HASHLOG_MAX',
'HASHLOG3_MAX',
'SEARCHLOG_MIN',
'SEARCHLOG_MAX',
'SEARCHLENGTH_MIN',
'SEARCHLENGTH_MAX',
'TARGETLENGTH_MIN',
'TARGETLENGTH_MAX',
'STRATEGY_FAST',
'STRATEGY_DFAST',
'STRATEGY_GREEDY',
'STRATEGY_LAZY',
'STRATEGY_LAZY2',
'STRATEGY_BTLAZY2',
'STRATEGY_BTOPT',
)
for a in attrs:
self.assertTrue(hasattr(zstd, a))
|
Fix bug accessing wrong schema instance | var clone = require('clone'),
mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId;
module.exports = function(schema, options) {
options = options || {};
options.collection = options.collection || 'versions';
var versionedSchema = clone(schema);
// Fix for callQueue arguments
versionedSchema.callQueue.forEach(function(queueEntry) {
var args = [];
for(var key in queueEntry[1]) {
args.push(queueEntry[1][key]);
}
queueEntry[1] = args;
});
for(var key in options) {
if (options.hasOwnProperty(key)) {
versionedSchema.set(key, options[key]);
}
}
versionedSchema.add({
refId : ObjectId,
refVersion : Number
});
// Add reference to model to original schema
schema.statics.VersionedModel = mongoose.model(options.collection, versionedSchema);
schema.pre('save', function(next) {
this.increment(); // Increment origins version
var versionedModel = new schema.statics.VersionedModel(this);
versionedModel.refVersion = this._doc.__v; // Saves current document version
versionedModel.refId = this._id; // Sets origins document id as a reference
versionedModel._id = undefined;
versionedModel.save(function(err) {
next();
});
});
};
| var clone = require('clone'),
mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId;
module.exports = function(schema, options) {
options = options || {};
options.collection = options.collection || 'versions';
var versionedSchema = clone(schema);
// Fix for callQueue arguments
versionedSchema.callQueue.forEach(function(queueEntry) {
var args = [];
for(var key in queueEntry[1]) {
args.push(queueEntry[1][key]);
}
queueEntry[1] = args;
});
for(var key in options) {
if (options.hasOwnProperty(key)) {
versionedSchema.set(key, options[key]);
}
}
versionedSchema.add({
refId : ObjectId,
refVersion : Number
});
// Add reference to model to original schema
schema.statics.VersionedModel = mongoose.model(options.collection, versionedSchema);
schema.pre('save', function(next) {
this.increment(); // Increment origins version
var versionedModel = new versionedSchema.statics.VersionedModel(this);
versionedModel.refVersion = this._doc.__v; // Saves current document version
versionedModel.refId = this._id; // Sets origins document id as a reference
versionedModel._id = undefined;
versionedModel.save(function(err) {
next();
});
});
};
|
Add some more padding to login screen | var zk = {
toMonthCalendar: function() {
$.fn.fullpage.moveSlideRight();
$(window).scrollTop(0);
},
toMain: function() {
$.fn.fullpage.moveSlideLeft();
$(window).scrollTop(0);
},
fillMonthCalendar: function(month, data) {
$('#_MonthCalendar').html(data);
},
resizeLoginArea: function() {
var windowHeight = $(window).innerHeight();
var topHeight = $('#top').innerHeight();
var padding = windowHeight * 0.025 + 20;
$('#login').css({
height: windowHeight - topHeight - padding
});
},
resetValidation: function() {
// Removes validation from input-fields
$('.input-validation-error').empty();
// Removes validation message after input-fields
$('.field-validation-error').empty();
// Removes validation summary
$('.validation-summary-errors').empty();
},
showSignupBox: function() {
$('#loginbox').hide();
$('#signupbox').show();
this.resetValidation();
},
showLoginBox: function() {
$('#signupbox').hide();
$('#loginbox').show();
this.resetValidation()
},
// Helper functions:
capitaliseFirstLetter: function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
},
// Returns the elements from an array (arr) where the type (type) has the specified value (val).
getData: function(arr, type, val) {
return arr.filter(function (el) {
return el[type] === val;
});
}
}; | var zk = {
toMonthCalendar: function() {
$.fn.fullpage.moveSlideRight();
$(window).scrollTop(0);
},
toMain: function() {
$.fn.fullpage.moveSlideLeft();
$(window).scrollTop(0);
},
fillMonthCalendar: function(month, data) {
$('#_MonthCalendar').html(data);
},
resizeLoginArea: function() {
var windowHeight = $(window).innerHeight();
var topHeight = $('#top').innerHeight();
var padding = windowHeight * 0.025;
$('#login').css({
height: windowHeight - topHeight - padding
});
},
resetValidation: function() {
// Removes validation from input-fields
$('.input-validation-error').empty();
// Removes validation message after input-fields
$('.field-validation-error').empty();
// Removes validation summary
$('.validation-summary-errors').empty();
},
showSignupBox: function() {
$('#loginbox').hide();
$('#signupbox').show();
this.resetValidation();
},
showLoginBox: function() {
$('#signupbox').hide();
$('#loginbox').show();
this.resetValidation()
},
// Helper functions:
capitaliseFirstLetter: function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
},
// Returns the elements from an array (arr) where the type (type) has the specified value (val).
getData: function(arr, type, val) {
return arr.filter(function (el) {
return el[type] === val;
});
}
}; |
Allow null as defining class.
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1736 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | /*
* Copyright (C) 2008, 2010 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
if ((declaringClass == null && field.declaringClass != null)
|| (declaringClass != null && field.declaringClass == null)) {
return false;
}
return name.equals(field.getName())
&& (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
}
return false;
}
public int hashCode() {
return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
}
public String toString() {
return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
}
} | /*
* Copyright (C) 2008 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 13. October 2008 by Joerg Schaible
*/
package com.thoughtworks.xstream.core.util;
public final class FastField {
private final String name;
private final Class declaringClass;
public FastField(Class definedIn, String name) {
this.name = name;
this.declaringClass = definedIn;
}
public String getName() {
return this.name;
}
public Class getDeclaringClass() {
return this.declaringClass;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this == null) {
return false;
}
if (obj.getClass() == FastField.class) {
final FastField field = (FastField)obj;
return name.equals(field.getName())
&& declaringClass.equals(field.getDeclaringClass());
}
return false;
}
public int hashCode() {
return name.hashCode() ^ declaringClass.hashCode();
}
public String toString() {
return declaringClass.getName() + "[" + name + "]";
}
} |
Check if slaves are alive and fallback to other slaves and eventually to master. | # -*- coding:utf-8 -*-
import random
from django.db import connections
from django.db.utils import DEFAULT_DB_ALIAS
from django.conf import settings
def is_alive(db):
try:
if db.connection is not None and hasattr(db.connection, 'ping'):
db.connection.ping()
else:
db.cursor()
return True
except StandardError:
return False
class ReplicationRouter(object):
def __init__(self):
self.state_stack = ['master']
self._state_change_enabled = True
def set_state_change(self, enabled):
self._state_change_enabled = enabled
def state(self):
'''
Current state of routing: 'master' or 'slave'.
'''
return self.state_stack[-1]
def use_state(self, state):
'''
Switches router into a new state. Requires a paired call
to 'revert' for reverting to previous state.
'''
if not self._state_change_enabled:
state = self.state()
self.state_stack.append(state)
return self
def revert(self):
'''
Reverts wrapper state to a previous value after calling
'use_state'.
'''
self.state_stack.pop()
def db_for_write(self, model, **hints):
return DEFAULT_DB_ALIAS
def db_for_read(self, model, **hints):
if self.state() == 'master':
return self.db_for_write(model, **hints)
slaves = getattr(settings, 'DATABASE_SLAVES', [DEFAULT_DB_ALIAS])
random.shuffle(slaves)
for slave in slaves:
if is_alive(connections[slave]):
return slave
else:
return DEFAULT_DB_ALIAS
| # -*- coding:utf-8 -*-
import random
from django.db.utils import DEFAULT_DB_ALIAS
from django.conf import settings
class ReplicationRouter(object):
def __init__(self):
self.state_stack = ['master']
self._state_change_enabled = True
def set_state_change(self, enabled):
self._state_change_enabled = enabled
def state(self):
'''
Current state of routing: 'master' or 'slave'.
'''
return self.state_stack[-1]
def use_state(self, state):
'''
Switches router into a new state. Requires a paired call
to 'revert' for reverting to previous state.
'''
if not self._state_change_enabled:
state = self.state()
self.state_stack.append(state)
return self
def revert(self):
'''
Reverts wrapper state to a previous value after calling
'use_state'.
'''
self.state_stack.pop()
def db_for_write(self, model, **hints):
return DEFAULT_DB_ALIAS
def db_for_read(self, model, **hints):
if self.state() == 'master':
return self.db_for_write(model, **hints)
slaves = getattr(settings, 'DATABASE_SLAVES', [DEFAULT_DB_ALIAS])
return random.choice(slaves)
|
Change the markup in the Character component
It uses now the initial design for the character component, they seem
now more like cards | var React = require('react');
var Character = React.createClass({
getThumbnail: function() {
var image = 'http://placehold.it/250x250';
if(this.props.character.thumbnail) {
image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension;
}
return (
<img className="character-image" src={image}/>
)
},
getName: function() {
return (
<span className="character-name">
{this.props.character.name}
</span>
);
},
getDescription: function() {
var description = this.props.character.description ? this.props.character.description : 'No description'
return (
<p>
{description}
</p>
)
},
getLinks: function() {
return (
<p>
<a href={this.props.character.urls[0].url}>Wiki</a>|
<a href={this.props.character.urls[1].url}>More details</a>
</p>
)
},
render: function () {
return (
<div className="character">
<div className="col-xs-12 col-sm-3">
<div className="thumbnail">
{this.getThumbnail()}
<div className="caption">
<span className="character-name">{this.getName()}</span>
<div className="character-description">
{this.getDescription()}
{this.getLinks()}
</div>
</div>
</div>
</div>
</div>
);
}
});
module.exports = Character;
| var React = require('react');
var Character = React.createClass({
getThumbnail: function() {
var image = 'http://placehold.it/250x250';
if(this.props.character.thumbnail) {
image = this.props.character.thumbnail.path+'.'+this.props.character.thumbnail.extension;
}
return (
<img className="character-image" src={image}/>
)
},
getName: function() {
return (
<span className="character-name">
{this.props.character.name}
</span>
);
},
getDescription: function() {
var description = this.props.character.description ? this.props.character.description : 'No description'
return (
<p>
{description}
</p>
)
},
getLinks: function() {
return (
<p>
<a href={this.props.character.urls[0].url}>Wiki</a>|
<a href={this.props.character.urls[1].url}>More details</a>
</p>
)
},
render: function () {
return (
<div className="row character">
<div className="col-xs-12">
<div className="row">
<div className="col-xs-3">
{this.getThumbnail()}
</div>
<div className="col-xs-9">
{this.getName()}
<div className="character-description">
{this.getDescription()}
{this.getLinks()}
</div>
</div>
</div>
</div>
</div>
);
}
});
module.exports = Character;
|
Fix issue when debugger is used with DI
This fix allows the debug module to properly serialize action params even if they are complex. It realizes this by replacing the params with string descriptions. | <?php
namespace SamIT\Yii2\Traits;
use yii\base\InlineAction;
use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
/**
* Trait that implements dependency injection for controller actions.
* It should be bound only to subclasses of controller.
*/
trait ActionInjectionTrait
{
/**
* @see https://github.com/yiisoft/yii2/issues/9476
* @inheritdoc
*/
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$callable = [$this, $action->actionMethod];
} else {
$callable = [$action, 'run'];
}
$actionParams = [];
try {
$args = \Yii::$container->resolveCallableDependencies($callable, $params);
} catch (InvalidConfigException $e) {
throw new BadRequestHttpException($e->getMessage());
}
foreach ((new \ReflectionMethod($callable[0], $callable[1]))->getParameters() as $i => $param) {
$actionParams[$param->getName()] = $args[$i];
}
if (property_exists($this, 'actionParams')) {
$this->actionParams = $actionParams;
}
// Dont put injected params in requestedParams, this breaks the debugger.
foreach($actionParams as $key => $value) {
if (is_object($value)) {
if (\Yii::$app->has($key, true)
&& $value === \Yii::$app->get($key)
) {
$value = "Application component: $key";
} else {
$value = "DI: " .get_class($value);
}
}
\Yii::$app->requestedParams[$key] = $value;
}
return $args;
}
}
| <?php
namespace SamIT\Yii2\Traits;
use yii\base\InlineAction;
use yii\base\InvalidConfigException;
use yii\web\BadRequestHttpException;
/**
* Trait that implements dependency injection for controller actions.
* It should be bound only to subclasses of controller.
*/
trait ActionInjectionTrait
{
/**
* @see https://github.com/yiisoft/yii2/issues/9476
* @inheritdoc
*/
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$callable = [$this, $action->actionMethod];
} else {
$callable = [$action, 'run'];
}
$actionParams = [];
try {
$args = \Yii::$container->resolveCallableDependencies($callable, $params);
} catch (InvalidConfigException $e) {
throw new BadRequestHttpException($e->getMessage());
}
foreach ((new \ReflectionMethod($callable[0], $callable[1]))->getParameters() as $i => $param) {
$actionParams[$param->getName()] = $args[$i];
}
if (property_exists($this, 'actionParams')) {
$this->actionParams = $actionParams;
}
return $args;
}
} |
Rename FK in migration 70 - For some reason, Gunks' db has it named differently than ours. | """Fix Folder, EASFolderSyncStatus unique constraints
Revision ID: 2525c5245cc2
Revises: 479b3b84a73e
Create Date: 2014-07-28 18:57:24.476123
"""
# revision identifiers, used by Alembic.
revision = '2525c5245cc2'
down_revision = '479b3b84a73e'
from alembic import op
import sqlalchemy as sa
from inbox.ignition import main_engine
engine = main_engine()
Base = sa.ext.declarative.declarative_base()
Base.metadata.reflect(engine)
def upgrade():
op.drop_constraint('folder_fk1', 'folder', type_='foreignkey')
op.drop_constraint('account_id', 'folder', type_='unique')
op.create_foreign_key('folder_fk1',
'folder', 'account',
['account_id'], ['id'])
op.create_unique_constraint('account_id',
'folder',
['account_id', 'name', 'canonical_name'])
if 'easfoldersyncstatus' in Base.metadata.tables:
op.create_unique_constraint('account_id_2',
'easfoldersyncstatus',
['account_id', 'eas_folder_id'])
def downgrade():
raise Exception('Unsupported, going back will break things.')
| """Fix Folder, EASFolderSyncStatus unique constraints
Revision ID: 2525c5245cc2
Revises: 479b3b84a73e
Create Date: 2014-07-28 18:57:24.476123
"""
# revision identifiers, used by Alembic.
revision = '2525c5245cc2'
down_revision = '479b3b84a73e'
from alembic import op
import sqlalchemy as sa
from inbox.ignition import main_engine
engine = main_engine()
Base = sa.ext.declarative.declarative_base()
Base.metadata.reflect(engine)
def upgrade():
op.drop_constraint('folder_ibfk_1', 'folder', type_='foreignkey')
op.drop_constraint('account_id', 'folder', type_='unique')
op.create_foreign_key('folder_ibfk_1',
'folder', 'account',
['account_id'], ['id'])
op.create_unique_constraint('account_id',
'folder',
['account_id', 'name', 'canonical_name'])
if 'easfoldersyncstatus' in Base.metadata.tables:
op.create_unique_constraint('account_id_2',
'easfoldersyncstatus',
['account_id', 'eas_folder_id'])
def downgrade():
raise Exception('Unsupported, going back will break things.')
|
Join word tokens into space-delimited string in InfoRetriever | # LING 573 Question Answering System
# Code last updated 4/17/14 by Clara Gordon
# This code implements an InfoRetriever for the question answering system.
from pymur import *
from general_classes import *
class InfoRetriever:
# builds a QueryEnvironment associated with the indexed document collection
def __init__(self, index_path):
# how to get this to link up to the doc collection?
self.path_to_idx = index_path
self.index = Index(self.path_to_idx)
self.query_env = QueryEnvironment()
self.query_env.addIndex(self.path_to_idx)
# creates a list of all the passages returned by all the queries generated by
# the query-processing module
def retrieve_passages(self, queries):
passages = []
for query in queries:
query = " ".join(query)
# second argument is the number of documents desired
docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20)
for doc in docs:
doc_num = doc.document
begin = doc.begin
end = doc.end
doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output
passage = Passage(self.index.document(doc_num, True)[begin, end], doc.score, doc_id)
passages.append(passage)
return passages
| # LING 573 Question Answering System
# Code last updated 4/17/14 by Clara Gordon
# This code implements an InfoRetriever for the question answering system.
from pymur import *
from general_classes import *
class InfoRetriever:
# builds a QueryEnvironment associated with the indexed document collection
def __init__(self, index_path):
# how to get this to link up to the doc collection?
self.path_to_idx = index_path
self.index = Index(self.path_to_idx)
self.query_env = QueryEnvironment()
self.query_env.addIndex(self.path_to_idx)
# creates a list of all the passages returned by all the queries generated by
# the query-processing module
def retrieve_passages(self, queries):
passages = []
for query in queries:
# second argument is the number of documents desired
docs = self.query_env.runQuery("#combine[passage50:25](" + query + ")", 20)
for doc in docs:
doc_num = doc.document
begin = doc.begin
end = doc.end
doc_id = self.query_env.documents([doc_num])[0].metadata['docno'] # need this for output
passage = Passage(self.index.document(doc_num, True)[begin, end], doc.score, doc_id)
passages.append(passage)
return passages
|
Add source map and live reload | var grunt = require('grunt');
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.initConfig({
'6to5': {
options: {
sourceMap: true,
modules: 'ignore'
},
dist: {
files: [{
expand: true,
cwd: 'src',
src: ['**/*.js', '!intro.js', '!outro.js'],
dest: '.tmp/es5',
ext: '.js'
}]
}
},
concat: {
options: {
sourceMap: true,
separator: ''
},
dist: {
src: [
'src/intro.js',
'.tmp/es5/**/*.js',
'src/outro.js'
],
dest: 'dist/lithree.js'
}
},
uglify: {
my_target: {
files: {
'dist/lithree.min.js': ['dist/lithree.js']
}
}
},
watch: {
scripts: {
files: ['src/**/*.js'],
tasks: ['default'],
options: {
livereload: true,
spawn: false
}
}
}
});
grunt.registerTask('default', ['6to5', 'concat']);
grunt.registerTask('build', ['default', 'uglify']); | var grunt = require('grunt');
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.initConfig({
'6to5': {
options: {
sourceMap: true,
modules: 'ignore'
},
dist: {
files: [{
expand: true,
cwd: 'src',
src: ['**/*.js', '!intro.js', '!outro.js'],
dest: '.tmp/es5',
ext: '.js'
}]
}
},
concat: {
options: {
separator: ''
},
dist: {
src: [
'src/intro.js',
'.tmp/es5/**/*.js',
'src/outro.js'
],
dest: 'dist/lithree.js'
}
},
uglify: {
my_target: {
files: {
'dist/lithree.min.js': ['dist/lithree.js']
}
}
},
watch: {
scripts: {
files: ['src/**/*.js'],
tasks: ['default'],
options: {
spawn: false
}
}
}
});
grunt.registerTask('default', ['6to5', 'concat']);
grunt.registerTask('build', ['default', 'uglify']); |
[FlexLoader] Check for * missing paths in FlexPathsFatcory | <?php declare(strict_types=1);
namespace Symplify\FlexLoader\Flex;
use Nette\Utils\Strings;
use function Safe\glob;
final class FlexPathsFactory
{
/**
* @return string[]
*/
public function createServicePaths(string $projectDir, string $environment): array
{
$servicePaths = [
$projectDir . '/config/packages/*',
$projectDir . '/config/packages/' . $environment . '/**/*',
$projectDir . '/config/services',
$projectDir . '/config/services_' . $environment,
];
return $this->filterExistingPaths($servicePaths);
}
/**
* @return string[]
*/
public function createRoutingPaths(string $projectDir, string $environment): array
{
$routingPaths = [
$projectDir . '/config/routes/*',
$projectDir . '/config/routes/' . $environment . '/**/*',
$projectDir . '/config/routes',
];
return $this->filterExistingPaths($routingPaths);
}
/**
* This is needed, because $config->load() throws exception on non-existing glob paths
* @param string[] $globPaths
* @return string[]
*/
private function filterExistingPaths(array $globPaths): array
{
$existingGlobPaths = [];
foreach ($globPaths as $globPath) {
// the final glob is decorated with *, so we need to check it here too
if (! Strings::endsWith($globPath, '*')) {
$checkedGlobPath = $globPath . '*';
} else {
$checkedGlobPath = $globPath;
}
if (glob($checkedGlobPath)) {
$existingGlobPaths[] = $globPath;
}
}
return $existingGlobPaths;
}
}
| <?php declare(strict_types=1);
namespace Symplify\FlexLoader\Flex;
use function Safe\glob;
final class FlexPathsFactory
{
/**
* @return string[]
*/
public function createServicePaths(string $projectDir, string $environment): array
{
$servicePaths = [
$projectDir . '/config/packages/*',
$projectDir . '/config/packages/' . $environment . '/**/*',
$projectDir . '/config/services',
$projectDir . '/config/services_' . $environment,
];
return $this->filterExistingPaths($servicePaths);
}
/**
* @return string[]
*/
public function createRoutingPaths(string $projectDir, string $environment): array
{
$routingPaths = [
$projectDir . '/config/routes/*',
$projectDir . '/config/routes/' . $environment . '/**/*',
$projectDir . '/config/routes',
];
return $this->filterExistingPaths($routingPaths);
}
/**
* This is needed, because $config->load() throws exception on non-existing glob paths
* @param string[] $globPaths
* @return string[]
*/
private function filterExistingPaths(array $globPaths): array
{
$existingGlobPaths = [];
foreach ($globPaths as $globPath) {
if (glob($globPath)) {
$existingGlobPaths[] = $globPath;
}
}
return $existingGlobPaths;
}
}
|
Make get_date() return date object instead of datetime | import dateutil.parser
from datetime import datetime, date
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
return date(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
| import dateutil.parser
from datetime import datetime
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = tags
def __eq__(self, other):
return self.__start == other.get_start() \
and self.__end == other.get_end() \
and self.__tags == other.get_tags()
def get_start(self):
return self.__start
def get_end(self):
return self.__end
def get_tags(self):
return self.__tags
def is_open(self):
return self.__end is None
def get_duration(self):
if self.is_open():
return datetime.now(tz=tz.tzlocal()) - self.__start
else:
return self.__end - self.__start
def get_date(self):
return datetime(self.__start.year, self.__start.month, self.__start.day)
def __get_local_datetime(self, datetime_string):
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
date = dateutil.parser.parse(datetime_string)
date.replace(tzinfo=from_zone)
return date.astimezone(to_zone)
|
Change concatination of parsed data | from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
import inspect
import requests, json
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
validator = URLValidator(verify_exists=False)
try:
validator(uri)
self.__oerUri = uri
for t in templates:
if 'OERTemplate' == t.__class__.__bases__[0].__name__:
self.__parserTemplates.add(t)
if True == auto_retrieved:
self.retrieve_information()
except ValidationError, e:
pass
"""
To retrieve OER content from assigned URI
"""
def retrieve_information(self):
request_header = {'accept': 'application/ld+json'}
r = requests.get(self.__oerUri, headers=request_header)
json_response = r.json()
parsed_data = dict();
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
for key in template.__dict__.keys():
val = getattr(template, key)
parsed_data[key] = val
return parsed_data
| from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
import inspect
import requests, json
class FedoraConnectionManager:
__oerUri = ''
__parserTemplates = set()
def __init__(self, uri, templates=[], auto_retrieved=True):
validator = URLValidator(verify_exists=False)
try:
validator(uri)
self.__oerUri = uri
for t in templates:
if 'OERTemplate' == t.__class__.__bases__[0].__name__:
self.__parserTemplates.add(t)
if True == auto_retrieved:
self.retrieve_information()
except ValidationError, e:
pass
"""
To retrieve OER content from assigned URI
"""
def retrieve_information(self):
request_header = {'accept': 'application/ld+json'}
r = requests.get(self.__oerUri, headers=request_header)
json_response = r.json()
""" Start parsing information with assigned template """
for template in self.__parserTemplates:
template.parse(json_response)
self += template
def __add__(self, other):
for key in other.__dict__.keys():
setattr(self, key, other.__dict__[key])
|
Move support for dataview-specific database from lava-server | from lava_server.extension import LavaServerExtension
class DashboardExtension(LavaServerExtension):
@property
def app_name(self):
return "dashboard_app"
@property
def name(self):
return "Dashboard"
@property
def main_view_name(self):
return "dashboard_app.views.bundle_stream_list"
@property
def description(self):
return "Validation Dashboard"
@property
def version(self):
import versiontools
import dashboard_app
return versiontools.format_version(dashboard_app.__version__)
def contribute_to_settings(self, settings_module):
super(DashboardExtension, self).contribute_to_settings(settings_module)
settings_module['INSTALLED_APPS'].extend([
"linaro_django_pagination",
"south",
])
settings_module['MIDDLEWARE_CLASSES'].append(
'linaro_django_pagination.middleware.PaginationMiddleware')
def contribute_to_settings_ex(self, settings_module, settings_object):
settings_module['DATAVIEW_DIRS'] = settings_object._settings.get(
"DATAVIEW_DIRS", [])
settings_module['DATAREPORT_DIRS'] = settings_object._settings.get(
"DATAREPORT_DIRS", [])
# Enable constrained dataview database if requested
if settings_object._settings.get("use_dataview_database"):
# Copy everything from the default database and append _dataview to user
# name. The rest is out of scope (making sure it's actually setup
# properly, having permissions to login, permissions to view proper data)
settings_module['DATABASES']['dataview'] = dict(settings_module['DATABASES']['default'])
settings_module['DATABASES']['dataview']['USER'] += "_dataview"
| from lava_server.extension import LavaServerExtension
class DashboardExtension(LavaServerExtension):
@property
def app_name(self):
return "dashboard_app"
@property
def name(self):
return "Dashboard"
@property
def main_view_name(self):
return "dashboard_app.views.bundle_stream_list"
@property
def description(self):
return "Validation Dashboard"
@property
def version(self):
import versiontools
import dashboard_app
return versiontools.format_version(dashboard_app.__version__)
def contribute_to_settings(self, settings):
super(DashboardExtension, self).contribute_to_settings(settings)
settings['INSTALLED_APPS'].extend([
"linaro_django_pagination",
"south",
])
settings['MIDDLEWARE_CLASSES'].append(
'linaro_django_pagination.middleware.PaginationMiddleware')
settings['RESTRUCTUREDTEXT_FILTER_SETTINGS'] = {
"initial_header_level": 4}
def contribute_to_settings_ex(self, settings_module, settings_object):
settings_module['DATAVIEW_DIRS'] = settings_object._settings.get(
"DATAVIEW_DIRS", [])
settings_module['DATAREPORT_DIRS'] = settings_object._settings.get(
"DATAREPORT_DIRS", [])
|
Use className instead of class in jsx element | import React from 'react';
const BorrowRequests = (props) => {
const { books } = props;
if (!books.length) {
return (
<div className="row center">
<p className="grey-text">You have no pending borrow requests </p>
</div>
);
}
return (
<div className="row">
<table className="striped responsive-table">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{ books.map((book, index) =>
<tr key={ index }>
<td> { book.borrowRequests.title } </td>
<td> { book.borrowRequests.author } </td>
<td> { book.createdAt.split('T')[0] } </td>
<td> <button className="btn-flat btn-small">{ book.status } </button></td>
</tr>)}
</tbody>
</table>
</div>
);
};
export default BorrowRequests;
| import React from 'react';
const BorrowRequests = (props) => {
const { books } = props;
if (!books.length) {
return (
<div className="row center">
<p className="grey-text">You have no pending borrow requests </p>
</div>
);
}
return (
<div className="row">
<table class="striped responsive-table">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{ books.map((book, index) =>
<tr key={ index }>
<td> { book.borrowRequests.title } </td>
<td> { book.borrowRequests.author } </td>
<td> { book.createdAt.split('T')[0] } </td>
<td> <button className="btn-flat btn-small">{ book.status } </button></td>
</tr>)}
</tbody>
</table>
</div>
);
};
export default BorrowRequests;
|
Fix typo in default staging config | <?php
if (file_exists($this->DocPath()."/config.php")){
$defaultConfig = include($this->DocPath()."/config.php");
}else {
$defaultConfig = array();
}
$stagingConfig = array(
'db' => array_merge($defaultConfig["db"],array(
'dbname' => $defaultConfig["custom"]["staging_database"]
)),
'custom' => array_merge($defaultConfig["custom"],array(
'is_staging' => true,
)),
'cache' => array(
'backendOptions' => array("cache_dir" => $this->DocPath('staging_cache_general')),
'frontendOptions' => array()
),
'httpCache' => array(
'cache_dir' => $this->DocPath('staging_cache_templates_html')
),
'template' => array(
'cacheDir' => $this->DocPath('staging_cache_templates'),
'compileDir' => $this->DocPath('staging_cache_templates')
),
'hook' => array(
'proxyDir' => $this->DocPath('staging_cache_proxies'),
'proxyNamespace' => $this->App() . '_ProxiesStaging'
),
'model' => array(
'fileCacheDir' => $this->DocPath('staging_cache_doctrine_filecache'),
'attributeDir' => $this->DocPath('staging_cache_doctrine_attributes'),
'proxyDir' => $this->DocPath('staging_cache_doctrine_proxies'),
'proxyNamespace' => $this->App() . '\ProxiesStaging'
)
);
return $stagingConfig;
| <?php
if (file_exists($this->DocPath()."/config.php")){
$defaultConfig = include($this->DocPath()."/config.php");
}else {
$defaultConfig = array();
}
$stagingConfig = array(
'db' => array_merge($defaultConfig["db"],array(
'dbname' => $defaultConfig["custom"]["staging_cache_general"]
)),
'custom' => array_merge($defaultConfig["custom"],array(
'is_staging' => true,
)),
'cache' => array(
'backendOptions' => array("cache_dir" => $this->DocPath('staging_cache_general')),
'frontendOptions' => array()
),
'httpCache' => array(
'cache_dir' => $this->DocPath('staging_cache_templates_html')
),
'template' => array(
'cacheDir' => $this->DocPath('staging_cache_templates'),
'compileDir' => $this->DocPath('staging_cache_templates')
),
'hook' => array(
'proxyDir' => $this->DocPath('staging_cache_proxies'),
'proxyNamespace' => $this->App() . '_ProxiesStaging'
),
'model' => array(
'fileCacheDir' => $this->DocPath('staging_cache_doctrine_filecache'),
'attributeDir' => $this->DocPath('staging_cache_doctrine_attributes'),
'proxyDir' => $this->DocPath('staging_cache_doctrine_proxies'),
'proxyNamespace' => $this->App() . '\ProxiesStaging'
)
);
return $stagingConfig;
|
Increase default top margin to account for two line graph titles. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemFont, "Segoe UI", '
'Roboto, "Helvetica Neue", Arial, sans-serif, '
'"Apple Color Emoji", "Segoe UI Emoji", '
'"Segoe UI Symbol"',
'size': 14,
},
'margin': {'b': 40, 't': 80},
'xaxis': {
'titlefont': {
'color': 'rgba(0, 0, 0, 0.54)'
}
},
'yaxis': {
'titlefont': {
'color': 'rgba(0, 0, 0, 0.54)'
}
}
}
def split_graph_output(output):
"""Split out of a Plotly graph in to html and javascript.
"""
html, javascript = output.split('<script')
javascript = '<script' + javascript
return html, javascript
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
def default_graph_layout_options():
"""Default layout options for all graphs.
"""
return {
'font': {
'color': 'rgba(0, 0, 0, 1)',
# Bootstrap 4 font family.
'family': '-apple-system, BlinkMacSystemFont, "Segoe UI", '
'Roboto, "Helvetica Neue", Arial, sans-serif, '
'"Apple Color Emoji", "Segoe UI Emoji", '
'"Segoe UI Symbol"',
'size': 14,
},
'margin': {'b': 40, 't': 40},
'xaxis': {
'titlefont': {
'color': 'rgba(0, 0, 0, 0.54)'
}
},
'yaxis': {
'titlefont': {
'color': 'rgba(0, 0, 0, 0.54)'
}
}
}
def split_graph_output(output):
"""Split out of a Plotly graph in to html and javascript.
"""
html, javascript = output.split('<script')
javascript = '<script' + javascript
return html, javascript
|
Add function to post a message to the channel | 'use strict';
angular.module('chatApp', [])
.controller('ChatCtrl', function($scope, $http) {
$scope.chatChannel = "chatApp";
$scope.messageLimit = 50;
$scope.defaultUsername = "Guest";
$scope.currentConnectionStatus = 0;
$scope.errorMessage;
$scope.loggedIn = false;
PUBNUB.subscribe({
channel: $scope.chatChannel,
restore: false,
callback: function() { },
disconnect: function() {
$scope.$apply(function(){
$scope.currentConnectionStatus = 0;
});
},
reconnect: function() {
$scope.$apply(function(){
$scope.currentConnectionStatus = 1;
});
},
connect: function() {
$scope.$apply(function(){
$scope.currentConnectionStatus = 2;
});
}
});
$scope.attemptLogin = function() {
$scope.errorMessage = "";
if (!$scope.message.username) {
$scope.errorMessage = "you must enter a username.";
return;
}
if (!$scope.currentConnectionStatus) {
$scope.errorMessage = "you're not connect to our chat room yet.";
return;
}
$scope.loggedIn = true;
};
$scope.postMessage = function() {
};
}); | 'use strict';
angular.module('chatApp', [])
.controller('ChatCtrl', function($scope, $http) {
$scope.chatChannel = "chatApp";
$scope.messageLimit = 50;
$scope.defaultUsername = "Guest";
$scope.currentConnectionStatus = 0;
$scope.errorMessage;
$scope.loggedIn = false;
PUBNUB.subscribe({
channel: $scope.chatChannel,
restore: false,
callback: function() { },
disconnect: function() {
$scope.$apply(function(){
$scope.currentConnectionStatus = 0;
});
},
reconnect: function() {
$scope.$apply(function(){
$scope.currentConnectionStatus = 1;
});
},
connect: function() {
$scope.$apply(function(){
$scope.currentConnectionStatus = 2;
});
}
});
$scope.attemptLogin = function() {
$scope.errorMessage = "";
if (!$scope.message.username) {
$scope.errorMessage = "you must enter a username.";
return;
}
if (!$scope.currentConnectionStatus) {
$scope.errorMessage = "you're not connect to our chat room yet.";
return;
}
$scope.loggedIn = true;
};
}); |
Set log settings to empty array by default | <?php namespace Tait\ModelLogging;
use Tait\ModelLogging\ModelLog;
use Auth;
trait LoggableTrait
{
/**
* Get all logs for this object
*
* @return collection
*/
public function getAllLogs()
{
return ModelLog::
with('user')
->where('content_id', '=', $this->id)
->where('content_type', '=', class_basename($this))
->get();
}
/**
* Get paginated logs for this object
*
* @return collection
*/
public function getPaginatedLogs($per_page = 10)
{
return ModelLog::
with('user')
->where('content_id', '=', $this->id)
->where('content_type', '=', class_basename($this))
->paginate($per_page);
}
/**
* Save a new log
*
* @param array $settings An array of settings to override the defaults
*
* @return void
*/
public function saveLog(array $settings = array())
{
$log = new ModelLog;
$log->fill(array_merge($this->getDefaults(), $settings));
$log->save();
}
/**
* Get some sensible defaults for this class
*
* @return array
*/
protected function getDefaults()
{
return [
'user_id' => Auth::id(),
'content_id' => $this->id,
'content_type' => class_basename($this),
'action' => '',
'description' => null,
];
}
}
| <?php namespace Tait\ModelLogging;
use Tait\ModelLogging\ModelLog;
use Auth;
trait LoggableTrait
{
/**
* Get all logs for this object
*
* @return collection
*/
public function getAllLogs()
{
return ModelLog::
with('user')
->where('content_id', '=', $this->id)
->where('content_type', '=', class_basename($this))
->get();
}
/**
* Get paginated logs for this object
*
* @return collection
*/
public function getPaginatedLogs($per_page = 10)
{
return ModelLog::
with('user')
->where('content_id', '=', $this->id)
->where('content_type', '=', class_basename($this))
->paginate($per_page);
}
/**
* Save a new log
*
* @param array $settings An array of settings to override the defaults
*
* @return void
*/
public function saveLog(array $settings)
{
$log = new ModelLog;
$log->fill(array_merge($this->getDefaults(), $settings));
$log->save();
}
/**
* Get some sensible defaults for this class
*
* @return array
*/
protected function getDefaults()
{
return [
'user_id' => Auth::id(),
'content_id' => $this->id,
'content_type' => class_basename($this),
'action' => '',
'description' => null,
];
}
}
|
Break potential cycle because we are storing the traceback | #
# This file is part of Evergreen. See the NOTICE for more information.
#
import pyuv
import sys
from evergreen.event import Event
from evergreen.futures import Future
__all__ = ('ThreadPool')
"""Internal thread pool which uses the pyuv work queuing capability. This module
is for internal use of Evergreen.
"""
class _Work(object):
__slots__ = ('func', 'args', 'kwargs', 'result', 'exc')
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
self.result = None
self.exc = None
def __call__(self):
try:
self.result = self.func(*self.args, **self.kwargs)
except BaseException:
self.exc = sys.exc_info()
self = None
class ThreadPool(object):
def __init__(self, loop):
self.loop = loop
def spawn(self, func, *args, **kwargs):
fut = Future()
work = _Work(func, *args, **kwargs)
def after(error):
if error is not None:
assert error == pyuv.errno.UV_ECANCELLED
return
if work.exc is not None:
fut.set_exception(work.exc)
else:
fut.set_result(work.result)
fut.set_running_or_notify_cancel()
self.loop._loop.queue_work(work, after)
return fut
| #
# This file is part of Evergreen. See the NOTICE for more information.
#
import pyuv
import sys
from evergreen.event import Event
from evergreen.futures import Future
__all__ = ('ThreadPool')
"""Internal thread pool which uses the pyuv work queuing capability. This module
is for internal use of Evergreen.
"""
class _Work(object):
__slots__ = ('func', 'args', 'kwargs', 'result', 'exc')
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
self.result = None
self.exc = None
def __call__(self):
try:
self.result = self.func(*self.args, **self.kwargs)
except BaseException:
self.exc = sys.exc_info()
class ThreadPool(object):
def __init__(self, loop):
self.loop = loop
def spawn(self, func, *args, **kwargs):
fut = Future()
work = _Work(func, *args, **kwargs)
def after(error):
if error is not None:
assert error == pyuv.errno.UV_ECANCELLED
return
if work.exc is not None:
fut.set_exception(work.exc)
else:
fut.set_result(work.result)
fut.set_running_or_notify_cancel()
self.loop._loop.queue_work(work, after)
return fut
|
Fix typo in follower restrictions | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import models, api
class MailFollowers(models.Model):
""" Prevent having too much followers in mail threads.
"""
_inherit = 'mail.followers'
@api.model
def _mail_restrict_follower_selection_get_domain(self, model):
parameter_name = 'mail_restrict_follower_selection.domain'
return self.env['ir.config_parameter'].get_param(
'%s.%s' % (parameter_name, model),
self.env['ir.config_parameter'].get_param(
parameter_name, default='[]')
)
@api.model
def create(self, vals):
"""
Remove partners not in domain selection of module
mail_restrict_follower_selection
"""
model = vals['res_model']
res_id = vals['partner_id']
domain = self._mail_restrict_follower_selection_get_domain(model)
allowed = self.env['res.partner'].search(eval(domain))
if allowed and res_id in allowed.ids:
return super(MailFollowers, self).create(vals)
return self
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import models, api
class MailFollowers(models.Model):
""" Prevent having too much followers in mail threads.
"""
_inherit = 'mail.followers'
@api.model
def _mail_restrict_follower_selection_get_domain(self, model):
parameter_name = 'mail_restrict_follower_selection.domain'
return self.env['ir.config_parameter'].get_param(
'%s.%s' % (parameter_name, model),
self.env['ir.config_parameter'].get_param(
parameter_name, default='[]')
)
@api.model
def create(self, vals):
"""
Remove partners not in domain selection of module
mail_restrict_follower_selection
"""
model = vals['res_model']
res_id = vals['res_id']
domain = self._mail_restrict_follower_selection_get_domain(model)
allowed = self.env['res.partner'].search(eval(domain))
if allowed and res_id in allowed.ids:
return super(MailFollowers, self).create(vals)
return self
|
Add default value to _has_data | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from calvin.runtime.south.plugins.io.sensors.distance import distance
class Distance(object):
"""
Distance sensor
"""
def __init__(self, node, actor):
self._node = node
self._actor = actor
self._distance = distance.Distance(node, self._new_measurement)
self._has_data = False
def _new_measurement(self, measurement):
self._measurement = measurement
self._has_data = True
self._node.sched.trigger_loop(actor_ids=[self._actor])
def start(self, frequency):
self._distance.start(frequency)
def stop(self):
self._distance.stop()
def has_data(self):
return self._has_data
def read(self):
if self._has_data:
self._has_data = False
return self._measurement
def register(node=None, actor=None):
return Distance(node, actor)
| # -*- coding: utf-8 -*-
# Copyright (c) 2016 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from calvin.runtime.south.plugins.io.sensors.distance import distance
class Distance(object):
"""
Distance sensor
"""
def __init__(self, node, actor):
self._node = node
self._actor = actor
self._distance = distance.Distance(node, self._new_measurement)
def _new_measurement(self, measurement):
self._measurement = measurement
self._has_data = True
self._node.sched.trigger_loop(actor_ids=[self._actor])
def start(self, frequency):
self._distance.start(frequency)
def stop(self):
self._distance.stop()
def has_data(self):
return self._has_data
def read(self):
if self._has_data:
self._has_data = False
return self._measurement
def register(node=None, actor=None):
return Distance(node, actor)
|
Use `removeClass` instead of `toggle` | $(document).ready(function()
{
$("#invite-form").on('submit', function()
{
var inviteeEmail = $("#email").val();
console.log(inviteeEmail)
if (!inviteeEmail || !inviteeEmail.length) {
alert('Please enter an email');
return false;
}
$.ajax({
type: "POST",
url: "/",
headers: {
'X-CSRFToken': csrfToken,
},
data: { email: inviteeEmail},
success: function(data) {
handleResponse(data);
}
});
return false;
});
});
function handleResponse(data) {
if (data.status === 'fail') {
$("#response-text").text(getUserFriendlyError(data.error));
}
$("#response-div").removeClass('hidden');
}
function getUserFriendlyError(error){
if(error === 'already_in_team'){
return 'Already signed up! Click on "Sign in" below to get started';
} else if(error === 'invalid_email'){
return 'Thats an invalid email address. Please check again';
} else if(error === 'already_invited'){
return 'You have been invited already. Check your inbox!';
} else if(error === 'invalid_auth'){
return 'There seems to be some issues with the setup. Please contact the admin of this channel';
} else{
return error;
}
} | $(document).ready(function()
{
$("#invite-form").on('submit', function()
{
var inviteeEmail = $("#email").val();
console.log(inviteeEmail)
if (!inviteeEmail || !inviteeEmail.length) {
alert('Please enter an email');
return false;
}
$.ajax({
type: "POST",
url: "/",
headers: {
'X-CSRFToken': csrfToken,
},
data: { email: inviteeEmail},
success: function(data) {
handleResponse(data);
}
});
return false;
});
});
function handleResponse(data) {
if (data.status === 'fail') {
$("#response-text").text(getUserFriendlyError(data.error));
}
$("#response-div").toggleClass('hidden');
}
function getUserFriendlyError(error){
if(error === 'already_in_team'){
return 'Already signed up! Click on "Sign in" below to get started';
} else if(error === 'invalid_email'){
return 'Thats an invalid email address. Please check again';
} else if(error === 'already_invited'){
return 'You have been invited already. Check your inbox!';
} else if(error === 'invalid_auth'){
return 'There seems to be some issues with the setup. Please contact the admin of this channel';
} else{
return error;
}
} |
Move dev server to port 2112 because omg collisions | var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
open: false,
https: true,
port: 2112,
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: [dest, src]
},
files: [
dest + "/**",
// Exclude Map files
"!" + dest + "/**.map"
]
},
stylus: {
src: src + "/stylus/*.styl",
dest: dest
},
sass: {
src: src + "/sass/*.{sass, scss}",
dest: dest
},
images: {
src: src + "/images/**",
dest: dest + "/images"
},
markup: {
src: src + "/htdocs/**",
dest: dest
},
ghdeploy : {
},
browserify: {
// Enable source maps
debug: false,
// Additional file extentions to make optional
extensions: ['.coffee', '.hbs'],
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [
{
entries: './src/javascript/app.js',
dest: dest,
outputName: 'app.js'
},
/*
{
entries: './src/javascript/head.js',
dest: dest,
outputName: 'head.js'
},
*/
{
entries: './src/javascript/site.js',
dest: dest,
outputName: 'site.js'
}
]
}
};
| var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
open: false,
https: true,
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: [dest, src]
},
files: [
dest + "/**",
// Exclude Map files
"!" + dest + "/**.map"
]
},
stylus: {
src: src + "/stylus/*.styl",
dest: dest
},
sass: {
src: src + "/sass/*.{sass, scss}",
dest: dest
},
images: {
src: src + "/images/**",
dest: dest + "/images"
},
markup: {
src: src + "/htdocs/**",
dest: dest
},
ghdeploy : {
},
browserify: {
// Enable source maps
debug: false,
// Additional file extentions to make optional
extensions: ['.coffee', '.hbs'],
// A separate bundle will be generated for each
// bundle config in the list below
bundleConfigs: [
{
entries: './src/javascript/app.js',
dest: dest,
outputName: 'app.js'
},
/*
{
entries: './src/javascript/head.js',
dest: dest,
outputName: 'head.js'
},
*/
{
entries: './src/javascript/site.js',
dest: dest,
outputName: 'site.js'
}
]
}
};
|
Upgrade dependency requests to ==2.10.0 | import re
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
with open('abakus/__init__.py', 'r') as fd:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(),
re.MULTILINE
).group(1)
setup(
name="django-auth-abakus",
version='1.1.0',
url='http://github.com/webkom/django-auth-abakus',
author='Webkom, Abakus Linjeforening',
author_email='[email protected]',
description='A django auth module that can be used to to authenticate '
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
'requests==2.7.0',
],
tests_require=[
'django>=1.4',
'requests==2.10.0',
'responses'
],
license='MIT',
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
"Programming Language :: Python",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Natural Language :: English",
]
)
| import re
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
with open('abakus/__init__.py', 'r') as fd:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(),
re.MULTILINE
).group(1)
setup(
name="django-auth-abakus",
version='1.1.0',
url='http://github.com/webkom/django-auth-abakus',
author='Webkom, Abakus Linjeforening',
author_email='[email protected]',
description='A django auth module that can be used to to authenticate '
'users against the API of abakus.no.',
packages=find_packages(exclude='tests'),
install_requires=[
'requests==2.7.0',
],
tests_require=[
'django>=1.4',
'requests==2.7.0',
'responses'
],
license='MIT',
test_suite='runtests.runtests',
include_package_data=True,
classifiers=[
"Programming Language :: Python",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Natural Language :: English",
]
)
|
Update data for the High Line, NYC
Looks like it was turned into a multipolygon relation in [this changeset](http://www.openstreetmap.org/changeset/47542769). | from shapely.geometry import shape
# this is mid way along the High Line in NYC, which is a huge long
# "building". we should be clipping it to a buffer of 3x the tile
# dimensions.
# http://www.openstreetmap.org/relation/7141751
with features_in_tile_layer(16, 19295, 24631, 'buildings') as buildings:
# max width and height in degress as 3x the size of the above tile
max_w = 0.0164794921875
max_h = 0.012484410579673977
# need to check that we at least saw the high line
saw_the_high_line = False
for building in buildings:
bounds = shape(building['geometry']).bounds
w = bounds[2] - bounds[0]
h = bounds[3] - bounds[1]
if building['properties']['id'] == -7141751:
saw_the_high_line = True
if w > max_w or h > max_h:
raise Exception("feature %r is %rx%r, larger than the allowed "
"%rx%r."
% (building['properties']['id'],
w, h, max_w, max_h))
if not saw_the_high_line:
raise Exception("Expected to see the High Line in this tile, "
"but didn't.")
| from shapely.geometry import shape
# this is mid way along the High Line in NYC, which is a huge long
# "building". we should be clipping it to a buffer of 3x the tile
# dimensions.
# http://www.openstreetmap.org/way/37054313
with features_in_tile_layer(16, 19295, 24631, 'buildings') as buildings:
# max width and height in degress as 3x the size of the above tile
max_w = 0.0164794921875
max_h = 0.012484410579673977
# need to check that we at least saw the high line
saw_the_high_line = False
for building in buildings:
bounds = shape(building['geometry']).bounds
w = bounds[2] - bounds[0]
h = bounds[3] - bounds[1]
if building['properties']['id'] == 37054313:
saw_the_high_line = True
if w > max_w or h > max_h:
raise Exception("feature %r is %rx%r, larger than the allowed "
"%rx%r."
% (building['properties']['id'],
w, h, max_w, max_h))
if not saw_the_high_line:
raise Exception("Expected to see the High Line in this tile, "
"but didn't.")
|
ADD title to example usage of refs | module.exports = {
stories: ['./stories/*.*'],
refs: {
ember: {
id: 'ember',
title: 'Ember',
url: 'https://5e32a5d4977061000ca89459--storybookjs.netlify.com/ember-cli',
},
cra: 'https://5e32a5d4977061000ca89459--storybookjs.netlify.com/cra-ts-kitchen-sink',
},
webpack: async config => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
resolve: {
...config.resolve,
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
managerWebpack: async config => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /manager\.js$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
}),
};
| module.exports = {
stories: ['./stories/*.*'],
refs: {
ember: 'https://5e32a5d4977061000ca89459--storybookjs.netlify.com/ember-cli',
cra: 'https://5e32a5d4977061000ca89459--storybookjs.netlify.com/cra-ts-kitchen-sink',
},
webpack: async config => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
resolve: {
...config.resolve,
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
managerWebpack: async config => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /manager\.js$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
}),
};
|
Remove _setImageText in image header | import View from '../View';
import HeaderAnalysesView from './HeaderAnalysesView';
import HeaderUserView from './HeaderUserView';
import HeaderImageView from './HeaderImageView';
import router from '../../router';
import headerTemplate from '../../templates/layout/header.pug';
import '../../stylesheets/layout/header.styl';
var HeaderView = View.extend({
events: {
'click .g-app-title': function () {
router.navigate('', {trigger: true});
}
},
initialize() {
return View.prototype.initialize.apply(this, arguments);
},
render() {
this.$el.html(headerTemplate());
this.$('a[title]').tooltip({
placement: 'bottom',
delay: {show: 300}
});
new HeaderUserView({
el: this.$('.h-current-user-wrapper'),
parentView: this
}).render();
new HeaderImageView({
el: this.$('.h-image-menu-wrapper'),
parentView: this
}).render();
new HeaderAnalysesView({
el: this.$('.h-analyses-wrapper'),
parentView: this
}).render();
return this;
}
});
export default HeaderView;
| import View from '../View';
import HeaderAnalysesView from './HeaderAnalysesView';
import HeaderUserView from './HeaderUserView';
import HeaderImageView from './HeaderImageView';
import router from '../../router';
import events from '../../events';
import headerTemplate from '../../templates/layout/header.pug';
import '../../stylesheets/layout/header.styl';
var HeaderView = View.extend({
events: {
'click .g-app-title': function () {
router.navigate('', {trigger: true});
}
},
initialize() {
this.listenTo(events, 'h:imageOpened', this._setImageText);
return View.prototype.initialize.apply(this, arguments);
},
render() {
this.$el.html(headerTemplate());
this.$('a[title]').tooltip({
placement: 'bottom',
delay: {show: 300}
});
new HeaderUserView({
el: this.$('.h-current-user-wrapper'),
parentView: this
}).render();
new HeaderImageView({
el: this.$('.h-image-menu-wrapper'),
parentView: this
}).render();
new HeaderAnalysesView({
el: this.$('.h-analyses-wrapper'),
parentView: this
}).render();
return this;
},
_setImageText(img) {
console.log(img);
}
});
export default HeaderView;
|
Comment out dependency for now | 'use strict';
// var AutoprefixPlugin = require('less-plugin-autoprefix');
var CleanCSSPlugin = require('less-plugin-clean-css');
var extend = require('extend');
var path = require('path');
var rump = require('rump');
exports.rebuild = function() {
var plugins = [];
rump.configs.main.globs = extend(true, {
build: {
less: '*.less'
},
watch: {
less: '**/*.less'
}
}, rump.configs.main.globs);
rump.configs.main.paths = extend(true, {
source: {
less: 'styles'
},
destination: {
less: 'styles'
}
}, rump.configs.main.paths);
rump.configs.main.styles = extend(true, {
minify: rump.configs.main.environment === 'production',
sourceMap: rump.configs.main.environment === 'development'
}, rump.configs.main.styles);
// plugins.push(new AutoprefixPlugin(rump.configs.main.styles.autoprefixer));
if(rump.configs.main.styles.minify) {
plugins.push(new CleanCSSPlugin({advanced: true}));
}
exports.less = extend(true, {
paths: [
'node_modules',
'bower_components',
path.join(rump.configs.main.paths.source.root,
rump.configs.main.paths.source.less)
],
plugins: plugins
}, rump.configs.main.styles.less);
};
exports.rebuild();
| 'use strict';
var AutoprefixPlugin = require('less-plugin-autoprefix');
var CleanCSSPlugin = require('less-plugin-clean-css');
var extend = require('extend');
var path = require('path');
var rump = require('rump');
exports.rebuild = function() {
var plugins = [];
rump.configs.main.globs = extend(true, {
build: {
less: '*.less'
},
watch: {
less: '**/*.less'
}
}, rump.configs.main.globs);
rump.configs.main.paths = extend(true, {
source: {
less: 'styles'
},
destination: {
less: 'styles'
}
}, rump.configs.main.paths);
rump.configs.main.styles = extend(true, {
minify: rump.configs.main.environment === 'production',
sourceMap: rump.configs.main.environment === 'development'
}, rump.configs.main.styles);
// plugins.push(new AutoprefixPlugin(rump.configs.main.styles.autoprefixer));
if(rump.configs.main.styles.minify) {
plugins.push(new CleanCSSPlugin({advanced: true}));
}
exports.less = extend(true, {
paths: [
'node_modules',
'bower_components',
path.join(rump.configs.main.paths.source.root,
rump.configs.main.paths.source.less)
],
plugins: plugins
}, rump.configs.main.styles.less);
};
exports.rebuild();
|
Fix issue with accent escaped in some xml response | package fr.insee.rmes.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.apache.commons.text.StringEscapeUtils;
import org.codehaus.stax2.io.EscapingWriterFactory;
public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {
public Writer createEscapingWriterFor(final Writer out, String enc) {
return new Writer(){
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
//WARN : the cbuf contains only part of the string = can't validate xml here
String val = "";
for (int i = off; i < len; i++) {
val += cbuf[i];
}
String escapedStr = XmlUtils.encodeXml(escapeHtml(val)); //encode manually some xml tags
out.write(escapedStr);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
}
};
}
private String escapeHtml(String s) {
s = StringEscapeUtils.unescapeHtml4(s);
return s.replace("&", "&")
.replace(">", ">")
.replace("<", "<")
.replace("\"", """);
}
public Writer createEscapingWriterFor(OutputStream out, String enc) {
throw new IllegalArgumentException("not supported");
}
} | package fr.insee.rmes.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.codehaus.stax2.io.EscapingWriterFactory;
public class CustomXmlEscapingWriterFactory implements EscapingWriterFactory {
public Writer createEscapingWriterFor(final Writer out, String enc) {
return new Writer(){
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
//WARN : the cbuf contains only part of the string = can't validate xml here
String val = "";
for (int i = off; i < len; i++) {
val += cbuf[i];
}
String escapedStr = XmlUtils.encodeXml(escapeHtml(val)); //encode manually some xml tags
out.write(escapedStr);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
}
};
}
private String escapeHtml(String s) {
return s.replace("&", "&")
.replace(">", ">")
.replace("<", "<")
.replace("\"", """);
}
public Writer createEscapingWriterFor(OutputStream out, String enc) {
throw new IllegalArgumentException("not supported");
}
} |
Fix API info reporting in "lxc info"
Signed-off-by: Stéphane Graber <[email protected]> | package shared
type ServerStateEnvironment struct {
Addresses []string `json:"addresses"`
Architectures []string `json:"architectures"`
Certificate string `json:"certificate"`
CertificateFingerprint string `json:"certificate_fingerprint"`
Driver string `json:"driver"`
DriverVersion string `json:"driver_version"`
Kernel string `json:"kernel"`
KernelArchitecture string `json:"kernel_architecture"`
KernelVersion string `json:"kernel_version"`
Server string `json:"server"`
ServerPid int `json:"server_pid"`
ServerVersion string `json:"server_version"`
Storage string `json:"storage"`
StorageVersion string `json:"storage_version"`
}
type ServerState struct {
APIExtensions []string `json:"api_extensions"`
APIStatus string `json:"api_status"`
APIVersion string `json:"api_version"`
Auth string `json:"auth"`
Environment ServerStateEnvironment `json:"environment"`
Config map[string]interface{} `json:"config"`
Public bool `json:"public"`
}
type BriefServerState struct {
Config map[string]interface{} `json:"config"`
}
func (c *ServerState) Brief() BriefServerState {
retstate := BriefServerState{Config: c.Config}
return retstate
}
| package shared
type ServerStateEnvironment struct {
Addresses []string `json:"addresses"`
Architectures []string `json:"architectures"`
Certificate string `json:"certificate"`
CertificateFingerprint string `json:"certificate_fingerprint"`
Driver string `json:"driver"`
DriverVersion string `json:"driver_version"`
Kernel string `json:"kernel"`
KernelArchitecture string `json:"kernel_architecture"`
KernelVersion string `json:"kernel_version"`
Server string `json:"server"`
ServerPid int `json:"server_pid"`
ServerVersion string `json:"server_version"`
Storage string `json:"storage"`
StorageVersion string `json:"storage_version"`
}
type ServerState struct {
APICompat int `json:"api_compat"`
Auth string `json:"auth"`
Environment ServerStateEnvironment `json:"environment"`
Config map[string]interface{} `json:"config"`
Public bool `json:"public"`
}
type BriefServerState struct {
Config map[string]interface{} `json:"config"`
}
func (c *ServerState) Brief() BriefServerState {
retstate := BriefServerState{Config: c.Config}
return retstate
}
|
Add worflow validation to prevent user replacement assumptions | (function( $ ) {
$.fn.searchify = function() {
return this.each(function() {
$(this).autocomplete({
source: $(this).data("search-url"),
select: function (event, ui) {
if (select_url = $(this).data("select-url")) {
for (element in ui.item)
select_url = select_url.replace('\(' + element + '\)', ui.item[element]);
window.location.href = select_url;
} else {
$(this).prev().val(ui.item.id);
$(this).data('value', ui.item.id)
$(this).blur();
$(this).focus();
}
}
});
$(this).change( function (event, ui) {
if ( $(this).prev().val() == '' || $(this).prev().val() != $(this).data('value') ) {
$(this).val('');
$(this).prev().val('');
}
});
$(this).focus( function (event, ui) {
$(this).data('value', '');
});
});
};
})( jQuery );
| (function( $ ) {
$.fn.searchify = function() {
return this.each(function() {
$(this).autocomplete({
source: $(this).data("search-url"),
select: function (event, ui) {
if (select_url = $(this).data("select-url")) {
for (element in ui.item)
select_url = select_url.replace('\(' + element + '\)', ui.item[element]);
window.location.href = select_url;
} else {
$(this).prev().val(ui.item.id);
$(this).data('value', ui.item.id)
$(this).blur();
$(this).focus();
}
}
});
$(this).change( function (event, ui) {
if ( $(this).data('value') != $(this).prev().val() ) {
$(this).val('');
$(this).prev().val('');
}
});
$(this).focus( function (event, ui) {
$(this).data('value', '');
});
});
};
})( jQuery );
|
Fix up regex for path matching | from __future__ import print_function, absolute_import, division
from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda, config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file [\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
def test_user_exception(self):
@cuda.jit("void(int32)", debug=True)
def test_exc(x):
if x == 1:
raise MyError
elif x == 2:
raise MyError("foo")
test_exc(0) # no raise
with self.assertRaises(MyError) as cm:
test_exc(1)
if not config.ENABLE_CUDASIM:
self.assertRegexpMatches(str(cm.exception), regex_pattern)
self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]", str(cm.exception))
with self.assertRaises(MyError) as cm:
test_exc(2)
if not config.ENABLE_CUDASIM:
self.assertRegexpMatches(str(cm.exception), regex_pattern)
self.assertRegexpMatches(str(cm.exception), regex_pattern)
self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]: foo", str(cm.exception))
if __name__ == '__main__':
unittest.main()
| from __future__ import print_function, absolute_import, division
from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda, config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file ([\.\/\\a-zA-Z_0-9]+), line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
def test_user_exception(self):
@cuda.jit("void(int32)", debug=True)
def test_exc(x):
if x == 1:
raise MyError
elif x == 2:
raise MyError("foo")
test_exc(0) # no raise
with self.assertRaises(MyError) as cm:
test_exc(1)
if not config.ENABLE_CUDASIM:
self.assertRegexpMatches(str(cm.exception), regex_pattern)
self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]", str(cm.exception))
with self.assertRaises(MyError) as cm:
test_exc(2)
if not config.ENABLE_CUDASIM:
self.assertRegexpMatches(str(cm.exception), regex_pattern)
self.assertRegexpMatches(str(cm.exception), regex_pattern)
self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]: foo", str(cm.exception))
if __name__ == '__main__':
unittest.main()
|
Remove Interstellar poster as placeholder. | package gouravexample.popularmoviesstage1;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by GOURAV on 17-08-2016.
*/
public class ViewAdapter extends ArrayAdapter<MovieItem>{
private static final String LOG_TAG = ViewAdapter.class.getSimpleName();
public ViewAdapter(Context context, int resource, List<MovieItem> objects) {
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item_movie,null);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
MovieItem item = (MovieItem)getItem(position);
Log.d(LOG_TAG,item.getPosterPath());
// imageView.setImageResource(getContext().getResources().getIdentifier((String)getItem(position), "drawable", getContext().getPackageName()));
Picasso.with(getContext())
.load(item.getPosterPath())
// .placeholder(R.drawable.circular)
// .resize(185,278)
// .centerCrop()
.into(imageView);
return convertView;
}
}
| package gouravexample.popularmoviesstage1;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by GOURAV on 17-08-2016.
*/
public class ViewAdapter extends ArrayAdapter<MovieItem>{
private static final String LOG_TAG = ViewAdapter.class.getSimpleName();
public ViewAdapter(Context context, int resource, List<MovieItem> objects) {
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item_movie,null);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
MovieItem item = (MovieItem)getItem(position);
Log.d(LOG_TAG,item.getPosterPath());
// imageView.setImageResource(getContext().getResources().getIdentifier((String)getItem(position), "drawable", getContext().getPackageName()));
Picasso.with(getContext())
.load(item.getPosterPath())
.placeholder(R.drawable.circular)
// .resize(185,278)
// .centerCrop()
.into(imageView);
return convertView;
}
}
|
Fix users retrieval for daily meeting | from datetime import datetime
from tinydb import TinyDB, Query
from tinydb_serialization import Serializer, SerializationMiddleware
class DateTimeSerializer(Serializer):
OBJ_CLASS = datetime # The class this serializer handles
def encode(self, obj):
return obj.strftime('%Y-%m-%dT%H:%M:%S')
def decode(self, s):
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
class Storage:
def __init__(self):
serialization = SerializationMiddleware()
serialization.register_serializer(DateTimeSerializer(), 'TinyDate')
self.db = TinyDB('db.json', storage=serialization)
self.users = self.db.table('users')
def get_user(self, id, default):
if default is None:
default = {'id': id, 'name': '', 'last_report': None}
query = Query()
user = self.users.get(query.id == id)
if not user:
user = default
self.users.insert(user)
return user
def get_users_for_daily_meeting(self):
query = Query()
return self.users.search(
(~ query.last_report.exists()) |
(query.last_report.test(lambda d:
not d or
d.date() < datetime.today().date()))
)
def save_user(self, user):
if not user and not 'id' in user:
raise Exception("Not a valid user")
query = Query()
self.users.update(user, query.id == user['id'])
| from datetime import datetime
from tinydb import TinyDB, Query
from tinydb_serialization import Serializer, SerializationMiddleware
class DateTimeSerializer(Serializer):
OBJ_CLASS = datetime # The class this serializer handles
def encode(self, obj):
return obj.strftime('%Y-%m-%dT%H:%M:%S')
def decode(self, s):
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
class Storage:
def __init__(self):
serialization = SerializationMiddleware()
serialization.register_serializer(DateTimeSerializer(), 'TinyDate')
self.db = TinyDB('db.json', storage=serialization)
self.users = self.db.table('users')
def get_user(self, id, default):
if default is None:
default = {'id': id, 'name': '', 'last_report': None}
query = Query()
user = self.users.get(query.id == id)
if not user:
user = default
self.users.insert(user)
return user
def get_users_for_daily_meeting(self):
query = Query()
return self.users.search(
(~ query.last_report.exists()) |
(query.last_report.test(lambda d:
d and
d.date() < datetime.today().date()))
)
def save_user(self, user):
if not user and not 'id' in user:
raise Exception("Not a valid user")
query = Query()
self.users.update(user, query.id == user['id'])
|
Update cmd to allow args
Change the cmd string so that the "args" argument can be used in linter settings. The way it was any args would be inserted between the '-file' and the filename which broke the '-file' argument.
For this config,
"cflint": {
"@disable": false,
"args": ['-configfile c:\cflintrc.xml'],
"excludes": []
}
The results are:
old: cflint -q -text -file -configfile c:\cflintrc.xml index.cfm
new: cflint -file index.cfm -q -text -configfile c:\cflintrc.xml | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by ckaznocha
# Copyright (c) 2014 ckaznocha
#
# License: MIT
#
"""This module exports the CFLint plugin class."""
from SublimeLinter.lint import Linter, util
class CFLint(Linter):
"""Provides an interface to CFLint."""
syntax = ('coldfusioncfc', 'html+cfml')
cmd = 'cflint -file @ -q -text'
version_args = '-version'
version_re = r'\b(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.1.8'
regex = r'''(?xi)
# The severity
^\s*Severity:(?:(?P<warning>(INFO|WARNING))|(?P<error>ERROR))\s*$\r?\n
# The file name
^.*$\r?\n
# The Message Code
^.*$\r?\n
# The Column number
^\s*Column:(?P<col>\d+)\s*$\r?\n
# The Line number
^\s*Line:(?P<line>\d+)\s*$\r?\n
# The Error Message
^\s*Message:(?P<message>.+)$\r?\n
'''
multiline = True
error_stream = util.STREAM_STDOUT
word_re = r'^<?(#?[-\w]+)'
tempfile_suffix = '-'
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by ckaznocha
# Copyright (c) 2014 ckaznocha
#
# License: MIT
#
"""This module exports the CFLint plugin class."""
from SublimeLinter.lint import Linter, util
class CFLint(Linter):
"""Provides an interface to CFLint."""
syntax = ('coldfusioncfc', 'html+cfml')
cmd = 'cflint -q -text -file'
version_args = '-version'
version_re = r'\b(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 0.1.8'
regex = r'''(?xi)
# The severity
^\s*Severity:(?:(?P<warning>(INFO|WARNING))|(?P<error>ERROR))\s*$\r?\n
# The file name
^.*$\r?\n
# The Message Code
^.*$\r?\n
# The Column number
^\s*Column:(?P<col>\d+)\s*$\r?\n
# The Line number
^\s*Line:(?P<line>\d+)\s*$\r?\n
# The Error Message
^\s*Message:(?P<message>.+)$\r?\n
'''
multiline = True
error_stream = util.STREAM_STDOUT
word_re = r'^<?(#?[-\w]+)'
tempfile_suffix = '-'
|
Replace lambda with higher-order function | import sys
from itertools import imap
from collections import Counter
class Room:
pass
def parse_room(s):
last_dash = s.rfind("-")
after_name = s[last_dash+1:]
bracket = after_name.find("[")
room = Room()
room.name = s[:last_dash]
room.sector = int(after_name[:bracket])
room.checksum = after_name[bracket+1:-2]
return room
def frequencies(coll):
ret = Counter(coll)
del ret['-']
return ret
def sort_frequencies(dict):
def alphasort((a, i), (b, j)):
if i != j:
return j - i
return ord(a) - ord(b)
return sorted(dict.items(), cmp=alphasort)
def run_checksum(name):
return ''.join([c for (c, n) in sort_frequencies(frequencies(name))[:5]])
def rotate(amt):
def rotator(c):
if c == '-':
return " "
x = ord(c) - ord('a')
return chr((x + amt) % 26 + ord('a'))
return rotator
if __name__ == '__main__':
sum = 0
for room in imap(parse_room, sys.stdin):
if room.checksum == run_checksum(room.name):
sum = sum + room.sector
if ('northpole object storage' ==
''.join(map(rotate(room.sector), room.name))):
print "part 2:", room.sector
print "part 1:", sum
| import sys
from itertools import imap
from collections import Counter
class Room:
pass
def parse_room(s):
last_dash = s.rfind("-")
after_name = s[last_dash+1:]
bracket = after_name.find("[")
room = Room()
room.name = s[:last_dash]
room.sector = int(after_name[:bracket])
room.checksum = after_name[bracket+1:-2]
return room
def frequencies(coll):
ret = Counter(coll)
del ret['-']
return ret
def sort_frequencies(dict):
def alphasort((a, i), (b, j)):
if i != j:
return j - i
return ord(a) - ord(b)
return sorted(dict.items(), cmp=alphasort)
def run_checksum(name):
return ''.join([c for (c, n) in sort_frequencies(frequencies(name))[:5]])
def rotate(c, amt):
if c == '-':
return " "
x = ord(c) - ord('a')
return chr((x + amt) % 26 + ord('a'))
if __name__ == '__main__':
sum = 0
for room in imap(parse_room, sys.stdin):
if room.checksum == run_checksum(room.name):
sum = sum + room.sector
if ('northpole object storage' ==
''.join(map(lambda c: rotate(c, room.sector), room.name))):
print "part 2:", room.sector
print "part 1:", sum
|
Fix init of local recognizer | import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
rl = RecognizerLoop()
self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl,
16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
| import unittest
import os
from speech_recognition import WavFile
from mycroft.client.speech.listener import RecognizerLoop
__author__ = 'seanfitz'
DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data")
class LocalRecognizerTest(unittest.TestCase):
def setUp(self):
self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000,
"en-us")
def testRecognizerWrapper(self):
source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
source = WavFile(os.path.join(DATA_DIR, "mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
def testRecognitionInLongerUtterance(self):
source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav"))
with source as audio:
hyp = self.recognizer.transcribe(audio.stream.read())
assert self.recognizer.key_phrase in hyp.hypstr.lower()
|
Use null if query strings are empty
Using `UrlUtils.buildFullRequestUrl()` if query string equals to `""` that will append `?` (but without any query string) at the end of the request.
fixes #44 | package com.kakawait.spring.security.cas.web.authentication;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
/**
* @author Thibaud Leprêtre
*/
class DefaultProxyCallbackAndServiceAuthenticationDetails
implements ProxyCallbackAndServiceAuthenticationDetails {
private final ServiceProperties serviceProperties;
private final transient HttpServletRequest context;
private final String proxyCallbackPath;
DefaultProxyCallbackAndServiceAuthenticationDetails(ServiceProperties serviceProperties, HttpServletRequest context,
String proxyCallbackPath) {
this.serviceProperties = serviceProperties;
this.context = context;
this.proxyCallbackPath = proxyCallbackPath;
}
@Override
public String getProxyCallbackUrl() {
if (proxyCallbackPath == null) {
return null;
}
String path = context.getContextPath() + proxyCallbackPath;
return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
context.getServerPort(), path, null);
}
@Override
public String getServiceUrl() {
String query = UriComponentsBuilder
.newInstance()
.query(context.getQueryString())
.replaceQueryParam(serviceProperties.getArtifactParameter(), new Object[0])
.build()
.toString()
.replaceFirst("^\\?", "");
return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
context.getServerPort(), context.getRequestURI(), StringUtils.hasText(query) ? query : null);
}
}
| package com.kakawait.spring.security.cas.web.authentication;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
/**
* @author Thibaud Leprêtre
*/
class DefaultProxyCallbackAndServiceAuthenticationDetails
implements ProxyCallbackAndServiceAuthenticationDetails {
private final ServiceProperties serviceProperties;
private final transient HttpServletRequest context;
private final String proxyCallbackPath;
DefaultProxyCallbackAndServiceAuthenticationDetails(ServiceProperties serviceProperties, HttpServletRequest context,
String proxyCallbackPath) {
this.serviceProperties = serviceProperties;
this.context = context;
this.proxyCallbackPath = proxyCallbackPath;
}
@Override
public String getProxyCallbackUrl() {
if (proxyCallbackPath == null) {
return null;
}
String path = context.getContextPath() + proxyCallbackPath;
return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
context.getServerPort(), path, null);
}
@Override
public String getServiceUrl() {
String query = UriComponentsBuilder
.newInstance()
.query(context.getQueryString())
.replaceQueryParam(serviceProperties.getArtifactParameter(), new Object[0])
.build()
.toString()
.replaceFirst("^\\?", "");
return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
context.getServerPort(), context.getRequestURI(), query);
}
}
|
Allow for a ZMQ socket to handle receiving for RPC. | <?php
namespace Prooph\ServiceBus\Message\ZeroMQ;
use ZMQSocket;
class ZeroMQSocket
{
/** @var \ZMQSocket */
private $socket;
/** @var string */
private $dsn;
/** @var bool */
private $connected = false;
/**
* @param \ZMQSocket $socket
* @param string $dsn
*/
public function __construct(ZMQSocket $socket, $dsn)
{
$this->socket = $socket;
$this->dsn = $dsn;
}
/**
* @param string|array $message
* @param int $mode
*/
public function send($message, $mode = 0)
{
if (false === $this->connected) {
$connectedTo = $this->socket->getEndpoints();
if (! in_array($this->dsn, $connectedTo)) {
$this->socket->connect($this->dsn);
}
$this->connected = true;
}
$this->socket->send($message, $mode);
}
/**
* @return string
*/
public function receive()
{
return $this->socket->recv();
}
/**
* @return bool
*/
public function handlesDeferred()
{
return $this->socket->getSocketType() === \ZMQ::SOCKET_REQ;
}
/**
* @return string
*/
public function getDsn()
{
return $this->dsn;
}
/**
* @return ZMQSocket
*/
public function getSocket()
{
return $this->socket;
}
}
| <?php
namespace Prooph\ServiceBus\Message\ZeroMQ;
use ZMQSocket;
class ZeroMQSocket
{
/** @var \ZMQSocket */
private $socket;
/** @var string */
private $dsn;
/** @var bool */
private $connected = false;
/**
* @param \ZMQSocket $socket
* @param string $dsn
*/
public function __construct(ZMQSocket $socket, $dsn)
{
$this->socket = $socket;
$this->dsn = $dsn;
}
/**
* @param string|array $message
* @param int $mode
*/
public function send($message, $mode = 0)
{
if (false === $this->connected) {
$connectedTo = $this->socket->getEndpoints();
if (! in_array($this->dsn, $connectedTo)) {
$this->socket->connect($this->dsn);
}
$this->connected = true;
}
$this->socket->send($message, $mode);
}
/**
* @return string
*/
public function getDsn()
{
return $this->dsn;
}
/**
* @return ZMQSocket
*/
public function getSocket()
{
return $this->socket;
}
}
|
Allow nullable on all fields. | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateHospitalsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('hospitals', function (Blueprint $table) {
$table->increments('id');
$table->string('provider_id')->nullable();
$table->string('name')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('zipcode')->nullable();
$table->string('county')->nullable();
$table->string('phone')->nullable();
$table->string('type')->nullable();
$table->string('ownership')->nullable();
$table->boolean('emergency_services')->nullable();
$table->string('human_address')->nullable();
$table->decimal('latitude', 18, 15)->nullable();
$table->decimal('longitude', 18, 15)->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('hospitals');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateHospitalsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('hospitals', function (Blueprint $table) {
$table->increments('id');
$table->string('provider_id');
$table->string('name');
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('zipcode');
$table->string('county');
$table->string('phone');
$table->string('type');
$table->string('ownership');
$table->boolean('emergency_services');
$table->string('human_address')->default("");
$table->decimal('latitude', 18, 15);
$table->decimal('longitude', 18, 15);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('hospitals');
}
}
|
Correct messages printed during tests | 'use strict';
module.exports = function (grunt) {
require('time-grunt')(grunt);
grunt.initConfig({
eslint: {
all: {
src: [
'*.js',
'bin/grunth',
'lib/*.js',
],
},
},
jscs: {
all: {
src: '<%= eslint.all.src %>',
options: {
config: '.jscsrc',
},
},
},
});
// Load all grunt tasks matching the `grunt-*` pattern.
require('load-grunt-tasks')(grunt);
grunt.registerTask('asserts', function () {
try {
/* eslint-disable no-eval */
eval('function* f() {yield 2;} var g = f(); g.next();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Generators not recognized!');
}
grunt.log.writeln('Generators recognized.');
try {
/* eslint-disable no-eval */
eval('function f() {"use strict"; const x = 2; let y = 3; return [x, y];} f();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Block scoping (const/let) not recognized!');
}
grunt.log.writeln('Block scoping (const/let) recognized.');
});
grunt.registerTask('lint', [
'eslint',
'jscs',
]);
grunt.registerTask('test', [
'lint',
'asserts',
]);
grunt.registerTask('default', ['test']);
};
| 'use strict';
module.exports = function (grunt) {
require('time-grunt')(grunt);
grunt.initConfig({
eslint: {
all: {
src: [
'*.js',
'bin/grunth',
'lib/*.js',
],
},
},
jscs: {
all: {
src: '<%= eslint.all.src %>',
options: {
config: '.jscsrc',
},
},
},
});
// Load all grunt tasks matching the `grunt-*` pattern.
require('load-grunt-tasks')(grunt);
grunt.registerTask('asserts', function () {
try {
/* eslint-disable no-eval */
eval('function* f() {yield 2;} var g = f(); g.next();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Generators not recognized!');
}
try {
/* eslint-disable no-eval */
eval('function f() {"use strict"; const x = 2; return x;} f();');
/* eslint-ensable no-eval */
} catch (e) {
throw new Error('Generators not recognized!');
}
});
grunt.registerTask('lint', [
'eslint',
'jscs',
]);
grunt.registerTask('test', [
'lint',
'asserts',
]);
grunt.registerTask('default', ['test']);
};
|
[AllBundles] Fix incorrect namespaces in test classes | <?php
namespace Kunstmaan\UtilitiesBundle\Tests\Helper;
use Kunstmaan\UtilitiesBundle\Helper\Slugifier;
use PHPUnit\Framework\TestCase;
class SlugifierTest extends TestCase
{
/**
* @var Slugifier
*/
private $slugifier;
public function setUp(): void
{
$this->slugifier = new Slugifier();
}
/**
* @param string $text The text to slugify
* @param string $result The slug it should generate
*
* @dataProvider getSlugifyData
*/
public function testSlugify($text, $result)
{
$this->assertEquals($result, $this->slugifier->slugify($text));
}
/**
* Provides data to the {@link testSlugify} function
*
* @return array
*/
public function getSlugifyData()
{
return [
['', ''],
['test', 'test'],
['een titel met spaties', 'een-titel-met-spaties'],
['à partir d\'aujourd\'hui', 'a-partir-daujourdhui'],
['CaPs ShOulD be LoweRCasEd', 'caps-should-be-lowercased'],
['áàäåéèëíìïóòöúùüñßæ', 'aaaaeeeiiiooouuunssae'],
['polish-ążśźęćńół', 'polish-azszecnol'],
];
}
}
| <?php
namespace Kunstmaan\NodeBundle\Tests\Helper;
use Kunstmaan\UtilitiesBundle\Helper\Slugifier;
use PHPUnit\Framework\TestCase;
class SlugifierTest extends TestCase
{
/**
* @var Slugifier
*/
private $slugifier;
public function setUp(): void
{
$this->slugifier = new Slugifier();
}
/**
* @param string $text The text to slugify
* @param string $result The slug it should generate
*
* @dataProvider getSlugifyData
*/
public function testSlugify($text, $result)
{
$this->assertEquals($result, $this->slugifier->slugify($text));
}
/**
* Provides data to the {@link testSlugify} function
*
* @return array
*/
public function getSlugifyData()
{
return [
['', ''],
['test', 'test'],
['een titel met spaties', 'een-titel-met-spaties'],
['à partir d\'aujourd\'hui', 'a-partir-daujourdhui'],
['CaPs ShOulD be LoweRCasEd', 'caps-should-be-lowercased'],
['áàäåéèëíìïóòöúùüñßæ', 'aaaaeeeiiiooouuunssae'],
['polish-ążśźęćńół', 'polish-azszecnol'],
];
}
}
|
Revert "Revert "Revert "Reorder operator"""
This reverts commit 78a1b5e8391875e2b0e9e8272104e80ca10f3275. | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tw.edu.npu.mis;
/**
* The model class of the calculator application.
*/
public class Calculator {
/**
* The available operators of the calculator.
*/
public enum Operator {
EQUAL, // =
PLUS, // +
MINUS, // -
TIMES, // ×
OVER, // ⁄
PLUS_MINUS, // ±
RECIPROCAL, // 1/x
PERCENT, // %
SQRT, // √
BACKSPACE, // ⌫
CLEAR, // C
CLEAR_ENTRY, // CE
MEM_SET, // MS
MEM_PLUS, // M+
MEM_MINUS, // M-
MEM_RECALL, // MR
MEM_CLEAR // MC
}
public void appendDigit(int digit) {
// TODO code application logic here
}
public void appendDot() {
// TODO code application logic here
}
public void performOperation(Operator operator) {
// TODO code application logic here
}
public String getDisplay() {
// TODO code application logic here
return null;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tw.edu.npu.mis;
/**
* The model class of the calculator application.
*/
public class Calculator {
/**
* The available operators of the calculator.
*/
public enum Operator {
CLEAR, // C
CLEAR_ENTRY, // CE
BACKSPACE, // ⌫
EQUAL, // =
PLUS, // +
MINUS, // -
TIMES, // ×
OVER, // ⁄
PLUS_MINUS, // ±
RECIPROCAL, // 1/x
PERCENT, // %
SQRT, // √
MEM_CLEAR, // MC
MEM_SET, // MS
MEM_PLUS, // M+
MEM_MINUS, // M-
MEM_RECALL // MR
}
public void appendDigit(int digit) {
// TODO code application logic here
}
public void appendDot() {
// TODO code application logic here
}
public void performOperation(Operator operator) {
// TODO code application logic here
}
public String getDisplay() {
// TODO code application logic here
return null;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
|
Fix tests to allow use of random, but not change each time | import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
| import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
|
Make this test an expected fail on darwin until we can fix this bug.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@197087 91177308-0d34-0410-b5e6-96231b3b80d8 | """
Test example snippets from the lldb 'help expression' output.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
import lldbutil
class Radar9673644TestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break inside main().
self.main_source = "main.c"
self.line = line_number(self.main_source, '// Set breakpoint here.')
@expectedFailureDarwin(15641319)
def test_expr_commands(self):
"""The following expression commands should just work."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
self.runCmd("run", RUN_SUCCEEDED)
# rdar://problem/9673664 lldb expression evaluation problem
self.expect('expr char c[] = "foo"; c[0]',
substrs = ["'f'"])
# runCmd: expr char c[] = "foo"; c[0]
# output: (char) $0 = 'f'
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
| """
Test example snippets from the lldb 'help expression' output.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
import lldbutil
class Radar9673644TestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to break inside main().
self.main_source = "main.c"
self.line = line_number(self.main_source, '// Set breakpoint here.')
# rdar://problem/9673664
def test_expr_commands(self):
"""The following expression commands should just work."""
self.buildDefault()
self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
self.runCmd("run", RUN_SUCCEEDED)
# rdar://problem/9673664 lldb expression evaluation problem
self.expect('expr char c[] = "foo"; c[0]',
substrs = ["'f'"])
# runCmd: expr char c[] = "foo"; c[0]
# output: (char) $0 = 'f'
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
|
Remove exclusion of node_modules as Uglify needs all code as ES5 | var path = require('path');
var webpack = require('webpack');
module.exports = {
regular: {
devtool: 'source-map',
output: {
filename: 'meyda.js'
},
module: {
rules: [
{
test: /\.js$/,
//exclude: /node_modules/, <-- include node_modules because of jsfft's ES6 push to npm 😡
loader: 'babel-loader',
options: {
presets: [[ 'es2015', { modules: false } ]]
}
}
]
}
},
minified: {
devtool: 'source-map',
output: {
filename: 'meyda.min.js',
sourceMapFilename: 'meyda.min.map'
},
module: {
rules: [
{
test: /\.js$/,
//exclude: /node_modules/, <-- include node_modules because of jsfft's ES6 push to npm 😡
loader: 'babel-loader',
options: {
presets: [[ 'es2015', { modules: false } ]]
}
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true,
drop_console: false
},
sourceMap: true
})
]
}
}; | var path = require('path');
var webpack = require('webpack');
module.exports = {
regular: {
output: {
filename: 'meyda.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [[ 'es2015', { modules: false } ]]
}
}
]
}
},
minified: {
devtool: 'source-map',
output: {
filename: 'meyda.min.js',
sourceMapFilename: 'meyda.min.map'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [[ 'es2015', { modules: false } ]]
}
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true,
drop_console: false
},
sourceMap: true
})
]
}
}; |
[QT] Refactor platform branching in JS bridge call
This is to avoid conflicts in some recent versions of QtWebEngine, where
window.external does seems to be present by default. It's better to
check for Qt first; window.qt is not likely to be defined anywhere else,
so we won't hopefully run to conflicts. | window.pywebview = {
_createApi: function(funcList) {
for (var i = 0; i < funcList.length; i++) {
window.pywebview.api[funcList[i]] = (function (funcName) {
return function(params) {
var promise = new Promise(function(resolve, reject) {
window.pywebview._checkValue(funcName, resolve);
});
window.pywebview._bridge.call(funcName, JSON.stringify(params))
return promise;
}
})(funcList[i])
window.pywebview._returnValues[funcList[i]] = {
isSet: false,
value: undefined,
}
}
},
_bridge: {
call: function (func_name, params) {
if (window.qt) {
new QWebChannel(qt.webChannelTransport, function(channel) {
channel.objects.external.call(func_name, params)
});
} else if (window.external) {
return window.external.call(func_name, params)
}
}
},
_checkValue: function(funcName, resolve) {
var check = setInterval(function () {
var returnObj = window.pywebview._returnValues[funcName]
if (returnObj.isSet) {
returnObj.isSet = false
try {
resolve(JSON.parse(returnObj.value.replace(/\n/, '\\n')))
} catch(e) {
resolve(returnObj.value)
}
clearInterval(check);
}
}, 100)
},
api: {},
_returnValues: {},
}
window.pywebview._createApi(%s)
| window.pywebview = {
_createApi: function(funcList) {
for (var i = 0; i < funcList.length; i++) {
window.pywebview.api[funcList[i]] = (function (funcName) {
return function(params) {
var promise = new Promise(function(resolve, reject) {
window.pywebview._checkValue(funcName, resolve);
});
window.pywebview._bridge.call(funcName, JSON.stringify(params))
return promise;
}
})(funcList[i])
window.pywebview._returnValues[funcList[i]] = {
isSet: false,
value: undefined,
}
}
},
_bridge: {
call: function (func_name, params) {
if (window.external) {
return window.external.call(func_name, params)
} else if (window.qt) {
new QWebChannel(qt.webChannelTransport, function(channel) {
channel.objects.external.call(func_name, params)
});
}
}
},
_checkValue: function(funcName, resolve) {
var check = setInterval(function () {
var returnObj = window.pywebview._returnValues[funcName]
if (returnObj.isSet) {
returnObj.isSet = false
try {
resolve(JSON.parse(returnObj.value.replace(/\n/, '\\n')))
} catch(e) {
resolve(returnObj.value)
}
clearInterval(check);
}
}, 100)
},
api: {},
_returnValues: {},
}
window.pywebview._createApi(%s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.