text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Handle NFC permission being unavailable.
With a rooted device, some apps can remove permissions. Prevents chrome
from crashing if NFC is revoked.
BUG=481979
Review URL: https://codereview.chromium.org/1104053003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#327571} | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.nfc;
import android.app.Activity;
import android.nfc.NfcAdapter;
import android.util.Log;
/**
* Initializes Android Beam (sharing URL via NFC) for devices that have NFC. If user taps their
* device with another Beam capable device, then Chrome gets the current URL, filters for security
* and returns the result to Android.
*/
public final class BeamController {
/**
* If the device has NFC, construct a BeamCallback and pass it to Android.
*
* @param activity Activity that is sending out beam messages.
* @param provider Provider that returns the URL that should be shared.
*/
public static void registerForBeam(final Activity activity, final BeamProvider provider) {
final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) return;
try {
final BeamCallback beamCallback = new BeamCallback(activity, provider);
nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
} catch (IllegalStateException | SecurityException e) {
Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
}
}
}
| // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.nfc;
import android.app.Activity;
import android.nfc.NfcAdapter;
import android.util.Log;
/**
* Initializes Android Beam (sharing URL via NFC) for devices that have NFC. If user taps their
* device with another Beam capable device, then Chrome gets the current URL, filters for security
* and returns the result to Android.
*/
public final class BeamController {
/**
* If the device has NFC, construct a BeamCallback and pass it to Android.
*
* @param activity Activity that is sending out beam messages.
* @param provider Provider that returns the URL that should be shared.
*/
public static void registerForBeam(final Activity activity, final BeamProvider provider) {
final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) return;
try {
final BeamCallback beamCallback = new BeamCallback(activity, provider);
nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
} catch (IllegalStateException e) {
Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
}
}
}
|
Add requests[security] extras to install_requires
Installs pyopenssl, ndg-httpsclient, and pyasn1 packages to avoid SSL InsecurePlatformWarning messages | #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='bux-grader-framework',
version='0.4.3',
author='Boston University',
author_email='webteam@bu.edu',
url='https://github.com/bu-ist/bux-grader-framework/',
description='An external grader framework for the edX platform.',
long_description=open('README.md').read(),
packages=['bux_grader_framework', 'bux_grader_test_framework'],
scripts=['bin/grader'],
license='LICENSE',
install_requires=[
'requests[security]>=2.0, <3.0',
'pika>=0.9.12, <0.10',
'statsd>=2.0, <3.0',
'lxml>=3.3, <3.4'
]
)
| #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='bux-grader-framework',
version='0.4.3',
author='Boston University',
author_email='webteam@bu.edu',
url='https://github.com/bu-ist/bux-grader-framework/',
description='An external grader framework for the edX platform.',
long_description=open('README.md').read(),
packages=['bux_grader_framework', 'bux_grader_test_framework'],
scripts=['bin/grader'],
license='LICENSE',
install_requires=[
'requests>=2.0, <3.0',
'pika>=0.9.12, <0.10',
'statsd>=2.0, <3.0',
'lxml>=3.3, <3.4'
]
)
|
Change format of log lines | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger("blockbuster")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger("blockbuster")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh) |
Add string for execution mode | package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale;
import com.google.gwt.i18n.client.Messages;
@DefaultLocale("en")
public interface SqlRequestLauncherConstants extends Messages {
@DefaultMessage("Open SQL editor")
String menuEntryOpenSqlEditor();
@DefaultMessage("SQL editor")
String sqlEditorWindowTitle();
@DefaultMessage("Select datasource")
String selectDatasourceLabel();
@DefaultMessage("Result limit")
String resultLimitLabel();
@DefaultMessage("Execute")
String executeButtonLabel();
@DefaultMessage("{0} rows.")
@AlternateMessage({"one", "{0} row."})
String updateCountMessage(@PluralCount int count);
@DefaultMessage("Export as CSV file")
String exportCsvLabel();
@DefaultMessage("Execution mode")
String executionModeLabel();
@DefaultMessage("Execute all - ignore and report errors")
String executeAllModeItem();
@DefaultMessage("First error - stop on first error")
String stopOnErrorModeitem();
@DefaultMessage("Transaction - rollback on first error")
String transactionModeItem();
}
| package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale;
import com.google.gwt.i18n.client.Messages;
@DefaultLocale("en")
public interface SqlRequestLauncherConstants extends Messages {
@DefaultMessage("Open SQL editor")
String menuEntryOpenSqlEditor();
@DefaultMessage("SQL editor")
String sqlEditorWindowTitle();
@DefaultMessage("Select datasource")
String selectDatasourceLabel();
@DefaultMessage("Result limit")
String resultLimitLabel();
@DefaultMessage("Execute")
String executeButtonLabel();
@DefaultMessage("{0} rows.")
@AlternateMessage({"one", "{0} row."})
String updateCountMessage(@PluralCount int count);
@DefaultMessage("Export as CSV file")
String exportCsvLabel();
}
|
Update the comment spelling :-p | package org.jsmpp.session;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;
/**
* This listener will listen to every incoming short message, recognized by
* deliver_sm command. The logic on this listener should be accomplish in a
* short time, because the deliver_sm_resp will be processed after the logic
* executed. Normal logic will be return the deliver_sm_resp with zero valued
* command_status, or throw {@link ProcessMessageException} that gave non-zero
* valued command_status (in means negative response) depends on the given error
* code specified on the {@link ProcessMessageException}.
*
* @author uudashr
* @version 1.0
* @since 2.0
*
*/
public interface MessageReceiverListener {
/**
* Event that called when an short message accepted.
*
* @param deliverSm is the deliver_sm command.
* @throws ProcessMessageException throw if there should be return Non-OK
* command_status for the response.
*/
public void onAcceptDeliverSm(DeliverSm deliverSm)
throws ProcessMessageException;
}
| package org.jsmpp.session;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;
/**
* This listener will listen to every incomming short message, recognized by
* deliver_sm command. The logic on this listener should be accomplish in a
* short time, because the deliver_sm_resp will be processed after the logic
* executed. Normal logic will be return the deliver_sm_resp with zero valued
* command_status, or throw {@link ProcessMessageException} that gave non-zero
* valued command_status (in means negative response) depends on the given error
* code specified on the {@link ProcessMessageException}.
*
* @author uudashr
* @version 1.0
* @since 2.0
*
*/
public interface MessageReceiverListener {
/**
* Event that called when an short message accepted.
*
* @param deliverSm is the deliver_sm command.
* @throws ProcessMessageException throw if there should be return Non-OK
* command_status for the response.
*/
public void onAcceptDeliverSm(DeliverSm deliverSm)
throws ProcessMessageException;
}
|
Change python code to only listen on localhost | import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = 'localhost'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
| import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = ''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
|
Fix select query constructor docu | <?php
class CM_Db_Query_Select extends CM_Db_Query_Abstract {
/**
* @param string $table
* @param string|array $fields Column-name OR Column-names array
* @param string|array|null $where Associative array field=>value OR string
* @param string|null $order
*/
public function __construct($table, $fields, $where = null, $order = null) {
$fields = (array) $fields;
foreach ($fields as &$field) {
if ($field == '*') {
$field = '*';
} else {
$field = $this->_quoteIdentifier($field);
}
}
$this->_addSql('SELECT ' . implode(',', $fields));
$this->_addSql('FROM ' . $this->_quoteIdentifier($table));
$this->_addWhere($where);
$this->_addOrderBy($order);
}
}
| <?php
class CM_Db_Query_Select extends CM_Db_Query_Abstract {
/**
* @param string $table
* @param string|array $fields Column-name OR Column-names array
* @param string|array|null $where Associative array field=>value OR string
* @param string|null $order
* @return CM_Db_Query_Select
*/
public function __construct($table, $fields, $where = null, $order = null) {
$fields = (array) $fields;
foreach ($fields as &$field) {
if ($field == '*') {
$field = '*';
} else {
$field = $this->_quoteIdentifier($field);
}
}
$this->_addSql('SELECT ' . implode(',', $fields));
$this->_addSql('FROM ' . $this->_quoteIdentifier($table));
$this->_addWhere($where);
$this->_addOrderBy($order);
}
}
|
Remove Component Test Blueprint `assert.expect`s
All steps in the generated exercise and assertion phases occur
synchronously. Therefore, the `assert.expect(n)` lines:
* add noise to the generated file
* make the resulting tests brittle
* encourages new Ember developers to unnecessarily add them to future
tests | import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });" + EOL + EOL +
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:" + EOL +
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>
// Creates the component instance
/*var component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
| import { moduleForComponent, test } from 'ember-qunit';<% if (testType === 'integration') { %>
import hbs from 'htmlbars-inline-precompile';<% } %>
moduleForComponent('<%= componentPathName %>', '<%= friendlyTestDescription %>', {
<% if (testType === 'integration' ) { %>integration: true<% } else if(testType === 'unit') { %>// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true<% } %>
});
test('it renders', function(assert) {
<% if (testType === 'integration' ) { %>assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });" + EOL + EOL +
this.render(hbs`{{<%= componentPathName %>}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:" + EOL +
this.render(hbs`
{{#<%= componentPathName %>}}
template block text
{{/<%= componentPathName %>}}
`);
assert.equal(this.$().text().trim(), 'template block text');<% } else if(testType === 'unit') { %>assert.expect(1);
// Creates the component instance
/*var component =*/ this.subject();
// Renders the component to the page
this.render();
assert.equal(this.$().text().trim(), '');<% } %>
});
|
Enable CORS on the API server. | var express = require('express');
var MetaInspector = require('node-metainspector');
var app = express();
// TODO: Improve CSP
// http://enable-cors.org/server_expressjs.html
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.get('/api/v1/urlmeta/:url', function(req, res) {
var client = new MetaInspector(req.params.url, {});
client.on('fetch', function () {
res.json({
url: client.url,
title: client.title
});
});
client.on('error', function (err) {
res.statusCode = 404;
res.json(err);
});
client.fetch();
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('API server listening at http://%s:%s', host, port);
}); | var express = require('express');
var MetaInspector = require('node-metainspector');
var app = express();
app.get('/api/v1/urlmeta/:url', function(req, res) {
var client = new MetaInspector(req.params.url, {});
client.on('fetch', function () {
res.json({
url: client.url,
title: client.title
});
});
client.on('error', function (err) {
res.statusCode = 404;
res.json(err);
});
client.fetch();
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('API server listening at http://%s:%s', host, port);
}); |
Remove extraneous call in demo app | package com.google.maps.android.utils.demo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public abstract class BaseDemoActivity extends FragmentActivity {
private GoogleMap mMap;
protected int getLayoutId() {
return R.layout.map;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
startDemo();
}
private void setUpMapIfNeeded() {
if (mMap != null) {
return;
}
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}
/**
* Run the demo-specific code.
*/
protected abstract void startDemo();
protected GoogleMap getMap() {
setUpMapIfNeeded();
return mMap;
}
}
| package com.google.maps.android.utils.demo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public abstract class BaseDemoActivity extends FragmentActivity {
private GoogleMap mMap;
protected int getLayoutId() {
return R.layout.map;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
startDemo();
}
private void setUpMapIfNeeded() {
if (mMap != null) {
return;
}
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap == null) {
return;
}
}
/**
* Run the demo-specific code.
*/
protected abstract void startDemo();
protected GoogleMap getMap() {
setUpMapIfNeeded();
return mMap;
}
}
|
Add error handling and change names of properties. | var mongodb = require('mongodb');
var nodefn = require('when/node');
var util = require('util');
// ### Errors ###
function MongoConnectionError(error) {
this.name = 'MongoConnectionError';
this.message = error;
}
util.inherits(MongoConnectionError, Error);
function MongoAdapter() {
this._connectURI = 'mongodb://0.0.0.0:27017/';
this._databaseName = 'testowa';
this.collections = {
'users': undefined
};
}
MongoAdapter.prototype.connect = function () {
var self = this;
return function (req, res, next) {
var MongoClient = mongodb.MongoClient;
var promisedConnect = nodefn.call(MongoClient.connect, self._connectURI + self._databaseName);
promisedConnect.done(function (db) {
for (var collection in self.collections) {
self.collections[collection] = db.collection(collection);
}
next();
}, function (error) {
throw new MongoConnectionError(error);
});
};
};
module.exports.MongoAdapter = MongoAdapter; | var mongodb = require('mongodb');
var nodefn = require('when/node');
function MongoAdapter() {
this.connectURI = 'mongodb://0.0.0.0:27017/';
this.databaseName = 'testowa';
this.collections = {
'users': undefined
};
}
MongoAdapter.prototype.connect = function () {
var self = this;
return function (req, res, next) {
var MongoClient = mongodb.MongoClient;
var promisedConnect = nodefn.call(MongoClient.connect, self.connectURI + self.databaseName);
promisedConnect.done(function (db) {
for (var collection in self.collections) {
self.collections[collection] = db.collection(collection);
}
next();
}, function (error) {
console.log('!!', error);
next();
});
};
};
module.exports.MongoAdapter = MongoAdapter; |
Check integration test source address. | package net.ripe.db.whois.common.domain;
import com.google.common.collect.Sets;
import net.ripe.db.whois.common.etree.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Set;
@Component
public class IpRanges {
private static final Logger LOGGER = LoggerFactory.getLogger(IpRanges.class);
private Set<Interval> ripeRanges;
@Value("${ipranges.trusted}")
public void setRipeRanges(final String... ripeRanges) {
final Set<Interval> ipResources = Sets.newLinkedHashSetWithExpectedSize(ripeRanges.length);
for (final String ripeRange : ripeRanges) {
ipResources.add(IpInterval.parse(ripeRange));
}
this.ripeRanges = ipResources;
LOGGER.info("Using ripe ranges: {}", ripeRanges);
}
public boolean isInRipeRange(final Interval ipResource) {
for (final Interval resource : ripeRanges) {
if (resource.getClass().equals(ipResource.getClass()) && resource.contains(ipResource)) {
return true;
}
}
LOGGER.info("{} is not in RIPE range", ipResource.toString());
return false;
}
}
| package net.ripe.db.whois.common.domain;
import com.google.common.collect.Sets;
import net.ripe.db.whois.common.etree.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Set;
@Component
public class IpRanges {
private static final Logger LOGGER = LoggerFactory.getLogger(IpRanges.class);
private Set<Interval> ripeRanges;
@Value("${ipranges.trusted}")
public void setRipeRanges(final String... ripeRanges) {
final Set<Interval> ipResources = Sets.newLinkedHashSetWithExpectedSize(ripeRanges.length);
for (final String ripeRange : ripeRanges) {
ipResources.add(IpInterval.parse(ripeRange));
}
this.ripeRanges = ipResources;
LOGGER.info("Using ripe ranges: {}", ripeRanges);
}
public boolean isInRipeRange(final Interval ipResource) {
for (final Interval resource : ripeRanges) {
if (resource.getClass().equals(ipResource.getClass()) && resource.contains(ipResource)) {
return true;
}
}
return false;
}
}
|
Check for unchecked repos in more than just the edx org | #!/usr/bin/env python
"""List repos missing from repos.yaml."""
from __future__ import print_function
import yaml
from helpers import paginated_get
REPOS_URL = "https://api.github.com/orgs/{org}/repos"
# This is hacky; you need to have repo-tools-data cloned locally one dir up.
# To do this properly, you should use yamldata.py
with open("../repo-tools-data/repos.yaml") as repos_yaml:
tracked_repos = yaml.load(repos_yaml)
ORGS = ["edX", "edx-solutions"]
repos = []
for org in ORGS:
repos.extend(paginated_get(REPOS_URL.format(org=org)))
shown_any = False
for r in repos:
if not r['private'] and not r['fork']:
if r['full_name'] not in tracked_repos:
if not shown_any:
print("\n### Untracked repos:")
print("{r[full_name]}: {r[description]}".format(r=r))
shown_any = True
shown_any = False
actual_repos = set(r['full_name'] for r in repos)
for tracked in tracked_repos:
if tracked not in actual_repos:
if not shown_any:
print("\n### Disappeared repos:")
print(tracked)
shown_any = True
| #!/usr/bin/env python
"""List repos missing from repos.yaml."""
from __future__ import print_function
import yaml
from helpers import paginated_get
REPOS_URL = "https://api.github.com/orgs/{org}/repos"
# This is hacky; you need to have repo-tools-data cloned locally one dir up.
# To do this properly, you should use yamldata.py
with open("../repo-tools-data/repos.yaml") as repos_yaml:
tracked_repos = yaml.load(repos_yaml)
repos = list(paginated_get(REPOS_URL.format(org="edX")))
shown_any = False
for r in repos:
if not r['private'] and not r['fork']:
if r['full_name'] not in tracked_repos:
if not shown_any:
print("\n### Untracked repos:")
print("{r[full_name]}: {r[description]}".format(r=r))
shown_any = True
shown_any = False
actual_repos = set(r['full_name'] for r in repos)
for tracked in tracked_repos:
if tracked not in actual_repos:
if not shown_any:
print("\n### Disappeared repos:")
print(tracked)
shown_any = True
|
Fix the syntax for NickServ logins | from pyheufybot.module_interface import Module, ModuleType
from pyheufybot.message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", "IDENTIFY " + password, responseType.MESSAGE) ]
else:
return []
| from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
from pyheufybot import globalvars
class NickServIdentify(Module):
def __init__(self):
self.moduleType = ModuleType.PASSIVE
self.messageTypes = ["USER"]
self.helpText = "Attempts to log into NickServ with the password in the config"
def execute(self, message, serverInfo):
config = globalvars.botHandler.factories[serverInfo.name].config
passwordType = config.getSettingWithDefault("passwordType", None)
password = config.getSettingWithDefault("password", "")
if passwordType == "NickServ":
return [ IRCResponse("NickServ", password, responseType.MESSAGE) ]
else:
return []
|
Use an optimized crc32 library which is faster | package sarama
import (
"encoding/binary"
"github.com/klauspost/crc32"
)
// crc32Field implements the pushEncoder and pushDecoder interfaces for calculating CRC32s.
type crc32Field struct {
startOffset int
}
func (c *crc32Field) saveOffset(in int) {
c.startOffset = in
}
func (c *crc32Field) reserveLength() int {
return 4
}
func (c *crc32Field) run(curOffset int, buf []byte) error {
crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
binary.BigEndian.PutUint32(buf[c.startOffset:], crc)
return nil
}
func (c *crc32Field) check(curOffset int, buf []byte) error {
crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
if crc != binary.BigEndian.Uint32(buf[c.startOffset:]) {
return PacketDecodingError{"CRC didn't match"}
}
return nil
}
| package sarama
import (
"encoding/binary"
"hash/crc32"
)
// crc32Field implements the pushEncoder and pushDecoder interfaces for calculating CRC32s.
type crc32Field struct {
startOffset int
}
func (c *crc32Field) saveOffset(in int) {
c.startOffset = in
}
func (c *crc32Field) reserveLength() int {
return 4
}
func (c *crc32Field) run(curOffset int, buf []byte) error {
crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
binary.BigEndian.PutUint32(buf[c.startOffset:], crc)
return nil
}
func (c *crc32Field) check(curOffset int, buf []byte) error {
crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset])
if crc != binary.BigEndian.Uint32(buf[c.startOffset:]) {
return PacketDecodingError{"CRC didn't match"}
}
return nil
}
|
Make steps and out arguments optional and add defaults | from argparse import ArgumentParser
from matplotlib import pyplot as plt
from graph import Greengraph
def process():
parser = ArgumentParser(
description="Produce graph quantifying the amount of green land between two locations")
parser.add_argument("--start", required=True,
help="The starting location ")
parser.add_argument("--end", required=True,
help="The ending location")
parser.add_argument("--steps",
help="The number of steps between the starting and ending locations, defaults to 10")
parser.add_argument("--out",
help="The output filename, defaults to graph.png")
arguments = parser.parse_args()
mygraph = Greengraph(arguments.start, arguments.end)
if arguments.steps:
data = mygraph.green_between(arguments.steps)
else:
data = mygraph.green_between(10)
plt.plot(data)
# TODO add a title and axis labels to this graph
if arguments.out:
plt.savefig(arguments.out)
else:
plt.savefig("graph.png")
if __name__ == "__main__":
process()
| from argparse import ArgumentParser
from matplotlib import pyplot as plt
from graph import Greengraph
def process():
parser = ArgumentParser(
description="Produce graph of green land between two locations")
parser.add_argument("--start", required=True,
help="The starting location ")
parser.add_argument("--end", required=True,
help="The ending location")
parser.add_argument("--steps", required=True,
help="The number of steps between the starting and ending locations")
parser.add_argument("--out", required=True,
help="The output filename")
arguments = parser.parse_args()
mygraph = Greengraph(arguments.start, arguments.end)
data = mygraph.green_between(arguments.steps)
plt.plot(data)
# TODO add a title and axis labels to this graph
plt.savefig(arguments.out)
if __name__ == "__main__":
process()
|
Update server url with https | # -*- coding: utf-8 -*-
"""
como.settings - some global variables
"""
import os
from paxo.util import DEBUG_MODE
LOCATION_CODES = [
'1C', '2Z', '4H', '5K', '8H', '5D', '7J', 'CK', 'E', 'EE',
'F', 'FC', 'G8', 'GQ', 'PT', 'CY', 'QT', 'QP', 'RN', 'RM',
'SG', 'UV', 'U2', 'V7', 'VM', 'W8', 'WQ', 'XA', 'XB', 'YM'
]
DEV_URL = 'http://127.0.0.1:5000'
REAL_URL = 'https://como.cwoebker.com'
COMO_BATTERY_FILE = os.path.expanduser('~/.como')
if DEBUG_MODE:
SERVER_URL = DEV_URL
else:
SERVER_URL = REAL_URL
| # -*- coding: utf-8 -*-
"""
como.settings - some global variables
"""
import os
from paxo.util import DEBUG_MODE
LOCATION_CODES = [
'1C', '2Z', '4H', '5K', '8H', '5D', '7J', 'CK', 'E', 'EE',
'F', 'FC', 'G8', 'GQ', 'PT', 'CY', 'QT', 'QP', 'RN', 'RM',
'SG', 'UV', 'U2', 'V7', 'VM', 'W8', 'WQ', 'XA', 'XB', 'YM'
]
DEV_URL = 'http://127.0.0.1:5000'
REAL_URL = 'http://como.cwoebker.com'
COMO_BATTERY_FILE = os.path.expanduser('~/.como')
if DEBUG_MODE:
SERVER_URL = DEV_URL
else:
SERVER_URL = REAL_URL
|
Increase max length for repo names | """ Basic models, such as user profile """
from django.db import models
class Language(models.Model):
name = models.CharField(max_length=40, null=False)
learn_url = models.URLField(null=True, blank=True)
@staticmethod
def all():
return [l.name for l in Language.objects.all()]
def __unicode__(self):
return self.name
class Repo(models.Model):
# Full name is required
full_name = models.CharField(max_length=300, null=False)
url = models.URLField(null=True)
language = models.ForeignKey(Language, related_name='repos')
description = models.CharField(max_length=500, null=True, blank=True)
def save(self, *args, **kwargs):
'''Override save method to set default url.'''
BASE = 'https://github.com/'
# Default url to base url + full_name
if not self.url:
self.url = BASE + self.full_name
super(Repo, self).save(*args, **kwargs)
def __unicode__(self):
return "{full_name}: {language}".format(full_name=self.full_name,
language=self.language.name)
| """ Basic models, such as user profile """
from django.db import models
class Language(models.Model):
name = models.CharField(max_length=40, null=False)
learn_url = models.URLField(null=True, blank=True)
@staticmethod
def all():
return [l.name for l in Language.objects.all()]
def __unicode__(self):
return self.name
class Repo(models.Model):
# Full name is required
full_name = models.CharField(max_length=30, null=False)
url = models.URLField(null=True)
language = models.ForeignKey(Language, related_name='repos')
description = models.CharField(max_length=300, null=True, blank=True)
def save(self, *args, **kwargs):
'''Override save method to set default url.'''
BASE = 'https://github.com/'
# Default url to base url + full_name
if not self.url:
self.url = BASE + self.full_name
super(Repo, self).save(*args, **kwargs)
def __unicode__(self):
return "{full_name}: {language}".format(full_name=self.full_name,
language=self.language.name)
|
Use `app.bowerDirectory` instead of hardcoded `bower_components` | /* jshint node: true */
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
var app = new EmberAddon();
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.css');
app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.css.map', {
destDir: 'assets'
});
app.import(app.bowerDirectory + '/bootstrap-datepicker/js/locales/bootstrap-datepicker.de.js');
module.exports = app.toTree();
| /* jshint node: true */
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
var app = new EmberAddon();
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/css/bootstrap.css.map', {
destDir: 'assets'
});
app.import('bower_components/bootstrap-datepicker/js/locales/bootstrap-datepicker.de.js');
module.exports = app.toTree();
|
Remove blank lines at the begin or the end of the imported file | @extends('layout')
@section('title')File - {{$file}}@stop
@section('content')
<h1>{{SourceController::linkedPath($path)}}</h1>
<h2>Query</h2>
<?php
$source = file_get_contents(base_path() . "/query/" . $file . ".sql");
$geshi = new GeSHi(trim($source), 'sql');
echo $geshi->parse_code();
?>
<h2>Output</h2>
<?php
$outputs = SourceController::getDir("output/" . $path);
$filename = $outputs[sizeof($outputs) - 1];
$source = file_get_contents(base_path() . "/output/" . $file . "/" . $filename);
$geshi = new GeSHi(trim($source), 'sql');
echo $geshi->parse_code();
?>
@stop
| @extends('layout')
@section('title')File - {{$file}}@stop
@section('content')
<h1>{{SourceController::linkedPath($path)}}</h1>
<h2>Query</h2>
<?php
$source = file_get_contents(base_path() . "/query/" . $file . ".sql");
$geshi = new GeSHi($source, 'sql');
echo $geshi->parse_code();
?>
<h2>Output</h2>
<?php
$outputs = SourceController::getDir("output/" . $path);
$filename = $outputs[sizeof($outputs) - 1];
$source = file_get_contents(base_path() . "/output/" . $file . "/" . $filename);
$geshi = new GeSHi($source, 'sql');
echo $geshi->parse_code();
?>
@stop
|
Correct expected output for integration test | import org.fluentlenium.adapter.FluentTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import static org.assertj.core.api.Assertions.assertThat;
public class IntegrationTest extends FluentTest {
public WebDriver webDriver = new HtmlUnitDriver();
@Override
public WebDriver getDefaultDriver() {
return webDriver;
}
@ClassRule
public static ServerRule server = new ServerRule();
@Test
public void rootTest() {
goTo("http://localhost:4567/");
assertThat(pageSource()).contains("Shipping Calculator");
}
@Test
public void resultsTest_returnsCostCorrectly() {
goTo("http://localhost:4567/");
fill("#length").with("10");
fill("#width").with("10");
fill("#height").with("10");
fill("#weight").with("5");
fill("#distance").with("100");
submit(".btn");
assertThat(pageSource()).contains("Base Shipping Cost: $50.00");
}
}
| import org.fluentlenium.adapter.FluentTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import static org.assertj.core.api.Assertions.assertThat;
public class IntegrationTest extends FluentTest {
public WebDriver webDriver = new HtmlUnitDriver();
@Override
public WebDriver getDefaultDriver() {
return webDriver;
}
@ClassRule
public static ServerRule server = new ServerRule();
@Test
public void rootTest() {
goTo("http://localhost:4567/");
assertThat(pageSource()).contains("Shipping Calculator");
}
@Test
public void resultsTest_returnsCostCorrectly() {
goTo("http://localhost:4567/");
fill("#length").with("10");
fill("#width").with("10");
fill("#height").with("10");
fill("#weight").with("5");
fill("#distance").with("100");
submit(".btn");
assertThat(pageSource()).contains("Cost to Ship: 5000");
}
}
|
Use element.localName and check namespaceURI | import { Localization } from './base';
import { overlayElement } from './overlay';
export { contexts } from './base';
const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
const allowed = {
attributes: {
global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'],
button: ['accesskey'],
tab: ['label'],
textbox: ['placeholder'],
}
};
export class XULLocalization extends Localization {
overlayElement(element, translation) {
return overlayElement(this, element, translation);
}
isElementAllowed(element) {
return false;
}
isAttrAllowed(attr, element) {
if (element.namespaceURI !== ns) {
return false;
}
const tagName = element.localName;
const attrName = attr.name;
// is it a globally safe attribute?
if (allowed.attributes.global.indexOf(attrName) !== -1) {
return true;
}
// are there no allowed attributes for this element?
if (!allowed.attributes[tagName]) {
return false;
}
// is it allowed on this element?
// XXX the allowed list should be amendable; https://bugzil.la/922573
if (allowed.attributes[tagName].indexOf(attrName) !== -1) {
return true;
}
return false;
}
}
| import { Localization } from './base';
import { overlayElement } from './overlay';
export { contexts } from './base';
const allowed = {
attributes: {
global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'],
button: ['accesskey'],
tab: ['label'],
textbox: ['placeholder'],
}
};
export class XULLocalization extends Localization {
overlayElement(element, translation) {
return overlayElement(this, element, translation);
}
isElementAllowed(element) {
return false;
}
isAttrAllowed(attr, element) {
const attrName = attr.name.toLowerCase();
const tagName = element.tagName.toLowerCase();
// is it a globally safe attribute?
if (allowed.attributes.global.indexOf(attrName) !== -1) {
return true;
}
// are there no allowed attributes for this element?
if (!allowed.attributes[tagName]) {
return false;
}
// is it allowed on this element?
// XXX the allowed list should be amendable; https://bugzil.la/922573
if (allowed.attributes[tagName].indexOf(attrName) !== -1) {
return true;
}
return false;
}
}
|
Remove version restriction from opt_einsum.
See https://github.com/dgasmith/opt_einsum/issues/98. | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
global __version__
__version__ = None
with open('jax/version.py') as f:
exec(f.read(), globals())
setup(
name='jax',
version=__version__,
description='Differentiate, compile, and transform Numpy code.',
author='JAX team',
author_email='jax-dev@google.com',
packages=find_packages(exclude=["examples"]),
install_requires=[
'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py', 'opt_einsum',
'fastcache'
],
url='https://github.com/google/jax',
license='Apache-2.0',
)
| # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
global __version__
__version__ = None
with open('jax/version.py') as f:
exec(f.read(), globals())
setup(
name='jax',
version=__version__,
description='Differentiate, compile, and transform Numpy code.',
author='JAX team',
author_email='jax-dev@google.com',
packages=find_packages(exclude=["examples"]),
install_requires=[
'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py', 'opt_einsum<3',
'fastcache'
],
url='https://github.com/google/jax',
license='Apache-2.0',
)
|
Use a config file for the FlightAware keys. | var express = require('express');
var path = require('path');
var FlightAware = require('flightaware.js');
var config = require('./config');
// Get access to the FlightAware 2.0 client API ...
// See http://flightaware.com/commercial/flightxml for username/apiKey ...
var client = new FlightAware(config.username, config.apiKey);
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/api/Arrived/:airport', function(req, res) {
client.Arrived({
airport: req.params.airport,
}, function(err, result) {
if (err) return res.send(err);
res.json(result);
});
});
var port = 8000;
app.listen(port, function() {
console.log("Node app is running at http://localhost:" + port);
});
| var express = require('express');
var path = require('path');
var FlightAware = require('flightaware.js');
// Get access to the FlightAware 2.0 client API ...
// See http://flightaware.com/commercial/flightxml for username/apiKey ...
var username = 'your-flightaware-username';
var apiKey = 'your-flightaware-apiKey';
var client = new FlightAware(username, apiKey);
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/api/Arrived/:airport', function(req, res) {
client.Arrived({
airport: req.params.airport,
}, function(err, result) {
if (err) return res.send(err);
res.json(result);
});
});
var port = 8000;
app.listen(port, function() {
console.log("Node app is running at http://localhost:" + port);
});
|
Fix temporary directory name in jQuery test | 'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-assert');
describe('jquery', function () {
describe('on', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({'skip-install': true})
.withPrompts({
features: [],
includeJQuery: true
})
.on('end', done);
});
it('adds the bower dependency', function () {
assert.fileContent('bower.json', '"jquery"');
});
});
describe('off', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({'skip-install': true})
.withPrompts({
features: [],
includeJQuery: false
})
.on('end', done);
});
it('doesn\'t add the bower dependency', function () {
assert.noFileContent('bower.json', '"jquery"');
});
});
});
| 'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-assert');
describe('jquery', function () {
describe('on', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, '.tmp'))
.withOptions({'skip-install': true})
.withPrompts({
features: [],
includeJQuery: true
})
.on('end', done);
});
it('adds the bower dependency', function () {
assert.fileContent('bower.json', '"jquery"');
});
});
describe('off', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(__dirname, 'temp'))
.withOptions({'skip-install': true})
.withPrompts({
features: [],
includeJQuery: false
})
.on('end', done);
});
it('doesn\'t add the bower dependency', function () {
assert.noFileContent('bower.json', '"jquery"');
});
});
});
|
Update go-netroute and go-reuseport for Plan 9 support | package tcpreuse
import (
"net"
"os"
)
const (
EADDRINUSE = "address in use"
ECONNREFUSED = "connection refused"
)
// reuseErrShouldRetry diagnoses whether to retry after a reuse error.
// if we failed to bind, we should retry. if bind worked and this is a
// real dial error (remote end didnt answer) then we should not retry.
func reuseErrShouldRetry(err error) bool {
if err == nil {
return false // hey, it worked! no need to retry.
}
// if it's a network timeout error, it's a legitimate failure.
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
return false
}
e, ok := err.(*net.OpError)
if !ok {
return true
}
e1, ok := e.Err.(*os.PathError)
if !ok {
return true
}
switch e1.Err.Error() {
case EADDRINUSE:
return true
case ECONNREFUSED:
return false
default:
return true // optimistically default to retry.
}
}
| package tcpreuse
import (
"net"
"os"
)
// reuseErrShouldRetry diagnoses whether to retry after a reuse error.
// if we failed to bind, we should retry. if bind worked and this is a
// real dial error (remote end didnt answer) then we should not retry.
func reuseErrShouldRetry(err error) bool {
if err == nil {
return false // hey, it worked! no need to retry.
}
// if it's a network timeout error, it's a legitimate failure.
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
return false
}
e, ok := err.(*net.OpError)
if !ok {
return true
}
e1, ok := e.Err.(*os.PathError)
if !ok {
return true
}
switch e1.Err.Error() {
case "address in use":
return true
case "connection refused":
return false
default:
return true // optimistically default to retry.
}
}
|
Add tmdb_id to show model | // Import the neccesary modules.
import mongoose from "mongoose";
// The show schema used by mongoose.
const ShowSchema = new mongoose.Schema({
_id: {
type: String,
required: true
},
imdb_id: String,
tvdb_id: String,
tmdb_id: String,
title: String,
year: String,
slug: String,
synopsis: String,
runtime: String,
rating: {
percentage: Number,
watching: Number,
votes: Number,
loved: Number,
hated: Number
},
country: String,
network: String,
air_day: String,
air_time: String,
status: String,
num_seasons: Number,
last_updated: Number,
latest_episode: {
type: Number,
default: 0
},
images: {
banner: String,
fanart: String,
poster: String
},
genres: [],
episodes: []
});
ShowSchema.index({ title: "text", synopsis: "text", _id: 1 });
// Create the show model.
const Show = mongoose.model("Show", ShowSchema);
/**
* A model object for shows.
* @type {Show}
*/
export default Show;
| // Import the neccesary modules.
import mongoose from "mongoose";
// The show schema used by mongoose.
const ShowSchema = new mongoose.Schema({
_id: {
type: String,
required: true
},
imdb_id: String,
tvdb_id: String,
title: String,
year: String,
slug: String,
synopsis: String,
runtime: String,
rating: {
percentage: Number,
watching: Number,
votes: Number,
loved: Number,
hated: Number
},
country: String,
network: String,
air_day: String,
air_time: String,
status: String,
num_seasons: Number,
last_updated: Number,
latest_episode: {
type: Number,
default: 0
},
images: {
banner: String,
fanart: String,
poster: String
},
genres: [],
episodes: []
});
ShowSchema.index({ title: "text", synopsis: "text", _id: 1 });
// Create the show model.
const Show = mongoose.model("Show", ShowSchema);
/**
* A model object for shows.
* @type {Show}
*/
export default Show;
|
Configure nova.flags as well as openstack.common.cfg
Because we are using nova classes directly (Service, Manager, etc.)
we need to initialize the configuration modules that those
classes use.
Change-Id: Idafd4a8346fc59332114ea7536893470bf9eaff8 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright © 2012 eNovance <licensing@enovance.com>
#
# Author: Julien Danjou <julien@danjou.info>
#
# 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 nova import flags
from ceilometer import log
from ceilometer.openstack.common import cfg
cfg.CONF.register_opts([
cfg.IntOpt('periodic_interval',
default=60,
help='seconds between running periodic tasks')
])
def prepare_service(argv=[]):
cfg.CONF(argv[1:])
# FIXME(dhellmann): We must set up the nova.flags module in order
# to have the RPC and DB access work correctly because we are
# still using the Service object out of nova directly. We need to
# move that into openstack.common.
flags.FLAGS(argv[1:])
log.setup()
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright © 2012 eNovance <licensing@enovance.com>
#
# Author: Julien Danjou <julien@danjou.info>
#
# 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 ceilometer import log
from ceilometer.openstack.common import cfg
cfg.CONF.register_opts([
cfg.IntOpt('periodic_interval',
default=60,
help='seconds between running periodic tasks')
])
def prepare_service(argv=[]):
cfg.CONF(argv[1:])
log.setup()
|
Fix test by passing placeholder variables. | import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
links = VendCrawler('a', 'b', 'c').get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
page_count = VendCrawler('a', 'b', 'c').get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
| import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
links = VendCrawler().get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
page_count = VendCrawler().get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
|
Remove unnecessary call to setEncoding. | /*globals require, module, Promise */
'use strict';
var streamify;
streamify = require('./streamify');
module.exports = stringify;
/**
* Public function `stringify`.
*
* Asynchronously serialises a data structure and returns a promise
* that resolves to a JSON string. Sanely handles promises, buffers,
* dates, maps and other iterables.
*
* @param data: The data to transform
*
* @option promises: 'resolve' or 'ignore', default is 'resolve'.
*
* @option buffers: 'toString' or 'ignore', default is 'toString'.
*
* @option dates: 'toJSON' or 'ignore', default is 'toJSON'.
*
* @option maps: 'object', or 'ignore', default is 'object'.
*
* @option iterables: 'array', or 'ignore', default is 'array'.
*
* @option debug: Log debug messages to the console.
**/
function stringify (data, options) {
var stream, json, resolve;
// TODO: options.replacer, options.space
stream = streamify(data, options);
json = '';
stream.on('data', read);
stream.on('end', end);
return new Promise(function (res) {
resolve = res;
});
function read (chunk) {
json += chunk;
}
function end () {
resolve(json);
}
}
| /*globals require, module, Promise */
'use strict';
var streamify;
streamify = require('./streamify');
module.exports = stringify;
/**
* Public function `stringify`.
*
* Asynchronously serialises a data structure and returns a promise
* that resolves to a JSON string. Sanely handles promises, buffers,
* dates, maps and other iterables.
*
* @param data: The data to transform
*
* @option promises: 'resolve' or 'ignore', default is 'resolve'.
*
* @option buffers: 'toString' or 'ignore', default is 'toString'.
*
* @option dates: 'toJSON' or 'ignore', default is 'toJSON'.
*
* @option maps: 'object', or 'ignore', default is 'object'.
*
* @option iterables: 'array', or 'ignore', default is 'array'.
*
* @option debug: Log debug messages to the console.
**/
function stringify (data, options) {
var stream, json, resolve;
// TODO: options.replacer, options.space
stream = streamify(data, options);
json = '';
stream.setEncoding('utf8');
stream.on('data', read);
stream.on('end', end);
return new Promise(function (res) {
resolve = res;
});
function read (chunk) {
json += chunk;
}
function end () {
resolve(json);
}
}
|
Remove import for debug code
Remove an import added during debugging. | import {
moduleFor,
test
} from 'ember-qunit';
moduleFor('service:i18n', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
test('it exists', function(assert) {
var service = this.subject();
assert.ok(service);
});
test('throws when action names are blank', function (assert) {
var service = this.subject();
assert.throws(function () { service.registerPreInitAction('', function () {}); },
'Throws if pre-init action name is blank.');
assert.throws(function () { service.registerPostInitAction('', function () {}); },
'Throws if post-init action name is blank.');
});
test('throws when actions are not functions', function (assert) {
var service = this.subject();
assert.throws(function () { service.registerPreInitAction('woo', 'woo'); },
'Throws if pre-init action is not a function.');
assert.throws(function () { service.registerPostInitAction('woo', 'hoo'); },
'Throws if post-init action is not a function.');
});
| import Ember from 'ember';
import {
moduleFor,
test
} from 'ember-qunit';
moduleFor('service:i18n', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
test('it exists', function(assert) {
var service = this.subject();
assert.ok(service);
});
test('throws when action names are blank', function (assert) {
var service = this.subject();
assert.throws(function () { service.registerPreInitAction('', function () {}); },
'Throws if pre-init action name is blank.');
assert.throws(function () { service.registerPostInitAction('', function () {}); },
'Throws if post-init action name is blank.');
});
test('throws when actions are not functions', function (assert) {
var service = this.subject();
assert.throws(function () { service.registerPreInitAction('woo', 'woo'); },
'Throws if pre-init action is not a function.');
assert.throws(function () { service.registerPostInitAction('woo', 'hoo'); },
'Throws if post-init action is not a function.');
});
|
Allow preRequest as option passed in | var Controller = require('./controller');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var errors = require('./errors');
exports.errors = require('./errors').http;
/**
* [createApiController description]
* @param {ControllerOptions} opts [description]
* @param {Object} ctx [description]
* @return {Controller} [description]
*/
exports.createApiController = function(opts, ctx) {
opts = opts || {};
// if (!opts) {
// throw new errors.generic.MissingOptionsError('Options parameter must be provided');
// }
// if (!opts.sessionManager || !opts.sessionManager.getSession) {
// throw new errors.generic.ValidationError('Session manager must be provided with options');
// }
if (opts.sessionManager && !opts.sessionManager.getSession) {
throw new errors.generic.ValidationError('Session manager must implement getSession');
}
var sessionManager = opts.sessionManager;
var errorHandlers = (opts.subController) ?
require('./error-handlers').apiSubControllerHandlers(opts) :
require('./error-handlers').apiRootControllerHandlers(opts);
var ctrlOps = {
sessionManager: sessionManager,
errorHandlers: errorHandlers,
validator: opts.validator,
models: opts.models,
cors: opts.cors,
logger: opts.logger,
domain: opts.domain,
preRequest: opts.preRequest || [bodyParser.json(), methodOverride('X-HTTP-Method-Override')]
};
return new Controller(ctrlOps, ctx);
};
exports.createStaticSite = function(opts) {
};
| var Controller = require('./controller');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var errors = require('./errors');
exports.errors = require('./errors').http;
/**
* [createApiController description]
* @param {ControllerOptions} opts [description]
* @param {Object} ctx [description]
* @return {Controller} [description]
*/
exports.createApiController = function(opts, ctx) {
opts = opts || {};
// if (!opts) {
// throw new errors.generic.MissingOptionsError('Options parameter must be provided');
// }
// if (!opts.sessionManager || !opts.sessionManager.getSession) {
// throw new errors.generic.ValidationError('Session manager must be provided with options');
// }
if (opts.sessionManager && !opts.sessionManager.getSession) {
throw new errors.generic.ValidationError('Session manager must implement getSession');
}
var sessionManager = opts.sessionManager;
var errorHandlers = (opts.subController) ?
require('./error-handlers').apiSubControllerHandlers(opts) :
require('./error-handlers').apiRootControllerHandlers(opts);
var ctrlOps = {
sessionManager: sessionManager,
errorHandlers: errorHandlers,
validator: opts.validator,
models: opts.models,
cors: opts.cors,
logger: opts.logger,
domain: opts.domain,
preRequest: [bodyParser.json(), methodOverride('X-HTTP-Method-Override')]
};
return new Controller(ctrlOps, ctx);
};
exports.createStaticSite = function(opts) {
};
|
Fix AnchorJS messing up due to missing semicolon
Closes #13 | (function($) {
// SVG polyfill
svg4everybody();
// Deep anchor links for headings
anchors.options = {
placement: 'left',
visible: 'touch',
icon: '#'
};
anchors.add('.post h3, .post h4, .post h5, post h6, .page h3, .page h4, .page h5, page h6, .archive-overview h3, .archive-overview h4');
anchors.remove('.comment header > h4');
// Smooth scrolling links in comments
$('.comment_reply').click(function(e) {
var $el = $(this);
var target, replyTo;
target = '#reply';
replyTo = $el.attr("id").replace(/serendipity_reply_/g, "");
$("#serendipity_replyTo").val(replyTo);
$('html, body').animate({
scrollTop: $(target).offset().top
}, 250);
e.preventDefault();
});
// Move comment preview
$('#c').insertAfter('#feedback');
})(jQuery);
| (function($) {
// SVG polyfill
svg4everybody();
// Deep anchor links for headings
anchors.options = {
placement: 'left',
visible: 'touch',
icon: '#'
}
anchors.add('.post h3, .post h4, .post h5, post h6, .page h3, .page h4, .page h5, page h6, .archive-overview h3, .archive-overview h4');
anchors.remove('.comment header > h4');
// Smooth scrolling links in comments
$('.comment_reply').click(function(e) {
var $el = $(this);
var target, replyTo;
target = '#reply';
replyTo = $el.attr("id").replace(/serendipity_reply_/g, "");
$("#serendipity_replyTo").val(replyTo);
$('html, body').animate({
scrollTop: $(target).offset().top
}, 250);
e.preventDefault();
});
// Move comment preview
$('#c').insertAfter('#feedback');
})(jQuery);
|
Add more props to select field | import { createElement as h } from 'react'
import PropTypes from 'prop-types'
const Select = (props) => {
return (
h('select', {
className: 'select',
id: props.id,
required: props.required,
disabled: props.disabled,
value: props.value,
onChange: props.onChange
},
props.items.map((item, index) => (
h('option', {
key: item.value + index,
value: item.value
}, item.label)
))
)
)
}
Select.propTypes = {
id: PropTypes.string,
required: PropTypes.bool,
disabled: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
items: PropTypes.arrayOf(
PropTypes.shape({
value: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
})
).isRequired
}
export default Select | import { createElement as h } from 'react'
import PropTypes from 'prop-types'
const Select = (props) => {
return (
h('select', {
className: 'select',
value: props.value,
onChange: props.onChange,
disabled: props.disabled
},
props.items.map((item, index) => (
h('option', {
key: item.value + index,
value: item.value
}, item.label)
))
)
)
}
Select.propTypes = {
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
items: PropTypes.arrayOf(
PropTypes.shape({
value: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
})
).isRequired
}
export default Select |
Fix ZeroClipboard.swf's path in dist/gh-pages (Previously, it worked in local `gulp serve:list` but not on github page) | 'use strict';
/* globals window */
angular.module('vleApp', [
'ngAnimate',
'ngCookies',
'ngSanitize',
'ngTouch',
'ngDragDrop',
'monospaced.elastic',
'zeroclipboard',
'ui.router'])
.constant('_', window._)
.constant('vl', window.vl)
.constant('vg', window.vg)
.constant('Papa', window.Papa)
.constant('tv4', window.tv4)
.config(['uiZeroclipConfigProvider', function(uiZeroclipConfigProvider) {
// config ZeroClipboard
uiZeroclipConfigProvider.setZcConf({
swfPath: 'bower_components/zeroclipboard/dist/ZeroClipboard.swf'
});
}])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('/');
});
| 'use strict';
/* globals window */
angular.module('vleApp', [
'ngAnimate',
'ngCookies',
'ngSanitize',
'ngTouch',
'ngDragDrop',
'monospaced.elastic',
'zeroclipboard',
'ui.router'])
.constant('_', window._)
.constant('vl', window.vl)
.constant('vg', window.vg)
.constant('Papa', window.Papa)
.constant('tv4', window.tv4)
.config(['uiZeroclipConfigProvider', function(uiZeroclipConfigProvider) {
// config ZeroClipboard
uiZeroclipConfigProvider.setZcConf({
swfPath: '../bower_components/zeroclipboard/dist/ZeroClipboard.swf'
});
}])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('/');
});
|
Add @Documented annotation for the new REST annotation. | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit.http;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** Make a PATCH request to a REST path relative to base URL. */
@Documented
@Target(METHOD)
@Retention(RUNTIME)
@RestMethod(value = "PATCH", hasBody = true)
public @interface PATCH {
String value();
}
| /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit.http;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** Make a PATCH request to a REST path relative to base URL. */
@Target(METHOD)
@Retention(RUNTIME)
@RestMethod(value = "PATCH", hasBody = true)
public @interface PATCH {
String value();
}
|
4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
#
# License: Apache 2.0
#
# TODO: Create a menu for file selection
import ibmcnx.filehandle
import sys
emp1 = ibmcnx.filehandle.Ibmcnxfile()
sys.stdout = emp1.askFileParams()
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) | ######
# Create a file (html or markdown) with the output of
# - JVMHeap
# - LogFiles
# - Ports
# - Variables
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-08
#
# License: Apache 2.0
#
# TODO: Create a menu for file selection
import ibmcnx.filehandle
import sys
emp1 = ibmcnx.filehandle.Ibmcnxfile()
sys.stdout = emp1
print '# JVM Settings of all AppServers:'
execfile( 'ibmcnx/doc/JVMSettings.py' )
print '# Used Ports:'
execfile( 'ibmcnx/doc/Ports.py' )
print '# LogFile Settgins:'
execfile( 'ibmcnx/doc/LogFiles.py' )
print '# WebSphere Variables'
execfile( 'ibmcnx/doc/Variables.py' ) |
Use defaults in coffe parser | const eol = require('eol');
const commentsUtil = require('../utils/comments');
module.exports = function({ customTags } = {}) {
const regex = commentsUtil.getRegex(customTags);
const commentsRegex = new RegExp('^\\s*#' + regex + '$', 'mig');
return function parse(contents, file) {
const comments = [];
eol.split(contents).forEach(function(line, index) {
const match = commentsRegex.exec(line);
const comment = commentsUtil.prepareComment(match, index + 1, file);
if (!comment) {
return;
}
comments.push(comment);
});
return comments;
};
};
| const eol = require('eol');
const commentsUtil = require('../utils/comments');
module.exports = function(params) {
params = params || {};
const regex = commentsUtil.getRegex(params.customTags);
const commentsRegex = new RegExp('^\\s*#' + regex + '$', 'mig');
return function parse(contents, file) {
const comments = [];
eol.split(contents).forEach(function(line, index) {
const match = commentsRegex.exec(line);
const comment = commentsUtil.prepareComment(match, index + 1, file);
if (!comment) {
return;
}
comments.push(comment);
});
return comments;
};
};
|
Add phpdoc for registration form | <?php
namespace Feedme\FeedmeUserBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use \FOS\UserBundle\Form\Type\RegistrationFormType as FOSUserRegistrationFormType;
use Symfony\Component\Validator\Constraints\NotBlank;
/**
* Class RegistrationFormType
* @package Feedme\FeedmeUserBundle\Form\Type
*/
class RegistrationFormType extends FOSUserRegistrationFormType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('firstname', null,['constraints' => $this->getValidators('firstname'), 'translation_domain' => 'messages'])
->add('lastname', null, ['constraints' => $this->getValidators('lastname'), 'translation_domain' => 'messages'])
;
}
public function getName()
{
return 'feedme_user_registration';
}
private function getValidators($name)
{
$validators = [];
$validator = new NotBlank(['groups' => ['Registration', 'Profile']]);
$validator->message = sprintf('form.validation.%s.notblank', $name);
$validators[] = $validator;
return $validators;
}
}
| <?php
namespace Feedme\FeedmeUserBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use \FOS\UserBundle\Form\Type\RegistrationFormType as FOSUserRegistrationFormType;
use Symfony\Component\Validator\Constraints\NotBlank;
class RegistrationFormType extends FOSUserRegistrationFormType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('firstname', null,['constraints' => $this->getValidators('firstname'), 'translation_domain' => 'messages'])
->add('lastname', null, ['constraints' => $this->getValidators('lastname'), 'translation_domain' => 'messages'])
;
}
public function getName()
{
return 'feedme_user_registration';
}
private function getValidators($name)
{
$validators = [];
$validator = new NotBlank(['groups' => ['Registration', 'Profile']]);
$validator->message = sprintf('form.validation.%s.notblank', $name);
$validators[] = $validator;
return $validators;
}
}
|
Remove placeholder from state atom | 'use strict'
var zip = require('zippo')
var State = require('dover')
var Observ = require('observ')
var pipe = require('value-pipe')
var changeEvent = require('value-event/change')
var h = require('virtual-dom/h')
module.exports = ZipInput
function ZipInput (data) {
data = data || {}
var state = State({
value: Observ(data.value || ''),
valid: Observ(zip.validate(data.value || '')),
channels: {
change: change
}
})
state.value(pipe(zip.validate, state.valid.set))
return state
}
function change (state, data) {
state.value.set(zip.parse(data.zip))
}
ZipInput.render = function render (state) {
return h('input', {
type: 'text',
name: 'zip',
value: state.value,
// trigger the big number keyboard on mobile
pattern: '[0-9]*',
'ev-event': changeEvent(state.channels.change)
})
}
| 'use strict'
var zip = require('zippo')
var State = require('dover')
var Observ = require('observ')
var pipe = require('value-pipe')
var changeEvent = require('value-event/change')
var h = require('virtual-dom/h')
module.exports = ZipInput
function ZipInput (data) {
data = data || {}
var state = State({
value: Observ(data.value || ''),
valid: Observ(zip.validate(data.value || '')),
placeholder: Observ(data.placeholder || ''),
channels: {
change: change
}
})
state.value(pipe(zip.validate, state.valid.set))
return state
}
function change (state, data) {
state.value.set(zip.parse(data.zip))
}
ZipInput.render = function render (state) {
return h('input', {
type: 'text',
name: 'zip',
value: state.value,
placeholder: state.placeholder,
// trigger the big number keyboard on mobile
pattern: '[0-9]*',
'ev-event': changeEvent(state.channels.change)
})
}
|
Add new preprint provider properties to model | import DS from 'ember-data';
import OsfModel from 'ember-osf/models/osf-model';
export default OsfModel.extend({
name: DS.attr('fixstring'),
logoPath: DS.attr('string'),
bannerPath: DS.attr('string'),
description: DS.attr('fixstring'),
domain: DS.attr('string'),
domainRedirectEnabled: DS.attr('boolean'),
example: DS.attr('fixstring'),
advisoryBoard: DS.attr('string'),
emailContact: DS.attr('fixstring'),
emailSupport: DS.attr('fixstring'),
socialTwitter: DS.attr('fixstring'),
socialFacebook: DS.attr('fixstring'),
socialInstagram: DS.attr('fixstring'),
aboutLink: DS.attr('fixstring'),
headerText: DS.attr('fixstring'),
subjectsAcceptable: DS.attr(),
footerLinks: DS.attr('string'),
allowSubmissions: DS.attr('boolean'),
additionalProviders: DS.attr(),
// Relationships
taxonomies: DS.hasMany('taxonomy'),
preprints: DS.hasMany('preprint', { inverse: 'provider', async: true }),
licensesAcceptable: DS.hasMany('license', { inverse: null }),
});
| import DS from 'ember-data';
import OsfModel from 'ember-osf/models/osf-model';
export default OsfModel.extend({
name: DS.attr('fixstring'),
logoPath: DS.attr('string'),
bannerPath: DS.attr('string'),
description: DS.attr('fixstring'),
domain: DS.attr('string'),
domainRedirectEnabled: DS.attr('boolean'),
example: DS.attr('fixstring'),
advisoryBoard: DS.attr('string'),
emailContact: DS.attr('fixstring'),
emailSupport: DS.attr('fixstring'),
socialTwitter: DS.attr('fixstring'),
socialFacebook: DS.attr('fixstring'),
socialInstagram: DS.attr('fixstring'),
aboutLink: DS.attr('fixstring'),
headerText: DS.attr('fixstring'),
subjectsAcceptable: DS.attr(),
// Relationships
taxonomies: DS.hasMany('taxonomy'),
preprints: DS.hasMany('preprint', { inverse: 'provider', async: true }),
licensesAcceptable: DS.hasMany('license', { inverse: null }),
});
|
Fix remove words on mobile |
'use strict';
angular.module('copayApp.services').factory('confirmDialog', function($log, $timeout, profileService, configService, gettextCatalog, isCordova, isChromeApp) {
var root = {};
var acceptMsg = gettextCatalog.getString('Accept');
var cancelMsg = gettextCatalog.getString('Cancel');
var confirmMsg = gettextCatalog.getString('Confirm');
root.show = function(msg, cb) {
if (isCordova) {
navigator.notification.confirm(
msg,
function(buttonIndex) {
if (buttonIndex == 1) {
$timeout(function() {
return cb(true);
}, 1);
} else {
return cb(false);
}
},
confirmMsg, [acceptMsg, cancelMsg]
);
} else if (isChromeApp) {
// No feedback, alert/confirm not supported.
return cb(true);
} else {
return cb(confirm(msg));
}
};
return root;
});
|
'use strict';
angular.module('copayApp.services').factory('confirmDialog', function($log, profileService, configService, gettextCatalog, isCordova, isChromeApp) {
var root = {};
var acceptMsg = gettextCatalog.getString('Accept');
var cancelMsg = gettextCatalog.getString('Cancel');
var confirmMsg = gettextCatalog.getString('Confirm');
root.show = function(msg, cb) {
if (isCordova) {
navigator.notification.confirm(
msg,
function(buttonIndex) {
if (buttonIndex == 1) {
$timeout(function() {
return cb(true);
}, 1);
} else {
return cb(false);
}
},
confirmMsg, [acceptMsg, cancelMsg]
);
} else if (isChromeApp) {
// No feedback, alert/confirm not supported.
return cb(true);
} else {
return cb(confirm(msg));
}
};
return root;
});
|
Add url logging in google shortener | import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener url:', url, '; response:', response)
return response['id']
| import os
import time
import json
import requests
def get_timezone(lat, long):
response = requests.get('https://maps.googleapis.com/maps/api/timezone/json', params={
'location': '{},{}'.format(lat, long),
'timestamp': int(time.time()),
'key': os.environ['GOOGLE_API_TOKEN']
}).json()
return response['timeZoneId']
def shorten_url(url):
response = requests.post(
'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(os.environ['GOOGLE_API_TOKEN']),
data=json.dumps({'longUrl': url}), headers={'Content-Type': 'application/json'}
).json()
print('Google Shortener response:', response)
return response['id']
|
core: Fix ISO Domain List refresh NPE
Fix ISO DomainList refresh NPE when no ISO domain
is configured.
Change-Id: Ied2b1490d8f66bb40f6f456d2d39bb05120e97d3
Bug-Url: https://bugzilla.redhat.com/1291202
Signed-off-by: Marek Libra <e8e92ef0eef30bdb5bafbacaf4ac8261fffd12ff@redhat.com> | package org.ovirt.engine.core.bll.storage.repoimage;
import java.util.ArrayList;
import java.util.List;
import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.bll.storage.domain.IsoDomainListSyncronizer;
import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.queries.GetImagesListParametersBase;
import org.ovirt.engine.core.compat.Guid;
public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> {
public GetImagesListQueryBase(P parameters) {
super(parameters);
}
@Override
protected void executeQueryCommand() {
// Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id.
getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList());
}
/**
* @return The storage domain to get the images from
*/
protected abstract Guid getStorageDomainIdForQuery();
protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() {
Guid storageDomainId = getStorageDomainIdForQuery();
if (Guid.Empty.equals(storageDomainId)) {
return new ArrayList<>();
}
return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList
(storageDomainId, getParameters().getImageType(), getParameters().getForceRefresh());
}
}
| package org.ovirt.engine.core.bll.storage.repoimage;
import java.util.List;
import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.bll.storage.domain.IsoDomainListSyncronizer;
import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.queries.GetImagesListParametersBase;
import org.ovirt.engine.core.compat.Guid;
public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> {
public GetImagesListQueryBase(P parameters) {
super(parameters);
}
@Override
protected void executeQueryCommand() {
// Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id.
getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList());
}
/**
* @return The storage domain to get the images from
*/
protected abstract Guid getStorageDomainIdForQuery();
protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() {
return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList
(getStorageDomainIdForQuery(), getParameters().getImageType(), getParameters().getForceRefresh());
}
}
|
Add packet show command and TODO. | #!/etc/usr/python
from scapy.all import *
import sys
iface = "eth0"
filter = "ip"
#victim in this case is the initiator
VICTIM_IP = "192.168.1.121"
MY_IP = "192.168.1.154"
# gateway is the target
GATEWAY_IP = "192.168.1.171"
#VICTIM_MAC = "### don't want so show###"
MY_MAC = "08:00:27:7b:80:18"
#target mac address
GATEWAY_MAC = "08:00:27:24:08:34"
def handle_packet(packet):
if (packet[IP].dst == GATEWAY_IP) and (packet[Ether].dst == MY_MAC):
# we change the packet destination to the target machine
packet[Ether].dst = GATEWAY_MAC
# TODO: block iscsi packets with an if condition
if(packet[TCP]):
# shows what the packet contains
packet.show()
# TODO: create condition to check/filter the 'dport' packet tcp argument for 'iscsi_target'
sendp(packet)
print "A packet from " + packet[IP].src + " redirected!"
sniff(prn=handle_packet, filter=filter, iface=iface, store=0)
| #!/etc/usr/python
from scapy.all import *
import sys
iface = "eth0"
filter = "ip"
#victim in this case is the initiator
VICTIM_IP = "192.168.1.121"
MY_IP = "192.168.1.154"
# gateway is the target
GATEWAY_IP = "192.168.1.171"
#VICTIM_MAC = "### don't want so show###"
MY_MAC = "08:00:27:7b:80:18"
#target mac address
GATEWAY_MAC = "08:00:27:24:08:34"
def handle_packet(packet):
if (packet[IP].dst == GATEWAY_IP) and (packet[Ether].dst == MY_MAC):
# we change the packet destination to the target machine
packet[Ether].dst = GATEWAY_MAC
# TODO: block iscsi packets with an if condition
if(packet[TCP]):
# sprintf("{Raw:%Raw.load%\n}")
print str(packet) + "\n"
sendp(packet)
print "A packet from " + packet[IP].src + " redirected!"
#printing redirected packets load
#sprintf("{Raw:%Raw.load%\n}")
sniff(prn=handle_packet, filter=filter, iface=iface, store=0)
|
Replace try_get_property with property access | <?php
namespace tomlib\object;
function try_get_property($object, $name, $default = null) {
if(property_exists($object, $name))
return $object->$name;
else
return $default;
}
function to_indexed_array($object, $properties, $reference = false) {
if($reference) {
foreach($properties as $property) {
$result[$property] = $object->$property;
}
} else {
foreach($properties as $property) {
$result[$property] = $object->$property;
}
}
return $result;
}
function to_array($object, $properties, $reference = false) {
if($reference) {
foreach($properties as $property) {
$result[] =& $object->$property;
}
} else {
foreach($properties as $property) {
$result[] = $object->$property;
}
}
return $result;
}
| <?php
namespace tomlib\object;
function try_get_property($object, $name, $default = null) {
if(property_exists($object, $name))
return $object->$name;
else
return $default;
}
function to_indexed_array($object, $properties, $reference = false) {
if($reference) {
foreach($properties as $property) {
$result[$property] =& try_get_property($object, $property);
}
} else {
foreach($properties as $property) {
$result[$property] = try_get_property($object, $property);
}
}
return $result;
}
function to_array($object, $properties, $reference = false) {
if($reference) {
foreach($properties as $property) {
$result[] =& try_get_property($object, $property);
}
} else {
foreach($properties as $property) {
$result[] = try_get_property($object, $property);
}
}
return $result;
}
|
Fix loaded time variable name | import os
from threading import Thread
from werkzeug._reloader import ReloaderLoop
class Watcher(Thread, ReloaderLoop):
def __init__(self, paths, static, tasks, interval=1, *args, **kwargs):
self.paths = paths
self.static = static
self.tasks = tasks
super(Watcher, self).__init__(*args, **kwargs)
ReloaderLoop.__init__(self, interval=interval)
def run(self):
times = {}
while not self._Thread__stopped:
for filename in self.paths:
try:
currtime = os.stat(filename).st_mtime
except OSError:
continue
oldtime = times.get(filename)
if oldtime and currtime > oldtime:
self.static.run(*self.tasks)
times[filename] = currtime
self._sleep(self.interval)
| import os
from threading import Thread
from werkzeug._reloader import ReloaderLoop
class Watcher(Thread, ReloaderLoop):
def __init__(self, paths, static, tasks, interval=1, *args, **kwargs):
self.paths = paths
self.static = static
self.tasks = tasks
super(Watcher, self).__init__(*args, **kwargs)
ReloaderLoop.__init__(self, interval=interval)
def run(self):
times = {}
while not self._Thread__stopped:
for filename in self.paths:
try:
currtime = os.stat(filename).st_mtime
except OSError:
continue
oldtime = times.get(filename)
if oldtime and currtime > oldtime:
self.static.run(*self.tasks)
times[filename] = mtime
self._sleep(self.interval)
|
Change back to unsigned samples | define(function() {
'use strict';
var DELTAS = new Int8Array([0, -49, -36, -25, -16, -9, -4, -1, 0, 1, 4, 9, 16, 25, 36, 49]);
function open(item) {
return item.getBytes().then(function(bytes) {
var samples = new Uint8Array(2 * (bytes.length - 20));
var value = 128;
for (var i = 0; i < samples.length; i++) {
var index = 20 + i >> 1;
value += (i % 2) ? DELTAS[bytes[index] >> 4] : DELTAS[bytes[index] & 0xf];
value |= 0;
samples[i] = value & 0xff; // (value << 24 >> 24) + 128;
}
item.setRawAudio({
channels: 1,
samplingRate: 11000,
bytesPerSample: 1,
samples: samples,
});
});
}
return open;
});
| define(function() {
'use strict';
var DELTAS = new Int8Array([0, -49, -36, -25, -16, -9, -4, -1, 0, 1, 4, 9, 16, 25, 36, 49]);
function open(item) {
return item.getBytes().then(function(bytes) {
var samples = new Uint8Array(2 * (bytes.length - 20));
var value = 128;
for (var i = 0; i < samples.length; i++) {
var index = 20 + i >> 1;
value += (i % 2) ? DELTAS[bytes[index] >> 4] : DELTAS[bytes[index] & 0xf];
value |= 0;
samples[i] = (value << 24 >> 24) + 128;
}
item.setRawAudio({
channels: 1,
samplingRate: 11000,
bytesPerSample: 1,
samples: samples,
});
});
}
return open;
});
|
Update xsan flavor now that they're running on GCE bots.
- Don't add ~/llvm-3.4 to PATH: we've installed Clang 3.4 systemwide.
- Don't `which clang` or `clang --version`: tools/xsan_build does it anyway.
- Explicitly disable LSAN. Clang 3.5 seems to enable this by default.
Going to submit this before review for the LSAN change, to shut up
failures like this one:
http://108.170.220.120:10117/builders/Test-Ubuntu13.10-GCE-NoGPU-x86_64-Debug-ASAN/builds/1424/steps/RunTests/logs/stdio
BUG=skia:
R=borenet@google.com, mtklein@google.com
Author: mtklein@chromium.org
Review URL: https://codereview.chromium.org/312263003 | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from utils import shell_utils
import os
class XsanBuildStepUtils(DefaultBuildStepUtils):
def Compile(self, target):
# Run the xsan_build script.
os.environ['GYP_DEFINES'] = self._step.args['gyp_defines']
print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES']
cmd = [
os.path.join('tools', 'xsan_build'),
self._step.args['sanitizer'],
target,
'BUILDTYPE=%s' % self._step.configuration,
]
cmd.extend(self._step.default_make_flags)
cmd.extend(self._step.make_flags)
shell_utils.run(cmd)
def RunFlavoredCmd(self, app, args):
# New versions of ASAN run LSAN by default. We're not yet clean for that.
os.environ['ASAN_OPTIONS'] = 'detect_leaks=0'
# Point TSAN at our suppressions file.
os.environ['TSAN_OPTIONS'] = 'suppressions=tools/tsan.supp'
return shell_utils.run([self._PathToBinary(app)] + args)
| #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from utils import shell_utils
import os
LLVM_PATH = '/home/chrome-bot/llvm-3.4/Release+Asserts/bin/'
class XsanBuildStepUtils(DefaultBuildStepUtils):
def Compile(self, target):
# Run the xsan_build script.
os.environ['PATH'] = LLVM_PATH + ':' + os.environ['PATH']
shell_utils.run(['which', 'clang'])
shell_utils.run(['clang', '--version'])
os.environ['GYP_DEFINES'] = self._step.args['gyp_defines']
print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES']
cmd = [
os.path.join('tools', 'xsan_build'),
self._step.args['sanitizer'],
target,
'BUILDTYPE=%s' % self._step.configuration,
]
cmd.extend(self._step.default_make_flags)
cmd.extend(self._step.make_flags)
shell_utils.run(cmd)
def RunFlavoredCmd(self, app, args):
os.environ['TSAN_OPTIONS'] = 'suppressions=tools/tsan.supp'
return shell_utils.run([self._PathToBinary(app)] + args)
|
Fix tests in test helpers | import {
introJSNext,
introJSPrevious,
introJSExit,
introJSEnsureClosed,
introJSCurrentStep } from './../helpers/ember-introjs';
import { module, test } from 'qunit';
import { visit } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
module('test helpers', function(hooks) {
setupApplicationTest(hooks);
hooks.beforeEach(async function() {
await visit('/');
});
hooks.afterEach(async function() {
return await introJSEnsureClosed();
})
test('can use the next helper', async function(assert) {
await introJSNext();
assert.equal(introJSCurrentStep().intro, 'Step 2!');
});
test('can use the exit helper', async function(assert){
await introJSExit();
assert.equal(document.querySelector('.introjs-overlay'), null);
});
test('can use the previous helper', async function(assert){
await introJSNext();
await introJSPrevious();
assert.equal(introJSCurrentStep().intro, 'Step 1!');
});
})
| import {
introJSNext,
introJSPrevious,
introJSExit,
introJSEnsureClosed,
introJSCurrentStep } from './../helpers/ember-introjs';
import { expect } from 'chai';
import { describe, it, beforeEach, afterEach } from 'mocha';
import { visit } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-mocha';
describe('test helpers', function() {
setupApplicationTest();
beforeEach(async function(){
await visit('/');
});
afterEach(async function(){
return await introJSEnsureClosed();
});
it('can use the next helper', async function(){
await introJSNext();
expect(introJSCurrentStep().intro).to.equal('Step 2!');
});
it('can use the exit helper', async function(){
await introJSExit();
expect(document.querySelector('.introjs-overlay')).to.equal(null);
});
it('can use the previous helper', async function(){
await introJSNext();
await introJSPrevious();
expect(introJSCurrentStep().intro).to.equal('Step 1!');
});
});
|
Add missing properties to response json | /*****************************************************************************
** Copyright (c) 2010 - 2012 Ushahidi Inc
** All rights reserved
** Contact: team@ushahidi.com
** Website: http://www.ushahidi.com
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: http://www.gnu.org/licenses/lgpl.html.
**
**
** If you have questions regarding the use of this file, please contact
** Ushahidi developers at team@ushahidi.com.
**
*****************************************************************************/
package com.crowdmap.java.sdk.json;
/**
* The class represents the Main response returned as a result of a Crowdmap api
* call.
*
*
*/
public class ResponseJson {
public String next;
public String curr;
public String prev;
public boolean success;
public int status;
public String timestamp;
public int qcount;
}
| /*****************************************************************************
** Copyright (c) 2010 - 2012 Ushahidi Inc
** All rights reserved
** Contact: team@ushahidi.com
** Website: http://www.ushahidi.com
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: http://www.gnu.org/licenses/lgpl.html.
**
**
** If you have questions regarding the use of this file, please contact
** Ushahidi developers at team@ushahidi.com.
**
*****************************************************************************/
package com.crowdmap.java.sdk.json;
/**
* The class represents the Main response returned as a result of a Crowdmap
* api call.
*
* @author eyedol
*
*/
public class ResponseJson {
public String next;
public String curr;
public String prev;
public boolean success;
public int status;
}
|
Fix the ‘Unexpected token’ error. | import lodash from 'lodash';
import merge from 'lodash/merge';
import keys from 'lodash/keys';
import each from 'lodash/each';
import clientWebpackConfig from './client';
const packageJson = require('../package.json');
let externals = {
'abagnale/lib/abagnale': {
root: 'abagnale',
commonjs2: 'abagnale',
commonjs: 'abagnale',
amd: 'abagnale',
},
};
each(keys(lodash), (method) => {
externals[`lodash/${method}`] = {
root: `lodash/${method}`,
commonjs2: `lodash/${method}`,
commonjs: `lodash/${method}`,
amd: `lodash/${method}`,
};
});
each(keys(packageJson.devDependencies), (devDependency) => {
externals[devDependency] = {
root: devDependency,
commonjs2: devDependency,
commonjs: devDependency,
amd: devDependency,
};
});
export default merge({}, clientWebpackConfig, {
output: {
filename: 'attributes-kit-no-deps.js',
},
externals,
devtool: 'source-map',
});
| import lodash from 'lodash';
import merge from 'lodash/merge';
import keys from 'lodash/keys';
import each from 'lodash/each';
import clientWebpackConfig from './client';
const packageJson = require('../package.json');
let externals = {
'abagnale/lib/abagnale': {
root: 'abagnale',
commonjs2: 'abagnale',
commonjs: 'abagnale',
amd: 'abagnale',
},
};
each(keys(lodash), => {
externals[`lodash/${method}`] = {
root: `lodash/${method}`,
commonjs2: `lodash/${method}`,
commonjs: `lodash/${method}`,
amd: `lodash/${method}`,
};
});
each(keys(packageJson.devDependencies), (devDependency) => {
externals[devDependency] = {
root: devDependency,
commonjs2: devDependency,
commonjs: devDependency,
amd: devDependency,
};
});
export default merge({}, clientWebpackConfig, {
output: {
filename: 'attributes-kit-no-deps.js',
},
externals,
devtool: 'source-map',
});
|
PEP8: Bring scripts folder up to pep8 standards | #!/usr/bin/env python
import serial
import os
import sys
import time
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("""\nPlease press the phsyical reset button on
the STM32F4Discovery board and then press enter to continue...""")
# Open a serial port
time.sleep(1)
print 'Connecting to /dev/serial/by-id/usb-eecs567_final_project-if00'
ser = serial.Serial("/dev/serial/by-id/usb-eecs567_final_project-if00", 115200)
# time.sleep(1)
# Send data to start USB OTG
print 'Write start'
ser.write("start")
print 'Run test'
# Read until we see the finished text
result = ''
try:
while True:
num_chars = ser.inWaiting()
if num_chars:
new = ''
try:
new = ser.read(num_chars)
except:
print '\nFailed to read'
sys.stdout.write(new)
result += new
if result.find("Finished") != -1:
break
finally:
# Close the serial port
ser.close()
| #!/usr/bin/env python
import serial
import os
import sys
import time
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("\nPlease press the phsyical reset button on the STM32F4Discovery board and then press enter to continue...")
# Open a serial port
time.sleep(1)
print 'Connecting to /dev/serial/by-id/usb-eecs567_final_project-if00'
ser = serial.Serial("/dev/serial/by-id/usb-eecs567_final_project-if00", 115200)
# time.sleep(1)
# Send data to start USB OTG
print 'Write start'
ser.write("start")
print 'Run test'
# Read until we see the finished text
result = ''
try:
while True:
num_chars = ser.inWaiting()
if num_chars:
new = ''
try:
new = ser.read(num_chars)
except:
print '\nFailed to read'
sys.stdout.write(new)
result += new
if result.find("Finished") != -1:
break
finally:
# Print the result so the user can see and close the serial port
#print result
ser.close() |
Remove writing to options object. This allows options parameter to be readonly | "use strict";
var mischief = require('./mischief');
// The only surface area for this module is the middleware factory
// prototype defined here.
var chaos_monkeyware = module.exports = function (options) {
var probability = options.probability || 0.1;
return function middleware (req, res, next) {
var mischiefNames, mischiefName;
// First, decide whether to do anything at all.
if (Math.random() > 1 - probability) {
// Select a mischief at random.
mischiefNames = Object.keys(mischief);
mischiefName = mischiefNames[Math.floor(Math.random() * mischiefNames.length)];
// Set a header so it's apparent to anyone inspecting the request
// that this failure was... special.
res.setHeader('ChaosMonkeyWare', mischiefName);
if (options && typeof options.logger === 'function') {
options.logger('ChaosMonkeyWare mischief: ' + mischiefName);
}
return mischief[mischiefName](req, res, next);
}
return next();
};
};
| "use strict";
var mischief = require('./mischief');
// The only surface area for this module is the middleware factory
// prototype defined here.
var chaos_monkeyware = module.exports = function (options) {
// Set default values for those not provided by user.
options = options || {};
options.probability = options.probability || 0.1;
return function middleware (req, res, next) {
var mischiefNames, mischiefName;
// First, decide whether to do anything at all.
if (Math.random() > 1 - options.probability) {
// Select a mischief at random.
mischiefNames = Object.keys(mischief);
mischiefName = mischiefNames[Math.floor(Math.random() * mischiefNames.length)];
// Set a header so it's apparent to anyone inspecting the request
// that this failure was... special.
res.setHeader('ChaosMonkeyWare', mischiefName);
if (options.logger) {
options.logger('ChaosMonkeyWare mischief: ' + mischiefName);
}
return mischief[mischiefName](req, res, next);
}
return next();
};
};
|
Fix Orbit namespace reference to LocalStorageSource | import Orbit from './orbit/core';
import eq from './orbit/lib/eq';
import clone from './orbit/lib/clone';
import diffs from './orbit/lib/diffs';
import Cache from './orbit/cache';
import Document from './orbit/document';
import Evented from './orbit/evented';
import Notifier from './orbit/notifier';
import Requestable from './orbit/requestable';
import Transaction from './orbit/transaction';
import TransformQueue from './orbit/transform_queue';
import Transformable from './orbit/transformable';
import Source from './orbit/sources/source';
import LocalStorageSource from './orbit/sources/local_storage_source';
import MemorySource from './orbit/sources/memory_source';
import JSONAPISource from './orbit/sources/jsonapi_source';
import RequestConnector from './orbit/connectors/request_connector';
import TransformConnector from './orbit/connectors/transform_connector';
Orbit.eq = eq;
Orbit.clone = clone;
Orbit.diffs = diffs;
Orbit.Cache = Cache;
Orbit.Document = Document;
Orbit.Evented = Evented;
Orbit.Notifier = Notifier;
Orbit.Requestable = Requestable;
Orbit.Transaction = Transaction;
Orbit.TransformQueue = TransformQueue;
Orbit.Transformable = Transformable;
Orbit.Source = Source;
Orbit.LocalStorageSource = LocalStorageSource;
Orbit.MemorySource = MemorySource;
Orbit.JSONAPISource = JSONAPISource;
Orbit.RequestConnector = RequestConnector;
Orbit.TransformConnector = TransformConnector;
export default Orbit; | import Orbit from './orbit/core';
import eq from './orbit/lib/eq';
import clone from './orbit/lib/clone';
import diffs from './orbit/lib/diffs';
import Cache from './orbit/cache';
import Document from './orbit/document';
import Evented from './orbit/evented';
import Notifier from './orbit/notifier';
import Requestable from './orbit/requestable';
import Transaction from './orbit/transaction';
import TransformQueue from './orbit/transform_queue';
import Transformable from './orbit/transformable';
import Source from './orbit/sources/source';
import LocalSource from './orbit/sources/local_storage_source';
import MemorySource from './orbit/sources/memory_source';
import JSONAPISource from './orbit/sources/jsonapi_source';
import RequestConnector from './orbit/connectors/request_connector';
import TransformConnector from './orbit/connectors/transform_connector';
Orbit.eq = eq;
Orbit.clone = clone;
Orbit.diffs = diffs;
Orbit.Cache = Cache;
Orbit.Document = Document;
Orbit.Evented = Evented;
Orbit.Notifier = Notifier;
Orbit.Requestable = Requestable;
Orbit.Transaction = Transaction;
Orbit.TransformQueue = TransformQueue;
Orbit.Transformable = Transformable;
Orbit.Source = Source;
Orbit.LocalSource = LocalSource;
Orbit.MemorySource = MemorySource;
Orbit.JSONAPISource = JSONAPISource;
Orbit.RequestConnector = RequestConnector;
Orbit.TransformConnector = TransformConnector;
export default Orbit; |
Fix reference to pluginError function | var through = require("through2"),
gutil = require("gulp-util"),
cdnizer = require('cdnizer');
function pluginError(msg) {
return new gutil.PluginError("gulp-cdnizer", msg);
}
module.exports = function(opts) {
"use strict";
var cdnizerHandler = cdnizer(opts);
//noinspection JSUnusedLocalSymbols
function cdnizerStream(file, enc, callback) {
// Do nothing if no contents
if(file.isNull()) {
this.push(file);
return callback();
}
if(file.isStream()) {
this.emit("error", pluginError("Stream content is not supported"));
return callback();
}
// check if file.contents is a `Buffer`
if(file.isBuffer()) {
try {
file.contents = new Buffer(cdnizerHandler(String(file.contents)));
this.push(file);
} catch(error) {
this.emit("error", pluginError(error.toString()))
}
}
return callback();
}
return through.obj(cdnizerStream);
};
| var through = require("through2"),
gutil = require("gulp-util"),
cdnizer = require('cdnizer');
function pluginError(msg) {
return new gutil.PluginError("gulp-cdnizer", msg);
}
module.exports = function(opts) {
"use strict";
var cdnizerHandler = cdnizer(opts);
//noinspection JSUnusedLocalSymbols
function cdnizerStream(file, enc, callback) {
// Do nothing if no contents
if(file.isNull()) {
this.push(file);
return callback();
}
if(file.isStream()) {
this.emit("error", pluginError("Stream content is not supported"));
return callback();
}
// check if file.contents is a `Buffer`
if(file.isBuffer()) {
try {
file.contents = new Buffer(cdnizerHandler(String(file.contents)));
this.push(file);
} catch(error) {
this.emit("error", error(error.toString()))
}
}
return callback();
}
return through.obj(cdnizerStream);
};
|
Read DB test config from a file | <?php
namespace Hodor\Database;
use Exception;
use PHPUnit_Framework_TestCase;
class PgsqlAdapterTest extends PHPUnit_Framework_TestCase
{
/**
* @var array
*/
private $config;
public function setUp()
{
parent::setUp();
$config_path = __DIR__ . '/../../../config/config.php';
if (!file_exists($config_path)) {
throw new Exception("'{$config_path}' not found");
}
$this->config = require $config_path;
}
/**
* @expectedException \Exception
*/
public function testRequestingAConnectionWithoutADsnThrowsAnException()
{
$db = new PgsqlAdapter([]);
$db->getConnection();
}
/**
* @expectedException \Exception
*/
public function testAConnectionFailureThrowsAnException()
{
$db = new PgsqlAdapter(['dsn' => 'host=localhost user=nonexistent']);
$db->getConnection();
}
public function testAConnectionCanBeMade()
{
$db = new PgsqlAdapter($this->config['test']['db']['pgsql']);
$this->assertEquals('resource', gettype($db->getConnection()));
}
}
| <?php
namespace Hodor\Database;
use PHPUnit_Framework_TestCase;
class PgsqlAdapterTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException \Exception
*/
public function testRequestingAConnectionWithoutADsnThrowsAnException()
{
$db = new PgsqlAdapter([]);
$db->getConnection();
}
/**
* @expectedException \Exception
*/
public function testAConnectionFailureThrowsAnException()
{
$db = new PgsqlAdapter(['dsn' => 'host=localhost user=nonexistent']);
$db->getConnection();
}
public function testAConnectionCanBeMade()
{
$db = new PgsqlAdapter(['dsn' => 'host=localhost user=lightster2']);
$this->assertEquals('resource', gettype($db->getConnection()));
}
}
|
Set base path before capturing context | 'use strict';
var ap = require('ap');
var d = require('../decorators');
var fs = require('fs');
var merge = require('merge');
var q = require('q');
var cons = require('consolidate');
var writeFile;
Object.keys(cons).forEach(function (engine) {
var renderFile;
exports[engine] = d.push(d.srcDest(function (src, dest, options) {
// Lazy
renderFile = renderFile || q.denodeify(cons[engine]);
writeFile = writeFile || q.denodeify(fs.writeFile);
// Ensure base path is set
this.base(dest);
// Merge options
var ctx = merge({}, this.ctx, options);
// Write destination callback
var writeDest = ap([dest], writeFile);
// Render, then write
return renderFile(src, ctx).then(writeDest);
}));
});
| 'use strict';
var ap = require('ap');
var d = require('../decorators');
var fs = require('fs');
var merge = require('merge');
var q = require('q');
var cons = require('consolidate');
var writeFile;
Object.keys(cons).forEach(function (engine) {
var renderFile;
exports[engine] = d.push(d.srcDest(function (src, dest, options) {
// Lazy
renderFile = renderFile || q.denodeify(cons[engine]);
writeFile = writeFile || q.denodeify(fs.writeFile);
// Merge options
var ctx = merge({}, this.ctx, options);
// Write destination callback
var writeDest = ap([dest], writeFile);
// Ensure base path is set
this.base(dest);
// Render, then write
return renderFile(src, ctx).then(writeDest);
}));
});
|
Stop AJAX updates queuing requests
The `updateContent` module updates a section of the page based on an
AJAX request.
The current implementation will poll every `x` seconds. If the server
takes a long time to respond, this results in a the browser queuing up
requests. If a particular endpoint is slow, this can result in one
client making enough requests to slow down the whole server, to the
point where it gets removed from the loadbalancer, eventually bringing
the whole site down.
This commit rewrites the module so that it queues up the render
operations, not the requests.
There is one queue per endpoint, so for
`http://example.com/endpoint.json`:
1. Queue is empty
```javascript
{
'http://example.com/endpoint.json': []
}
```
2. Inital re-render is put on the queue…
```javascript
{
'http://example.com/endpoint.json': [
function render(){…}
]
}
```
…AJAX request fires
```
GET http://example.com/endpoint.json
```
3. Every `x` seconds, another render operation is put on the queue
```javascript
{
'http://example.com/endpoint.json': [
function render(){…},
function render(){…},
function render(){…}
]
}
```
4. AJAX request returns queue is flushed by executing each queued
render function in sequence
```javascript
render(response); render(response); render(response);
```
```javascript
{
'http://example.com/endpoint.json': []
}
```
5. Repeat
This means that, at most, the AJAX requests will never fire more than
once every `x` seconds, where `x` defaults to `1.5`. | (function(Modules) {
"use strict";
var queues = {};
var dd = new diffDOM();
var getRenderer = $component => response => dd.apply(
$component.get(0),
dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
);
var getQueue = resource => (
queues[resource] = queues[resource] || []
);
var flushQueue = function(queue, response) {
while(queue.length) queue.shift()(response);
};
var poll = function(renderer, resource, queue, interval) {
if (queue.push(renderer) === 1) $.get(
resource,
response => flushQueue(queue, response)
);
setTimeout(
() => poll(...arguments), interval
);
};
Modules.UpdateContent = function() {
this.start = component => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
($(component).data('interval-seconds') || 1.5) * 1000
);
};
})(window.GOVUK.Modules);
| (function(GOVUK, Modules) {
"use strict";
GOVUK.timeCache = {};
GOVUK.resultCache = {};
var dd = new diffDOM();
let getter = function(resource, interval, render) {
if (
GOVUK.resultCache[resource] &&
(Date.now() < GOVUK.timeCache[resource])
) {
render(GOVUK.resultCache[resource]);
} else {
GOVUK.timeCache[resource] = Date.now() + interval;
$.get(
resource,
response => render(GOVUK.resultCache[resource] = response)
);
}
};
let poller = (resource, key, $component, interval) => () => getter(
resource, interval, response => dd.apply(
$component.get(0),
dd.diff($component.get(0), $(response[key]).get(0))
)
);
Modules.UpdateContent = function() {
this.start = function(component) {
const $component = $(component);
interval = ($(component).data("interval-seconds") * 1000) || 1500;
setInterval(
poller($component.data('resource'), $component.data('key'), $component, interval),
interval / 5
);
};
};
})(window.GOVUK, window.GOVUK.Modules);
|
Use 'on duplicate key update' rather than 'replace into'
'relace into' fires triggers and constraints. :( | package bamboo.crawl;
import bamboo.pandas.PandasAgency;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlBatch;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean;
import java.util.List;
public interface AgencyDAO {
@SqlQuery("SELECT * FROM agency WHERE id = :id")
@MapResultAsBean
Agency findAgencyById(@Bind("id") int id);
@SqlBatch("INSERT INTO agency (id, name, abbreviation, url, logo) " +
"VALUES (:id, :name, :abbreviation, :url, :logo) " +
"ON DUPLICATE KEY UPDATE name = :name, abbreviation = :abbreviation, url = :url, logo = :logo")
void replaceAll(@BindBean List<PandasAgency> listAgencies);
}
| package bamboo.crawl;
import bamboo.pandas.PandasAgency;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlBatch;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean;
import java.util.List;
public interface AgencyDAO {
@SqlQuery("SELECT * FROM agency WHERE id = :id")
@MapResultAsBean
Agency findAgencyById(@Bind("id") int id);
@SqlBatch("REPLACE INTO agency (id, name, abbreviation, url, logo) VALUES (:id, :name, :abbreviation, :url, :logo)")
void replaceAll(@BindBean List<PandasAgency> listAgencies);
}
|
Update Carbon versionadded tags to 2016.11.0 in grains/* | # -*- coding: utf-8 -*-
'''
Grains for Cisco NX OS Switches Proxy minions
.. versionadded: 2016.11.0
For documentation on setting up the nxos proxy minion look in the documentation
for :doc:`salt.proxy.nxos</ref/proxy/all/salt.proxy.nxos>`.
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Libs
import salt.utils
import salt.modules.nxos
import logging
log = logging.getLogger(__name__)
__proxyenabled__ = ['nxos']
__virtualname__ = 'nxos'
def __virtual__():
try:
if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'nxos':
return __virtualname__
except KeyError:
pass
return False
def proxy_functions(proxy=None):
if proxy is None:
return {}
if proxy['nxos.initialized']() is False:
return {}
return {'nxos': proxy['nxos.grains']()}
| # -*- coding: utf-8 -*-
'''
Grains for Cisco NX OS Switches Proxy minions
.. versionadded: Carbon
For documentation on setting up the nxos proxy minion look in the documentation
for :doc:`salt.proxy.nxos</ref/proxy/all/salt.proxy.nxos>`.
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Libs
import salt.utils
import salt.modules.nxos
import logging
log = logging.getLogger(__name__)
__proxyenabled__ = ['nxos']
__virtualname__ = 'nxos'
def __virtual__():
try:
if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'nxos':
return __virtualname__
except KeyError:
pass
return False
def proxy_functions(proxy=None):
if proxy is None:
return {}
if proxy['nxos.initialized']() is False:
return {}
return {'nxos': proxy['nxos.grains']()}
|
Align with changes in abc-table-detail. | <?php
//----------------------------------------------------------------------------------------------------------------------
namespace SetBased\Abc\Core\TableRow\System;
use SetBased\Abc\Core\Page\System\PageDetailsPage;
use SetBased\Abc\Helper\Html;
use SetBased\Abc\Table\DetailTable;
//----------------------------------------------------------------------------------------------------------------------
/**
* Table row showing the original page of a page.
*/
class PageDetailsTableRow
{
//--------------------------------------------------------------------------------------------------------------------
/**
* Adds a row with a class name of a page with link to the page details to a detail table.
*
* @param DetailTable $table The (detail) table.
* @param string $header The row header text.
* @param array $data The page details.
*/
public static function addRow($table, $header, $data)
{
$a = Html::generateElement('a', ['href' => PageDetailsPage::getUrl($data['pag_id_org'])], $data['pag_id_org']);
$table->addRow($header, ['class' => 'text'], $a, true);
}
//--------------------------------------------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------------------------------------------
| <?php
//----------------------------------------------------------------------------------------------------------------------
namespace SetBased\Abc\Core\TableRow\System;
use SetBased\Abc\Core\Page\System\PageDetailsPage;
use SetBased\Abc\Helper\Html;
use SetBased\Abc\Table\DetailTable;
//----------------------------------------------------------------------------------------------------------------------
/**
*
*/
class PageDetailsTableRow
{
//--------------------------------------------------------------------------------------------------------------------
/**
* Adds a row with a class name of a page with link to the page details to a detail table.
*
* @param DetailTable $table The (detail) table.
* @param string $header The row header text.
* @param array $data The page details.
*/
public static function addRow($table, $header, $data)
{
$row = '<tr><th>';
$row .= Html::txt2Html($header);
$row .= '</th><td class="text"><a';
$row .= Html::generateAttribute('href', PageDetailsPage::getUrl($data['pag_id_org']));
$row .= '>';
$row .= $data['pag_id_org'];
$row .= '</a></td></tr>';
$table->addRow($row);
}
//--------------------------------------------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------------------------------------------
|
Update for Backbone 1.3.3 parity. | /**
* ModuleRuntime.js (Parse) -- Provides the standard / default configuration that is the same as Backbone 1.2.3
*/
'use strict';
import Backbone from 'backbone-es6/src/Backbone.js';
import ParseCollection from './ParseCollection.js';
import TyphonEvents from 'typhonjs-core-backbone-events/src/TyphonEvents.js';
import History from 'backbone-es6/src/History.js';
import Model from './ParseModel.js';
import Router from 'backbone-es6/src/Router.js';
import View from 'backbone-es6/src/View.js';
import parseSync from './parseSync.js';
import parseExtend from './parseExtend.js';
import typhonExtend from 'typhonjs-core-backbone-common/src/typhonExtend.js';
const options =
{
// Current version of the library. Keep in sync with Backbone version supported.
VERSION: '1.3.3'
};
const backbone = new Backbone(ParseCollection, TyphonEvents, History, Model, Router, View, parseSync, options);
parseExtend(backbone);
typhonExtend(backbone);
export default backbone; | /**
* ModuleRuntime.js (Parse) -- Provides the standard / default configuration that is the same as Backbone 1.2.3
*/
'use strict';
import Backbone from 'backbone-es6/src/Backbone.js';
import ParseCollection from './ParseCollection.js';
import TyphonEvents from 'typhonjs-core-backbone-events/src/TyphonEvents.js';
import History from 'backbone-es6/src/History.js';
import Model from './ParseModel.js';
import Router from 'backbone-es6/src/Router.js';
import View from 'backbone-es6/src/View.js';
import parseSync from './parseSync.js';
import parseExtend from './parseExtend.js';
import typhonExtend from 'typhonjs-core-backbone-common/src/typhonExtend.js';
const options =
{
// Current version of the library. Keep in sync with Backbone version supported.
VERSION: '1.2.3'
};
const backbone = new Backbone(ParseCollection, TyphonEvents, History, Model, Router, View, parseSync, options);
parseExtend(backbone);
typhonExtend(backbone);
export default backbone; |
Add visibility tagging to MethoDefinition | from thinglang.lexer.definitions.tags import LexicalPrivateTag
from thinglang.lexer.definitions.thing_definition import LexicalDeclarationMember
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.symbols.symbol import Symbol
class MemberDefinition(BaseNode):
"""
A member definition
Must be a direct child of a ThingDefinition
"""
def __init__(self, name, type_name, visibility=Symbol.PUBLIC):
super(MemberDefinition, self).__init__([name, type_name])
self.type, self.name, self.visibility = type_name, name, visibility
def __repr__(self):
return 'has {} {}'.format(self.type, self.name)
def symbol(self):
return Symbol.member(self.name, self.type, self.visibility)
MEMBER_NAME_TYPES = Identifier
@staticmethod
@ParserRule.mark
def parse_member_definition(_: (LexicalDeclarationMember, LexicalPrivateTag), type_name: MEMBER_NAME_TYPES, name: Identifier):
return MemberDefinition(name, type_name)
| from thinglang.lexer.definitions.tags import LexicalPrivateTag
from thinglang.lexer.definitions.thing_definition import LexicalDeclarationMember
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.symbols.symbol import Symbol
class MemberDefinition(BaseNode):
"""
A member definition
Must be a direct child of a ThingDefinition
"""
def __init__(self, name, type_name, visibility=Symbol.PUBLIC):
super(MemberDefinition, self).__init__([name, type_name])
self.type, self.name, self.visibility = type_name, name, visibility
def __repr__(self):
return 'has {} {}'.format(self.type, self.name)
def symbol(self):
return Symbol.member(self.name, self.type, self.visibility)
MEMBER_NAME_TYPES = Identifier
@staticmethod
@ParserRule.mark
def parse_member_definition(_: LexicalDeclarationMember, type_name: MEMBER_NAME_TYPES, name: Identifier):
return MemberDefinition(name, type_name)
@staticmethod
@ParserRule.mark
def tag_member_definition(_: LexicalPrivateTag, member: 'MemberDefinition'):
member.visibility = Symbol.PRIVATE
return member
|
Remove lingering backlog import that broke things | import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
// import { AccountsTemplates } from 'meteor/useraccounts:core';
// Import to load these templates
import '../../ui/layouts/layout.js';
import '../../ui/pages/dashboard.js';
import '../../ui/pages/history.js';
// Import to override accounts templates
// import '../../ui/accounts/accounts-templates.js'; // TODO: set up user accounts
// Below here are the route definitions
FlowRouter.route('/dashboard', {
action: function(params, queryParams) {
BlazeLayout.render('layout', { page: 'dashboard' });
}
});
FlowRouter.route('/history', {
action: function(params, queryParams) {
BlazeLayout.render('layout', { page: 'history' });
}
});
FlowRouter.route('/', {
triggersEnter: [function(context, redirect) {
redirect('/dashboard');
}]
});
| import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
// import { AccountsTemplates } from 'meteor/useraccounts:core';
// Import to load these templates
import '../../ui/layouts/layout.js';
import '../../ui/pages/backlog.js';
import '../../ui/pages/dashboard.js';
import '../../ui/pages/history.js';
// Import to override accounts templates
// import '../../ui/accounts/accounts-templates.js'; // TODO: set up user accounts
// Below here are the route definitions
FlowRouter.route('/dashboard', {
action: function(params, queryParams) {
BlazeLayout.render('layout', { page: 'dashboard' });
}
});
FlowRouter.route('/history', {
action: function(params, queryParams) {
BlazeLayout.render('layout', { page: 'history' });
}
});
FlowRouter.route('/', {
triggersEnter: [function(context, redirect) {
redirect('/dashboard');
}]
});
|
Fix typo. dest_key => dest_keys.
modified: s3s3/api.py | """
The API for s3s3.
"""
import tempfile
from boto.s3.connection import S3Connection
def create_connection(connection_args):
connection_args = connection_args.copy()
connection_args.pop('bucket_name')
return S3Connection(**connection_args)
def upload(source_key, dest_keys):
"""
`source_key` The source boto s3 key.
`dest_keys` A list of the destination boto s3 keys.
"""
# Use the same name if no destination key is passed.
if not dest_keys or not source_key:
raise Exception(
'The source_key and dest_keys parameters are required.')
with tempfile.NamedTemporaryFile() as data:
source_key.get_contents_to_file(data)
for dest_key in dest_keys:
dest_key.set_contents_from_filename(data.name)
| """
The API for s3s3.
"""
import tempfile
from boto.s3.connection import S3Connection
def create_connection(connection_args):
connection_args = connection_args.copy()
connection_args.pop('bucket_name')
return S3Connection(**connection_args)
def upload(source_key, dest_keys):
"""
`source_key` The source boto s3 key.
`dest_keys` The destination boto s3 keys.
"""
# Use the same name if no destination key is passed.
if not dest_key:
dest_key = source_key
with tempfile.NamedTemporaryFile() as data:
source_key.get_contents_to_file(data)
for dest_key in dest_keys:
dest_key.set_contents_from_filename(data.name)
|
Add an equality method for CloudConfig
In order to track if a config has changed, we need to be able to compare
the CloudConfig objects for equality.
Change-Id: Icdd9acede81bc5fba60d877194048e24a62c9e5d | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.
class CloudConfig(object):
def __init__(self, name, region, config):
self.name = name
self.region = region
self.config = config
def __getattr__(self, key):
"""Return arbitrary attributes."""
if key.startswith('os_'):
key = key[3:]
if key in [attr.replace('-', '_') for attr in self.config]:
return self.config[key]
else:
return None
def __iter__(self):
return self.config.__iter__()
def __eq__(self, other):
return (self.name == other.name and self.region == other.region
and self.config == other.config)
| # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.
class CloudConfig(object):
def __init__(self, name, region, config):
self.name = name
self.region = region
self.config = config
def __getattr__(self, key):
"""Return arbitrary attributes."""
if key.startswith('os_'):
key = key[3:]
if key in [attr.replace('-', '_') for attr in self.config]:
return self.config[key]
else:
return None
def __iter__(self):
return self.config.__iter__()
|
Use our own get_object_or_404 for ModelPublisher.get_object | from __future__ import unicode_literals
from .. import http
from ..shortcuts import get_object_or_404
from .publisher import Publisher
from django.db import transaction
class ModelPublisher(Publisher):
'''A Publisher with useful methods to publish Models'''
@property
def model(self):
'''By default, we try to get the model from our serialiser'''
# XXX Should this call get_serialiser?
return self.serialiser._meta.model
# Auto-build serialiser from model class?
def get_object_list(self):
return self.model.objects.all()
def get_object(self, object_id):
return get_object_or_404(self.get_object_list(), pk=object_id)
def list_post_default(self, request, **kwargs):
data = self.get_request_data()
serialiser = self.get_serialiser()
serialiser_kwargs = self.get_serialiser_kwargs()
try:
with transaction.atomic():
obj = serialiser.object_inflate(data, **serialiser_kwargs)
except ValueError as e:
return http.BadRequest(str(e))
return self.render_single_object(obj, serialiser)
| from __future__ import unicode_literals
from .. import http
from .publisher import Publisher
from django.db import transaction
from django.shortcuts import get_object_or_404
class ModelPublisher(Publisher):
'''A Publisher with useful methods to publish Models'''
@property
def model(self):
'''By default, we try to get the model from our serialiser'''
# XXX Should this call get_serialiser?
return self.serialiser._meta.model
# Auto-build serialiser from model class?
def get_object_list(self):
return self.model.objects.all()
def get_object(self, object_id):
return get_object_or_404(self.get_object_list(), pk=object_id)
def list_post_default(self, request, **kwargs):
data = self.get_request_data()
serialiser = self.get_serialiser()
serialiser_kwargs = self.get_serialiser_kwargs()
try:
with transaction.atomic():
obj = serialiser.object_inflate(data, **serialiser_kwargs)
except ValueError as e:
return http.BadRequest(str(e))
return self.render_single_object(obj, serialiser)
|
Allow persistent locale-based formatting for DateFormat | package com.xfyre.tapestry5.xtensions.components;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PersistentLocale;
/**
* Convenience component for formatting dates
* @author xfire
*
*/
public class FormatDate {
/**
* Date value
*/
@Parameter(required=true,defaultPrefix=BindingConstants.PROP)
private Date date;
/**
* Format string
*/
@Parameter(required=false,defaultPrefix=BindingConstants.LITERAL)
private String format;
@Inject
private PersistentLocale persistentLocale;
void beginRender ( MarkupWriter writer ) {
if ( date == null ) {
writer.writeRaw ( "" );
} else {
DateFormat df = format == null ?
DateFormat.getDateInstance ( DateFormat.SHORT, persistentLocale.get () ) : new SimpleDateFormat ( format );
writer.writeRaw ( df.format ( date ) );
}
}
}
| package com.xfyre.tapestry5.xtensions.components;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.Parameter;
/**
* Convenience component for formatting dates
* @author xfire
*
*/
public class FormatDate {
/**
* Date value
*/
@Parameter(required=true,defaultPrefix=BindingConstants.PROP)
private Date date;
/**
* Format string
*/
@Parameter(required=true,defaultPrefix=BindingConstants.LITERAL)
private String format;
void beginRender ( MarkupWriter writer ) {
if ( date == null ) {
writer.writeRaw ( "" );
} else {
DateFormat df = new SimpleDateFormat ( format );
writer.writeRaw ( df.format ( date ) );
}
}
}
|
Update MathJax URL to 2.7.4 | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js'
PYGMENTS_STYLE = 'default'
def get_pygments_stylesheet(selector, style=None):
if style is None:
style = PYGMENTS_STYLE
if style == '':
return ''
try:
from pygments.formatters import HtmlFormatter
except ImportError:
return ''
else:
return HtmlFormatter(style=style).get_style_defs(selector) + '\n'
def get_mathjax_url(webenv):
if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
return MATHJAX_LOCAL_URL
else:
return MATHJAX_WEB_URL
| # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.expanduser('~/.config'))
MATHJAX_LOCAL_URL = 'file:///usr/share/javascript/mathjax/MathJax.js'
MATHJAX_WEB_URL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js'
PYGMENTS_STYLE = 'default'
def get_pygments_stylesheet(selector, style=None):
if style is None:
style = PYGMENTS_STYLE
if style == '':
return ''
try:
from pygments.formatters import HtmlFormatter
except ImportError:
return ''
else:
return HtmlFormatter(style=style).get_style_defs(selector) + '\n'
def get_mathjax_url(webenv):
if os.path.exists(MATHJAX_LOCAL_URL[7:]) and not webenv:
return MATHJAX_LOCAL_URL
else:
return MATHJAX_WEB_URL
|
Fix test to import moved package. | package sanitized_anchor_name_test
import (
"fmt"
"github.com/shurcooL/sanitized_anchor_name"
)
func ExampleCreate() {
anchorName := sanitized_anchor_name.Create("This is a header")
fmt.Println(anchorName)
// Output:
// this-is-a-header
}
func ExampleCreate2() {
fmt.Println(sanitized_anchor_name.Create("This is a header"))
fmt.Println(sanitized_anchor_name.Create("This is also a header"))
fmt.Println(sanitized_anchor_name.Create("main.go"))
fmt.Println(sanitized_anchor_name.Create("Article 123"))
fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?"))
fmt.Printf("%q\n", sanitized_anchor_name.Create(" "))
fmt.Println(sanitized_anchor_name.Create("Hello, 世界"))
// Output:
// this-is-a-header
// this-is-also-a-header
// main-go
// article-123
// let-s-try-this-shall-we
// ""
// hello-世界
}
| package sanitized_anchor_name_test
import (
"fmt"
"github.com/shurcooL/go/github_flavored_markdown/sanitized_anchor_name"
)
func ExampleCreate() {
anchorName := sanitized_anchor_name.Create("This is a header")
fmt.Println(anchorName)
// Output:
// this-is-a-header
}
func ExampleCreate2() {
fmt.Println(sanitized_anchor_name.Create("This is a header"))
fmt.Println(sanitized_anchor_name.Create("This is also a header"))
fmt.Println(sanitized_anchor_name.Create("main.go"))
fmt.Println(sanitized_anchor_name.Create("Article 123"))
fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?"))
fmt.Printf("%q\n", sanitized_anchor_name.Create(" "))
fmt.Println(sanitized_anchor_name.Create("Hello, 世界"))
// Output:
// this-is-a-header
// this-is-also-a-header
// main-go
// article-123
// let-s-try-this-shall-we
// ""
// hello-世界
}
|
Use cloning. Sorry, screwed that up. | //
// Like testTwo, but instead of simply replacing the nodes
// we first clone them. This leads to a single DOM op instead
// of `n+1` DOM ops.
//
(function() {
var btn = document.querySelector('#test3');
btn.addEventListener('click', function() {
// Create our list, and append it to the test node
var $list = $('<ul></ul>');
var lis = new Array(10000);
for(var i=0; i<lis.length; i++) {
var $li = $('<li></li>').addClass('l'+i);
lis[i] = $li;
$list.append($li);
}
test.$el.append($list);
// Rather than create a new tree from a template, I'm going ahead and cloning it
var $listClone = $list.clone();
// Kick off the test
test.start('three');
// Loop through the children in the cloned tree, replacing
// them with cloned versions of the elements in the existing
// tree. This causes 0 ops
$listClone.children().each(function(index, li) {
$(li).replaceWith(lis[index].clone(true));
});
// The only op is the replace
test.$el.find('ul').empty().append($listClone);
test.stop();
});
})();
| //
// Like testTwo, but instead of simply replacing the nodes
// we first clone them. This leads to a single DOM op instead
// of `n+1` DOM ops.
//
(function() {
var btn = document.querySelector('#test3');
btn.addEventListener('click', function() {
// Create our list, and append it to the test node
var $list = $('<ul></ul>');
var lis = new Array(10000);
for(var i=0; i<lis.length; i++) {
var $li = $('<li></li>').addClass('l'+i);
lis[i] = $li;
$list.append($li);
}
test.$el.append($list);
// Rather than create a new tree from a template, I'm going ahead and cloning it
var $listClone = $list.clone();
// Kick off the test
test.start('three');
// Loop through the children in the cloned tree, replacing
// them with cloned versions of the elements in the existing
// tree. This causes 0 ops
$listClone.children().each(function(index, li) {
$(li).replaceWith(lis[index]);
});
// The only op is the replace
test.$el.find('ul').append($listClone.contents());
test.stop();
});
})();
|
Remove debug output from insertDataTable |
function jsonRequestFailure(jqXHR, status, errorThrown){
console.log(errorThrown);
}
function requestDataTable(target, dataSource){
$.ajax({
url: dataSource,
type: 'GET',
dataType: 'json',
success: function(incoming) { insertDataTable(target, incoming); },
error: jsonRequestFailure,
});
}
function insertDataTable(target, data){
console.log(target);
console.log(data);
data = data['data'];
var columns = [];
var rows = [];
for(var key in data[0]){
columns.push(key);
}
for(var i = 0; i < data.length; i++){
var row = [];
rows.push(row);
for(var keyId in columns){
row.push(data[i][columns[keyId]]);
}
}
$(target)
.TidyTable({
columnTitles : columns,
columnValues : rows,
});
}
|
function jsonRequestFailure(jqXHR, status, errorThrown){
console.log(errorThrown);
}
function requestDataTable(target, dataSource){
$.ajax({
url: dataSource,
type: 'GET',
dataType: 'json',
success: function(incoming) { insertDataTable(target, incoming); },
error: jsonRequestFailure,
});
}
function insertDataTable(target, data){
console.log(target);
console.log(data);
data = data['data'];
var columns = [];
var rows = [];
for(var key in data[0]){
columns.push(key);
}
for(var i = 0; i < data.length; i++){
var row = [];
rows.push(row);
for(var keyId in columns){
row.push(data[i][columns[keyId]]);
}
}
console.log(columns);
console.log(rows);
$(target)
.TidyTable({
columnTitles : columns,
columnValues : rows,
});
}
|
Remove now useless timers polyfill |
'use strict';
// Move to titaniumifier!
process.execPath || (process.execPath = '/path/to/node');
var Promise = require('bluebird');
var request = require('./lib/request');
var liferay = exports;
liferay.Promise = Promise;
liferay.request = request;
liferay.errors = require('./lib/errors');
liferay.identify = require('./lib/identify');
liferay.camelcase = require('./lib/camelcase');
liferay.base = require('./lib/connectors/base');
liferay.v61 = require('./lib/connectors/liferay61');
liferay.v62 = require('./lib/connectors/liferay62');
liferay.connectors = [
liferay.v61, liferay.v62
];
liferay.guest = function (portalURL, auth, callback) {
return liferay.identify(portalURL, null).then(function (connector) {
return connector.guest(portalURL);
}).nodeify(callback);
};
liferay.authenticate = function (portalURL, auth, callback) {
return liferay.identify(portalURL, auth).then(function (connector) {
return connector.authenticate(portalURL, auth);
}).nodeify(callback);
};
|
'use strict';
// Move to titaniumifier!
process.execPath || (process.execPath = '/path/to/node');
// Move to titaniumifier!
global.setTimeout = (function (setTimeout) {
return function _setTimeout(fn, timeout) {
return setTimeout(fn, timeout);
};
})(global.setTimeout);
global.clearTimeout = (function (clearTimeout) {
return function _clearTimeout(timeoutId) {
if (typeof timeoutId === 'number') return clearTimeout(timeoutId);
else return undefined;
};
})(global.clearTimeout);
var Promise = require('bluebird');
var request = require('./lib/request');
var liferay = exports;
liferay.Promise = Promise;
liferay.request = request;
liferay.errors = require('./lib/errors');
liferay.identify = require('./lib/identify');
liferay.camelcase = require('./lib/camelcase');
liferay.base = require('./lib/connectors/base');
liferay.v61 = require('./lib/connectors/liferay61');
liferay.v62 = require('./lib/connectors/liferay62');
liferay.connectors = [
liferay.v61, liferay.v62
];
liferay.guest = function (portalURL, auth, callback) {
return liferay.identify(portalURL, null).then(function (connector) {
return connector.guest(portalURL);
}).nodeify(callback);
};
liferay.authenticate = function (portalURL, auth, callback) {
return liferay.identify(portalURL, auth).then(function (connector) {
return connector.authenticate(portalURL, auth);
}).nodeify(callback);
};
|
Add note to misleading test | """
Plot to test custom date axis tick locations and labels
NOTE (@vladh): We may see different behaviour in mpld3 vs d3 for the y axis, because we never
specified exactly how we want the y axis formatted. This is ok.
"""
from datetime import datetime
import matplotlib.pyplot as plt
import mpld3
def create_plot():
times = [datetime(2013, 12, i) for i in range(1, 20)]
ticks = [times[0], times[1], times[2], times[6], times[-2], times[-1]]
labels = [t.strftime("%Y-%m-%d") for t in ticks]
plt.plot_date(times, times, xdate=True, ydate=True)
plt.xticks(ticks, labels)
plt.yticks(ticks)
plt.xlim([times[1], times[-2]])
plt.ylim([times[1], times[-2]])
return plt.gcf()
def test_date():
fig = create_plot()
_ = mpld3.fig_to_html(fig)
plt.close(fig)
if __name__ == "__main__":
mpld3.show(create_plot(), template_type='simple')
| """Plot to test custom date axis tick locations and labels"""
from datetime import datetime
import matplotlib.pyplot as plt
import mpld3
def create_plot():
times = [datetime(2013, 12, i) for i in range(1, 20)]
ticks = [times[0], times[1], times[2], times[6], times[-2], times[-1]]
labels = [t.strftime("%Y-%m-%d") for t in ticks]
plt.plot_date(times, times, xdate=True, ydate=True)
plt.xticks(ticks, labels)
plt.yticks(ticks)
plt.xlim([times[1], times[-2]])
plt.ylim([times[1], times[-2]])
return plt.gcf()
def test_date():
fig = create_plot()
_ = mpld3.fig_to_html(fig)
plt.close(fig)
if __name__ == "__main__":
mpld3.show(create_plot(), template_type='simple')
|
Use the production backend in production | const _Environments = {
production: { API_URL: 'https://api.vets.gov', BASE_URL: 'https://www.vets.gov' },
staging: { API_URL: 'https://staging-api.vets.gov', BASE_URL: 'https://staging.vets.gov' },
development: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://dev.vets.gov' },
local: { API_URL: 'http://localhost:3000', BASE_URL: 'http://localhost:3001' },
e2e: { API_URL: 'http://localhost:4000', BASE_URL: 'http://localhost:3333' }
};
function getEnvironment() {
let platform;
if (location.host === 'localhost:3001') {
platform = 'local';
} else if (location.host === 'localhost:3333') {
platform = 'e2e';
} else {
platform = __BUILDTYPE__;
}
return _Environments[platform];
}
const environment = getEnvironment();
module.exports = environment;
| const _Environments = {
production: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://www.vets.gov' },
staging: { API_URL: 'https://staging-api.vets.gov', BASE_URL: 'https://staging.vets.gov' },
development: { API_URL: 'https://dev-api.vets.gov', BASE_URL: 'https://dev.vets.gov' },
local: { API_URL: 'http://localhost:3000', BASE_URL: 'http://localhost:3001' },
e2e: { API_URL: 'http://localhost:4000', BASE_URL: 'http://localhost:3333' }
};
function getEnvironment() {
let platform;
if (location.host === 'localhost:3001') {
platform = 'local';
} else if (location.host === 'localhost:3333') {
platform = 'e2e';
} else {
platform = __BUILDTYPE__;
}
return _Environments[platform];
}
const environment = getEnvironment();
module.exports = environment;
|
Use a rejection instead of throwing | // @flow
import deviceInfo from 'react-native-device-info'
import networkInfo from 'react-native-network-info'
import pkg from '../../../package.json'
export const getIpAddress = (): Promise<?string> =>
new Promise(resolve => {
try {
networkInfo.getIPAddress(resolve)
} catch (err) {
resolve(null)
}
})
export const getPosition = (): Promise<Object> =>
new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, err => reject(err))
})
export const collectData = async () => ({
id: deviceInfo.getUniqueID(),
brand: deviceInfo.getBrand(),
model: deviceInfo.getModel(),
deviceKind: deviceInfo.getDeviceId(),
os: deviceInfo.getSystemName(),
osVersion: deviceInfo.getSystemVersion(),
appVersion: deviceInfo.getReadableVersion(),
jsVersion: pkg.version,
ua: deviceInfo.getUserAgent(),
ip: await getIpAddress(),
dateRecorded: new Date().toJSON(),
})
export const reportToServer = (url: string, data: Object) =>
fetch(url, {method: 'POST', body: JSON.stringify(data)})
| // @flow
import deviceInfo from 'react-native-device-info'
import networkInfo from 'react-native-network-info'
import pkg from '../../../package.json'
export const getIpAddress = (): Promise<?string> =>
new Promise(resolve => {
try {
networkInfo.getIPAddress(resolve)
} catch (err) {
resolve(null)
}
})
export const getPosition = (): Promise<Object> =>
new Promise(resolve => {
navigator.geolocation.getCurrentPosition(resolve, err => { throw err })
})
export const collectData = async () => ({
id: deviceInfo.getUniqueID(),
brand: deviceInfo.getBrand(),
model: deviceInfo.getModel(),
deviceKind: deviceInfo.getDeviceId(),
os: deviceInfo.getSystemName(),
osVersion: deviceInfo.getSystemVersion(),
appVersion: deviceInfo.getReadableVersion(),
jsVersion: pkg.version,
ua: deviceInfo.getUserAgent(),
ip: await getIpAddress(),
dateRecorded: new Date().toJSON(),
})
export const reportToServer = (url: string, data: Object) =>
fetch(url, {method: 'POST', body: JSON.stringify(data)})
|
Allow API config to be specified in user configuration | import client from '@sanity/client-next'
import getUserConfig from './getUserConfig'
/**
* Creates a wrapper/getter function to retrieve a Sanity API client.
* Instead of spreading the error checking logic around the project,
* we call it here when (and only when) a command needs to use the API
*/
const defaults = {
requireUser: true,
requireProject: true
}
export default function clientWrapper(manifest, path) {
return function (opts = {}) {
const {requireUser, requireProject, api} = {...defaults, ...opts}
const userConfig = getUserConfig()
const userApiConf = userConfig.get('api')
const token = userConfig.get('authToken')
const apiConfig = api || (manifest && manifest.api) || userApiConf || {}
if (requireUser && !token) {
throw new Error('You must login first')
}
if (requireProject && !apiConfig.projectId) {
throw new Error(
`"${path}" does not contain a project identifier ("api.projectId"), `
+ 'which is required for the Sanity CLI to communicate with the Sanity API'
)
}
return client({
...apiConfig,
dataset: apiConfig.dataset || 'dummy',
token: token,
useProjectHostname: requireProject
})
}
}
| import client from '@sanity/client-next'
import getUserConfig from './getUserConfig'
/**
* Creates a wrapper/getter function to retrieve a Sanity API client.
* Instead of spreading the error checking logic around the project,
* we call it here when (and only when) a command needs to use the API
*/
const defaults = {
requireUser: true,
requireProject: true
}
export default function clientWrapper(manifest, path) {
return function (opts = {}) {
const {requireUser, requireProject, api} = {...defaults, ...opts}
const token = getUserConfig().get('authToken')
const apiConfig = api || (manifest && manifest.api) || {}
if (requireUser && !token) {
throw new Error('You must login first')
}
if (requireProject && !apiConfig.projectId) {
throw new Error(
`"${path}" does not contain a project identifier ("api.projectId"), `
+ 'which is required for the Sanity CLI to communicate with the Sanity API'
)
}
return client({
...apiConfig,
dataset: apiConfig.dataset || 'dummy',
token: token,
useProjectHostname: requireProject
})
}
}
|
Update namespaces for beta 8
Refs flarum/core#1235. | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Markdown\Listener;
use Flarum\Formatter\Event\Configuring;
use Illuminate\Contracts\Events\Dispatcher;
class FormatMarkdown
{
/**
* @param Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen(Configuring::class, [$this, 'addMarkdownFormatter']);
}
/**
* @param Configuring $event
*/
public function addMarkdownFormatter(Configuring $event)
{
$event->configurator->Litedown;
}
}
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Markdown\Listener;
use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;
class FormatMarkdown
{
/**
* @param Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen(ConfigureFormatter::class, [$this, 'addMarkdownFormatter']);
}
/**
* @param ConfigureFormatter $event
*/
public function addMarkdownFormatter(ConfigureFormatter $event)
{
$event->configurator->Litedown;
}
}
|
Create fullname user object locally in test | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import datetime
import pytest
from byceps.services.user.models.user import User as DbUser
from byceps.services.user.models.detail import UserDetail as DbUserDetail
@pytest.mark.parametrize(
'first_names, last_name, expected',
[
(None, None , None ),
('Giesbert Z.', None , 'Giesbert Z.' ),
(None, 'Blümli', 'Blümli' ),
('Giesbert Z.', 'Blümli', 'Giesbert Z. Blümli'),
],
)
def test_full_name(first_names, last_name, expected):
user = create_user(first_names, last_name)
assert user.detail.full_name == expected
def create_user(first_names: str, last_name: str) -> DbUser:
created_at = datetime.utcnow()
screen_name = 'Anyone'
email_address = 'anyone@example.test'
user = DbUser(created_at, screen_name, email_address)
detail = DbUserDetail(user=user)
detail.first_names = first_names
detail.last_name = last_name
return user
| """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from testfixtures.user import create_user_with_detail
@pytest.mark.parametrize(
'first_names, last_name, expected',
[
(None, None , None ),
('Giesbert Z.', None , 'Giesbert Z.' ),
(None, 'Blümli', 'Blümli' ),
('Giesbert Z.', 'Blümli', 'Giesbert Z. Blümli'),
],
)
def test_full_name(first_names, last_name, expected):
user = create_user_with_detail(first_names=first_names, last_name=last_name)
assert user.detail.full_name == expected
|
Use @Inject Controller instead of Context
OPEN - task 51: Create CRUD packages for Product entity
http://github.com/DevOpsDistilled/OpERP/issues/issue/51 | package devopsdistilled.operp.client.items.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.controllers.ProductController;
import devopsdistilled.operp.client.items.models.ProductModel;
import devopsdistilled.operp.client.items.panes.controllers.CreateProductPaneController;
import devopsdistilled.operp.server.data.entity.items.Product;
public class ProductControllerImpl implements ProductController {
@Inject
private ProductModel productModel;
@Inject
private CreateProductPaneController createProductPaneController;
@Override
public void create() {
createProductPaneController.init();
}
@Override
public void edit(Product product) {
// TODO Auto-generated method stub
}
@Override
public void list() {
// TODO Auto-generated method stub
}
@Override
public void delete(Product product) {
productModel.deleteAndUpdateModel(product);
}
}
| package devopsdistilled.operp.client.items.controllers.impl;
import javax.inject.Inject;
import org.springframework.context.ApplicationContext;
import devopsdistilled.operp.client.items.controllers.ProductController;
import devopsdistilled.operp.client.items.models.ProductModel;
import devopsdistilled.operp.client.items.panes.controllers.CreateProductPaneController;
import devopsdistilled.operp.server.data.entity.items.Product;
public class ProductControllerImpl implements ProductController {
@Inject
private ApplicationContext context;
@Inject
private ProductModel productModel;
@Override
public void create() {
CreateProductPaneController createProductPaneController = context
.getBean(CreateProductPaneController.class);
createProductPaneController.init();
}
@Override
public void edit(Product product) {
// TODO Auto-generated method stub
}
@Override
public void list() {
// TODO Auto-generated method stub
}
@Override
public void delete(Product product) {
productModel.deleteAndUpdateModel(product);
}
}
|
Remove OpenSSL from about dialog
it is implied by the Node version | const electron = require('electron')
const app = require('electron').app
const dialog = electron.dialog
const Channel = require('./channel')
const path = require('path')
module.exports.showAbout = function () {
dialog.showMessageBox({
title: 'Brave',
message: 'Brave: ' + app.getVersion() + '\n' +
'Electron: ' + process.versions['atom-shell'] + '\n' +
'libchromiumcontent: ' + process.versions['chrome'] + '\n' +
'V8: ' + process.versions.v8 + '\n' +
'Node.js: ' + process.versions.node + '\n' +
'Update channel: ' + Channel.channel(),
icon: path.join(__dirname, '..', 'app', 'img', 'braveAbout.png'),
buttons: ['Ok']
})
}
| const electron = require('electron')
const app = require('electron').app
const dialog = electron.dialog
const Channel = require('./channel')
const path = require('path')
module.exports.showAbout = function () {
dialog.showMessageBox({
title: 'Brave',
message: 'Brave: ' + app.getVersion() + '\n' +
'Electron: ' + process.versions['atom-shell'] + '\n' +
'libchromiumcontent: ' + process.versions['chrome'] + '\n' +
'V8: ' + process.versions.v8 + '\n' +
'Node.js: ' + process.versions.node + '\n' +
'OpenSSL: ' + process.versions.openssl + '\n' +
'Update channel: ' + Channel.channel(),
icon: path.join(__dirname, '..', 'app', 'img', 'braveAbout.png'),
buttons: ['Ok']
})
}
|
Add documentation to controller methods. | /*
* Copyright 2016, Frederik Boster
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.syquel.bushytail.controller;
import org.apache.olingo.server.api.uri.UriParameter;
import java.util.List;
/**
* Interface for all ODataControllers. Provides CRUD Operations.
*
* @author Clemens Bartz
* @author Frederik Boster
* @since 1.0
*
* @param <T> Entity which is handled by the controller.
*/
public interface IBushyTailController<T> {
/**
* Read an entity.
* @param keyPredicates the search criterias
* @return the entity
*/
T read(List<UriParameter> keyPredicates);
/**
* Create the entity.
* @param entity the entity
*/
void create(T entity);
}
| /*
* Copyright 2016, Frederik Boster
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.syquel.bushytail.controller;
import org.apache.olingo.server.api.uri.UriParameter;
import java.util.List;
/**
* Interface for all ODataControllers. Provides CRUD Operations.
*
* @author Clemens Bartz
* @author Frederik Boster
* @since 1.0
*
* @param <T> Entity which is handled by the controller.
*/
public interface IBushyTailController<T> {
T read(List<UriParameter> keyPredicates);
void create(T entity);
}
|
Add clarifying comment about Django setup | #!/usr/bin/env python
# Django must be set up before we import our libraries and run our tests
from django.conf import settings
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
},
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'localhost',
'OPTIONS': {
'MAX_ENTRIES': 2 ** 32,
},
},
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'ormcache',
'ormcache.tests.testapp',
),
TEST_RUNNER='django_nose.NoseTestSuiteRunner',
)
# Run tests
import sys
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=1)
test_runner.setup_databases()
failures = test_runner.run_tests(['ormcache', ])
if failures:
sys.exit(failures)
| #!/usr/bin/env python
# Setup Django
from django.conf import settings
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
},
},
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'localhost',
'OPTIONS': {
'MAX_ENTRIES': 2 ** 32,
},
},
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'ormcache',
'ormcache.tests.testapp',
),
TEST_RUNNER='django_nose.NoseTestSuiteRunner',
)
# Run tests
import sys
from django_nose import NoseTestSuiteRunner
test_runner = NoseTestSuiteRunner(verbosity=1)
test_runner.setup_databases()
failures = test_runner.run_tests(['ormcache', ])
if failures:
sys.exit(failures)
|
Allow Logger to be subclassed and modified more easily | import os
from .core import Agent
from .core import Proxy
from .core import BaseAgent
from .core import run_agent
def pyro_log():
os.environ["PYRO_LOGFILE"] = "pyro_osbrain.log"
os.environ["PYRO_LOGLEVEL"] = "DEBUG"
class Logger(BaseAgent):
def on_init(self):
self.log_history = []
handlers = {
'INFO': self.log_handler,
'ERROR': self.log_handler
}
self.bind('SUB', 'logger_sub_socket', handlers)
def log_handler(self, message, topic):
# TODO: handle INFO, ERROR... differently?
self.log_history.append(message)
def run_logger(name, nsaddr=None, addr=None, base=Logger):
"""
Ease the logger creation process.
This function will create a new logger, start the process and then run
its main loop through a proxy.
Parameters
----------
name : str
Logger name or alias.
nsaddr : SocketAddress, default is None
Name server address.
addr : SocketAddress, default is None
New logger address, if it is to be fixed.
Returns
-------
proxy
A proxy to the new logger.
"""
return run_agent(name, nsaddr, addr, base)
| import os
from .core import Agent
from .core import Proxy
def pyro_log():
os.environ["PYRO_LOGFILE"] = "pyro_osbrain.log"
os.environ["PYRO_LOGLEVEL"] = "DEBUG"
def log_handler(agent, message, topic):
# TODO: handle INFO, ERROR... differently?
agent.log_history.append(message)
def run_logger(name, nsaddr=None, addr=None):
"""
Ease the logger creation process.
This function will create a new logger, start the process and then run
its main loop through a proxy.
Parameters
----------
name : str
Logger name or alias.
nsaddr : SocketAddress, default is None
Name server address.
addr : SocketAddress, default is None
New logger address, if it is to be fixed.
Returns
-------
proxy
A proxy to the new logger.
"""
Agent(name, nsaddr, addr).start()
proxy = Proxy(name, nsaddr)
proxy.set_attr('log_history', [])
handlers = {
'INFO': log_handler,
'ERROR': log_handler
}
proxy.bind('SUB', 'logger_sub_socket', handlers)
proxy.run()
return proxy
|
Make Pholio mock image thumbnails publicly visible
Summary:
Refs T2652 - This should make all of Pholio mocks publicly visible
The rest that is to be done is more generic, like the ActionListView etc.
Test Plan: set mock to public, visited it in another browser without user session
Reviewers: epriestley, btrahan
Reviewed By: epriestley
CC: aran, Korvin
Maniphest Tasks: T2652
Differential Revision: https://secure.phabricator.com/D5454 | <?php
/**
* @group pholio
*/
final class PholioInlineThumbController extends PholioController {
private $imageid;
public function shouldAllowPublic() {
return true;
}
public function willProcessRequest(array $data) {
$this->imageid = idx($data, 'imageid');
}
public function processRequest() {
$request = $this->getRequest();
$user = $request->getUser();
$image = id(new PholioImage())->load($this->imageid);
if ($image == null) {
return new Aphront404Response();
}
$mock = id(new PholioMockQuery())
->setViewer($user)
->withIDs(array($image->getMockID()))
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$file = id(new PhabricatorFile())->loadOneWhere(
'phid = %s',
$image->getFilePHID());
return id(new AphrontRedirectResponse())->setURI($file->getThumb60x45URI());
}
}
| <?php
/**
* @group pholio
*/
final class PholioInlineThumbController extends PholioController {
private $imageid;
public function willProcessRequest(array $data) {
$this->imageid = idx($data, 'imageid');
}
public function processRequest() {
$request = $this->getRequest();
$user = $request->getUser();
$image = id(new PholioImage())->load($this->imageid);
if ($image == null) {
return new Aphront404Response();
}
$mock = id(new PholioMockQuery())
->setViewer($user)
->withIDs(array($image->getMockID()))
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$file = id(new PhabricatorFile())->loadOneWhere(
'phid = %s',
$image->getFilePHID());
return id(new AphrontRedirectResponse())->setURI($file->getThumb60x45URI());
}
}
|
Watch legacy includes directory as well | // Watch project files for and spawn associated tasks upon changes
module.exports = function(grunt) {
grunt.config('watch', {
options: {
spawn: false
},
// svg: {
// files: 'src/icons/*.svg',
// tasks: ['svgstore'],
// },
processhtml: {
files: ['src/pages/*.html', 'src/includes/*.html', 'src/includes/legacy/*.html'],
tasks: ['processhtml:dev'],
},
scss: {
files: 'src/scss/**/*.scss',
tasks: ['sass', 'postcss:build', 'bs-inject-css'],
},
js: {
files: 'src/scripts/main.js',
tasks: ['concat', 'bs-inject-js'],
}
});
};
| // Watch project files for and spawn associated tasks upon changes
module.exports = function(grunt) {
grunt.config('watch', {
options: {
spawn: false
},
// svg: {
// files: 'src/icons/*.svg',
// tasks: ['svgstore'],
// },
processhtml: {
files: ['src/pages/*.html', 'src/includes/*.html'],
tasks: ['processhtml:dev'],
},
scss: {
files: 'src/scss/**/*.scss',
tasks: ['sass', 'postcss:build', 'bs-inject-css'],
},
js: {
files: 'src/scripts/main.js',
tasks: ['concat', 'bs-inject-js'],
}
});
};
|
Check that export-contacts is included in the top-level command. | """ Tests for go_cli.main. """
from unittest import TestCase
from click.testing import CliRunner
from go_cli.main import cli
class TestCli(TestCase):
def test_help(self):
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
self.assertEqual(result.exit_code, 0)
self.assertTrue("Vumi Go command line utility." in result.output)
self.assertTrue(
"export-contacts Export contacts from the contacts API."
in result.output)
self.assertTrue(
"send Send messages via an HTTP API (nostream)..."
in result.output)
def test_version(self):
runner = CliRunner()
result = runner.invoke(cli, ['--version'])
self.assertEqual(result.exit_code, 0)
self.assertTrue("go-cli, version " in result.output)
| """ Tests for go_cli.main. """
from unittest import TestCase
from click.testing import CliRunner
from go_cli.main import cli
class TestCli(TestCase):
def test_help(self):
runner = CliRunner()
result = runner.invoke(cli, ['--help'])
self.assertEqual(result.exit_code, 0)
self.assertTrue("Vumi Go command line utility." in result.output)
self.assertTrue("send Send messages via an HTTP API (nostream)..."
in result.output)
def test_version(self):
runner = CliRunner()
result = runner.invoke(cli, ['--version'])
self.assertEqual(result.exit_code, 0)
self.assertTrue("go-cli, version " in result.output)
|
Call Resource constructor from Validator, fixing a Girder warning | from girder.api import access
from girder.api.rest import Resource
from girder.api.describe import Description
class Validator(Resource):
def __init__(self, celeryApp):
super(Validator, self).__init__()
self.resourceName = 'romanesco_validator'
self.route('GET', (), self.find)
self.celeryApp = celeryApp
@access.public
def find(self, params):
return self.celeryApp.send_task('romanesco.validators', [
params.get('type', None),
params.get('format', None)]).get()
find.description = (
Description('List or search for validators.')
.param('type', 'Find validators with this type.', required=False)
.param('format', 'Find validators with this format.', required=False)
)
| from girder.api import access
from girder.api.rest import Resource
from girder.api.describe import Description
class Validator(Resource):
def __init__(self, celeryApp):
self.resourceName = 'romanesco_validator'
self.route('GET', (), self.find)
self.celeryApp = celeryApp
@access.public
def find(self, params):
return self.celeryApp.send_task('romanesco.validators', [
params.get('type', None),
params.get('format', None)]).get()
find.description = (
Description('List or search for validators.')
.param('type', 'Find validators with this type.', required=False)
.param('format', 'Find validators with this format.', required=False)
)
|
Allow log-in for people who don+t have pension account
Enable DTO debug | package ee.tuleva.onboarding.account;
import ee.tuleva.onboarding.auth.principal.Person;
import ee.tuleva.onboarding.epis.EpisService;
import ee.tuleva.onboarding.epis.account.FundBalanceDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Service
@Slf4j
@RequiredArgsConstructor
public class AccountStatementService {
private final EpisService episService;
private final FundBalanceDtoToFundBalanceConverter fundBalanceConverter;
public List<FundBalance> getAccountStatement(Person person) {
List<FundBalanceDto> accountStatement = episService.getAccountStatement(person);
return accountStatement.stream()
.map(fundBalanceDto -> convertToFundBalance(fundBalanceDto, person))
.collect(toList());
}
private FundBalance convertToFundBalance(FundBalanceDto fundBalanceDto, Person person) {
try {
if (log.isDebugEnabled()) {
log.debug("Fund Balance DTO: {}", fundBalanceDto);
}
return fundBalanceConverter.convert(fundBalanceDto);
} catch(IllegalArgumentException e) {
throw new IllegalStateException("Could not convert fund balance for person " + person, e);
}
}
}
| package ee.tuleva.onboarding.account;
import ee.tuleva.onboarding.auth.principal.Person;
import ee.tuleva.onboarding.epis.EpisService;
import ee.tuleva.onboarding.epis.account.FundBalanceDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Service
@Slf4j
@RequiredArgsConstructor
public class AccountStatementService {
private final EpisService episService;
private final FundBalanceDtoToFundBalanceConverter fundBalanceConverter;
public List<FundBalance> getAccountStatement(Person person) {
List<FundBalanceDto> accountStatement = episService.getAccountStatement(person);
return accountStatement.stream()
.map(fundBalanceDto -> convertToFundBalance(fundBalanceDto, person))
.collect(toList());
}
private FundBalance convertToFundBalance(FundBalanceDto fundBalanceDto, Person person) {
try {
if (log.isDebugEnabled()) {
log.debug("Fund Balance DTO:" + fundBalanceDto);
}
return fundBalanceConverter.convert(fundBalanceDto);
} catch(IllegalArgumentException e) {
throw new IllegalStateException("Could not convert fund balance for person " + person, e);
}
}
}
|
Update spacing when importing components. | import {
Forms,
Select,
Dropdown,
Modal,
Datepicker,
Timepicker
} from 'materialize-css';
document.addEventListener('DOMContentLoaded', function() {
// Init select box
const selects = document.querySelectorAll('select');
const selectInstances = M.FormSelect.init(selects, {});
// Init datepicker
// The format has been set up following Drupal time field standards.
// TODO: Create a fallback which takes the value from the field data attrs.
const datepickers = document.querySelectorAll('.datepicker');
const datepikerInstances = M.Datepicker.init(datepickers, {'format': 'yyyy-m-d'});
// Init timepicker
// Twelve hours type isn't supported by Drupal..
// TODO: Create a fallback function that convert the value to requirements.
const timepickers = document.querySelectorAll('.timepicker');
const timepickerInstances = M.Timepicker.init(timepickers, {'twelveHour': false});
});
| import {
Forms,
Select,
Dropdown,
Modal,
Datepicker,
Timepicker
} from 'materialize-css';
document.addEventListener('DOMContentLoaded', function() {
// Init select box
const selects = document.querySelectorAll('select');
const selectInstances = M.FormSelect.init(selects, {});
// Init datepicker
// The format has been set up following Drupal time field standards.
// TODO: Create a fallback which takes the value from the field data attrs.
const datepickers = document.querySelectorAll('.datepicker');
const datepikerInstances = M.Datepicker.init(datepickers, {'format': 'yyyy-m-d'});
// Init timepicker
// Twelve hours type isn't supported by Drupal..
// TODO: Create a fallback function that convert the value to requirements.
const timepickers = document.querySelectorAll('.timepicker');
const timepickerInstances = M.Timepicker.init(timepickers, {'twelveHour': false});
});
|
Remove an extraneous comma in ReviewReplyModel.
This comma would break certain browsers. | /*
* Review replies.
*
* Encapsulates replies to a top-level review.
*/
RB.ReviewReply = RB.BaseResource.extend({
defaults: _.defaults({
review: null,
public: false,
bodyTop: null,
bodyBottom: null
}, RB.BaseResource.prototype.defaults),
rspNamespace: 'reply',
listKey: 'replies',
toJSON: function() {
return {
'public': this.get('public'),
'body_top': this.get('bodyTop'),
'body_bottom': this.get('bodyBottom')
};
},
parse: function(rsp) {
var result = RB.BaseResource.prototype.parse.call(this, rsp),
rspData = rsp[this.rspNamespace];
result.bodyTop = rspData.body_top;
result.bodyBottom = rspData.body_bottom;
result.public = rspData.public;
return result;
}
});
| /*
* Review replies.
*
* Encapsulates replies to a top-level review.
*/
RB.ReviewReply = RB.BaseResource.extend({
defaults: _.defaults({
review: null,
public: false,
bodyTop: null,
bodyBottom: null
}, RB.BaseResource.prototype.defaults),
rspNamespace: 'reply',
listKey: 'replies',
toJSON: function() {
return {
'public': this.get('public'),
'body_top': this.get('bodyTop'),
'body_bottom': this.get('bodyBottom')
};
},
parse: function(rsp) {
var result = RB.BaseResource.prototype.parse.call(this, rsp),
rspData = rsp[this.rspNamespace];
result.bodyTop = rspData.body_top;
result.bodyBottom = rspData.body_bottom;
result.public = rspData.public;
return result;
},
});
|
tests: Disable some PHP insights sniffs | <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
| to make your code reliable, simple, and clean. However, you can always
| adjust the `Metrics` and `Insights` below in this configuration file.
|
| Supported: "default", "laravel", "symfony"
|
*/
'preset' => 'symfony',
/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
|
| Here you may adjust all the various `Insights` that will be used by PHP
| Insights. You can either add, remove or configure `Insights`. Keep in
| mind, that all added `Insights` must belong to a specific `Metric`.
|
*/
'add' => [
// ExampleMetric::class => [
// ExampleInsight::class,
// ]
],
'remove' => [
// ExampleInsight::class,
ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
],
'config' => [
// ExampleInsight::class => [
// 'key' => 'value',
// ],
],
];
| <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
| to make your code reliable, simple, and clean. However, you can always
| adjust the `Metrics` and `Insights` below in this configuration file.
|
| Supported: "default", "laravel", "symfony"
|
*/
'preset' => 'symfony',
/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
|
| Here you may adjust all the various `Insights` that will be used by PHP
| Insights. You can either add, remove or configure `Insights`. Keep in
| mind, that all added `Insights` must belong to a specific `Metric`.
|
*/
'add' => [
// ExampleMetric::class => [
// ExampleInsight::class,
// ]
],
'remove' => [
// ExampleInsight::class,
],
'config' => [
// ExampleInsight::class => [
// 'key' => 'value',
// ],
],
];
|
Include all but have a supported set
Rather than commenting out the values, this seems more sensible. And pretty.. of
course.
Signed-off-by: Venkatesh Shukla <8349e50bec2939976da648e286d7e261bcd17fa3@iitbhu.ac.in> | class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
BLOGS = 'blogs'
CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
READERS_ED = 'Readers-Editor'
SUNDAY_ANCHOR = 'sunday-anchor'
SUPPORTED = [COLUMNS, EDITORIAL, INTERVIEW, LEAD, OP_ED,
OPEN_PAGE]
class Tags:
accepted = ['a', 'b', 'i', 'p']
| class AppUrl:
"""Class for storing all the URLs used in the application"""
BASE = "http://www.thehindu.com/"
OP_BASE = BASE + "opinion/"
OPINION = OP_BASE + "?service=rss"
EDITORIAL = OP_BASE + "editorial/?service=rss"
SAMPLE = BASE + "op-ed/a-super-visit-in-the-season-of-hope/article7214799.ece"
RSS_ARGS = "?utm_source=RSS_Feed&utm_medium=RSS&utm_campaign=RSS_Syndication"
class Kind:
#BLOGS = 'blogs'
#CARTOON = 'cartoon'
COLUMNS = 'columns'
EDITORIAL = 'editorial'
INTERVIEW = 'interview'
LEAD = 'lead'
#LETTERS = 'letters'
OP_ED = 'op-ed'
OPEN_PAGE = 'open-page'
#READERS_ED = 'Readers-Editor'
#SUNDAY_ANCHOR = 'sunday-anchor'
class Tags:
accepted = ['a', 'b', 'i', 'p']
|
Put remove to the first column and changed the text for adding a url | <html>
<body>
<?php
require 'includes/url-list.inc';
$file = $_SERVER["DOCUMENT_ROOT"] . "/kiosk/sites";
$file_list = get_url_list($file);
$list_count = count($file_list);
$url = $urlError = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["urlError"])) {
$urlError = $_POST["urlError"];
$url = $_POST["url"];
}
}
?>
<?php if ($list_count > 0): ?>
<table>
<tbody>
<?php foreach ($file_list as $item): ?>
<tr>
<td><a href="pages/delete-from-url-list.php?hash=<?php echo hash("sha256",trim($item)); ?>">remove</a>
<td><?php echo $item; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<br>
<form method="post" action="pages/url-list.php">
Add URL:
<input type="text" name="url" value="<?php echo $url;?>">
<span class="error"><?php echo $urlError;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php //echo shell_exec('killall chromium-browser'); ?>
</body>
</html>
| <html>
<body>
<?php
require 'includes/url-list.inc';
$file = $_SERVER["DOCUMENT_ROOT"] . "/kiosk/sites";
$file_list = get_url_list($file);
$list_count = count($file_list);
$url = $urlError = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["urlError"])) {
$urlError = $_POST["urlError"];
$url = $_POST["url"];
}
}
?>
<?php if ($list_count > 0): ?>
<table>
<tbody>
<?php foreach ($file_list as $item): ?>
<tr>
<td><?php echo $item; ?></td>
<td><a href="pages/delete-from-url-list.php?hash=<?php echo hash("sha256",trim($item)); ?>">remove</a>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<br>
<form method="post" action="pages/url-list.php">
URL:
<input type="text" name="url" value="<?php echo $url;?>">
<span class="error"><?php echo $urlError;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php //echo shell_exec('killall chromium-browser'); ?>
</body>
</html>
|
Fix one more place where STAGING_HOSTNAME uses settings | import os
from django import template
from wagtail.wagtailcore.models import Page
register = template.Library()
@register.filter
def is_shared(page):
page = page.specific
if isinstance(page, Page):
if page.shared:
return True
else:
return False
@register.assignment_tag(takes_context=True)
def staging_url(context, page):
url = page.url
if os.environ.get('STAGING_HOSTNAME') not in page.url:
url = url.replace(context['request'].site.hostname,
os.environ.get('STAGING_HOSTNAME'))
return url
@register.assignment_tag(takes_context=True)
def v1page_permissions(context, page):
page = page.specific
return page.permissions_for_user(context['request'].user)
| import os
from django import template
from wagtail.wagtailcore.models import Page
from django.conf import settings
register = template.Library()
@register.filter
def is_shared(page):
page = page.specific
if isinstance(page, Page):
if page.shared:
return True
else:
return False
@register.assignment_tag(takes_context=True)
def staging_url(context, page):
url = page.url
if settings.STAGING_HOSTNAME not in page.url:
url = url.replace(context['request'].site.hostname,
os.environ.get('STAGING_HOSTNAME'))
return url
@register.assignment_tag(takes_context=True)
def v1page_permissions(context, page):
page = page.specific
return page.permissions_for_user(context['request'].user)
|
Update unit test for changes to topf | """Test functions for util.mrbump_util"""
import cPickle
import os
import unittest
from ample.constants import AMPLE_PKL, SHARE_DIR
from ample.util import mrbump_util
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.thisd = os.path.abspath( os.path.dirname( __file__ ) )
cls.ample_share = SHARE_DIR
cls.testfiles_dir = os.path.join(cls.ample_share,'testfiles')
def test_final_summary(self):
pkl = os.path.join(self.testfiles_dir, AMPLE_PKL)
if not os.path.isfile(pkl): return
with open(pkl) as f: d = cPickle.load(f)
summary = mrbump_util.finalSummary(d)
self.assertIsNotNone(summary)
def test_topfiles(self):
topf = mrbump_util.ResultsSummary(results_pkl=os.path.join(self.testfiles_dir, AMPLE_PKL)).topFiles()
self.assertEqual(len(topf),3)
self.assertEqual(topf[2]['source'],'SHELXE trace of MR result')
if __name__ == "__main__":
unittest.main()
| """Test functions for util.mrbump_util"""
import cPickle
import os
import unittest
from ample.constants import AMPLE_PKL, SHARE_DIR
from ample.util import mrbump_util
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.thisd = os.path.abspath( os.path.dirname( __file__ ) )
cls.ample_share = SHARE_DIR
cls.testfiles_dir = os.path.join(cls.ample_share,'testfiles')
def test_final_summary(self):
pkl = os.path.join(self.testfiles_dir, AMPLE_PKL)
if not os.path.isfile(pkl): return
with open(pkl) as f: d = cPickle.load(f)
summary = mrbump_util.finalSummary(d)
self.assertIsNotNone(summary)
def test_topfiles(self):
topf = mrbump_util.ResultsSummary(results_pkl=os.path.join(self.testfiles_dir, AMPLE_PKL)).topFiles()
self.assertEqual(len(topf),3)
self.assertIn('info',topf[2])
if __name__ == "__main__":
unittest.main()
|
Add a note concerning FEINCMS_USE_PAGE_ADMIN | # ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
# XXX move this setting to feincms.settings?
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
| # ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
from __future__ import absolute_import
from django.conf import settings
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from feincms import ensure_completely_loaded
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
if getattr(settings, 'FEINCMS_USE_PAGE_ADMIN', True):
ensure_completely_loaded()
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
"The page module requires a 'Page.register_templates()' call "
"somewhere ('Page.register_regions()' is not sufficient). "
"If you're not using the default Page admin, maybe try "
"FEINCMS_USE_PAGE_ADMIN=False to avoid this warning."
)
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
|
Update +l with new checkSet parameter | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "LimitMode"
core = True
affectedActions = [ "joinpermission" ]
def hookIRCd(self, ircd):
self.ircd = ircd
def channelModes(self):
return [ ("l", ModeType.Param, self) ]
def actions(self):
return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]
def isModeSet(self, channel, alsoChannel, user):
if "l" in channel.modes:
return channel.modes["l"]
return None
def checkSet(self, channel, param):
try:
return [ int(param) ]
except ValueError:
return None
def apply(self, actionType, channel, param, alsoChannel, user):
if len(channel.users) >= param:
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
return False
return None
limitMode = LimitMode() | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "LimitMode"
core = True
affectedActions = [ "joinpermission" ]
def hookIRCd(self, ircd):
self.ircd = ircd
def channelModes(self):
return [ ("l", ModeType.Param, self) ]
def actions(self):
return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]
def isModeSet(self, channel, alsoChannel, user):
if "l" in channel.modes:
return channel.modes["l"]
return None
def checkSet(self, param):
try:
return [ int(param) ]
except ValueError:
return None
def apply(self, actionType, channel, param, alsoChannel, user):
if len(channel.users) >= param:
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
return False
return None
limitMode = LimitMode() |
Expand path for other folder structures. | #MenuTitle: Run preglyphs
# -*- coding: utf-8 -*-
__doc__="""
Runs preglyphs from your chosen project folder then open the generated file
"""
__copyright__ = 'Copyright (c) 2019, SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
__author__ = 'Nicolas Spalinger'
import GlyphsApp
from subprocess import Popen, PIPE
def runAppleScript(scpt, args=[]):
p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
if stderr:
print "AppleScript Error:"
print stderr.decode('utf-8')
return stdout
runpreglyphs = """
tell application "Finder"
activate
set frontmost to true
set projectRoot to quoted form of POSIX path of (choose folder with prompt "Please select the project folder root, e.g. font-gentium")
set sourcefolder to projectRoot & "source/"
tell application "Terminal"
activate
tell window 1
do script "cd " & projectRoot & "; ./preglyphs"
delay 25
do script "cd " & sourcefolder & "; open *.glyphs masters/*.glyphs"
tell window 1 to quit
end tell
end tell
end tell
"""
save = runAppleScript( runpreglyphs )
| #MenuTitle: Run preglyphs
# -*- coding: utf-8 -*-
__doc__="""
Runs preglyphs from your chosen project folder then open the generated file
"""
__copyright__ = 'Copyright (c) 2019, SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
__author__ = 'Nicolas Spalinger'
import GlyphsApp
from subprocess import Popen, PIPE
def runAppleScript(scpt, args=[]):
p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
if stderr:
print "AppleScript Error:"
print stderr.decode('utf-8')
return stdout
runpreglyphs = """
tell application "Finder"
activate
set frontmost to true
set projectRoot to quoted form of POSIX path of (choose folder with prompt "Please select the project folder root, e.g. font-gentium")
set sourcefolder to projectRoot & "source/"
tell application "Terminal"
activate
tell window 1
do script "cd " & projectRoot & "; ./preglyphs"
delay 25
do script "cd " & sourcefolder & "; open *.glyphs"
tell window 1 to quit
end tell
end tell
end tell
"""
save = runAppleScript( runpreglyphs )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.