hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
c19ab917a3e1d777ceccd3becc84870b700a09f2
diff --git a/examples/example.php b/examples/example.php index <HASH>..<HASH> 100755 --- a/examples/example.php +++ b/examples/example.php @@ -2,15 +2,14 @@ require_once '../vendor/autoload.php'; $arrCredentials = array( -'username' => 'xxx', -'password' => 'xxx', -'identifier' => '1' + 'username' => 'xxx', + 'password' => 'xxx' ); try { $objGarminConnect = new \dawguk\GarminConnect($arrCredentials); - $objResults = $objGarminConnect->getExtendedActivityDetails(593520370); + $objResults = $objGarminConnect->getActivityList(); print_r($objResults); } catch (Exception $objException) { diff --git a/src/dawguk/GarminConnect.php b/src/dawguk/GarminConnect.php index <HASH>..<HASH> 100755 --- a/src/dawguk/GarminConnect.php +++ b/src/dawguk/GarminConnect.php @@ -57,12 +57,7 @@ class GarminConnect { $this->strUsername = $arrCredentials['username']; unset($arrCredentials['username']); - if (!isset($arrCredentials['identifier'])) { - throw new \Exception("Identifier credential missing"); - } - - $intIdentifier = $arrCredentials['identifier']; - unset($arrCredentials['identifier']); + $intIdentifier = md5($this->strUsername); $this->objConnector = new Connector($intIdentifier); diff --git a/src/dawguk/GarminConnect/Connector.php b/src/dawguk/GarminConnect/Connector.php index <HASH>..<HASH> 100755 --- a/src/dawguk/GarminConnect/Connector.php +++ b/src/dawguk/GarminConnect/Connector.php @@ -19,13 +19,12 @@ namespace dawguk\GarminConnect; class Connector { - const COOKIE_DIRECTORY = '/tmp/'; - /** * @var null|resource */ private $objCurl = NULL; private $arrCurlInfo = array(); + private $strCookieDirectory = ''; /** * @var array @@ -36,7 +35,8 @@ class Connector { CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_COOKIESESSION => FALSE, CURLOPT_AUTOREFERER => TRUE, - CURLOPT_VERBOSE => FALSE + CURLOPT_VERBOSE => FALSE, + CURLOPT_FRESH_CONNECT => TRUE ); /** @@ -47,17 +47,18 @@ class Connector { /** * @var string */ - private $strUniqueIdentifier = ''; + private $strCookieFile = ''; /** * @param string $strUniqueIdentifier * @throws \Exception */ public function __construct($strUniqueIdentifier) { + $this->strCookieDirectory = sys_get_temp_dir(); if (strlen(trim($strUniqueIdentifier)) == 0) { throw new \Exception("Identifier isn't valid"); } - $this->strUniqueIdentifier = $strUniqueIdentifier; + $this->strCookieFile = $this->strCookieDirectory . DIRECTORY_SEPARATOR . "GarminCookie_" . $strUniqueIdentifier; $this->refreshSession(); } @@ -66,8 +67,8 @@ class Connector { */ public function refreshSession() { $this->objCurl = curl_init(); - $this->arrCurlOptions[CURLOPT_COOKIEJAR] = self::COOKIE_DIRECTORY . $this->strUniqueIdentifier; - $this->arrCurlOptions[CURLOPT_COOKIEFILE] = self::COOKIE_DIRECTORY . $this->strUniqueIdentifier; + $this->arrCurlOptions[CURLOPT_COOKIEJAR] = $this->strCookieFile; + $this->arrCurlOptions[CURLOPT_COOKIEFILE] = $this->strCookieFile; curl_setopt_array($this->objCurl, $this->arrCurlOptions); } @@ -82,7 +83,6 @@ class Connector { $strUrl .= '?' . http_build_query($arrParams); } - curl_setopt($this->objCurl, CURLOPT_FRESH_CONNECT, TRUE); curl_setopt($this->objCurl, CURLOPT_URL, $strUrl); curl_setopt($this->objCurl, CURLOPT_FOLLOWLOCATION, (bool)$bolAllowRedirects); curl_setopt($this->objCurl, CURLOPT_CUSTOMREQUEST, 'GET'); @@ -139,8 +139,8 @@ class Connector { * Removes the cookie */ public function clearCookie() { - if (file_exists(self::COOKIE_DIRECTORY . $this->strUniqueIdentifier)) { - unlink(self::COOKIE_DIRECTORY . $this->strUniqueIdentifier); + if (file_exists($this->strCookieFile)) { + unlink($this->strCookieFile); } }
Re-jigging cookie storage for non-Linux systems Update: Now using sys_get_temp_dir() to get the native OS temporary directory Update: Removed requirement to specify an identifier in the credentials - the identifier is now generated by using md5 on the username. This should ensure that user switching is easier, and makes much more sense anyway.
dawguk_php-garmin-connect
train
68dd0a24fb515eccadd6685cc85cdd7039e0f4e2
diff --git a/auth/authdb/sessions.go b/auth/authdb/sessions.go index <HASH>..<HASH> 100644 --- a/auth/authdb/sessions.go +++ b/auth/authdb/sessions.go @@ -16,7 +16,7 @@ type SessionManager struct { } // Create creates a new session using a key generated for the given User -func (m *SessionManager) Create(user User) (auth.Session, error) { +func (m *SessionManager) Create(user auth.User) (auth.Session, error) { s := &Session{ UserField: user.ID(), } @@ -32,8 +32,12 @@ func (m *SessionManager) Create(user User) (auth.Session, error) { return s, auth.NewServerError("authdb: key generation error: %s", err) } // TODO distinguish between no response and an improper query - session, _ := m.Get(s.KeyField) - if session == nil { + var sessions []Session + stmt := Sessions.Select().Where(Sessions.C["key"].Equals(s.KeyField)).Limit(2) + if err = m.db.QueryAll(stmt, &sessions); err != nil { + return s, auth.NewServerError("authdb: error checking if key exists: %s", err) + } + if len(sessions) == 0 { break } } @@ -73,6 +77,15 @@ func (m *SessionManager) Delete(key string) error { return err } +func NewSessionManager(db *aspect.DB, c config.CookieConfig) *SessionManager { + return &SessionManager{ + db: db, + cookie: c, + keyFunc: auth.RandomKey, + nowFunc: time.Now, + } +} + // Session is a database-backed session that implements the volta auth.Session // interface. type Session struct { diff --git a/auth/authdb/users.go b/auth/authdb/users.go index <HASH>..<HASH> 100644 --- a/auth/authdb/users.go +++ b/auth/authdb/users.go @@ -75,7 +75,7 @@ func (m *UserManager) Get(fields auth.Fields) (auth.User, error) { } // Get the user at the given name var user User - stmt := Users.Select().Where(Users.C["name"].Equals(name)) + stmt := Users.Select().Where(Users.C["email"].Equals(name)) if err := m.db.QueryOne(stmt, &user); err != nil { // TODO distinguish between no response and an improper query return &user, auth.NewUserError("no user with name %s exists", name) @@ -98,6 +98,13 @@ func (m *UserManager) Delete(id int64) (auth.User, error) { return nil, nil } +func NewUserManager(db *aspect.DB, h auth.Hasher) *UserManager { + return &UserManager{ + db: db, + h: h, + } +} + // User is a database-backed user that implements the volta auth.User // interface. type User struct { @@ -136,7 +143,7 @@ func (u *User) Delete() (err error) { } var Users = aspect.Table("users", - aspect.Column("id", aspect.Integer{}), + aspect.Column("id", postgres.Serial{}), aspect.Column("email", aspect.String{}), aspect.Column("password", aspect.String{}), aspect.Column("is_admin", aspect.Boolean{}),
Added create functions for authdb session and user managers
aodin_volta
train
1b6e00559cdfe886c0ea8ced6e7c32b7686b919b
diff --git a/js/jsbin-embed.js b/js/jsbin-embed.js index <HASH>..<HASH> 100644 --- a/js/jsbin-embed.js +++ b/js/jsbin-embed.js @@ -54,17 +54,26 @@ function findCodeInParent(element) { function findCode(link) { var rel = link.rel, + query = link.search.substring(1), element, - code; - - if (!rel) { + code, + panels = []; + + if (rel && element = document.getElementById(rel.substring(1))) { + code = element[innerText]; + // else - try to support multiple targets for each panel... + // } else if (query.indexOf('=') !== -1) { + // // assumes one of the panels points to an ID + // query.replace(/([^,=]*)=([^,=]*)/g, function (all, key, value) { + // code = document.getElementById(value.substring(1))[innerText]; + + // }); + } else { // go looking through it's parents element = findCodeInParent(link); if (element) { code = element[innerText]; } - } else { - code = document.getElementById(rel.substring(1))[innerText]; } return code;
Be nice to support multiple code blocks for embed - not for now though
jsbin_jsbin
train
dbdb7632577194a63ca2c37734809b25641f9288
diff --git a/system/Config/AutoloadConfig.php b/system/Config/AutoloadConfig.php index <HASH>..<HASH> 100644 --- a/system/Config/AutoloadConfig.php +++ b/system/Config/AutoloadConfig.php @@ -181,9 +181,13 @@ class AutoloadConfig 'CodeIgniter\View\Parser' => BASEPATH . 'View/Parser.php', 'CodeIgniter\View\Cell' => BASEPATH . 'View/Cell.php', 'Zend\Escaper\Escaper' => BASEPATH . 'ThirdParty/ZendEscaper/Escaper.php', - 'CodeIgniter\Log\TestLogger' => SUPPORTPATH . 'Log/TestLogger.php', - 'CIDatabaseTestCase' => SUPPORTPATH . 'CIDatabaseTestCase.php', ]; + + if (isset($_SERVER['CI_ENVIRONMENT']) && $_SERVER['CI_ENVIRONMENT'] === 'testing') + { + $this->classmap['CodeIgniter\Log\TestLogger'] = SUPPORTPATH . 'Log/TestLogger.php'; + $this->classmap['CIDatabaseTestCase'] = SUPPORTPATH . 'CIDatabaseTestCase.php'; + } } //--------------------------------------------------------------------
use SUPPORTPATH constant int classmap definition as well
codeigniter4_CodeIgniter4
train
770d5918fdbffdb8c590bc6d3868ef09b48c54be
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,6 +1,7 @@ +require(File.expand_path('../../lib/lyricfy', __FILE__)) + require 'minitest/autorun' require 'minitest/pride' -require 'lyricfy' require 'webmock' require 'webmock/minitest' require 'vcr'
Change test helper to require Lyricfy relative path
javichito_Lyricfy
train
c33c6bb90f5a80656750b5a4d58f042573ff695e
diff --git a/kernel/classes/ezcontentobject.php b/kernel/classes/ezcontentobject.php index <HASH>..<HASH> 100644 --- a/kernel/classes/ezcontentobject.php +++ b/kernel/classes/ezcontentobject.php @@ -3528,7 +3528,11 @@ class eZContentObject extends eZPersistentObject { if ( isset( $params['IgnoreVisibility'] ) ) { - $showInvisibleNodesCond = self::createFilterByVisibilitySQLString( $params['IgnoreVisibility'], 'inner_object' ); + $showInvisibleNodesCond = self::createFilterByVisibilitySQLString( + $params['IgnoreVisibility'], + // inner_object represents the source of relation while outer_object represents the target + $reverseRelatedObjects ? 'inner_object' : 'outer_object' + ); } }
Fix EZP-<I> : When calling the method eZContentObject::relatedObjectCount with the IgnoreVisibility parameter, the count is not correct
ezsystems_ezpublish-legacy
train
0f54b4437345dfadbff20479adc17ccd22fe36db
diff --git a/keysmith.py b/keysmith.py index <HASH>..<HASH> 100644 --- a/keysmith.py +++ b/keysmith.py @@ -7,7 +7,7 @@ import string import sys from typing import Callable, Sequence -__version__ = '3.0.0' +__version__ = '3.0.1' CONSOLE_SCRIPT = 'keysmith'
Bump the version to <I>
dmtucker_keysmith
train
044f3e8725ee06e42e476578fdab5136c3f5e70f
diff --git a/src/Utility/Validate/Utility.php b/src/Utility/Validate/Utility.php index <HASH>..<HASH> 100644 --- a/src/Utility/Validate/Utility.php +++ b/src/Utility/Validate/Utility.php @@ -12,11 +12,13 @@ namespace CsvMigrations\Utility\Validate; use Cake\Core\Configure; +use Cake\Utility\Hash; use CsvMigrations\FieldHandlers\Config\ConfigFactory; use InvalidArgumentException; use Qobo\Utils\ModuleConfig\ConfigType; use Qobo\Utils\ModuleConfig\ModuleConfig; use Qobo\Utils\Utility as QoboUtility; +use Qobo\Utils\Utility\Convert; /** * Utility Class @@ -96,33 +98,53 @@ class Utility */ public static function isRealModuleField(string $module, string $field) : bool { - $moduleFields = []; - try { - $mc = new ModuleConfig(ConfigType::MIGRATION(), $module, null, ['cacheSkip' => true]); - $moduleFields = json_encode($mc->parse()); - if (false === $moduleFields) { - return false; - } - $moduleFields = json_decode($moduleFields, true); - } catch (InvalidArgumentException $e) { - // We already report issues with migration in _checkMigrationPresence() - return true; - } + $fields = self::getRealModuleFields($module); // If we couldn't get the migration, we cannot verify if the // field is real or not. To avoid unnecessary fails, we // assume that it's real. - if (empty($moduleFields)) { + if (empty($fields)) { return true; } - foreach ($moduleFields as $moduleField) { - if ($field == $moduleField['name']) { - return true; - } + return in_array($field, $fields); + } + + /** + * Returns a list of fields defined in `migration.json`. + * + * @param string $module Module name. + * @return string[] List of fields. + */ + public static function getRealModuleFields(string $module) : array + { + $moduleFields = []; + + $mc = new ModuleConfig(ConfigType::MIGRATION(), $module, null, ['cacheSkip' => true]); + $moduleFields = Convert::objectToArray($mc->parse()); + $fields = Hash::extract($moduleFields, '{*}.name'); + + return (array)$fields; + } + + /** + * Returns a list of virtual fields in `config.json`. + * + * @param string $module Module name. + * @return string[] list of virtual fields. + */ + public static function getVirtualModuleFields(string $module) : array + { + $fields = []; + + $mc = new ModuleConfig(ConfigType::MODULE(), $module, null, ['cacheSkip' => true]); + $virtualFields = Convert::objectToArray($mc->parse()); + + if (isset($virtualFields['virtualFields'])) { + $fields = $virtualFields['virtualFields']; } - return false; + return $fields; } /** @@ -138,31 +160,13 @@ class Utility */ public static function isVirtualModuleField(string $module, string $field) : bool { - $config = []; - try { - $mc = new ModuleConfig(ConfigType::MODULE(), $module, null, ['cacheSkip' => true]); - $config = json_encode($mc->parse()); - if (false === $config) { - return false; - } - $config = (array)json_decode($config, true); - } catch (InvalidArgumentException $e) { - return false; - } - - if (empty($config)) { - return false; - } - - if (empty($config['virtualFields'])) { - return false; - } + $config = self::getVirtualModuleFields($module); - if (! is_array($config['virtualFields'])) { + if (empty($config) || !is_array($config)) { return false; } - return in_array($field, array_keys($config['virtualFields'])); + return in_array($field, array_keys($config)); } /**
Add extra methods for fetching field name to validation utility class (task #<I>)
QoboLtd_cakephp-csv-migrations
train
e33c6e912e0f5db99413badeaf361ffc28df7d13
diff --git a/peewee.py b/peewee.py index <HASH>..<HASH> 100644 --- a/peewee.py +++ b/peewee.py @@ -3646,7 +3646,10 @@ class CursorWrapper(object): def iterator(self): """Efficient one-pass iteration over the result set.""" while True: - yield self.iterate(False) + try: + yield self.iterate(False) + except StopIteration: + return def fill_cache(self, n=0): n = n or float('Inf')
Fix compatibility with Python <I>
coleifer_peewee
train
d834c7244c0911d4f289a5e8f67a8c649b522ba2
diff --git a/userena/managers.py b/userena/managers.py index <HASH>..<HASH> 100644 --- a/userena/managers.py +++ b/userena/managers.py @@ -5,7 +5,7 @@ from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext as _ from userena import settings as userena_settings -from userena.utils import generate_sha1, get_profile_model +from userena.utils import generate_sha1, get_profile_model, get_datetime_now from userena import signals as userena_signals from guardian.shortcuts import assign, get_perms @@ -53,7 +53,7 @@ class UserenaManager(UserManager): :return: :class:`User` instance representing the new user. """ - now = datetime.datetime.now() + now = get_datetime_now() new_user = User.objects.create_user(username, email, password) new_user.is_active = active
Changed a call from datetime.datetime.now() to get_datetime_now() for Django <I> compatibility.
django-userena-ce_django-userena-ce
train
4da3d47e1d164eb65d14bc62ba407f14e60df9e1
diff --git a/go/vt/worker/vtworkerclient/client_testsuite.go b/go/vt/worker/vtworkerclient/client_testsuite.go index <HASH>..<HASH> 100644 --- a/go/vt/worker/vtworkerclient/client_testsuite.go +++ b/go/vt/worker/vtworkerclient/client_testsuite.go @@ -55,6 +55,11 @@ func commandSucceeds(t *testing.T, client VtworkerClient) { if err := errFunc(); err != nil { t.Fatalf("Remote error: %v", err) } + + _, errFuncReset := client.ExecuteVtworkerCommand(context.Background(), []string{"Reset"}) + if err := errFuncReset(); err != nil { + t.Fatalf("Cannot execute remote command: %v", err) + } } func commandErrors(t *testing.T, client VtworkerClient) { @@ -84,11 +89,6 @@ func commandErrors(t *testing.T, client VtworkerClient) { } func commandPanics(t *testing.T, client VtworkerClient) { - _, errFuncReset := client.ExecuteVtworkerCommand(context.Background(), []string{"Reset"}) - if err := errFuncReset(); err != nil { - t.Fatalf("Cannot execute remote command: %v", err) - } - logs, errFunc := client.ExecuteVtworkerCommand(context.Background(), []string{"Panic"}) if err := errFunc(); err != nil { t.Fatalf("Cannot execute remote command: %v", err)
vtworker: client_testsuite: Move Reset() at the end of the test whose command should actually be reset.
vitessio_vitess
train
7f628d3c34d6dfe1d339aeefecf03342a55eb197
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ Props | Type | Default Value | Descripti `customPaging` | `func` | `i => <button>{i + 1}</button>` | Custom paging templates. [Example](examples/CustomPaging.js) | Yes `dots` | `bool` | `Default` | | Yes `dotsClass` | `string` | `'slick-dots'` | CSS class for dots | Yes -`renderDots` | `func` | `dots => <ul>{dots}</ul>` | Custom dots templates. Works same as customPaging | Yes +`appendDots` | `func` | `dots => <ul>{dots}</ul>` | Custom dots templates. Works same as customPaging | Yes `draggable` | `bool` | `true` | Enable scrollable via dragging on desktop | Yes `easing` | `string` | `'linear'` | | `fade` | `bool` | `Default` | | Yes diff --git a/src/default-props.js b/src/default-props.js index <HASH>..<HASH> 100644 --- a/src/default-props.js +++ b/src/default-props.js @@ -47,7 +47,7 @@ var defaultProps = { // nextArrow, prevArrow should react componets nextArrow: null, prevArrow: null, - renderDots: function(dots) { + appendDots: function(dots) { return <ul style={{display: 'block'}}>{dots}</ul>; } }; diff --git a/src/dots.js b/src/dots.js index <HASH>..<HASH> 100644 --- a/src/dots.js +++ b/src/dots.js @@ -59,6 +59,6 @@ export class Dots extends React.Component { ); }); - return React.cloneElement(this.props.renderDots(dots), {className: this.props.dotsClass}); + return React.cloneElement(this.props.appendDots(dots), {className: this.props.dotsClass}); } } diff --git a/src/inner-slider.js b/src/inner-slider.js index <HASH>..<HASH> 100644 --- a/src/inner-slider.js +++ b/src/inner-slider.js @@ -198,7 +198,7 @@ export var InnerSlider = createReactClass({ children: this.props.children, customPaging: this.props.customPaging, infinite: this.props.infinite, - renderDots: this.props.renderDots + appendDots: this.props.appendDots }; dots = (<Dots {...dotProps} />);
renamed renderDots to appendDots to follow slick naming convention
akiran_react-slick
train
b433666bb87bfa2185916670ae95272fab6a3284
diff --git a/structr-ui/src/main/java/org/structr/web/resource/LoginResource.java b/structr-ui/src/main/java/org/structr/web/resource/LoginResource.java index <HASH>..<HASH> 100644 --- a/structr-ui/src/main/java/org/structr/web/resource/LoginResource.java +++ b/structr-ui/src/main/java/org/structr/web/resource/LoginResource.java @@ -19,25 +19,21 @@ package org.structr.web.resource; -import org.structr.common.SecurityContext; -import org.structr.common.error.FrameworkException; -import org.structr.core.Result; -import org.structr.rest.RestMethodResult; -import org.structr.rest.exception.IllegalMethodException; -import org.structr.rest.exception.NotAllowedException; -import org.structr.rest.resource.Resource; - -//~--- JDK imports ------------------------------------------------------------ - import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; - import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; +import org.structr.common.SecurityContext; +import org.structr.common.error.FrameworkException; +import org.structr.core.Result; import org.structr.core.entity.Principal; import org.structr.core.property.PropertyKey; import org.structr.core.property.PropertyMap; +import org.structr.rest.RestMethodResult; +import org.structr.rest.exception.IllegalMethodException; +import org.structr.rest.exception.NotAllowedException; +import org.structr.rest.resource.Resource; import org.structr.web.entity.User; //~--- classes ---------------------------------------------------------------- @@ -94,7 +90,7 @@ public class LoginResource extends Resource { } - logger.log(Level.INFO, "Invalid credentials (name, password): {0}, {1}, {2}", new Object[]{ name, password }); + logger.log(Level.INFO, "Invalid credentials (name, email, password): {0}, {1}, {2}", new Object[]{ name, email, password }); return new RestMethodResult(401);
Fixed logging by adding third parameter.
structr_structr
train
9afd5ff712e552accfd45fdabea657e2b7fe1d44
diff --git a/internal/lib/container_server.go b/internal/lib/container_server.go index <HASH>..<HASH> 100644 --- a/internal/lib/container_server.go +++ b/internal/lib/container_server.go @@ -151,11 +151,11 @@ func (c *ContainerServer) LoadSandbox(id string) error { } var m rspec.Spec if err := json.Unmarshal(config, &m); err != nil { - return err + return errors.Wrap(err, "error unmarshalling sandbox spec") } labels := make(map[string]string) if err := json.Unmarshal([]byte(m.Annotations[annotations.Labels]), &labels); err != nil { - return err + return errors.Wrapf(err, "error unmarshalling %s annotation", annotations.Labels) } name := m.Annotations[annotations.Name] name, err = c.ReservePodName(id, name) @@ -169,7 +169,7 @@ func (c *ContainerServer) LoadSandbox(id string) error { }() var metadata pb.PodSandboxMetadata if err := json.Unmarshal([]byte(m.Annotations[annotations.Metadata]), &metadata); err != nil { - return err + return errors.Wrapf(err, "error unmarshalling %s annotation", annotations.Metadata) } processLabel := m.Process.SelinuxLabel @@ -179,19 +179,19 @@ func (c *ContainerServer) LoadSandbox(id string) error { kubeAnnotations := make(map[string]string) if err := json.Unmarshal([]byte(m.Annotations[annotations.Annotations]), &kubeAnnotations); err != nil { - return err + return errors.Wrapf(err, "error unmarshalling %s annotation", annotations.Annotations) } portMappings := []*hostport.PortMapping{} if err := json.Unmarshal([]byte(m.Annotations[annotations.PortMappings]), &portMappings); err != nil { - return err + return errors.Wrapf(err, "error unmarshalling %s annotation", annotations.PortMappings) } privileged := isTrue(m.Annotations[annotations.PrivilegedRuntime]) hostNetwork := isTrue(m.Annotations[annotations.HostNetwork]) nsOpts := pb.NamespaceOption{} if err := json.Unmarshal([]byte(m.Annotations[annotations.NamespaceOptions]), &nsOpts); err != nil { - return err + return errors.Wrapf(err, "error unmarshalling %s annotation", annotations.NamespaceOptions) } sb, err := sandbox.New(id, m.Annotations[annotations.Namespace], name, m.Annotations[annotations.KubeName], filepath.Dir(m.Annotations[annotations.LogPath]), labels, kubeAnnotations, processLabel, mountLabel, &metadata, m.Annotations[annotations.ShmPath], m.Annotations[annotations.CgroupParent], privileged, m.Annotations[annotations.RuntimeHandler], m.Annotations[annotations.ResolvPath], m.Annotations[annotations.HostName], portMappings, hostNetwork)
container_server: Wrap a few more errors in LoadSandbox This should give more helpful messages in the logs whe LoadSandbox fails. Especially if something is wrong with the nested JSON structures in the Sandbox config.
cri-o_cri-o
train
cc98679e565be7802f0c6d7e66005f42dc92a0ad
diff --git a/deis/__init__.py b/deis/__init__.py index <HASH>..<HASH> 100644 --- a/deis/__init__.py +++ b/deis/__init__.py @@ -6,4 +6,4 @@ the api, provider, cm, and web Django apps. from __future__ import absolute_import -__version__ = '1.2.0-dev' +__version__ = '1.2.0'
chore(release): update version to <I>
deis_controller-sdk-go
train
066435d6f07bdc596f9eecd92ae4f9b67faf5197
diff --git a/l20n/ast.py b/l20n/ast.py index <HASH>..<HASH> 100644 --- a/l20n/ast.py +++ b/l20n/ast.py @@ -53,10 +53,10 @@ class String(Value): content = pyast.field(str) class Array(Value): - content = pyast.seq(Value) + content = pyast.seq(Value, null=True) class Hash(Value): - content = pyast.seq(KeyValuePair) + content = pyast.seq(KeyValuePair, null=True) ### Operators @@ -93,8 +93,8 @@ class UnaryExpression(Expression): argument = pyast.field(Expression) class CallExpression(Expression): - callee = pyast.field(Expression) - arguments = pyast.seq(Expression) + callee = pyast.field(Identifier) + arguments = pyast.seq(Expression, null=True) class LogicalExpression(Expression): operator = pyast.field(LogicalOperator) @@ -102,10 +102,14 @@ class LogicalExpression(Expression): right = pyast.field(Expression) class MemberExpression(Expression): - pass + object = pyast.field(Identifier) + property = pyast.field(Expression) + computed = pyast.field(bool) class AttributeExpression(Expression): - pass + object = pyast.field(Identifier) + attribute = pyast.field(Expression) + computed = pyast.field(bool) class ParenthesisExpression(Expression): expression = pyast.field(Expression)
update the AST for AttributeExpression, MemberExpression and CallExpression and allow for Hash and Array value to be empty
l20n_l20n.js
train
41fdea08a5d204990d1d70b7cef414a5a2ba358e
diff --git a/.gitignore b/.gitignore index <HASH>..<HASH> 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,5 @@ tags *.tar.gz *.tgz .ipynb_checkpoints -*.orig \ No newline at end of file +*.orig +.cache \ No newline at end of file diff --git a/bambi/tests/test_built_models.py b/bambi/tests/test_built_models.py index <HASH>..<HASH> 100644 --- a/bambi/tests/test_built_models.py +++ b/bambi/tests/test_built_models.py @@ -298,16 +298,29 @@ def test_cell_means_with_random_intercepts(crossed_data): assert set(priors0) == set(priors1) # test summary - fitted.summary() - fitted.summary(exclude_ranefs=False) + # it looks like some versions of pymc3 add a trailing '_' to transformed + # vars and some dont. so here for consistency we strip out any trailing '_' + # that we find + full = fitted.summary(exclude_ranefs=False, hide_transformed=False).index + full = set([re.sub(r'_$', r'', x) for x in full]) + test_set = fitted.summary(exclude_ranefs=False).index + test_set = set([re.sub(r'_$', r'', x) for x in test_set]) + assert test_set == full.difference(set(['Y_sd_interval', 'u_subj_sd_log'])) + test_set = fitted.summary(hide_transformed=False).index + test_set = set([re.sub(r'_$', r'', x) for x in test_set]) + assert test_set == full.difference( + set(['subj[{}]'.format(i) for i in range(10)])) + + # test get_trace + test_set = fitted.get_trace().columns + test_set = set([re.sub(r'_$', r'', x) for x in test_set]) + assert test_set == full.difference(set(['Y_sd_interval', 'u_subj_sd_log'])) \ + .difference(set(['subj[{}]'.format(i) for i in range(10)])) # test plots fitted.plot(kind='priors') fitted.plot() - # test get_trace - fitted.get_trace() - def test_random_intercepts(crossed_data): # using formula and '1|' syntax diff --git a/bambi/tests/test_model_construction.py b/bambi/tests/test_model_construction.py index <HASH>..<HASH> 100644 --- a/bambi/tests/test_model_construction.py +++ b/bambi/tests/test_model_construction.py @@ -10,7 +10,6 @@ matplotlib.use('Agg') @pytest.fixture(scope="module") def diabetes_data(): - from os.path import dirname, join data_dir = join(dirname(__file__), 'data') data = pd.read_csv(join(data_dir, 'diabetes.txt'), sep='\t') data['age_grp'] = 0
revert mangled test and cleanup
bambinos_bambi
train
aadd3eba5b423cc86f299e7088e996a4767dd7d8
diff --git a/tchannel/tornado/connection.py b/tchannel/tornado/connection.py index <HASH>..<HASH> 100644 --- a/tchannel/tornado/connection.py +++ b/tchannel/tornado/connection.py @@ -654,7 +654,10 @@ class Reader(object): if f.exception(): self.filling = False # This is usually StreamClosed due to a client disconnecting. - return log.info("read error", exc_info=f.exc_info()) + if isinstance(f.exception(), StreamClosedError): + return log.info("read error", exc_info=f.exc_info()) + else: + return log.error("read error", exc_info=f.exc_info()) # connect these two in the case when put blocks self.queue.put(f.result()).add_done_callback( lambda f: io_loop.spawn_callback(self.fill), diff --git a/tests/tornado/test_connection.py b/tests/tornado/test_connection.py index <HASH>..<HASH> 100644 --- a/tests/tornado/test_connection.py +++ b/tests/tornado/test_connection.py @@ -24,6 +24,7 @@ import mock import pytest import tornado.ioloop from tornado import gen +from datetime import timedelta from tchannel import TChannel from tchannel.errors import TimeoutError @@ -113,3 +114,35 @@ def test_local_timeout_unconsumed_message(): yield gen.sleep(0.03) assert mock_warn.call_count == 0 + + [email protected]_test +def test_stream_closed_error_on_read(tornado_pair): + # Test that we don't log an error for StreamClosedErrors while reading. + server, client = tornado_pair + future = server.await() + client.close() + + with mock.patch.object(connection, 'log') as mock_log: # :( + with pytest.raises(gen.TimeoutError): + yield gen.with_timeout(timedelta(milliseconds=100), future) + + assert mock_log.error.call_count == 0 + assert mock_log.info.call_count == 1 + + [email protected]_test +def test_other_error_on_read(tornado_pair): + # Test that we do log errors for non-StreamClosedError failures while + # reading. + server, client = tornado_pair + + future = server.await() + yield client.connection.write(b'\x00\x02\x00\x00') # bad payload + + with mock.patch.object(connection, 'log') as mock_log: # :( + with pytest.raises(gen.TimeoutError): + yield gen.with_timeout(timedelta(milliseconds=100), future) + + assert mock_log.error.call_count == 1 + assert mock_log.info.call_count == 0
Lower read errors to INFO on StreamClosedError only.
uber_tchannel-python
train
4d5370c3ca979e14f470d8e18e5c5da1560a95fc
diff --git a/web/opensubmit/tests/test_student_display.py b/web/opensubmit/tests/test_student_display.py index <HASH>..<HASH> 100644 --- a/web/opensubmit/tests/test_student_display.py +++ b/web/opensubmit/tests/test_student_display.py @@ -127,11 +127,6 @@ class StudentDisplayTestCase(SubmitTestCase): response=self.c.get('/') self.assertEquals(response.status_code, 302) - def testIndexViewNoProfile(self): - self.loginUser(self.noprofileuser) - response=self.c.get('/') - self.assertEquals(response.status_code, 302) - def testIndexWithoutLoginView(self): self.c.logout() response=self.c.get('/')
Fix broken test case from earlier edits
troeger_opensubmit
train
793565f84f842fdd868adc49295000dfe55454e8
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -2,13 +2,12 @@ var path = require("path"), - assign = require("lodash.assign"), each = require("lodash.foreach"), sum = require("lodash.sumby"), parse = require("module-details-from-path"), filesize = require("filesize"); -module.exports = function(options) { +module.exports = (options) => { var entry, base; if(!options) { @@ -19,28 +18,31 @@ module.exports = function(options) { name : "rollup-plugin-sizes", // Grab some needed bits out of the options - options : function(config) { + options : (config) => { entry = config.entry; base = path.dirname(config.entry); }, // Spit out stats during bundle generation - ongenerate : function(details, result) { + ongenerate : (details) => { var data = {}, - totals = []; + totals = [], + total = 0; - details.bundle.modules.forEach(function(module) { - var parsed = parse(module.id); + details.bundle.modules.forEach((module) => { + var parsed; - if(!parsed) { - // Handle rollup-injected helpers - if(module.id.indexOf("\u0000") === 0) { - parsed = { - name : "rollup helpers", - basedir : "", - path : module.id.replace("\u0000", "") - }; - } else { + // Handle rollup-injected helpers + if(module.id.indexOf("\u0000") === 0) { + parsed = { + name : "rollup helpers", + basedir : "", + path : module.id.replace("\u0000", "") + }; + } else { + parsed = parse(module.id); + + if(!parsed) { parsed = { name : "app", basedir : base, @@ -53,47 +55,43 @@ module.exports = function(options) { data[parsed.name] = []; } - data[parsed.name].push(assign(parsed, { size : module.code.length })); + data[parsed.name].push(Object.assign(parsed, { size : module.code.length })); }); - + // Sum all files in each chunk - each(data, function(files, name) { + each(data, (files, name) => { var size = sum(files, "size"); + + total += size; totals.push({ - name : name, - size : size, - percent : (size / result.code.length) * 100 + name, + size }); }); // Sort - totals.sort(function(a, b) { - return b.size - a.size; - }); + totals.sort((a, b) => b.size - a.size); console.log("%s:", entry); - totals.forEach(function(item) { + totals.forEach((item) => { console.log( "%s - %s (%s%%)", item.name, filesize(item.size), - item.percent.toFixed(2) + ((item.size / total) * 100).toFixed(2) ); if(options.details) { - data[item.name].sort(function(a, b) { - return b.size - a.size; - }) - .forEach(function(file) { - console.log( + data[item.name] + .sort((a, b) => b.size - a.size) + .forEach((file) => console.log( "\t%s - %s (%s%%)", file.path, filesize(file.size), ((file.size / item.size) * 100).toFixed(2) - ); - }); + )); } }); }
fix: reflect latest commonjs changes, more accurate totals Fixes #2
tivac_rollup-plugin-sizes
train
b45f3cc91d20732fb6649dad9c8c87d439f78e9b
diff --git a/lib/rack-google-analytics.rb b/lib/rack-google-analytics.rb index <HASH>..<HASH> 100755 --- a/lib/rack-google-analytics.rb +++ b/lib/rack-google-analytics.rb @@ -45,7 +45,7 @@ module Rack def _call(env) @status, @headers, @response = @app.call(env) - return [@status, @headers, @response] unless @headers['Content-Type'] =~ /html/ && Rails.env.casecmp(@env) == 0 + return [@status, @headers, @response] unless @headers['Content-Type'] =~ /html/ && defined?(Rails) && Rails.env.casecmp(@env) == 0 @headers.delete('Content-Length') response = Rack::Response.new([], @status, @headers) @response.each do |fragment|
Neutralise a slight railsism
kangguru_rack-google-analytics
train
7bbc3290cb0dcb031e4e34db89e2e7fd043a4f8a
diff --git a/src/Illuminate/Database/Capsule/Manager.php b/src/Illuminate/Database/Capsule/Manager.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Capsule/Manager.php +++ b/src/Illuminate/Database/Capsule/Manager.php @@ -19,6 +19,13 @@ class Manager { protected static $instance; /** + * The database manager instance. + * + * @var \Illuminate\Database\DatabaseManager + */ + protected $manager; + + /** * Create a new database capsule manager. * * @param \Illuminate\Container\Container $container @@ -176,6 +183,16 @@ class Manager { } /** + * Get the database manager instance. + * + * @return \Illuminate\Database\Manager + */ + public function getDatabaseManager() + { + return $this->manager; + } + + /** * Get the current event dispatcher instance. * * @return \Illuminate\Events\Dispatcher
Added getDatabaseManager method to capsule.
laravel_framework
train
ed3b815a04014d4ea6196cee2f9643af0acf7a5a
diff --git a/ecblock.go b/ecblock.go index <HASH>..<HASH> 100644 --- a/ecblock.go +++ b/ecblock.go @@ -111,14 +111,14 @@ func (e *ECBlock) UnmarshalJSON(js []byte) error { for _, v := range tmp.Body.Entries { switch { case regexp.MustCompile(`"number":`).MatchString(string(v)): - a := new(MinuteNumber) + a := new(ECMinuteNumber) err := json.Unmarshal(v, a) if err != nil { return err } e.Entries = append(e.Entries, a) case regexp.MustCompile(`"serverindexnumber":`).MatchString(string(v)): - a := new(ServerIndexNumber) + a := new(ECServerIndexNumber) err := json.Unmarshal(v, a) if err != nil { return err @@ -126,7 +126,7 @@ func (e *ECBlock) UnmarshalJSON(js []byte) error { e.Entries = append(e.Entries, a) case regexp.MustCompile(`"entryhash":`).MatchString(string(v)): if regexp.MustCompile(`"chainidhash":`).MatchString(string(v)) { - a := new(ChainCommit) + a := new(ECChainCommit) err := json.Unmarshal(v, a) if err != nil { return err @@ -134,7 +134,7 @@ func (e *ECBlock) UnmarshalJSON(js []byte) error { e.Entries = append(e.Entries, a) } else { - a := new(EntryCommit) + a := new(ECEntryCommit) err := json.Unmarshal(v, a) if err != nil { return err @@ -155,31 +155,31 @@ type ECBEntry interface { String() string } -type ServerIndexNumber struct { +type ECServerIndexNumber struct { ServerIndexNumber int `json:"serverindexnumber"` } -func (i *ServerIndexNumber) Type() ECID { +func (i *ECServerIndexNumber) Type() ECID { return ECIDServerIndexNumber } -func (i *ServerIndexNumber) String() string { +func (i *ECServerIndexNumber) String() string { return fmt.Sprintln("ServerIndexNumber:", i.ServerIndexNumber) } -type MinuteNumber struct { +type ECMinuteNumber struct { Number int `json:"number"` } -func (m *MinuteNumber) Type() ECID { +func (m *ECMinuteNumber) Type() ECID { return ECIDMinuteNumber } -func (m *MinuteNumber) String() string { +func (m *ECMinuteNumber) String() string { return fmt.Sprintln("MinuteNumber:", m.Number) } -type ChainCommit struct { +type ECChainCommit struct { Version int `json:"version"` MilliTime int64 `json:"millitime"` ChainIDHash string `json:"chainidhash"` @@ -190,7 +190,7 @@ type ChainCommit struct { Sig string `json:"sig"` } -func (c *ChainCommit) UnmarshalJSON(js []byte) error { +func (c *ECChainCommit) UnmarshalJSON(js []byte) error { tmp := new(struct { Version int `json:"version"` MilliTime string `json:"millitime"` @@ -228,11 +228,11 @@ func (c *ChainCommit) UnmarshalJSON(js []byte) error { return nil } -func (c *ChainCommit) Type() ECID { +func (c *ECChainCommit) Type() ECID { return ECIDChainCommit } -func (c *ChainCommit) String() string { +func (c *ECChainCommit) String() string { var s string s += fmt.Sprintln("ChainCommit {") @@ -249,7 +249,7 @@ func (c *ChainCommit) String() string { return s } -type EntryCommit struct { +type ECEntryCommit struct { Version int `json:"version"` MilliTime int64 `json:"millitime"` EntryHash string `json:"entryhash"` @@ -258,7 +258,7 @@ type EntryCommit struct { Sig string `json:"sig"` } -func (e *EntryCommit) UnmarshalJSON(js []byte) error { +func (e *ECEntryCommit) UnmarshalJSON(js []byte) error { tmp := new(struct { Version int `json:"version"` MilliTime string `json:"millitime"` @@ -292,11 +292,11 @@ func (e *EntryCommit) UnmarshalJSON(js []byte) error { return nil } -func (e *EntryCommit) Type() ECID { +func (e *ECEntryCommit) Type() ECID { return ECIDEntryCommit } -func (e *EntryCommit) String() string { +func (e *ECEntryCommit) String() string { var s string s += fmt.Sprintln("EntryCommit {")
rename ECBlock Entry Types
FactomProject_factom
train
ffdacf021e54658498fac7a16715ca66578ff778
diff --git a/dropwizard-e2e/src/main/java/com/example/app1/App1Resource.java b/dropwizard-e2e/src/main/java/com/example/app1/App1Resource.java index <HASH>..<HASH> 100644 --- a/dropwizard-e2e/src/main/java/com/example/app1/App1Resource.java +++ b/dropwizard-e2e/src/main/java/com/example/app1/App1Resource.java @@ -8,6 +8,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import java.util.LinkedHashMap; import java.util.HashMap; import java.util.Map; import java.util.OptionalInt; @@ -33,7 +34,7 @@ public class App1Resource { @POST @Path("mapper") public Map<String, String> postMapper(Map<String, String> map) { - final Map<String, String> resultMap = new HashMap<>(map); + final Map<String, String> resultMap = new LinkedHashMap<>(map); resultMap.put("hello", "world"); return resultMap; }
Use LinkedHashMap in App1Resource for deterministic iterations (#<I>)
dropwizard_dropwizard
train
95fd6bf5cd33b3c6e4cbdb64ef6c35ba3c8c9334
diff --git a/tests/tests/views/authorize.py b/tests/tests/views/authorize.py index <HASH>..<HASH> 100644 --- a/tests/tests/views/authorize.py +++ b/tests/tests/views/authorize.py @@ -1,5 +1,6 @@ from django.test import TestCase from oauth2_consumer.models import Client, RedirectUri +import urllib class TestErrors(TestCase): @@ -12,6 +13,18 @@ class TestErrors(TestCase): self.client_secret = self.oauth_client.secret + def assertExceptionRedirect(self, request, exception): + params = { + "error": exception.error, + "error_description": exception.reason, + "state": "o2cs", + } + + url = self.redirect_uri.url + "?" + urllib.urlencode(params) + + self.assertRedirects(request, url) + self.assertEquals(request.status_code, 302) + def test_client_id(self): request = self.client.get("/oauth/authorize/") self.assertEqual(request.content, "The client was malformed or invalid.")
Added assertExceptionRedirect assertExceptionRedirect can be used to assert that an exception was thrown by the API that can be redirected.
Rediker-Software_doac
train
794e4330abfde5b1c9b31a07d10c0d30f77e5ea6
diff --git a/visidata/addons/commandlog.py b/visidata/addons/commandlog.py index <HASH>..<HASH> 100644 --- a/visidata/addons/commandlog.py +++ b/visidata/addons/commandlog.py @@ -83,8 +83,7 @@ class CommandLog(Sheet): def beforeExecHook(self, sheet, keystrokes, args=''): 'Log keystrokes and args unless replaying.' assert not sheet or sheet is vd().sheets[0], (sheet.name, vd().sheets[0].name) - if CommandLog.currentReplayRow is None: - self.currentActiveRow = CommandLogRow([sheet.name, sheet.cursorCol.name, sheet.cursorRowIndex, keystrokes, args, sheet._commands[keystrokes][1]]) + self.currentActiveRow = CommandLogRow([sheet.name, sheet.cursorCol.name, sheet.cursorRowIndex, keystrokes, args, sheet._commands[keystrokes][1]]) def afterExecSheet(self, vs, escaped): 'Set end_sheet for the most recent command.'
Add replayed rows to commandlog
saulpw_visidata
train
56835e03bd390f3b340e1b96e3dc8b4205d2a7f5
diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clientTelemetry/ClientTelemetry.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clientTelemetry/ClientTelemetry.java index <HASH>..<HASH> 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clientTelemetry/ClientTelemetry.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clientTelemetry/ClientTelemetry.java @@ -4,8 +4,6 @@ package com.azure.cosmos.implementation.clientTelemetry; import com.azure.cosmos.ConnectionMode; import com.azure.cosmos.implementation.Configs; -import com.azure.cosmos.implementation.GlobalEndpointManager; -import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.cpu.CpuMemoryMonitor; import com.azure.cosmos.implementation.http.HttpClient; import com.azure.cosmos.implementation.http.HttpHeaders; @@ -22,6 +20,7 @@ import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; +import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; @@ -164,7 +163,7 @@ public class ClientTelemetry { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono = this.httpClient.send(httpRequest); - httpResponseMono.flatMap(response -> response.bodyAsString()).map(metadataJson -> Utils.parse(metadataJson, + httpResponseMono.flatMap(response -> response.bodyAsString()).map(metadataJson -> parse(metadataJson, AzureVMMetadata.class)).doOnSuccess(azureVMMetadata -> { this.clientTelemetryInfo.setApplicationRegion(azureVMMetadata.getLocation()); this.clientTelemetryInfo.setHostEnvInfo(azureVMMetadata.getOsType() + "|" + azureVMMetadata.getSku() + @@ -175,6 +174,15 @@ public class ClientTelemetry { }).subscribe(); } + private static <T> T parse(String itemResponseBodyAsString, Class<T> itemClassType) { + try { + return OBJECT_MAPPER.readValue(itemResponseBodyAsString, itemClassType); + } catch (IOException e) { + throw new IllegalStateException( + String.format("Failed to parse string [%s] to POJO.", itemResponseBodyAsString, e)); + } + } + private void clearDataForNextRun() { this.clientTelemetryInfo.getOperationInfoMap().clear(); this.clientTelemetryInfo.getCacheRefreshInfoMap().clear();
Clienttelemetry use internal objectmapper to fix the deserialization problem (#<I>) use internal objectMapper to fix the cosmos telemetry deserialization issue. bug: #<I>
Azure_azure-sdk-for-java
train
55fd5d2995841714f87fc1c0573db6406d93bea4
diff --git a/pypeerassets/__main__.py b/pypeerassets/__main__.py index <HASH>..<HASH> 100644 --- a/pypeerassets/__main__.py +++ b/pypeerassets/__main__.py @@ -16,7 +16,7 @@ from .pautils import (load_deck_p2th_into_local_node, ) from .voting import * from .exceptions import * -from .transactions import (nulldata_output, tx_output, monosig_p2pkh, +from .transactions import (nulldata_script, tx_output, monosig_p2pkh_script, make_raw_transaction) from .constants import param_query, params from .networks import query, networks @@ -98,9 +98,9 @@ def deck_spawn(deck: Deck, inputs: dict, change_address: str) -> bytes: change_sum = float(inputs['total']) - float(tx_fee) - float(pa_params.P2TH_fee) outputs = [ - tx_output(value=pa_params.P2TH_fee, seq=0, script=monosig_p2pkh(p2th_addr)), # p2th - nulldata_output(value=0, seq=1, data=deck.metainfo_to_protobuf), # op_return - tx_output(value=change_sum, seq=2, script=monosig_p2pkh(change_address)) # change + tx_output(value=pa_params.P2TH_fee, seq=0, script=monosig_p2pkh_script(p2th_addr)), # p2th + tx_output(value=0, seq=1, script=nulldata_script(deck.metainfo_to_protobuf)), # op_return + tx_output(value=change_sum, seq=2, script=monosig_p2pkh_script(change_address)) # change ] return make_raw_transaction(inputs['utxos'], outputs) diff --git a/pypeerassets/transactions.py b/pypeerassets/transactions.py index <HASH>..<HASH> 100644 --- a/pypeerassets/transactions.py +++ b/pypeerassets/transactions.py @@ -9,15 +9,14 @@ from btcpy.structs.script import P2pkhScript, MultisigScript, P2shScript from .networks import query -def nulldata_output(data: bytes, seq: int, value=0): - '''create nulldata (OP_return) output''' +def nulldata_script(data: bytes): + '''create nulldata (OP_return) script''' stack = StackData.from_bytes(data) - op_ret = NulldataScript(stack) - return TxOut(value, seq, op_ret) + return NulldataScript(stack) -def monosig_p2pkh(address: str): +def monosig_p2pkh_script(address: str): '''create pay-to-key-hash (P2PKH) script''' addr = Address.from_string(address)
more tweaks to nulldata script mechanism
PeerAssets_pypeerassets
train
83164479bc5ef67a33f99f8f2945e14ec44bccfc
diff --git a/lib/appraisal/appraisal.rb b/lib/appraisal/appraisal.rb index <HASH>..<HASH> 100644 --- a/lib/appraisal/appraisal.rb +++ b/lib/appraisal/appraisal.rb @@ -25,7 +25,7 @@ module Appraisal end def install - Command.new(bundle_command).run + Command.new(install_command).run end def gemfile_path @@ -36,14 +36,14 @@ module Appraisal ::File.join(gemfile_root, "#{clean_name}.gemfile") end - def bundle_command + private + + def install_command gemfile = "--gemfile='#{gemfile_path}'" commands = ['bundle', 'install', gemfile, bundle_parallel_option] "bundle check #{gemfile} || #{commands.compact.join(' ')}" end - private - def gemfile_root ::File.join(Dir.pwd, "gemfiles") end diff --git a/spec/appraisal/appraisal_spec.rb b/spec/appraisal/appraisal_spec.rb index <HASH>..<HASH> 100644 --- a/spec/appraisal/appraisal_spec.rb +++ b/spec/appraisal/appraisal_spec.rb @@ -3,23 +3,6 @@ require 'appraisal/appraisal' require 'tempfile' describe Appraisal::Appraisal do - it "creates a proper bundle command" do - appraisal = Appraisal::Appraisal.new('fake', 'fake') - appraisal.stub(:gemfile_path).and_return("/home/test/test directory") - stub_const('Bundler::VERSION', '1.3.0') - - appraisal.bundle_command.should == "bundle check --gemfile='/home/test/test directory' || bundle install --gemfile='/home/test/test directory'" - end - - it "adds bundler parallel option" do - appraisal = Appraisal::Appraisal.new('fake', 'fake') - appraisal.stub(:gemfile_path).and_return("/home/test/test directory") - stub_const('Bundler::VERSION', '1.4.0') - Parallel.stub(:processor_count).and_return(42) - - appraisal.bundle_command.should == "bundle check --gemfile='/home/test/test directory' || bundle install --gemfile='/home/test/test directory' --jobs=42" - end - it "converts spaces to underscores in the gemfile path" do appraisal = Appraisal::Appraisal.new("one two", "Gemfile") appraisal.gemfile_path.should =~ /one_two\.gemfile$/ @@ -35,20 +18,58 @@ describe Appraisal::Appraisal do appraisal.gemfile_path.should =~ /rails3\.0\.gemfile$/ end - describe "with tempfile output" do + context 'gemfiles generation' do before do @output = Tempfile.new('output') end + after do @output.close @output.unlink end - it "gemfile end with one newline" do + it 'generates a gemfile with a newline at the end of file' do appraisal = Appraisal::Appraisal.new('fake', 'fake') appraisal.stub(:gemfile_path) { @output.path } appraisal.write_gemfile @output.read.should =~ /[^\n]*\n\z/m end end + + context 'parallel installation' do + before do + @appraisal = Appraisal::Appraisal.new('fake', 'fake') + @appraisal.stub(:gemfile_path).and_return("/home/test/test directory") + Appraisal::Command.stub(:new => double(:run => true)) + end + + it 'runs single install command on Bundler < 1.4.0' do + stub_const('Bundler::VERSION', '1.3.0') + @appraisal.install + + Appraisal::Command.should have_received(:new). + with("#{bundle_check_command} || #{bundle_single_install_command}") + end + + it 'runs parallel install command on Bundler >= 1.4.0' do + stub_const('Bundler::VERSION', '1.4.0') + Parallel.stub(:processor_count).and_return(42) + @appraisal.install + + Appraisal::Command.should have_received(:new). + with("#{bundle_check_command} || #{bundle_parallel_install_command}") + end + + def bundle_check_command + "bundle check --gemfile='/home/test/test directory'" + end + + def bundle_single_install_command + "bundle install --gemfile='/home/test/test directory'" + end + + def bundle_parallel_install_command + "bundle install --gemfile='/home/test/test directory' --jobs=42" + end + end end
Refactor and private `Appraisal#install_command` This command should not be called directly outside Appraisal, so it does not make sense to leave it as a public method.
thoughtbot_appraisal
train
18ada67fb23b7232939cd79cd6e0427ba6d83c11
diff --git a/py3status/modules/group.py b/py3status/modules/group.py index <HASH>..<HASH> 100644 --- a/py3status/modules/group.py +++ b/py3status/modules/group.py @@ -172,6 +172,20 @@ class Py3status: response['color'] = self.color return response + def _call_i3status_config_on_click(self, module_name, event): + """ + call any on_click event set in the config for the named module + """ + config = self.py3_module.py3_wrapper.i3status_thread.config[ + 'on_click'] + click_info = config.get(module_name, None) + if click_info: + action = click_info.get(event['button']) + if action: + # we have an action so call it + self.py3_module.py3_wrapper.events_thread.i3_msg( + module_name, action) + def on_click(self, i3s_output_list, i3s_config, event): """ Switch the displayed module or pass the event on to the active module @@ -182,27 +196,22 @@ class Py3status: self._cycle_time = time() + self.cycle if self.button_next and event['button'] == self.button_next: self._next() - elif self.button_prev and event['button'] == self.button_prev: + if self.button_prev and event['button'] == self.button_prev: self._prev() - else: - # pass the event to the module - # first see if any event set in the config - current_module = self.items[self.active] - config = self.py3_module.py3_wrapper.i3status_thread.config[ - 'on_click'] - click_info = config.get(current_module, None) - if click_info: - action = click_info.get(event['button']) - if action: - # we have an action so call it - self.py3_module.py3_wrapper.events_thread.i3_msg( - current_module, action) - - # try the modules own click event - current_module = self._get_current_module() - current_module.click_event(event) - self.py3_wrapper.events_thread.refresh( - current_module.module_full_name) + + # any event set in the config for the group + name = self.py3_module.module_full_name + self._call_i3status_config_on_click(name, event) + + # any event set in the config for the active module + current_module = self.items[self.active] + self._call_i3status_config_on_click(current_module, event) + + # try the modules own click event + current_module = self._get_current_module() + current_module.click_event(event) + self.py3_wrapper.events_thread.refresh( + current_module.module_full_name) if __name__ == "__main__":
call any defined on_click events for group
ultrabug_py3status
train
0d1a2a3c2239ed02f39e3e4690b905b0e86e80be
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index <HASH>..<HASH> 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1770,84 +1770,6 @@ module ActiveRecord relation.to_sql end - def tables_in_string(string) - return [] if string.blank? - string.scan(/([a-zA-Z_][\.\w]+).?\./).flatten - end - - def tables_in_hash(hash) - return [] if hash.blank? - tables = hash.map do |key, value| - if value.is_a?(Hash) - key.to_s - else - tables_in_string(key) if key.is_a?(String) - end - end - tables.flatten.compact - end - - def conditions_tables(options) - # look in both sets of conditions - conditions = [scope(:find, :conditions), options[:conditions]].inject([]) do |all, cond| - case cond - when nil then all - when Array then all << tables_in_string(cond.first) - when Hash then all << tables_in_hash(cond) - else all << tables_in_string(cond) - end - end - conditions.flatten - end - - def order_tables(options) - order = [options[:order], scope(:find, :order) ].join(", ") - return [] unless order && order.is_a?(String) - tables_in_string(order) - end - - def selects_tables(options) - select = options[:select] - return [] unless select && select.is_a?(String) - tables_in_string(select) - end - - def joined_tables(options) - scope = scope(:find) - joins = options[:joins] - merged_joins = scope && scope[:joins] && joins ? merge_joins(scope[:joins], joins) : (joins || scope && scope[:joins]) - [table_name] + case merged_joins - when Symbol, Hash, Array - if array_of_strings?(merged_joins) - tables_in_string(merged_joins.join(' ')) - else - join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(self, merged_joins, nil) - join_dependency.join_associations.collect {|join_association| [join_association.aliased_join_table_name, join_association.aliased_table_name]}.flatten.compact - end - else - tables_in_string(merged_joins) - end - end - - # Checks if the conditions reference a table other than the current model table - def include_eager_conditions?(options, joined_tables) - (conditions_tables(options) - joined_tables).any? - end - - # Checks if the query order references a table other than the current model's table. - def include_eager_order?(options, joined_tables) - (order_tables(options) - joined_tables).any? - end - - def include_eager_select?(options, joined_tables) - (selects_tables(options) - joined_tables).any? - end - - def references_eager_loaded_tables?(options) - joined_tables = joined_tables(options) - include_eager_order?(options, joined_tables) || include_eager_conditions?(options, joined_tables) || include_eager_select?(options, joined_tables) - end - def using_limitable_reflections?(reflections) reflections.reject { |r| [ :belongs_to, :has_one ].include?(r.macro) }.length.zero? end
Remove unused code from association.rb now that Relation takes care of checking the referenced tables
rails_rails
train
e298229f861dc39f37bcf54b69eff6202bd994e4
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -36,9 +36,7 @@ gulp.task('build:dev', function (callback) { ], [ 'static:hb', - 'static:hb:indexr' - ], - [ + 'static:hb:indexr', 'browserSupport' ], [ diff --git a/tasks/browserSupport.js b/tasks/browserSupport.js index <HASH>..<HASH> 100644 --- a/tasks/browserSupport.js +++ b/tasks/browserSupport.js @@ -13,7 +13,6 @@ const browserSupportData = require(config.global.cwd + '/browserSupport.json') | */ gulp.task('browserSupport', function () { if (config.global.tasks.browserSupport) { - console.log(config.global.tasks.browserSupport); let dataObject = { package: packageData, browserSupport: browserSupportData
removed console.logs moved browserSupport task to static tasks
biotope_biotope-build
train
e9491b3ccecfdc48ae618058475a8b743007aca3
diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb index <HASH>..<HASH> 100644 --- a/config/initializers/rack_attack.rb +++ b/config/initializers/rack_attack.rb @@ -58,6 +58,12 @@ class Rack::Attack { controller: "owners", action: "destroy" } ] + protected_password_actions = [ + { controller: "profiles", action: "update" }, + { controller: "profiles", action: "destroy" }, + { controller: "sessions", action: "authenticate" } + ] + def self.protected_route?(protected_actions, path, method) route_params = Rails.application.routes.recognize_path(path, method: method) protected_actions.any? { |hash| hash[:controller] == route_params[:controller] && hash[:action] == route_params[:action] } @@ -157,6 +163,13 @@ class Rack::Attack end end + throttle("password/user", limit: REQUEST_LIMIT, period: LIMIT_PERIOD) do |req| + if protected_route?(protected_password_actions, req.path, req.request_method) + action_dispatch_req = ActionDispatch::Request.new(req.env) + User.find_by_remember_token(action_dispatch_req.cookie_jar.signed["remember_token"])&.email.presence + end + end + ############################# rate limit per email ############################ protected_passwords_action = [{ controller: "passwords", action: "create" }] diff --git a/test/integration/rack_attack_test.rb b/test/integration/rack_attack_test.rb index <HASH>..<HASH> 100644 --- a/test/integration/rack_attack_test.rb +++ b/test/integration/rack_attack_test.rb @@ -292,6 +292,14 @@ class RackAttackTest < ActionDispatch::IntegrationTest assert_response :too_many_requests end + should "throttle profile update per user" do + sign_in_as @user + update_limit_for("password/user:#{@user.email}", exceeding_limit) + patch "/profile" + + assert_response :too_many_requests + end + should "throttle profile delete" do post session_path(session: { who: @user.handle, password: PasswordHelpers::SECURE_TEST_PASSWORD }) @@ -302,6 +310,14 @@ class RackAttackTest < ActionDispatch::IntegrationTest assert_response :too_many_requests end + should "throttle profile delete per user" do + sign_in_as @user + update_limit_for("password/user:#{@user.email}", exceeding_limit) + delete "/profile" + + assert_response :too_many_requests + end + should "throttle reverse_dependencies index" do exceed_limit_for("clearance/ip") rubygem = create(:rubygem, name: "test", number: "0.0.1")
Add per user rate limit to password pages It was possible to bypass existing limits using ip rotator
rubygems_rubygems.org
train
07e539dc52ac099256dbdcf1d407e10b73e535b9
diff --git a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/LogFileNotificationProvider.java b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/LogFileNotificationProvider.java index <HASH>..<HASH> 100644 --- a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/LogFileNotificationProvider.java +++ b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/LogFileNotificationProvider.java @@ -1,7 +1,7 @@ -package net.anotheria.moskito.core.treshold.alerts.notificationprovider; +package net.anotheria.moskito.core.threshold.alerts.notificationprovider; -import net.anotheria.moskito.core.treshold.alerts.NotificationProvider; -import net.anotheria.moskito.core.treshold.alerts.ThresholdAlert; +import net.anotheria.moskito.core.threshold.alerts.NotificationProvider; +import net.anotheria.moskito.core.threshold.alerts.ThresholdAlert; import org.apache.log4j.Logger; /** diff --git a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/MailNotificationProvider.java b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/MailNotificationProvider.java index <HASH>..<HASH> 100644 --- a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/MailNotificationProvider.java +++ b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/MailNotificationProvider.java @@ -1,9 +1,9 @@ -package net.anotheria.moskito.core.treshold.alerts.notificationprovider; +package net.anotheria.moskito.core.threshold.alerts.notificationprovider; import net.anotheria.communication.data.SimpleMailMessage; import net.anotheria.communication.service.MessagingService; -import net.anotheria.moskito.core.treshold.alerts.NotificationProvider; -import net.anotheria.moskito.core.treshold.alerts.ThresholdAlert; +import net.anotheria.moskito.core.threshold.alerts.NotificationProvider; +import net.anotheria.moskito.core.threshold.alerts.ThresholdAlert; import net.anotheria.util.NumberUtils; import net.anotheria.util.StringUtils; import org.apache.log4j.Logger; diff --git a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SyserrNotificationProvider.java b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SyserrNotificationProvider.java index <HASH>..<HASH> 100644 --- a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SyserrNotificationProvider.java +++ b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SyserrNotificationProvider.java @@ -1,7 +1,7 @@ -package net.anotheria.moskito.core.treshold.alerts.notificationprovider; +package net.anotheria.moskito.core.threshold.alerts.notificationprovider; -import net.anotheria.moskito.core.treshold.alerts.NotificationProvider; -import net.anotheria.moskito.core.treshold.alerts.ThresholdAlert; +import net.anotheria.moskito.core.threshold.alerts.NotificationProvider; +import net.anotheria.moskito.core.threshold.alerts.ThresholdAlert; /** * TODO comment this class diff --git a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SysoutNotificationProvider.java b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SysoutNotificationProvider.java index <HASH>..<HASH> 100644 --- a/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SysoutNotificationProvider.java +++ b/moskito-core/java/net/anotheria/moskito/core/threshold/alerts/notificationprovider/SysoutNotificationProvider.java @@ -1,7 +1,7 @@ -package net.anotheria.moskito.core.treshold.alerts.notificationprovider; +package net.anotheria.moskito.core.threshold.alerts.notificationprovider; -import net.anotheria.moskito.core.treshold.alerts.NotificationProvider; -import net.anotheria.moskito.core.treshold.alerts.ThresholdAlert; +import net.anotheria.moskito.core.threshold.alerts.NotificationProvider; +import net.anotheria.moskito.core.threshold.alerts.ThresholdAlert; /** * TODO comment this class
fixed broken package name treshold -> threshold
anotheria_moskito
train
89bb173269e2ed5340b3e7fa23210cb333d0f04c
diff --git a/entify/entify-launcher.py b/entify/entify-launcher.py index <HASH>..<HASH> 100644 --- a/entify/entify-launcher.py +++ b/entify/entify-launcher.py @@ -40,7 +40,7 @@ if __name__ == "__main__": # Adding the main options # Defining the mutually exclusive group for the main options groupInput = parser.add_mutually_exclusive_group(required=True) - groupInput.add_argument('-i', '--input_folder', metavar='<path_to_input_folder>', default=None, action='store', help='path to the file where the list of Classes is stored (one per line).') + groupInput.add_argument('-i', '--input_folder', metavar='<path_to_input_folder>', default=None, action='store', help='path to the folder to analyse.') groupInput.add_argument('-w', '--web', metavar='<url>', action='store', default=None, help='URI to be recovered and analysed.') # adding the option diff --git a/entify/lib/regexp/url.py b/entify/lib/regexp/url.py index <HASH>..<HASH> 100644 --- a/entify/lib/regexp/url.py +++ b/entify/lib/regexp/url.py @@ -37,9 +37,9 @@ class URL(RegexpObject): # This is the tag of the regexp self.name = "i3visio.url" # This is the string containing the reg_exp to be seeked. The former and latter characters are not needed. - # This is not working because python is grabbing each parenthesis - #self.reg_exp = ["[^a-zA-Z0-9]" + "((https?|s?ftp|file)?://[a-zA-Z0-9\_\.\-]+(:[0-9]{1,5})?(/[a-zA-Z0-9\_\.\-/=\?&]+)?)" + "[^a-zA-Z0-9]"] - self.reg_exp = ["[^a-zA-Z0-9]" + "((?:https?|s?ftp|file)://[a-zA-Z0-9\_\.\-]+(?:\:[0-9]{1,5})(?:/[a-zA-Z0-9\_\.\-/=\?&]+))" + "[^a-zA-Z0-9]"] + #self.reg_exp = ["((?:https?|s?ftp|file)://[a-zA-Z0-9\_\.\-]+(?:\:[0-9]{1,5})(?:/[a-zA-Z0-9\_\.\-/=\?&]+))"] + self.reg_exp = ["((?:https?|s?ftp|file)://[a-zA-Z0-9\_\.\-]+(?:\:[0-9]{1,5}|)(?:/[a-zA-Z0-9\_\.\-/=\?&]+|))"] + #self.reg_exp = ["((?:https?|s?ftp|file)://[a-zA-Z0-9\_\.\-]+(?:/[a-zA-Z0-9\_\.\-/=\?&%]+))"] def getAttributes(self, foundExp): ''' @@ -51,20 +51,19 @@ class URL(RegexpObject): # Defining a dictionary attributes = [] - - protocolRegExp = "((https?|s?ftp|file))://" + protocolRegExp = "((?:https?|s?ftp|file))://" foundProtocol = re.findall(protocolRegExp, foundExp) if len(foundProtocol) > 0: # Defining a protocol element aux = {} aux["type"] = "i3visio.protocol" # Defining the regular expression to extract the protocol from a URL - aux["value"] = foundProtocol[0][0] + aux["value"] = foundProtocol[0] # Each attributes will be swept aux["attributes"] = [] attributes.append(aux) - domainRegExp = "(https?|s?ftp)://([a-zA-Z0-9\_\.\-]+)(:|/)" + domainRegExp = "(?:https?|s?ftp)://([a-zA-Z0-9\_\.\-]+)(?:\:|/)" foundDomain = re.findall(domainRegExp, foundExp) if len(foundDomain) > 0: # Defining a domain element @@ -76,9 +75,9 @@ class URL(RegexpObject): aux["attributes"] = [] attributes.append(aux) - portRegExp = "(https?|s?ftp)://[a-zA-Z0-9\_\.\-]+:([0-9]{1,5})/" + portRegExp = "(?:https?|s?ftp)://[a-zA-Z0-9\_\.\-]+:([0-9]{1,5})/" foundPort = re.findall(portRegExp, foundExp) - if len(foundDomain) > 0: + if len(foundPort) > 0: # Defining a domain element aux = {} aux["type"] = "i3visio.port" @@ -88,7 +87,6 @@ class URL(RegexpObject): aux["attributes"] = [] attributes.append(aux) - return attributes
Updated the URL regular expression to match nested brackets
i3visio_entify
train
dc7914a71623603e16f8b4c54b548e90f8726643
diff --git a/art/__main__.py b/art/__main__.py index <HASH>..<HASH> 100644 --- a/art/__main__.py +++ b/art/__main__.py @@ -21,7 +21,6 @@ if __name__ == "__main__": cov.stop() cov.report() cov.save() - cov.html_report() sys.exit(error_flag) elif args[1].upper() == "TEST": error_flag = doctest.testfile( diff --git a/art/art.py b/art/art.py index <HASH>..<HASH> 100644 --- a/art/art.py +++ b/art/art.py @@ -5,20 +5,20 @@ import os import sys import random -VERSION = "2.8" +VERSION = "2.8" # pragma: no cover -FONT_SMALL_THRESHOLD = 50 -FONT_MEDIUM_THRESHOLD = 100 -FONT_LARGE_THRESHOLD = 200 +FONT_SMALL_THRESHOLD = 50 # pragma: no cover +FONT_MEDIUM_THRESHOLD = 100 # pragma: no cover +FONT_LARGE_THRESHOLD = 200 # pragma: no cover -TEXT_XLARGE_THRESHOLD = 3 -TEXT_LARGE_THRESHOLD = 7 -TEXT_MEDIUM_THRESHOLD = 10 +TEXT_XLARGE_THRESHOLD = 3 # pragma: no cover +TEXT_LARGE_THRESHOLD = 7 # pragma: no cover +TEXT_MEDIUM_THRESHOLD = 10 # pragma: no cover -SMALL_WIZARD_FONT = ["contessa","avatar","mini","twopoint","3x5","threepoint","ascii_new_roman","bulbhead","serifcap","lockergnome"] -MEDIUM_WIZARD_FONT = ["soft","4max","5x7","charact4","o8","alphabet","shadow","speed","rounded","chartri"] -LARGE_WIZARD_FONT = ["xhelvi","amcun1","smpoison","3-d","nancyj","os2","block2"] -XLARGE_WIZARD_FONT = ["dotmatrix","sweet","hollywood","nscript","georgia11","block"] +SMALL_WIZARD_FONT = ["contessa","avatar","mini","twopoint","3x5","threepoint","ascii_new_roman","bulbhead","serifcap","lockergnome"] # pragma: no cover +MEDIUM_WIZARD_FONT = ["soft","4max","5x7","charact4","o8","alphabet","shadow","speed","rounded","chartri"] # pragma: no cover +LARGE_WIZARD_FONT = ["xhelvi","amcun1","smpoison","3-d","nancyj","os2","block2"] # pragma: no cover +XLARGE_WIZARD_FONT = ["dotmatrix","sweet","hollywood","nscript","georgia11","block"] # pragma: no cover DESCRIPTION = '''ASCII art is also known as "computer text art". It involves the smart placement of typed special characters or @@ -58,7 +58,7 @@ def font_size_splitter(font_map): "xlarge_list": xlarge_font} -font_map = {"block": [block_dic, True], "banner": [banner_dic, False], +font_map = {"block": [block_dic, True], "banner": [banner_dic, False], # pragma: no cover "standard": [standard_dic, False], "avatar": [avatar_dic, True], "basic": [basic_dic, True], "bulbhead": [bulbhead_dic, True], "chunky": [chunky_dic, False], "coinstak": [coinstak_dic, False], @@ -326,9 +326,9 @@ font_map = {"block": [block_dic, True], "banner": [banner_dic, False], "zone7": [zone7_dic, False], "z-pilot": [z_pilot_dic, False] } -font_counter = len(font_map) -DEFAULT_FONT = "standard" -RND_SIZE_DICT = font_size_splitter(font_map) +font_counter = len(font_map) # pragma: no cover +DEFAULT_FONT = "standard" # pragma: no cover +RND_SIZE_DICT = font_size_splitter(font_map) # pragma: no cover def line(char="*", number=30):
fix : # pragma: no cover added to some lines of code
sepandhaghighi_art
train
81881bf39ca21c793dd8d7619295f26978777eaa
diff --git a/src/config/lfm.php b/src/config/lfm.php index <HASH>..<HASH> 100644 --- a/src/config/lfm.php +++ b/src/config/lfm.php @@ -48,7 +48,7 @@ return [ 'folder_categories' => [ 'file' => [ 'folder_name' => 'files', - 'startup_view' => 'grid', + 'startup_view' => 'list', 'max_size' => 50000, // size in KB 'valid_mime' => [ 'image/jpeg', @@ -56,11 +56,13 @@ return [ 'image/png', 'image/gif', 'image/svg+xml', + 'application/pdf', + 'text/plain', ], ], 'image' => [ 'folder_name' => 'photos', - 'startup_view' => 'list', + 'startup_view' => 'grid', 'max_size' => 50000, // size in KB 'valid_mime' => [ 'image/jpeg', @@ -68,8 +70,6 @@ return [ 'image/png', 'image/gif', 'image/svg+xml', - 'application/pdf', - 'text/plain', ], ], ],
Fix 'valid_mime' issue in config file 'valid_mime' and 'startup_view' values for 'file' and 'image' categories is vice-versa. I swapped them and it's correct now.
UniSharp_laravel-filemanager
train
05ce034a4ba4112b7a55490456691159a7daa76a
diff --git a/lib/viewn.js b/lib/viewn.js index <HASH>..<HASH> 100644 --- a/lib/viewn.js +++ b/lib/viewn.js @@ -46,7 +46,6 @@ ViewN.prototype.clone = function() { var nv = new ViewN(nbuf, this.shape.slice(0), nstride); return nv.assign(this); } -//When stride order is compatible, just scan in raster order function assign_compat(a_data, a_stride, a_ptr, b_data, b_stride, b_ptr, shape) { @@ -118,7 +117,7 @@ ViewN.prototype.assign = function(other) { var a_stride_p = this.stride.slice(0); var b_stride_p = other.stride.slice(0); var i_shape = this.shape.slice(0); - var rec_end = 0; + var rec_end = this.shape.length; for(var i=this.shape.length-1; i>=0; --i) { if(a_order[i] !== b_order[i]) { rec_end = i; @@ -129,7 +128,6 @@ ViewN.prototype.assign = function(other) { b_stride_p[q] = other.stride[p]; i_shape[q] = this.shape[p]; } - //console.log("here:", i_shape, rec_end, a_order, b_order); assign_rec( this.data, a_stride_p, this.offset, other.data, b_stride_p, other.offset, i_shape, rec_end ); @@ -180,5 +178,4 @@ ViewN.prototype.transpose = function() { return new ViewN(this.data, nshape, nstride, noffset); } - module.exports = ViewN; \ No newline at end of file diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -18,9 +18,20 @@ for(var i=0; i<y.shape[0]; ++i) { } } -//console.log(y) - x.hi(2,2).assign(y) x.lo(2,2).assign(y) -console.log(x.hi(3,3)); \ No newline at end of file + + +var x = ndarray.zeros([5,5], "float64", [0,1]) +var y = ndarray.zeros([5,5], "float64", [1,0]) +for(var i=0; i<x.shape[0]; ++i) { + for(var j=0; j<x.shape[1]; ++j) { + x.set(i,j, i + j * 10); + } +} + +console.log(x) +y.assign(x) +console.log(y) +
removed a comment, need to add proper toString() support
scijs_ndarray
train
2c2520a882bd0cf3c9e679a3a3d7739389f97e84
diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java index <HASH>..<HASH> 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java @@ -28,7 +28,7 @@ import ch.qos.logback.core.spi.LifeCycle; * @author Carl Harris */ public abstract class ReceiverBase extends ContextAwareBase - implements LifeCycle, Runnable { + implements LifeCycle { private ExecutorService executor; private boolean started; @@ -43,9 +43,9 @@ public abstract class ReceiverBase extends ContextAwareBase } if (shouldStart()) { executor = createExecutorService(); - executor.execute(this); + executor.execute(getRunnableTask()); started = true; - } + } } /** @@ -74,8 +74,9 @@ public abstract class ReceiverBase extends ContextAwareBase * Determines whether this receiver should start. * <p> * Subclasses will implement this method to do any subclass-specific - * validation. The subclass's {@link #run()} method will be invoked if - * and only if this method returns {@code true}. + * validation. The subclass's {@link #getRunnableTask()} method will be + * invoked (and the task returned will be submitted to the executor) + * if and only if this method returns {@code true} * @return flag indicating whether this receiver should start */ protected abstract boolean shouldStart(); @@ -86,6 +87,12 @@ public abstract class ReceiverBase extends ContextAwareBase protected abstract void onStop(); /** + * Provides the runnable task this receiver will execute. + * @return runnable task + */ + protected abstract Runnable getRunnableTask(); + + /** * Creates an executor for concurrent execution of tasks associated with * the receiver (including the receiver's {@link #run()} task itself. * <p> diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java index <HASH>..<HASH> 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java @@ -42,7 +42,7 @@ import ch.qos.logback.core.util.CloseUtil; * @author Carl Harris */ public class SocketReceiver extends ReceiverBase - implements SocketConnector.ExceptionHandler { + implements Runnable, SocketConnector.ExceptionHandler { private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000; @@ -102,6 +102,11 @@ public class SocketReceiver extends ReceiverBase } } + @Override + protected Runnable getRunnableTask() { + return this; + } + /** * {@inheritDoc} */
a receiver now has-a Runnable, no longer is-a Runnable This will make it easier to refactor SocketServer so that it extends ReceiverBase.
tony19_logback-android
train
f44592112d5e4cd3785c14c2237f42acbad83be0
diff --git a/src/sap.ui.mdc/src/sap/ui/mdc/condition/FilterOperatorUtil.js b/src/sap.ui.mdc/src/sap/ui/mdc/condition/FilterOperatorUtil.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.mdc/src/sap/ui/mdc/condition/FilterOperatorUtil.js +++ b/src/sap.ui.mdc/src/sap/ui/mdc/condition/FilterOperatorUtil.js @@ -389,17 +389,27 @@ function( tokenFormat: "<#tokenText#>", valueTypes: [], getModelFilter: function(oCondition, sFieldPath, oType) { - //TODO Type specific handling of empty is missing - // if (Type == "date") { - // return new Filter({ path: sFieldPath, operator: oOperator.filterOperator, value1: null }); + var isNullable = false; + if (oType) { + var vResult = oType.parseValue("", "string"); + try { + oType.validateValue(vResult); + isNullable = vResult === null; + } catch (oError) { + isNullable = false; + } + } + //TODO Type specific handling of empty is missing. Empty is currently only available for type String + // if (oType == "date") { + // return new Filter(sFieldPath, oOperator.filterOperator, null}); // } else { - // if (isNullable) { - // return new Filter({ filters: [new Filter(sFieldPath, ModelOperator.EQ, ""), - // new Filter(sFieldPath, ModelOperator.EQ, null)], - // and: false}); - // } else { - return new Filter({ path: sFieldPath, operator: this.filterOperator, value1: "" }); - // } + if (isNullable) { + return new Filter({ filters: [new Filter(sFieldPath, ModelOperator.EQ, ""), + new Filter(sFieldPath, ModelOperator.EQ, null)], + and: false}); + } else { + return new Filter(sFieldPath, this.filterOperator, ""); + } // } } }), diff --git a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/condition/FilterOperatorUtil.qunit.js b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/condition/FilterOperatorUtil.qunit.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/condition/FilterOperatorUtil.qunit.js +++ b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/condition/FilterOperatorUtil.qunit.js @@ -15,6 +15,7 @@ sap.ui.define([ "sap/ui/mdc/enum/ConditionValidated", "sap/ui/model/Filter", "sap/ui/model/type/Integer", + "sap/ui/model/odata/type/String", "sap/ui/core/date/UniversalDate", "sap/ui/core/date/UniversalDateUtils" ], function( @@ -27,6 +28,7 @@ sap.ui.define([ ConditionValidated, Filter, IntegerType, + StringType, UniversalDate, UniversalDateUtils ) { @@ -210,7 +212,7 @@ sap.ui.define([ } if (oTest.filter) { - var oFilter = oOperator.getModelFilter(oCondition, "test"); + var oFilter = oOperator.getModelFilter(oCondition, "test", oTest.oType); assert.ok(oFilter, "Filter returned"); assert.equal(oFilter.sPath, oTest.filter.path, "Filter path"); assert.equal(oFilter.sOperator, oTest.filter.operator, "Filter operator"); @@ -890,7 +892,18 @@ sap.ui.define([ isEmpty: false, valid: true, filter: {path: "test", operator: "EQ", value1: ""}, - isSingleValue: true + isSingleValue: true, + oType: new StringType({}, {nullable: false}) + }, + { + formatArgs: [Condition.createCondition("Empty", [])], + formatValue: "<empty>", + parsedValue: "", // empty array (which is the current return value), joined with space. Better check whether it matches TODO + isEmpty: false, + valid: true, + filter: {path: undefined, operator: undefined, value1: undefined, value2: undefined}, + isSingleValue: true, + oType: new StringType({}, {nullable: true}) } ], "NotEmpty": [{
[INTERNAL] FilterOperatorUtil.js : empty and nullable The empty operator for type string with nullable=true should create a filter with EQ "" or EQ null. BCP: <I> Change-Id: I3e7c<I>c<I>a8a<I>e2a<I>fe7e<I>b6f5f<I>bf
SAP_openui5
train
304138e84a9035ca7a575dfe7020eba9e656130c
diff --git a/lib/preflight/rules/no_transparency.rb b/lib/preflight/rules/no_transparency.rb index <HASH>..<HASH> 100644 --- a/lib/preflight/rules/no_transparency.rb +++ b/lib/preflight/rules/no_transparency.rb @@ -1,6 +1,6 @@ # coding: utf-8 -require 'yaml' +require 'forwardable' module Preflight module Rules @@ -19,33 +19,67 @@ module Preflight # class NoTransparency include Preflight::Measurements + extend Forwardable + + # Graphics State Operators + def_delegators :@state, :save_graphics_state, :restore_graphics_state + + # Matrix Operators + def_delegators :@state, :concatenate_matrix attr_reader :issues # we're about to start a new page, reset state # def page=(page) - @issues = [] - @page = page - @objects = page.objects - @xobjects = @page.xobjects + @page = page + @state = PDF::Reader::PageState.new(page) + @issues = [] + end + + def invoke_xobject(label) + @state.invoke_xobject(label) do |xobj| + case xobj + when PDF::Reader::FormXObject then + detect_transparent_form(xobj) + xobj.walk(self) + else + # TODO. can other xobjects have transparency? + end + end end # As each xobject is drawn on the canvas, record if it's Group XObject # with transparency # - def invoke_xobject(label) - xobj = deref(@xobjects[label]) - group = deref(xobj.hash[:Group]) if xobj - stype = deref(group[:S]) if group + def detect_transparent_form(form) + xobject = form.xobject + group = deref(xobject.hash[:Group]) + stype = deref(group[:S]) if group if stype == :Transparency - @issues << Issue.new("Transparent xobject found", self, :page => @page.number) + bbox = xobject.hash[:BBox] || @page.attributes[:MediaBox] + bbox = translate_to_device_space(bbox) + @issues << Issue.new("Transparent xobject found", self, :page => @page.number, + :top_left => bbox[:tl], + :bottom_left => bbox[:bl], + :bottom_right => bbox[:br], + :top_right => bbox[:tr]) end end private + def translate_to_device_space(bbox) + bl_x, bl_y, tr_x, tr_y = *bbox + { + :tl => @state.ctm_transform(bl_x, tr_y), + :bl => @state.ctm_transform(bl_x, bl_y), + :br => @state.ctm_transform(tr_x, bl_y), + :tr => @state.ctm_transform(tr_x, tr_y) + } + end + def deref(obj) @objects ? @objects.deref(obj) : obj end diff --git a/spec/rules/no_transparency_spec.rb b/spec/rules/no_transparency_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rules/no_transparency_spec.rb +++ b/spec/rules/no_transparency_spec.rb @@ -2,26 +2,38 @@ require File.dirname(__FILE__) + "/../spec_helper" describe Preflight::Rules::NoTransparency do - it "should fail files that use transparency" do - filename = pdf_spec_file("transparency") # page 2 has transparency - rule = Preflight::Rules::NoTransparency.new - - PDF::Reader.open(filename) do |reader| - reader.page(2).walk(rule) - rule.issues.should have(1).item - issue = rule.issues.first - issue.rule.should == :"Preflight::Rules::NoTransparency" - issue.attributes[:page].should == 2 + context "a page with transparent xobjects" do + let!(:filename) { pdf_spec_file("transparency") } + + it "should fail with an issue" do + rule = Preflight::Rules::NoTransparency.new + + PDF::Reader.open(filename) do |reader| + reader.page(2).walk(rule) + + rule.issues.should have(1).item + + issue = rule.issues.first + issue.rule.should == :"Preflight::Rules::NoTransparency" + issue.page.should == 2 + issue.top_left.should == [99.0, 540.89] + issue.bottom_left.should == [99.0, 742.89] + issue.bottom_right.should == [301.0, 742.89] + issue.top_right.should == [301.0, 540.89] + end end end - it "should pass files that have no transparency" do - filename = pdf_spec_file("transparency") # page 1 has no transparency - rule = Preflight::Rules::NoTransparency.new + context "a page without transparent xobjects" do + let!(:filename) { pdf_spec_file("transparency") } + + it "should pass with no issues" do + rule = Preflight::Rules::NoTransparency.new - PDF::Reader.open(filename) do |reader| - reader.page(1).walk(rule) - rule.issues.should be_empty + PDF::Reader.open(filename) do |reader| + reader.page(1).walk(rule) + rule.issues.should be_empty + end end end
update the NoTransparency rule to include co-ordinates on the Issue
yob_pdf-preflight
train
e15eda666a6ed3a58ddde0f5e20f795fefb43431
diff --git a/lib/chores/boss.rb b/lib/chores/boss.rb index <HASH>..<HASH> 100644 --- a/lib/chores/boss.rb +++ b/lib/chores/boss.rb @@ -57,6 +57,12 @@ module Chores end self.in_progress = remaining + + self.in_progress.each do |chore| + while chore.completed.any? + self.completed << chore.shift + end + end end def assignable_chores diff --git a/lib/chores/chore.rb b/lib/chores/chore.rb index <HASH>..<HASH> 100644 --- a/lib/chores/chore.rb +++ b/lib/chores/chore.rb @@ -3,7 +3,7 @@ module Chores attr_accessor :on_success, :on_failure, :on_stderr attr_accessor :command, :stdin, :stdout, :stderr attr_accessor :cost, :thread, :result - attr_accessor :deps, :name + attr_accessor :deps, :name, :completed def initialize(opts) [:on_success, :on_failure, :on_stderr].each do |cb| @@ -12,6 +12,7 @@ module Chores self.name = opts[:name] || nil self.deps = opts[:deps] || [] + self.completed = Queue.new self.command = opts.fetch(:command).dup self.command = [self.command] unless self.command.is_a? Array @@ -54,6 +55,10 @@ module Chores self.result == :success || self.result == :failure end + def done_with(name) + self.completed << name + end + def handle_completion if self.result == :success self.on_success.call diff --git a/lib/chores/version.rb b/lib/chores/version.rb index <HASH>..<HASH> 100644 --- a/lib/chores/version.rb +++ b/lib/chores/version.rb @@ -1,3 +1,3 @@ module Chores - VERSION = "0.1.1" + VERSION = "0.1.2" end
add ability to mark things completed that are not chores
emcien_parenting
train
da49ad95b3cf5098435409704e66282f3e1822cc
diff --git a/src/Cilex/Provider/ConfigServiceProvider.php b/src/Cilex/Provider/ConfigServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Cilex/Provider/ConfigServiceProvider.php +++ b/src/Cilex/Provider/ConfigServiceProvider.php @@ -20,7 +20,10 @@ class ConfigServiceProvider implements ServiceProviderInterface public function register(Application $app) { $app['config'] = $app->share(function () use ($app) { - switch (strtolower(end(explode('.', $app['config.path'])))) { + + $fullpath = explode('.', $app['config.path']); + + switch (strtolower(end($fullpath))) { case 'yml': $parser = new Yaml\Parser(); $result = new \ArrayObject(
Fixed "Only variables should be passed by reference" issue on the config provider
Cilex_Cilex
train
374cf68c7461f5a0689ea4d882b282bca23d6498
diff --git a/lib/project.js b/lib/project.js index <HASH>..<HASH> 100644 --- a/lib/project.js +++ b/lib/project.js @@ -27,7 +27,8 @@ var Project = function(prjDir) { this._docDir = this.mkdir(prjDir, "doc"); this._tmpDir = this.mkdir(prjDir, "tmp"); this._wwwDir = this.mkdir(prjDir, "www"); - Util.cleanDir(this.wwwPath(), true); + Util.cleanDir(this.wwwPath( 'js' ), true); + Util.cleanDir(this.wwwPath( 'css' ), true); // To prevent double flushing of the same file, this array keep the // name of the already flushed files. @@ -813,8 +814,10 @@ Project.prototype.addModuleToList = function(moduleName) { * Link every `*.html` file found in _srcDir_. */ Project.prototype.link = function() { - console.log("Cleaning output: " + this.wwwPath()); - Util.cleanDir(this.wwwPath()); + console.log("Cleaning output: " + this.wwwPath( 'js' )); + Util.cleanDir(this.wwwPath( 'js' )); + console.log("Cleaning output: " + this.wwwPath( 'css' )); + Util.cleanDir(this.wwwPath( 'css' )); this.mkdir(this.wwwPath("DEBUG")); this.mkdir(this.wwwPath("RELEASE")); this._htmlFiles.forEach(
Don't clean all the www. Just www/js and www/css.
tolokoban_ToloFrameWork
train
bb984eedbaa80275041ea9d77b4208878b6444d0
diff --git a/cassandra/cqltypes.py b/cassandra/cqltypes.py index <HASH>..<HASH> 100644 --- a/cassandra/cqltypes.py +++ b/cassandra/cqltypes.py @@ -73,20 +73,6 @@ def trim_if_startswith(s, prefix): return s -def unix_time_from_uuid1(u): - msg = "'cassandra.cqltypes.unix_time_from_uuid1' has moved to 'cassandra.util'. This entry point will be removed in the next major version." - warnings.warn(msg, DeprecationWarning) - log.warning(msg) - return util.unix_time_from_uuid1(u) - - -def datetime_from_timestamp(timestamp): - msg = "'cassandra.cqltypes.datetime_from_timestamp' has moved to 'cassandra.util'. This entry point will be removed in the next major version." - warnings.warn(msg, DeprecationWarning) - log.warning(msg) - return util.datetime_from_timestamp(timestamp) - - _casstypes = {} @@ -538,7 +524,6 @@ class DateType(_CassandraType): @staticmethod def interpret_datestring(val): - # not used internally. deprecate? if val[-5] in ('+', '-'): offset = (int(val[-4:-2]) * 3600 + int(val[-2:]) * 60) * int(val[-5] + '1') val = val[:-5] @@ -582,7 +567,7 @@ class TimeUUIDType(DateType): typename = 'timeuuid' def my_timestamp(self): - return unix_time_from_uuid1(self.val) + return util.unix_time_from_uuid1(self.val) @staticmethod def deserialize(byts, protocol_version):
Remove deprecated cqltypes time/date functions Moved to util
datastax_python-driver
train
9b3607c56cd865de0d03c487ec632821fdcefdf5
diff --git a/salt/log.py b/salt/log.py index <HASH>..<HASH> 100644 --- a/salt/log.py +++ b/salt/log.py @@ -110,7 +110,7 @@ class Logging(LoggingLoggerClass): fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) - if match and int(match.group('digits')) < max_logger_length: + if match and match.group('digits') and int(match.group('digits')) < max_logger_length: fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length,
Fix exception in log.py.
saltstack_salt
train
266e5be4b7aa19c8e764df64a9c5802aba6af6e9
diff --git a/src/helpers/FileHelper.php b/src/helpers/FileHelper.php index <HASH>..<HASH> 100644 --- a/src/helpers/FileHelper.php +++ b/src/helpers/FileHelper.php @@ -9,11 +9,14 @@ */ class FileHelper extends \yii\helpers\BaseFileHelper { - const MIME_DIR = 'directory'; - const MIME_PHP = 'text/x-php'; - const MIME_TXT = 'text/plain'; - const MIME_XML = 'application/xml'; - const MIME_TEXT_XML = 'text/xml'; + const MIME_DIR = 'directory'; + const MIME_PDF = 'application/pd'; + const MIME_PHP = 'text/x-php'; + const MIME_PPT = 'application/vnd.ms-powerpoint'; + const MIME_TXT = 'text/plain'; + const MIME_TEXT_XML = 'text/xml'; + const MIME_TEXT_HTML = 'text/html'; + const MIME_XML = 'application/xml'; /** * Clears given directory without deleting it itself. @@ -44,6 +47,7 @@ * ``` * * @param string $path + * * @return boolean */ public static function clearDir ($path) @@ -90,6 +94,7 @@ * ``` * * @param string $path + * * @return int|null */ public static function countItems ($path) @@ -129,6 +134,7 @@ * ``` * * @param string $path The directory under which the items should be counted. + * * @return integer|null */ public static function countItemsInDir ($path) @@ -171,6 +177,7 @@ * ``` * * @param string $path + * * @return bool */ public static function deleteFile ($path) @@ -205,8 +212,9 @@ * // [ 'dir_1_1', 'dir_1_2', 'dir_1_3' ] * ``` * - * @param string $path The directory under which the items will be looked for. + * @param string $path The directory under which the items will be looked for. * @param boolean $absolute Whether return path to items should be absolute. + * * @return array|null List of paths to the found items. */ public static function listDirs ($path, $absolute = false) @@ -246,8 +254,9 @@ * // [ 'file8.txt', 'file9.txt' ] * ``` * - * @param string $path The directory under which the items will be looked for. + * @param string $path The directory under which the items will be looked for. * @param boolean $absolute Whether return path to items should be absolute. + * * @return array|null List of paths to the found items. */ public static function listFiles ($path, $absolute = false) @@ -287,8 +296,9 @@ * // [ 'dir_1_2_1', 'file5.txt' ] * ``` * - * @param string $path The directory under which the items will be looked for. + * @param string $path The directory under which the items will be looked for. * @param boolean $absolute Whether return path to items should be absolute. + * * @return array|null List of paths to the found items. */ public static function listItems ($path, $absolute = false) @@ -326,8 +336,9 @@ * [ 'file9.txt', 'file8.txt' ] * ``` * - * @param string $path The directory under which the files will be looked for. + * @param string $path The directory under which the files will be looked for. * @param integer $order Order direction. Default is descending. + * * @return array|null Array of pairs 'modification time - full path to the file'. */ public static function listItemsByDate ($path, $order = SORT_DESC) @@ -373,8 +384,9 @@ * ``` * * @param string $pattern - * @param string $path The directory under which the items will be looked for. + * @param string $path The directory under which the items will be looked for. * @param boolean $absolute Whether return path to items should be absolute. + * * @return array List of paths to the found items. */ public static function listPatternItems ($path, $pattern = '*', $absolute = false) @@ -417,6 +429,7 @@ * * @param string $path * @param string $relativepath + * * @return array */ public static function listRelativeFiles ($path, $relativepath) @@ -447,6 +460,7 @@ * ``` * * @param string $path Path to the file. + * * @return string|null */ public static function mimetypeFile ($path) @@ -467,6 +481,7 @@ * Get extension of the given file. * * @param string $file Path to the file. + * * @return string */ public static function extension ($file)
#<I> Added const mime-type
pulsarvp_vps-tools
train
fd7b648393b4d728b6e4c54c9c6ecf5b7a3d96c6
diff --git a/SimpleDOM/SimpleDOM.php b/SimpleDOM/SimpleDOM.php index <HASH>..<HASH> 100644 --- a/SimpleDOM/SimpleDOM.php +++ b/SimpleDOM/SimpleDOM.php @@ -302,8 +302,7 @@ namespace s9e\Toolkit\SimpleDOM throw new BadMethodCallException('remove() cannot be used to remove the root node'); } - $node = $tmp->parentNode->removeChild($tmp); - return static::import($node); + return static::import($tmp->parentNode->removeChild($tmp)); } /** @@ -322,8 +321,7 @@ namespace s9e\Toolkit\SimpleDOM $old = dom_import_simplexml($this); $new = $old->ownerDocument->importNode(dom_import_simplexml($new), true); - $node = $old->parentNode->replaceChild($new, $old); - return static::import($node); + return static::import($old->parentNode->replaceChild($new, $old)); } /** @@ -473,16 +471,16 @@ namespace s9e\Toolkit\SimpleDOM $fragment = $tmp->ownerDocument->createDocumentFragment(); /** - * Disable error reporting + * Use internal errors while we append the XML */ $useErrors = libxml_use_internal_errors(true); + $success = $fragment->appendXML($xml); + libxml_use_internal_errors($useErrors); - if (!$fragment->appendXML($xml)) + if (!$success) { - libxml_use_internal_errors($useErrors); throw new InvalidArgumentException(libxml_get_last_error()->message); } - libxml_use_internal_errors($useErrors); $this->insertNode($tmp, $fragment, $mode); @@ -864,9 +862,9 @@ namespace s9e\Toolkit\SimpleDOM { $tmp = dom_import_simplexml($this); $method = 'create' . $type; + $new = $tmp->ownerDocument->$method($content); - $node = $tmp->ownerDocument->$method($content); - return $this->insertNode($tmp, $node, $mode); + return $this->insertNode($tmp, $new, $mode); } protected function insertNode(DOMNode $tmp, DOMNode $node, $mode)
Moved some code around, no functional change intended
s9e_TextFormatter
train
cf0d4bdba8febf88a7b51ab099d2b1fd5ecd572d
diff --git a/lib/active_interaction/filters/boolean_filter.rb b/lib/active_interaction/filters/boolean_filter.rb index <HASH>..<HASH> 100644 --- a/lib/active_interaction/filters/boolean_filter.rb +++ b/lib/active_interaction/filters/boolean_filter.rb @@ -20,9 +20,9 @@ module ActiveInteraction class BooleanFilter < Filter def cast(value) case value - when FalseClass, '0' + when FalseClass, '0', /\Afalse\z/i false - when TrueClass, '1' + when TrueClass, '1', /\Atrue\z/i true else super diff --git a/spec/active_interaction/filters/boolean_filter_spec.rb b/spec/active_interaction/filters/boolean_filter_spec.rb index <HASH>..<HASH> 100644 --- a/spec/active_interaction/filters/boolean_filter_spec.rb +++ b/spec/active_interaction/filters/boolean_filter_spec.rb @@ -38,5 +38,37 @@ describe ActiveInteraction::BooleanFilter, :filter do expect(filter.cast(value)).to be_true end end + + context 'with "false"' do + let(:value) { 'false' } + + it 'returns false' do + expect(filter.cast(value)).to be_false + end + end + + context 'with "true"' do + let(:value) { 'true' } + + it 'returns true' do + expect(filter.cast(value)).to be_true + end + end + + context 'with "FALSE"' do + let(:value) { 'FALSE' } + + it 'returns false' do + expect(filter.cast(value)).to be_false + end + end + + context 'with "TRUE"' do + let(:value) { 'TRUE' } + + it 'returns true' do + expect(filter.cast(value)).to be_true + end + end end end
Support casting "true" and "false" ... in a case-insensitive manner.
AaronLasseigne_active_interaction
train
6095c835ce109a2ec0c1f4de6b9d531aa55bd57a
diff --git a/docs-site/__tests__/pattern-lab.e2e.js b/docs-site/__tests__/pattern-lab.e2e.js index <HASH>..<HASH> 100644 --- a/docs-site/__tests__/pattern-lab.e2e.js +++ b/docs-site/__tests__/pattern-lab.e2e.js @@ -20,12 +20,19 @@ module.exports = { .url(`${testingUrl}/pattern-lab/?p=components-overview`) .waitForElementVisible('pl-header', 3000) .assert.elementPresent('.js-c-typeahead__input') + .click('.js-c-typeahead__input') // click on the PL search input + .keys('Components-Card') // type "Components-Card" in the input field + .click('.pl-c-typeahead__result--first') // click on the first result + .waitForElementVisible('.pl-js-open-new-window', 3000) // make sure the "Open in a New Tab" UI is there before clicking on it + .click('.pl-js-open-new-window') + .windowHandles(function(result) { + var handle = result.value[1]; + browser.switchWindow(handle); // switch browser windows to make sure the page we've just opened is in focus + }) + .waitForElementVisible('bolt-card', 3000) + .assert.urlContains('components-card') .saveScreenshot( - `screenshots/pattern-lab/pattern-lab-header--${browser.currentEnv || - 'chrome'}.png`, - ) - .saveScreenshot( - `screenshots/pattern-lab/pattern-lab-search--${browser.currentEnv || + `screenshots/pattern-lab/pattern-lab-search-results-load-new-page--${browser.currentEnv || 'chrome'}.png`, ) .end(); diff --git a/docs-site/__tests__/server-side-rendering.e2e.js b/docs-site/__tests__/server-side-rendering.e2e.js index <HASH>..<HASH> 100644 --- a/docs-site/__tests__/server-side-rendering.e2e.js +++ b/docs-site/__tests__/server-side-rendering.e2e.js @@ -3,15 +3,43 @@ module.exports = { const { testingUrl } = browser.globals; console.log(`global browser url: ${testingUrl}`); browser + .url(`${testingUrl}/pattern-lab/?p=viewall-components-button`) + .assert.urlContains('components-button') + .saveScreenshot( + `screenshots/pattern-lab/button-component-docs--${browser.currentEnv || + 'chrome'}.png`, + ) + .click('.pl-js-open-new-window') + .windowHandles(function(result) { + var handle = result.value[1]; + browser.switchWindow(handle); + }) + .waitForElementVisible('bolt-button', 3000) + .assert.elementPresent('.c-bolt-button') + .saveScreenshot( + `screenshots/pattern-lab/button-component-docs-in-new-window--${browser.currentEnv || + 'chrome'}.png`, + ) + .closeWindow() + .windowHandles(function(result) { + var handle = result.value[0]; + browser.switchWindow(handle); + }) .url( - `${testingUrl}/pattern-lab/patterns/02-components-button-70-button-ssr-example--web-component-wo-shadow-dom/02-components-button-70-button-ssr-example--web-component-wo-shadow-dom.html`, + `${testingUrl}/pattern-lab/?p=components-button-ssr--web-component-wo-shadow-dom`, ) + .click('.pl-js-open-new-window') + .windowHandles(function(result) { + var handle = result.value[1]; + browser.switchWindow(handle); + }) .waitForElementVisible('bolt-button', 3000) .assert.elementPresent('.c-bolt-button') .saveScreenshot( - `screenshots/pattern-lab/web-component-ssr--${browser.currentEnv || + `screenshots/pattern-lab/button-component-ssr--${browser.currentEnv || 'chrome'}.png`, ) + .closeWindow() .end(); }, };
refactor: update Nightwatch.js tests to use the component alias in the URL to find the right HTML page + open in a new window
bolt-design-system_bolt
train
8d167325e59bea6691ca98a0f92e4cc8365713de
diff --git a/servo-core/src/main/java/com/netflix/servo/publish/MonitorRegistryMetricPoller.java b/servo-core/src/main/java/com/netflix/servo/publish/MonitorRegistryMetricPoller.java index <HASH>..<HASH> 100644 --- a/servo-core/src/main/java/com/netflix/servo/publish/MonitorRegistryMetricPoller.java +++ b/servo-core/src/main/java/com/netflix/servo/publish/MonitorRegistryMetricPoller.java @@ -20,6 +20,8 @@ package com.netflix.servo.publish; import com.google.common.collect.Lists; +import com.google.common.util.concurrent.TimeLimiter; +import com.google.common.util.concurrent.SimpleTimeLimiter; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.Metric; @@ -33,6 +35,11 @@ import org.slf4j.LoggerFactory; import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -53,6 +60,11 @@ public final class MonitorRegistryMetricPoller implements MetricPoller { private final AtomicLong cacheLastUpdateTime = new AtomicLong(0L); + // Put limit on fetching the monitor value in-case someone does something silly like call a + // remote service inline + private final ExecutorService service = Executors.newSingleThreadExecutor(); + private final TimeLimiter limiter = new SimpleTimeLimiter(service); + /** * Creates a new instance using {@link com.netflix.servo.DefaultMonitorRegistry}. */ @@ -85,7 +97,8 @@ public final class MonitorRegistryMetricPoller implements MetricPoller { if (reset && monitor instanceof ResettableMonitor<?>) { return ((ResettableMonitor<?>) monitor).getAndResetValue(); } else { - return monitor.getValue(); + final MonitorValueCallable c = new MonitorValueCallable(monitor); + return limiter.callWithTimeout(c, 1, TimeUnit.SECONDS, true); } } catch (Exception e) { LOGGER.warn("failed to get value for " + monitor.getConfig(), e); @@ -143,4 +156,17 @@ public final class MonitorRegistryMetricPoller implements MetricPoller { } return metrics; } + + private static class MonitorValueCallable implements Callable<Object> { + + private final Monitor<?> monitor; + + public MonitorValueCallable(Monitor<?> monitor) { + this.monitor = monitor; + } + + public Object call() throws Exception { + return monitor.getValue(); + } + } }
add time limiter to prevent a slow getValue on a monitor from impacting overall collection
Netflix_servo
train
779964eedb9d485494034ddb2ebb27a188757205
diff --git a/lib/periodic_calculations/query.rb b/lib/periodic_calculations/query.rb index <HASH>..<HASH> 100644 --- a/lib/periodic_calculations/query.rb +++ b/lib/periodic_calculations/query.rb @@ -33,6 +33,10 @@ module PeriodicCalculations end end + def to_sql + sanitized_sql + end + private def sanitized_sql diff --git a/spec/periodic_calculations/query_spec.rb b/spec/periodic_calculations/query_spec.rb index <HASH>..<HASH> 100644 --- a/spec/periodic_calculations/query_spec.rb +++ b/spec/periodic_calculations/query_spec.rb @@ -13,6 +13,16 @@ describe PeriodicCalculations::Query do let(:end_time) { time + 1.day } let(:options) { {} } + describe "#to_sql" do + it "returns the sanitized_sql" do + query_options = PeriodicCalculations::QueryOptions.new(operation, column_name, start_time, end_time, options) + query = PeriodicCalculations::Query.new(scope, query_options) + + query.stub(:sanitized_sql).and_return("wohoo") + query.to_sql.should == "wohoo" + end + end + describe "#execute" do def execute(scope, *args)
Add Query#to_sql method
polmiro_periodic_calculations
train
52e382588b5d9782439fbcca0ce1b205a574a74b
diff --git a/addon/components/basic-dropdown.js b/addon/components/basic-dropdown.js index <HASH>..<HASH> 100644 --- a/addon/components/basic-dropdown.js +++ b/addon/components/basic-dropdown.js @@ -148,7 +148,7 @@ export default Component.extend({ let calculatePosition = this.get(this.get('renderInPlace') ? 'calculateInPlacePosition' : 'calculatePosition'); let options = this.getProperties('horizontalPosition', 'verticalPosition', 'matchTriggerWidth', 'previousHorizontalPosition', 'previousVerticalPosition'); - let positionData = calculatePosition(triggerElement, dropdownElement, options); + let positionData = calculatePosition.call(this, triggerElement, dropdownElement, options); return this.applyReposition(triggerElement, dropdownElement, positionData); }, diff --git a/tests/integration/components/basic-dropdown-test.js b/tests/integration/components/basic-dropdown-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/components/basic-dropdown-test.js +++ b/tests/integration/components/basic-dropdown-test.js @@ -477,8 +477,9 @@ test('The `reposition` public action returns an object with the changes', functi }); test('The user can pass a custom `calculatePosition` function to customize how the component is placed on the screen', function(assert) { - assert.expect(3); + assert.expect(4); this.calculatePosition = function() { + assert.ok(this, 'context shouldn\'t be undefined'); return { horizontalPosition: 'right', verticalPosition: 'above', @@ -504,8 +505,9 @@ test('The user can pass a custom `calculatePosition` function to customize how t }); test('The user can pass a custom `calculateInPlacePosition` function to customize how the component is placed on the screen when rendered "in place"', function(assert) { - assert.expect(3); + assert.expect(4); this.calculateInPlacePosition = function() { + assert.ok(this, 'context shouldn\'t be undefined'); return { horizontalPosition: 'right', verticalPosition: 'above',
call calculatePosition with context set to the component
cibernox_ember-basic-dropdown
train
90802db77acfda7af4813eb8b294c3dca9039a81
diff --git a/lib/sensu/api/process.rb b/lib/sensu/api/process.rb index <HASH>..<HASH> 100644 --- a/lib/sensu/api/process.rb +++ b/lib/sensu/api/process.rb @@ -346,10 +346,10 @@ module Sensu healthy << (info[:keepalives][:messages] <= max_messages) healthy << (info[:results][:messages] <= max_messages) end - healthy.all? ? no_content! : unavailable! + healthy.all? ? no_content! : precondition_failed! end else - unavailable! + precondition_failed! end end
if a health check fails, use exit status code <I> - precondition failed
sensu_sensu
train
9953959ef2f07bb1f84fef9b2e9418b16ac0d0f4
diff --git a/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-rejected.js b/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-rejected.js index <HASH>..<HASH> 100644 --- a/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-rejected.js +++ b/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-rejected.js @@ -1,7 +1,7 @@ var Promise = require('ember-cli/lib/ext/promise'); module.exports = function() { - return Promise(function(resolve, reject) { + return new Promise(function(resolve, reject) { setTimeout(5, () => reject('hook rejected')); }); }; diff --git a/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-resolved.js b/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-resolved.js index <HASH>..<HASH> 100644 --- a/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-resolved.js +++ b/node-tests/fixtures/ember-cordova-mock/ember-cordova/hooks/hook-promise-resolved.js @@ -1,7 +1,7 @@ var Promise = require('ember-cli/lib/ext/promise'); module.exports = function() { - return Promise(function(resolve, reject) { + return new Promise(function(resolve, reject) { setTimeout(5, () => resolve('resolved promise from hook')); }); }; diff --git a/node-tests/unit/tasks/run-hook-test.js b/node-tests/unit/tasks/run-hook-test.js index <HASH>..<HASH> 100644 --- a/node-tests/unit/tasks/run-hook-test.js +++ b/node-tests/unit/tasks/run-hook-test.js @@ -3,34 +3,39 @@ var expect = require('../../helpers/expect'); var HookTask = require('../../../lib/tasks/run-hook'); var mockProject = require('../../fixtures/ember-cordova-mock/project'); +var Promise = require('ember-cli/lib/ext/promise'); describe('Run Hook Task', function() { it('runs a hook at the provided path', function() { var hookTask = new HookTask(mockProject); - expect(hookTask.run('hook')).to.be.fulfilled; + return expect(hookTask.run('hook')).to.be.fulfilled; }); it('runs a hook at the provided path that has an error', function() { var hookTask = new HookTask(mockProject); - expect(hookTask.run('hook-with-error')).to.be.rejected; + return expect(hookTask.run('hook-with-error')).to.be.rejected; }); it('is rejected if the hook does not exist', function() { var hookTask = new HookTask(mockProject); - expect(hookTask.run('invalid')).to.be.rejected; + return expect(hookTask.run('invalid')).to.be.rejected; }); it('is resolved if the hook is resolved', function() { var hookTask = new HookTask(mockProject); var expectation = expect(hookTask.run('hook-promise-resolved')); - expectation.to.eventually.equal('hook resolved'); - expectation.to.be.fulfilled; + return Promise.all([ + expectation.to.eventually.equal('resolved promise from hook'), + expectation.to.be.fulfilled, + ]); }); it('is rejected if the hook is rejected', function() { var hookTask = new HookTask(mockProject); var expectation = expect(hookTask.run('hook-promise-rejected')); - expectation.to.eventually.equal('hook rejected'); - expectation.to.be.rejected; + return Promise.all([ + expectation.to.eventually.equal('hook rejected'), + expectation.to.be.rejected, + ]); }); });
fix(run-hook-test): Chai promise expectations need to be returned This fixes the expectations in run-hook-test so they actually trigger. One test is now failing, but I think the expectation it lays out is incorrect.
isleofcode_ember-cordova
train
9b89c303cc36b2ce8202b62fa88c9d8b849c6e6c
diff --git a/transport-sctp/src/main/java/io/netty/channel/sctp/SctpMessage.java b/transport-sctp/src/main/java/io/netty/channel/sctp/SctpMessage.java index <HASH>..<HASH> 100644 --- a/transport-sctp/src/main/java/io/netty/channel/sctp/SctpMessage.java +++ b/transport-sctp/src/main/java/io/netty/channel/sctp/SctpMessage.java @@ -136,6 +136,18 @@ public final class SctpMessage extends DefaultByteBufHolder { } @Override + public SctpMessage retain() { + super.retain(); + return this; + } + + @Override + public SctpMessage retain(int increment) { + super.retain(increment); + return this; + } + + @Override public String toString() { if (refCnt() == 0) { return "SctpFrame{" + diff --git a/transport-udt/src/main/java/io/netty/channel/udt/UdtMessage.java b/transport-udt/src/main/java/io/netty/channel/udt/UdtMessage.java index <HASH>..<HASH> 100644 --- a/transport-udt/src/main/java/io/netty/channel/udt/UdtMessage.java +++ b/transport-udt/src/main/java/io/netty/channel/udt/UdtMessage.java @@ -37,4 +37,15 @@ public final class UdtMessage extends DefaultByteBufHolder { return new UdtMessage(data().copy()); } + @Override + public UdtMessage retain() { + super.retain(); + return this; + } + + @Override + public UdtMessage retain(int increment) { + super.retain(increment); + return this; + } } diff --git a/transport/src/main/java/io/netty/channel/socket/DatagramPacket.java b/transport/src/main/java/io/netty/channel/socket/DatagramPacket.java index <HASH>..<HASH> 100644 --- a/transport/src/main/java/io/netty/channel/socket/DatagramPacket.java +++ b/transport/src/main/java/io/netty/channel/socket/DatagramPacket.java @@ -56,6 +56,18 @@ public final class DatagramPacket extends DefaultByteBufHolder { } @Override + public DatagramPacket retain() { + super.retain(); + return this; + } + + @Override + public DatagramPacket retain(int increment) { + super.retain(increment); + return this; + } + + @Override public String toString() { if (refCnt() == 0) { return "DatagramPacket{remoteAddress=" + remoteAddress().toString() +
Return correct type on retain(..)
netty_netty
train
d143f76973d5368389e760c73ae0c61113cb1c6a
diff --git a/jquery/jquery.js b/jquery/jquery.js index <HASH>..<HASH> 100644 --- a/jquery/jquery.js +++ b/jquery/jquery.js @@ -355,13 +355,13 @@ $.getCSS = function(e,p) { if ( p == 'height' || p == 'width' ) { // Handle extra width/height provided by the W3C box model - var ph = !$.boxModel ? 0 : + var ph = (!$.boxModel ? 0 : parseInt($.css(e,"paddingTop")) + parseInt($.css(e,"paddingBottom")) + - parseInt($.css(e,"borderTop")) + parseInt($.css(e,"borderBottom")) || 0; + parseInt($.css(e,"borderTopWidth")) + parseInt($.css(e,"borderBottomWidth"))) || 0; - var pw = !$.boxModel ? 0 : + var pw = (!$.boxModel ? 0 : parseInt($.css(e,"paddingLeft")) + parseInt($.css(e,"paddingRight")) + - parseInt($.css(e,"borderLeft")) + parseInt($.css(e,"borderRight")) || 0; + parseInt($.css(e,"borderLeftWidth")) + parseInt($.css(e,"borderRightWidth"))) || 0; var oHeight, oWidth;
Changed border stuff to borderTopWidth (Ticket #9)
jquery_jquery
train
348d59a683d4e5a1730661022a20b9298d3718c1
diff --git a/joyent.py b/joyent.py index <HASH>..<HASH> 100755 --- a/joyent.py +++ b/joyent.py @@ -133,11 +133,14 @@ class Client: See https://github.com/joyent/python-manta """ - def __init__(self, sdc_url, account, key_id, + def __init__(self, sdc_url, account, key_id, manta_url, user_agent=USER_AGENT, dry_run=False, verbose=False): if sdc_url.endswith('/'): sdc_url = sdc_url[1:] self.sdc_url = sdc_url + if manta_url.endswith('/'): + manta_url = manta_url[1:] + self.manta_url = manta_url self.account = account self.key_id = key_id self.user_agent = user_agent @@ -165,11 +168,16 @@ class Client: headers["User-Agent"] = USER_AGENT return headers - def _request(self, path, method="GET", body=None, headers=None): + def _request(self, path, method="GET", body=None, headers=None, + is_manta=False): headers = self.make_request_headers(headers) if path.startswith('/'): path = path[1:] - uri = "{}/{}/{}".format(self.sdc_url, self.account, path) + if is_manta: + base_url = self.manta_url + else: + base_url = self.sdc_url + uri = "{}/{}/{}".format(base_url, self.account, path) if method == 'DELETE': request = DeleteRequest(uri, headers=headers) elif method == 'HEAD': @@ -192,6 +200,22 @@ class Client: headers['reason'] = response.msg return headers, content + def _list_objects(self, path): + headers, content = self._request(path, is_manta=True) + objects = [] + for line in content.splitlines(): + obj = json.loads(line) + obj['path'] = '%s/%s' % (path, obj['name']) + objects.append(obj) + if self.verbose: + print(objects) + return objects + + def list_objects(self, path): + objects = self._list_objects(path) + for obj in objects: + print('{type} {mtime} {path}'.format(**obj)) + def _list_machines(self, machine_id=None): """Return a list of machine dicts.""" if machine_id: @@ -369,6 +393,10 @@ def parse_args(args=None): help="SDC URL. Environment: SDC_URL=URL", default=os.environ.get("SDC_URL")) parser.add_argument( + "-m", "--manta-url", dest="manta_url", + help="Manta URL. Environment: MANTA_URL=URL", + default=os.environ.get("MANTA_URL")) + parser.add_argument( "-a", "--account", help="Manta account. Environment: MANTA_USER=ACCOUNT", default=os.environ.get("MANTA_USER")) @@ -390,6 +418,10 @@ def parse_args(args=None): parser_list_tags = subparsers.add_parser( 'list-tags', help='List tags of running machines') parser_list_tags.add_argument('machine_id', help='The machine id.') + parser_list_objects = subparsers.add_parser( + 'list-objects', help='List directories and files in manta') + parser_list_objects.add_argument('path', help='The path') + return parser.parse_args() @@ -399,12 +431,14 @@ def main(argv): print('SDC_URL must be sourced into the environment.') sys.exit(1) client = Client( - args.sdc_url, args.account, args.key_id, + args.sdc_url, args.account, args.key_id, args.manta_url, dry_run=args.dry_run, verbose=args.verbose) if args.command == 'list-machines': client.list_machines() elif args.command == 'list-tags': client.list_machine_tags(args.machine_id) + elif args.command == 'list-objects': + client.list_objects(args.path) elif args.command == 'delete-old-machines': client.delete_old_machines(args.old_age, args.contact_mail_address) else:
Added simple listing of manta paths.
juju_juju
train
224b5fd33f5d738c97f3f16ad741bc80cb0793ed
diff --git a/public/js/kamba.js b/public/js/kamba.js index <HASH>..<HASH> 100644 --- a/public/js/kamba.js +++ b/public/js/kamba.js @@ -20,7 +20,11 @@ $(window).load(function () { $('#groups > tbody').sortable({ update: function (event, ui) { var data = $(this).sortable('serialize'); - $.post(prefixUri + '/puppet/groups/update', data); + $.post(prefixUri + '/puppet/groups/update', data).done(function(data) { + if (data.error) { + location.reload(true); + } + }); } }).disableSelection();
Reload page when groups sorting fails
kambalabs_KmbBase
train
cdc16e32981f33a65d401a2eadc250faa7716a8b
diff --git a/core/src/main/java/org/infinispan/eviction/ActivationManagerImpl.java b/core/src/main/java/org/infinispan/eviction/ActivationManagerImpl.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/infinispan/eviction/ActivationManagerImpl.java +++ b/core/src/main/java/org/infinispan/eviction/ActivationManagerImpl.java @@ -119,20 +119,5 @@ public class ActivationManagerImpl implements ActivationManager { public void resetStatistics() { activations.set(0); } - - /** - * Disables a cache loader of a given type, where type is the fully qualified class name of a {@link org.infinispan.loaders.CacheLoader} implementation. - * - * If the given type cannot be found, this is a no-op. If more than one cache loader of the same type is configured, - * all cache loaders of the given type are disabled. - * - * @param loaderType fully qualified class name of the cache loader type to disable - */ - @ManagedOperation(description = "Disable all cache loaders of a given type, where type is a fully qualified class name of the cache loader to disable") - @Operation(displayName = "Disable all cache loaders of a given type, where type is a fully qualified class name of the cache loader to disable") - @SuppressWarnings("unused") - public void disableCacheLoader(String loaderType) { - if (enabled) clm.disableCacheStore(loaderType); - } - } +
ISPN-<I> Remove a useless method from ActivationManagerImpl which also happens to break the build
infinispan_infinispan
train
c1618c6e17d8bea8c3099c20800f7691038d4f77
diff --git a/python_modules/libraries/dagster-k8s/dagster_k8s_tests/helm.py b/python_modules/libraries/dagster-k8s/dagster_k8s_tests/helm.py index <HASH>..<HASH> 100644 --- a/python_modules/libraries/dagster-k8s/dagster_k8s_tests/helm.py +++ b/python_modules/libraries/dagster-k8s/dagster_k8s_tests/helm.py @@ -1,7 +1,6 @@ import base64 import os import subprocess -import sys import time from contextlib import contextmanager @@ -185,8 +184,12 @@ def helm_chart(namespace, docker_image, should_cleanup=True): print('Running Helm Install: \n', ' '.join(helm_cmd), '\nWith config:\n', helm_config_yaml) - p = subprocess.Popen(helm_cmd, stdin=subprocess.PIPE, stdout=sys.stdout, stderr=sys.stderr) - p.communicate(six.ensure_binary(helm_config_yaml)) + p = subprocess.Popen( + helm_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + stdout, stderr = p.communicate(six.ensure_binary(helm_config_yaml)) + print('Helm install completed with stdout: ', stdout) + print('Helm install completed with stderr: ', stderr) assert p.returncode == 0 # Wait for Dagit pod to be ready (won't actually stay up w/out js rebuild) diff --git a/python_modules/libraries/dagster-k8s/dagster_k8s_tests/kind.py b/python_modules/libraries/dagster-k8s/dagster_k8s_tests/kind.py index <HASH>..<HASH> 100644 --- a/python_modules/libraries/dagster-k8s/dagster_k8s_tests/kind.py +++ b/python_modules/libraries/dagster-k8s/dagster_k8s_tests/kind.py @@ -49,7 +49,18 @@ def create_kind_cluster(cluster_name, should_cleanup=True): '--- \033[32m:k8s: Running kind cluster setup for cluster ' '{cluster_name}\033[0m'.format(cluster_name=cluster_name) ) - check_output(['kind', 'create', 'cluster', '--name', cluster_name]) + + p = subprocess.Popen( + ['kind', 'create', 'cluster', '--name', cluster_name], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + stdout, stderr = p.communicate() + + print('Kind create cluster command completed with stdout: ', stdout) + print('Kind create cluster command completed with stderr: ', stderr) + + assert p.returncode == 0 yield cluster_name finally:
Print stderr/stdout for helm install and kind create cluster Test Plan: bk Reviewers: nate Reviewed By: nate Differential Revision: <URL>
dagster-io_dagster
train
cd8ef8b60aea3220d25c816ce4fdea0daf998edc
diff --git a/cmd/juju/cloud/list_test.go b/cmd/juju/cloud/list_test.go index <HASH>..<HASH> 100644 --- a/cmd/juju/cloud/list_test.go +++ b/cmd/juju/cloud/list_test.go @@ -76,7 +76,7 @@ func (s *listSuite) TestListJSON(c *gc.C) { c.Assert(out, gc.Matches, `.*{"aws":{"defined":"public","type":"ec2","auth-types":\["access-key"\].*`) } -func (s *showSuite) TestListPreservesRegionOrder(c *gc.C) { +func (s *listSuite) TestListPreservesRegionOrder(c *gc.C) { ctx, err := testing.RunCommand(c, cloud.NewListCloudsCommand(), "--format", "yaml") c.Assert(err, jc.ErrorIsNil) lines := strings.Split(testing.Stdout(ctx), "\n")
Move a test method into the correct suite.
juju_juju
train
04682ffedd9494a1c347fdaa6cdcfa23457577e5
diff --git a/plugins/LanguagesManager/Commands/FetchTranslations.php b/plugins/LanguagesManager/Commands/FetchTranslations.php index <HASH>..<HASH> 100644 --- a/plugins/LanguagesManager/Commands/FetchTranslations.php +++ b/plugins/LanguagesManager/Commands/FetchTranslations.php @@ -62,17 +62,6 @@ class FetchTranslations extends TranslationBase $output->writeln("Fetching translations from Transifex for resource $resource"); - $availableLanguages = LanguagesManagerApi::getInstance()->getAvailableLanguageNames(); - - $languageCodes = array(); - foreach ($availableLanguages as $languageInfo) { - $languageCodes[] = $languageInfo['code']; - } - - $languageCodes = array_filter($languageCodes, function($code) { - return !in_array($code, array('en', 'dev')); - }); - try { $languages = $transifexApi->getAvailableLanguageCodes(); @@ -82,6 +71,23 @@ class FetchTranslations extends TranslationBase }); } } catch (AuthenticationFailedException $e) { + $availableLanguages = LanguagesManagerApi::getInstance()->getAvailableLanguageNames(); + + $languageCodes = array(); + foreach ($availableLanguages as $languageInfo) { + $codeParts = explode('-', $languageInfo['code']); + + if (!empty($codeParts[1])) { + $codeParts[1] = strtoupper($codeParts[1]); + } + + $languageCodes[] = implode('_', $codeParts); + } + + $languageCodes = array_filter($languageCodes, function($code) { + return !in_array($code, array('en', 'dev')); + }); + $languages = $languageCodes; }
Fix fetching translations if user is not able to fetch available languages
matomo-org_matomo
train
7e1cda19c4ab5f92111b91ac941db4907d26a4d2
diff --git a/LegacyMapper/Configuration.php b/LegacyMapper/Configuration.php index <HASH>..<HASH> 100644 --- a/LegacyMapper/Configuration.php +++ b/LegacyMapper/Configuration.php @@ -102,7 +102,7 @@ class Configuration implements EventSubscriberInterface foreach ( $aliasSettings['filters'] as $filter ) { - $imageSettings["image.ini/$aliasName/Filters"][] = $filter['name'] . '=' . implode( ', ', $filter['params'] ); + $imageSettings["image.ini/$aliasName/Filters"][] = $filter['name'] . '=' . implode( ';', $filter['params'] ); } }
EZP-<I>: Fixed wrong configuration translation to legacy kernel image alias
ezsystems_LegacyBridge
train
66f78133a97b6e215e959ea8cc5ef502bf5ee636
diff --git a/lib/resque/worker.rb b/lib/resque/worker.rb index <HASH>..<HASH> 100644 --- a/lib/resque/worker.rb +++ b/lib/resque/worker.rb @@ -312,8 +312,6 @@ module Resque # Unregisters ourself as a worker. Useful when shutting down. def unregister_worker - done_working - redis.srem(:workers, self) redis.del("worker:#{self}:started") diff --git a/test/worker_test.rb b/test/worker_test.rb index <HASH>..<HASH> 100644 --- a/test/worker_test.rb +++ b/test/worker_test.rb @@ -226,4 +226,9 @@ context "Resque::Worker" do assert_equal 1, Resque.workers.size end end + + test "Processed jobs count" do + @worker.work(0) + assert_equal 1, Resque.info[:processed] + end end
Worker#unregister_worker shouldn't call done_working unregister_worker faulty increments Stat[:processed] by calling done_working
resque_resque
train
5f4e4cd9bbe277d6b8ab40b4ba7ff06ffec0dec9
diff --git a/lib/erubis/engine.rb b/lib/erubis/engine.rb index <HASH>..<HASH> 100644 --- a/lib/erubis/engine.rb +++ b/lib/erubis/engine.rb @@ -48,7 +48,8 @@ module Erubis def self.load_file(filename, properties={}) cachename = properties[:cachename] || (filename + '.cache') properties[:filename] = filename - if test(?f, cachename) && File.mtime(filename) <= File.mtime(cachename) + timestamp = File.mtime(filename) + if test(?f, cachename) && timestamp == File.mtime(cachename) engine = self.new(nil, properties) engine.src = File.read(cachename) else @@ -57,6 +58,7 @@ module Erubis tmpname = cachename + rand().to_s[1,8] File.open(tmpname, 'wb') {|f| f.write(engine.src) } File.rename(tmpname, cachename) + File.utime(timestamp, timestamp, cachename) end engine.src.untaint # ok? return engine diff --git a/test/test-erubis.rb b/test/test-erubis.rb index <HASH>..<HASH> 100644 --- a/test/test-erubis.rb +++ b/test/test-erubis.rb @@ -119,32 +119,36 @@ END filename = 'tmp.load_file_timestamp1' cachename = filename + '.cache' begin + ## when cache doesn't exist then it is created automatically File.open(filename, 'w') { |f| f.write(@input) } - assert_block() { !test(?f, cachename) } + mtime = Time.now - 2.0 + File.utime(mtime, mtime, filename) + !test(?f, cachename) or raise "** failed" engine = @klass.load_file(filename) assert_block() { test(?f, cachename) } assert_block() { File.mtime(filename) <= File.mtime(cachename) } assert_text_equal(@src, engine.src) - # + ## when cache has different timestamp then it is recreated input2 = @input.gsub(/ul>/, 'ol>') src2 = @src.gsub(/ul>/, 'ol>') - mtime = File.mtime(filename) File.open(filename, 'w') { |f| f.write(input2) } t1 = Time.now() sleep(1) t2 = Time.now() + # File.utime(t1, t1, filename) File.utime(t2, t2, cachename) - assert_block('cache should be newer') { File.mtime(filename) < File.mtime(cachename) } + File.mtime(filename) < File.mtime(cachename) or raise "** failed" engine = @klass.load_file(filename) - assert_block('cache should be newer') { File.mtime(filename) < File.mtime(cachename) } - assert_text_equal(@src, engine.src) + assert_block('cache should have same timestamp') { File.mtime(filename) == File.mtime(cachename) } + #assert_text_equal(@src, engine.src) + assert_text_equal(src2, engine.src) # File.utime(t2, t2, filename) File.utime(t1, t1, cachename) - assert_block('cache should be older') { File.mtime(filename) > File.mtime(cachename) } + File.mtime(filename) > File.mtime(cachename) or raise "** failed" engine = @klass.load_file(filename) - assert_block('cache should be newer') { File.mtime(filename) <= File.mtime(cachename) } + assert_block('cache should have same timestamp') { File.mtime(filename) == File.mtime(cachename) } assert_text_equal(src2, engine.src) ensure File.unlink(cachename) if File.file?(cachename)
[change] 'Erubis::Engine.load_file()' to set cache timestamp to be the same value as original file
kwatch_erubis
train
ea2318e0102d80ff9ca0be937a7b93e3673634ad
diff --git a/testing.js b/testing.js index <HASH>..<HASH> 100644 --- a/testing.js +++ b/testing.js @@ -525,7 +525,11 @@ var createMockAuthServer = function(options) { app.use('/v1', router); // Create server - return app.createServer(); + return app.createServer().then(function(server) { + // Time out connections after 500 ms, prevents tests from hanging + server.setTimeout(500); + return server; + }); }); };
Added timeout to avoid test hangs with http.agent
taskcluster_taskcluster-base
train
83d39538941fa45b8e28cc8129d93925f2780722
diff --git a/user/config-sample.php b/user/config-sample.php index <HASH>..<HASH> 100644 --- a/user/config-sample.php +++ b/user/config-sample.php @@ -30,7 +30,7 @@ define( 'YOURLS_DB_PREFIX', 'yourls_' ); ** Site options */ -/** YOURLS installation URL -- all lowercase and with no trailing slash. +/** YOURLS installation URL -- all lowercase, no trailing slash at the end. ** If you define it to "http://sho.rt", don't use "http://www.sho.rt" in your browser (and vice-versa) */ define( 'YOURLS_SITE', 'http://your-own-domain-here.com' );
More explicitnessly explicitness See #<I>
YOURLS_YOURLS
train
8261bfb50f42bf8111538251988c2f5cb9c6156d
diff --git a/lib/github_api/repos/hooks.rb b/lib/github_api/repos/hooks.rb index <HASH>..<HASH> 100644 --- a/lib/github_api/repos/hooks.rb +++ b/lib/github_api/repos/hooks.rb @@ -59,9 +59,9 @@ module Github # github.repos.hooks.get 'user-name', 'repo-name', 'hook-id' # def get(*args) - arguments(args, :required => [:user, :repo, :hook_id]) + arguments(args, :required => [:user, :repo, :id]) - get_request("/repos/#{user}/#{repo}/hooks/#{hook_id}", arguments.params) + get_request("/repos/#{user}/#{repo}/hooks/#{id}", arguments.params) end alias :find :get @@ -104,7 +104,7 @@ module Github # # = Examples # github = Github.new - # github.repos.hooks.edit 'user-name', 'repo-name', + # github.repos.hooks.edit 'user-name', 'repo-name', 'hook-id', # "name" => "campfire", # "active" => true, # "config" => { @@ -114,12 +114,12 @@ module Github # } # def edit(*args) - arguments(args, :required => [:user, :repo, :hook_id]) do + arguments(args, :required => [:user, :repo, :id]) do sift VALID_HOOK_PARAM_NAMES, :recursive => false assert_required REQUIRED_PARAMS end - patch_request("/repos/#{user}/#{repo}/hooks/#{hook_id}", arguments.params) + patch_request("/repos/#{user}/#{repo}/hooks/#{id}", arguments.params) end # Test a hook @@ -131,7 +131,7 @@ module Github # github.repos.hooks.test 'user-name', 'repo-name', 'hook-id' # def test(*args) - arguments(args, :required => [:user, :repo, :hook_id]) + arguments(args, :required => [:user, :repo, :id]) params = arguments.params post_request("/repos/#{user}/#{repo}/hooks/#{id}/test", params) @@ -141,7 +141,7 @@ module Github # # = Examples # github = Github.new - # github.repos.hooks.delete 'user-name', 'repo-name', 'id' + # github.repos.hooks.delete 'user-name', 'repo-name', 'hook-id' # def delete(*args) arguments(args, :required => [:user, :repo, :id])
Convert hook_id to id.
piotrmurach_github
train
3b9903b1bd3824f77b772687bd5875b5eef28e66
diff --git a/galpy/potential_src/EllipticalDiskPotential.py b/galpy/potential_src/EllipticalDiskPotential.py index <HASH>..<HASH> 100644 --- a/galpy/potential_src/EllipticalDiskPotential.py +++ b/galpy/potential_src/EllipticalDiskPotential.py @@ -48,7 +48,7 @@ class EllipticalDiskPotential(planarPotential): """ planarPotential.__init__(self,amp=amp) - self.hasC= False + self.hasC= True self._phib= phib self._twophio= twophio self._p= p
EllipticalDiskPotential now has a C implementation
jobovy_galpy
train
725c411346e04dcc72934329345ef5607f912608
diff --git a/raft/doc.go b/raft/doc.go index <HASH>..<HASH> 100644 --- a/raft/doc.go +++ b/raft/doc.go @@ -35,7 +35,8 @@ previously-persisted entries with Index >= i must be discarded. 2. Send all Messages to the nodes named in the To field. It is important that no messages be sent until after the latest HardState has been persisted to disk, and all Entries written by any previous Ready batch (Messages may be sent while -entries from the same batch are being persisted). +entries from the same batch are being persisted). If any Message has type MsgSnap, +call Node.ReportSnapshot() after it has been sent (these messages may be large). 3. Apply Snapshot (if any) and CommittedEntries to the state machine. If any committed Entry has Type EntryConfChange, call Node.ApplyConfChange() diff --git a/raft/multinode.go b/raft/multinode.go index <HASH>..<HASH> 100644 --- a/raft/multinode.go +++ b/raft/multinode.go @@ -38,6 +38,10 @@ type MultiNode interface { Advance(map[uint64]Ready) // Status returns the current status of the given group. Status(group uint64) Status + // Report reports the given node is not reachable for the last send. + ReportUnreachable(id, groupID uint64) + // ReportSnapshot reports the stutus of the sent snapshot. + ReportSnapshot(id, groupID uint64, status SnapshotStatus) // Stop performs any necessary termination of the MultiNode. Stop() } @@ -447,3 +451,25 @@ func (mn *multiNode) Status(group uint64) Status { mn.status <- ms return <-ms.ch } + +func (mn *multiNode) ReportUnreachable(id, groupID uint64) { + select { + case mn.recvc <- multiMessage{ + group: groupID, + msg: pb.Message{Type: pb.MsgUnreachable, From: id}, + }: + case <-mn.done: + } +} + +func (mn *multiNode) ReportSnapshot(id, groupID uint64, status SnapshotStatus) { + rej := status == SnapshotFailure + + select { + case mn.recvc <- multiMessage{ + group: groupID, + msg: pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej}, + }: + case <-mn.done: + } +}
Add ReportUnreachable and ReportSnapshot to MultiNode. Add ReportSnapshot requirement to doc.go.
etcd-io_etcd
train
688331477609e2baa2d0a3403709cc91d2c0911e
diff --git a/test/pgslice_test.rb b/test/pgslice_test.rb index <HASH>..<HASH> 100644 --- a/test/pgslice_test.rb +++ b/test/pgslice_test.rb @@ -183,11 +183,11 @@ class PgSliceTest < Minitest::Test stdout, stderr = capture_io do PgSlice::CLI.start("#{command} --url #{$url}".split(" ")) end - assert_equal "", stderr if verbose? puts stdout puts end + assert_equal "", stderr stdout end
Improved debugging with VERBOSE option [skip ci]
ankane_pgslice
train
b86ab0904e3a04fb64e3596f22c3ae3c4cf395f9
diff --git a/ryu/services/protocols/bgp/peer.py b/ryu/services/protocols/bgp/peer.py index <HASH>..<HASH> 100644 --- a/ryu/services/protocols/bgp/peer.py +++ b/ryu/services/protocols/bgp/peer.py @@ -1466,8 +1466,10 @@ class Peer(Source, Sink, NeighborConfListener, Activity): received_route = ReceivedRoute(w_path, self, block) nlri_str = w_nlri.formatted_nlri_str - self._adj_rib_in[nlri_str] = received_route - self._signal_bus.adj_rib_in_changed(self, received_route) + + if nlri_str in self._adj_rib_in: + del self._adj_rib_in[nlri_str] + self._signal_bus.adj_rib_in_changed(self, received_route) if not block: # Update appropriate table with withdraws. @@ -1622,8 +1624,10 @@ class Peer(Source, Sink, NeighborConfListener, Activity): received_route = ReceivedRoute(w_path, self, block) nlri_str = w_nlri.formatted_nlri_str - self._adj_rib_in[nlri_str] = received_route - self._signal_bus.adj_rib_in_changed(self, received_route) + + if nlri_str in self._adj_rib_in: + del self._adj_rib_in[nlri_str] + self._signal_bus.adj_rib_in_changed(self, received_route) if not block: # Update appropriate table with withdraws.
bgp: don't hold withdrawn routes in adj_rib_in
osrg_ryu
train
168bc2b5113648fd481e94378bae3dae3599982a
diff --git a/src/openaccess_epub/main.py b/src/openaccess_epub/main.py index <HASH>..<HASH> 100755 --- a/src/openaccess_epub/main.py +++ b/src/openaccess_epub/main.py @@ -50,9 +50,15 @@ def OAEParser(): parser.add_argument('-c', '--clean', action='store_true', default=False, help='''Use to toggle on cleanup. With this flag, the pre-zipped output will be removed.''') - parser.add_argument('-N', '--no-epubcheck', action='store_false', + parser.add_argument('-e', '--no-epubcheck', action='store_false', default=True, help='''Use this to skip ePub validation by EpubCheck.''') + parser.add_argument('-d', '--no-dtd-validation', action='store_false', + default=True, + help='''Use this to skip DTD-validation on the input + file(s). This is advised only for use on files + that have already been validated by dtdvalidate + or otherwise.''') modes = parser.add_mutually_exclusive_group() modes.add_argument('-i', '--input', action='store', default=False, help='''Input may be a path to a local directory, a @@ -110,17 +116,17 @@ def single_input(args, config=None): if 'http:' in args.input: raw_name = u_input.url_input(args.input) abs_input_path = os.path.join(LOCAL_DIR, raw_name+'.xml') - parsed_article = Article(abs_input_path) + parsed_article = Article(abs_input_path, validation=args.no_dtd_validation) #Fetch by DOI elif args.input[:4] == 'doi:': raw_name = u_input.doi_input(args.input) abs_input_path = os.path.join(LOCAL_DIR, raw_name+'.xml') - parsed_article = Article(abs_input_path) + parsed_article = Article(abs_input_path, validation=args.no_dtd_validation) #Local XML input else: abs_input_path = utils.get_absolute_path(args.input) raw_name = u_input.local_input(abs_input_path) - parsed_article = Article(abs_input_path) + parsed_article = Article(abs_input_path, validation=args.no_dtd_validation) #Generate the output path name, this will be the directory name for the #output. This output directory will later be zipped into an EPUB @@ -179,7 +185,8 @@ def batch_input(args, config=None): except: traceback.print_exc(file=error_file) else: - parsed_article = Article(os.path.join(args.batch, raw_name+'.xml')) + parsed_article = Article(os.path.join(args.batch, raw_name+'.xml'), + validation=args.no_dtd_validation) #Create the output name output_name = os.path.join(utils.get_output_directory(args), raw_name) @@ -272,7 +279,7 @@ def collection_input(args, config=None): #Now it is time to operate on each of the xml files for xml_file in xml_files: raw_name = u_input.local_input(xml_file) # is this used? - parsed_article = Article(xml_file) + parsed_article = Article(xml_file, validation=args.no_dtd_validation) toc.take_article(parsed_article) myopf.take_article(parsed_article)
making some adjustments to the argument parser to enable toggling of dtd validation
SavinaRoja_OpenAccess_EPUB
train
f67c68fbfae9b7960fb400c46a51d77c19d523a6
diff --git a/src/Controller.php b/src/Controller.php index <HASH>..<HASH> 100644 --- a/src/Controller.php +++ b/src/Controller.php @@ -8,6 +8,7 @@ use SilverStripe\Control\Controller as BaseController; use SilverStripe\Control\Director; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPResponse; +use SilverStripe\Control\NullHTTPRequest; use SilverStripe\Core\Config\Config; use SilverStripe\Core\Flushable; use SilverStripe\Core\Injector\Injector; @@ -414,7 +415,12 @@ class Controller extends BaseController implements Flushable */ public function writeSchemaToFilesystem() { - $manager = $this->getManager(); + if (Injector::inst()->has(HTTPRequest::class)) { + $request = Injector::inst()->get(HTTPRequest::class); + } else { + $request = new NullHTTPRequest(); + } + $manager = $this->getManager($request); try { $types = StaticSchema::inst()->introspectTypes($manager); } catch (Exception $e) {
Add dummy request (#<I>) * Add dummy request Fixes #<I> * Implement feedback from robbieaverill * Fix failing CI build * Move use statement to proper location
silverstripe_silverstripe-graphql
train
9ed31320998c99622832e2ea35fb7c330cc9beda
diff --git a/lib/cache.js b/lib/cache.js index <HASH>..<HASH> 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -7,34 +7,58 @@ // Expires: Thu, 01 Dec 1994 16:00:00 GMT // Server: CERN/3.0 libwww/2.17 -module.exports=function(req,res,next){ - // cache files whose names begin with 'static' - if(req.url.match(/\/static[^\/]+$/)){ - res.setHeader("Cache-Control","max-age=604800,public"); - }else{ - var ext; - req.url.replace(/\.[a-z]+$/,function(e){ - ext=e; - return e; +module.exports=function(opt){ + opt=opt||{}; + + // default caching time for declared extensions + opt.def=opt.def||604800; + + // you can pass an array of extensions + // they will be initialized to use the default caching time + opt.std=opt.std||'jpg jpeg png ico'.split(' '); + + // for any more definitions, you can use an object + // in which the keys correspond to extensions + opt.dict=opt.dict||{ + ttf:290304000 + ,otf:290304000 + }; + + // you also have the option of caching files implicitly based on their url + // this uses a regex + opt.implicit=opt.implicit|| /\/static[^\/]+$/; + opt.implicitDuration=opt.implicitDuration||604800; + + // the final set of cache time definitions + var DICT={}; + + // define cache duration for all types considered standard + // use the default cache duration + opt.std + .map(function(ext){ + DICT[ext]=opt.def; + }); + + // merge in the types from the dictionary + Object.keys(opt.dict) + .map(function(ext){ + DICT[ext]=opt.dict[ext]; }); - if(ext){ - switch(ext){ - // fonts are good for a loooong time - case '.ttf': - // 480 weeks is a little over 9 years - res.setHeader("Cache-Control","max-age=290304000,public"); - break; - // if it's a picture - case '.jpeg': - case '.jpg': - case '.png': - case '.ico': // cache it for the next week - res.setHeader("Cache-Control","max-age=604800,public"); - break; - default: - break; + + return function(req,res,next){ + // cache files whose names begin with 'static' + if(opt.implicit.test(req.url)){ + res.setHeader("Cache-Control","max-age="+opt.implicitDuration+",public"); + }else{ + var ext; + req.url.replace(/\.[a-z]+$/,function(e){ + ext=e.slice(1); + return e; + }); + if(ext){ + res.setHeader("Cache-Control","max-age="+(DICT[ext]||0)+",public"); } } - } - next(); + next(); + }; };
lib/cache.js : cache is now configurable via some nifty tricks
ansuz_unmon
train
5e7ec04d63c22f3148667fb7daffa9fd757081d3
diff --git a/app/controllers/devise/g5_sessions_controller.rb b/app/controllers/devise/g5_sessions_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/devise/g5_sessions_controller.rb +++ b/app/controllers/devise/g5_sessions_controller.rb @@ -1,4 +1,7 @@ module Devise - class G5SessionsController < Devise::SessionsController + class G5SessionsController < Devise::OmniauthCallbacksController + def new + redirect_to user_g5_authorize_path + end end end diff --git a/lib/devise_g5_authenticatable/routes.rb b/lib/devise_g5_authenticatable/routes.rb index <HASH>..<HASH> 100644 --- a/lib/devise_g5_authenticatable/routes.rb +++ b/lib/devise_g5_authenticatable/routes.rb @@ -10,7 +10,7 @@ module ActionDispatch::Routing match 'auth/g5', controller: controllers[:g5_sessions], - action: 'new', + action: 'passthru', as: :g5_authorize, via: [:get, :post] diff --git a/spec/controllers/g5_sessions_controller_spec.rb b/spec/controllers/g5_sessions_controller_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/g5_sessions_controller_spec.rb +++ b/spec/controllers/g5_sessions_controller_spec.rb @@ -6,14 +6,18 @@ describe Devise::G5SessionsController do describe '#new' do subject(:get_new) { get :new } - it 'should return a 404 to trigger OmniAuth' do + it 'should redirect to the g5 authorize path' do get_new - expect(response).to be_not_found + expect(response).to redirect_to(user_g5_authorize_path) end + end - it 'should redirect to the g5 authorize path' do - get_new - expect(response.body).to eq('Not found. Authentication passthru.') + describe '#passthru' do + subject(:passthru) { get :passthru } + + it 'should return a 404' do + passthru + expect(response).to be_not_found end end diff --git a/spec/routing/sessions_routing_spec.rb b/spec/routing/sessions_routing_spec.rb index <HASH>..<HASH> 100644 --- a/spec/routing/sessions_routing_spec.rb +++ b/spec/routing/sessions_routing_spec.rb @@ -15,12 +15,12 @@ describe 'Sessions controller' do it 'should route GET /users/auth/g5' do expect(get '/users/auth/g5').to route_to(controller: 'devise/g5_sessions', - action: 'new') + action: 'passthru') end it 'should route POST /users/auth/g5' do expect(post '/users/auth/g5').to route_to(controller: 'devise/g5_sessions', - action: 'new') + action: 'passthru') end it 'should route GET /users/auth/g5/callback' do @@ -47,12 +47,12 @@ describe 'Sessions controller' do it 'should route GET /registered/admins/auth/g5' do expect(get '/registered/admins/auth/g5').to route_to(controller: 'custom_sessions', - action: 'new') + action: 'passthru') end it 'should route POST /registered/admins/auth/g5' do expect(post '/registered/admins/auth/g5').to route_to(controller: 'custom_sessions', - action: 'new') + action: 'passthru') end it 'should route GET /registered/admins/auth/g5/callback' do
Auth passthru for entry point into OmniAuth
G5_devise_g5_authenticatable
train
5028978e32e775ec5578ff5d2ed7a982f742ff77
diff --git a/Slim/Routing/RouteCollector.php b/Slim/Routing/RouteCollector.php index <HASH>..<HASH> 100644 --- a/Slim/Routing/RouteCollector.php +++ b/Slim/Routing/RouteCollector.php @@ -34,65 +34,44 @@ use function is_writable; */ class RouteCollector implements RouteCollectorInterface { - /** - * @var RouteParserInterface - */ - protected $routeParser; + protected RouteParserInterface $routeParser; - /** - * @var CallableResolverInterface - */ - protected $callableResolver; + protected CallableResolverInterface $callableResolver; - /** - * @var ContainerInterface|null - */ - protected $container; + protected ?ContainerInterface $container = null; - /** - * @var InvocationStrategyInterface - */ - protected $defaultInvocationStrategy; + protected InvocationStrategyInterface $defaultInvocationStrategy; /** * Base path used in pathFor() - * - * @var string */ - protected $basePath = ''; + protected string $basePath = ''; /** * Path to fast route cache file. Set to null to disable route caching - * - * @var string|null */ - protected $cacheFile; + protected ?string $cacheFile = null; /** * Routes * * @var RouteInterface[] */ - protected $routes = []; + protected array $routes = []; /** * Route groups * * @var RouteGroup[] */ - protected $routeGroups = []; + protected array $routeGroups = []; /** * Route counter incrementer - * - * @var int */ - protected $routeCounter = 0; + protected int $routeCounter = 0; - /** - * @var ResponseFactoryInterface - */ - protected $responseFactory; + protected ResponseFactoryInterface $responseFactory; /** * @param ResponseFactoryInterface $responseFactory
Adding types to RouteCollector
slimphp_Slim
train
c4c7cf2c54f19f96690b2f996f1b30fe9bf6cdab
diff --git a/source/org/jasig/portal/layout/AggregatedLayoutManager.java b/source/org/jasig/portal/layout/AggregatedLayoutManager.java index <HASH>..<HASH> 100644 --- a/source/org/jasig/portal/layout/AggregatedLayoutManager.java +++ b/source/org/jasig/portal/layout/AggregatedLayoutManager.java @@ -1279,6 +1279,10 @@ public class AggregatedLayoutManager implements IAggregatedUserLayoutManager { public synchronized boolean moveNode(String nodeId, String parentId,String nextSiblingId) throws PortalException { + + // if the node is being moved to itself that operation must be prevented + if ( nodeId.equals(nextSiblingId) ) + return false; // Checking restrictions if the parent is not the lost folder if ( !parentId.equals(IALFolderDescription.LOST_FOLDER_ID) )
Prevented the situation when a node could be moved to itself git-svn-id: <URL>
Jasig_uPortal
train
d1b23dcd365be30cd2f19b15da125002f49a8e40
diff --git a/coconut/root.py b/coconut/root.py index <HASH>..<HASH> 100644 --- a/coconut/root.py +++ b/coconut/root.py @@ -30,7 +30,7 @@ except ImportError: # CONSTANTS: #------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -VERSION = "0.1.0" +VERSION = "0.1.1" ENCODING = "UTF"
Updates to version <I>
evhub_coconut
train
2ce17df12e5b55dc0a90a02b6b3fc7d5e6679f59
diff --git a/master/buildbot/test/unit/steps/test_python.py b/master/buildbot/test/unit/steps/test_python.py index <HASH>..<HASH> 100644 --- a/master/buildbot/test/unit/steps/test_python.py +++ b/master/buildbot/test/unit/steps/test_python.py @@ -167,7 +167,7 @@ class PyLint(steps.BuildStepMixin, TestReactorMixin, unittest.TestCase): self.expect_outcome(result=SUCCESS, state_string='pylint') if store_results: self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')]) - self.expectTestResults([]) + self.expect_test_results([]) return self.run_step() @parameterized.expand([ @@ -296,7 +296,7 @@ class PyLint(steps.BuildStepMixin, TestReactorMixin, unittest.TestCase): self.expect_property('pylint-total', 2) if store_results: self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')]) - self.expectTestResults([ + self.expect_test_results([ (1000, 'test.py:9:4: W0311: Bad indentation. Found 6 spaces, expected 4 ' + '(bad-indentation)', None, 'test.py', 9, None), @@ -369,7 +369,7 @@ class PyLint(steps.BuildStepMixin, TestReactorMixin, unittest.TestCase): self.expect_property('pylint-total', 2) if store_results: self.expect_test_result_sets([('Pylint warnings', 'code_issue', 'message')]) - self.expectTestResults([ + self.expect_test_results([ (1000, 'test.py:9: [W0311] Bad indentation.', None, 'test.py', 9, None), (1000, 'test.py:3: [C0111, foo123] Missing docstring', None, 'test.py', 3, None), ]) diff --git a/master/buildbot/test/util/steps.py b/master/buildbot/test/util/steps.py index <HASH>..<HASH> 100644 --- a/master/buildbot/test/util/steps.py +++ b/master/buildbot/test/util/steps.py @@ -341,7 +341,7 @@ class BuildStepMixin: def expect_test_result_sets(self, sets): self._exp_test_result_sets = sets - def expectTestResults(self, results): + def expect_test_results(self, results): self._exp_test_results = results def _dump_logs(self):
test: Rename BuildStepMixin.expectTestResults() to snake case
buildbot_buildbot
train
2de70b422eb2141f864ae0388aa79b74f2786d08
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from setuptools import find_packages, setup setup( name='graphene-sqlalchemy', - version='1.1.0', + version='1.1.1', description='Graphene SQLAlchemy integration', long_description=open('README.rst').read(),
Updated version to <I>
graphql-python_graphene-sqlalchemy
train
d74669e2ab454886ae9958add5354374e8d0c207
diff --git a/tests/utils/mock_server.py b/tests/utils/mock_server.py index <HASH>..<HASH> 100644 --- a/tests/utils/mock_server.py +++ b/tests/utils/mock_server.py @@ -30,7 +30,7 @@ def default_ctx(): "files": {}, "k8s": False, "resume": False, - "file_bytes": 0, + "file_bytes": {}, } @@ -692,7 +692,12 @@ def create_app(user_ctx=None): # make sure to read the data request.get_data() if request.method == "PUT": - ctx["file_bytes"] += request.content_length + curr = ctx["file_bytes"].get(file) + if curr is None: + ctx["file_bytes"].setdefault(file, 0) + ctx["file_bytes"][file] += request.content_length + else: + ctx["file_bytes"][file] += request.content_length if file == "wandb_manifest.json": if _id == "bb8043da7d78ff168a695cff097897d2": return { diff --git a/tests/wandb_integration_test.py b/tests/wandb_integration_test.py index <HASH>..<HASH> 100644 --- a/tests/wandb_integration_test.py +++ b/tests/wandb_integration_test.py @@ -400,4 +400,6 @@ def test_live_policy_file_upload(live_mock_server, test_settings, mocker): server_ctx = live_mock_server.get_ctx() print(server_ctx["file_bytes"], sent) - assert abs(server_ctx["file_bytes"] - sent) < 15000 + assert "saveFile" in server_ctx["file_bytes"].keys() + # TODO: bug sometimes it seems that on windows the first file is sent twice + assert abs(server_ctx["file_bytes"]["saveFile"] - sent) <= 10000
[CLI-<I>-Tests-2]: Deflaking the new policy test (#<I>)
wandb_client
train
4460e2865dabb1d11950c04b5a4c9b79a12301e1
diff --git a/conf/cassandra.yaml b/conf/cassandra.yaml index <HASH>..<HASH> 100644 --- a/conf/cassandra.yaml +++ b/conf/cassandra.yaml @@ -623,6 +623,7 @@ server_encryption_options: # algorithm: SunX509 # store_type: JKS # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA] + # require_client_auth: false # enable or disable client/server encryption. client_encryption_options: @@ -634,6 +635,7 @@ client_encryption_options: # algorithm: SunX509 # store_type: JKS # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA] + # require_client_auth: false # internode_compression controls whether traffic between nodes is # compressed. diff --git a/src/java/org/apache/cassandra/config/EncryptionOptions.java b/src/java/org/apache/cassandra/config/EncryptionOptions.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/config/EncryptionOptions.java +++ b/src/java/org/apache/cassandra/config/EncryptionOptions.java @@ -27,6 +27,7 @@ public abstract class EncryptionOptions public String protocol = "TLS"; public String algorithm = "SunX509"; public String store_type = "JKS"; + public Boolean require_client_auth = false; public static class ClientEncryptionOptions extends EncryptionOptions { diff --git a/src/java/org/apache/cassandra/security/SSLFactory.java b/src/java/org/apache/cassandra/security/SSLFactory.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/security/SSLFactory.java +++ b/src/java/org/apache/cassandra/security/SSLFactory.java @@ -55,6 +55,7 @@ public final class SSLFactory serverSocket.setReuseAddress(true); String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites); serverSocket.setEnabledCipherSuites(suits); + serverSocket.setNeedClientAuth(options.require_client_auth); serverSocket.bind(new InetSocketAddress(address, port), 100); return serverSocket; } diff --git a/src/java/org/apache/cassandra/thrift/CustomTThreadPoolServer.java b/src/java/org/apache/cassandra/thrift/CustomTThreadPoolServer.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/thrift/CustomTThreadPoolServer.java +++ b/src/java/org/apache/cassandra/thrift/CustomTThreadPoolServer.java @@ -249,6 +249,7 @@ public class CustomTThreadPoolServer extends TServer logger.info("enabling encrypted thrift connections between client and server"); TSSLTransportParameters params = new TSSLTransportParameters(clientEnc.protocol, clientEnc.cipher_suites); params.setKeyStore(clientEnc.keystore, clientEnc.keystore_password); + params.requireClientAuth(clientEnc.require_client_auth); TServerSocket sslServer = TSSLTransportFactory.getServerSocket(addr.getPort(), 0, addr.getAddress(), params); serverTransport = new TCustomServerSocket(sslServer.getServerSocket(), args.keepAlive, args.sendBufferSize, args.recvBufferSize); } diff --git a/src/java/org/apache/cassandra/transport/Server.java b/src/java/org/apache/cassandra/transport/Server.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/transport/Server.java +++ b/src/java/org/apache/cassandra/transport/Server.java @@ -249,7 +249,8 @@ public class Server implements CassandraDaemon.Server SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); sslEngine.setEnabledCipherSuites(encryptionOptions.cipher_suites); - + sslEngine.setNeedClientAuth(encryptionOptions.require_client_auth); + SslHandler sslHandler = new SslHandler(sslEngine); sslHandler.setIssueHandshake(true); ChannelPipeline pipeline = super.getPipeline();
Add support for SSL sockets to use client certificate authentication. patch by Steven Franklin and Vijay for CASSANDRA-<I>
Stratio_stratio-cassandra
train
4332ed0e5c43214f1368f96f4c7fc32e3a9a8c23
diff --git a/webapps/webapp/src/test/js/e2e/admin/specs/authorizations-spec.js b/webapps/webapp/src/test/js/e2e/admin/specs/authorizations-spec.js index <HASH>..<HASH> 100644 --- a/webapps/webapp/src/test/js/e2e/admin/specs/authorizations-spec.js +++ b/webapps/webapp/src/test/js/e2e/admin/specs/authorizations-spec.js @@ -619,25 +619,25 @@ describe('Admin authorizations Spec', function() { expect(authorizationsPage.authorizationResource(2)).to.eventually.eql('foobar'); }); - it('should not apply conflicting updates', function() { + it('should restore previous state on cancel', function() { authorizationsPage.updateButton(3).click(); authorizationsPage.userGroupInput(3).clear().sendKeys('a4'); - authorizationsPage.applyUpdateButton(3).click(); - - // need sleep because update is successful until the server says otherwise - browser.sleep(500); + authorizationsPage.cancelUpdateButton(3).click(); expect(authorizationsPage.authorizationIdentity(3)).to.eventually.eql('a3'); }); - it('should restore previous state on cancel', function() { + it('should not apply conflicting updates', function() { authorizationsPage.updateButton(3).click(); authorizationsPage.userGroupInput(3).clear().sendKeys('a4'); - authorizationsPage.cancelUpdateButton(3).click(); + authorizationsPage.applyUpdateButton(3).click(); + + // need sleep because update is successful until the server says otherwise + browser.sleep(500); expect(authorizationsPage.authorizationIdentity(3)).to.eventually.eql('a3'); });
chore(tests): change order of auth update tests related to CAM-<I>
camunda_camunda-bpm-platform
train
77e2e523c88915ffd845e44bb5c5f4c59d948122
diff --git a/source/Core/Email.php b/source/Core/Email.php index <HASH>..<HASH> 100644 --- a/source/Core/Email.php +++ b/source/Core/Email.php @@ -1057,7 +1057,7 @@ class Email extends \PHPMailer $store['INCLUDE_ANY'] = $smarty->security_settings['INCLUDE_ANY']; //V send email in order language $oldTplLang = $lang->getTplLanguage(); - $oldBaseLang = $lang->getTplLanguage(); + $oldBaseLang = $lang->getBaseLanguage(); $lang->setTplLanguage($orderLang); $lang->setBaseLanguage($orderLang);
The tpl language is accidently used for saving the base language... ...which causes some broken view sql queries later.
OXID-eSales_oxideshop_ce
train
ea5f90b6bc358ab325ef43e28d597b9d296883ac
diff --git a/lib/dimples/configuration.rb b/lib/dimples/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/dimples/configuration.rb +++ b/lib/dimples/configuration.rb @@ -18,7 +18,7 @@ module Dimples def self.default_paths { - output: 'site', + output: 'public', archives: 'archives', posts: 'archives/%Y/%m/%d', categories: 'archives/categories' diff --git a/lib/dimples/site.rb b/lib/dimples/site.rb index <HASH>..<HASH> 100644 --- a/lib/dimples/site.rb +++ b/lib/dimples/site.rb @@ -19,7 +19,7 @@ module Dimples paths[:base] = Dir.pwd paths[:output] = File.join(paths[:base], @config.paths.output) paths[:sources] = {}.tap do |sources| - %w[pages posts public templates].each do |type| + %w[pages posts static templates].each do |type| sources[type.to_sym] = File.join(paths[:base], type) end end @@ -38,7 +38,7 @@ module Dimples read_pages create_output_directory - copy_assets + copy_static_assets publish_posts publish_pages @@ -126,9 +126,9 @@ module Dimples raise GenerationError, message end - def copy_assets - return unless Dir.exist?(@paths[:sources][:public]) - FileUtils.cp_r(File.join(@paths[:sources][:public], '.'), @paths[:output]) + def copy_static_assets + return unless Dir.exist?(@paths[:sources][:static]) + FileUtils.cp_r(File.join(@paths[:sources][:static], '.'), @paths[:output]) rescue StandardError => e raise GenerationError, "Failed to copy site assets (#{e.message})" end
Use static/ for assets and public/ for the published site
waferbaby_dimples
train
633360ead4bb58cd66ab128e8df29d12f36f63fc
diff --git a/index.php b/index.php index <HASH>..<HASH> 100644 --- a/index.php +++ b/index.php @@ -3,10 +3,10 @@ * A class that handles the detection and conversion of certain resource formats / content types into other formats. * The current formats are supported: XML, JSON, Array, Object, Serialized * - * @author Miles Johnson - http://milesj.me - * @copyright Copyright 2006-2010, Miles Johnson, Inc. - * @license http://opensource.org/licenses/mit-license.php - Licensed under The MIT License - * @link http://milesj.me/resources/script/type-converter + * @author Miles Johnson - http://milesj.me + * @copyright Copyright 2006-2011, Miles Johnson, Inc. + * @license http://opensource.org/licenses/mit-license.php - Licensed under The MIT License + * @link http://milesj.me/code/php/type-converter */ // Turn on errors diff --git a/readme.md b/readme.md index <HASH>..<HASH> 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -# Type Converter v1.1.1 # +# Type Converter v1.2 # A class that handles the detection and conversion of certain resource formats / content types into other formats. The current formats are supported: XML, JSON, Array, Object, Serialized diff --git a/type_converter/TypeConverter.php b/type_converter/TypeConverter.php index <HASH>..<HASH> 100644 --- a/type_converter/TypeConverter.php +++ b/type_converter/TypeConverter.php @@ -3,10 +3,10 @@ * A class that handles the detection and conversion of certain resource formats / content types into other formats. * The current formats are supported: XML, JSON, Array, Object, Serialized * - * @author Miles Johnson - http://milesj.me - * @copyright Copyright 2006-2010, Miles Johnson, Inc. - * @license http://opensource.org/licenses/mit-license.php - Licensed under The MIT License - * @link http://milesj.me/resources/script/type-converter + * @author Miles Johnson - http://milesj.me + * @copyright Copyright 2006-2011, Miles Johnson, Inc. + * @license http://opensource.org/licenses/mit-license.php - Licensed under The MIT License + * @link http://milesj.me/code/php/type-converter */ class TypeConverter { @@ -17,7 +17,7 @@ class TypeConverter { * @access public * @var string */ - public static $version = '1.1.1'; + public static $version = '1.2'; /** * Disregard XML attributes and only return the value.
Preparing for <I>.
milesj_type-converter
train
a7e83ec8d6a09e1c560b3375ca672c73f6c7a01e
diff --git a/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java b/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java +++ b/core/src/main/java/hudson/node_monitors/ResponseTimeMonitor.java @@ -113,7 +113,7 @@ public class ResponseTimeMonitor extends NodeMonitor { private static final class Step2 implements Callable<Step3,IOException> { private final Data cur; - private final long start = System.nanoTime(); + private final long start = System.currentTimeMillis(); public Step2(Data cur) { this.cur = cur; @@ -137,8 +137,8 @@ public class ResponseTimeMonitor extends NodeMonitor { } private Object readResolve() { - long end = System.nanoTime(); - return new Data(cur,TimeUnit2.NANOSECONDS.toMillis(end-start)); + long end = System.currentTimeMillis(); + return new Data(cur,(end-start)); } private static final long serialVersionUID = 1L;
Use System.currentTimeMillis() instead of System.nanoTime() to protect against incorrect values if times are ever compared between different JVM nodes
jenkinsci_jenkins
train
808e12ab28d8394e5a2f99d5cb14ee37a1bcc93e
diff --git a/lib/cocaine/cocaine.rb b/lib/cocaine/cocaine.rb index <HASH>..<HASH> 100644 --- a/lib/cocaine/cocaine.rb +++ b/lib/cocaine/cocaine.rb @@ -7,7 +7,8 @@ require 'celluloid' require 'celluloid/io' module Cocaine - # For dynamic method creation. [Detail]. + # [Detail] + # For dynamic method creation. class Meta def metaclass class << self
[Code Style] Documentation style.
cocaine_cocaine-framework-ruby
train
1d9d71c687a92274909802db8330317ec4509246
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -28,7 +28,7 @@ setup( author = "Olof Kindgren", author_email = "[email protected]", description = ("Edalize is a library for interfacing EDA tools, primarily for FPGA development"), - license = "", + license = "BSD-2-Clause", keywords = ["VHDL", "verilog", "EDA", "hdl", "rtl", "synthesis", "FPGA", "simulation", "Xilinx", "Altera"], url = "https://github.com/olofk/edalize", long_description=read('README.rst'),
Add license in setup.py Currently setup.py doesn't populate the "license" field, which causes `pip3 show edalize` to display this: ``` $ pip3 show edalize Name: edalize Version: <I> Summary: Edalize is a library for interfacing EDA tools, primarily for FPGA development Home-page: <URL>
olofk_edalize
train
d9f75a69585413b8c8cb177162ae15a58cde1aa2
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -258,6 +258,9 @@ function enableInlineVideo(video, hasAudio, onlyWhitelisted) { if (!hasAudio && video.autoplay) { video.play(); } + if (navigator.platform === 'MacIntel' || navigator.platform === 'Windows') { + console.warn('iphone-inline-video is not guaranteed to work in emulated environments'); + } } enableInlineVideo.isWhitelisted = isWhitelisted;
Added note about incompatibility with emulated envs (Chrome)
bfred-it_iphone-inline-video
train
1384220d9e52a407c8ab931e0dbdbdacf39591c0
diff --git a/app/Blueprint/ResourceLimit/EventListener/MainServiceBuiltListener.php b/app/Blueprint/ResourceLimit/EventListener/MainServiceBuiltListener.php index <HASH>..<HASH> 100644 --- a/app/Blueprint/ResourceLimit/EventListener/MainServiceBuiltListener.php +++ b/app/Blueprint/ResourceLimit/EventListener/MainServiceBuiltListener.php @@ -26,7 +26,11 @@ class MainServiceBuiltListener { */ public function mainserviceBuilt( MainServiceBuiltEvent $event ) { - $this->parser->parse( $event->getMainService(), $event->getEnvironmentConfiguration() ); + $mainService = $event->getMainService(); + $this->parser->parse( $mainService, $event->getEnvironmentConfiguration() ); + + foreach($mainService->getSidekicks() as $sidekick) + $this->parser->parse( $sidekick, $event->getEnvironmentConfiguration() ); } } \ No newline at end of file
apply resource limits to sidekicks
ipunkt_rancherize
train
86883090a8321a2ca4493e989df61bd45812996d
diff --git a/app/Subscribers/CommandSubscriber.php b/app/Subscribers/CommandSubscriber.php index <HASH>..<HASH> 100644 --- a/app/Subscribers/CommandSubscriber.php +++ b/app/Subscribers/CommandSubscriber.php @@ -84,7 +84,7 @@ class CommandSubscriber event(new SystemWasInstalledEvent()); - $command->success('System was installed!'); + $command->info('System was installed!'); } /** @@ -100,7 +100,7 @@ class CommandSubscriber event(new SystemWasUpdatedEvent()); - $command->success('System was updated!'); + $command->info('System was updated!'); } /** @@ -116,7 +116,7 @@ class CommandSubscriber event(new SystemWasResetEvent()); - $command->success('System was reset!'); + $command->info('System was reset!'); } /**
Use the info method, success doesn't exist
CachetHQ_Cachet
train
4bca19d547c82b77e63bab124788b988aeab5ec7
diff --git a/examples/CollectTest.php b/examples/CollectTest.php index <HASH>..<HASH> 100644 --- a/examples/CollectTest.php +++ b/examples/CollectTest.php @@ -20,7 +20,10 @@ class IntegerTest extends PHPUnit_Framework_TestCase public function testGeneratedDataCollectionOnMoreComplexDataStructures() { $this - ->forAll(Generator\vector(2, Generator\int())) + ->forAll( + Generator\vector(2, Generator\int()), + Generator\char() + ) ->hook(Listener\collectFrequencies()) ->then(function($vector) { $this->assertEquals(2, count($vector)); diff --git a/src/Eris/Listener/CollectFrequencies.php b/src/Eris/Listener/CollectFrequencies.php index <HASH>..<HASH> 100644 --- a/src/Eris/Listener/CollectFrequencies.php +++ b/src/Eris/Listener/CollectFrequencies.php @@ -20,7 +20,14 @@ class CollectFrequencies public function __construct($collectFunction = null) { if ($collectFunction === null) { - $collectFunction = function($value) { + $collectFunction = function(/*...*/) { + $generatedValues = func_get_args(); + if (count($generatedValues) === 1) { + $value = $generatedValues[0]; + } else { + $value = $generatedValues; + } + if (is_string($value) || is_integer($value)) { return $value; } else {
Default collection function only cares about the first value
giorgiosironi_eris
train
073f5575c01e151de0d7ce7633973cdaca26a224
diff --git a/server/webapp/WEB-INF/rails.new/webpack/rails-shared/plugin-endpoint-request-handler.js b/server/webapp/WEB-INF/rails.new/webpack/rails-shared/plugin-endpoint-request-handler.js index <HASH>..<HASH> 100644 --- a/server/webapp/WEB-INF/rails.new/webpack/rails-shared/plugin-endpoint-request-handler.js +++ b/server/webapp/WEB-INF/rails.new/webpack/rails-shared/plugin-endpoint-request-handler.js @@ -50,6 +50,12 @@ defineLinkHandler: function defineLinkHandler() { PluginEndpoint.define({ + "go.cd.analytics.v1.link-external": function goCdAnalyticsV1LinkExternal(message, trans) { + var params = _.clone(message.body), + url = params.url; + window.open(url, "_blank").focus(); + }, + "go.cd.analytics.v1.link-to": function goCdAnalyticsV1LinkTo(message, trans) { var params = _.clone(message.body); var linkTo = params.link_to;
Add a handler to allow analytics plugins to open external links in new windows.
gocd_gocd
train
de2047e7a985d6ed3d87bebf01deb480ab333ef5
diff --git a/mod/forum/index.php b/mod/forum/index.php index <HASH>..<HASH> 100644 --- a/mod/forum/index.php +++ b/mod/forum/index.php @@ -132,7 +132,7 @@ } if (!forum_is_forcesubscribed($forum)) { $subscribed = forum_is_subscribed($USER->id, $forum); - if ($subscribe && !$subscribed && $cansub) { + if ((has_capability('moodle/course:manageactivities', $coursecontext, $USER->id) || $forum->forcesubscribe != FORUM_DISALLOWSUBSCRIBE) && $subscribe && !$subscribed && $cansub) { forum_subscribe($USER->id, $forumid); } else if (!$subscribe && $subscribed) { forum_unsubscribe($USER->id, $forumid); diff --git a/mod/forum/lib.php b/mod/forum/lib.php index <HASH>..<HASH> 100644 --- a/mod/forum/lib.php +++ b/mod/forum/lib.php @@ -4442,31 +4442,52 @@ function forum_unsubscribe($userid, $forumid) { * Given a new post, subscribes or unsubscribes as appropriate. * Returns some text which describes what happened. */ -function forum_post_subscription($post) { +function forum_post_subscription($post, $forum) { - global $USER, $DB; - - $subscribed=forum_is_subscribed($USER->id, $post->forum); - if ((isset($post->subscribe) && $post->subscribe && $subscribed) - || (!$post->subscribe && !$subscribed)) { + global $USER; + + $action = ''; + $subscribed = forum_is_subscribed($USER->id, $forum); + + if ($forum->forcesubscribe == FORUM_FORCESUBSCRIBE) { // database ignored return ""; - } - if (!$forum = $DB->get_record("forum", array("id" => $post->forum))) { - return ""; + } elseif (($forum->forcesubscribe == FORUM_DISALLOWSUBSCRIBE) + && !has_capability('moodle/course:manageactivities', $coursecontext, $USER->id)) { + if ($subscribed) { + $action = 'unsubscribe'; // sanity check, following MDL-14558 + } else { + return ""; + } + + } else { // go with the user's choice + if (isset($post->subscribe)) { + // no change + if ((!empty($post->subscribe) && $subscribed) + || (empty($post->subscribe) && !$subscribed)) { + return ""; + + } elseif (!empty($post->subscribe) && !$subscribed) { + $action = 'subscribe'; + + } elseif (empty($post->subscribe) && $subscribed) { + $action = 'unsubscribe'; + } + } } $info = new object(); $info->name = fullname($USER); $info->forum = format_string($forum->name); - if (!empty($post->subscribe)) { - forum_subscribe($USER->id, $post->forum); - return "<p>".get_string("nowsubscribed", "forum", $info)."</p>"; + switch ($action) { + case 'subscribe': + forum_subscribe($USER->id, $post->forum); + return "<p>".get_string("nowsubscribed", "forum", $info)."</p>"; + case 'unsubscribe': + forum_unsubscribe($USER->id, $post->forum); + return "<p>".get_string("nownotsubscribed", "forum", $info)."</p>"; } - - forum_unsubscribe($USER->id, $post->forum); - return "<p>".get_string("nownotsubscribed", "forum", $info)."</p>"; } /** diff --git a/mod/forum/post.php b/mod/forum/post.php index <HASH>..<HASH> 100644 --- a/mod/forum/post.php +++ b/mod/forum/post.php @@ -502,7 +502,7 @@ } $message .= '<br />'.get_string("postupdated", "forum"); - if ($subscribemessage = forum_post_subscription($fromform)) { + if ($subscribemessage = forum_post_subscription($fromform, $forum)) { $timemessage = 4; } if ($forum->type == 'single') { @@ -533,7 +533,7 @@ $timemessage = 4; } - if ($subscribemessage = forum_post_subscription($fromform)) { + if ($subscribemessage = forum_post_subscription($fromform, $forum)) { $timemessage = 4; } @@ -609,7 +609,7 @@ $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>'; } - if ($subscribemessage = forum_post_subscription($discussion)) { + if ($subscribemessage = forum_post_subscription($discussion, $forum)) { $timemessage = 4; }
Forum/MDL-<I>: Prevent users from subscribing or getting subscribed to forums where subscriptions are not allowed. (merge)
moodle_moodle
train
68945d8d4497fdcfe86888d938ed8dd782adea84
diff --git a/override/endpoint.js b/override/endpoint.js index <HASH>..<HASH> 100644 --- a/override/endpoint.js +++ b/override/endpoint.js @@ -27,26 +27,22 @@ class Endpoint { /** * Publish Data for a specific endpoint */ - publish (data, endpoint = this.url) { - const id = `publish-${this.url}-${process.hrtime().join('').toString()}` - const update = { endpoint, data, id } + async publish (data, endpoint = this.url) { + const update = { endpoint, data } - this.api.emit('publish', update) cubic.log.verbose('Core | Sending data to publish for ' + endpoint) - return new Promise(resolve => this.api.on(id, resolve)) + return new Promise(resolve => this.api.connection.client.emit('publish', update, resolve)) } /** * Send data to be cached for endpoint on API node */ - cache (value, exp, key = this.url) { - const id = `cache-${this.url}-${process.hrtime().join('').toString()}` + async cache (value, exp, key = this.url) { const scope = this.schema.scope - const data = { key, value, exp, scope, id } + const data = { key, value, exp, scope } - this.api.emit('cache', data) cubic.log.verbose('Core | Sending data to cache for ' + key) - return new Promise(resolve => this.api.on(id, resolve)) + return new Promise(resolve => this.api.connection.client.emit('cache', data, resolve)) } /**
fix: Fix small memory leak in endpoint class
cubic-js_cubic
train
856ad6cee9fc261eda30942e638b77b450334023
diff --git a/lib/geocoder/cli.rb b/lib/geocoder/cli.rb index <HASH>..<HASH> 100644 --- a/lib/geocoder/cli.rb +++ b/lib/geocoder/cli.rb @@ -75,8 +75,18 @@ module Geocoder end if (result = Geocoder.search(query).first) - out << result.coordinates.join(',') + "\n" - out << result.address + "\n" + lines = [ + ["Latitude", :latitude], + ["Longitude", :longitude], + ["Full address", :address], + ["City", :city], + ["State/province", :state], + ["Postal code", :postal_code], + ["Country", :country], + ] + lines.each do |line| + out << (line[0] + ": ").ljust(18) + result.send(line[1]).to_s + "\n" + end exit 0 else out << "Location '#{query}' not found.\n"
Change CLI output format. Show all globally-supported attributes in a table.
alexreisner_geocoder
train
eaefb7264940d00258de90246e733299d80df36c
diff --git a/src/blockchainConnectors.js b/src/blockchainConnectors.js index <HASH>..<HASH> 100644 --- a/src/blockchainConnectors.js +++ b/src/blockchainConnectors.js @@ -1,27 +1,10 @@ -import debug from 'debug'; -import { getEtherScanFetcher } from './explorers/ethereum'; -import { getBlockcypherFetcher, getChainSoFetcher } from './explorers/bitcoin'; import { BLOCKCHAINS, CERTIFICATE_VERSIONS, CONFIG, SUB_STEPS } from './constants'; import { VerifierError } from './models'; - -const log = debug('blockchainConnectors'); - -const BitcoinExplorers = [ - (transactionId, chain) => getChainSoFetcher(transactionId, chain), - (transactionId, chain) => getBlockcypherFetcher(transactionId, chain) -]; - -const EthereumExplorers = [ - (transactionId, chain) => getEtherScanFetcher(transactionId, chain) -]; - -// for legacy (pre-v2) Blockcerts -const BlockchainExplorersWithSpentOutputInfo = [ - (transactionId, chain) => getBlockcypherFetcher(transactionId, chain) -]; +import { BitcoinExplorers, BlockchainExplorersWithSpentOutputInfo, EthereumExplorers } from './explorers'; +import PromiseProperRace from './helpers/promiseProperRace'; export function lookForTx (transactionId, chain, certificateVersion) { - var BlockchainExplorers; + let BlockchainExplorers; switch (chain) { case BLOCKCHAINS.bitcoin.code: case BLOCKCHAINS.regtest.code: @@ -51,12 +34,12 @@ export function lookForTx (transactionId, chain, certificateVersion) { let limit; if (certificateVersion === CERTIFICATE_VERSIONS.V1_1 || certificateVersion === CERTIFICATE_VERSIONS.V1_2) { limit = CONFIG.Race ? BlockchainExplorersWithSpentOutputInfo.length : CONFIG.MinimumBlockchainExplorers; - for (var i = 0; i < limit; i++) { + for (let i = 0; i < limit; i++) { promises.push(BlockchainExplorersWithSpentOutputInfo[i](transactionId, chain)); } } else { limit = CONFIG.Race ? BlockchainExplorers.length : CONFIG.MinimumBlockchainExplorers; - for (var j = 0; j < limit; j++) { + for (let j = 0; j < limit; j++) { promises.push(BlockchainExplorers[j](transactionId, chain)); } } @@ -76,9 +59,9 @@ export function lookForTx (transactionId, chain, certificateVersion) { // Note that APIs returning results where the number of confirmations is less than `MininumConfirmations` are // filtered out, but if there are at least `MinimumBlockchainExplorers` reporting that the number of confirmations // are above the `MininumConfirmations` threshold, then we can proceed with verification. - var firstResponse = winners[0]; - for (var i = 1; i < winners.length; i++) { - var thisResponse = winners[i]; + const firstResponse = winners[0]; + for (let i = 1; i < winners.length; i++) { + const thisResponse = winners[i]; if (firstResponse.issuingAddress !== thisResponse.issuingAddress) { throw new VerifierError(SUB_STEPS.fetchRemoteHash, `Issuing addresses returned by the blockchain APIs were different`); } @@ -92,28 +75,3 @@ export function lookForTx (transactionId, chain, certificateVersion) { }); }); } - -var PromiseProperRace = function (promises, count, results = []) { - // Source: https://www.jcore.com/2016/12/18/promise-me-you-wont-use-promise-race/ - promises = Array.from(promises); - if (promises.length < count) { - return Promise.reject(new VerifierError(SUB_STEPS.fetchRemoteHash, `Could not confirm the transaction`)); - } - - let indexPromises = promises.map((p, index) => p.then(() => index).catch((err) => { - log(err); - throw index; - })); - - return Promise.race(indexPromises).then(index => { - let p = promises.splice(index, 1)[0]; - p.then(e => results.push(e)); - if (count === 1) { - return results; - } - return PromiseProperRace(promises, count - 1, results); - }).catch(index => { - promises.splice(index, 1); - return PromiseProperRace(promises, count, results); - }); -};
refactor(connector): connector solely doing connector work
blockchain-certificates_cert-verifier-js
train