hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
5b51dedd34cb8d5a923c57028ef12b4ab6d38ad2
diff --git a/lib/david/server/mapping.rb b/lib/david/server/mapping.rb index <HASH>..<HASH> 100644 --- a/lib/david/server/mapping.rb +++ b/lib/david/server/mapping.rb @@ -3,6 +3,23 @@ module David module Mapping include Constants + HTTP_TO_COAP_CODES = { + 200 => 205, + 202 => 201, + 203 => 205, + 204 => 205, + 407 => 401, + 408 => 400, + 409 => 412, + 410 => 404, + 411 => 402, + 414 => 402, + 505 => 500, + 506 => 500, + 506 => 500, + 511 => 500, + }.freeze + protected def accept_to_http(request) @@ -19,9 +36,7 @@ module David def code_to_coap(code) code = code.to_i - - h = {200 => 205} - code = h[code] if h[code] + code = HTTP_TO_COAP_CODES[code] if HTTP_TO_COAP_CODES[code] a = code / 100 b = code - (a * 100)
HTTP to CoAP response code mappings.
nning_david
train
a62b2418facc60115dae4d388888c49f4ec50122
diff --git a/src/Jaspersoft/Service/OrganizationService.php b/src/Jaspersoft/Service/OrganizationService.php index <HASH>..<HASH> 100644 --- a/src/Jaspersoft/Service/OrganizationService.php +++ b/src/Jaspersoft/Service/OrganizationService.php @@ -154,23 +154,17 @@ class OrganizationService extends JRSService { $result = array(); $url = self::makeAttributeUrl($organization->id, $attributeNames); - $data = $this->service->prepAndSend($url, array(200, 204), 'GET', null, true, 'application/json', 'application/json'); - - if(!empty($data)) { - $json = json_decode($data); - } else { + $data = $this->service->prepAndSend($url, array(200), 'GET', null, true); + $jsonObj = json_decode($data); + if (!empty($jsonObj)) { + $result = array(); + foreach ($jsonObj->attribute as $attr) { + $result[] = Attribute::createFromJSON($attr); + } return $result; + } else { + return array(); } - - foreach($json->attribute as $element) { - // Secure attributes will not have a value, and must be set to null otherwise - $element->value = (empty($element->value)) ? null : $element->value; - $tempAttribute = new Attribute( - $element->name, - $element->value); - $result[] = $tempAttribute; - } - return $result; } /** diff --git a/src/Jaspersoft/Service/UserService.php b/src/Jaspersoft/Service/UserService.php index <HASH>..<HASH> 100644 --- a/src/Jaspersoft/Service/UserService.php +++ b/src/Jaspersoft/Service/UserService.php @@ -171,25 +171,18 @@ class UserService extends JRSService */ public function getAttributes(User $user, $attributeNames = null) { - $result = array(); $url = self::makeAttributeUrl($user->username, $user->tenantId, $attributeNames); - $data = $this->service->prepAndSend($url, array(200, 204), 'GET', null, true, 'application/json', 'application/json'); - - if(!empty($data)) { - $json = json_decode($data); - } else { + $data = $this->service->prepAndSend($url, array(200), 'GET', null, true); + $jsonObj = json_decode($data); + if (!empty($jsonObj)) { + $result = array(); + foreach ($jsonObj->attribute as $attr) { + $result[] = Attribute::createFromJSON($attr); + } return $result; + } else { + return array(); } - - foreach($json->attribute as $element) { - // Secure attributes will not have a value, and must be set to null otherwise - $element->value = (empty($element->value)) ? null : $element->value; - $tempAttribute = new Attribute( - $element->name, - $element->value); - $result[] = $tempAttribute; - } - return $result; } /**
Use createFromJSON for attribute creation instead of simple instantiation to avoid retrieving properties which may not exist in a response
Jaspersoft_jrs-rest-php-client
train
d5d84fdd1479a80ccf2b65c425789d898e0a01f2
diff --git a/bin/yay b/bin/yay index <HASH>..<HASH> 100755 --- a/bin/yay +++ b/bin/yay @@ -28,7 +28,7 @@ try { if ($source === false) throw new InvalidArgumentException("File '{$file}' not found'."); - file_put_contents('php://stdout', yay_parse($source, $file)); + file_put_contents('php://stdout', yay_parse($source)); } catch (Exception $e) { file_put_contents('php://stderr', $e . PHP_EOL); diff --git a/src/Cycle.php b/src/Cycle.php index <HASH>..<HASH> 100644 --- a/src/Cycle.php +++ b/src/Cycle.php @@ -9,16 +9,13 @@ use class Cycle { protected - $id = 0, - $salt = '' + $id = 0 ; - function __construct(string $salt) { $this->salt = $salt; } - function next() /*: void */ { $this->id++; } /** * Not security related, just making scope id not humanely predictable. */ - function id() : string { return md5($this->salt . $this->id); } + function id() : string { return md5((string) $this->id); } } diff --git a/src/StreamWrapper.php b/src/StreamWrapper.php index <HASH>..<HASH> 100644 --- a/src/StreamWrapper.php +++ b/src/StreamWrapper.php @@ -86,7 +86,7 @@ final class StreamWrapper { function stream_read($lengh) : string { return ! $this->file->eof() - ? yay_parse($this->file->fread($lengh), $this->file->getPath()) + ? yay_parse($this->file->fread($lengh)) : '' ; } diff --git a/tests/SpecsTest.php b/tests/SpecsTest.php index <HASH>..<HASH> 100644 --- a/tests/SpecsTest.php +++ b/tests/SpecsTest.php @@ -3,6 +3,7 @@ namespace Yay; use + Exception, RecursiveDirectoryIterator, RecursiveIteratorIterator, RegexIterator, @@ -100,11 +101,11 @@ class Test { list($this->name, $this->source, $this->expected) = $sections; try { - $this->out = yay_parse($this->source, ''); + $this->out = yay_parse($this->source); } catch(YayParseError $e) { $this->out = $e->getMessage(); // $this->out = (string) $e; - } catch(\Exception $e) { + } catch(Exception $e) { $this->out = $e->getMessage(); } @@ -112,7 +113,7 @@ class Test { Assert::assertStringMatchesFormat($this->expected, $this->out); $this->status = self::PASSED; } - catch(\Exception $e) { + catch(Exception $e) { $this->status = self::FAILED; throw $e; diff --git a/yay_parse.php b/yay_parse.php index <HASH>..<HASH> 100644 --- a/yay_parse.php +++ b/yay_parse.php @@ -3,13 +3,13 @@ use Yay\{ Token, TokenStream, Directives, Macro, Expected, Error, Cycle }; use Yay\{ const LAYER_DELIMITERS }; -function yay_parse(string $source, string $salt) : string { +function yay_parse(string $source) : string { start: if ($gc = gc_enabled()) gc_disable(); $ts = TokenStream::fromSource($source); $directives = new Directives; - $cycle = new Cycle($salt); + $cycle = new Cycle($source); $halt = function(Token ...$expected) use ($ts) { (new Error(new Expected(...$expected), $ts->current(), $ts->last()))->halt(); };
remove salt from Cycle as macro hygienization will be properly implemented soon
marcioAlmada_yay
train
18abce6529f5fe31f3184a506304acad97e54efa
diff --git a/sxxexx/sxxexx.py b/sxxexx/sxxexx.py index <HASH>..<HASH> 100644 --- a/sxxexx/sxxexx.py +++ b/sxxexx/sxxexx.py @@ -57,7 +57,6 @@ import logging import re -from getpass import getpass import t411 @@ -182,13 +181,13 @@ class series_t411(object): logging.info("%s torrent(s) found" % len(self.list)) - def downloadbest(self, dir_download=None): + def downloadbest(self): best = self.getbest() if best is not None: #use title of torrent as filename. Will be saved as 'filename' + '.torrent' - self.source.download(best[2], filename=best[0], directory=dir_download) + self.source.download(best[2], filename=best[0], directory=self.dir_download) else: - logging.error("Can't download because no torrent was found.") + logging.error("Can't download because no torrent was found for this search.") def __readsource__(self): """ @@ -649,7 +648,6 @@ def main(): else: print("Transmission start downloading...") else: - print("Downloading torrent %s" % best[2]) serie.downloadbest() # End of the game diff --git a/sxxexx/t411.py b/sxxexx/t411.py index <HASH>..<HASH> 100644 --- a/sxxexx/t411.py +++ b/sxxexx/t411.py @@ -15,6 +15,7 @@ from json import loads, dumps import requests from urllib2 import urlopen, URLError, HTTPError, Request import os +import logging HTTP_OK = 200 @@ -40,10 +41,11 @@ class T411(object): if 'uid' not in self.user_credentials or 'token' not in \ self.user_credentials: + logging.error('Wrong data found in user file: %s' % USER_CREDENTIALS_FILE) raise T411Exception('Wrong data found in user file') else: # nothing todo : we got credentials from file - print("Using credentials from user file: %s" %USER_CREDENTIALS_FILE) + logging.info('Using credentials from user file: %s' %USER_CREDENTIALS_FILE) except IOError as e: # we have to ask the user for its credentials and get # the token from the API @@ -53,12 +55,13 @@ class T411(object): try: self._auth(user, password) except T411Exception as e: - print('Error while trying identification as %s: %s' %(user, e.message)) + logging.error('Error while trying identification as %s: %s' %(user, e.message)) else: break except T411Exception as e: raise T411Exception(e.message) except Exception as e: + logging.error('Error while reading user credentials: %s.'% e.message) raise T411Exception('Error while reading user credentials: %s.'\ % e.message) @@ -78,26 +81,51 @@ class T411(object): def call(self, method = '', params = None) : """ Call T411 API """ - + # authentification request if method == 'auth' : req = requests.post(API_URL % method, data=params) + + # download torrent request elif 'download' in method: + torrentid = os.path.basename(method) + + # build torrent's filename if 'directory' in params and params['directory'] is not None: torrentfile = os.path.join(params['directory'], params['filename'] + '.torrent') else: torrentfile = params['filename'] + '.torrent' - print("Downloading torrent %s to file : %s" %(os.path.basename(method), torrentfile)) - - with open(torrentfile, 'wb') as handle: - req = requests.get(API_URL % method, headers={'Authorization': '%s' %self.user_credentials['token']}) - for block in req.iter_content(1024): - if not block: - break - handle.write(block) - return + logging.info("Downloading torrent %s to file : %s" %(torrentid, torrentfile)) + try: + with open(torrentfile, 'wb') as handle: + req = requests.get(API_URL % method, + headers={'Authorization': '%s' %self.user_credentials['token']}) + + if req.status_code == requests.codes.OK: + try: + req_json = req.json() + if 'error' in req_json: + logging.error('Got an error response from t411 server: %s' %req_json['error']) + except ValueError: + # unable to jsonify it, we considere response is the torrent file. + # just download it + for block in req.iter_content(1024): + if not block: + break + handle.write(block) + + print("Download success. Torrent file saved to '%s'" % torrentfile) + return + else: + logging.error('Invalid response status_code : %s' (req.status_code)) + except Exception as e: + logging.error('Download of torrent %s failed : %s' %(torrentid, e.message)) + raise T411Exception(e.message) + + # other type requests : include Authorizaton credentials to the request else: - req = requests.post(API_URL % method, data=params, headers={'Authorization': self.user_credentials['token']} ) + req = requests.post(API_URL % method, data=params, + headers={'Authorization': self.user_credentials['token']} ) if req.status_code == requests.codes.OK: return req.json()
patch bug when torrent is not found on server
nicolargo_sxxexx
train
d4feff676afe74b6aed08670aa0e030ca4e1cdcf
diff --git a/nodes/http-auth.js b/nodes/http-auth.js index <HASH>..<HASH> 100644 --- a/nodes/http-auth.js +++ b/nodes/http-auth.js @@ -106,12 +106,14 @@ function digestSession(realm) { } function unAuth(node, msg, stale) { + var res = msg.res._res || msg.res; // Resolves deprecates warning messages. + switch (node.httpauthconf.authType) { case "Digest": var session = digestSession(node.httpauthconf.realm); sessions[session.nonce + session.opaque] = session; - msg.res.set("WWW-Authenticate", + res.set("WWW-Authenticate", 'Digest realm="' + session.realm + '"' + ', nonce="' + session.nonce + '"' + ', opaque="' + session.opaque + '"' @@ -120,11 +122,11 @@ function unAuth(node, msg, stale) { + (stale ? ', stale="true"' : '') ); break; - case "Basic": default: msg.res.set("WWW-Authenticate", 'Basic realm="' + node.httpauthconf.realm + '"'); + case "Basic": default: res.set("WWW-Authenticate", 'Basic realm="' + node.httpauthconf.realm + '"'); } - msg.res.type("text/plain"); - msg.res.status(401).send("401 Unauthorized"); + res.type("text/plain"); + res.status(401).send("401 Unauthorized"); } module.exports = function(RED) {
Fixed issue with "deprecated" methods. Warnings no longer show. Changes to be committed: modified: nodes/http-auth.js
endemecio02_node-red-contrib-httpauth
train
e8501135b80fe78015f837b8700ae5fe8e9b1bd3
diff --git a/py3status/modules/weather_yahoo.py b/py3status/modules/weather_yahoo.py index <HASH>..<HASH> 100644 --- a/py3status/modules/weather_yahoo.py +++ b/py3status/modules/weather_yahoo.py @@ -17,7 +17,9 @@ Configuration parameters: - forecast_days : how many forecast days you want shown - forecast_format : possible placeholders: {icon}, {low}, {high}, {units}, {text} - - forecast_include_today: show today forecast as well, default false + - forecast_include_today: show today's forecast, default false. Note that + `{today}` in `format` shows the current conditions, while this variable + shows today's forecast. - forecast_text_separator : separator between forecast entries, default ' ' - format : uses 2 placeholders: - {today} : text generated by `today_format`
Update forecast_include_today description
ultrabug_py3status
train
85d78298ab0c464d3b579f60f985f89e391d4a7f
diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php index <HASH>..<HASH> 100644 --- a/lib/SimpleSAML/Utilities.php +++ b/lib/SimpleSAML/Utilities.php @@ -474,6 +474,10 @@ class SimpleSAML_Utilities { /* Set the location header. */ header('Location: ' . $url, TRUE, $code); + /* Disable caching of this response. */ + header('Pragma: no-cache'); + header('Cache-Control: no-cache, must-revalidate'); + /* Show a minimal web page with a clickable link to the URL. */ echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n"; echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' .
Disable caching of redirect responses.
simplesamlphp_saml2
train
9915bb873c653e1bc74f21ddbbbd8a0818087782
diff --git a/src/ol/feature.js b/src/ol/feature.js index <HASH>..<HASH> 100644 --- a/src/ol/feature.js +++ b/src/ol/feature.js @@ -21,6 +21,8 @@ goog.require('ol.style.Style'); * attribute properties, similar to the features in vector file formats like * GeoJSON. * Features can be styled individually or use the style of their vector layer. + * Note that attribute properties are set as {@link ol.Object} properties on the + * feature object, so they are observable, and have get/set accessors. * * @constructor * @extends {ol.Object}
Document that feature properties are set as object properties
openlayers_openlayers
train
5605a637c167fe67bb113ee52e5907dc60f1895a
diff --git a/lib/shared/utils.js b/lib/shared/utils.js index <HASH>..<HASH> 100644 --- a/lib/shared/utils.js +++ b/lib/shared/utils.js @@ -1,6 +1,5 @@ 'use strict'; -const { getPrototypeOf } = Reflect; const { hasOwnProperty } = Object; const isNumber = require('is-number'); const typeOf = require('kind-of'); @@ -39,12 +38,19 @@ exports.isPrimitive = value => { return typeof value === 'object' ? value === null : typeof value !== 'function'; }; -exports.is_nil = exports.nil = exports.isNil = value => value === null || value === undefined; -exports.empty = exports.isEmpty = value => exports.size(value) === 0; +exports.isNil = value => value === null || value === undefined; exports.blank = exports.isBlank = value => exports.size(value) === 0; exports.present = exports.isPresent = value => exports.size(value) > 0; -exports.isFalsy = value => exports.isNil(value) === true || value === false; -exports.isTruthy = value => exports.isFalsy(value) === false; + +exports.isEmpty = exports.empty = value => { + if (value === null || value === undefined) return true; + if (value === '') return true; + if (typeof value === 'number') return value; + if (typeof value.size === 'number') return value.size === 0; + if (Array.isArray(value)) return value.length === 0; + if (exports.isObject(value)) return Object.keys(value).length === 0; + return false; +}; exports.isNumber = value => { if (typeof value === 'number') { @@ -63,7 +69,9 @@ exports.ParseSyntax = (node, markup, regex) => { exports.handlers = { set(target, key, value, receiver) { - return key in target ? ((target[key] = value), true) : target.set(key, value); + if (key !== 'undefined') { + return key in target ? ((target[key] = value), true) : target.set(key, value); + } }, get(target, key, receiver) { return key in target ? target[key] : target.get && target.get(key); @@ -91,7 +99,7 @@ exports.size = value => { if (exports.isObject(value)) return Object.keys(value).length; if (typeof value.length === 'number') return value.length; if (typeof value.size === 'number') return value.size; - return null; + return String(value).length; }; exports.toArray = value => { @@ -110,7 +118,7 @@ exports.toArray = value => { } }; -exports.toInteger = exports.to_integer = exports.to_i = num => { +exports.toInteger = exports.to_i = num => { if (typeof num === 'number') { return Math.round(num); }
fix isEmpty to respect numbers, etc. also ensure that keys named `undefined` do not return a value.
jonschlinkert_dry
train
852c7423ad04e87c8ab22005f9739208f8542b16
diff --git a/pyexcelerate/Range.py b/pyexcelerate/Range.py index <HASH>..<HASH> 100644 --- a/pyexcelerate/Range.py +++ b/pyexcelerate/Range.py @@ -161,6 +161,8 @@ class Range(object): def __getitem__(self, key): if self.is_row: # return the key'th column + if isinstance(key, six.string_types): + key = Range.string_to_coordinate(key) return Range((self.x, key), (self.x, key), self.worksheet, validate=False) elif self.is_column: #return the key'th row @@ -178,13 +180,17 @@ class Range(object): def string_to_coordinate(s): # Convert a base-26 name to integer y = 0 + l = len(s) for index, c in enumerate(s): if ord(c) < Range.A or ord(c) > Range.Z: s = s[index:] break y *= 26 y += ord(c) - Range.A + 1 - return (int(s), y) + if len(s) == l: + return y + else: + return (int(s), y) _cts_cache = {} @staticmethod diff --git a/pyexcelerate/Workbook.py b/pyexcelerate/Workbook.py index <HASH>..<HASH> 100644 --- a/pyexcelerate/Workbook.py +++ b/pyexcelerate/Workbook.py @@ -43,7 +43,7 @@ class Workbook(object): yield (index, ws) def _align_styles(self): - if Workbook.alignment != self or len(self._items) == 0: + if Workbook.alignment != self: Utility.YOLO = True Workbook.alignment = self items = dict([(x, {}) for x in Workbook.STYLE_ATTRIBUTE_MAP.keys()]) diff --git a/pyexcelerate/tests/test_Workbook.py b/pyexcelerate/tests/test_Workbook.py index <HASH>..<HASH> 100644 --- a/pyexcelerate/tests/test_Workbook.py +++ b/pyexcelerate/tests/test_Workbook.py @@ -28,7 +28,7 @@ def test_save(): def test_formulas(): wb = Workbook() ws = wb.new_sheet("test") - ws[1][1].value = 1 + ws[1]['A'].value = 1 ws[1][2].value = 2 ws[1][3].value = '=SUM(A1,B1)' ws[1][4].value = datetime.now()
add range non-numeric column selector and minor speed improvement.
kz26_PyExcelerate
train
3c3d356aa013ce1fcaeb61e58efb366dabf1784a
diff --git a/biz/init.js b/biz/init.js index <HASH>..<HASH> 100644 --- a/biz/init.js +++ b/biz/init.js @@ -1,10 +1,21 @@ var util = require('../lib/util'); -module.exports = function init(proxy) { +module.exports = function init(proxy, callback) { var config = proxy.config; - require(config.uipath)(proxy); + var count = 2; + var execCallback = function() { + if (--count === 0) { + callback(); + } + }; + util.getServer(function(server, port) { + config.uiport = port; + require(config.uipath)(server, proxy); + execCallback(); + }, config.uiport); util.getServer(function(server, port) { config.weinreport = port; require('./weinre/app')(server); + execCallback(); }, config.weinreport); }; diff --git a/biz/webui/lib/index.js b/biz/webui/lib/index.js index <HASH>..<HASH> 100644 --- a/biz/webui/lib/index.js +++ b/biz/webui/lib/index.js @@ -217,7 +217,7 @@ app.all(/^\/weinre\/.*/, function(req, res) { util.transformReq(req, res, config.weinreport, true); }); -module.exports = function(proxy) { +module.exports = function(server, proxy) { proxyEvent = proxy; config = proxy.config; pluginMgr = proxy.pluginMgr; @@ -232,5 +232,5 @@ module.exports = function(proxy) { require('./values')(rulesUtil.values); require('./https-util')(httpsUtil = proxy.httpsUtil); require('./data')(proxy); - app.listen(config.uiport); + server.on('request', app); }; diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,6 +1,7 @@ var express = require('express'); var path = require('path'); var fs = require('fs'); +var http = require('http'); var EventEmitter = require('events').EventEmitter; var util = require('./util'); var logger = require('./util/logger'); @@ -19,7 +20,7 @@ var upgradeProxy = require('./upgrade'); function proxy(callback) { var app = express(); - var server = app.listen(config.port, callback); + var server = http.createServer(); var proxyEvents = new EventEmitter(); var middlewares = ['./init', '../biz'] .concat(require('./inspectors')) @@ -38,7 +39,6 @@ function proxy(callback) { upgradeProxy(server); initDataServer(proxyEvents); initLogServer(proxyEvents); - require('../biz/init')(proxyEvents); var properties = rulesUtil.properties; if (config.disableAllRules) { properties.set('disabledAllRules', true); @@ -58,6 +58,10 @@ function proxy(callback) { rulesUtil.addValues(config.values, config.replaceExistValue); rulesUtil.addRules(config.rules, config.replaceExistRule); config.debug && rules.disableDnsCache(); + require('../biz/init')(proxyEvents, function(){ + server.on('request', app); + server.listen(config.port, callback); + }); return proxyEvents; }
feat: Support for getting random port of ui server
avwo_whistle
train
6b0d16372725580162f0a4d29fbe39b915a9e2b9
diff --git a/scripts/database.py b/scripts/database.py index <HASH>..<HASH> 100644 --- a/scripts/database.py +++ b/scripts/database.py @@ -23,18 +23,10 @@ from __future__ import print_function import datetime -import os - -import sys - -from pipes import quote - from flask import current_app from invenio.ext.script import Manager, change_command_name, print_progress -from six import iteritems - manager = Manager(usage="Perform database operations") # Shortcuts for manager options to keep code DRY. @@ -54,47 +46,53 @@ option_default_data = manager.option( @option_yes_i_know def init(user='root', password='', yes_i_know=False): """Initialize database and user.""" - from invenio.ext.sqlalchemy import db + from invenio.ext.sqlalchemy.utils import initialize_database_user from invenio.utils.text import wrap_text_in_a_box, wait_for_user + from sqlalchemy_utils.functions import database_exists, create_database, \ + drop_database + + from sqlalchemy.engine.url import URL + from sqlalchemy import create_engine + # Step 0: confirm deletion wait_for_user(wrap_text_in_a_box( "WARNING: You are going to destroy your database tables! Run first" " `inveniomanage database drop`." )) - # Step 1: drop database and recreate it - if db.engine.name == 'mysql': - # FIXME improve escaping - args = dict((k, str(v).replace('$', '\$')) - for (k, v) in iteritems(current_app.config) - if k.startswith('CFG_DATABASE')) - args = dict(zip(args, map(quote, args.values()))) - prefix = ('{cmd} -u {user} --password={password} ' - '-h {CFG_DATABASE_HOST} -P {CFG_DATABASE_PORT} ') - cmd_prefix = prefix.format(cmd='mysql', user=user, password=password, - **args) - cmd_admin_prefix = prefix.format(cmd='mysqladmin', user=user, - password=password, - **args) - cmds = [ - cmd_prefix + '-e "DROP DATABASE IF EXISTS {CFG_DATABASE_NAME}"', - (cmd_prefix + '-e "CREATE DATABASE IF NOT EXISTS ' - '{CFG_DATABASE_NAME} DEFAULT CHARACTER SET utf8 ' - 'COLLATE utf8_general_ci"'), - # Create user and grant access to database. - (cmd_prefix + '-e "GRANT ALL PRIVILEGES ON ' - '{CFG_DATABASE_NAME}.* TO {CFG_DATABASE_USER}@localhost ' - 'IDENTIFIED BY {CFG_DATABASE_PASS}"'), - cmd_admin_prefix + 'flush-privileges' - ] - for cmd in cmds: - cmd = cmd.format(**args) - print(cmd) - if os.system(cmd): - print("ERROR: failed execution of", cmd, file=sys.stderr) - sys.exit(1) - print('>>> Database has been installed.') + # Step 1: create URI to connect admin user + cfg = current_app.config + SQLALCHEMY_DATABASE_URI = URL( + cfg.get('CFG_DATABASE_TYPE', 'mysql'), + username=user, + password=password, + host=cfg.get('CFG_DATABASE_HOST'), + database=cfg.get('CFG_DATABASE_NAME'), + port=cfg.get('CFG_DATABASE_PORT'), + ) + + # Step 2: drop the database if already exists + if database_exists(SQLALCHEMY_DATABASE_URI): + drop_database(SQLALCHEMY_DATABASE_URI) + print('>>> Database has been dropped.') + + # Step 3: create the database + create_database(SQLALCHEMY_DATABASE_URI, encoding='utf8') + print('>>> Database has been created.') + + # Step 4: setup connection with special user + engine = create_engine(SQLALCHEMY_DATABASE_URI) + engine.connect() + + # Step 5: grant privileges for the user + initialize_database_user( + engine=engine, + database_name=current_app.config['CFG_DATABASE_NAME'], + database_user=current_app.config['CFG_DATABASE_USER'], + database_pass=current_app.config['CFG_DATABASE_PASS'], + ) + print('>>> Database user has been initialized.') @option_yes_i_know @@ -148,7 +146,7 @@ def drop(yes_i_know=False, quiet=False): dropper(table) dropped += 1 except Exception: - print('\r', '>>> problem with dropping ', table) + print('\r>>> problem with dropping {0}'.format(table)) current_app.logger.exception(table) if dropped == N: @@ -201,7 +199,7 @@ def create(default_data=True, quiet=False): creator(table) created += 1 except Exception: - print('\r', '>>> problem with creating ', table) + print('\r>>> problem with creating {0}'.format(table)) current_app.logger.exception(table) if created == N:
script: better database initialization * BETTER Uses SQLAlchemy and SQLAlchemy-Utils to initialize the database instead of executing mysql in a python subshell. (closes #<I>) (closes #<I>) * NEW Adds support for PostgreSQL database initialization.
inveniosoftware_invenio-base
train
1cc2f12e84bc76d5d6951679e8939019f45d9c85
diff --git a/pykeepass/pykeepass.py b/pykeepass/pykeepass.py index <HASH>..<HASH> 100644 --- a/pykeepass/pykeepass.py +++ b/pykeepass/pykeepass.py @@ -12,6 +12,7 @@ import os import re +logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) @@ -26,12 +27,12 @@ class PyKeePass(): filename = self.kdb_filename assert filename, 'Filename should not be empty' logger.info('Open file {}'.format(filename)) - self.kdb = libkeepass.open( + return libkeepass.open( filename, password=password, keyfile=keyfile ).__enter__() - return self.kdb def save(self, filename=None): + # FIXME The *second* save operations creates gibberish passwords if not filename: filename = self.kdb_filename outfile = open(filename, 'w+').__enter__() @@ -92,6 +93,9 @@ class PyKeePass(): return self.__xpath(xp, first_match_only=False, tree=tree) def find_group_by_path(self, group_path_str, regex=False, tree=None): + # Remove leading '/' + if group_path_str: + group_path_str = group_path_str.lstrip('/') res = self.find_groups_by_path( group_path_str=group_path_str, regex=regex, @@ -101,7 +105,7 @@ class PyKeePass(): return res[0] def get_root_group(self, tree=None): - return self.find_group_by_path(group_path_str=None) + return self.find_group_by_path(group_path_str=None, tree=tree) def find_groups_by_name(self, group_name, tree=None, regex=False): if regex: @@ -123,20 +127,27 @@ class PyKeePass(): group = self.get_root_group(tree) path = '' for gn in group_path.split('/'): - group = self.__create_group_at_path(tree, path.rstrip('/'), gn) + # Create group if it does not already exist + gp = '{}/{}'.format(path.strip('/'), gn) + if not self.find_group_by_path(gp, tree=tree): + logger.info('Group {} does not exist. Create it.'.format(gn)) + group = self.__create_group_at_path(path.rstrip('/'), gn, tree=tree) + else: + logger.info('Group {} already exists'.format(gp)) path += gn + '/' return group - def __create_group_at_path(self, tree, group_path, group_name): + def __create_group_at_path(self, group_path, group_name, tree=None): logger.info( 'Create group {} at {}'.format( group_name, group_path if group_path else 'root dir' ) ) - parent_group = self.find_group_by_path(group_path, tree) + # FIXME Skip this step if the group already exists! + parent_group = self.find_group_by_path(group_path, tree=tree) if parent_group: - group = Group(element=group_name) + group = Group(name=group_name) parent_group.append(group) return group else:
Fix: Dupplicate groups are created
pschmitt_pykeepass
train
ad6be801311b3be14dde68be02f2b72dcdc1d8f9
diff --git a/guacamole-ext/src/main/java/org/apache/guacamole/token/StandardTokens.java b/guacamole-ext/src/main/java/org/apache/guacamole/token/StandardTokens.java index <HASH>..<HASH> 100644 --- a/guacamole-ext/src/main/java/org/apache/guacamole/token/StandardTokens.java +++ b/guacamole-ext/src/main/java/org/apache/guacamole/token/StandardTokens.java @@ -23,6 +23,10 @@ import java.text.SimpleDateFormat; import java.util.Date; import org.apache.guacamole.net.auth.AuthenticatedUser; import org.apache.guacamole.net.auth.Credentials; +import java.util.Map; +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Utility class which provides access to standardized token names, as well as @@ -75,6 +79,12 @@ public class StandardTokens { private static final String TIME_FORMAT = "HHmmss"; /** + * Standard prefix to append to beginning of the name of each custom + * LDAP attribute before adding attributes as tokens. + */ + private static final String LDAP_ATTR_PREFIX = "USER_ATTR:"; + + /** * This utility class should not be instantiated. */ private StandardTokens() {} @@ -134,6 +144,15 @@ public class StandardTokens { if (address != null) filter.setToken(CLIENT_ADDRESS_TOKEN, address); + // Add each custom client LDAP attribute token + Map<String, String> ldapAttrs = credentials.getLDAPAttributes(); + if (ldapAttrs != null) { + for (Map.Entry<String, String> attr : ldapAttrs.entrySet()) { + String tokenName = LDAP_ATTR_PREFIX + attr.getKey().toUpperCase(); + filter.setToken(tokenName, attr.getValue()); + } + } + // Add any tokens which do not require credentials addStandardTokens(filter);
GUACAMOLE-<I>: Add LDAP attribute tokens to StandardTokens. In method addStandardTokens(TokenFilter, Credentials), adds each LDAP attribute from credentials.getLDAPAttributes(). Name of token is "USER_ATTR:" + name of attribute and value is the value of the attribute.
glyptodon_guacamole-client
train
e6adbdd303281bfb5d6925464106c2a50ee9813e
diff --git a/src/Methods/Web3/ClientVersion.php b/src/Methods/Web3/ClientVersion.php index <HASH>..<HASH> 100644 --- a/src/Methods/Web3/ClientVersion.php +++ b/src/Methods/Web3/ClientVersion.php @@ -17,6 +17,13 @@ use Web3\Methods\EthMethod; class ClientVersion extends EthMethod { /** + * validators + * + * @var array + */ + protected $validators = []; + + /** * inputFormatters * * @var array diff --git a/src/Methods/Web3/Sha3.php b/src/Methods/Web3/Sha3.php index <HASH>..<HASH> 100644 --- a/src/Methods/Web3/Sha3.php +++ b/src/Methods/Web3/Sha3.php @@ -14,10 +14,20 @@ namespace Web3\Methods\Web3; use InvalidArgumentException; use Web3\Methods\EthMethod; use Web3\Formatters\HexFormatter; +use Web3\Validators\StringValidator; class Sha3 extends EthMethod { /** + * validators + * + * @var array + */ + protected $validators = [ + StringValidator::class + ]; + + /** * inputFormatters * * @var array diff --git a/src/Web3.php b/src/Web3.php index <HASH>..<HASH> 100644 --- a/src/Web3.php +++ b/src/Web3.php @@ -132,10 +132,19 @@ class Web3 } else { $methodObject = $this->methods[$method]; } - $inputs = $methodObject->transform($arguments, $methodObject->inputFormatters); - $methodObject->arguments = $inputs; - - $this->provider->send($methodObject, $callback); + try { + if ($methodObject->validate($arguments)) { + $inputs = $methodObject->transform($arguments, $methodObject->inputFormatters); + $methodObject->arguments = $inputs; + $this->provider->send($methodObject, $callback); + } + } catch (\Exception $e) { + if (is_callable($callback) === true) { + call_user_func($callback, $e, null); + } else { + throw $e; + } + } } } diff --git a/test/unit/Web3ApiTest.php b/test/unit/Web3ApiTest.php index <HASH>..<HASH> 100644 --- a/test/unit/Web3ApiTest.php +++ b/test/unit/Web3ApiTest.php @@ -102,13 +102,13 @@ class Web3ApiTest extends TestCase */ public function testWrongParam() { - $this->expectException(RuntimeException::class); + // $this->expectException(RuntimeException::class); $web3 = $this->web3; $web3->sha3($web3, function ($err, $hash) { if ($err !== null) { - return $this->fail($err->getMessage()); + return $this->assertTrue($err instanceof RuntimeException); } $this->assertTrue(true); }); diff --git a/test/unit/Web3BatchTest.php b/test/unit/Web3BatchTest.php index <HASH>..<HASH> 100644 --- a/test/unit/Web3BatchTest.php +++ b/test/unit/Web3BatchTest.php @@ -54,4 +54,28 @@ class Web3BatchTest extends TestCase $this->assertEquals($data[1], $this->testHash); }); } + + /** + * testWrongParam + * + * @return void + */ + public function testWrongParam() + { + $this->expectException(RuntimeException::class); + + $web3 = $this->web3; + + $web3->batch(true); + $web3->clientVersion(); + $web3->sha3($web3); + + $web3->provider->execute(function ($err, $data) { + if ($err !== null) { + return $this->fail('Got error!'); + } + $this->assertTrue(is_string($data[0])); + $this->assertEquals($data[1], $this->testHash); + }); + } } \ No newline at end of file
Web3 apis and test.
sc0Vu_web3.php
train
e1dc5a18d19e838c526e88032f04664d3952194d
diff --git a/lib/less/functions.js b/lib/less/functions.js index <HASH>..<HASH> 100644 --- a/lib/less/functions.js +++ b/lib/less/functions.js @@ -5,8 +5,8 @@ tree.functions = { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { - var rgb = [r, g, b].map(function (c) { return number(c) }), - a = number(a); + var rgb = [r, g, b].map(function (c) { return number(c); }); + a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { @@ -86,8 +86,8 @@ tree.functions = { luma: function (color) { return new(tree.Dimension)(Math.round((0.2126 * (color.rgb[0]/255) + 0.7152 * (color.rgb[1]/255) + - 0.0722 * (color.rgb[2]/255)) - * color.alpha * 100), '%'); + 0.0722 * (color.rgb[2]/255)) * + color.alpha * 100), '%'); }, saturate: function (color, amount) { var hsl = color.toHSL(); @@ -343,8 +343,8 @@ tree.functions = { } }; -function hsla(hsla) { - return tree.functions.hsla(hsla.h, hsla.s, hsla.l, hsla.a); +function hsla(color) { + return tree.functions.hsla(color.h, color.s, color.l, color.a); } function number(n) {
Cleaned up parts of functions.js making the code more lint-friendly
less_less.js
train
e047642bdfd2e9d8638923aabc7698da342ef4d3
diff --git a/src/main/java/javax/time/OffsetDate.java b/src/main/java/javax/time/OffsetDate.java index <HASH>..<HASH> 100644 --- a/src/main/java/javax/time/OffsetDate.java +++ b/src/main/java/javax/time/OffsetDate.java @@ -45,8 +45,8 @@ import javax.time.calendrical.LocalDateTimeField; import javax.time.calendrical.LocalPeriodUnit; import javax.time.calendrical.PeriodUnit; import javax.time.format.CalendricalFormatter; -import javax.time.format.DateTimeParseException; import javax.time.format.DateTimeFormatters; +import javax.time.format.DateTimeParseException; import javax.time.zone.ZoneResolvers; /** @@ -253,8 +253,8 @@ public final class OffsetDate @Override public long get(DateTimeField field) { if (field instanceof LocalDateTimeField) { - switch ((LocalDateTimeField) field) { - case OFFSET_SECONDS: return getOffset().getTotalSeconds(); + if (field == OFFSET_SECONDS) { + return getOffset().getTotalSeconds(); } return date.get(field); } @@ -426,11 +426,9 @@ public final class OffsetDate */ public OffsetDate with(DateTimeField field, long newValue) { if (field instanceof LocalDateTimeField) { - LocalDateTimeField f = (LocalDateTimeField) field; - switch (f) { - case OFFSET_SECONDS: { - return with(date, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); - } + if (field == OFFSET_SECONDS) { + LocalDateTimeField f = (LocalDateTimeField) field; + return with(date, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); } return with(date.with(field, newValue), offset); } diff --git a/src/main/java/javax/time/OffsetTime.java b/src/main/java/javax/time/OffsetTime.java index <HASH>..<HASH> 100644 --- a/src/main/java/javax/time/OffsetTime.java +++ b/src/main/java/javax/time/OffsetTime.java @@ -45,8 +45,8 @@ import javax.time.calendrical.LocalDateTimeField; import javax.time.calendrical.LocalPeriodUnit; import javax.time.calendrical.PeriodUnit; import javax.time.format.CalendricalFormatter; -import javax.time.format.DateTimeParseException; import javax.time.format.DateTimeFormatters; +import javax.time.format.DateTimeParseException; /** * A time with a zone offset from UTC in the ISO-8601 calendar system, @@ -284,8 +284,8 @@ public final class OffsetTime @Override public long get(DateTimeField field) { if (field instanceof LocalDateTimeField) { - switch ((LocalDateTimeField) field) { - case OFFSET_SECONDS: return getOffset().getTotalSeconds(); + if (field == OFFSET_SECONDS) { + return getOffset().getTotalSeconds(); } return time.get(field); } @@ -437,11 +437,9 @@ public final class OffsetTime */ public OffsetTime with(DateTimeField field, long newValue) { if (field instanceof LocalDateTimeField) { - LocalDateTimeField f = (LocalDateTimeField) field; - switch (f) { - case OFFSET_SECONDS: { - return with(time, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); - } + if (field == OFFSET_SECONDS) { + LocalDateTimeField f = (LocalDateTimeField) field; + return with(time, ZoneOffset.ofTotalSeconds(f.checkValidIntValue(newValue))); } return with(time.with(field, newValue), offset); }
Simpler implemenation of get/with
ThreeTen_threetenbp
train
f59e8c20dafa515beb6950c5c1e6351e241debea
diff --git a/publ/__init__.py b/publ/__init__.py index <HASH>..<HASH> 100755 --- a/publ/__init__.py +++ b/publ/__init__.py @@ -51,25 +51,28 @@ def publ(name, cfg): static=utils.static_url ) + caching.init_app(app) + if config.index_rescan_interval: app.before_request(scan_index) if 'CACHE_THRESHOLD' in config.cache: app.after_request(set_cache_expiry) - caching.init_app(app) - - # Scan the index - model.setup() - scan_index(True) - index.background_scan(config.content_folder) - + app.before_first_request(startup) return app last_scan = None # pylint: disable=invalid-name +def startup(): + """ Startup routine for initiating the content indexer """ + model.setup() + scan_index(True) + index.background_scan(config.content_folder) + + def scan_index(force=False): """ Rescan the index if it's been more than a minute since the last scan """ global last_scan # pylint: disable=invalid-name,global-statement diff --git a/publ/markdown.py b/publ/markdown.py index <HASH>..<HASH> 100644 --- a/publ/markdown.py +++ b/publ/markdown.py @@ -151,12 +151,14 @@ class TitleRenderer(HtmlRenderer): def paragraph(content): return content - def list(self, content, is_ordered, is_block): + @staticmethod + def list(content, is_ordered, is_block): # pylint: disable=unused-argument print('list', content, is_ordered, is_block) return content - def listitem(self, content, is_ordered, is_block): + @staticmethod + def listitem(content, is_ordered, is_block): # pylint: disable=unused-argument print('listitem', content, is_ordered, is_block) if not is_ordered:
Only start the context scan when the context is fully up, to prevent the double-threading bug
PlaidWeb_Publ
train
7e924dc8dbffb68d0631c9ab35cd24eb459b8be6
diff --git a/dynamic_dynamodb/core/gsi.py b/dynamic_dynamodb/core/gsi.py index <HASH>..<HASH> 100644 --- a/dynamic_dynamodb/core/gsi.py +++ b/dynamic_dynamodb/core/gsi.py @@ -96,14 +96,18 @@ def __calculate_always_decrease_rw_values( return (read_units, write_units) if read_units < provisioned_reads: - '{0} - GSI: {1} - Reads could be decreased, but we are waiting for ' - 'writes to get low too first'.format(table_name, gsi_name) + logger.info( + '{0} - GSI: {1} - Reads could be decreased, ' + 'but we are waiting for writes to get lower than the threshold ' + 'before scaling down'.format(table_name, gsi_name)) read_units = provisioned_reads elif write_units < provisioned_writes: - '{0} - GSI: {1} - Writes could be decreased, but we are waiting for ' - 'reads to get low too first'.format(table_name, gsi_name) + logger.info( + '{0} - GSI: {1} - Writes could be decreased, ' + 'but we are waiting for reads to get lower than the threshold ' + 'before scaling down'.format(table_name, gsi_name)) write_units = provisioned_writes diff --git a/dynamic_dynamodb/core/table.py b/dynamic_dynamodb/core/table.py index <HASH>..<HASH> 100644 --- a/dynamic_dynamodb/core/table.py +++ b/dynamic_dynamodb/core/table.py @@ -72,14 +72,18 @@ def __calculate_always_decrease_rw_values( return (read_units, write_units) if read_units < provisioned_reads: - '{0} - Reads could be decreased, but we are waiting for ' - 'writes to get low too first'.format(table_name) + logger.info( + '{0} - Reads could be decreased, but we are waiting for ' + 'writes to get lower than the threshold before ' + 'scaling down'.format(table_name)) read_units = provisioned_reads elif write_units < provisioned_writes: - '{0} - Writes could be decreased, but we are waiting for ' - 'reads to get low too first'.format(table_name) + logger.info( + '{0} - Writes could be decreased, but we are waiting for ' + 'reads to get lower than the threshold before ' + 'scaling down'.format(table_name)) write_units = provisioned_writes
Added logging info #<I>
sebdah_dynamic-dynamodb
train
33a3f41bb30539470e75be15520098051138a083
diff --git a/lib/knode.js b/lib/knode.js index <HASH>..<HASH> 100644 --- a/lib/knode.js +++ b/lib/knode.js @@ -246,7 +246,7 @@ exports.KNode.prototype._iterativeFind = function(key, mode, cb) { var contacted = {}; var foundValue = false; var value = null; - var contactsWhichHadValue = []; + var contactsWithoutValue = []; closestNode = shortlist[0]; if (!closestNode) { // we aren't connected to the overlay network! @@ -276,14 +276,14 @@ exports.KNode.prototype._iterativeFind = function(key, mode, cb) { } if (message.found && mode == 'VALUE') { - // TODO: iterative find value when it does find the - // value should store the value at the closest node which - // DID NOT have the value foundValue = true; value = message.value; - contactsWhichHadValue.push(contact.nodeID); } else { + if (mode == 'VALUE') { + // not found, so add this contact + contactsWithoutValue.push(contact); + } shortlist = shortlist.concat(message.contacts); shortlist = _.uniq(shortlist, false /* is sorted? */, function(contact) { return contact.nodeID; @@ -294,13 +294,8 @@ exports.KNode.prototype._iterativeFind = function(key, mode, cb) { }, this)); }, this), _.bind(function(err) { if (foundValue) { - console.log("Found value from ", contactsWhichHadValue); - // closest node without value - var thisNodeID = this.self.nodeID; - var contactsWithoutValue = _.reject(shortlist, function(contact) { - return _.include(contactsWhichHadValue, contact.nodeID); - }); + console.log("W/O value ", contactsWithoutValue); var distances = _.map(contactsWithoutValue, function(contact) {
Keep track of contacts without value instead of filtering later
nikhilm_kademlia
train
90be18150f1f2b1ab76978591508f88399be1736
diff --git a/core/src/main/java/org/bitcoinj/core/Transaction.java b/core/src/main/java/org/bitcoinj/core/Transaction.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/bitcoinj/core/Transaction.java +++ b/core/src/main/java/org/bitcoinj/core/Transaction.java @@ -35,11 +35,9 @@ import java.io.*; import java.util.*; import static org.bitcoinj.core.Utils.*; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import java.math.BigInteger; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import org.bitcoinj.script.ScriptChunk; /** * <p>A transaction represents the movement of coins from some addresses to some other addresses. It can also represent @@ -1203,8 +1201,8 @@ public class Transaction extends ChildMessage { */ public void checkCoinBaseHeight(final int height) throws VerificationException { - assert height >= Block.BLOCK_HEIGHT_GENESIS; - assert isCoinBase(); + checkArgument(height >= Block.BLOCK_HEIGHT_GENESIS); + checkState(isCoinBase()); // Check block height is in coinbase input script final TransactionInput in = this.getInputs().get(0); diff --git a/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java b/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java +++ b/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java @@ -150,7 +150,7 @@ public final class HDKeyDerivation { ChildNumber childNumber) throws HDDerivationException { checkArgument(parent.hasPrivKey(), "Parent key must have private key bytes for this method."); byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true); - assert parentPublicKey.length == 33 : parentPublicKey.length; + checkState(parentPublicKey.length == 33, "Parent pubkey must be 33 bytes, but is " + parentPublicKey.length); ByteBuffer data = ByteBuffer.allocate(37); if (childNumber.isHardened()) { data.put(parent.getPrivKeyBytes33()); @@ -159,7 +159,7 @@ public final class HDKeyDerivation { } data.putInt(childNumber.i()); byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array()); - assert i.length == 64 : i.length; + checkState(i.length == 64, i.length); byte[] il = Arrays.copyOfRange(i, 0, 32); byte[] chainCode = Arrays.copyOfRange(i, 32, 64); BigInteger ilInt = new BigInteger(1, il); @@ -178,12 +178,12 @@ public final class HDKeyDerivation { public static RawKeyBytes deriveChildKeyBytesFromPublic(DeterministicKey parent, ChildNumber childNumber, PublicDeriveMode mode) throws HDDerivationException { checkArgument(!childNumber.isHardened(), "Can't use private derivation with public keys only."); byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true); - assert parentPublicKey.length == 33 : parentPublicKey.length; + checkState(parentPublicKey.length == 33, "Parent pubkey must be 33 bytes, but is " + parentPublicKey.length); ByteBuffer data = ByteBuffer.allocate(37); data.put(parentPublicKey); data.putInt(childNumber.i()); byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array()); - assert i.length == 64 : i.length; + checkState(i.length == 64, i.length); byte[] il = Arrays.copyOfRange(i, 0, 32); byte[] chainCode = Arrays.copyOfRange(i, 32, 64); BigInteger ilInt = new BigInteger(1, il); diff --git a/core/src/main/java/org/bitcoinj/utils/BtcFormat.java b/core/src/main/java/org/bitcoinj/utils/BtcFormat.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/bitcoinj/utils/BtcFormat.java +++ b/core/src/main/java/org/bitcoinj/utils/BtcFormat.java @@ -23,6 +23,7 @@ import org.bitcoinj.core.Coin; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Strings; import java.math.BigDecimal; @@ -1359,7 +1360,7 @@ public abstract class BtcFormat extends Format { * forget to put the symbols back otherwise equals(), hashCode() and immutability will * break. */ private static DecimalFormatSymbols setSymbolAndCode(DecimalFormat numberFormat, String symbol, String code) { - assert Thread.holdsLock(numberFormat); + checkState(Thread.holdsLock(numberFormat)); DecimalFormatSymbols fs = numberFormat.getDecimalFormatSymbols(); DecimalFormatSymbols ante = (DecimalFormatSymbols)fs.clone(); fs.setInternationalCurrencySymbol(code); @@ -1380,7 +1381,7 @@ public abstract class BtcFormat extends Format { * @return The DecimalFormatSymbols before changing */ protected static void prefixUnitsIndicator(DecimalFormat numberFormat, int scale) { - assert Thread.holdsLock(numberFormat); // make sure caller intends to reset before changing + checkState(Thread.holdsLock(numberFormat)); // make sure caller intends to reset before changing DecimalFormatSymbols fs = numberFormat.getDecimalFormatSymbols(); setSymbolAndCode(numberFormat, prefixSymbol(fs.getCurrencySymbol(), scale), prefixCode(fs.getInternationalCurrencySymbol(), scale)
Migrate a few asserts to Guava checkArgument/checkState.
bitcoinj_bitcoinj
train
9d3d55d0fb6cb6c34161cd418a580d4fb266fa4d
diff --git a/pkg/kubelet/rkt/rkt.go b/pkg/kubelet/rkt/rkt.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/rkt/rkt.go +++ b/pkg/kubelet/rkt/rkt.go @@ -426,11 +426,17 @@ func setApp(imgManifest *appcschema.ImageManifest, c *api.Container, opts *kubec var command, args []string cmd, ok := imgManifest.Annotations.Get(appcDockerEntrypoint) if ok { - command = strings.Fields(cmd) + err := json.Unmarshal([]byte(cmd), &command) + if err != nil { + return fmt.Errorf("cannot unmarshal ENTRYPOINT %q: %v", cmd, err) + } } ag, ok := imgManifest.Annotations.Get(appcDockerCmd) if ok { - args = strings.Fields(ag) + err := json.Unmarshal([]byte(ag), &args) + if err != nil { + return fmt.Errorf("cannot unmarshal CMD %q: %v", ag, err) + } } userCommand, userArgs := kubecontainer.ExpandContainerCommandAndArgs(c, opts.Envs) @@ -814,8 +820,6 @@ func (r *Runtime) preparePod(pod *api.Pod, pullSecrets []api.Secret) (string, *k // TODO handle pod.Spec.HostIPC units := []*unit.UnitOption{ - // This makes the service show up for 'systemctl list-units' even if it exits successfully. - newUnitOption("Service", "RemainAfterExit", "true"), newUnitOption("Service", "ExecStart", runPrepared), // This enables graceful stop. newUnitOption("Service", "KillMode", "mixed"), diff --git a/pkg/kubelet/rkt/rkt_test.go b/pkg/kubelet/rkt/rkt_test.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/rkt/rkt_test.go +++ b/pkg/kubelet/rkt/rkt_test.go @@ -766,8 +766,16 @@ func baseApp(t *testing.T) *appctypes.App { func baseImageManifest(t *testing.T) *appcschema.ImageManifest { img := &appcschema.ImageManifest{App: baseApp(t)} - img.Annotations.Set(*appctypes.MustACIdentifier(appcDockerEntrypoint), "/bin/foo") - img.Annotations.Set(*appctypes.MustACIdentifier(appcDockerCmd), "bar") + entrypoint, err := json.Marshal([]string{"/bin/foo"}) + if err != nil { + t.Fatal(err) + } + cmd, err := json.Marshal([]string{"bar"}) + if err != nil { + t.Fatal(err) + } + img.Annotations.Set(*appctypes.MustACIdentifier(appcDockerEntrypoint), string(entrypoint)) + img.Annotations.Set(*appctypes.MustACIdentifier(appcDockerCmd), string(cmd)) return img }
rkt: Unmarshal the ENTRYPOINT/CMD from jsons instead of strings. Using json makes this robust to ENTRYPOINT/CMD that contains space. Also removed 'RemainAfterExit' option, originally this option is useful when we implement GetPods() by 'systemctl list-units'. However since we are using rkt API service now, it's no longer needed.
kubernetes_kubernetes
train
412db1c5209c4174690266df6f834b6ed6822f4b
diff --git a/core/lib/refinery/engine.rb b/core/lib/refinery/engine.rb index <HASH>..<HASH> 100644 --- a/core/lib/refinery/engine.rb +++ b/core/lib/refinery/engine.rb @@ -29,7 +29,7 @@ module Refinery if block && block.respond_to?(:call) after_inclusion_procs << block else - raise 'Anything added to be called before_inclusion must be callable.' + raise 'Anything added to be called after_inclusion must be callable.' end end
It's after_inclusion.
refinery_refinerycms
train
d4304ca7fdcd76b2f41ab4dbd10548fd56d5143d
diff --git a/src/main/java/com/github/maven_nar/NarUtil.java b/src/main/java/com/github/maven_nar/NarUtil.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/maven_nar/NarUtil.java +++ b/src/main/java/com/github/maven_nar/NarUtil.java @@ -257,7 +257,7 @@ public final class NarUtil { * */ String aol_linker; - if(linker != null & linker.getName() != null) + if(linker != null && linker.getName() != null) { log.debug("linker original name: " + linker.getName()); aol_linker = linker.getName();
NarUtil: handle null Linker parameter top getAOL(...) as intended Previously we were throwing a NullPointerException if we had a null Linker passed in, because of the line: if(linker != null & linker.getName() != null) This change simply changes that single-ampersand to a double-ampersand which is the behaviour the original author intended.
maven-nar_nar-maven-plugin
train
6ac0bc30b2943ab73a5677f5cf63b1a59cf552fe
diff --git a/classes/Gems/Default/TrackAction.php b/classes/Gems/Default/TrackAction.php index <HASH>..<HASH> 100644 --- a/classes/Gems/Default/TrackAction.php +++ b/classes/Gems/Default/TrackAction.php @@ -187,6 +187,17 @@ class Gems_Default_TrackAction extends \Gems_Default_RespondentChildActionAbstra 'Tracker\\TrackTokenOverviewSnippet', 'Tracker\\TrackUsageOverviewSnippet', ); + + /** + * Parameters for editing a track token + * + * @var mixed String or array of snippets name + */ + protected $editParameters = [ + 'formTitle' => null, + 'topicCallable' => 'getTokenTopicCallable', + ]; + /** * The parameters used for the edit track action.
Fixed #<I> - Title now shows Edit token instead of Edit track
GemsTracker_gemstracker-library
train
f3e19523ee4b178da1d2dcaaaa47be741ee27e1a
diff --git a/src/jparser.js b/src/jparser.js index <HASH>..<HASH> 100644 --- a/src/jparser.js +++ b/src/jparser.js @@ -77,6 +77,31 @@ jParser.prototype.structure = { offset = toInt.call(this, offset); this.view.seek(this.view.tell() + offset); return offset; + }, + bitfield: function (structure) { + var output = {}, + bitShift = 0; + + for (var key in structure) { + var fieldInfo = structure[key], + fieldValue; + + if (typeof fieldInfo === 'object') { + fieldValue = this.bitfield(fieldInfo); + } else { + var bitSize = toInt.call(this, fieldInfo), + fullValue = this.view.getUint32(undefined, true); + + bitShift += bitSize; + fieldValue = (fullValue >>> (32 - bitShift)) & ~(-1 << bitSize); + bitShift &= 7; + this.skip(4 - (bitSize >>> 3)); + } + + output[key] = fieldValue; + } + + return output; } };
Added bitfield support (not tested yet; no direction support yet).
jDataView_jBinary
train
c3311744c52e040ca2e3d98107df827e0fda80bd
diff --git a/contrib/mesos/pkg/scheduler/plugin.go b/contrib/mesos/pkg/scheduler/plugin.go index <HASH>..<HASH> 100644 --- a/contrib/mesos/pkg/scheduler/plugin.go +++ b/contrib/mesos/pkg/scheduler/plugin.go @@ -306,7 +306,8 @@ func (k *kubeScheduler) Schedule(pod *api.Pod, unused algorithm.NodeLister) (str } } -// Call ScheduleFunc and subtract some resources, returning the name of the machine the task is scheduled on +// doSchedule schedules the given task and returns the machine the task is scheduled on +// or an error if the scheduling failed. func (k *kubeScheduler) doSchedule(task *podtask.T) (string, error) { var offer offers.Perishable var err error
scheduler: correct doc in doSchedule
kubernetes_kubernetes
train
557f2a95271fe52769cca29a0b53674a1378f192
diff --git a/db/migrate/20150605095934_create_pd_regimes.rb b/db/migrate/20150605095934_create_pd_regimes.rb index <HASH>..<HASH> 100644 --- a/db/migrate/20150605095934_create_pd_regimes.rb +++ b/db/migrate/20150605095934_create_pd_regimes.rb @@ -5,16 +5,14 @@ class CreatePdRegimes < ActiveRecord::Migration t.integer :patient_id t.date :start_date t.date :end_date - t.integer :pd_treatment_regime_id t.integer :glucose_ml_percent_1_36 t.integer :glucose_ml_percent_2_27 t.integer :glucose_ml_percent_3_86 t.integer :amino_acid_ml t.integer :icodextrin_ml - t.string :low_glucose_degradation - t.string :low_sodium - t.integer :fluid_manufacturer - t.string :additional_hd + t.boolean :low_glucose_degradation + t.boolean :low_sodium + t.boolean :additional_hd t.timestamps null: false end end diff --git a/db/schema.rb b/db/schema.rb index <HASH>..<HASH> 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -249,16 +249,14 @@ ActiveRecord::Schema.define(version: 20150605095934) do t.integer "patient_id" t.date "start_date" t.date "end_date" - t.integer "pd_treatment_regime_id" t.integer "glucose_ml_percent_1_36" t.integer "glucose_ml_percent_2_27" t.integer "glucose_ml_percent_3_86" t.integer "amino_acid_ml" t.integer "icodextrin_ml" - t.string "low_glucose_degradation" - t.string "low_sodium" - t.integer "fluid_manufacturer" - t.string "additional_hd" + t.boolean "low_glucose_degradation" + t.boolean "low_sodium" + t.boolean "additional_hd" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
Edited columns for pd_regimes table.
airslie_renalware-core
train
bd0e97023e90b06dca13cbc424202cf24e03e0d6
diff --git a/lib/config/wrapper.go b/lib/config/wrapper.go index <HASH>..<HASH> 100644 --- a/lib/config/wrapper.go +++ b/lib/config/wrapper.go @@ -60,10 +60,8 @@ type Wrapper struct { deviceMap map[protocol.DeviceID]DeviceConfiguration folderMap map[string]FolderConfiguration replaces chan Configuration + subs []Committer mut sync.Mutex - - subs []Committer - sMut sync.Mutex } // Wrap wraps an existing Configuration structure and ties it to a file on @@ -73,7 +71,6 @@ func Wrap(path string, cfg Configuration) *Wrapper { cfg: cfg, path: path, mut: sync.NewMutex(), - sMut: sync.NewMutex(), } w.replaces = make(chan Configuration) return w @@ -109,15 +106,15 @@ func (w *Wrapper) Stop() { // Subscribe registers the given handler to be called on any future // configuration changes. func (w *Wrapper) Subscribe(c Committer) { - w.sMut.Lock() + w.mut.Lock() w.subs = append(w.subs, c) - w.sMut.Unlock() + w.mut.Unlock() } // Unsubscribe de-registers the given handler from any future calls to // configuration changes func (w *Wrapper) Unsubscribe(c Committer) { - w.sMut.Lock() + w.mut.Lock() for i := range w.subs { if w.subs[i] == c { copy(w.subs[i:], w.subs[i+1:]) @@ -126,7 +123,7 @@ func (w *Wrapper) Unsubscribe(c Committer) { break } } - w.sMut.Unlock() + w.mut.Unlock() } // Raw returns the currently wrapped Configuration object.
We don't need a separate subscription lock We forgot to lock it during replace, so data rate. This is simpler.
syncthing_syncthing
train
fdbaf9cb8b186ec0b49d7dbd19f542b7c90d0ac9
diff --git a/src/Climber/Cron/Executor.php b/src/Climber/Cron/Executor.php index <HASH>..<HASH> 100644 --- a/src/Climber/Cron/Executor.php +++ b/src/Climber/Cron/Executor.php @@ -2,7 +2,6 @@ namespace Peak\Climber\Cron; -use Doctrine\DBAL\Connection; use Peak\Climber\Application; use Peak\Climber\Cron\Exception\DatabaseNotFoundException; use Peak\Climber\Cron\Exception\TablesNotFoundException; @@ -52,6 +51,71 @@ class Executor */ public function run() { + $qb = $this->conn->createQueryBuilder(); + $qb->select('*') + ->from('climber_cron') + ->where('enabled = 1'); + + $result = $qb->execute(); + $count = $result->rowCount(); + + $time = round(microtime(true)); + //echo date('Y-m-d H:i:s', $time); + foreach ($result as $cron) { + if ($cron['repeat'] == -1 && empty($cron['last_execution'])) { + $this->processCron($cron); + } elseif ($cron['repeat'] == 0 && ( ($cron['interval'] + $time) <= $cron['last_execution'] ) ) { + $this->processCron($cron); + } + } + } + + public function processCron($cron) + { + $climber_prefix = $this->app->conf('climber_cmd_prefix'); + + $update = [ + 'last_execution' => time(), + 'error' => 0 + ]; + + if ($cron['repeat'] > 1) { + --$cron['repeat']; + $update['next_execution'] = time() + $cron['interval']; + } elseif($cron['repeat'] == 1) { + $cron['repeat'] = -1; + } + + if ($cron['repeat'] == -1) { + $update['enabled'] = 0; + $update['next_execution'] = null; + } + + $cmd = $cron['cmd']; + if (!empty($climber_prefix) && $cron['sys_cmd'] == 0) { + $cmd = $climber_prefix.' '.$cmd; + } + + echo 'Running cron job #'.$cron['id'].':'."\n"; + echo '$ '.$cmd."\n"; + + $process = new Process($cmd); + $process->run(); + + // executes after the command finishes + if (!$process->isSuccessful()) { + $update['error'] = 1; + } + + $this->conn->update('climber_cron', $update, [ + 'id' => $cron['id'] + ]); +// +// if (!$process->isSuccessful()) { +// throw new ProcessFailedException($process); +// } + + echo $process->getOutput(); } }
added run() and processCron()
peakphp_framework
train
97d4d177716b67ae964ebaf9da1d9fce5c1ec5da
diff --git a/py3nvml/utils.py b/py3nvml/utils.py index <HASH>..<HASH> 100644 --- a/py3nvml/utils.py +++ b/py3nvml/utils.py @@ -169,9 +169,25 @@ def try_get_info(f, h, default='N/A'): def get_free_gpus(max_procs=0): """ - Checks the number of GPUsprocesses running on your GPUs - For an N gpu system, returns a list of N boolean values. The nth value - will be True if no more than max_procs process was running on the nth gpu. + Checks the number of processes running on your GPUs. + + Parameters + ---------- + max_procs : int + Maximum number of procs allowed to run on a gpu for it to be considered + 'available' + + Returns + ------- + availabilities : list(bool) + List of length N for an N-gpu system. The nth value will be true, if the + nth gpu had at most max_procs processes running on it. Set to 0 to look + for gpus with no procs on it. + + Note + ---- + If function can't query the driver will return an empty list rather than raise an + Exception. """ # Try connect with NVIDIA drivers logger = logging.getLogger(__name__) @@ -203,12 +219,19 @@ def get_free_gpus(max_procs=0): def get_num_procs(): """ Gets the number of processes running on each gpu - Returns: - List(int): Number of processes running on each gpu + Returns + ------- + num_procs : list(int) + Number of processes running on each gpu + + Note + ---- + If function can't query the driver will return an empty list rather than raise an + Exception. - Note: - If couldn't query the driver will return an empty list. - If couldn't get the info from the gpu will return -1 in that gpu's place + Note + ---- + If function can't get the info from the gpu will return -1 in that gpu's place """ # Try connect with NVIDIA drivers logger = logging.getLogger(__name__)
Updated docstrings for new util functions
fbcotter_py3nvml
train
90e6a4b94acb90c67f6f3b240dcb9c5b29d0f3e3
diff --git a/subliminal/core.py b/subliminal/core.py index <HASH>..<HASH> 100644 --- a/subliminal/core.py +++ b/subliminal/core.py @@ -160,7 +160,7 @@ class Subliminal(object): if not wanted_languages: logger.debug(u'No need to list multi subtitles %r for %r because %r subtitles detected' % (self._languages, video.path, languages)) continue - if not self.force and not self.multi and has_single: + if not self.force and not self.multi and None in [s.language for s in subtitles]: logger.debug(u'No need to list single subtitles %r for %r because one detected' % (self._languages, video.path)) continue logger.debug(u'Listing subtitles %r for %r with %r' % (wanted_languages, video.path, self._plugins))
Fix core.py for single srt detection
Diaoul_subliminal
train
a9d3a617c7216f8a414c9cdd2a40757bfcdf29a5
diff --git a/src/Routing/DispatcherFactory.php b/src/Routing/DispatcherFactory.php index <HASH>..<HASH> 100644 --- a/src/Routing/DispatcherFactory.php +++ b/src/Routing/DispatcherFactory.php @@ -40,11 +40,13 @@ class DispatcherFactory { * * @param string|\Cake\Routing\DispatcherFilter $filter Either the classname of the filter * or an instance to use. + * @param array $options Constructor arguments/options for the filter if you are using a string name. + * If you are passing an instance, this argument will be ignored. * @return \Cake\Routing\DispatcherFilter */ - public static function add($filter) { + public static function add($filter, array $options = []) { if (is_string($filter)) { - $filter = static::_createFilter($filter); + $filter = static::_createFilter($filter, $options); } static::$_stack[] = $filter; return $filter; @@ -54,16 +56,17 @@ class DispatcherFactory { * Create an instance of a filter. * * @param string $name The name of the filter to build. + * @param array $options Constructor arguments/options for the filter. * @return \Cake\Routing\DispatcherFilter * @throws \Cake\Routing\Error\MissingDispatcherFilterException When filters cannot be found. */ - protected static function _createFilter($name) { + protected static function _createFilter($name, $options) { $className = App::className($name, 'Routing/Filter', 'Filter'); if (!$className) { $msg = sprintf('Cannot locate dispatcher filter named "%s".', $name); throw new MissingDispatcherFilterException($msg); } - return new $className(); + return new $className($options); } /** diff --git a/tests/TestCase/Routing/DispatcherFactoryTest.php b/tests/TestCase/Routing/DispatcherFactoryTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/Routing/DispatcherFactoryTest.php +++ b/tests/TestCase/Routing/DispatcherFactoryTest.php @@ -64,6 +64,19 @@ class DispatcherFactoryTest extends TestCase { } /** + * Test add filter + * + * @return void + */ + public function testAddFilterWithOptions() { + $config = ['config' => 'value', 'priority' => 999]; + $result = DispatcherFactory::add('Routing', $config); + $this->assertInstanceOf('Cake\Routing\Filter\RoutingFilter', $result); + $this->assertEquals($config['config'], $result->config('config')); + $this->assertEquals($config['priority'], $result->config('priority')); + } + +/** * Test creating a dispatcher with the factory * * @return void
Allow an array of options to be passed into a dispatcher filter. When using the string form, it is handy to be able to control the constructor arguments as well.
cakephp_cakephp
train
658bbb0ab9a6564f815052da118277ffea277162
diff --git a/lib/bcsec/authorities/composite.rb b/lib/bcsec/authorities/composite.rb index <HASH>..<HASH> 100644 --- a/lib/bcsec/authorities/composite.rb +++ b/lib/bcsec/authorities/composite.rb @@ -219,10 +219,10 @@ module Bcsec::Authorities ## # Finds users matching the given criteria. Criteria may either be - # a `String` or a `Hash`. If it's a `String`, it is interpreted - # as a username and this method will return an array containing - # either a single user with that username or an empty array. If - # the criteria is a `Hash`, the behavior will be + # `String`s or `Hash`es. If it's a single `String`, it is + # interpreted as a username and this method will return an array + # containing either a single user with that username or an empty + # array. If the criteria is a `Hash`, the behavior will be # authority-dependent. However, all the attributes of # {Bcsec::User} are reserved parameter names &mdash; if an # authority interprets the value associated with a {Bcsec::User} @@ -230,12 +230,28 @@ module Bcsec::Authorities # criteria for that authority's understanding of that attribute # (whatever it is). # + # If more than one criterion is provided, each value is treated + # separately according to the description given above for a single + # value. The resulting array will contain each matching user + # exactly once. It will not be possible to determine from the + # results alone which returned user matched which criterion. + # # Examples: # # authority.find_users("wakibbe") # => that single user, if # # the username is known # authority.find_users(:first_name => 'Warren') - # # => all the users named Warren + # # => all the users named + # # Warren + # authority.find_users( + # :first_name => 'Warren', :last_name => 'Kibbe') + # # => all the users named + # # Warren Kibbe + # authority.find_users( + # { :first_name => 'Warren' }, { :last_name => 'Kibbe' }) + # # => all the users with + # # first name Warren or + # # last name Kibbe # # The composite behavior is to invoke `find_users` on all the # authorities which support it and merge the resulting lists. Any @@ -245,10 +261,10 @@ module Bcsec::Authorities # # This method will always return an array. # - # @param [Hash,#to_s] criteria (see above) + # @param [Array<Hash,#to_s>] criteria (see above) # # @return [Array<Bcsec::User>] the matching users - def find_users(criteria) + def find_users(*criteria) poll(:find_users, criteria). collect { |result, authority| result }. compact.
Update composite #find_users docs to reflect desired additional behavior. #<I>.
NUBIC_aker
train
1fe980dc98728a94ddc0982bfa07c98771ac84e4
diff --git a/nptdms/tdms.py b/nptdms/tdms.py index <HASH>..<HASH> 100644 --- a/nptdms/tdms.py +++ b/nptdms/tdms.py @@ -467,8 +467,8 @@ class _TdmsSegment(object): for obj in self.ordered_objects: if obj.has_data: obj.tdms_object.number_values += ( - obj.number_values * (self.num_chunks - 1) - + int(obj.number_values * self.final_chunk_proportion)) + obj.number_values * (self.num_chunks - 1) + int( + obj.number_values * self.final_chunk_proportion)) def read_raw_data(self, f): """Read signal data from file""" @@ -693,8 +693,8 @@ class TdmsObject(object): # Because numpy only knows ints as its date datatype, # convert to accuracy. time_type = "timedelta64[{0}]".format(accuracy) - return (np.datetime64(start_time) - + (relative_time * unit_correction).astype(time_type)) + return (np.datetime64(start_time) + + (relative_time * unit_correction).astype(time_type)) def _initialise_data(self, memmap_dir=None): """Initialise data array to zeros""" diff --git a/nptdms/types.py b/nptdms/types.py index <HASH>..<HASH> 100644 --- a/nptdms/types.py +++ b/nptdms/types.py @@ -211,8 +211,8 @@ class TimeStamp(TdmsType): float(second_fractions) / cls._fractions_per_microsecond) # Adding timedelta with seconds ignores leap # seconds, so this is correct - return (cls._tdms_epoch + timedelta(seconds=seconds) - + timedelta(microseconds=micro_seconds)) + return (cls._tdms_epoch + timedelta(seconds=seconds) + + timedelta(microseconds=micro_seconds)) @tds_data_type(0xFFFFFFFF, np.int16)
Fix pep8 problems raised by new version of pep8
adamreeve_npTDMS
train
069d5eae2dc9e9eb0f96f1e63926968bb52a260d
diff --git a/code/model/TrackedManyManyList.php b/code/model/TrackedManyManyList.php index <HASH>..<HASH> 100644 --- a/code/model/TrackedManyManyList.php +++ b/code/model/TrackedManyManyList.php @@ -34,7 +34,7 @@ class TrackedManyManyList extends ManyManyList if (class_exists($addingToClass)) { $onItem = $addingToClass::get()->byID($addingTo); if ($onItem) { - if ($item && !$item instanceof DataObject) { + if ($item && !($item instanceof DataObject)) { $class = $this->dataClass; $item = $class::get()->byID($item); }
style(TrackedManyManyList): Add brackets around instanceof check
symbiote_silverstripe-datachange-tracker
train
d5b12419722feeddc207ebd96a9429dea462f486
diff --git a/tests/unit/modules/test_tls.py b/tests/unit/modules/test_tls.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/test_tls.py +++ b/tests/unit/modules/test_tls.py @@ -292,6 +292,15 @@ class TLSAddTestCase(TestCase, LoaderModuleMockMixin): err ) ) + # python-openssl version 0.14, when installed with the "junos-eznc" pip + # package, causes an error on this test. Newer versions of PyOpenSSL do not have + # this issue. If 0.14 is installed and we hit this error, skip the test. + if LooseVersion(OpenSSL.__version__) == LooseVersion('0.14'): + log.exception(err) + self.skipTest( + 'Encountered a package conflict. OpenSSL version 0.14 cannot be used with ' + 'the "junos-eznc" pip package on this test. Skipping.' + ) result = {} remove_not_in_result(ret, result)
Skip tsl unit test when we hit an error due to OpenSSL and junos-eznc packaging conflict he pip junos-eznc package, when installed with PyOpenSSL version <I> causes this test failure. If you either remove junos-eznc, or upgrade PyOpenSSL (current is <I>) the test is happy. So, we need to handle this case in the test.
saltstack_salt
train
2cbbbc9b1acff6a6ab7f41fe8d46043503e2898c
diff --git a/health-check.rb b/health-check.rb index <HASH>..<HASH> 100755 --- a/health-check.rb +++ b/health-check.rb @@ -12,7 +12,9 @@ whitelist_libs = [ /librt\.so/, /libutil\.so/, /libgcc_s\.so/, - /libstdc\+\+\.so/ + /libstdc\+\+\.so/, + /libnsl\.so/, + /libfreebl\d\.so/ ] ldd_output = `find /opt/opscode -name '*.so' | xargs ldd`
updated health-check from clojure omnibus
chef_omnibus
train
d48e16255a7bf2452a0452bd6d050513ff56ed50
diff --git a/rapidoid-commons/src/main/java/org/rapidoid/env/EnvMode.java b/rapidoid-commons/src/main/java/org/rapidoid/env/EnvMode.java index <HASH>..<HASH> 100644 --- a/rapidoid-commons/src/main/java/org/rapidoid/env/EnvMode.java +++ b/rapidoid-commons/src/main/java/org/rapidoid/env/EnvMode.java @@ -27,6 +27,6 @@ import org.rapidoid.annotation.Since; @Since("5.2.0") public enum EnvMode { - DEV, TEST, PRODUCTION; + DEV, TEST, PRODUCTION } diff --git a/rapidoid-platform/src/main/java/org/rapidoid/deploy/AppDeployer.java b/rapidoid-platform/src/main/java/org/rapidoid/deploy/AppDeployer.java index <HASH>..<HASH> 100644 --- a/rapidoid-platform/src/main/java/org/rapidoid/deploy/AppDeployer.java +++ b/rapidoid-platform/src/main/java/org/rapidoid/deploy/AppDeployer.java @@ -3,6 +3,7 @@ package org.rapidoid.deploy; import org.rapidoid.RapidoidThing; import org.rapidoid.annotation.Authors; import org.rapidoid.annotation.Since; +import org.rapidoid.env.Env; import org.rapidoid.io.IO; import org.rapidoid.log.Log; import org.rapidoid.process.Proc; @@ -59,7 +60,14 @@ public class AppDeployer extends RapidoidThing { String appJar = Msc.mainAppJar(); String[] appJarCmd = {"java", "-jar", appJar, "root=/app"}; - String[] defaultAppCmd = {"java", "-cp", CLASSPATH, "org.rapidoid.platform.DefaultApp", "root=/app"}; + + String[] defaultAppCmd = { + "java", + "-cp", CLASSPATH, + "org.rapidoid.platform.DefaultApp", + "root=/app", + "mode=" + Env.mode().name().toLowerCase() + }; String[] cmd = new File(appJar).exists() ? appJarCmd : defaultAppCmd;
Passing the env mode to the child processes.
rapidoid_rapidoid
train
9fce1bc430c18472ae47394ff232fd6092ae854e
diff --git a/codenerix/models_people.py b/codenerix/models_people.py index <HASH>..<HASH> 100644 --- a/codenerix/models_people.py +++ b/codenerix/models_people.py @@ -25,6 +25,7 @@ from functools import reduce from django.db.models import Q from django.db import models +from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import smart_text from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User, Group, Permission @@ -77,7 +78,7 @@ class GenPerson(GenLog, models.Model): # META: Abstract class return fields def __limitQ__(self, info): - l = {} + limit = {} # If user is not a superuser, the shown records depends on the profile if not info.request.user.is_superuser: @@ -86,9 +87,9 @@ class GenPerson(GenLog, models.Model): # META: Abstract class # The criterials are not exclusives if criterials: - l["profile_people_limit"] = reduce(operator.or_, criterials) + limit["profile_people_limit"] = reduce(operator.or_, criterials) - return l + return limit def __searchF__(self, info): tf = {} @@ -114,13 +115,13 @@ class GenPerson(GenLog, models.Model): # META: Abstract class ''' return the rolls this people is related with ''' - l = [] + limit = [] if self.is_admin(): - l.append(_("Administrator")) - l.sort() + limit.append(_("Administrator")) + limit.sort() - return l + return limit def delete(self): self.clean_memcache() @@ -269,8 +270,8 @@ class GenPerson(GenLog, models.Model): # META: Abstract class # Remember perms for this group if groupname not in groupsresult: - groupsresult[groupname]=[] - groupsresult[groupname]+=perms + groupsresult[groupname] = [] + groupsresult[groupname] += perms # Set permissions for all groups for groupname in groupsresult: @@ -314,6 +315,14 @@ class GenRole(object): for field in self._meta.get_fields(): model = field.related_model if model and issubclass(model, GenPerson): - person = getattr(self, field.name) + try: + person = getattr(self, field.name) + except ObjectDoesNotExist: + pass break return person + + def CDNX_refresh_permissions_CDNX(self): + person = self.__CDNX_search_person_CDNX__() + if person: + person.refresh_permissions()
Refresh permission of GenRole
codenerix_django-codenerix
train
927cf9180e30072f8241f42d39b29dfae72f4831
diff --git a/lib/socket.js b/lib/socket.js index <HASH>..<HASH> 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -19,11 +19,14 @@ module.exports = function makeSocketFactory (emitter, requestMeteorProcess) { socketPort = meteorProcess.gagarinPort; - socketPromise = new Promise(function (resolve, reject) { + socketPromise = new Promise(function (resolve) { + // XXX note that we do not reject explicitly socket && socket.destroy(); socket = net.createConnection(socketPort, function () { - resolve(socket); + resolve(function transmit (payload, callback) { + socket.write(JSON.stringify(payload) + '\n', callback); + }); }); //--------------- PARSE RESPONSE FROM SERVER ------------------ diff --git a/lib/transponder.js b/lib/transponder.js index <HASH>..<HASH> 100644 --- a/lib/transponder.js +++ b/lib/transponder.js @@ -22,14 +22,14 @@ function MeteorTransponder(requestMeteorProcess, options) { args = Array.isArray(args) ? args : [ args ]; } - //----------------------------------------------- - return socketAsPromise().then(function (socket) { - socket.write(JSON.stringify({ + //------------------------------------------------- + return socketAsPromise().then(function (transmit) { + transmit({ code: code.toString(), mode: mode, name: name, args: args, - }) + '\n', function () { + }, function (err) { // do we need this callback (?) }); return new Promise(function (resolve, reject) { @@ -51,16 +51,16 @@ function MeteorTransponder(requestMeteorProcess, options) { args = Array.isArray(args) ? args : [ args ]; } - //----------------------------------------------- - return socketAsPromise().then(function (socket) { - socket.write(JSON.stringify({ + //------------------------------------------------- + return socketAsPromise().then(function (transmit) { + transmit({ code: code.toString(), mode: 'wait', name: name, args: args, time: timeout, mesg: message, - }) + '\n', function () { + }, function (err) { // do we need this callback (?) }); return new Promise(function (resolve, reject) {
Add a level of abstraction to hide transmit protocol implementation
anticoders_gagarin
train
bf1e41a9f286cf93aee7a5a7d2d7c73e45674a9d
diff --git a/docs/storage/driver/gcs/gcs.go b/docs/storage/driver/gcs/gcs.go index <HASH>..<HASH> 100644 --- a/docs/storage/driver/gcs/gcs.go +++ b/docs/storage/driver/gcs/gcs.go @@ -318,13 +318,13 @@ func retry(maxTries int, req request) error { backoff := time.Second var err error for i := 0; i < maxTries; i++ { - err := req() + err = req() if err == nil { return nil } - status := err.(*googleapi.Error) - if status == nil || (status.Code != 429 && status.Code < http.StatusInternalServerError) { + status, ok := err.(*googleapi.Error) + if !ok || (status.Code != 429 && status.Code < http.StatusInternalServerError) { return err } diff --git a/docs/storage/driver/gcs/gcs_test.go b/docs/storage/driver/gcs/gcs_test.go index <HASH>..<HASH> 100644 --- a/docs/storage/driver/gcs/gcs_test.go +++ b/docs/storage/driver/gcs/gcs_test.go @@ -3,10 +3,13 @@ package gcs import ( + "fmt" "io/ioutil" "os" "testing" + "google.golang.org/api/googleapi" + ctx "github.com/docker/distribution/context" storagedriver "github.com/docker/distribution/registry/storage/driver" "github.com/docker/distribution/registry/storage/driver/testsuites" @@ -55,6 +58,43 @@ func init() { }, skipGCS) } +func TestRetry(t *testing.T) { + if skipGCS() != "" { + t.Skip(skipGCS()) + } + + assertError := func(expected string, observed error) { + observedMsg := "<nil>" + if observed != nil { + observedMsg = observed.Error() + } + if observedMsg != expected { + t.Fatalf("expected %v, observed %v\n", expected, observedMsg) + } + } + + err := retry(2, func() error { + return &googleapi.Error{ + Code: 503, + Message: "google api error", + } + }) + assertError("googleapi: Error 503: google api error", err) + + err = retry(2, func() error { + return &googleapi.Error{ + Code: 404, + Message: "google api error", + } + }) + assertError("googleapi: Error 404: google api error", err) + + err = retry(2, func() error { + return fmt.Errorf("error") + }) + assertError("error", err) +} + func TestEmptyRootList(t *testing.T) { if skipGCS() != "" { t.Skip(skipGCS())
GCS driver: fix retry function
docker_distribution
train
e1d5c7ccb2901381e0b137972d109d958971670d
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ * Added `Time::getImmutable()` method. * Added `Redis::subscribeTo()` method. * Added `Redis::subscribeToPattern()` method. +* Added `Redis::monitor()` method. -------------------------------------------------------- diff --git a/src/mako/redis/Redis.php b/src/mako/redis/Redis.php index <HASH>..<HASH> 100644 --- a/src/mako/redis/Redis.php +++ b/src/mako/redis/Redis.php @@ -631,6 +631,26 @@ class Redis } /** + * Monitors the redis server. + * + * @param \Closure $monitor Monitor closure + */ + public function monitor(Closure $monitor): void + { + $this->sendCommandAndGetResponse($this->buildCommand('monitor')); + + while(true) + { + if($monitor($this->getResponse()) === false) + { + break; + } + } + + $this->sendCommandAndGetResponse($this->buildCommand('quit')); + } + + /** * Pipeline commands. * * @param \Closure $pipeline Pipelined commands diff --git a/tests/unit/redis/RedisTest.php b/tests/unit/redis/RedisTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/redis/RedisTest.php +++ b/tests/unit/redis/RedisTest.php @@ -395,4 +395,39 @@ class RedisTest extends TestCase return false; }, ['pmessage', 'psubscribe']); } + + /** + * + */ + public function testMonitor(): void + { + $connection = Mockery::mock(Connection::class); + + $redis = new Redis($connection); + + $connection->shouldReceive('write')->once()->with("*1\r\n$7\r\nMONITOR\r\n"); + + $connection->shouldReceive('readLine')->once()->andReturn("+OK\r\n"); + + // + + $connection->shouldReceive('readLine')->once()->andReturn("$6\r\n"); + + $connection->shouldReceive('read')->once()->andReturn("foobar\r\n"); + + // + + $connection->shouldReceive('write')->once()->with("*1\r\n$4\r\nQUIT\r\n"); + + $connection->shouldReceive('readLine')->once()->andReturn("+OK\r\n"); + + // + + $redis->monitor(function($line) + { + $this->assertSame('foobar', $line); + + return false; + }); + } }
Added Redis::monitor() method
mako-framework_framework
train
ae006e1b9388c5a5e8101a16126df7511e7da229
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -37,7 +37,7 @@ const displayFailure = function (component, failureInfo, options = {}, done) { const { tagName , msg - , ref + , refs } = failureInfo if (includeSrcNode && component) { @@ -45,7 +45,8 @@ const displayFailure = function (component, failureInfo, options = {}, done) { // Cannot log a node reference until the component is in the DOM, // so defer the call until componentDidMount or componentDidUpdate. after.render(instance, function () { - const srcNode = _ReactDOM.findDOMNode(instance.refs[ref]) + // unpack the ref + const srcNode = refs.node if (includeSrcNode === "asString") { return done(tagName, msg, `Source Node: ${srcNode.outerHTML}`) @@ -58,7 +59,7 @@ const displayFailure = function (component, failureInfo, options = {}, done) { } } -const failureHandler = (options = {}, reactEl) => function (type, props, failureMsg) { +const failureHandler = (options = {}, reactEl, refs) => function (type, props, failureMsg) { const { includeSrcNode = false , throw: doThrow = false @@ -76,7 +77,7 @@ const failureHandler = (options = {}, reactEl) => function (type, props, failure const failureInfo = { tagName , msg: warningPrefix.concat(failureMsg) - , ref: props.ref + , refs } const opts = { @@ -117,14 +118,19 @@ const reactA11y = function (React, options = {}) { assertions.setReact(_React, _ReactDOM) // replace createElement with our overloaded version - _React.createElement = function (type, props = {}, ...children) { - - // add a ref when the component is a DOM component (eg. div) - const ref = createRef(props) + _React.createElement = function (type, _props = {}, ...children) { + // fix for props = null + const props = _props || {} + + // create a refs object to hold the ref. + // this needs to be an object so that it can be passed + // by reference, and hold chaning state + const refs = {} + const ref = node => refs.node = node const newProps = typeof type === 'string' ? { ...props, ref } : props const reactEl = _createElement(type, newProps, ...children) - const handler = failureHandler(options, reactEl) + const handler = failureHandler(options, reactEl, refs) // only test html elements if (typeof type === 'string') {
use different mechanism of storing refs, so root-level DOM elements will work
reactjs_react-a11y
train
7ab0a491e7f155299d25993fb84504c39ca7268d
diff --git a/src/com/google/javascript/jscomp/newtypes/FunctionType.java b/src/com/google/javascript/jscomp/newtypes/FunctionType.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/newtypes/FunctionType.java +++ b/src/com/google/javascript/jscomp/newtypes/FunctionType.java @@ -734,15 +734,25 @@ public final class FunctionType { for (int i = 0; i < maxNonInfiniteArity; i++) { JSType thisFormal = getFormalType(i); JSType otherFormal = other.getFormalType(i); + // NOTE(dimvar): The correct handling here would be to implement + // unifyWithSupertype for JSType, ObjectType, etc, to handle the + // contravariance here. + // But it's probably an overkill to do, so instead we just do a subtype + // check if unification fails. Same for restFormals. + // Altenatively, maybe the unifyWith function could handle both subtype + // and supertype, and we'd catch type errors as invalid-argument-type + // after unification. (Not sure this is correct, I'd have to try it.) if (otherFormal != null - && !thisFormal.unifyWithSubtype(otherFormal, typeParameters, typeMultimap)) { + && !thisFormal.unifyWithSubtype(otherFormal, typeParameters, typeMultimap) + && !thisFormal.isSubtypeOf(otherFormal)) { return false; } } if (this.restFormals != null) { JSType otherRestFormals = other.getFormalType(maxNonInfiniteArity); if (otherRestFormals != null - && !this.restFormals.unifyWithSubtype(otherRestFormals, typeParameters, typeMultimap)) { + && !this.restFormals.unifyWithSubtype(otherRestFormals, typeParameters, typeMultimap) + && !this.restFormals.isSubtypeOf(otherRestFormals)) { return false; } } @@ -764,7 +774,7 @@ public final class FunctionType { return false; } - return returnType.unifyWithSubtype(other.returnType, typeParameters, typeMultimap); + return this.returnType.unifyWithSubtype(other.returnType, typeParameters, typeMultimap); } private static FunctionType instantiateGenericsWithUnknown(FunctionType f) { diff --git a/test/com/google/javascript/jscomp/NewTypeInferenceES5OrLowerTest.java b/test/com/google/javascript/jscomp/NewTypeInferenceES5OrLowerTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/NewTypeInferenceES5OrLowerTest.java +++ b/test/com/google/javascript/jscomp/NewTypeInferenceES5OrLowerTest.java @@ -14389,4 +14389,60 @@ public final class NewTypeInferenceES5OrLowerTest extends NewTypeInferenceTestBa "g({bar:1});"), NewTypeInference.INVALID_ARGUMENT_TYPE); } + + public void testFunctionUnificationWithSubtyping() { + typeCheck(LINE_JOINER.join( + "/**", + " * @template T", + " * @param {function(number,T)} x", + " */", + "function g(x) {}", + "function h(/** number|string */ x, /** number */ y) {}", + "g(h);")); + + typeCheck(LINE_JOINER.join( + "/**", + " * @template T", + " * @param {function(T, ...number)} x", + " */", + "function g(x) {}", + "/** @type {function(string, ...(number|string))} */", + "function h(x, var_args) {}", + "g(h);")); + + typeCheck(LINE_JOINER.join( + "/**", + " * @template T", + " * @param {function(T):(number|string)} x", + " */", + "function g(x) {}", + "/** @type {function(string):string} */", + "function h(x) { return x; }", + "g(h);")); + + // This could unify without warnings; we'd have to implement + // a unifyWithSupertype function. + // Overkill for now. + typeCheck(LINE_JOINER.join( + "/**", + " * @constructor", + " * @template T", + " */", + "function Parent() {}", + "/**", + " * @constructor", + " * @template T", + " * @extends {Parent<T>}", + " */", + "function Child() {}", + "/**", + " * @template T", + " * @param {function(!Child<T>)} x", + " */", + "function g(x) {}", + "/** @type {function(!Parent<number>)} */", + "function h(x) {}", + "g(h);"), + NewTypeInference.FAILED_TO_UNIFY); + } }
[NTI] Take function subtyping into account when doing unification. ------------- Created by MOE: <URL>
google_closure-compiler
train
4936d85a30b8867a7583491e781c03a617dda12e
diff --git a/owner/src/main/java/org/aeonbits/owner/ConfigCache.java b/owner/src/main/java/org/aeonbits/owner/ConfigCache.java index <HASH>..<HASH> 100644 --- a/owner/src/main/java/org/aeonbits/owner/ConfigCache.java +++ b/owner/src/main/java/org/aeonbits/owner/ConfigCache.java @@ -96,6 +96,7 @@ public final class ConfigCache { * @param <T> type of the interface. * @return the {@link Config} object from the cache if exists, or <tt>null</tt> if it doesn't. */ + @SuppressWarnings("unchecked") public static <T extends Config> T get(Object key) { return (T) CACHE.get(key); } @@ -109,6 +110,7 @@ public final class ConfigCache { * @return the previous value associated with the specified key, or * <tt>null</tt> if there was no mapping for the key. */ + @SuppressWarnings("unchecked") public static <T extends Config> T add(Object key, T instance) { return (T) CACHE.putIfAbsent(key, instance); } @@ -134,6 +136,7 @@ public final class ConfigCache { * @return the previous instance associated with <tt>key</tt>, or * <tt>null</tt> if there was no instance for <tt>key</tt>. */ + @SuppressWarnings("unchecked") public static <T extends Config> T remove(Object key) { return (T) CACHE.remove(key); }
added @SuppressWarnings where required.
lviggiano_owner
train
9bbf12d392278de33652973e76fe12a02fe4fa05
diff --git a/spec/sanity_spec.rb b/spec/sanity_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sanity_spec.rb +++ b/spec/sanity_spec.rb @@ -42,6 +42,13 @@ describe "asciidoctor integration" do publisher = {Publisher}, year = {2000} } + + @article{Qux00, + author = {Qux Zot}, + title = {Title}, + publisher = {Publisher}, + year = {3000} + } BIBTEX describe "testing procedure" do @@ -117,4 +124,92 @@ describe "asciidoctor integration" do BODY end end + + describe "multiple bibliographies usage" do + it "works with a single file and multiple bibliographies" do + setup_file tmpdir, "nested.adoc", <<~ADOC + This is content from a nested file. cite:[Foo00] + + bibliography::[] + ADOC + + input_path, output_path = setup_main_document tmpdir, <<~ADOC + :bibliography-database: #{bibliography_path} + + ## Citations + + cite:[Foo00] + + cite:first[Qux00] + + cite:first[Foo00]+last[Qux00] + + ## Bibliographies + + ### Default + + bibliography::[] + + ### First + + bibliography::first[] + + ### Last + + bibliography::last[] + ADOC + + expect { `asciidoctor -r asciidoctor-bibliography #{input_path} --trace` }.to_not raise_exception + expect(File.read(output_path)).to include <<~'BODY' + <div id="content"> + <div class="sect1"> + <h2 id="_citations">Citations</h2> + <div class="sectionbody"> + <div class="paragraph"> + <p>(<a href="#bibliography-default-Foo00">Bar, 2000</a>)</p> + </div> + <div class="paragraph"> + <p>(<a href="#bibliography-first-Qux00">Zot, 3000</a>)</p> + </div> + <div class="paragraph"> + <p>(<a href="#bibliography-first-Foo00">Bar, 2000</a>; <a href="#bibliography-last-Qux00">Zot, 3000</a>)</p> + </div> + </div> + </div> + <div class="sect1"> + <h2 id="_bibliographies">Bibliographies</h2> + <div class="sectionbody"> + <div class="sect2"> + <h3 id="_default">Default</h3> + <div class="paragraph"> + <p><a id="bibliography-default-Foo00"></a>Bar, F. (2000). Title.</p> + </div> + <div class="paragraph"> + <p><a id="bibliography-default-Qux00"></a>Zot, Q. (3000). Title.</p> + </div> + </div> + <div class="sect2"> + <h3 id="_first">First</h3> + <div class="paragraph"> + <p><a id="bibliography-first-Foo00"></a>Bar, F. (2000). Title.</p> + </div> + <div class="paragraph"> + <p><a id="bibliography-first-Qux00"></a>Zot, Q. (3000). Title.</p> + </div> + </div> + <div class="sect2"> + <h3 id="_last">Last</h3> + <div class="paragraph"> + <p><a id="bibliography-last-Foo00"></a>Bar, F. (2000). Title.</p> + </div> + <div class="paragraph"> + <p><a id="bibliography-last-Qux00"></a>Zot, Q. (3000). Title.</p> + </div> + </div> + </div> + </div> + </div> + BODY + end + end end
add spec for targeted bibs
riboseinc_asciidoctor-bibliography
train
1ff2fce25b5beeff50c9f312a32785c6cc6f0018
diff --git a/oauthproxy.go b/oauthproxy.go index <HASH>..<HASH> 100644 --- a/oauthproxy.go +++ b/oauthproxy.go @@ -197,8 +197,8 @@ func (p *OauthProxy) redeemCode(host, code string) (s *providers.SessionState, e if code == "" { return nil, errors.New("missing code") } - redirectUri := p.GetRedirectURI(host) - s, err = p.provider.Redeem(redirectUri, code) + redirectURI := p.GetRedirectURI(host) + s, err = p.provider.Redeem(redirectURI, code) if err != nil { return }
oauthproxy: rename Uri to URI Be consistent with Go coding style for acroynyms.
bitly_oauth2_proxy
train
80788474e0256fa5aa230e327cb911766c5de542
diff --git a/lib/fluent/mixin.rb b/lib/fluent/mixin.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/mixin.rb +++ b/lib/fluent/mixin.rb @@ -17,6 +17,7 @@ module Fluent class TimeFormatter require 'fluent/timezone' + require 'fluent/time' def initialize(format, localtime, timezone = nil) @tc1 = 0 @@ -55,9 +56,9 @@ module Fluent end def format(time) - if @tc1 == time + if Fluent::NanoTime.eq?(@tc1, time) return @tc1_str - elsif @tc2 == time + elsif Fluent::NanoTime.eq?(@tc2, time) return @tc2_str else str = format_nocache(time) diff --git a/lib/fluent/time.rb b/lib/fluent/time.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/time.rb +++ b/lib/fluent/time.rb @@ -61,6 +61,14 @@ module Fluent from_time(Time.now) end + def self.eq?(a, b) + if a.is_a?(Fluent::NanoTime) && b.is_a?(Fluent::NanoTime) + a.sec == b.sec && a.nsec == b.nsec + else + a == b + end + end + ## TODO: For performance, implement +, -, and so on def method_missing(name, *args, &block) @sec.send(name, *args, &block)
TimeFormatter cache time as NanoTime if possible
fluent_fluentd
train
3e2d12e2f8685e3042f0e5844b2088e8e4c1a13e
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -80,7 +80,7 @@ setup(name = 'pefile', author = _read_attr('__author__'), author_email = _read_attr('__contact__'), url = 'https://github.com/erocarrera/pefile', - download_url='https://github.com/erocarrera/pefile/releases/download/v2016.3.4/pefile-2016.3.4.tar.gz', + download_url='https://github.com/erocarrera/pefile/releases/download/v2016.3.28/pefile-2016.3.28.tar.gz', keywords = ['pe', 'exe', 'dll', 'pefile', 'pecoff'], classifiers = [ 'Development Status :: 5 - Production/Stable',
Updated links in setup.py
erocarrera_pefile
train
842fd4b23e2f58accd4e74a53fb557438f8b4131
diff --git a/src/cf/commands/application/helpers_test.go b/src/cf/commands/application/helpers_test.go index <HASH>..<HASH> 100644 --- a/src/cf/commands/application/helpers_test.go +++ b/src/cf/commands/application/helpers_test.go @@ -10,6 +10,10 @@ import ( "time" ) +func TestTimestampFormat(t *testing.T) { + assert.Equal(t,TIMESTAMP_FORMAT,"2006-01-02T15:04:05.00-0700") +} + func TestLogMessageOutput(t *testing.T) { cloud_controller := logmessage.LogMessage_CLOUD_CONTROLLER router := logmessage.LogMessage_ROUTER @@ -20,12 +24,10 @@ func TestLogMessageOutput(t *testing.T) { stdout := logmessage.LogMessage_OUT stderr := logmessage.LogMessage_ERR - date := "2013 Sep 20 09:33:30 PDT" - logTime, err := time.Parse("2006 Jan 2 15:04:05 MST", date) - assert.NoError(t, err) - timestamp := logTime.UnixNano() - expectedTZ := logTime.Format("-0700") + + date := time.Now() + timestamp := date.UnixNano() sourceId := "0" @@ -38,43 +40,43 @@ func TestLogMessageOutput(t *testing.T) { } msg := createMessage(t, protoMessage, &cloud_controller, &stdout) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [API]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [API]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStdoutColor("OUT Hello World!")) msg = createMessage(t, protoMessage, &cloud_controller, &stderr) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [API]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [API]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStderrColor("ERR Hello World!")) sourceId = "1" msg = createMessage(t, protoMessage, &router, &stdout) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [RTR]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [RTR]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStdoutColor("OUT Hello World!")) msg = createMessage(t, protoMessage, &router, &stderr) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [RTR]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [RTR]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStderrColor("ERR Hello World!")) sourceId = "2" msg = createMessage(t, protoMessage, &uaa, &stdout) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [UAA]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [UAA]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStdoutColor("OUT Hello World!")) msg = createMessage(t, protoMessage, &uaa, &stderr) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [UAA]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [UAA]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStderrColor("ERR Hello World!")) sourceId = "3" msg = createMessage(t, protoMessage, &dea, &stdout) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [DEA]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [DEA]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStdoutColor("OUT Hello World!")) msg = createMessage(t, protoMessage, &dea, &stderr) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [DEA]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [DEA]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStderrColor("ERR Hello World!")) sourceId = "4" msg = createMessage(t, protoMessage, &wardenContainer, &stdout) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [App/4]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [App/4]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStdoutColor("OUT Hello World!")) msg = createMessage(t, protoMessage, &wardenContainer, &stderr) - assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("2013-09-20T09:33:30.00%s [App/4]", expectedTZ)) + assert.Contains(t, logMessageOutput(msg), fmt.Sprintf("%s [App/4]", date.Format(TIMESTAMP_FORMAT))) assert.Contains(t, logMessageOutput(msg), terminal.LogStderrColor("ERR Hello World!")) }
log format tests work in all timezones
cloudfoundry_cli
train
7b48470f9db006bddabe939ac2e124cc7f8efe0b
diff --git a/mtools/test/test_mlogfilter.py b/mtools/test/test_mlogfilter.py index <HASH>..<HASH> 100644 --- a/mtools/test/test_mlogfilter.py +++ b/mtools/test/test_mlogfilter.py @@ -40,8 +40,6 @@ class TestMLogFilter(object): def test_from(self): random_start = random_date(self.logfile.start, self.logfile.end) - print "random_start", random_start - self.tool.run('%s --from %s'%(self.logfile_path, random_start.strftime("%b %d %H:%M:%S"))) output = sys.stdout.getvalue() for line in output.splitlines(): diff --git a/mtools/util/logline.py b/mtools/util/logline.py index <HASH>..<HASH> 100644 --- a/mtools/util/logline.py +++ b/mtools/util/logline.py @@ -410,11 +410,15 @@ class LogLine(object): if self.datetime_format == None or (self.datetime_format == format and self._datetime_str != '') and not force: return - elif format == 'ctime': - dt_string = self.weekdays[self.datetime.weekday()] + ' ' + self.datetime.strftime("%b %d %H:%M:%S") - dt_string += '.' + str(int(self.datetime.microsecond / 1000)).zfill(3) - elif format == 'ctime-pre2.4': + elif format.startswith('ctime'): dt_string = self.weekdays[self.datetime.weekday()] + ' ' + self.datetime.strftime("%b %d %H:%M:%S") + # remove zero-padding from day number + tokens = dt_string.split(' ') + if tokens[2].startswith('0'): + tokens[2] = tokens[2].replace('0', ' ', 1) + dt_string = ' '.join(tokens) + if format == 'ctime': + dt_string += '.' + str(int(self.datetime.microsecond / 1000)).zfill(3) elif format == 'iso8601-local': dt_string = self.datetime.isoformat() if not self.datetime.utcoffset():
removed debug print out from test_mlogfilter. removed zero-padding from days in ctime format.
rueckstiess_mtools
train
b86b8482bc22a89398606e34b55b0c3f8b3b142e
diff --git a/js/bitbank.js b/js/bitbank.js index <HASH>..<HASH> 100644 --- a/js/bitbank.js +++ b/js/bitbank.js @@ -42,11 +42,9 @@ module.exports = class bitbank extends Exchange { 'fetchPremiumIndexOHLCV': false, 'fetchTicker': true, 'fetchTrades': true, - 'loadLeverageBrackets': false, 'reduceMargin': false, 'setLeverage': false, 'setPositionMode': false, - 'transferOut': false, 'withdraw': true, }, 'timeframes': {
bitbank loadLeverageBrackets and transferOut are not unified
ccxt_ccxt
train
36de2e3381df07ff109d9e73093b67abb39e7394
diff --git a/src/App.php b/src/App.php index <HASH>..<HASH> 100644 --- a/src/App.php +++ b/src/App.php @@ -972,6 +972,7 @@ class App } echo $content; + @flush(); } /**
add flush to force output? cannot recreate locally. just try to solve issue on travis for Callbacks TEST
atk4_ui
train
596d9663efd42247d5d8d17b33f9d09dfa0122c2
diff --git a/src/frontend/org/voltdb/expressions/ExpressionUtil.java b/src/frontend/org/voltdb/expressions/ExpressionUtil.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/expressions/ExpressionUtil.java +++ b/src/frontend/org/voltdb/expressions/ExpressionUtil.java @@ -61,6 +61,7 @@ public final class ExpressionUtil { put("subtract", ExpressionType.OPERATOR_MINUS); put("multiply", ExpressionType.OPERATOR_MULTIPLY); put("divide", ExpressionType.OPERATOR_DIVIDE); + put("is_null", ExpressionType.OPERATOR_IS_NULL); }}; private ExpressionUtil() {} diff --git a/tests/frontend/org/voltdb/TestAdhocMigrateTable.java b/tests/frontend/org/voltdb/TestAdhocMigrateTable.java index <HASH>..<HASH> 100644 --- a/tests/frontend/org/voltdb/TestAdhocMigrateTable.java +++ b/tests/frontend/org/voltdb/TestAdhocMigrateTable.java @@ -76,7 +76,12 @@ public class TestAdhocMigrateTable extends AdhocDDLTestBase { Pair.of("MIGRATE FROM with_ttl WHERE not not migrating;", false), Pair.of("MIGRATE FROM with_ttl WHERE migrating() and j > 0;", false), // we don't prevent user from doing this - Pair.of("MIGRATE FROM with_ttl WHERE not (not migrating);", true) + Pair.of("MIGRATE FROM with_ttl WHERE not (not migrating);", true), + // ENG-16463 + Pair.of("MIGRATE FROM without_ttl where j is not null;", false), + Pair.of("MIGRATE FROM without_ttl where j is null;", false), + Pair.of("MIGRATE FROM without_ttl where j is not null and not migrating;", true), + Pair.of("MIGRATE FROM without_ttl where j is null and not migrating;", true) ).collect(Collectors.toList())); }
ENG-<I> (#<I>)
VoltDB_voltdb
train
e397983e788acc5534fa10e20dab74e9f20dfeae
diff --git a/cmd/swarm-bench/benchmark.go b/cmd/swarm-bench/benchmark.go index <HASH>..<HASH> 100644 --- a/cmd/swarm-bench/benchmark.go +++ b/cmd/swarm-bench/benchmark.go @@ -35,12 +35,12 @@ func NewBenchmark(cfg *Config) *Benchmark { } // Run starts the benchmark session and waits for it to be completed. -func (b *Benchmark) Run() error { +func (b *Benchmark) Run(ctx context.Context) error { fmt.Printf("Listening for incoming connections at %s:%d\n", b.cfg.IP, b.cfg.Port) if err := b.collector.Listen(b.cfg.Port); err != nil { return err } - j, err := b.launch() + j, err := b.launch(ctx) if err != nil { return err } @@ -61,7 +61,7 @@ func (b *Benchmark) Run() error { }() fmt.Println("Collecting metrics...") - b.collector.Collect(b.cfg.Count) + b.collector.Collect(ctx, b.cfg.Count) doneCh <- struct{}{} fmt.Printf("\n%s: Benchmark completed\n", time.Now()) @@ -91,13 +91,13 @@ func (b *Benchmark) spec() *api.ServiceSpec { } } -func (b *Benchmark) launch() (*api.Service, error) { +func (b *Benchmark) launch(ctx context.Context) (*api.Service, error) { conn, err := grpc.Dial(b.cfg.Manager, grpc.WithInsecure()) if err != nil { return nil, err } client := api.NewControlClient(conn) - r, err := client.CreateService(context.Background(), &api.CreateServiceRequest{ + r, err := client.CreateService(ctx, &api.CreateServiceRequest{ Spec: b.spec(), }) if err != nil { diff --git a/cmd/swarm-bench/collector.go b/cmd/swarm-bench/collector.go index <HASH>..<HASH> 100644 --- a/cmd/swarm-bench/collector.go +++ b/cmd/swarm-bench/collector.go @@ -30,12 +30,12 @@ func (c *Collector) Listen(port int) error { } // Collect blocks until `count` tasks phoned home. -func (c *Collector) Collect(count uint64) { +func (c *Collector) Collect(ctx context.Context, count uint64) { start := time.Now() for i := uint64(0); i < count; i++ { conn, err := c.ln.Accept() if err != nil { - log.G(context.Background()).WithError(err).Error("failure accepting connection") + log.G(ctx).WithError(err).Error("failure accepting connection") continue } c.t.UpdateSince(start) diff --git a/cmd/swarm-bench/main.go b/cmd/swarm-bench/main.go index <HASH>..<HASH> 100644 --- a/cmd/swarm-bench/main.go +++ b/cmd/swarm-bench/main.go @@ -6,6 +6,7 @@ import ( "time" "github.com/spf13/cobra" + "golang.org/x/net/context" ) var ( @@ -13,6 +14,7 @@ var ( Use: os.Args[0], Short: "Benchmark swarm", RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.Background() count, err := cmd.Flags().GetUint64("count") if err != nil { return err @@ -40,7 +42,7 @@ var ( Port: port, Unit: time.Second, }) - return b.Run() + return b.Run(ctx) }, } ) diff --git a/cmd/swarmd/main.go b/cmd/swarmd/main.go index <HASH>..<HASH> 100644 --- a/cmd/swarmd/main.go +++ b/cmd/swarmd/main.go @@ -117,8 +117,8 @@ var ( return err } - // Create a context for our GRPC call - ctx, cancel := context.WithCancel(context.Background()) + // Create a cancellable context for our GRPC call + ctx, cancel := context.WithCancel(ctx) defer cancel() client, err := engineapi.NewClient(engineAddr, "", nil, nil) @@ -175,7 +175,7 @@ var ( } }() - return n.Err(context.Background()) + return n.Err(ctx) }, } )
cmd: correctly plumb context in swarmd, swarm-bench The context has been correctly plumbed for future use for cancellation and timeouts. This PR is a little silly but I thought it would be good to show how to do this correctly.
docker_swarmkit
train
8f3965da0a166e4c42f927d55057d12a2001d4af
diff --git a/caspo/console/handlers.py b/caspo/console/handlers.py index <HASH>..<HASH> 100644 --- a/caspo/console/handlers.py +++ b/caspo/console/handlers.py @@ -94,7 +94,7 @@ def analyze(args): from pyzcasp import asp, potassco from caspo import core, analyze, learn, control - clingo = potassco.Clingo(args.clingo) + clingo = component.getUtility(potassco.IClingo) reader = component.getUtility(core.ICsvReader) lines = [] @@ -113,8 +113,8 @@ def analyze(args): point = core.TimePoint(int(args.midas[1])) writer = component.getMultiAdapter((networks, dataset, point), core.ICsvWriter) - writer.write('networks-mse.csv', args.outdir) - + writer.write('networks-mse-len.csv', args.outdir) + behaviors = component.getMultiAdapter((networks, dataset, clingo), analyze.IBooleLogicBehaviorSet) multiwriter = component.getMultiAdapter((behaviors, point), core.IMultiFileWriter) multiwriter.write(['behaviors.csv', 'behaviors-mse-len.csv', 'variances.csv', 'core.csv'], args.outdir) diff --git a/caspo/learn/adapters.py b/caspo/learn/adapters.py index <HASH>..<HASH> 100644 --- a/caspo/learn/adapters.py +++ b/caspo/learn/adapters.py @@ -33,7 +33,7 @@ class Sif2Graph(core.GraphAdapter): line = line.strip() if line: try: - source, rel, target = line.split('\t') + source, rel, target = line.split() sign = int(rel) except Exception, e: raise IOError("Cannot read line %s in SIF file: %s" % (line, str(e))) @@ -242,12 +242,14 @@ class BooleLogicNetworkSet2CsvWriter(object): for network, mse in self.networks.itermses(self.dataset, self.point.time): row = component.getMultiAdapter((network, self._nheader), core.ILogicalMapping) row.mapping["MSE"] = "%.4f" % mse + row.mapping["SIZE"] = len(network) yield row.mapping def write(self, filename, path="./"): self.writer = component.getUtility(core.ICsvWriter) header = list(self._nheader) header.append("MSE") + header.append("SIZE") self.writer.load(self.mses(), header) self.writer.write(filename, path)
Include networks len in caspo analyze
bioasp_caspo
train
cada341678e25083740a934cccddcc8e895a4a57
diff --git a/lib/auth/apiserver.go b/lib/auth/apiserver.go index <HASH>..<HASH> 100644 --- a/lib/auth/apiserver.go +++ b/lib/auth/apiserver.go @@ -2121,6 +2121,7 @@ type upsertRoleRawReq struct { Role json.RawMessage `json:"role"` } +// DELETE IN 7.0 func (s *APIServer) upsertRole(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { var req *upsertRoleRawReq if err := httplib.ReadJSON(r, &req); err != nil { @@ -2140,14 +2141,24 @@ func (s *APIServer) upsertRole(auth ClientI, w http.ResponseWriter, r *http.Requ return message(fmt.Sprintf("'%v' role upserted", role.GetName())), nil } +// DELETE IN 7.0 func (s *APIServer) getRole(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { role, err := auth.GetRole(r.Context(), p.ByName("role")) if err != nil { return nil, trace.Wrap(err) } - return rawMessage(services.MarshalRole(role, services.WithVersion(version), services.PreserveResourceID())) + roleV4, ok := role.(*types.RoleV4) + if !ok { + return nil, trace.BadParameter("unrecognized role version") + } + downgraded, err := downgradeRole(context.Background(), roleV4) + if err != nil { + return nil, trace.Wrap(err) + } + return rawMessage(services.MarshalRole(downgraded, services.WithVersion(version), services.PreserveResourceID())) } +// DELETE IN 7.0 func (s *APIServer) getRoles(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { roles, err := auth.GetRoles(r.Context()) if err != nil { @@ -2155,7 +2166,15 @@ func (s *APIServer) getRoles(auth ClientI, w http.ResponseWriter, r *http.Reques } out := make([]json.RawMessage, len(roles)) for i, role := range roles { - raw, err := services.MarshalRole(role, services.WithVersion(version), services.PreserveResourceID()) + roleV4, ok := role.(*types.RoleV4) + if !ok { + return nil, trace.BadParameter("unrecognized role version") + } + downgraded, err := downgradeRole(r.Context(), roleV4) + if err != nil { + return nil, trace.Wrap(err) + } + raw, err := services.MarshalRole(downgraded, services.WithVersion(version), services.PreserveResourceID()) if err != nil { return nil, trace.Wrap(err) } @@ -2164,6 +2183,7 @@ func (s *APIServer) getRoles(auth ClientI, w http.ResponseWriter, r *http.Reques return out, nil } +// DELETE IN 7.0 func (s *APIServer) deleteRole(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) { role := p.ByName("role") if err := auth.DeleteRole(r.Context(), role); err != nil { diff --git a/lib/auth/grpcserver.go b/lib/auth/grpcserver.go index <HASH>..<HASH> 100644 --- a/lib/auth/grpcserver.go +++ b/lib/auth/grpcserver.go @@ -1382,6 +1382,11 @@ func (g *GRPCServer) DeleteAllKubeServices(ctx context.Context, req *proto.Delet // for V4 roles returns a shallow copy of the given role downgraded to V3. If // the passed in role is already V3, it is returned unmodified. func downgradeRole(ctx context.Context, role *types.RoleV4) (*types.RoleV4, error) { + if role.Version == types.V3 { + // role is already V3, no need to downgrade + return role, nil + } + var clientVersion *semver.Version clientVersionString, ok := metadata.ClientVersionFromContext(ctx) if ok {
Downgrade V4 roles to V3 at webapi endpoints (#<I>)
gravitational_teleport
train
d779e5ffccfc89f79367b37eb7350bf3bddb7d5a
diff --git a/packages/blueprint/lib/RouterBuilder.js b/packages/blueprint/lib/RouterBuilder.js index <HASH>..<HASH> 100644 --- a/packages/blueprint/lib/RouterBuilder.js +++ b/packages/blueprint/lib/RouterBuilder.js @@ -34,7 +34,7 @@ function makeAction (controller, method, options) { * @param next * @returns {*} */ -function handleError (err, res, next) { +function handleError (err, res) { var errType = typeof err; if (errType === 'string') { @@ -50,15 +50,13 @@ function handleError (err, res, next) { res.status (400).send (err); } } - - return next ('route'); } function validateBySchema (schema) { return function __blueprint_validate_schema (req, res, next) { req.check (schema); var errors = req.validationErrors (); - return !errors ? next () : handleError (errors, res, next); + return !errors ? next () : handleError (errors, res); } } @@ -66,7 +64,7 @@ function validateByFunction (validator) { return function __blueprint_validate_function (req, res, next) { return validator (req, function (err) { if (!err) return next (); - return handleError (err, res, next); + return handleError (err, res); }); } } @@ -75,7 +73,7 @@ function executor (execute) { return function __blueprint_execute (req, res, next) { execute (req, res, function (err) { if (!err) return next (); - return handleError (err, res, next); + return handleError (err, res); }); } } @@ -84,7 +82,7 @@ function sanitizer (sanitize) { return function __blueprint_sanitize (req, res, next) { return sanitize (req, function (err) { if (!err) return next (); - return handleError (err, res, next); + return handleError (err, res); }); } }
handleError() should not advance to next route
onehilltech_blueprint
train
8410d30940ff11396ddbb598ebb2424d364e232e
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, find_packages setup(name='trelliolibs', - version='0.22', + version='0.23', author='Abhishek Verma, Nirmal Singh', author_email='ashuverma1989@gmail.com, nirmal.singh.cer08@itbhu.ac.in', url='https://github.com/technomaniac/trelliolibs', diff --git a/trelliolibs/utils/base.py b/trelliolibs/utils/base.py index <HASH>..<HASH> 100644 --- a/trelliolibs/utils/base.py +++ b/trelliolibs/utils/base.py @@ -1,9 +1,11 @@ +from functools import partial from time import time from asyncpg.exceptions import UniqueViolationError, UndefinedColumnError from trellio import request, get, put, post, delete, api from trelliopg import get_db_adapter +from trelliolibs.utils.helpers import json_serializer from .decorators import TrellioValidator from .helpers import RecordHelper, uuid_serializer, json_response @@ -39,11 +41,11 @@ def extract_request_params(request, filter_keys=()): class CRUDModel: - def __init__(self, table=''): + def __init__(self, table='', json_fields=()): self._table = table self._db = get_db_adapter() self._record = RecordHelper() - self._serializers = [uuid_serializer] + self._serializers = [uuid_serializer, partial(json_serializer, field=json_fields)] async def get(self, id=None): results = await self._db.where(table=self._table, id=id) @@ -95,10 +97,10 @@ class CRUDTCPClient: class CRUDHTTPService: def __init__(self, name, version, host, port, table_name='', base_uri='', required_params=(), state_key=None, - create_schema=None, update_schema=None, allow_unknown=False): + create_schema=None, update_schema=None, allow_unknown=False, json_fields=()): super(CRUDHTTPService, self).__init__(name, version, host, port) self._table_name = table_name - self._model = CRUDModel(table=table_name) + self._model = CRUDModel(table=table_name, json_fields=json_fields) self._state_key = state_key self._create_schema = create_schema self._update_schema = update_schema diff --git a/trelliolibs/utils/helpers.py b/trelliolibs/utils/helpers.py index <HASH>..<HASH> 100644 --- a/trelliolibs/utils/helpers.py +++ b/trelliolibs/utils/helpers.py @@ -1,5 +1,6 @@ -from uuid import UUID import collections +from uuid import UUID + from asyncpg.exceptions import DuplicateTableError from asyncpg.exceptions import UndefinedTableError from trellio.wrappers import Response @@ -39,6 +40,12 @@ def uuid_serializer(data): return data +def json_serializer(data, fields=()): + for field in fields: + data[field] = json.loads(data[field]) + return data + + class RecordHelper: @staticmethod def record_to_dict(recs, normalize=None):
added json_serializer in CRUDModel
quikmile_trelliolibs
train
4842866abb8ca893aa17918d1bfea7d05a399ae2
diff --git a/library/CM/Jobdistribution/Job/Abstract.php b/library/CM/Jobdistribution/Job/Abstract.php index <HASH>..<HASH> 100644 --- a/library/CM/Jobdistribution/Job/Abstract.php +++ b/library/CM/Jobdistribution/Job/Abstract.php @@ -16,7 +16,6 @@ abstract class CM_Jobdistribution_Job_Abstract extends CM_Class_Abstract { * @return mixed */ private function _executeJob(CM_Params $params) { - CMService_Newrelic::getInstance()->endTransaction(); CMService_Newrelic::getInstance()->startTransaction('job manager: ' . $this->_getClassName()); $return = $this->_execute($params); CMService_Newrelic::getInstance()->endTransaction();
removed not needed endTransaction, because this is set in the beginning of startTransaction
cargomedia_cm
train
9412d427075e846166164a3dcb8f1571b2b1d30a
diff --git a/src/Sylius/Bundle/CartBundle/Context/SessionBasedCartContext.php b/src/Sylius/Bundle/CartBundle/Context/SessionBasedCartContext.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/CartBundle/Context/SessionBasedCartContext.php +++ b/src/Sylius/Bundle/CartBundle/Context/SessionBasedCartContext.php @@ -54,7 +54,7 @@ final class SessionBasedCartContext implements CartContextInterface public function getCart() { if (!$this->session->has($this->sessionKeyName)) { - throw new CartNotFoundException(); + throw new CartNotFoundException('Sylius was not able to find the cart in session'); } $cart = $this->cartRepository->findCartById($this->session->get($this->sessionKeyName)); @@ -62,7 +62,7 @@ final class SessionBasedCartContext implements CartContextInterface if (null === $cart) { $this->session->remove($this->sessionKeyName); - throw new CartNotFoundException(); + throw new CartNotFoundException('Sylius was not able to find the cart in session'); } return $cart; diff --git a/src/Sylius/Component/Cart/Context/CartNotFoundException.php b/src/Sylius/Component/Cart/Context/CartNotFoundException.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Component/Cart/Context/CartNotFoundException.php +++ b/src/Sylius/Component/Cart/Context/CartNotFoundException.php @@ -19,8 +19,8 @@ class CartNotFoundException extends \RuntimeException /** * {@inheritdoc} */ - public function __construct(\Exception $previousException = null) + public function __construct($message = null, \Exception $previousException = null) { - parent::__construct('Sylius was not able to figure out the current cart.', 0, $previousException); + parent::__construct($message ?: 'Sylius was not able to figure out the current cart.', 0, $previousException); } } diff --git a/src/Sylius/Component/Core/Cart/Context/ShopBasedCartContext.php b/src/Sylius/Component/Core/Cart/Context/ShopBasedCartContext.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Component/Core/Cart/Context/ShopBasedCartContext.php +++ b/src/Sylius/Component/Core/Cart/Context/ShopBasedCartContext.php @@ -65,7 +65,7 @@ final class ShopBasedCartContext implements CartContextInterface try { $cart->setChannel($this->shopperContext->getChannel()); } catch (ChannelNotFoundException $exception) { - throw new CartNotFoundException($exception); + throw new CartNotFoundException('Sylius was not able to prepare the cart properly', $exception); } try {
[Cart] Rework the cart not found exception
Sylius_Sylius
train
c893695cfbfce43bef7bd00c10fc982343f08c50
diff --git a/arangodb/orm/models.py b/arangodb/orm/models.py index <HASH>..<HASH> 100644 --- a/arangodb/orm/models.py +++ b/arangodb/orm/models.py @@ -17,6 +17,10 @@ class CollectionQueryset(object): self._manager = manager self._collection = manager._model_class.collection_instance self._query = Query() + # Relations + self._is_working_on_relations = False + self._relations_start_model = None + self._relations_relation_collection = None # Cache self._has_cache = False self._cache = [] @@ -25,13 +29,13 @@ class CollectionQueryset(object): """ """ - found_relations = Traveser.follow( - start_vertex=start_model.document.id, - edge_collection=relation_collection, - direction='outbound' - ) + self._is_working_on_relations = True + self._has_cache = False + + self._relations_start_model = start_model + self._relations_relation_collection = relation_collection - return found_relations + return self def all(self): """ @@ -73,7 +77,21 @@ class CollectionQueryset(object): self._cache = [] # TODO: Check how to best clear this list self._has_cache = True - result = self._query.execute() + if self._is_working_on_relations: + + start_model = self._relations_start_model + relation_collection = self._relations_relation_collection + + found_relations = Traveser.follow( + start_vertex=start_model.document.id, + edge_collection=relation_collection, + direction='outbound' + ) + + result = found_relations + + else: + result = self._query.execute() for doc in result: model = self._manager._create_model_from_doc(doc=doc) diff --git a/arangodb/tests.py b/arangodb/tests.py index <HASH>..<HASH> 100644 --- a/arangodb/tests.py +++ b/arangodb/tests.py @@ -988,23 +988,25 @@ class ManyToManyFieldTestCase(unittest.TestCase): start_model.save() start_model = StartModel.objects.get(_id=start_model.document.id) - print(start_model.others) + + related_models = start_model.others + + self.assertEqual(len(related_models), 2) + + rel1 = related_models[0] + rel2 = related_models[1] + + is_first_the_first_end_model = rel1.document.id == end_model1.document.id + is_first_the_second_end_model = rel1.document.id == end_model2.document.id + self.assertTrue(is_first_the_first_end_model or is_first_the_second_end_model) + + is_second_the_first_end_model = rel2.document.id == end_model1.document.id + is_second_the_second_end_model = rel2.document.id == end_model2.document.id + self.assertTrue(is_second_the_first_end_model or is_second_the_second_end_model) StartModel.destroy() EndModel.destroy() - # - # def test_equals(self): - # model = ForeignkeyFieldTestCase.TestModel() - # - # field1 = ForeignKeyField(to=CollectionModel) - # field1.set(model) - # - # field2 = ForeignKeyField(to=CollectionModel) - # field2.set(model) - # - # self.assertEqual(field1, field2) - class TransactionTestCase(ExtendedTestCase): def setUp(self):
Now we should have basic lazy relation querysets
saeschdivara_ArangoPy
train
1eb5ad63ac9e4724c3d313814d4cebef7ada109d
diff --git a/pyethereum/blocks.py b/pyethereum/blocks.py index <HASH>..<HASH> 100644 --- a/pyethereum/blocks.py +++ b/pyethereum/blocks.py @@ -47,10 +47,10 @@ for i, (name, typ, default) in enumerate(block_structure): block_structure_rev[name] = [i, typ, default] acct_structure = [ - ["nonce", "int", 0], ["balance", "int", 0], - ["code", "bin", ""], + ["nonce", "int", 0], ["storage", "trie_root", ""], + ["code", "bin", ""], ] acct_structure_rev = {}
changed order of acct_structure according to cpp client
ethereum_pyethereum
train
d8180f4236b5ba8d65d72c0836c1556ed7803091
diff --git a/django_extensions/management/commands/shell_plus.py b/django_extensions/management/commands/shell_plus.py index <HASH>..<HASH> 100644 --- a/django_extensions/management/commands/shell_plus.py +++ b/django_extensions/management/commands/shell_plus.py @@ -68,8 +68,12 @@ class Command(NoArgsCommand): def run_notebook(): from django.conf import settings - from IPython.frontend.html.notebook import notebookapp - app = notebookapp.NotebookApp.instance() + try: + from IPython.html.notebookapp import NotebookApp + except ImportError: + from IPython.frontend.html.notebook import notebookapp + NotebookApp = notebookapp.NotebookApp + app = NotebookApp.instance() ipython_arguments = getattr(settings, 'IPYTHON_ARGUMENTS', ['--ext', 'django_extensions.management.notebook_extension']) app.initialize(ipython_arguments) app.start()
fix ticket #<I> IPython.frontend is deprecated fix import with backwards compatibility
django-extensions_django-extensions
train
4b5445ad2e3b652edaf2f83147edbcc077c64328
diff --git a/iron_mq.py b/iron_mq.py index <HASH>..<HASH> 100644 --- a/iron_mq.py +++ b/iron_mq.py @@ -76,16 +76,25 @@ class Queue(object): return result["body"] - def delete_multiple(self, ids): + def delete_multiple(self, ids=None, messages=None): """Execute an HTTP request to delete messages from queue. Arguments: - ids -- A list of messages to be deleted from the queue. [{ "id": "xxxxxxxxx", "reservation_id": "xxxxxxxxx"}] - ] + ids -- A list of messages id to be deleted from the queue. + ] messages -- Response to message reserving. """ url = "queues/%s/messages" % self.name - data = json.dumps({"ids": ids}) + items = None + if ids is not None and messages is not None: + raise Exception("Please, specify at least one parameter.") + if ids is not None: + items = map(lambda item: {"id": item}, ids) + if messages is not None: + items = map(lambda item: {"id": item["id"] ,"reservation_id": item["reservation_id"]}, messages["messages"]) + + data = json.dumps({"ids": items}) + result = self.client.delete(url=url, body=data, headers={"Content-Type":"application/json"}) return result["body"] @@ -109,7 +118,7 @@ class Queue(object): return result['body'] def get(self, max=None, timeout=None, wait=None): - """Deprecated. User Queue.reserve() instead. Executes an HTTP request to get a message off of a queue. + """Deprecated. Use Queue.reserve() instead. Executes an HTTP request to get a message off of a queue. Keyword arguments: max -- The maximum number of messages to pull. Defaults to 1. @@ -118,12 +127,14 @@ class Queue(object): return response - def reserve(self, max=None, timeout=None): + def reserve(self, max=None, timeout=None, wait=None, delete=None): """Retrieves Messages from the queue and reserves it. Arguments: max -- The maximum number of messages to reserve. Defaults to 1. timeout -- Timeout in seconds. + wait -- Time to long poll for messages, in seconds. Max is 30 seconds. Default 0. + delete -- If true, do not put each message back on to the queue after reserving. Default false. """ url = "queues/%s/reservations" % self.name qitems = {} @@ -131,6 +142,10 @@ class Queue(object): qitems["n"] = max if timeout is not None: qitems["timeout"] = timeout + if wait is not None: + qitems["wait"] = wait + if delete is not None: + qitems["delete"] = delete body = json.dumps(qitems) response = self.client.post(url, body=body, diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -158,13 +158,19 @@ class TestIronMQ(unittest.TestCase): q = self.mq.queue("test_queue") q.clear() old_size = q.size() + ids = q.post("more", "and more")["ids"] + self.assertEqual(old_size, q.size() - 2) + q.delete_multiple(ids=ids) + self.assertEqual(old_size, q.size()) + + def test_deleteMultipleReservedMessages(self): + q = self.mq.queue("test_queue") + q.clear() + old_size = q.size() q.post("more", "and more") - response = q.reserve(2, 60) + messages = q.reserve(2, 60) self.assertEqual(old_size, q.size() - 2) - ids = list() - for item in response["messages"]: - ids.append({"reservation_id": item["reservation_id"], "id": item["id"]}) - q.delete_multiple(ids) + q.delete_multiple(messages=messages) self.assertEqual(old_size, q.size()) def test_getMessageById(self):
Delete messages by ids and response after reserving. Add wait and delete arguments to the reserve method.
iron-io_iron_mq_python
train
2e4d01885155f23c306fda11e757ed4671658735
diff --git a/tools/listclasses.py b/tools/listclasses.py index <HASH>..<HASH> 100755 --- a/tools/listclasses.py +++ b/tools/listclasses.py @@ -5,12 +5,16 @@ # and scan metadata. # +from __future__ import print_function + import getopt +import io import os import re import sys from meta import scanallmeta +from functools import reduce ### @@ -25,7 +29,7 @@ def get_finterfaces(fn, include_list=None, tmpfilename='_cpp.tmp'): finterfaces = [] - f = open(tmpfilename, 'r') + f = io.open(tmpfilename, mode='r', encoding='latin-1') l = f.readline() while l: l = f.readline() @@ -51,8 +55,8 @@ def get_module_list(metadata, interface, finterface_list=[], exclude_list=[], depalready = [] # Loop over all files and find modules - for path, metapath in metadata.iteritems(): - for fn, meta in metapath.iteritems(): + for path, metapath in metadata.items(): + for fn, meta in metapath.items(): if 'interface' in meta: if meta['interface'] == interface: classtype = meta['classtype'] @@ -83,15 +87,15 @@ def write_interface_info(metadata, interface, finterface_list, exclude_list, include_list, deffn, mkfn, cfgfn): fns = [] - deff = open(deffn, 'a') - mkf = open(mkfn, 'a') - cfgf = open(cfgfn, 'a') + deff = io.open(deffn, 'a') + mkf = io.open(mkfn, 'a') + cfgf = io.open(cfgfn, 'a') - print >> mkf, '%s_MODS = \\' % interface.upper() + print(u'%s_MODS = \\' % interface.upper(), file=mkf) depalready = [] - for path, metapath in metadata.iteritems(): - for fn, meta in metapath.iteritems(): + for path, metapath in metadata.items(): + for fn, meta in metapath.items(): if 'interface' in meta: if meta['interface'] == interface: classtype = meta['classtype'] @@ -107,23 +111,23 @@ def write_interface_info(metadata, interface, finterface_list, exclude_list, if len(finterfaces_present) > 0: s = reduce(lambda x,y: x+','+y, finterfaces_present[1:], finterfaces_present[0]) - print >> deff, '%s:%s:%s:%s:%s' % (classtype[:-2], + print('%s:%s:%s:%s:%s' % (classtype[:-2], classtype, classname, - features, s) + features, s), file=deff) if 'dependencies' in meta: dependencies = meta['dependencies'].split(',') for depfn in dependencies: depfn = os.path.basename(depfn) if not depfn in depalready: - print >> mkf, '\t%s \\' % depfn + print('\t%s \\' % depfn, file=mkf) depalready += [ depfn ] - print >> mkf, '\t%s \\' % fn + print(u'\t%s \\' % fn, file=mkf) - print >> cfgf, '#define HAVE_%s' % \ - (classtype[:-2].upper()) + print('#define HAVE_%s' % \ + (classtype[:-2].upper()), file=cfgf) deff.close() - print >> mkf + print(u'', file=mkf) mkf.close() cfgf.close() @@ -162,10 +166,10 @@ if __name__ == '__main__': else: raise RuntimeError('Unknown comand line argument: {}'.format(key)) - print 'Scanning metadata of all source files...' + print('Scanning metadata of all source files...') metadata = scanallmeta(path) - print "Dumping information for classes that implement '{}' interface..." \ - .format(interface) + print("Dumping information for classes that implement '{}' interface..." \ + .format(interface)) write_interface_info(metadata, interface, finterface_list, exclude_list, include_list, deffn, mkfn, cfgfn) diff --git a/tools/meta.py b/tools/meta.py index <HASH>..<HASH> 100755 --- a/tools/meta.py +++ b/tools/meta.py @@ -2,6 +2,7 @@ is intended to scan directories for this information. """ +import io import os @@ -13,7 +14,7 @@ def scanmeta(f): a dictionary. """ if isinstance(f, str): - f = open(f, 'r') + f = io.open(f, mode='r', encoding='latin-1') done = False @@ -63,23 +64,21 @@ def scanmeta(f): return d -def walkfunc(d, dirname, fns): - dd = { } +def _scanallmeta(dirname, fns): + d = {} for fn in fns: fullfn = dirname+'/'+fn if os.path.isfile(fullfn): if fn.split('.')[-1] in srcexts: - dd[fn] = scanmeta(fullfn) - elif os.path.islink(fullfn): - os.path.walk(fullfn, walkfunc, d) - d[dirname] = dd + d[fn] = scanmeta(fullfn) + return d def scanallmeta(path): - d = { } + d = {} if isinstance(path, str): - os.path.walk(path, walkfunc, d) - else: - for p in path: - os.path.walk(p, walkfunc, d) + path = [path] + for p in path: + for dirpath, dirnames, filenames in os.walk(p): + d[dirpath] = _scanallmeta(dirpath, filenames) return d
Make meta and listclasses work with Python 3
Atomistica_atomistica
train
c66b7c77aa79f4d289ab8ce04944866648329290
diff --git a/src/result.js b/src/result.js index <HASH>..<HASH> 100644 --- a/src/result.js +++ b/src/result.js @@ -61,15 +61,20 @@ class Result { */ chunks() { return insertIntoIndexHTML(this._html, this._head, this._body, this._bodyAttributes).then((html) => { - let [, head, body] = html.match(HTML_HEAD_REGEX); + let docParts = html.match(HTML_HEAD_REGEX); + let head = docParts[1]; + let body = docParts[2]; if (!head || !body) { throw new Error('Could not idenfity head and body of the document! Make sure the document is well formed.'); } let chunks = [head]; - let [plainBody, ...shoeboxes] = body.split(SHOEBOX_TAG_PATTERN); + let bodyParts = body.split(SHOEBOX_TAG_PATTERN); + let plainBody = bodyParts[0]; chunks.push(plainBody); + + let shoeboxes = bodyParts.splice(1); shoeboxes.forEach((shoebox) => { chunks.push(`${SHOEBOX_TAG_PATTERN}${shoebox}`); }); diff --git a/test/result-test.js b/test/result-test.js index <HASH>..<HASH> 100644 --- a/test/result-test.js +++ b/test/result-test.js @@ -134,8 +134,8 @@ describe('Result', function() { }); describe('chunks()', function() { - let HEAD = '<meta name="foo" content="bar">'; - let BODY = '<h1>A normal response document</h1>'; + var HEAD = '<meta name="foo" content="bar">'; + var BODY = '<h1>A normal response document</h1>'; beforeEach(function() { result._fastbootInfo.response.statusCode = 200;
fix code for Node 4 …which does not support destructuring and let
ember-fastboot_ember-cli-fastboot
train
10571cd08acaab5686f37900f9cc2dae853343b4
diff --git a/src/ORM/Model.php b/src/ORM/Model.php index <HASH>..<HASH> 100644 --- a/src/ORM/Model.php +++ b/src/ORM/Model.php @@ -124,17 +124,23 @@ abstract class Model extends \ArrayObject * т.к. есть проблемы с неймспейсами xmlns * * Для каждого элемента необходимо указывать наймспейс "c", например: - * //c:Свойство/c:ВариантыЗначений/c:Справочник[c:ИдЗначения = '{$id}'] - * + * //c:Свойство/c:ВариантыЗначений/c:Справочник[c:ИдЗначения = ':параметр'] + * * @param string $path + * @param array $args - Аргументы задаём в бинд стиле ['параметр'=>'значение'] без двоеточия * @return \SimpleXMLElement[] */ - public function xpath($path) + public function xpath($path, $args=[]) { $this->registerNamespace(); if (!$this->namespaceRegistered) { $path = str_replace('c:', '', $path); } + if (!empty($args) and is_array($args)) { + foreach ($args as $ka=>$kv) { + $path = str_replace(':'.$ka, (strstr($kv,"'")?("concat('" .str_replace("'", "',\"'\",'",$kv) . "')"): "'" . $kv . "'") , $path); + } + } return $this->xml->xpath($path); } }
Update Model.php (#3) * Update Model.php
carono_php-commerceml
train
e5ed3a9abd784ecb5755bac42990f8d51c66ab50
diff --git a/openpack/editor.py b/openpack/editor.py index <HASH>..<HASH> 100644 --- a/openpack/editor.py +++ b/openpack/editor.py @@ -3,6 +3,7 @@ from __future__ import with_statement import argparse import tempfile import os +import sys import posixpath import inspect import subprocess @@ -54,7 +55,13 @@ class EditableFile(object): with self: editor = self.get_editor(ipath) cmd = [editor, self.name] - if subprocess.call(cmd) != 0: return + try: + res = subprocess.call(cmd) + except Exception, e: + print("Error launching editor %(editor)s" % vars()) + print(e) + return + if res != 0: return new_data = self.read() if new_data != self.data: self.changed = True @@ -62,8 +69,14 @@ class EditableFile(object): @staticmethod def get_editor(filepath): - # for now, assume path is XML - return os.environ.get('XML_EDITOR', os.environ.get('EDITOR', 'edit')) + """ + Give preference to an XML_EDITOR or EDITOR defined in the + environment. Otherwise use notepad on Windows and edit on other + platforms. + """ + default_editor = ['edit', 'notepad'][sys.platform.startswith('win32')] + return os.environ.get('XML_EDITOR', + os.environ.get('EDITOR', default_editor)) def part_edit(path, reformat_xml): file, ipath = find_file(path)
Improved robustness around part-edit - now selects notepad on windows if no XML_EDITOR or EDITOR environment variable defined
yougov_openpack
train
b7b0672f1654b4d538fcd3095f27db2f59fe8055
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -24,13 +24,13 @@ function dtype( value ) { // Check for base types: type = typeof value; switch ( type ) { - case 'undefined': - case 'boolean': - case 'number': - case 'string': - case 'function': - case 'symbol': - return type; + case 'undefined': + case 'boolean': + case 'number': + case 'string': + case 'function': + case 'symbol': + return type; } // Resort to slower look-up: type = typeName( value );
[FIX] switch indentation.
compute-io_dtype
train
1383f3a30ca208c07108e14695ff5d891f5403b2
diff --git a/kubespawner/__init__.py b/kubespawner/__init__.py index <HASH>..<HASH> 100644 --- a/kubespawner/__init__.py +++ b/kubespawner/__init__.py @@ -6,23 +6,6 @@ import time from traitlets import Unicode -template = { - 'apiVersion': 'v1', - 'kind': 'Pod', - 'metadata': { - 'name': 'jupyter', - 'labels': { - 'name': 'jupyter', - } - }, - 'spec': { - 'containers': [ - {'name': 'jupyter', 'image': 'jupyter/singleuser'}, - ] - } -} - - class UnicodeOrFalse(Unicode): info_text = 'a unicode string or False' @@ -80,6 +63,64 @@ class KubeSpawner(Spawner): help='Name of Docker image to use when spawning user pods' ) + cpu_limit = Unicode( + "2000m", + config=True, + help='Max number of CPU cores that a single user can use' + ) + + cpu_request = Unicode( + "200m", + config=True, + help='Min nmber of CPU cores that a single user is guaranteed' + ) + + mem_limit = Unicode( + "1Gi", + config=True, + help='Max amount of memory a single user can use' + ) + + mem_request = Unicode( + "128Mi", + config=True, + help='Min amount of memory a single user is guaranteed' + ) + + def get_pod_manifest(self): + return { + 'apiVersion': 'v1', + 'kind': 'Pod', + 'metadata': { + 'name': self.pod_name, + 'labels': { + 'name': self.pod_name + } + }, + 'spec': { + 'containers': [ + { + 'name': 'jupyter', + 'image': self.singleuser_image_spec, + 'resources': { + 'requests': { + 'memory': self.mem_request, + 'cpu': self.cpu_request, + }, + 'limits': { + 'memory': self.mem_limit, + 'cpu': self.cpu_limit + } + }, + 'env': [ + {'name': k, 'value': v} + for k, v in self._env_default().items() + ] + } + ] + } + } + def _get_pod_url(self, pod_name=None): url = '{host}/api/{version}/namespaces/{namespace}/pods'.format( host=self.kube_api_endpoint, @@ -140,16 +181,11 @@ class KubeSpawner(Spawner): @gen.coroutine def start(self): self.log.info('start called') - env = self._env_default() - env_mapping = [{'name': k, 'value': v} for k, v in env.items()] - template['metadata']['name'] = self.pod_name - template['metadata']['labels']['name'] = self.pod_name - template['spec']['containers'][0]['env'] = env_mapping - template['spec']['containers'][0]['image'] = self.singleuser_image_spec + pod_manifest = self.get_pod_manifest() self.log.info(self._get_pod_url()) resp = yield self.session.post( self._get_pod_url(), - data=json.dumps(template)) + data=json.dumps(pod_manifest)) self.log.info(repr(resp.headers)) self.log.info(repr(resp.text)) while True: @@ -162,7 +198,7 @@ class KubeSpawner(Spawner): self.user.server.ip = data['items'][0]['status']['podIP'] self.user.server.port = 8888 self.db.commit() - self.log.info(template) + self.log.info(pod_manifest) @gen.coroutine def stop(self):
Make resource limits be configurable Also construct the pod manifest in a less shitty way
jupyterhub_kubespawner
train
b52c257fcde22e982aea7b2287b3d0b943b16df2
diff --git a/cordova-lib/src/hooks/Context.js b/cordova-lib/src/hooks/Context.js index <HASH>..<HASH> 100644 --- a/cordova-lib/src/hooks/Context.js +++ b/cordova-lib/src/hooks/Context.js @@ -17,6 +17,9 @@ under the License. */ +var path = require('path'); +var events = require('cordova-common').events; + /** * Creates hook script context * @constructor @@ -39,13 +42,39 @@ function Context(hook, opts) { this.cordova = require('../cordova/cordova'); } +// As per CB-9834 we need to maintain backward compatibility and provide a compat layer +// for plugins that still require modules, factored to cordova-common. +var compatMap = { + '../configparser/ConfigParser': function () { + return require('cordova-common').ConfigParser; + }, + '../util/xml-helpers': function () { + return require('cordova-common').xmlHelpers; + } +}; /** * Returns a required module - * @param {String} path Module path + * @param {String} modulePath Module path * @returns {Object} */ -Context.prototype.requireCordovaModule = function (path) { - return require(path); +Context.prototype.requireCordovaModule = function (modulePath) { + // There is a very common mistake, when hook requires some cordova functionality + // using 'cordova-lib/...' path. + // This path will be resolved only when running cordova from 'normal' installation + // (without symlinked modules). If cordova-lib linked to cordova-cli this path is + // never resolved, so hook fails with 'Error: Cannot find module 'cordova-lib'' + var resolvedPath = path.resolve(__dirname, modulePath.replace(/^cordova-lib/, '../../../cordova-lib')); + var relativePath = path.relative(__dirname, resolvedPath).replace(/\\/g, '/'); + events.emit('verbose', 'Resolving module name for ' + modulePath + ' => ' + relativePath); + + var compatRequire = compatMap[relativePath]; + if (compatRequire) { + events.emit('warn', 'The module "' + path.basename(relativePath) + '" has been factored ' + + 'into "cordova-common". Consider update your plugin hooks.'); + return compatRequire(); + } + + return require(relativePath); }; module.exports = Context;
CB-<I> Introduce compat map for hook requires
apache_cordova-lib
train
1eb3ec97f4f98d5c4759bc11ad20e964c50fe1f0
diff --git a/lib/linkage/field.rb b/lib/linkage/field.rb index <HASH>..<HASH> 100644 --- a/lib/linkage/field.rb +++ b/lib/linkage/field.rb @@ -28,14 +28,20 @@ module Linkage def ruby_type unless @ruby_type hsh = - case t = @schema[:db_type].downcase - when /\A(?:medium|small)?int(?:eger)?(?:\((?:\d+)\))?(?: unsigned)?\z/o - {:type=>Integer} - when /\Atinyint(?:\((\d+)\))?\z/o - {:type =>@schema[:type] == :boolean ? TrueClass : Integer} + case @schema[:db_type].downcase + when /\A(medium|small)?int(?:eger)?(?:\((\d+)\))?( unsigned)?\z/o + if !$1 && $2 && $2.to_i >= 10 && $3 + # Unsigned integer type with 10 digits can potentially contain values which + # don't fit signed integer type, so use bigint type in target database. + {:type=>Bignum} + else + {:type=>Integer} + end + when /\Atinyint(?:\((\d+)\))?(?: unsigned)?\z/o + {:type =>schema[:type] == :boolean ? TrueClass : Integer} when /\Abigint(?:\((?:\d+)\))?(?: unsigned)?\z/o {:type=>Bignum} - when /\A(?:real|float|double(?: precision)?)\z/o + when /\A(?:real|float|double(?: precision)?|double\(\d+,\d+\)(?: unsigned)?)\z/o {:type=>Float} when 'boolean' {:type=>TrueClass} @@ -60,7 +66,7 @@ module Linkage {:type=>BigDecimal, :size=>(s.empty? ? nil : s)} when /\A(?:bytea|(?:tiny|medium|long)?blob|(?:var)?binary)(?:\((\d+)\))?\z/o {:type=>File, :size=>($1.to_i if $1)} - when 'year' + when /\A(?:year|(?:int )?identity)\z/o {:type=>Integer} else {:type=>String}
Update Field#ruby_type from Sequel code
coupler_linkage
train
e6ed6e4dd499736b451ddd5f2fde8b68a238dcdf
diff --git a/util/functions.php b/util/functions.php index <HASH>..<HASH> 100644 --- a/util/functions.php +++ b/util/functions.php @@ -74,7 +74,7 @@ function string_contains( $hay, $needle ) { } function string_i_contains( $hay, $needle ) { - return contains( strtolower( $hay ), strtolower( $needle ) ); + return string_contains( strtolower( $hay ), strtolower( $needle ) ); } @@ -90,7 +90,7 @@ function string_substr_before( $hay, $needles ) { must_be_array( $needles ); $return = $hay; foreach( $needles as $needle ) { - if ( ! empty( $needle) && contains( $hay, $needle ) ) { + if ( ! empty( $needle) && string_contains( $hay, $needle ) ) { $cut = substr( $hay, 0, strpos( $hay, $needle ) ); if ( strlen( $cut ) < strlen ( $return ) ) { $return = $cut; @@ -111,7 +111,7 @@ function string_substr_before_last( $hay, $needles ) { must_be_array( $needles ); $return = ''; foreach( $needles as $needle ) { - if ( ! empty( $needle) && contains( $hay, $needle ) ) { + if ( ! empty( $needle) && string_contains( $hay, $needle ) ) { $cut = substr( $hay, 0, strrpos( $hay, $needle ) ); if ( strlen( $cut ) > strlen ( $return ) ) { $return = $cut; @@ -132,7 +132,7 @@ function string_substr_after( $hay, $needles ) { must_be_array( $needles ); $return = ''; foreach( $needles as $needle ) { - if ( ! empty( $needle) && contains( $hay, $needle ) ) { + if ( ! empty( $needle) && string_contains( $hay, $needle ) ) { $cut = substr( $hay, strpos( $hay, $needle ) + strlen( $needle ) ); if ( strlen( $cut ) > strlen ( $return ) ) { $return = $cut; @@ -152,7 +152,7 @@ function string_substr_after_last( $hay, $needles ) { must_be_array( $needles ); $return = $hay; foreach( $needles as $needle ) { - if ( ! empty( $needle) && contains( $hay, $needle ) ) { + if ( ! empty( $needle) && string_contains( $hay, $needle ) ) { $cut = substr( $hay, strrpos( $hay, $needle ) + strlen( $needle ) ); if ( strlen( $cut ) < strlen ( $return ) ) { $return = $cut;
BugFix: Rename internal call of util functions
Elephant418_Staq
train
6cc6e5b83b97ba276484667a7db27be9869cec2c
diff --git a/presto-orc/src/main/java/com/facebook/presto/orc/stream/ByteInputStream.java b/presto-orc/src/main/java/com/facebook/presto/orc/stream/ByteInputStream.java index <HASH>..<HASH> 100644 --- a/presto-orc/src/main/java/com/facebook/presto/orc/stream/ByteInputStream.java +++ b/presto-orc/src/main/java/com/facebook/presto/orc/stream/ByteInputStream.java @@ -146,24 +146,4 @@ public class ByteInputStream offset += chunkSize; } } - - public void next(byte[] values, int items) - throws IOException - { - int outputOffset = 0; - while (outputOffset < items) { - if (offset == length) { - readNextBlock(); - } - if (length == 0) { - throw new OrcCorruptionException(input.getOrcDataSourceId(), "Unexpected end of stream"); - } - - int chunkSize = min(items - outputOffset, length - offset); - System.arraycopy(buffer, offset, values, outputOffset, chunkSize); - - outputOffset += chunkSize; - offset += chunkSize; - } - } }
Fix the build broken by <I> Fix the build broken by <I> Improve ORC byte reader.
prestodb_presto
train
f5f0e6f3faf35d96663c391aed8d5526f60596af
diff --git a/lib/opal/lexer.rb b/lib/opal/lexer.rb index <HASH>..<HASH> 100644 --- a/lib/opal/lexer.rb +++ b/lib/opal/lexer.rb @@ -181,8 +181,8 @@ module Opal end if opt - opt[1..-1].each do |opt| - res << opt[1] + opt[1..-1].each do |_opt| + res << _opt[1] end end @@ -212,8 +212,8 @@ module Opal end if opt - opt[1..-1].each do |opt| - res << s(:lasgn, opt[1]) + opt[1..-1].each do |_opt| + res << s(:lasgn, _opt[1]) end end
Don't overwrite the value of vars from outer scope (in <I>)
opal_opal
train
0f82ffec2163792e2afd3f932e4a86782d5a7868
diff --git a/demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationCirclePanel.java b/demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationCirclePanel.java index <HASH>..<HASH> 100644 --- a/demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationCirclePanel.java +++ b/demonstrations/src/main/java/boofcv/demonstrations/calibration/DetectCalibrationCirclePanel.java @@ -43,6 +43,9 @@ public class DetectCalibrationCirclePanel extends DetectCalibrationPanel { boolean showGraphs ) { super(gridRows, gridColumns, true, false); + doShowNumbers = false; + this.showNumbers.setSelected(doShowNumbers); + this.showGraphs = showGraphs; this.circleDiameter = diameter; this.circleSpacing = spacing;
- turned off showing numbers by default in calibration circle panel * Too much clutter
lessthanoptimal_BoofCV
train
626d8766a26a517b19f5399f132bc85a4f7ff274
diff --git a/registration/models.py b/registration/models.py index <HASH>..<HASH> 100644 --- a/registration/models.py +++ b/registration/models.py @@ -118,12 +118,10 @@ class RegistrationManager(models.Manager): associated users. """ - for profile in self.all(): - if profile.activation_key_expired(): - user = profile.user - if not user.is_active: - profile.delete() - user.delete() + for profile in self.expired(): + user = profile.user + profile.delete() + user.delete() @python_2_unicode_compatible
And have the cleanup command use the new query.
ubernostrum_django-registration
train
a236656c007fa24f17f3466416562065b08975dd
diff --git a/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonDeserializer.java b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonDeserializer.java index <HASH>..<HASH> 100644 --- a/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonDeserializer.java +++ b/extensions/jackson/src/main/java/io/jsonwebtoken/jackson/io/JacksonDeserializer.java @@ -63,7 +63,7 @@ public class JacksonDeserializer<T> implements Deserializer<T> { * <p> * If you would like to use your own {@code ObjectMapper} instance that also supports custom types for * JWT {@code Claims}, you will need to first customize your {@code ObjectMapper} instance by registering - * your custom types and then use the {@link JacksonDeserializer(ObjectMapper)} constructor instead. + * your custom types and then use the {@link #JacksonDeserializer(ObjectMapper)} constructor instead. * * @param claimTypeMap The claim name-to-class map used to deserialize claims into the given type */
Fix minor Javadoc error in JacksonDeserializer (#<I>) missing `#` in @link tag
jwtk_jjwt
train
0c5c27d51f21810899a8001fc16dfa7514d1e900
diff --git a/core/cb.project/project.js b/core/cb.project/project.js index <HASH>..<HASH> 100644 --- a/core/cb.project/project.js +++ b/core/cb.project/project.js @@ -122,7 +122,7 @@ ProjectType.prototype.define = function(types) { return that.merge(type); }); }, Q()).then(function() { - typeIds = _.pluck(types, "id"); + typeIds = that.types; var diff = !(_.difference(oldTypes, typeIds).length == 0 && oldTypes.length == typeIds.length); if (diff) that.events.emit('project.define', typeIds); diff --git a/core/cb.rpc.project/service.js b/core/cb.rpc.project/service.js index <HASH>..<HASH> 100644 --- a/core/cb.rpc.project/service.js +++ b/core/cb.rpc.project/service.js @@ -17,6 +17,12 @@ ProjectRPCService.prototype._reprProjectType = function(projectType) { }; }; +ProjectRPCService.prototype.detect = function(args) { + return this.project.detect().then(function(p) { + return p.reprData(); + }); +}; + ProjectRPCService.prototype.supported = function(args) { return _.map(this.projectTypes.SUPPORTED, this._reprProjectType, this) };
Fix propagation of project.detect when detecting project php
CodeboxIDE_codebox
train
a14c4d99802dae9f20f5303f2fc495a315f9baa9
diff --git a/lib/modules/apostrophe-express/index.js b/lib/modules/apostrophe-express/index.js index <HASH>..<HASH> 100644 --- a/lib/modules/apostrophe-express/index.js +++ b/lib/modules/apostrophe-express/index.js @@ -265,7 +265,7 @@ module.exports = { maxAge: 86400000 }); if (sessionOptions.secret === 'you should have a secret') { - console.log('WARNING: No session secret provided, please set the `secret` property of the `session` property of the apostrophe-express module in app.js'); + console.error('WARNING: No session secret provided, please set the `secret` property of the `session` property of the apostrophe-express module in app.js'); } if (!sessionOptions.store) { var MongoStore = require('connect-mongo/es5')(expressSession);
stdout should never be used for warnings
apostrophecms_apostrophe
train
1af4f372bd3ad688ca8089357f3658950489945a
diff --git a/src/Kris/LaravelFormBuilder/FormHelper.php b/src/Kris/LaravelFormBuilder/FormHelper.php index <HASH>..<HASH> 100644 --- a/src/Kris/LaravelFormBuilder/FormHelper.php +++ b/src/Kris/LaravelFormBuilder/FormHelper.php @@ -143,7 +143,7 @@ class FormHelper if (!in_array($type, static::$availableFieldTypes)) { throw new \InvalidArgumentException( sprintf( - 'Unsupported field type [%s]. Avaiable types are: %s', + 'Unsupported field type [%s]. Available types are: %s', $type, join(', ', array_merge(static::$availableFieldTypes, array_keys($this->customTypes))) )
Typo in FormHelper.php
kristijanhusak_laravel-form-builder
train
914cd83c8a38f5221384aeeae48740f75d4e9ee4
diff --git a/aws/data_source_aws_iam_assumed_role_source_test.go b/aws/data_source_aws_iam_assumed_role_source_test.go index <HASH>..<HASH> 100644 --- a/aws/data_source_aws_iam_assumed_role_source_test.go +++ b/aws/data_source_aws_iam_assumed_role_source_test.go @@ -9,29 +9,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -/* -arn:aws:iam::123456789012:root -arn:aws:iam::123456789012:user/JohnDoe -arn:aws:iam::123456789012:user/division_abc/subdivision_xyz/JaneDoe -arn:aws:iam::123456789012:group/Developers -arn:aws:iam::123456789012:group/division_abc/subdivision_xyz/product_A/Developers -arn:aws:iam::123456789012:role/S3Access -arn:aws:iam::123456789012:role/application_abc/component_xyz/RDSAccess -arn:aws:iam::123456789012:role/aws-service-role/access-analyzer.amazonaws.com/AWSServiceRoleForAccessAnalyzer -arn:aws:iam::123456789012:role/service-role/QuickSightAction -arn:aws:iam::123456789012:policy/UsersManageOwnCredentials -arn:aws:iam::123456789012:policy/division_abc/subdivision_xyz/UsersManageOwnCredentials -arn:aws:iam::123456789012:instance-profile/Webserver -arn:aws:sts::123456789012:federated-user/JohnDoe -arn:aws:sts::123456789012:assumed-role/Accounting-Role/JaneDoe -arn:aws:iam::123456789012:mfa/JaneDoeMFA -arn:aws:iam::123456789012:u2f/user/JohnDoe/default (U2F security key) -arn:aws:iam::123456789012:server-certificate/ProdServerCert -arn:aws:iam::123456789012:server-certificate/division_abc/subdivision_xyz/ProdServerCert -arn:aws:iam::123456789012:saml-provider/ADFSProvider -arn:aws:iam::123456789012:oidc-provider/GoogleProvider -*/ - func TestAssumedRoleRoleSessionName(t *testing.T) { testCases := []struct { Name string
tests/d/iam_assumed_role_source: Remove comments
terraform-providers_terraform-provider-aws
train
be642291169849b061a1900902264d5026c57394
diff --git a/src/Sulu/Bundle/AdminBundle/DependencyInjection/SuluAdminExtension.php b/src/Sulu/Bundle/AdminBundle/DependencyInjection/SuluAdminExtension.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/AdminBundle/DependencyInjection/SuluAdminExtension.php +++ b/src/Sulu/Bundle/AdminBundle/DependencyInjection/SuluAdminExtension.php @@ -51,7 +51,7 @@ class SuluAdminExtension extends Extension implements PrependExtensionInterface 'cache' => [ 'pools' => [ 'sulu_admin.collaboration_cache' => [ - 'adapter' => 'cache.adapter.filesystem', + 'adapter' => 'cache.app', ], ], ],
Fix correct cache adapter for collabration (#<I>)
sulu_sulu
train
2dc399ec478304ff13d825260122ea2ae5eb9aa0
diff --git a/src/devices.js b/src/devices.js index <HASH>..<HASH> 100644 --- a/src/devices.js +++ b/src/devices.js @@ -159,23 +159,26 @@ class BleDevice { let setupFns = [] for (let nobleService of services) { + let sUUID = util.normalizeUUID(nobleService.uuid) + let service = null + if (this._services[sUUID]) { + // Service exists + service = BleServices.fromExistingService(this._services[sUUID], nobleService) + } else { + // New service + service = BleServices.fromNobleService(nobleService) + } + logger.info(`Found service: ${service.getName()} / ${nobleService.uuid}`) + this._services[sUUID] = service + } + + for (let i in this._services) { + let s = this._services[i] setupFns.push((setupCallback)=> { - let sUUID = util.normalizeUUID(nobleService.uuid) - let service = null - if (this._services[sUUID]) { - // Service exists - service = BleServices.fromExistingService(this._services[sUUID], nobleService) - } else { - // New service - service = BleServices.fromNobleService(nobleService) - } - - service.setup((setupError)=> { - logger.info(`Service setup successfully: ${service.getName()}`) + s.setup((setupError)=> { + logger.info(`Service setup successfully: ${s.getName()}`) setupCallback(setupError) }) - - this._services[sUUID] = service }) } @@ -183,6 +186,7 @@ class BleDevice { logger.info('All services have been setup!') callback(error) }) + } }) }
sdk: prevent duplicate service setups (unlikely)
PunchThrough_bean-sdk-node
train
3ba3d0f7698cbfcd783e4c0ba7e1d0e0168c7d6f
diff --git a/lib/event_sourcery/event_store/postgres/optimised_event_poll_waiter.rb b/lib/event_sourcery/event_store/postgres/optimised_event_poll_waiter.rb index <HASH>..<HASH> 100644 --- a/lib/event_sourcery/event_store/postgres/optimised_event_poll_waiter.rb +++ b/lib/event_sourcery/event_store/postgres/optimised_event_poll_waiter.rb @@ -21,6 +21,7 @@ module EventSourcery catch(:stop) { block.call loop do + ensure_listen_thread_alive! wait_for_new_event_to_appear clear_new_event_queue block.call
Add this back in because it results in faster failure
envato_event_sourcery
train
eaffd324e3a7f52d86a826ab15dd19579909a7d7
diff --git a/chess_py/core/board.py b/chess_py/core/board.py index <HASH>..<HASH> 100644 --- a/chess_py/core/board.py +++ b/chess_py/core/board.py @@ -61,8 +61,11 @@ class Board: """ self.position = position self.possible_moves = dict() - self.king_loc_dict = {white: self.find_king(white), - black: self.find_king(black)} + try: + self.king_loc_dict = {white: self.find_king(white), + black: self.find_king(black)} + except ValueError: + self.king_loc_dict = None @classmethod def init_default(cls): @@ -242,7 +245,19 @@ class Board: test = cp(self) test.update(move) - if not test.piece_at_square(self.king_loc_dict[input_color]).in_check(test): + if self.king_loc_dict is None: + yield move + continue + + my_king = test.piece_at_square(self.king_loc_dict[input_color]) + + if my_king is None or \ + not isinstance(my_king, King) or \ + my_king.color != input_color: + self.king_loc_dict[input_color] = test.find_king(input_color) + my_king = test.piece_at_square(self.king_loc_dict[input_color]) + + if not my_king.in_check(test): yield move def runInParallel(*fns): @@ -293,7 +308,7 @@ class Board: self.piece_at_square(loc) == piece: return loc - raise Exception("{} \nPiece not found: {}".format(self, piece)) + raise ValueError("{} \nPiece not found: {}".format(self, piece)) def get_piece(self, piece_type, input_color): """ @@ -368,7 +383,7 @@ class Board: if move is None: raise Exception("Move cannot be None") - if isinstance(move.piece, King): + if self.king_loc_dict is not None and isinstance(move.piece, King): self.king_loc_dict[move.color] = move.end_loc if move.status == notation_const.KING_SIDE_CASTLE:
Fix king location dictionary exceptions Check for when King does not exist or is moved by an outside function
LordDarkula_chess_py
train
126fdba93b9d72474c94c9510981cbaa0ff10412
diff --git a/Connector/ServiceBus/ValidatorMiddleware/ValidatorMiddleware.php b/Connector/ServiceBus/ValidatorMiddleware/ValidatorMiddleware.php index <HASH>..<HASH> 100644 --- a/Connector/ServiceBus/ValidatorMiddleware/ValidatorMiddleware.php +++ b/Connector/ServiceBus/ValidatorMiddleware/ValidatorMiddleware.php @@ -38,7 +38,7 @@ class ValidatorMiddleware implements Middleware return $next($command); } - $object = $command->getTransferObject(); + $object = $command->getPayload(); $this->validator->validate($object);
correct validator middleware (#<I>)
plentymarkets_plentymarkets-shopware-connector
train
6c0dcf222caea580b4561b22306faa29b56abc10
diff --git a/salt/states/file.py b/salt/states/file.py index <HASH>..<HASH> 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -2719,7 +2719,7 @@ def managed(name, try: if __opts__['test']: if 'file.check_managed_changes' in __salt__: - ret['pchanges'] = __salt__['file.check_managed_changes']( + ret['changes'] = __salt__['file.check_managed_changes']( name, source, source_hash, @@ -2750,15 +2750,15 @@ def managed(name, reset=win_perms_reset) except CommandExecutionError as exc: if exc.strerror.startswith('Path not found'): - ret['pchanges'] = '{0} will be created'.format(name) + ret['changes'] = '{0} will be created'.format(name) - if isinstance(ret['pchanges'], tuple): - ret['result'], ret['comment'] = ret['pchanges'] - elif ret['pchanges']: + if isinstance(ret['changes'], tuple): + ret['result'], ret['comment'] = ret['changes'] + elif ret['changes']: ret['result'] = None ret['comment'] = 'The file {0} is set to be changed'.format(name) - if 'diff' in ret['pchanges'] and not show_changes: - ret['pchanges']['diff'] = '<show_changes=False>' + if 'diff' in ret['changes'] and not show_changes: + ret['changes']['diff'] = '<show_changes=False>' else: ret['result'] = True ret['comment'] = 'The file {0} is in the correct state'.format(name) diff --git a/tests/integration/states/test_file.py b/tests/integration/states/test_file.py index <HASH>..<HASH> 100644 --- a/tests/integration/states/test_file.py +++ b/tests/integration/states/test_file.py @@ -459,6 +459,21 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): changes = next(six.itervalues(ret))['changes'] self.assertEqual('<show_changes=False>', changes['diff']) + def test_managed_show_changes_true(self): + ''' + file.managed test interface + ''' + name = os.path.join(TMP, 'grail_not_scene33') + with salt.utils.files.fopen(name, 'wb') as fp_: + fp_.write(b'test_managed_show_changes_false\n') + + ret = self.run_state( + 'file.managed', name=name, source='salt://grail/scene33', + ) + + changes = next(six.itervalues(ret))['changes'] + self.assertIn('diff', changes) + @skipIf(IS_WINDOWS, 'Don\'t know how to fix for Windows') def test_managed_escaped_file_path(self): '''
Swapping pchanges for changes in file state.
saltstack_salt
train
5e8218a2fb5b0c63df4394e299ad75fec2494b29
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ setup( 'appdirs==1.4.3', 'docopt==0.6.2', 'prompt-toolkit==1.0', - 'python-slugify==1.2.1', + 'python-slugify==1.2.2', ], packages=['withtool'], classifiers=[
Upgrade dependency python-slugify to ==<I>
renanivo_with
train
0b575750a90c43c6763154333a6f065756b3b25e
diff --git a/credentials/alts/alts_test.go b/credentials/alts/alts_test.go index <HASH>..<HASH> 100644 --- a/credentials/alts/alts_test.go +++ b/credentials/alts/alts_test.go @@ -1,3 +1,5 @@ +// +build linux,windows + /* * * Copyright 2018 gRPC authors. diff --git a/credentials/alts/utils_test.go b/credentials/alts/utils_test.go index <HASH>..<HASH> 100644 --- a/credentials/alts/utils_test.go +++ b/credentials/alts/utils_test.go @@ -1,3 +1,5 @@ +// +build linux,windows + /* * * Copyright 2018 gRPC authors.
credentials/alts: Skip ALTS tests on darwin. (#<I>) Anyways, only linux and windows are supported platforms. Running these tests on darwin causes a top level `make test` to fail, and one has to scroll all the way up to realize that it is only these alts tests which have failed, and not something that one is actively working on.
grpc_grpc-go
train
e20d9b5600acbefabae4d35bf8e5aa77a5fd97eb
diff --git a/nfsexports.go b/nfsexports.go index <HASH>..<HASH> 100644 --- a/nfsexports.go +++ b/nfsexports.go @@ -81,6 +81,31 @@ func Remove(exportsFile string, identifier string) ([]byte, error) { return newExports, nil } +// Exists checks the existence of a given export +// The export must, however, have been created by this library using Add +func Exists(exportsFile string, identifier string) (bool, error) { + if exportsFile == "" { + exportsFile = defaultExportsFile + } + + exports, err := ioutil.ReadFile(exportsFile) + if err != nil { + return false, err + } + + beginMark := []byte(fmt.Sprintf("# BEGIN: %s", identifier)) + endMark := []byte(fmt.Sprintf("# END: %s\n", identifier)) + + begin := bytes.Index(exports, beginMark) + end := bytes.Index(exports, endMark) + + if begin == -1 || end == -1 { + return false, nil + } + + return true, nil +} + // ReloadDaemon reload NFS daemon func ReloadDaemon() error { cmd := exec.Command("sudo", "nfsd", "update") diff --git a/nfsexports_test.go b/nfsexports_test.go index <HASH>..<HASH> 100644 --- a/nfsexports_test.go +++ b/nfsexports_test.go @@ -68,6 +68,42 @@ func TestAddWithInvalid(t *testing.T) { } } +func TestCheckExistsWithValid(t *testing.T) { + exportsFile, err := exportsFile(`/Users 192.168.64.1 -alldirs -maproot=root +# BEGIN: my-id +/Users 192.168.64.2 -alldirs -maproot=root +# END: my-id +`) + if err != nil { + t.Error("Failed creating test exports file", err) + } + + result, err := Exists(exportsFile, "my-id") + if err != nil { + t.Error("Checking existence of valid exports fails", err) + } else if result == false { + t.Error("Checking existence of valid exports returned false", result) + } +} + +func TestCheckExistsWithInvalid(t *testing.T) { + exportsFile, err := exportsFile(`/Users 192.168.64.1 -alldirs -maproot=root +# BEGIN: my-id +/Users 192.168.64.2 -alldirs -maproot=root +# END: my-id +`) + if err != nil { + t.Error("Failed creating test exports file", err) + } + + result, err := Exists(exportsFile, "my-invalid-id") + if err != nil { + t.Error("Checking existence of invalid exports fails", err) + } else if result == true { + t.Error("Checking existence of invalid exports returned true", result) + } +} + func TestAddNewFile(t *testing.T) { tempDir, err := ioutil.TempDir("", "nfsexports") if err != nil {
Add an `Exists` function allowing to check for the existence of a given export
johanneswuerbach_nfsexports
train
5b00a0364682618cfebd85358fa9a0419b3ea421
diff --git a/src/test/java/org/camunda/bpm/model/bpmn/builder/ProcessBuilderTest.java b/src/test/java/org/camunda/bpm/model/bpmn/builder/ProcessBuilderTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/camunda/bpm/model/bpmn/builder/ProcessBuilderTest.java +++ b/src/test/java/org/camunda/bpm/model/bpmn/builder/ProcessBuilderTest.java @@ -1827,6 +1827,46 @@ public class ProcessBuilderTest { } @Test + public void testErrorDefinitionForBoundaryEventWithoutEventDefinitionId() { + modelInstance = Bpmn.createProcess() + .startEvent() + .userTask("task") + .endEvent() + .moveToActivity("task") + .boundaryEvent("boundary") + .errorEventDefinition() + .errorCodeVariable("errorCodeVariable") + .errorMessageVariable("errorMessageVariable") + .error("errorCode") + .errorEventDefinitionDone() + .endEvent("boundaryEnd") + .done(); + + assertErrorEventDefinition("boundary", "errorCode"); + assertErrorEventDefinitionForErrorVariables("boundary", "errorCodeVariable", "errorMessageVariable"); + } + + @Test + public void testErrorDefinitionForBoundaryEventWithoutErrorEventId() { + modelInstance = Bpmn.createProcess() + .startEvent() + .userTask("task") + .endEvent() + .moveToActivity("task") + .boundaryEvent("boundary") + .errorEventDefinition() + .errorCodeVariable("errorCodeVariable") + .errorMessageVariable("errorMessageVariable") + .error("errorCode") + .errorEventDefinitionDone() + .endEvent("boundaryEnd") + .done(); + + assertErrorEventDefinition("boundary", "errorCode"); + assertErrorEventDefinitionForErrorVariables("boundary", "errorCodeVariable", "errorMessageVariable"); + } + + @Test public void testErrorEndEvent() { modelInstance = Bpmn.createProcess() .startEvent()
test(model-api): Added test cases for error event definition withour id related to #CAM-<I>
camunda_camunda-bpmn-model
train
dc5dee6b61a08555837bc34187f89d03923bf5d8
diff --git a/Holodeck/Environments.py b/Holodeck/Environments.py index <HASH>..<HASH> 100755 --- a/Holodeck/Environments.py +++ b/Holodeck/Environments.py @@ -7,6 +7,7 @@ import os import numpy as np from copy import copy +from .Agents import * from .Exceptions import HolodeckException from .ShmemClient import ShmemClient from .Sensors import Sensors @@ -14,24 +15,40 @@ from .Sensors import Sensors class AgentDefinition(object): """A class for declaring what agents are expected in a particular Holodeck Environment.""" + __agent_keys__ = {"DiscreteSphereAgent": DiscreteSphereAgent, + "UAVAgent": UAVAgent, + DiscreteSphereAgent: DiscreteSphereAgent, + UAVAgent: UAVAgent} + + @staticmethod + def __convert_sensors__(sensors): + result = [] + for sensor in sensors: + if type(sensor) == str: + result.append(Sensors.name_to_sensor(sensor)) + else: + result.append(sensor) + return result + def __init__(self, agent_name, agent_type, sensors=list()): """Constructor for AgentDefinition. Positional Arguments: agent_name -- The name of the agent to control - agent_type -- The type of HolodeckAgent to control + agent_type -- The type of HolodeckAgent to control, string or class reference Keyword arguments: - sensors -- A list of HolodeckSensors to read from this agent (default empty) + sensors -- A list of HolodeckSensors to read from this agent, string or class reference (default empty) """ super(AgentDefinition, self).__init__() self.name = agent_name - self.type = agent_type - self.sensors = sensors + self.type = AgentDefinition.__agent_keys__[agent_type] + self.sensors = AgentDefinition.__convert_sensors__(sensors) class HolodeckEnvironment(object): """The high level interface for interacting with a Holodeck Environment""" + def __init__(self, agent_definitions, binary_path=None, task_key=None, height=512, width=512, start_world=True, uuid="", gl_version=4): """Constructor for HolodeckEnvironment. diff --git a/Holodeck/Holodeck.py b/Holodeck/Holodeck.py index <HASH>..<HASH> 100644 --- a/Holodeck/Holodeck.py +++ b/Holodeck/Holodeck.py @@ -3,7 +3,6 @@ import uuid from .Environments import * from .Exceptions import HolodeckException -from .Agents import * class GL_VERSION(object): @@ -12,10 +11,7 @@ class GL_VERSION(object): def _get_worlds_map(): - string_to_agent = {"DiscreteSphereAgent": DiscreteSphereAgent, - "UAVAgent": UAVAgent} holodeck_worlds = dict() - # Load in all existing worlds holodeck_path = os.environ["HOLODECKPATH"] if holodeck_path == "": @@ -29,14 +25,12 @@ def _get_worlds_map(): with open(os.path.join(full_path, file_name), 'r') as f: config = json.load(f) for level in config["maps"]: - holodeck_worlds[level["name"]] = {"binary_path": os.path.join(full_path, config["path"]), - "agent_type": string_to_agent[level["agent"]], - "agent_name": level["agent_name"], - "task_key": level["name"], - "height": level["resy"], - "width": level["resx"], - "sensors": map(lambda x: Sensors.name_to_sensor(x), - level["sensors"])} + holodeck_worlds[level["name"]] = { + "agent_definitions": [AgentDefinition(**x) for x in level["agents"]], + "binary_path": os.path.join(full_path, config["path"]), + "task_key": level["name"], + "height": level["resy"], + "width": level["resx"]} return holodeck_worlds
Made the multi agent setup compatible with the latest changes in json loading
BYU-PCCL_holodeck
train
99cfe6fa22b95beba3dbb3524a39d0adf9287585
diff --git a/azkaban-common/src/main/java/azkaban/executor/ExecutionFlowDao.java b/azkaban-common/src/main/java/azkaban/executor/ExecutionFlowDao.java index <HASH>..<HASH> 100644 --- a/azkaban-common/src/main/java/azkaban/executor/ExecutionFlowDao.java +++ b/azkaban-common/src/main/java/azkaban/executor/ExecutionFlowDao.java @@ -46,7 +46,7 @@ public class ExecutionFlowDao { this.dbOperator = dbOperator; } - public synchronized void uploadExecutableFlow(final ExecutableFlow flow) + public void uploadExecutableFlow(final ExecutableFlow flow) throws ExecutorManagerException { final String useExecutorParam = diff --git a/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/AzkabanProcess.java b/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/AzkabanProcess.java index <HASH>..<HASH> 100644 --- a/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/AzkabanProcess.java +++ b/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/AzkabanProcess.java @@ -122,12 +122,7 @@ public class AzkabanProcess { errorGobbler.awaitCompletion(5000); if (exitCode != 0) { - final String output = - new StringBuilder().append("Stdout:\n") - .append(outputGobbler.getRecentLog()).append("\n\n") - .append("Stderr:\n").append(errorGobbler.getRecentLog()) - .append("\n").toString(); - throw new ProcessFailureException(exitCode, output); + throw new ProcessFailureException(exitCode); } } finally { diff --git a/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/ProcessFailureException.java b/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/ProcessFailureException.java index <HASH>..<HASH> 100644 --- a/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/ProcessFailureException.java +++ b/azkaban-common/src/main/java/azkaban/jobExecutor/utils/process/ProcessFailureException.java @@ -21,19 +21,17 @@ public class ProcessFailureException extends RuntimeException { private static final long serialVersionUID = 1; private final int exitCode; - private final String logSnippet; - public ProcessFailureException(final int exitCode, final String logSnippet) { + public ProcessFailureException(final int exitCode) { this.exitCode = exitCode; - this.logSnippet = logSnippet; } public int getExitCode() { return this.exitCode; } - public String getLogSnippet() { - return this.logSnippet; + @Override + public String getMessage() { + return "Process exited with code " + this.exitCode; } - } diff --git a/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java b/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java index <HASH>..<HASH> 100644 --- a/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java +++ b/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ExecutorServlet.java @@ -177,7 +177,7 @@ public class ExecutorServlet extends LoginAbstractAzkabanServlet { ret.put("project", projectName); if (ajaxName.equals("executeFlow")) { - ajaxAttemptExecuteFlow(req, resp, ret, session.getUser()); + ajaxExecuteFlow(req, resp, ret, session.getUser()); } } if (ret != null) { @@ -943,30 +943,6 @@ public class ExecutorServlet extends LoginAbstractAzkabanServlet { ret.putAll(flowObj); } - private void ajaxAttemptExecuteFlow(final HttpServletRequest req, - final HttpServletResponse resp, final HashMap<String, Object> ret, final User user) - throws ServletException { - final String projectName = getParam(req, "project"); - final String flowId = getParam(req, "flow"); - - final Project project = - getProjectAjaxByPermission(ret, projectName, user, Type.EXECUTE); - if (project == null) { - ret.put("error", "Project '" + projectName + "' doesn't exist."); - return; - } - - ret.put("flow", flowId); - final Flow flow = project.getFlow(flowId); - if (flow == null) { - ret.put("error", "Flow '" + flowId + "' cannot be found in project " - + project); - return; - } - - ajaxExecuteFlow(req, resp, ret, user); - } - private void ajaxExecuteFlow(final HttpServletRequest req, final HttpServletResponse resp, final HashMap<String, Object> ret, final User user) throws ServletException { @@ -983,8 +959,7 @@ public class ExecutorServlet extends LoginAbstractAzkabanServlet { ret.put("flow", flowId); final Flow flow = project.getFlow(flowId); if (flow == null) { - ret.put("error", "Flow '" + flowId + "' cannot be found in project " - + project); + ret.put("error", "Flow '" + flowId + "' cannot be found in project " + project); return; }
Remove unnecessary code (#<I>)
azkaban_azkaban
train
3e56c493bae0653c12b2454001c3afa798d3c331
diff --git a/tests/profiles/googlefonts_test.py b/tests/profiles/googlefonts_test.py index <HASH>..<HASH> 100644 --- a/tests/profiles/googlefonts_test.py +++ b/tests/profiles/googlefonts_test.py @@ -4081,3 +4081,21 @@ def test_check_description_urls(): good_desc = check["description"].replace(">https://", ">") assert_PASS(check(font, {"description": good_desc})) + +def test_check_metadata_unsupported_subsets(): + """Check for METADATA subsets with zero support.""" + check = CheckTester(googlefonts_profile, + "com.google.fonts/check/metadata/unsupported_subsets") + + font = TEST_FILE("librecaslontext/LibreCaslonText[wght].ttf") + assert_PASS(check(font)) + + md = check["family_metadata"] + md.subsets.extend(["foo"]) + assert_results_contain(check(font, {"family_metadata": md}), + WARN, 'unknown-subset') + + del md.subsets[:] + md.subsets.extend(["cyrillic"]) + assert_results_contain(check(font, {"family_metadata": md}), + WARN, 'unsupported-subset')
Code-test for check/metadata/unsupported_subsets (issue #<I>)
googlefonts_fontbakery
train
c73b2bc3cbc0667ea8e29eec1ebe30af69b6b0b1
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -64,13 +64,17 @@ $barbeQ = new BarbeQ($adapter, $messageDispatcher, $dispatcher); $testConsumer = new TestConsumer(); $barbeQ->addConsumer('test', $testConsumer); -$barbeQ->eat( - 'test', - 5, - function($i, MessageInterface $message) { - error_log(sprintf('For Iteration #%d, Memory: %s, Time: %0.04fs', $i, $message->getMemory(), $message->getTime())); - } -); +// Trace what's happening +$barbeQ->addListener('barbeq.pre_consume', function(ConsumeEvent $event) { + echo sprintf("Start consuming message #%d\n", $event->getMessage()->getMetadataValue('index')); +}); + +$barbeQ->addListener('barbeq.post_consume', function(ConsumeEvent $event) { + echo sprintf("Memory: %s, Time: %0.04fs\n", $event->getMessage()->getMemory(), $event->getMessage()->getTime()); +}); + +$barbeQ->eat('test', 5); +// or $barbeQ->consume(...), same action ``` Credits diff --git a/src/BarbeQ/BarbeQ.php b/src/BarbeQ/BarbeQ.php index <HASH>..<HASH> 100644 --- a/src/BarbeQ/BarbeQ.php +++ b/src/BarbeQ/BarbeQ.php @@ -79,17 +79,16 @@ class BarbeQ * * @param string $queue * @param int $amount - * @param \Closure $callback * * @return void */ - public function consume($queue, $amount = 50, \Closure $callback) + public function consume($queue, $amount = 50) { $i = 0; foreach ($this->getMessages($queue) as $message) { $i++; + $message->addMetadata('index', $i); $this->consumeOne($message); - $callback($i, $message); if ($i >= $amount) { $this->stopConsuming(); @@ -119,6 +118,8 @@ class BarbeQ $this->adapter->onSuccess($message); $message->complete(); + + $this->dispatcher->dispatch(BarbeQEvents::POST_CONSUME, $consumeEvent); } catch(ConsumerIndigestionException $e) { $this->adapter->onError($message); @@ -137,13 +138,12 @@ class BarbeQ * * @param string $queue * @param int $amount - * @param \Closure $callback * * @return void */ - public function eat($queue, $amount = 50, \Closure $callback) + public function eat($queue, $amount = 50) { - $this->consume($queue, $amount, $callback); + $this->consume($queue, $amount); } /** @@ -167,4 +167,28 @@ class BarbeQ { $this->getAdapter()->stopConsuming(); } + + /** + * Adds an event listener that listens on the specified events. + * + * @param string $eventName The event to listen on + * @param callable $listener The listener + * @param integer $priority The higher this value, the earlier an event + * listener will be triggered in the chain (defaults to 0) + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addListener($eventName, $listener, $priority = 0) + { + if (!in_array($eventName, array( + BarbeQEvents::PRE_CONSUME, + BarbeQEvents::POST_CONSUME, + ))) { + throw new \InvalidArgumentException(sprintf('"%s" event does not exist in BarbeQ.', $eventName)); + } + + $this->dispatcher->addListener($eventName, $listener, $priority); + } } \ No newline at end of file diff --git a/src/BarbeQ/BarbeQEvents.php b/src/BarbeQ/BarbeQEvents.php index <HASH>..<HASH> 100644 --- a/src/BarbeQ/BarbeQEvents.php +++ b/src/BarbeQ/BarbeQEvents.php @@ -10,6 +10,6 @@ namespace BarbeQ; final class BarbeQEvents { - const PRE_CONSUME = 'ano_mq.pre_consume'; - const POST_CONSUME = 'ano_mq.post_consume'; + const PRE_CONSUME = 'barbeq.pre_consume'; + const POST_CONSUME = 'barbeq.post_consume'; } \ No newline at end of file
Removed closure since event listeners are already used. Added an addListener method to BarbeQ + Updated README code example
benjamindulau_BarbeQ
train
d1a72fc5e189f332e96c0855b0f1e5305418fd27
diff --git a/scandir.py b/scandir.py index <HASH>..<HASH> 100644 --- a/scandir.py +++ b/scandir.py @@ -12,23 +12,14 @@ the full license text. from __future__ import division -import collections import ctypes -import fnmatch import os import stat import sys -import warnings __version__ = '0.2' __all__ = ['scandir', 'walk'] -# Python 3 support -try: - unicode -except NameError: - unicode = str - # Shortcuts to these functions for speed and ease join = os.path.join lstat = os.lstat @@ -188,7 +179,7 @@ elif sys.platform.startswith(('linux', 'darwin')) or 'bsd' in sys.platform: # Rather annoying how the dirent struct is slightly different on each # platform. The only fields we care about are d_name and d_type. - class dirent(ctypes.Structure): + class Dirent(ctypes.Structure): if sys.platform.startswith('linux'): _fields_ = ( ('d_ino', ctypes.c_ulong), @@ -211,8 +202,8 @@ elif sys.platform.startswith(('linux', 'darwin')) or 'bsd' in sys.platform: DT_REG = 8 DT_LNK = 10 - dirent_p = ctypes.POINTER(dirent) - dirent_pp = ctypes.POINTER(dirent_p) + Dirent_p = ctypes.POINTER(Dirent) + Dirent_pp = ctypes.POINTER(Dirent_p) libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True) opendir = libc.opendir @@ -220,7 +211,7 @@ elif sys.platform.startswith(('linux', 'darwin')) or 'bsd' in sys.platform: opendir.restype = DIR_p readdir_r = libc.readdir_r - readdir_r.argtypes = [DIR_p, dirent_p, dirent_pp] + readdir_r.argtypes = [DIR_p, Dirent_p, Dirent_pp] readdir_r.restype = ctypes.c_int closedir = libc.closedir @@ -293,9 +284,9 @@ elif sys.platform.startswith(('linux', 'darwin')) or 'bsd' in sys.platform: if not dir_p: raise posix_error(path) try: - result = dirent_p() + result = Dirent_p() while True: - entry = dirent() + entry = Dirent() if readdir_r(dir_p, entry, result): raise posix_error(path) if not result:
Fix a few issues that pylint noticed.
benhoyt_scandir
train
fb074813ea68faae1293c8054e365dc52153ace8
diff --git a/lib/raven/rack.rb b/lib/raven/rack.rb index <HASH>..<HASH> 100644 --- a/lib/raven/rack.rb +++ b/lib/raven/rack.rb @@ -34,7 +34,7 @@ module Raven end if env['rack.exception'] - evt = Event.capture_rack_exception(e, env) + evt = Event.capture_rack_exception(env['rack.exception'], env) Raven.send(evt) if evt end diff --git a/spec/raven/rack_spec.rb b/spec/raven/rack_spec.rb index <HASH>..<HASH> 100644 --- a/spec/raven/rack_spec.rb +++ b/spec/raven/rack_spec.rb @@ -11,17 +11,33 @@ describe Raven::Rack do it 'should capture exceptions' do exception = build_exception() - env = { 'key' => 'value' } + env = {} + + Raven::Event.should_receive(:capture_rack_exception).with(exception, env) + Raven.should_receive(:send).with(@event) app = lambda do |e| raise exception end stack = Raven::Rack.new(app) + lambda {stack.call(env)}.should raise_error(exception) + end + + it 'should capture rack.exception' do + exception = build_exception() + env = {} Raven::Event.should_receive(:capture_rack_exception).with(exception, env) Raven.should_receive(:send).with(@event) - - lambda {stack.call(env)}.should raise_error(exception) + + app = lambda do |e| + e['rack.exception'] = exception + [200, {}, ['okay']] + end + + stack = Raven::Rack.new(app) + + stack.call(env) end end
Correct rack.exception behavior and add corresponding test
getsentry_raven-ruby
train