hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
2c7c62c6d045746eb71d4e5087166a5fe3d8f4af
|
diff --git a/nat/paramSample.py b/nat/paramSample.py
index <HASH>..<HASH> 100644
--- a/nat/paramSample.py
+++ b/nat/paramSample.py
@@ -10,8 +10,10 @@ from warnings import warn
from .modelingParameter import NumericalVariable, ParamDescTrace, ValuesSimple, \
getParameterTypeIDFromName, getParameterTypeNameFromID
+from .annotationSearch import ParameterGetter
from .zoteroWrap import ZoteroWrap
from .ageResolver import AgeResolver
+from quantities import Quantity
class ParamSample:
@@ -39,18 +41,55 @@ class ParamSample:
self.zotWrap.loadCachedDB(libraryId, libraryType, apiKey)
- def rescaleUnit(self, unit):
+
+ def rescaleUnit(self, unit, rescaleStereo=True):
+
+ def rescale2DStereo(paramID, thicknessValue, thicknessUnit, desiredUnit):
+ density = paramGetter.getParam(paramID)
+ thickness = Quantity(thicknessValue, thicknessUnit)
+ return (density/thickness).rescale(desiredUnit)
+
+
+ paramGetter = ParameterGetter(pathDB=self.searcher.pathDB)
for param, annot, (index, row) in zip(self.sampleDF["obj_parameter"],
self.sampleDF["obj_annotation"],
self.sampleDF.iterrows()):
- param = param.rescale(unit)
- if param.unit != unit:
+
+ if param.unit == unit:
+ continue
+
+ try:
+ param = param.rescale(unit)
+ except ValueError:
+
+ if rescaleStereo:
+ thicknessInstanceId = [param.instanceId for param in annot.experimentProperties
+ if getParameterTypeNameFromID(param.paramTypeId) == "slice_thickness"]
+
+ if len(thicknessInstanceId) == 1:
+ thicknessParameter = paramGetter.getParam(thicknessInstanceId[0])
+ if len(thicknessParameter.values) == 1:
+ param = rescale2DStereo(param.id, thicknessValue=thicknessParameter.values[0],
+ thicknessUnit=thicknessParameter.unit,
+ desiredUnit=unit)
+ self.sampleDF.loc[index, "obj_parameter"] = param
+ self.sampleDF.loc[index, "Values"] = param.valuesText()
+ self.sampleDF.loc[index, "Unit"] = param.unit
+ continue
+
warn("The annotation with the parameter ID " + row["Parameter instance ID"] +
" cannot be rescaled from unit " +
str(param.unit) + " to unit " + str(unit) + ". Dropping this record.")
del row
continue
+ if Quantity(1, param.unit) != Quantity(1, unit):
+ warn("The annotation with the parameter ID " + row["Parameter instance ID"] +
+ " cannot be rescaled from unit " +
+ str(param.unit) + " to unit " + str(unit) + ". Dropping this record.")
+ del row
+ continue
+
self.sampleDF.loc[index, "obj_parameter"] = param
self.sampleDF.loc[index, "Values"] = param.valuesText()
self.sampleDF.loc[index, "Unit"] = param.unit
@@ -119,27 +158,49 @@ class ParamSample:
ageCategories = []
numericalAges = []
for noRow, row in self.sampleDF.iterrows():
- tags = row["AgeCategories"]
- if len(tags) > 1 :
+
+ # First check if an experimental property with age as been attributed to the record
+ ageExpProp = [expProp.instanceId for expProp in row["obj_annotation"].experimentProperties if expProp.paramTypeId == 'BBP-002001']
+ if len(ageExpProp) > 1 :
warn("The annotation with the parameter ID " + row["Parameter instance ID"] +
- " is associated with more than one age categories (" +
- str([tag.name for tag in tags])
- + "). The age cannot be automatically attributed unambiguously. " +
+ " is associated with more than one species age experimental properties." +
+ +" The age cannot be automatically attributed unambiguously. " +
"Skipping this record.")
del row
- continue
+ continue
+
+ if len(ageExpProp) == 1 :
+ getter = ParameterGetter(pathDB=self.searcher.pathDB)
+
+ ageParam = getter.getParam(ageExpProp[0])
- if len(tags) == 0:
ageCategoryIds.append(None)
- ageCategories.append(None)
- numericalAges.append(None)
- continue
-
- ageCategoryIds.append(tags[0].id)
- ageCategories.append(tags[0].name)
- age = AgeResolver.resolve_fromIDs(row["SpeciesId"], tags[0].id, unit=self.ageUnit,
- typeValue=self.ageTypeValue)
- numericalAges.append(age)
+ ageCategories.append(None)
+ numericalAges.append(Quantity(ageParam.means[0], ageParam.unit).rescale(self.ageUnit))
+
+ # No experimental property attributed. Check to use a age category if one has been attributed.
+ else:
+ tags = row["AgeCategories"]
+ if len(tags) > 1 :
+ warn("The annotation with the parameter ID " + row["Parameter instance ID"] +
+ " is associated with more than one age categories (" +
+ str([tag.name for tag in tags])
+ + "). The age cannot be automatically attributed unambiguously. " +
+ "Skipping this record.")
+ del row
+ continue
+
+ if len(tags) == 0:
+ ageCategoryIds.append(None)
+ ageCategories.append(None)
+ numericalAges.append(None)
+ continue
+
+ ageCategoryIds.append(tags[0].id)
+ ageCategories.append(tags[0].name)
+ age = AgeResolver.resolve_fromIDs(row["SpeciesId"], tags[0].id, unit=self.ageUnit,
+ typeValue=self.ageTypeValue)
+ numericalAges.append(age)
self.sampleDF["AgeCategoryId"] = ageCategoryIds
self.sampleDF["AgeCategory"] = ageCategories
|
Adding support for rescaling stereology from 2D to 3D using slice thickness. Adding support for processing age form experimental properties.
|
BlueBrain_nat
|
train
|
778d14fb16dec59ac15b60c641e7ce3e53cb8191
|
diff --git a/lib/doorkeeper.rb b/lib/doorkeeper.rb
index <HASH>..<HASH> 100644
--- a/lib/doorkeeper.rb
+++ b/lib/doorkeeper.rb
@@ -1,46 +1,46 @@
-require "doorkeeper/version"
-require "doorkeeper/engine"
-require "doorkeeper/config"
-require "doorkeeper/doorkeeper_for"
+require 'doorkeeper/version'
+require 'doorkeeper/engine'
+require 'doorkeeper/config'
+require 'doorkeeper/doorkeeper_for'
require 'doorkeeper/errors'
require 'doorkeeper/server'
require 'doorkeeper/request'
-require "doorkeeper/validations"
-
-require "doorkeeper/oauth/authorization/code"
-require "doorkeeper/oauth/authorization/token"
-require "doorkeeper/oauth/authorization/uri_builder"
-require "doorkeeper/oauth/helpers/scope_checker"
-require "doorkeeper/oauth/helpers/uri_checker"
-require "doorkeeper/oauth/helpers/unique_token"
-require "doorkeeper/oauth/helpers/find_or_create_access_token"
-
-require "doorkeeper/oauth/scopes"
-require "doorkeeper/oauth/error"
-require "doorkeeper/oauth/code_response"
-require "doorkeeper/oauth/token_response"
-require "doorkeeper/oauth/error_response"
-require "doorkeeper/oauth/pre_authorization"
-require "doorkeeper/oauth/authorization_code_request"
-require "doorkeeper/oauth/refresh_token_request"
-require "doorkeeper/oauth/password_access_token_request"
-require "doorkeeper/oauth/client_credentials_request"
-require "doorkeeper/oauth/code_request"
-require "doorkeeper/oauth/token_request"
-require "doorkeeper/oauth/client"
-require "doorkeeper/oauth/token"
-require "doorkeeper/oauth/invalid_token_response"
+require 'doorkeeper/validations'
+
+require 'doorkeeper/oauth/authorization/code'
+require 'doorkeeper/oauth/authorization/token'
+require 'doorkeeper/oauth/authorization/uri_builder'
+require 'doorkeeper/oauth/helpers/scope_checker'
+require 'doorkeeper/oauth/helpers/uri_checker'
+require 'doorkeeper/oauth/helpers/unique_token'
+require 'doorkeeper/oauth/helpers/find_or_create_access_token'
+
+require 'doorkeeper/oauth/scopes'
+require 'doorkeeper/oauth/error'
+require 'doorkeeper/oauth/code_response'
+require 'doorkeeper/oauth/token_response'
+require 'doorkeeper/oauth/error_response'
+require 'doorkeeper/oauth/pre_authorization'
+require 'doorkeeper/oauth/authorization_code_request'
+require 'doorkeeper/oauth/refresh_token_request'
+require 'doorkeeper/oauth/password_access_token_request'
+require 'doorkeeper/oauth/client_credentials_request'
+require 'doorkeeper/oauth/code_request'
+require 'doorkeeper/oauth/token_request'
+require 'doorkeeper/oauth/client'
+require 'doorkeeper/oauth/token'
+require 'doorkeeper/oauth/invalid_token_response'
require 'doorkeeper/models/scopes'
require 'doorkeeper/models/expirable'
require 'doorkeeper/models/revocable'
require 'doorkeeper/models/accessible'
-require "doorkeeper/helpers/filter"
-require "doorkeeper/helpers/controller"
+require 'doorkeeper/helpers/filter'
+require 'doorkeeper/helpers/controller'
-require "doorkeeper/rails/routes"
+require 'doorkeeper/rails/routes'
module Doorkeeper
def self.configured?
|
Undo unwanted rebase effect.
|
doorkeeper-gem_doorkeeper
|
train
|
08be2fbdfe2b14bba768bbb4ebab950c512cad96
|
diff --git a/lxd/db/network_forwards.go b/lxd/db/network_forwards.go
index <HASH>..<HASH> 100644
--- a/lxd/db/network_forwards.go
+++ b/lxd/db/network_forwards.go
@@ -173,7 +173,7 @@ func (c *Cluster) DeleteNetworkForward(networkID int64, forwardID int64) error {
// GetNetworkForward returns the Network Forward ID and info for the given network ID and listen address.
// If memberSpecific is true, then the search is restricted to forwards that belong to this member or belong to
// all members.
-func (c *Cluster) GetNetworkForward(networkID int64, memberSpecific bool, listenAddress string) (int64, *api.NetworkForward, error) {
+func (c *Cluster) GetNetworkForward(ctx context.Context, networkID int64, memberSpecific bool, listenAddress string) (int64, *api.NetworkForward, error) {
var q *strings.Builder = &strings.Builder{}
args := []any{networkID, listenAddress}
@@ -200,7 +200,7 @@ func (c *Cluster) GetNetworkForward(networkID int64, memberSpecific bool, listen
var forward api.NetworkForward
var portsJSON string
- err = c.Transaction(context.TODO(), func(ctx context.Context, tx *ClusterTx) error {
+ err = c.Transaction(ctx, func(ctx context.Context, tx *ClusterTx) error {
var rowCount int
err = tx.tx.QueryRow(q.String(), args...).Scan(&forwardID, &forward.ListenAddress, &forward.Description, &forward.Location, &portsJSON, &rowCount)
@@ -406,7 +406,7 @@ func (c *ClusterTx) GetProjectNetworkForwardListenAddressesOnMember() (map[strin
// GetNetworkForwards returns map of Network Forwards for the given network ID keyed on Forward ID.
// If memberSpecific is true, then the search is restricted to forwards that belong to this member or belong to
// all members.
-func (c *Cluster) GetNetworkForwards(networkID int64, memberSpecific bool) (map[int64]*api.NetworkForward, error) {
+func (c *Cluster) GetNetworkForwards(ctx context.Context, networkID int64, memberSpecific bool) (map[int64]*api.NetworkForward, error) {
var q *strings.Builder = &strings.Builder{}
args := []any{networkID}
@@ -430,7 +430,7 @@ func (c *Cluster) GetNetworkForwards(networkID int64, memberSpecific bool) (map[
var err error
forwards := make(map[int64]*api.NetworkForward)
- err = c.Transaction(context.TODO(), func(ctx context.Context, tx *ClusterTx) error {
+ err = c.Transaction(ctx, func(ctx context.Context, tx *ClusterTx) error {
err = tx.QueryScan(q.String(), func(scan func(dest ...any) error) error {
var forwardID int64 = int64(-1)
var portsJSON string
|
lxd/db/network/forwards: Adds context arg to GetNetworkForwards and GetNetworkForward
|
lxc_lxd
|
train
|
4694aef3336fb3cb780798dc272203fa35797fe9
|
diff --git a/lib/aker/ldap/authority.rb b/lib/aker/ldap/authority.rb
index <HASH>..<HASH> 100644
--- a/lib/aker/ldap/authority.rb
+++ b/lib/aker/ldap/authority.rb
@@ -336,6 +336,9 @@ module Aker::Ldap
base = self.find_user(user.username)
return user unless base
+ user.extend UserExt
+ user.ldap_attributes = base.ldap_attributes
+
user.merge!(base)
end
diff --git a/spec/aker/ldap/authority_spec.rb b/spec/aker/ldap/authority_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/aker/ldap/authority_spec.rb
+++ b/spec/aker/ldap/authority_spec.rb
@@ -449,6 +449,14 @@ module Aker::Ldap
it "has a business phone" do
amplified.business_phone.should == "+1 312 555 3229"
end
+
+ it 'mixes in UserExt' do
+ amplified.should respond_to(:ldap_attributes)
+ end
+
+ it 'has the original ldap attributes' do
+ amplified.ldap_attributes[:givenname].should == ['Warren']
+ end
end
end
end
|
Add ldap_attributes when amplifying. #<I>.
|
NUBIC_aker
|
train
|
98e42bc37e866508a671b569d905852c2e6ae17e
|
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -436,6 +436,17 @@ module ActiveRecord
# The chain is built by recursively calling #chain on the source reflection and the through
# reflection. The base case for the recursion is a normal association, which just returns
# [self] as its #chain.
+ #
+ # class Post < ActiveRecord::Base
+ # has_many :taggings
+ # has_many :tags, through: :taggings
+ # end
+ #
+ # tags_reflection = Post.reflect_on_association(:tags)
+ # tags_reflection.chain
+ # #=> [<ActiveRecord::Reflection::ThroughReflection: @macro=:has_many, @name=:tags, @options={:through=>:taggings}, @active_record=Post>,
+ # <ActiveRecord::Reflection::AssociationReflection: @macro=:has_many, @name=:taggings, @options={}, @active_record=Post>]
+ #
def chain
@chain ||= begin
chain = source_reflection.chain + through_reflection.chain
@@ -506,9 +517,16 @@ module ActiveRecord
source_reflection.options[:primary_key] || primary_key(klass || self.klass)
end
- # Gets an array of possible <tt>:through</tt> source reflection names:
+ # Gets an array of possible <tt>:through</tt> source reflection names in both singular and plural form.
#
- # [:singularized, :pluralized]
+ # class Post < ActiveRecord::Base
+ # has_many :taggings
+ # has_many :tags, through: :taggings
+ # end
+ #
+ # tags_reflection = Post.reflect_on_association(:tags)
+ # tags_reflection.source_reflection_names
+ # #=> [:tag, :tags]
#
def source_reflection_names
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
|
expanded rdoc for chain and reflection_names
|
rails_rails
|
train
|
d4721249703358cc7ca38903ef6383537c87c537
|
diff --git a/go/stellar/stellarsvc/frontend_test.go b/go/stellar/stellarsvc/frontend_test.go
index <HASH>..<HASH> 100644
--- a/go/stellar/stellarsvc/frontend_test.go
+++ b/go/stellar/stellarsvc/frontend_test.go
@@ -506,12 +506,10 @@ func TestAcceptDisclaimer(t *testing.T) {
require.NoError(t, err)
require.Equal(t, false, userSettings.AcceptedDisclaimer)
- if false { // CORE-9108 have to wait for server PR to land for this
- t.Logf("can't create wallet before disclaimer")
- _, err = stellar.CreateWallet(context.Background(), tcs[0].G)
- require.Error(t, err)
- require.True(t, libkb.IsAppStatusErrorCode(err, keybase1.StatusCode_SCStellarNeedDisclaimer))
- }
+ t.Logf("can't create wallet before disclaimer")
+ _, err = stellar.CreateWallet(context.Background(), tcs[0].G)
+ require.Error(t, err)
+ require.True(t, libkb.IsAppStatusErrorCode(err, keybase1.StatusCode_SCStellarNeedDisclaimer))
userSettings, err = tcs[0].Srv.GetWalletSettingsLocal(context.Background(), 0)
require.NoError(t, err)
diff --git a/go/systests/stellar_test.go b/go/systests/stellar_test.go
index <HASH>..<HASH> 100644
--- a/go/systests/stellar_test.go
+++ b/go/systests/stellar_test.go
@@ -87,7 +87,6 @@ func TestStellarRelayAutoClaims(t *testing.T) {
// Test took 29s on a dev server 2018-06-07
func TestStellarRelayAutoClaimsWithPUK(t *testing.T) {
- t.Skip("CORE-9018 blockade required for relays to be sent")
if disable {
t.Skip(disableMsg)
}
|
more test (#<I>)
|
keybase_client
|
train
|
6e58eae3016187f7732cbade4066952f0c8b520a
|
diff --git a/pyghmi/ipmi/command.py b/pyghmi/ipmi/command.py
index <HASH>..<HASH> 100644
--- a/pyghmi/ipmi/command.py
+++ b/pyghmi/ipmi/command.py
@@ -87,6 +87,9 @@ class Command(object):
onlogon=self.logged,
port=port,
kg=kg)
+ # induce one iteration of the loop, now that we would be
+ # prepared for it in theory
+ session.Session.wait_for_rsp(0)
else:
self.ipmi_session = session.Session(bmc=bmc,
userid=userid,
diff --git a/pyghmi/ipmi/console.py b/pyghmi/ipmi/console.py
index <HASH>..<HASH> 100644
--- a/pyghmi/ipmi/console.py
+++ b/pyghmi/ipmi/console.py
@@ -61,6 +61,9 @@ class Console(object):
port=port,
kg=kg,
onlogon=self._got_session)
+ # induce one iteration of the loop, now that we would be
+ # prepared for it in theory
+ session.Session.wait_for_rsp(0)
def _got_session(self, response):
"""Private function to navigate SOL payload activation
diff --git a/pyghmi/ipmi/private/session.py b/pyghmi/ipmi/private/session.py
index <HASH>..<HASH> 100644
--- a/pyghmi/ipmi/private/session.py
+++ b/pyghmi/ipmi/private/session.py
@@ -318,9 +318,6 @@ class Session(object):
self.logonwaiters.append(onlogon)
else:
self.iterwaiters.append(onlogon)
- # Induce an immediate iteration of the event loop
- # so that these handlers get the information they are hoping for
- Session.wait_for_rsp(0)
return
self.maxtimeout = 3 # be aggressive about giving up on initial packet
self.incommand = False
|
Move previous fix out to command and console
console at least needed the assignment to the session to occur
prior to its callback working. Move the responsibility of the
mandatory loop iteration up a layer so that pyghmi won't break,
but calling code won't have to worry about this either.
Change-Id: I<I>acf<I>bb<I>e<I>e<I>bb3f<I>
|
openstack_pyghmi
|
train
|
b0211bf92ecfb474f1539fa34c15ae76dada6142
|
diff --git a/src/oidcendpoint/oidc/registration.py b/src/oidcendpoint/oidc/registration.py
index <HASH>..<HASH> 100755
--- a/src/oidcendpoint/oidc/registration.py
+++ b/src/oidcendpoint/oidc/registration.py
@@ -5,9 +5,10 @@ import logging
import time
from random import random
from urllib.parse import parse_qs
-from urllib.parse import splitquery
from urllib.parse import urlencode
from urllib.parse import urlparse
+from urllib.parse import urlsplit
+from urllib.parse import urlunsplit
from cryptojwt.jws.utils import alg2keytype
from oidcmsg.exception import MessageException
@@ -90,6 +91,21 @@ def secret(seed, sid):
return csum.hexdigest()
+def split_uri(uri):
+ p = urlsplit(uri)
+
+ if p.fragment:
+ p = p._replace(fragment='')
+
+ if p.query:
+ o = p._replace(query='')
+ base = urlunsplit(o)
+ return base, parse_qs(p.query)
+ else:
+ base = urlunsplit(p)
+ return base, ''
+
+
def comb_uri(args):
for param in ["redirect_uris", "post_logout_redirect_uris"]:
if param not in args:
@@ -160,11 +176,7 @@ class Registration(Endpoint):
"fragment",
)
return err
- base, query = splitquery(uri)
- if query:
- plruri.append((base, parse_qs(query)))
- else:
- plruri.append((base, query))
+ plruri.append(split_uri(uri))
_cinfo["post_logout_redirect_uris"] = plruri
if "redirect_uris" in request:
@@ -275,7 +287,7 @@ class Registration(Endpoint):
if _custom: # Can not verify a custom scheme
verified_redirect_uris.append((uri, {}))
else:
- base, query = splitquery(uri)
+ base, query = split_uri(uri)
if query:
verified_redirect_uris.append((base, parse_qs(query)))
else:
|
Don't use splitquery - deprecated.
|
IdentityPython_oidcendpoint
|
train
|
9ce7f64423f28ce7510dcba324c0ca7e1bc3ae5c
|
diff --git a/lib/jsaws.js b/lib/jsaws.js
index <HASH>..<HASH> 100644
--- a/lib/jsaws.js
+++ b/lib/jsaws.js
@@ -699,6 +699,11 @@ jsaws.getLatest = function(awsCollection, tagName) {
// Export the jsaws library object
sg.exportify(module, jsaws);
+exports.lib2 = {};
+_.each(require('../lib2/ec2/ec2.js'), function(value, key) {
+ exports.lib2[key] = value;
+});
+
// Export our AWS object wrappers
sg.exportify(module, require('./ec2/ec2.js'));
sg.exportify(module, require('./s3/s3.js'));
diff --git a/lib2/ec2/ec2.js b/lib2/ec2/ec2.js
index <HASH>..<HASH> 100644
--- a/lib2/ec2/ec2.js
+++ b/lib2/ec2/ec2.js
@@ -164,7 +164,7 @@ ec2.getSnapshots = function(argv_, context, callback) {
} else {
_.extend(params, {OwnerIds:_.values(accounts)});
}
-console.error(params);
+
return awsServiceLib.describe(params, context, function(err, snapshots) {
if (err) { return sg.die(err, callback, 'getSnapshots.describe'); }
|
Just causing them to be afraid.
|
briancsparks_js-aws
|
train
|
940d868b53f650d3f20f53304243158faf725186
|
diff --git a/runspade.py b/runspade.py
index <HASH>..<HASH> 100755
--- a/runspade.py
+++ b/runspade.py
@@ -4,14 +4,12 @@ import os, signal
import sys
import time
import thread
-#import ConfigParser
from getopt import getopt
from spade import spade_backend
from spade import SpadeConfigParser
from spade import colors
import xmppd
-#import spade
VERSION = "1.9.7"
@@ -38,9 +36,9 @@ def main():
try:
import psyco
- print "Psyco optimizing compiler found. Using psyco.full()."
+ print "Using Psyco optimizing compiler."
#psyco.log(logfile='/tmp/psyco.log')
- #######psyco.full()
+ psyco.full()
#psyco.profile()
except ImportError: print "W: Psyco optimizing compiler not found."
@@ -72,40 +70,19 @@ def main():
except:
pass
- configfile = SpadeConfigParser.ConfigParser(configfilename)
-
- #workpath = "/usr/share/spade/jabberd/" #configfile.get("jabber","workpath")
- #if not os.path.exists(workpath):
- # workpath = "./usr/share/spade/jabberd/"
+ sys.stdout.write("Launching SPADE")
- #if os.name == "posix":
- # jabberpath = workpath + "jabberd"
- # spool = os.environ['HOME'] + "/.spade"
- # if not os.path.exists(spool):
- # os.mkdir(spool)
- #else:
- # jabberpath = workpath + "jabberd.exe"
- # spool = workpath + "spool"
-
- #if os.path.exists(jabberpath): # and os.path.exists(jabberxml):
- #print "JABBERPATH: " + jabberpath
- #print "JABBERXML: "+ jabberxml
- ####jabberpid = os.spawnl(os.P_NOWAIT, jabberpath, jabberpath, '-c', str(jabberxml), '-H', str(workpath), '-s', str(spool))
- #print "PID: " + str(jabberpid)
- # pass
+ configfile = SpadeConfigParser.ConfigParser(configfilename)
- sys.stdout.write("Launching spade")
+ sys.stdout.write(".")
s = xmppd.server.Server(cfgfile=jabberxml, debug = dbg)
+
sys.stdout.write(".")
+
thread.start_new_thread(s.run,tuple())
try:
- #print "Esperando...."
- #time.sleep(2)
- #print "Lanzando..."
-
-
sys.stdout.write(".")
platform = spade_backend.SpadeBackend(configfilename)
sys.stdout.write(".")
@@ -122,11 +99,11 @@ def main():
s.shutdown("Jabber server terminated...")
print colors.color_green + " [done]" + colors.color_none
+
+
while True:
try:
time.sleep(1)
- #except KeyboardInterrupt:
- # pass
except KeyboardInterrupt:
del platform
s.shutdown("Jabber server terminated...")
@@ -137,10 +114,5 @@ def main():
#s.shutdown("Jabber server terminated...")
#sys.exit(0)
- #if os.name == "posix":
- # ######os.kill(jabberpid, signal.SIGTERM)
- # time.sleep(2)
-
-
if __name__ == '__main__': main()
diff --git a/spade/spade_backend.py b/spade/spade_backend.py
index <HASH>..<HASH> 100644
--- a/spade/spade_backend.py
+++ b/spade/spade_backend.py
@@ -42,20 +42,10 @@ class SpadeBackend:
return agent
def __init__(self, configfilename="/etc/spade/spade.xml"):
- #print "SPADE started."
- #self.configfile = ConfigParser.ConfigParser()
self.configfile = SpadeConfigParser.ConfigParser(configfilename)
- #try:
- # cffile = open(configfilename,'r')
- #except IOError:
- # print "SPADE requires configuration file, please supply spade.xml"
- # sys.exit(1)
-
- #self.configfile.readfp(cffile)
- #cffile.close()
-
def start(self):
+ #TODO: this should be configurable
self.runAgent(self.configfile, "acc", Platform.SpadePlatform)
self.runAgent(self.configfile, "ams", AMS.AMS)
self.runAgent(self.configfile, "df", DF.DF)
|
xmpp dict bug solved
|
javipalanca_spade
|
train
|
66fba70af7408beec02ed8123a7f6309fe940a43
|
diff --git a/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/MappingManagerPanel.java b/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/MappingManagerPanel.java
index <HASH>..<HASH> 100644
--- a/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/MappingManagerPanel.java
+++ b/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/MappingManagerPanel.java
@@ -748,6 +748,11 @@ public class MappingManagerPanel extends JPanel implements MappingManagerPrefere
private void cmdAddMappingActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addMappingButtonActionPerformed
if (selectedSource != null) {
addMapping();
+
+ // Make sure the user can see the new node.
+ MappingTreeModel model = (MappingTreeModel) mappingsTree.getModel();
+ MappingNode newNode = model.getLastMappingNode();
+ mappingsTree.scrollPathToVisible(new TreePath(newNode.getPath()));
} else {
JOptionPane.showMessageDialog(this, "Select the data source first!", "Warning", JOptionPane.WARNING_MESSAGE);
return;
diff --git a/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/treemodel/MappingTreeModel.java b/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/treemodel/MappingTreeModel.java
index <HASH>..<HASH> 100644
--- a/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/treemodel/MappingTreeModel.java
+++ b/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/treemodel/MappingTreeModel.java
@@ -55,6 +55,7 @@ public class MappingTreeModel extends DefaultTreeModel implements
private MappingController controller = null;
private DefaultMutableTreeNode root = null;
// private DatasourcesController dsc = null; TODO Remove this ds?
+ private MappingNode mappingnode = null;
private URI currentDataSourceUri;
private final List<TreeModelFilter<OBDAMappingAxiom>> ListFilters = new ArrayList<TreeModelFilter<OBDAMappingAxiom>>();
protected OBDAModel apic = null;
@@ -155,9 +156,7 @@ public class MappingTreeModel extends DefaultTreeModel implements
RDBMSMappingAxiomImpl mapping = (RDBMSMappingAxiomImpl) controller.getMapping(srcuri, mapping_id);
MappingNode mappingNode = getMappingNodeFromMapping(mapping);
- insertNodeInto(mappingNode, root, root
- .getChildCount());
- nodeStructureChanged(root);
+ insertNodeInto(mappingNode, root, root.getChildCount());
} catch (Exception e) {
e.printStackTrace(System.err);
}
@@ -262,7 +261,7 @@ public class MappingTreeModel extends DefaultTreeModel implements
* @return
*/
private MappingNode getMappingNodeFromMapping(OBDAMappingAxiom mapping) {
- MappingNode mappingnode = new MappingNode(mapping.getId());
+ mappingnode = new MappingNode(mapping.getId());
Query srcquery = mapping.getSourceQuery();
CQIE tgtquery = (CQIEImpl) mapping.getTargetQuery();
MappingBodyNode body = null;
@@ -284,6 +283,10 @@ public class MappingTreeModel extends DefaultTreeModel implements
return mappingnode;
}
+
+ public MappingNode getLastMappingNode() {
+ return mappingnode;
+ }
/**
* Synchronizes an array of mapping axioms to the tree node structure
|
The problem the tree got reset is because of nodeStructureChange() method. It triggers the update of the whole tree structure and redraws the tree display. So instead of doing this, we just look for the new node and display it without triggering any massive update event.
BUG=<I>
Ticket URL=<URL>
|
ontop_ontop
|
train
|
6ba1325874871b69a963193864dbb6b7cdb5e720
|
diff --git a/hdl_toolkit/synthetisator/interfaceLevel/unit.py b/hdl_toolkit/synthetisator/interfaceLevel/unit.py
index <HASH>..<HASH> 100644
--- a/hdl_toolkit/synthetisator/interfaceLevel/unit.py
+++ b/hdl_toolkit/synthetisator/interfaceLevel/unit.py
@@ -73,6 +73,9 @@ class Unit(UnitBase, Buildable, PropDeclrCollector, UnitImplHelpers):
yield from self._synthetiseContext(externInterf, self._cntx)
self._checkArchCompInstances()
+
+ def _wasSynthetised(self):
+ return hasattr(self, "_cntx")
def _synthetiseContext(self, externInterf, cntx):
# synthetize signal level context
diff --git a/hdl_toolkit/synthetisator/interfaceLevel/unitFromHdl.py b/hdl_toolkit/synthetisator/interfaceLevel/unitFromHdl.py
index <HASH>..<HASH> 100644
--- a/hdl_toolkit/synthetisator/interfaceLevel/unitFromHdl.py
+++ b/hdl_toolkit/synthetisator/interfaceLevel/unitFromHdl.py
@@ -208,5 +208,8 @@ class UnitFromHdl(Unit):
return [self]
+ def _wasSynthetised(self):
+ return True
+
def __str__(self):
return "\n".join(['--%s' % (repr(s)) for s in self._hdlSources])
diff --git a/hdl_toolkit/synthetisator/shortcuts.py b/hdl_toolkit/synthetisator/shortcuts.py
index <HASH>..<HASH> 100644
--- a/hdl_toolkit/synthetisator/shortcuts.py
+++ b/hdl_toolkit/synthetisator/shortcuts.py
@@ -20,6 +20,8 @@ def toRtl(unitOrCls, name=None, serializer=VhdlSerializer):
else:
u = unitOrCls
+ assert not u._wasSynthetised()
+
u._loadDeclarations()
if name is not None:
u._name = name
|
new: _wasSynthetised
|
Nic30_hwt
|
train
|
b241c50957c6f651d293600a74d06ae61aa69a72
|
diff --git a/source/php/BulkImport.php b/source/php/BulkImport.php
index <HASH>..<HASH> 100644
--- a/source/php/BulkImport.php
+++ b/source/php/BulkImport.php
@@ -296,7 +296,13 @@ class BulkImport
foreach ($userNames as $userName) {
if (!empty($userName) && !in_array($userName, $this->getLocalAccounts())) {
- $userId = wp_create_user($userName, wp_generate_password(), $this->createFakeEmail($userName));
+
+ //Do a sanity check
+ if (username_exists($userName)) {
+ $userId = wp_create_user($userName, wp_generate_password(), $this->createFakeEmail($userName));
+ } else {
+ $userId = null;
+ }
if (is_numeric($userId)) {
$this->setUserRole($userId);
|
Check that the username exists before creating it.
|
helsingborg-stad_active-directory-api-wp-integration
|
train
|
d892ca944d92b0de2e821d4a4421cce84bc5b514
|
diff --git a/lib/AdapterLdap.php b/lib/AdapterLdap.php
index <HASH>..<HASH> 100644
--- a/lib/AdapterLdap.php
+++ b/lib/AdapterLdap.php
@@ -52,8 +52,13 @@ class AdapterLdap extends Adapter
public const TYPE_BOOL = 'bool';
+ public const TYPE_ARRAY = 'array';
+
+ //TODO: remove in future major release and replace with self::TYPE_ARRAY
public const TYPE_MAP = 'map';
+ public const TYPE_DICTIONARY = 'dictionary';
+
public const INTERNAL_ATTR_NAME = 'internalAttrName';
public const TYPE = 'type';
@@ -272,7 +277,7 @@ class AdapterLdap extends Adapter
foreach (array_keys($attrTypeMap) as $attrName) {
$attributesValues[$attrTypeMap[$attrName][self::INTERNAL_ATTR_NAME]] =
- $this->setAttrValue($attrTypeMap, $perunAttrs[0], $attrName);
+ $this->resolveAttrValue($attrTypeMap, $perunAttrs[0], $attrName);
}
return $attributesValues;
@@ -330,7 +335,7 @@ class AdapterLdap extends Adapter
foreach (array_keys($attrTypeMap) as $attrName) {
$attributesValues[$attrTypeMap[$attrName][self::INTERNAL_ATTR_NAME]] =
- $this->setAttrValue($attrTypeMap, $perunAttrs[0], $attrName);
+ $this->resolveAttrValue($attrTypeMap, $perunAttrs[0], $attrName);
}
return $attributesValues;
@@ -365,7 +370,7 @@ class AdapterLdap extends Adapter
foreach (array_keys($attrTypeMap) as $attrName) {
$attributesValues[$attrTypeMap[$attrName][self::INTERNAL_ATTR_NAME]] =
- $this->setAttrValue($attrTypeMap, $perunAttrs[0], $attrName);
+ $this->resolveAttrValue($attrTypeMap, $perunAttrs[0], $attrName);
}
return $attributesValues;
@@ -533,20 +538,34 @@ class AdapterLdap extends Adapter
return $facilityCapabilities['capabilities'];
}
- private function setAttrValue($attrsNameTypeMap, $attrsFromLdap, $attr)
+ private function resolveAttrValue($attrsNameTypeMap, $attrsFromLdap, $attr)
{
- if (! array_key_exists($attr, $attrsFromLdap) && $attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_BOOL) {
- return false;
- } elseif (! array_key_exists(
- $attr,
- $attrsFromLdap
- ) && $attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_MAP) {
- return [];
- } elseif (array_key_exists($attr, $attrsFromLdap) && $attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_MAP) {
- return $attrsFromLdap[$attr];
- } elseif (array_key_exists($attr, $attrsFromLdap)) {
+ if (! array_key_exists($attr, $attrsFromLdap)) {
+ if ($attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_BOOL) {
+ return false;
+ } elseif ($attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_MAP
+ || $attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_DICTIONARY
+ ) {
+ return [];
+ }
+ } else {
+ if ($attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_MAP) {
+ return $attrsFromLdap[$attr];
+ } elseif ($attrsNameTypeMap[$attr][self::TYPE] === self::TYPE_DICTIONARY) {
+ return $this->convertToMap($attrsFromLdap[$attr]);
+ }
return $attrsFromLdap[$attr][0];
}
return null;
}
+
+ private function convertToMap($attrValue)
+ {
+ $result = [];
+ foreach ($attrValue as $sub) {
+ list($key, $value) = explode('=', $sub, 2);
+ $result[$key] = $value;
+ }
+ return $result;
+ }
}
|
fix: fix processing attr val of map type in LDAP
- previous implementation did not convert map value to associative array
|
CESNET_perun-simplesamlphp-module
|
train
|
061cfbecd4c025dc5c575ed4a89b3a9446c0849f
|
diff --git a/tests/system/Helpers/FormHelperTest.php b/tests/system/Helpers/FormHelperTest.php
index <HASH>..<HASH> 100644
--- a/tests/system/Helpers/FormHelperTest.php
+++ b/tests/system/Helpers/FormHelperTest.php
@@ -557,6 +557,33 @@ EOH;
}
// ------------------------------------------------------------------------
+ public function testFormMultiselectArrayData()
+ {
+ $expected = <<<EOH
+<select name="shirts[]" multiple="multiple">
+<option value="small">Small Shirt</option>
+<option value="med" selected="selected">Medium Shirt</option>
+<option value="large" selected="selected">Large Shirt</option>
+<option value="xlarge">Extra Large Shirt</option>
+</select>\n
+EOH;
+ $options = [
+ 'small' => 'Small Shirt',
+ 'med' => 'Medium Shirt',
+ 'large' => 'Large Shirt',
+ 'xlarge' => 'Extra Large Shirt',
+ ];
+
+ $data = [
+ 'name' => 'shirts[]',
+ 'options' => $options,
+ 'selected' => ['med', 'large'],
+ ];
+
+ $this->assertEquals($expected, form_multiselect($data));
+ }
+
+ // ------------------------------------------------------------------------
public function testFormFieldset()
{
$expected = <<<EOH
|
test for Multiselect with Array Data
|
codeigniter4_CodeIgniter4
|
train
|
c26a778c6943d8ddae9f71c2de3f7daa65cdb35d
|
diff --git a/app/assets/javascripts/govuk_publishing_components/components/cookie-banner.js b/app/assets/javascripts/govuk_publishing_components/components/cookie-banner.js
index <HASH>..<HASH> 100644
--- a/app/assets/javascripts/govuk_publishing_components/components/cookie-banner.js
+++ b/app/assets/javascripts/govuk_publishing_components/components/cookie-banner.js
@@ -13,9 +13,6 @@ window.GOVUK.Modules = window.GOVUK.Modules || {};
this.$module.cookieBanner = document.querySelector('.gem-c-cookie-banner')
this.$module.cookieBannerConfirmationMessage = this.$module.querySelector('.gem-c-cookie-banner__confirmation')
- // Temporary check while we have 2 banners co-existing.
- // Once the new banner has been deployed, we will be able to remove code relating to the old banner
- // Separating the code out like this does mean some repetition, but will make it easier to remove later
this.setupCookieMessage()
// Listen for cross-origin communication messages (e.g. hideCookieBanner for when previewing GOV.UK pages
|
Remove comment about co-existing cookie banners
as we don't have 2 banners anymore
|
alphagov_govuk_publishing_components
|
train
|
70836bc87d7cd052b6e3ff84226a71069c454947
|
diff --git a/server.go b/server.go
index <HASH>..<HASH> 100644
--- a/server.go
+++ b/server.go
@@ -343,7 +343,7 @@ func (s *Server) StartSelfMonitoring(database, retention string, interval time.D
pointFromStats := func(st *Stats, tags map[string]string) Point {
point := Point{
Timestamp: time.Now(),
- Name: st.Name(),
+ Name: "stat_" + st.Name(),
Tags: make(map[string]string),
Fields: make(map[string]interface{}),
}
@@ -382,7 +382,7 @@ func (s *Server) StartSelfMonitoring(database, retention string, interval time.D
// Server diagnostics.
for _, row := range s.DiagnosticsAsRows() {
- points, err := s.convertRowToPoints(row.Name, row)
+ points, err := s.convertRowToPoints("diag_"+row.Name, row)
if err != nil {
s.Logger.Printf("failed to write diagnostic row for %s: %s", row.Name, err.Error())
continue
@@ -3120,8 +3120,8 @@ func (s *Server) DiagnosticsAsRows() []*influxql.Row {
Name: "server",
Columns: []string{"time", "startTime", "uptime", "id",
"path", "authEnabled", "index", "retentionAutoCreate", "numShards", "cqLastRun"},
- Values: [][]interface{}{[]interface{}{now, startTime, time.Since(startTime).String(), strconv.FormatUint(s.id, 10),
- s.path, s.authenticationEnabled, s.index, s.RetentionAutoCreate, len(s.shards), s.lastContinuousQueryRun}},
+ Values: [][]interface{}{[]interface{}{now, startTime.String(), time.Since(startTime).String(), strconv.FormatUint(s.id, 10),
+ s.path, s.authenticationEnabled, int(s.index), s.RetentionAutoCreate, len(s.shards), s.lastContinuousQueryRun.String()}},
}
// Shard groups.
@@ -3134,7 +3134,7 @@ func (s *Server) DiagnosticsAsRows() []*influxql.Row {
for _, rp := range db.policies {
for _, g := range rp.shardGroups {
shardGroupsRow.Values = append(shardGroupsRow.Values, []interface{}{now, db.name, rp.Name,
- strconv.FormatUint(g.ID, 10), g.StartTime, g.EndTime, g.Duration().String(), len(g.Shards)})
+ strconv.FormatUint(g.ID, 10), g.StartTime.String(), g.EndTime.String(), g.Duration().String(), len(g.Shards)})
}
}
}
@@ -3148,7 +3148,7 @@ func (s *Server) DiagnosticsAsRows() []*influxql.Row {
for _, n := range sh.DataNodeIDs {
nodes = append(nodes, strconv.FormatUint(n, 10))
shardsRow.Values = append(shardsRow.Values, []interface{}{now, strconv.FormatUint(sh.ID, 10), strings.Join(nodes, ","),
- sh.index, sh.store.Path()})
+ strconv.FormatUint(sh.index, 10), sh.store.Path()})
}
}
|
Write stats and diags to different measurements
Also, some fixes to casts. This may need further work.
|
influxdata_influxdb
|
train
|
ada7f8cca313dd3bc5a0f24650c4d862679320e2
|
diff --git a/internal_test.go b/internal_test.go
index <HASH>..<HASH> 100644
--- a/internal_test.go
+++ b/internal_test.go
@@ -95,7 +95,7 @@ func TestFlusher(t *testing.T) {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
- time.Sleep(1)
+ time.Sleep(time.Microsecond)
}
})
@@ -117,6 +117,12 @@ func TestFlusher(t *testing.T) {
var i int
for {
n, err := resp.Body.Read(buf)
+ if n == 0 {
+ if !assert.Equal(t, len(lines)-1, i-1, "wrong number of chunks") {
+ return
+ }
+ break
+ }
t.Logf("Response body %d: %d %s", i, n, buf)
if !assert.Equal(t, []byte(lines[i]), buf[:n], "wrong response body") {
return
|
Sleep longer between writes; check for empty reads
|
lestrrat-go_apache-logformat
|
train
|
37523ebc044fca7946c56596bd6911871ff42244
|
diff --git a/test/rally_api_spec_helper.rb b/test/rally_api_spec_helper.rb
index <HASH>..<HASH> 100644
--- a/test/rally_api_spec_helper.rb
+++ b/test/rally_api_spec_helper.rb
@@ -102,4 +102,7 @@ end
RSpec.configure do |c|
c.include(RallyConfigLoader)
+ c.tty = true
+ c.color = true
+ c.formatter = :documentation
end
\ No newline at end of file
|
S<I>- colorize and format test output
|
RallyTools_RallyRestToolkitForRuby
|
train
|
89d38677a73d21aa19fba8a01bb23998a478cefa
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100755
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Removed remaining `_type` field usages [#2017](https://github.com/ruflin/Elastica/pull/2017)
### Fixed
* Fixed type-hint for `Elastica\Search::setOptionsAndQuery()` [#2009](https://github.com/ruflin/Elastica/pull/2009)
+* Fixed terms query params resolution [#2032](https://github.com/ruflin/Elastica/pull/2032)
### Security
## [7.1.2](https://github.com/ruflin/Elastica/compare/7.1.1...7.1.2)
diff --git a/src/Query/Terms.php b/src/Query/Terms.php
index <HASH>..<HASH> 100644
--- a/src/Query/Terms.php
+++ b/src/Query/Terms.php
@@ -20,16 +20,6 @@ class Terms extends AbstractQuery
private $field;
/**
- * @var array<float|int|string>
- */
- private $terms;
-
- /**
- * @var string[]|null
- */
- private $lookup;
-
- /**
* @param array<bool|float|int|string> $terms Terms list, leave empty if building a terms-lookup query
*/
public function __construct(string $field, array $terms = [])
@@ -39,7 +29,7 @@ class Terms extends AbstractQuery
}
$this->field = $field;
- $this->terms = $terms;
+ $this->setTerms($terms);
}
/**
@@ -49,9 +39,7 @@ class Terms extends AbstractQuery
*/
public function setTerms(array $terms): self
{
- $this->terms = $terms;
-
- return $this;
+ return $this->setParam($this->field, $terms);
}
/**
@@ -65,37 +53,21 @@ class Terms extends AbstractQuery
throw new \TypeError(\sprintf('Argument 1 passed to "%s()" must be a scalar, %s given.', __METHOD__, \is_object($term) ? \get_class($term) : \gettype($term)));
}
- $this->terms[] = $term;
+ $terms = $this->getParam($this->field);
- return $this;
+ if (isset($terms['index'])) {
+ throw new InvalidException('Mixed terms and terms lookup are not allowed.');
+ }
+
+ return $this->addParam($this->field, $term);
}
public function setTermsLookup(string $index, string $id, string $path): self
{
- $this->lookup = [
+ return $this->setParam($this->field, [
'index' => $index,
'id' => $id,
'path' => $path,
- ];
-
- return $this;
- }
-
- /**
- * {@inheritdoc}
- */
- public function toArray(): array
- {
- if (null !== $this->lookup && \count($this->terms)) {
- throw new InvalidException('Unable to build Terms query: only one of terms or lookup properties should be set');
- }
-
- if (null !== $this->lookup) {
- $this->setParam($this->field, $this->lookup);
- } else {
- $this->setParam($this->field, $this->terms);
- }
-
- return parent::toArray();
+ ]);
}
}
diff --git a/tests/Query/TermsTest.php b/tests/Query/TermsTest.php
index <HASH>..<HASH> 100644
--- a/tests/Query/TermsTest.php
+++ b/tests/Query/TermsTest.php
@@ -17,17 +17,21 @@ class TermsTest extends BaseTest
*/
public function testSetTermsLookup(): void
{
- $terms = [
- 'index' => 'index_name',
- 'id' => '1',
- 'path' => 'terms',
+ $expected = [
+ 'terms' => [
+ 'name' => [
+ 'index' => 'index_name',
+ 'id' => '1',
+ 'path' => 'terms',
+ ],
+ ],
];
- $query = new Terms('name');
- $query->setTermsLookup('index_name', '1', 'terms');
+ $query = (new Terms('name'))
+ ->setTermsLookup('index_name', '1', 'terms')
+ ;
- $data = $query->toArray();
- $this->assertEquals($terms, $data['terms']['name']);
+ $this->assertSame($expected, $query->toArray());
}
/**
@@ -35,11 +39,13 @@ class TermsTest extends BaseTest
*/
public function testInvalidParams(): void
{
- $query = new Terms('field', ['aaa', 'bbb']);
- $query->setTermsLookup('index', '1', 'path');
-
$this->expectException(InvalidException::class);
- $query->toArray();
+ $this->expectExceptionMessage('Mixed terms and terms lookup are not allowed.');
+
+ (new Terms('field', ['aaa', 'bbb']))
+ ->setTermsLookup('index', '1', 'path')
+ ->addTerm('ccc')
+ ;
}
/**
@@ -48,6 +54,8 @@ class TermsTest extends BaseTest
public function testEmptyField(): void
{
$this->expectException(InvalidException::class);
+ $this->expectExceptionMessage('Terms field name has to be set');
+
new Terms('');
}
|
Use params to configure terms query (#<I>)
* Use params to configure terms query
* Adapt tests
* Store field as property
* Add changelog
|
ruflin_Elastica
|
train
|
7fabd25bdb0191597212be9437e0417b9c98c7c8
|
diff --git a/src/main/java/su/litvak/chromecast/api/v2/Channel.java b/src/main/java/su/litvak/chromecast/api/v2/Channel.java
index <HASH>..<HASH> 100644
--- a/src/main/java/su/litvak/chromecast/api/v2/Channel.java
+++ b/src/main/java/su/litvak/chromecast/api/v2/Channel.java
@@ -250,8 +250,7 @@ class Channel implements Closeable {
/**
* Open the channel.
*
- * <p>
- * This function must be called before any other usage.
+ * <p>This function must be called before any other usage.</p>
*
* @throws IOException
* @throws GeneralSecurityException
diff --git a/src/main/java/su/litvak/chromecast/api/v2/ChromeCast.java b/src/main/java/su/litvak/chromecast/api/v2/ChromeCast.java
index <HASH>..<HASH> 100644
--- a/src/main/java/su/litvak/chromecast/api/v2/ChromeCast.java
+++ b/src/main/java/su/litvak/chromecast/api/v2/ChromeCast.java
@@ -35,7 +35,7 @@ public class ChromeCast {
private final int port;
private String appsURL;
private String application;
- private final Channel channel;
+ private Channel channel;
ChromeCast(JmDNS mDNS, String name) {
this.name = name;
@@ -44,7 +44,6 @@ public class ChromeCast {
this.port = serviceInfo.getPort();
this.appsURL = serviceInfo.getURLs().length == 0 ? null : serviceInfo.getURLs()[0];
this.application = serviceInfo.getApplication();
- this.channel = new Channel(address, port, this.eventListenerHolder);
}
public ChromeCast(String address) {
@@ -54,7 +53,6 @@ public class ChromeCast {
public ChromeCast(String address, int port) {
this.address = address;
this.port = port;
- this.channel = new Channel(address, port, this.eventListenerHolder);
}
public final String getName() {
@@ -90,17 +88,23 @@ public class ChromeCast {
}
public final synchronized void connect() throws IOException, GeneralSecurityException {
- if (channel.isClosed()) {
+ if (channel == null) {
+ channel = new Channel(this.address, this.port, this.eventListenerHolder);
channel.open();
}
}
public final synchronized void disconnect() throws IOException {
+ if (channel == null) {
+ return;
+ }
+
channel.close();
+ channel = null;
}
public final boolean isConnected() {
- return !channel.isClosed();
+ return channel != null && !channel.isClosed();
}
/**
|
Make 'channel' a short-living object as it was before
|
vitalidze_chromecast-java-api-v2
|
train
|
bb1a5707d872d39212f1046a37afb3305807f788
|
diff --git a/.eslintrc.js b/.eslintrc.js
index <HASH>..<HASH> 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -5,6 +5,9 @@ module.exports = {
es6: true,
node: true
},
+ parserOptions: {
+ ecmaVersion: 2020
+ },
plugins: ['ghost'],
extends: [
'plugin:ghost/node'
|
Updated eslint ecma version to <I>
- It's time, we want to be able to use more modern features, and now we're on node <I> min this makes sense
- @TODO: do this in eslint-plugin-ghost and add new rules to guard the new features
|
TryGhost_Ghost
|
train
|
bbf3fd8ce5a9a9592a09c591088a5c5be93bd706
|
diff --git a/textbuilder.go b/textbuilder.go
index <HASH>..<HASH> 100644
--- a/textbuilder.go
+++ b/textbuilder.go
@@ -217,16 +217,15 @@ func (mtb MarkdownTxBuilder) BuildWrap(s string, fg, bg Attribute, wl uint) []Ce
} else if plainRune[i] != plainWrappedRune[i] && plainWrappedRune[i] == 10 {
trigger = "go"
cell := Cell{10, 0, 0}
+ j := i - 0
// insert a cell into the []Cell in correct position
- tmpCell = append(tmpCell, Cell{0, 0, 0})
- copy(tmpCell[i+1:], tmpCell[i:])
tmpCell[i] = cell
// insert the newline into plain so we avoid indexing errors
plainRuneNew = append(plainRune, 10)
- copy(plainRuneNew[i+1:], plainRuneNew[i:])
- plainRuneNew[i] = plainWrappedRune[i]
+ copy(plainRuneNew[j+1:], plainRuneNew[j:])
+ plainRuneNew[j] = plainWrappedRune[j]
// restart the inner for loop until plain and plain wrapped are
// the same; yeah, it's inefficient, but the text amounts
|
fixed bug in where the newline should just replace the space
|
gizak_termui
|
train
|
581d7b4959ef480890a797db0d9bb73ef46561a8
|
diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index <HASH>..<HASH> 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -371,30 +371,30 @@ function reset_login_count() {
$SESSION->logincount = 0;
}
-function isadmin($userid=false) {
+function isadmin($userid=0) {
/// Is the user an admin?
global $USER;
static $admins = array();
static $nonadmins = array();
- if (empty($USER->id)) {
- return false;
+ if (!$userid){
+ if (empty($USER->id)) {
+ return false;
+ }
+ $userid = $USER->id;
}
- $checkid = $userid ? $userid : $USER->id;
-
- if (in_array($checkid, $admins)) {
+ if (in_array($userid, $admins)) {
return true;
- } elseif (in_array($ceckid, $nonadmins)) {
+ } else if (in_array($userid, $nonadmins)) {
return false;
- } elseif (record_exists("user_admins", "userid", $checkid)){
- $admins[] = $checkid;
+ } else if (record_exists("user_admins", "userid", $userid)){
+ $admins[] = $userid;
return true;
} else {
- $nonadmins[] = $checkid;
+ $nonadmins[] = $userid;
return false;
}
-
}
function isteacher($courseid, $userid=0) {
|
Fixes for isadmin()
|
moodle_moodle
|
train
|
11e6eccb8a80b0031068563b2efa776068babcd2
|
diff --git a/lib/yard/generators/base.rb b/lib/yard/generators/base.rb
index <HASH>..<HASH> 100644
--- a/lib/yard/generators/base.rb
+++ b/lib/yard/generators/base.rb
@@ -175,7 +175,11 @@ module YARD
if section.is_a?(Symbol)
if respond_to?(section)
- send(section, object, &block) || ""
+ if method(section).arity != 1
+ send(section, &block)
+ else
+ send(section, object, &block)
+ end || ""
else # treat it as a String
render(object, section, &block)
end
@@ -183,38 +187,21 @@ module YARD
render(object, section, &block)
end
else
- raise ArgumentError
+ type = section.is_a?(String) || section.is_a?(Symbol) ? 'section' : 'generator'
+ log.warn "Ignoring invalid #{type} '#{section}' in #{self.class}"
+ ""
end
- rescue ArgumentError
- type = section <= Generators::Base ? "generator" : "section"
- log.warn "Ignoring invalid #{type} '#{section}' in #{self.class}"
- ""
- rescue => e
- log.error "In generator #{self.class.name}, section #{section}:"
- log.error "\tFailed to parse object: " + object.inspect
- log.error "\tException message: " + e.message
- log.error "\n\t" + e.backtrace[0..5].join("\n\t")
- log.error ""
- raise
end
end
- def render(object, file = nil, generator = generator_name, &block)
- path = template_path(file, generator)
- f = find_template(path)
- if f
- begin
- Erubis::Eruby.new(File.read(f)).result(binding)
- rescue => e
- log.error "In generator #{self.class.name}, rendering: #{path}:"
- log.error "\tFailed to parse object: " + object.inspect
- log.error "\tException message: " + e.message
- log.error "\n\t" + e.backtrace[0..5].join("\n\t")
- log.error ""
- raise
- end
+ def render(object, file = nil, locals = {}, &block)
+ _path = template_path(file, generator_name)
+ _f = find_template(_path)
+ if _f
+ __l = locals.map {|k,v| "#{k} = #{v.inspect}" }.join(";")
+ Erubis::Eruby.new("<% #{__l} %>" + File.read(_f)).result(binding)
else
- log.warn "Cannot find template `#{path}`"
+ log.warn "Cannot find template `#{_path}`"
""
end
end
|
If generator method does not have object argument, don't send object to it. Add locals hash to #render. Also remove all custom stacktrace printing because it was messy
|
lsegal_yard
|
train
|
aa19fdf6aea853fb8e8a7797892a9e40fdfa4e70
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java
@@ -524,7 +524,7 @@ public abstract class ODatabaseRecordAbstract<REC extends ORecordInternal<?>> ex
readerRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + "." + OStorage.CLUSTER_INTERNAL_NAME, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
- readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_NONE);
+ readerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_READ);
readerRole.addRule(ODatabaseSecurityResources.QUERY, ORole.PERMISSION_READ);
@@ -537,7 +537,7 @@ public abstract class ODatabaseRecordAbstract<REC extends ORecordInternal<?>> ex
writerRole.addRule(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + "." + OStorage.CLUSTER_INTERNAL_NAME, ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".orole", ORole.PERMISSION_READ);
- writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_NONE);
+ writerRole.addRule(ODatabaseSecurityResources.CLUSTER + ".ouser", ORole.PERMISSION_READ);
writerRole.addRule(ODatabaseSecurityResources.ALL_CLASSES, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.ALL_CLUSTERS, ORole.PERMISSION_ALL);
writerRole.addRule(ODatabaseSecurityResources.QUERY, ORole.PERMISSION_READ);
|
Fixed bug on remote opening using users different by ADMIN.
|
orientechnologies_orientdb
|
train
|
6e16419c18da08323e6f6177c9065ccf1dfd1eaf
|
diff --git a/src/main/java/com/amazon/carbonado/cursor/AbstractCursor.java b/src/main/java/com/amazon/carbonado/cursor/AbstractCursor.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/amazon/carbonado/cursor/AbstractCursor.java
+++ b/src/main/java/com/amazon/carbonado/cursor/AbstractCursor.java
@@ -21,6 +21,7 @@ package com.amazon.carbonado.cursor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.NoSuchElementException;
import com.amazon.carbonado.Cursor;
import com.amazon.carbonado.FetchException;
@@ -39,17 +40,18 @@ public abstract class AbstractCursor<S> implements Cursor<S> {
public int copyInto(Collection<? super S> c) throws FetchException {
try {
int count = 0;
- while (hasNext()) {
- c.add(next());
- count++;
+ try {
+ while (hasNext()) {
+ c.add(next());
+ count++;
+ }
+ } catch (NoSuchElementException e) {
+ // Race condition cause by concurrent repository close.
+ silentClose();
}
return count;
} catch (FetchException e) {
- try {
- close();
- } catch (Exception e2) {
- // Don't care.
- }
+ silentClose();
throw e;
}
}
@@ -57,17 +59,18 @@ public abstract class AbstractCursor<S> implements Cursor<S> {
public int copyInto(Collection<? super S> c, int limit) throws FetchException {
try {
int count = 0;
- while (--limit >= 0 && hasNext()) {
- c.add(next());
- count++;
+ try {
+ while (--limit >= 0 && hasNext()) {
+ c.add(next());
+ count++;
+ }
+ } catch (NoSuchElementException e) {
+ // Race condition cause by concurrent repository close.
+ silentClose();
}
return count;
} catch (FetchException e) {
- try {
- close();
- } catch (Exception e2) {
- // Don't care.
- }
+ silentClose();
throw e;
}
}
@@ -78,11 +81,7 @@ public abstract class AbstractCursor<S> implements Cursor<S> {
copyInto(list);
return list;
} catch (FetchException e) {
- try {
- close();
- } catch (Exception e2) {
- // Don't care.
- }
+ silentClose();
throw e;
}
}
@@ -93,11 +92,7 @@ public abstract class AbstractCursor<S> implements Cursor<S> {
copyInto(list, limit);
return list;
} catch (FetchException e) {
- try {
- close();
- } catch (Exception e2) {
- // Don't care.
- }
+ silentClose();
throw e;
}
}
@@ -112,19 +107,27 @@ public abstract class AbstractCursor<S> implements Cursor<S> {
try {
int count = 0;
- while (--amount >= 0 && hasNext()) {
- next();
- count++;
+ try {
+ while (--amount >= 0 && hasNext()) {
+ next();
+ count++;
+ }
+ } catch (NoSuchElementException e) {
+ // Race condition cause by concurrent repository close.
+ silentClose();
}
-
return count;
} catch (FetchException e) {
- try {
- close();
- } catch (Exception e2) {
- // Don't care.
- }
+ silentClose();
throw e;
}
}
+
+ private void silentClose() {
+ try {
+ close();
+ } catch (Exception e2) {
+ // Don't care.
+ }
+ }
}
|
Handle concurrent close while copying cursor contents.
|
Carbonado_Carbonado
|
train
|
5007093ac6e6c77fee5d1ab1e0295923106a822d
|
diff --git a/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetIntrospectable.java b/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetIntrospectable.java
index <HASH>..<HASH> 100644
--- a/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetIntrospectable.java
+++ b/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetIntrospectable.java
@@ -1,5 +1,5 @@
package org.ow2.chameleon.fuchsia.tools.proxiesutils;
public interface ProxyFacetIntrospectable extends FuchsiaProxy {
- public <T> T get(String varName, Class<T> klass);
+ <T> T get(String varName, Class<T> klass);
}
diff --git a/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetInvokable.java b/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetInvokable.java
index <HASH>..<HASH> 100644
--- a/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetInvokable.java
+++ b/tools/proxies-utils/src/main/java/org/ow2/chameleon/fuchsia/tools/proxiesutils/ProxyFacetInvokable.java
@@ -9,7 +9,7 @@ public interface ProxyFacetInvokable extends FuchsiaProxy {
* @param args
* @return
*/
- public Object invoke(String method, Object... args) throws ProxyInvokationException;
+ Object invoke(String method, Object... args) throws ProxyInvokationException;
/**
* Async
@@ -19,6 +19,6 @@ public interface ProxyFacetInvokable extends FuchsiaProxy {
* @param callback
* @param args
*/
- public void invoke(String method, Integer transactionID, Object callback, Object... args) throws ProxyInvokationException;
+ void invoke(String method, Integer transactionID, Object callback, Object... args) throws ProxyInvokationException;
}
|
Fix sonar issues in proxies-utils
|
ow2-chameleon_fuchsia
|
train
|
7ceaec333b53b66c31e8e00ee7bdf670a30f5abf
|
diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml
index <HASH>..<HASH> 100644
--- a/.rubocop_todo.yml
+++ b/.rubocop_todo.yml
@@ -63,12 +63,6 @@ Metrics/ParameterLists:
Metrics/PerceivedComplexity:
Max: 20
-# Offense count: 2
-Naming/AccessorMethodName:
- Exclude:
- - 'lib/gruff/helper/stacked_mixin.rb'
- - 'lib/gruff/store/store.rb'
-
# Offense count: 1
# Configuration parameters: EnforcedStyleForLeadingUnderscores.
# SupportedStylesForLeadingUnderscores: disallowed, required, optional
diff --git a/lib/gruff/base.rb b/lib/gruff/base.rb
index <HASH>..<HASH> 100644
--- a/lib/gruff/base.rb
+++ b/lib/gruff/base.rb
@@ -803,7 +803,7 @@ module Gruff
# Set the color for each data set unless it was given in the data(...) call.
def set_colors
- store.set_colors!(@colors)
+ store.change_colors(@colors)
end
# Sort with largest overall summed value at front of array so it shows up
diff --git a/lib/gruff/helper/stacked_mixin.rb b/lib/gruff/helper/stacked_mixin.rb
index <HASH>..<HASH> 100644
--- a/lib/gruff/helper/stacked_mixin.rb
+++ b/lib/gruff/helper/stacked_mixin.rb
@@ -5,7 +5,7 @@ module Gruff::Base::StackedMixin
# Used by StackedBar and child classes.
#
# tsal: moved from Base 03 FEB 2007
- def get_maximum_by_stack
+ def calculate_maximum_by_stack
# Get sum of each stack
max_hash = {}
store.data.each do |data_set|
diff --git a/lib/gruff/side_stacked_bar.rb b/lib/gruff/side_stacked_bar.rb
index <HASH>..<HASH> 100644
--- a/lib/gruff/side_stacked_bar.rb
+++ b/lib/gruff/side_stacked_bar.rb
@@ -49,7 +49,7 @@ class Gruff::SideStackedBar < Gruff::SideBar
def draw
@has_left_labels = true
- get_maximum_by_stack
+ calculate_maximum_by_stack
super
end
diff --git a/lib/gruff/stacked_area.rb b/lib/gruff/stacked_area.rb
index <HASH>..<HASH> 100644
--- a/lib/gruff/stacked_area.rb
+++ b/lib/gruff/stacked_area.rb
@@ -18,7 +18,7 @@ class Gruff::StackedArea < Gruff::Base
attr_accessor :last_series_goes_on_bottom
def draw
- get_maximum_by_stack
+ calculate_maximum_by_stack
super
return unless data_given?
diff --git a/lib/gruff/stacked_bar.rb b/lib/gruff/stacked_bar.rb
index <HASH>..<HASH> 100644
--- a/lib/gruff/stacked_bar.rb
+++ b/lib/gruff/stacked_bar.rb
@@ -41,7 +41,7 @@ class Gruff::StackedBar < Gruff::Base
# Draws a bar graph, but multiple sets are stacked on top of each other.
def draw
- get_maximum_by_stack
+ calculate_maximum_by_stack
super
return unless data_given?
diff --git a/lib/gruff/store/store.rb b/lib/gruff/store/store.rb
index <HASH>..<HASH> 100644
--- a/lib/gruff/store/store.rb
+++ b/lib/gruff/store/store.rb
@@ -67,7 +67,7 @@ module Gruff
@data.reverse!
end
- def set_colors!(colors)
+ def change_colors(colors)
index = 0
@data.each do |data_row|
data_row.color ||= begin
|
Rubocop: Fix method name for Naming/AccessorMethodName in Rubocop (#<I>)
|
topfunky_gruff
|
train
|
60458890bbf8d53a82e5a3a882c6a9e94292283f
|
diff --git a/lib/chef/knife/solo_cook.rb b/lib/chef/knife/solo_cook.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/knife/solo_cook.rb
+++ b/lib/chef/knife/solo_cook.rb
@@ -270,9 +270,11 @@ class Chef
cmd = ['rsync', '-rL', rsync_debug, rsync_permissions, %Q{--rsh=#{ssh_command}}]
cmd += extra_opts
cmd += rsync_excludes.map { |ignore| "--exclude=#{ignore}" }
- cmd << adjust_rsync_path_on_client(source_path)
- cmd << %Q{:#{adjust_rsync_path_on_node(target_path)}}
- cmd = cmd.flatten.compact
+ cmd += [ adjust_rsync_path_on_client(source_path),
+ ':' + adjust_rsync_path_on_node(target_path) ]
+
+ cmd = cmd.compact
+
Chef::Log.debug cmd.inspect
system!(*cmd)
end
|
More code consistency in rsync command build step
|
matschaffer_knife-solo
|
train
|
cbf2967167819866c939622aab0c120f3efc1e8d
|
diff --git a/simplekv/git.py b/simplekv/git.py
index <HASH>..<HASH> 100644
--- a/simplekv/git.py
+++ b/simplekv/git.py
@@ -8,7 +8,7 @@ from dulwich.objects import Commit, Tree, Blob
from . import KeyValueStore, __version__
-def on_tree(repo, tree, components, obj):
+def _on_tree(repo, tree, components, obj):
"""Mounts an object on a tree, using the given path components.
:param tree: Tree object to mount on.
@@ -46,7 +46,7 @@ def on_tree(repo, tree, components, obj):
a_tree = Tree()
else:
a_tree = Tree()
- res = on_tree(repo, a_tree, bc, obj)
+ res = _on_tree(repo, a_tree, bc, obj)
a_tree_new = res[-1]
if a_tree_new.items():
@@ -109,7 +109,7 @@ class GitCommitStore(KeyValueStore):
if self.subdir:
components = self.subdir.split('/') + components
- res = on_tree(self.repo, tree, components, None)
+ res = _on_tree(self.repo, tree, components, None)
objects_to_add.extend(res)
tree = res[-1]
@@ -181,7 +181,7 @@ class GitCommitStore(KeyValueStore):
components = [key.encode('ascii')]
if self.subdir:
components = self.subdir.split('/') + components
- res = on_tree(self.repo, tree, components, blob)
+ res = _on_tree(self.repo, tree, components, blob)
objects_to_add.extend(res)
commit.tree = res[-1].id
|
Prefixed on_tree with an underscore to mark its non-public nature.
|
mbr_simplekv
|
train
|
686f6b102e3d249d7379ab2424591cad5b086b83
|
diff --git a/src/mixed.js b/src/mixed.js
index <HASH>..<HASH> 100644
--- a/src/mixed.js
+++ b/src/mixed.js
@@ -46,19 +46,21 @@ SchemaType.prototype = {
if (!schema)
return this
- if( schema._type !== this._type )
+ if (schema._type !== this._type && this._type !== 'mixed')
throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this._type} and ${schema._type}`)
var next = _.merge(this.clone(), schema.clone())
// undefined isn't merged over, but is a valid value for default
- if( schema._default === undefined && _.has(this, '_default') )
+ if (schema._default === undefined && _.has(this, '_default'))
next._default = schema._default
// trim exclusive tests, take the most recent ones
next.tests = _.uniq(next.tests.reverse(),
(fn, idx) => next[fn.VALIDATION_KEY] ? fn.VALIDATION_KEY : idx).reverse()
+ next._type = schema._type;
+
return next
},
@@ -68,7 +70,7 @@ SchemaType.prototype = {
},
cast(_value, _opts) {
- var schema = this._resolve((_opts|| {}).context)
+ var schema = this._resolve((_opts || {}).context)
return schema._cast(_value, _opts)
},
@@ -212,7 +214,7 @@ SchemaType.prototype = {
test(name, message, test, useCallback) {
var opts = name
, next = this.clone()
- , errorMsg, isExclusive;
+ , isExclusive;
if (typeof name === 'string') {
if (typeof message === 'function')
diff --git a/src/util/condition.js b/src/util/condition.js
index <HASH>..<HASH> 100644
--- a/src/util/condition.js
+++ b/src/util/condition.js
@@ -24,8 +24,8 @@ class Conditional {
if( !options.then && !options.otherwise )
throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions')
- if( options.then && options.then._type !== type || options.otherwise && options.otherwise._type !== type)
- throw new TypeError(`cannot create polymorphic conditionals, \`then\` and \`otherwise\` must be the same type: ${type}`)
+ // if( options.then && options.then._type !== type || options.otherwise && options.otherwise._type !== type)
+ // throw new TypeError(`cannot create polymorphic conditionals, \`then\` and \`otherwise\` must be the same type: ${type}`)
is = typeof is === 'function'
? is : ((is, value) => is === value).bind(null, is)
@@ -53,4 +53,4 @@ class Conditional {
}
}
-module.exports = Conditional;
\ No newline at end of file
+module.exports = Conditional;
diff --git a/test/mixed.js b/test/mixed.js
index <HASH>..<HASH> 100644
--- a/test/mixed.js
+++ b/test/mixed.js
@@ -105,7 +105,7 @@ describe( 'Mixed Types ', function(){
})
it('exclusive tests should throw without a name', function(){
- ;(function(){
+ (function(){
mixed().test({ message: 'invalid', exclusive: true, test: function(){} })
}).should.throw()
})
@@ -133,7 +133,7 @@ describe( 'Mixed Types ', function(){
message: 'invalid',
exclusive: true,
name: 'max',
- test: function(v, path, context){
+ test: function(){
this.path.should.equal('test')
this.parent.should.eql({ other: 5, test : 'hi' })
this.options.context.should.eql({ user: 'jason' })
@@ -149,7 +149,7 @@ describe( 'Mixed Types ', function(){
var inst = mixed().test({
message: 'invalid ${path}',
name: 'max',
- test: function(v){
+ test: function(){
return this.createError({ path: 'my.path' })
}
})
@@ -166,7 +166,7 @@ describe( 'Mixed Types ', function(){
var inst = mixed().test({
message: 'invalid ${path}',
name: 'max',
- test: function(v){
+ test: function(){
return this.createError({ message: '${path} nope!', path: 'my.path' })
}
})
@@ -254,13 +254,22 @@ describe( 'Mixed Types ', function(){
})
it('concat should fail on different types', function(){
- var inst = string().default('hi')
+ var inst = string().default('hi');
- ;(function(){
+ (function(){
inst.concat(object())
}).should.throw(TypeError)
})
+ it('concat should allow mixed and other type', function(){
+ var inst = mixed().default('hi');
+
+ (function(){
+ inst.concat(string())._type.should.equal('string')
+
+ }).should.not.throw(TypeError)
+ })
+
it('concat should maintain undefined defaults', function(){
var inst = string().default('hi')
@@ -285,7 +294,7 @@ describe( 'Mixed Types ', function(){
//parent
inst._validate(undefined, {}, { parent: { prop: 5 }}).should.be.rejected,
inst._validate(undefined, {}, { parent: { prop: 1 }}).should.be.fulfilled,
- inst._validate('hello', {}, { parent: { prop: 5 }}).should.be.fulfilled,
+ inst._validate('hello', {}, { parent: { prop: 5 }}).should.be.fulfilled
])
.then(function(){
@@ -336,6 +345,3 @@ describe( 'Mixed Types ', function(){
})
})
-
-
-
|
[changed] concat() allows mixing "mixed" and other type
|
jquense_yup
|
train
|
61bb6e37ab9b8fcbe380d30aa5d3cdb5e2c9bdb2
|
diff --git a/rundeck-storage/rundeck-storage-conf/src/main/java/org/rundeck/storage/conf/SubPathTree.java b/rundeck-storage/rundeck-storage-conf/src/main/java/org/rundeck/storage/conf/SubPathTree.java
index <HASH>..<HASH> 100644
--- a/rundeck-storage/rundeck-storage-conf/src/main/java/org/rundeck/storage/conf/SubPathTree.java
+++ b/rundeck-storage/rundeck-storage-conf/src/main/java/org/rundeck/storage/conf/SubPathTree.java
@@ -4,6 +4,7 @@ import org.rundeck.storage.api.*;
import org.rundeck.storage.api.PathUtil;
import org.rundeck.storage.impl.DelegateResource;
import org.rundeck.storage.impl.DelegateTree;
+import org.rundeck.storage.impl.ResourceBase;
import java.util.Collections;
import java.util.HashSet;
@@ -75,7 +76,7 @@ public class SubPathTree<T extends ContentMeta> extends DelegateTree<T> implemen
@Override
public boolean hasResource(Path path) {
- return super.hasResource(translatePathInternal(path));
+ return !isLocalRoot(path) && super.hasResource(translatePathInternal(path));
}
@Override
@@ -89,11 +90,19 @@ public class SubPathTree<T extends ContentMeta> extends DelegateTree<T> implemen
@Override
public Resource<T> getResource(Path path) {
+ if(isLocalRoot(path)) {
+ //root is treated as a dir
+ throw new IllegalArgumentException("No resource for path: " + path);
+ }
return translateResourceExternal(super.getResource(translatePathInternal(path)));
}
@Override
public Resource<T> getPath(Path path) {
+ if(isLocalRoot(path) && !super.hasDirectory(translatePathInternal(path))) {
+ //empty dir
+ return translateResourceExternal(new ResourceBase<T>(path, null, true));
+ }
return translateResourceExternal(super.getPath(translatePathInternal(path)));
}
|
root path treated as implicit dir for SubPathTree
|
rundeck_rundeck
|
train
|
11cd0c68c9bead2762e767181e9e8ec2e0a47579
|
diff --git a/mode/markdown/markdown.js b/mode/markdown/markdown.js
index <HASH>..<HASH> 100644
--- a/mode/markdown/markdown.js
+++ b/mode/markdown/markdown.js
@@ -437,13 +437,13 @@ CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
return tokenTypes.image;
}
- if (ch === '[' && stream.match(/.*\](\(.*\)| ?\[.*\])/, false)) {
+ if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false)) {
state.linkText = true;
if (modeCfg.highlightFormatting) state.formatting = "link";
return getType(state);
}
- if (ch === ']' && state.linkText && stream.match(/\(.*\)| ?\[.*\]/, false)) {
+ if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) {
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
state.linkText = false;
|
[markdown mode] Fix some issues with link matching
Closes #<I>
|
codemirror_CodeMirror
|
train
|
64611ced8519faa7bc0283323a1ce064a75d2daf
|
diff --git a/assets/src/scripts/charcoal/admin/property/input/text.js b/assets/src/scripts/charcoal/admin/property/input/text.js
index <HASH>..<HASH> 100644
--- a/assets/src/scripts/charcoal/admin/property/input/text.js
+++ b/assets/src/scripts/charcoal/admin/property/input/text.js
@@ -504,3 +504,7 @@ Charcoal.Admin.Property_Input_Text.prototype.set_split_on = function (splitOn) {
this.split_on = splitOn;
return this;
};
+
+Charcoal.Admin.Property_Input_Text.prototype.destroy()
+{
+}
|
Fix an issue preventing text input to re-render itself correctly
Apparently adding an empty delete method forces the manager the call init on the widget 🤷
|
locomotivemtl_charcoal-admin
|
train
|
8614d5bbe2307277c52c0a41f56d1664e9b6bc0a
|
diff --git a/test/string.js b/test/string.js
index <HASH>..<HASH> 100644
--- a/test/string.js
+++ b/test/string.js
@@ -404,6 +404,16 @@ tests = {
assert.equal(expected, data);
}
+, 'test stripTags': function () {
+ var html = '<div>foo</div><p>bar<br/>wooby</p>'
+ , expected = 'foobarwooby';
+ assert.equal(string.stripTags(html), expected);
+ }
+, 'test stripTags with allowed <br>': function () {
+ var html = '<div>foo</div><p>bar<br/>wooby</p>'
+ , expected = 'foobar<br/>wooby';
+ assert.equal(string.stripTags(html, '<br>'), expected);
+ }
};
module.exports = tests;
|
added tests for string.stripTags()
|
mde_utilities
|
train
|
d4d414694a77a373a06f141eaece29e675dd0c18
|
diff --git a/lib/setuplib.php b/lib/setuplib.php
index <HASH>..<HASH> 100644
--- a/lib/setuplib.php
+++ b/lib/setuplib.php
@@ -897,7 +897,11 @@ function initialise_fullme() {
// (That is, the Moodle server uses http, with an external box translating everything to https).
if (empty($CFG->sslproxy)) {
if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
- print_error('sslonlyaccess', 'error');
+ if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
+ print_error('sslonlyaccess', 'error');
+ } else {
+ redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
+ }
}
} else {
if ($wwwroot['scheme'] !== 'https') {
|
MDL-<I> setuplib: Redirect on https mismatch
When the wwwroot indicates https support and a page is accessed over http,
redirect to the wwwroot. This is a better experience than displaying an error.
|
moodle_moodle
|
train
|
1ab16480c3eda2ea7ca5de33474e649d4a9b2044
|
diff --git a/src/js/confirmation.js b/src/js/confirmation.js
index <HASH>..<HASH> 100644
--- a/src/js/confirmation.js
+++ b/src/js/confirmation.js
@@ -4,14 +4,14 @@
// CONFIRMATION CLASS DEFINITION
// =============================
- var Confirmation = function($triggerEl, options) {
- var message = (!options || !('confirm-message' in options) || !options['confirm-message']) ? this.defaults['confirm-message'] : options['confirm-message'];
- var yes = (!options || !('confirm-yes' in options) || !options['confirm-yes']) ? this.defaults['confirm-yes'] : options['confirm-yes'];
- var no = (!options || !('confirm-no' in options) || !options['confirm-no']) ? this.defaults['confirm-no'] : options['confirm-no'];
+ var Confirmation = function($triggerEl, callback, message, yes, no) {
+ message = message !== null ? message : this.defaults['confirm-message'];
+ yes = yes !== null ? yes : this.defaults['confirm-yes'];
+ no = no !== null ? no : this.defaults['confirm-no'];
+ callback = callback !== null ? callback : this.defaults.callback;
this.modal = this.getModal(message, yes, no);
-
this.$triggerEl = $triggerEl;
- this.callback = (!options || !('callback' in options) || !options.callback) ? this.defaults.callback : options.callback;
+ this.callback = callback;
};
Confirmation.prototype.defaults = {
@@ -87,12 +87,17 @@
function Plugin(options) {
var $element, data;
+ var message = options && ('confirm-message' in options) && options['confirm-message'] ? options['confirm-message'] : null;
+ var yes = options && ('confirm-yes' in options) && options['confirm-yes'] ? options['confirm-yes'] : null;
+ var no = options && ('confirm-no' in options) && options['confirm-no'] ? options['confirm-no'] : null;
+ var callback = options && ('callback' in options) && options.callback ? options.callback : null;
+
return this.each(function() {
$element = $(this);
data = $element.data('sui.confirmation');
if (!data) {
- $element.data('sui.confirmation', (data = new Confirmation($element, options)));
+ $element.data('sui.confirmation', (data = new Confirmation($element, callback, message, yes, no)));
}
data.showConfirmation();
|
Refactoring to follow 'Ask for what you need' rule
|
visionappscz_bootstrap-ui
|
train
|
e5ff7224d8657d63ae8ca44451e80dc44b4e0026
|
diff --git a/src/formulas.js b/src/formulas.js
index <HASH>..<HASH> 100644
--- a/src/formulas.js
+++ b/src/formulas.js
@@ -30,7 +30,7 @@ SOFTWARE.
* @private
*/
- /**
+/**
* Compute the optimal size of a Bloom Filter
* @param {int} setLength - The length of the dataset used to fill the filter
* @param {number} errorRate - The targeted false positive rate
|
Fix linting error with standard
|
Callidon_bloom-filters
|
train
|
2b905754ca31ba6ade7b5558a59cd7081689df20
|
diff --git a/src/WeAreDe/TbcPay/TbcPayProcessor.php b/src/WeAreDe/TbcPay/TbcPayProcessor.php
index <HASH>..<HASH> 100644
--- a/src/WeAreDe/TbcPay/TbcPayProcessor.php
+++ b/src/WeAreDe/TbcPay/TbcPayProcessor.php
@@ -68,7 +68,7 @@ class TbcPayProcessor
/**
* authorization language identifier, optional (up to 32 characters)
- * EN, GE e.g,
+ * EN, GE e.g,
* @var string
*/
public $language;
@@ -78,6 +78,12 @@ class TbcPayProcessor
* @var string
*/
public $biller;
+
+ /**
+ * charge ertguli points instead of cash
+ * @var bool
+ */
+ public $charge_ertguli_points = false;
/**
* ? this seems to be ignored by tbcbank
@@ -91,7 +97,6 @@ class TbcPayProcessor
* private $property_value;
*/
-
/**
* @param string $cert_path
* @param string $cert_pass
@@ -195,6 +200,10 @@ class TbcPayProcessor
'biller' => $this->biller,
'msg_type' => 'SMS'
);
+
+ if ($this->charge_ertguli_points) {
+ $post_fields['account'] = '80|0000';
+ }
return $this->process($post_fields);
}
@@ -219,6 +228,10 @@ class TbcPayProcessor
'biller' => $this->biller,
'msg_type' => 'DMS'
);
+
+ if ($this->charge_ertguli_points) {
+ $post_fields['account'] = '80|0000';
+ }
return $this->process($post_fields);
}
|
feat: Charge ertguli points
|
plugandpay_tbc-credit-card-payment-gateway-php-lib
|
train
|
39db59bbefa9317076798880714b062a239661af
|
diff --git a/admin/context.go b/admin/context.go
index <HASH>..<HASH> 100644
--- a/admin/context.go
+++ b/admin/context.go
@@ -372,7 +372,8 @@ func (context *Context) funcMap() template.FuncMap {
return funcMap
}
-// PatchURL updates the query part of the current request url
+// PatchURL updates the query part of the current request url. You can
+// access it in template by `patch_url`.
// patch_url "key" "value"
func (context *Context) PatchURL(parts ...interface{}) (u string, err error) {
url := *context.Request.URL
@@ -380,12 +381,12 @@ func (context *Context) PatchURL(parts ...interface{}) (u string, err error) {
for i := 0; i < len(parts)/2; i++ {
key, ok := parts[i*2].(string)
if !ok {
- err = fmt.Errorf("%[1]s type is %[1]T, want string", parts[i*2])
+ err = fmt.Errorf("%[1]v type is %[1]T, want string", parts[i*2])
return
}
value, ok := parts[i*2+1].(string)
if !ok {
- err = fmt.Errorf("%[1]s type is %[1]T, want string", parts[i*2+1])
+ err = fmt.Errorf("%[1]v type is %[1]T, want string", parts[i*2+1])
return
}
if value == "" {
diff --git a/admin/context_test.go b/admin/context_test.go
index <HASH>..<HASH> 100644
--- a/admin/context_test.go
+++ b/admin/context_test.go
@@ -1,6 +1,7 @@
package admin
import (
+ "errors"
"net/http"
"net/url"
"testing"
@@ -13,6 +14,7 @@ func TestPatchUrl(t *testing.T) {
original string
input []interface{}
want string
+ err error
}{
{
original: "http://qor.com/admin/orders?locale=global&q=dotnet&test=1#test",
@@ -24,16 +26,27 @@ func TestPatchUrl(t *testing.T) {
input: []interface{}{"locale", ""},
want: "http://qor.com/admin/orders?q=dotnet&test=1#test",
},
+ {
+ original: "http://qor.com/admin/orders?locale=global&q=dotnet&test=1#test",
+ input: []interface{}{"locale", 1},
+ err: errors.New("1 type is int, want string"),
+ },
}
for _, c := range cases {
u, _ := url.Parse(c.original)
context := Context{Context: &qor.Context{Request: &http.Request{URL: u}}}
got, err := context.PatchURL(c.input...)
- if err != nil {
- t.Error(err)
- }
- if got != c.want {
- t.Errorf("context.PatchURL = %s; c.want %s", got, c.want)
+ if c.err != nil {
+ if err == nil || err.Error() != c.err.Error() {
+ t.Errorf("got error %s; want %s", err, c.err)
+ }
+ } else {
+ if err != nil {
+ t.Error(err)
+ }
+ if got != c.want {
+ t.Errorf("context.PatchURL = %s; c.want %s", got, c.want)
+ }
}
}
}
|
add tests and help doc for patch_url
|
qor_qor
|
train
|
849477f734700be201df64a0f0f32afc1e21333d
|
diff --git a/route.go b/route.go
index <HASH>..<HASH> 100644
--- a/route.go
+++ b/route.go
@@ -4,6 +4,7 @@ import (
"net/http"
"sort"
"strings"
+ "net/url"
)
const (
@@ -126,7 +127,12 @@ func (r *Route) getExecution(method string, pathParts []string, ex *routeExecuti
// save path parameters
if curRoute.isParam {
- ex.params[curRoute.paramName] = pathParts[0]
+ value, err := url.PathUnescape(pathParts[0])
+ if err != nil {
+ // TODO: maybe handle errors more gracefully
+ panic(err)
+ }
+ ex.params[curRoute.paramName] = value
}
// check if this is the bottom of the path
|
decode path param, panic if it fails
|
AndrewBurian_powermux
|
train
|
a05e72c35629949a811c0c43942e0e7deae0d7e3
|
diff --git a/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/DepthFirstSearch.java b/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/DepthFirstSearch.java
index <HASH>..<HASH> 100644
--- a/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/DepthFirstSearch.java
+++ b/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/DepthFirstSearch.java
@@ -47,7 +47,7 @@ public class DepthFirstSearch<A,S,N extends Node<A,S,N>> extends Algorithm<A,S,N
this.initialNode = initialNode;
}
- private class StackFrameNode {
+ public class StackFrameNode {
// Iterable used to compute neighbors of the current node
java.util.Iterator<N> successors;
// Current search node
|
Update DepthFirstSearch.java
StackFrameNode changed to public
|
citiususc_hipster
|
train
|
cbb22ef6b2004e5edc247514eb86b56059c19913
|
diff --git a/tests/PluginClientBuilderTest.php b/tests/PluginClientBuilderTest.php
index <HASH>..<HASH> 100644
--- a/tests/PluginClientBuilderTest.php
+++ b/tests/PluginClientBuilderTest.php
@@ -49,6 +49,29 @@ class PluginClientBuilderTest extends TestCase
$this->assertSame($expected, $plugged);
}
+ /** @dataProvider clientProvider */
+ public function testOptions(string $client): void
+ {
+ $builder = new PluginClientBuilder();
+ $builder->setOption('max_restarts', 5);
+
+ $client = $this->prophesize($client)->reveal();
+ $client = $builder->createClient($client);
+
+ $closure = Closure::bind(
+ function (): array {
+ return $this->options;
+ },
+ $client,
+ PluginClient::class
+ );
+
+ $options = $closure();
+
+ $this->assertArrayHasKey('max_restarts', $options);
+ $this->assertSame(5, $options['max_restarts']);
+ }
+
public function clientProvider(): iterable
{
yield 'sync\'d http client' => [HttpClient::class];
|
Add test on passing options from the client builder to the client
|
php-http_client-common
|
train
|
ee67757a81596202e605838e9d8b242ef2e0afa7
|
diff --git a/core/src/main/java/io/undertow/server/DefaultByteBufferPool.java b/core/src/main/java/io/undertow/server/DefaultByteBufferPool.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/undertow/server/DefaultByteBufferPool.java
+++ b/core/src/main/java/io/undertow/server/DefaultByteBufferPool.java
@@ -152,7 +152,7 @@ public class DefaultByteBufferPool implements ByteBufferPool {
local.allocationDepth++;
}
buffer.clear();
- return new DefaultPooledBuffer(this, buffer, leakDectionPercent == 0 ? false : (++count % 100 > leakDectionPercent));
+ return new DefaultPooledBuffer(this, buffer, leakDectionPercent == 0 ? false : (++count % 100 < leakDectionPercent));
}
@Override
|
UNDERTOW-<I> DefaultByteBufferPool leak detection works properly at <I>%
Previously the comparison was inverted such that passing <I>%
detection would never instantiate a LeakDetector.
|
undertow-io_undertow
|
train
|
908ce3c9343548475f819861d17f767b1c6e1566
|
diff --git a/js/researches/english/passivevoice-english/auxiliaries.js b/js/researches/english/passivevoice-english/auxiliaries.js
index <HASH>..<HASH> 100644
--- a/js/researches/english/passivevoice-english/auxiliaries.js
+++ b/js/researches/english/passivevoice-english/auxiliaries.js
@@ -1,31 +1,41 @@
+// These auxiliaries are filtered from the beginning of word combinations in the keyword suggestions.
+var filteredAuxiliaries = [
+ "am",
+ "is",
+ "are",
+ "was",
+ "were",
+ "been",
+ "get",
+ "gets",
+ "got",
+ "gotten",
+ "be",
+ "she's",
+ "he's",
+ "it's",
+ "i'm",
+ "we're",
+ "they're",
+ "you're",
+ "isn't",
+ "weren't",
+ "wasn't",
+ "that's",
+ "aren't"
+];
+
+// These auxiliaries are not filtered from the beginning of word combinations in the keyword suggestions.
+var notFilteredAuxiliaries = [
+ "being",
+ "getting",
+ "having",
+ "what's"
+];
+
module.exports = function() {
- return [
- "am",
- "is",
- "are",
- "was",
- "were",
- "been",
- "being",
- "get",
- "gets",
- "getting",
- "got",
- "gotten",
- "having",
- "be",
- "she's",
- "he's",
- "it's",
- "i'm",
- "we're",
- "they're",
- "you're",
- "what's",
- "isn't",
- "weren't",
- "wasn't",
- "that's",
- "aren't",
- ];
+ return {
+ filteredAuxiliaries: filteredAuxiliaries,
+ all: filteredAuxiliaries.concat( notFilteredAuxiliaries ),
+ };
};
diff --git a/js/researches/getPassiveVoice.js b/js/researches/getPassiveVoice.js
index <HASH>..<HASH> 100644
--- a/js/researches/getPassiveVoice.js
+++ b/js/researches/getPassiveVoice.js
@@ -8,7 +8,7 @@ var normalizeSingleQuotes = require( "../stringProcessing/quotes.js" ).normalize
var nonverbEndingEd = require( "./english/passivevoice-english/non-verb-ending-ed.js" )();
var determiners = require( "./english/passivevoice-english/determiners.js" )();
-var auxiliaries = require( "./english/passivevoice-english/auxiliaries.js" )();
+var auxiliaries = require( "./english/passivevoice-english/auxiliaries.js" )().all;
var irregulars = require( "./english/passivevoice-english/irregulars.js" )();
var stopwords = require( "./english/passivevoice-english/stopwords.js" )();
|
Refactor auxiliaries to prepare for use in keyword suggestion tool
|
Yoast_YoastSEO.js
|
train
|
9f4560b20fb3bd4bb855fada3e6feea59b26ce66
|
diff --git a/CONTRIBUTORS b/CONTRIBUTORS
index <HASH>..<HASH> 100644
--- a/CONTRIBUTORS
+++ b/CONTRIBUTORS
@@ -68,6 +68,7 @@ Joe Buck [@four2five](https://github.com/four2five)
John Barker [@j16r](https://github.com/j16r)
John Goodall [@jgoodall](https://github.com/jgoodall)
John Stanford [@jxstanford](https://github.com/jxstanford)
+Jonas Groenaas Drange [@semafor](https://github.com/semafor)
Josh Chorlton [@jchorl](https://github.com/jchorl)
jun [@coseyo](https://github.com/coseyo)
Junpei Tsuji [@jun06t](https://github.com/jun06t)
diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -26,7 +26,7 @@ import (
const (
// Version is the current version of Elastic.
- Version = "6.1.6"
+ Version = "6.1.7"
// DefaultURL is the default endpoint of Elasticsearch on the local machine.
// It is used e.g. when initializing a new Client without a specific URL.
diff --git a/errors.go b/errors.go
index <HASH>..<HASH> 100644
--- a/errors.go
+++ b/errors.go
@@ -94,7 +94,7 @@ func (e *Error) Error() string {
// IsConnErr returns true if the error indicates that Elastic could not
// find an Elasticsearch host to connect to.
func IsConnErr(err error) bool {
- return errors.Cause(err) == ErrNoClient
+ return err == ErrNoClient || errors.Cause(err) == ErrNoClient
}
// IsNotFound returns true if the given error indicates that Elasticsearch
diff --git a/reindex.go b/reindex.go
index <HASH>..<HASH> 100644
--- a/reindex.go
+++ b/reindex.go
@@ -20,6 +20,7 @@ type ReindexService struct {
waitForActiveShards string
waitForCompletion *bool
requestsPerSecond *int
+ slices *int
body interface{}
source *ReindexSource
destination *ReindexDestination
@@ -51,6 +52,12 @@ func (s *ReindexService) RequestsPerSecond(requestsPerSecond int) *ReindexServic
return s
}
+// Slices specifies the number of slices this task should be divided into. Defaults to 1.
+func (s *ReindexService) Slices(slices int) *ReindexService {
+ s.slices = &slices
+ return s
+}
+
// Refresh indicates whether Elasticsearch should refresh the effected indexes
// immediately.
func (s *ReindexService) Refresh(refresh string) *ReindexService {
@@ -179,6 +186,9 @@ func (s *ReindexService) buildURL() (string, url.Values, error) {
if s.requestsPerSecond != nil {
params.Set("requests_per_second", fmt.Sprintf("%v", *s.requestsPerSecond))
}
+ if s.slices != nil {
+ params.Set("slices", fmt.Sprintf("%v", *s.slices))
+ }
if s.waitForActiveShards != "" {
params.Set("wait_for_active_shards", s.waitForActiveShards)
}
|
Add support for automatic slicing in Reindex API
As of Elasticsearch <I>, there is a support for automatically slicing
the reindexing task. See
<URL>
|
olivere_elastic
|
train
|
87ac8ca6183b9ffd7cd936ef8fe5769d6d700d7c
|
diff --git a/pyhomematic/devicetypes/sensors.py b/pyhomematic/devicetypes/sensors.py
index <HASH>..<HASH> 100644
--- a/pyhomematic/devicetypes/sensors.py
+++ b/pyhomematic/devicetypes/sensors.py
@@ -284,7 +284,7 @@ class MotionV2(Motion, HelperSabotage):
"""Motion detection version 2."""
-class MotionIP(HMBinarySensor, HMSensor):
+class MotionIP(HMBinarySensor, HMSensor, HelperLowBatIP, HelperOperatingVoltageIP):
"""Motion detection indoor (rf ip)"""
def __init__(self, device_description, proxy, resolveparamsets=False):
@@ -293,7 +293,7 @@ class MotionIP(HMBinarySensor, HMSensor):
# init metadata
self.BINARYNODE.update({"MOTION_DETECTION_ACTIVE": [1], "MOTION": [1]})
self.SENSORNODE.update({"ILLUMINATION": [1]})
- self.ATTRIBUTENODE.update({"LOW_BAT": [0], "ERROR_CODE": [0]})
+ self.ATTRIBUTENODE.update({"ERROR_CODE": [0]})
def is_motion(self, channel=None):
""" Return True if motion is detected """
@@ -306,20 +306,12 @@ class MotionIP(HMBinarySensor, HMSensor):
""" Return brightness from 0 (dark) to 163830 (bright) """
return float(self.getSensorData("ILLUMINATION", channel))
- def low_batt(self, channel=None):
- """ Returns if the battery is low. """
- return self.getAttributeData("LOW_BAT", channel)
-
- def sabotage(self, channel=None):
- """Returns True if the devicecase has been opened."""
- return bool(self.getAttributeData("SABOTAGE", channel))
-
@property
def ELEMENT(self):
return [0, 1]
-class MotionIPV2(HMBinarySensor, HMSensor):
+class MotionIPV2(HMBinarySensor, HMSensor, HelperLowBatIP, HelperOperatingVoltageIP):
"""Motion detection indoor 55 (rf ip)"""
def __init__(self, device_description, proxy, resolveparamsets=False):
@@ -328,7 +320,7 @@ class MotionIPV2(HMBinarySensor, HMSensor):
# init metadata
self.BINARYNODE.update({"MOTION_DETECTION_ACTIVE": [3], "MOTION": [3]})
self.SENSORNODE.update({"ILLUMINATION": [3]})
- self.ATTRIBUTENODE.update({"LOW_BAT": [0], "ERROR_CODE": [0], "SABOTAGE": [0]})
+ self.ATTRIBUTENODE.update({"ERROR_CODE": [0], "SABOTAGE": [0]})
def is_motion(self, channel=None):
""" Return True if motion is detected """
@@ -341,10 +333,6 @@ class MotionIPV2(HMBinarySensor, HMSensor):
""" Return brightness from 0 (dark) to 163830 (bright) """
return float(self.getSensorData("ILLUMINATION", channel))
- def low_batt(self, channel=None):
- """ Returns if the battery is low. """
- return self.getAttributeData("LOW_BAT", channel)
-
def sabotage(self, channel=None):
"""Returns True if the devicecase has been opened."""
return bool(self.getAttributeData("SABOTAGE", channel))
|
MotionIP + MotionIPV2 cleanup and OPERATING_VOLTAGE support, removed obsolete Sabotage in MotionIP
Added operating voltage support and removed obsolete Sabotage in MotionIP
|
danielperna84_pyhomematic
|
train
|
c20d165e29fa486a56f13477df414f4c2f72b66b
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -13,11 +13,12 @@ setup(
url = "http://wiki.github.com/pteichman/cobe/",
description = "Markov chain based text generator library and chatbot",
packages = ["cobe"],
- test_suite = "tests",
+ test_suite = "unittest2.collector",
setup_requires = [
+ "coverage==3.5.2",
"nose==1.1.2",
- "coverage==3.5"
+ "unittest2==0.5.1"
],
install_requires = [
|
Require unittest2 <I> and coverage <I>
|
pteichman_cobe
|
train
|
4663e2814b359b0719d978d63cebba4d65adddb7
|
diff --git a/lib/basic_app/actions/base_action.rb b/lib/basic_app/actions/base_action.rb
index <HASH>..<HASH> 100644
--- a/lib/basic_app/actions/base_action.rb
+++ b/lib/basic_app/actions/base_action.rb
@@ -119,9 +119,12 @@ module BasicApp
filters += options[:filter] if options[:filter]
result = result.merge(:filter => filters) unless filters.empty?
- # TODO: do not hard code folder key in configuration
+ type = options[:type] || :app_asset
+ attributes_key = "#{type.to_s}s".to_sym
+ result = result.merge(:type => type)
+
# optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified
- result = result.merge(:assets_folder => configuration[:folders][:app_assets]) if configuration[:folders]
+ result = result.merge(:assets_folder => configuration[:folders][attributes_key]) if configuration[:folders]
# optional key: :base_folder is the folder that contains the main config file
result = result.merge(:base_folder => File.dirname(configuration[:configuration_filename]))
diff --git a/lib/basic_app/actions/list_action.rb b/lib/basic_app/actions/list_action.rb
index <HASH>..<HASH> 100644
--- a/lib/basic_app/actions/list_action.rb
+++ b/lib/basic_app/actions/list_action.rb
@@ -77,12 +77,6 @@ module BasicApp
end
end
- def asset_options
- result = super
- result = result.merge(:type => :app_asset) unless options[:type]
- result
- end
-
def render
# templates override all other modes, if no mode specified, allow super to handle
list_mode = options[:template] || options[:list]
diff --git a/lib/basic_app/assets/base_asset.rb b/lib/basic_app/assets/base_asset.rb
index <HASH>..<HASH> 100644
--- a/lib/basic_app/assets/base_asset.rb
+++ b/lib/basic_app/assets/base_asset.rb
@@ -23,14 +23,14 @@ module BasicApp
# Call with classname to create. Pass in optional configuration folder
# name and/or a hash of attributes
#
- # @param [String] klassname (AppAsset) classname to initialize
+ # @param [String] asset_type (AppAsset) classname to initialize
# @param [String] asset_name (nil) asset name or folder name, if folder, will load YAML config
# @param [Hash] attributes ({}) initial attributes
#
# @return [BaseAsset] the created BaseAsset or decendent asset
- def self.create(klassname, asset_name=nil, attributes={})
- klassname ||= :app_asset
- classified_name = klassname.to_s.split('_').collect!{ |w| w.capitalize }.join
+ def self.create(asset_type=:app_asset, asset_name=nil, attributes={})
+ @asset_type = asset_type
+ classified_name = asset_type.to_s.split('_').collect!{ |w| w.capitalize }.join
Object.const_get('BasicApp').const_get(classified_name).new(asset_name, attributes)
end
@@ -48,6 +48,10 @@ module BasicApp
end
end
+ def asset_type
+ @asset_type ||= :app_asset
+ end
+
def configuration
@configuration ||= BasicApp::AssetConfiguration.new(self)
end
|
don't hard-code asset folder hash key
|
robertwahler_repo_manager
|
train
|
3d77198d96fa152f4f30220e519b149f977881dd
|
diff --git a/packages/ringcentral-widgets/modules/CallLogSection/getCallLogSectionReducer.js b/packages/ringcentral-widgets/modules/CallLogSection/getCallLogSectionReducer.js
index <HASH>..<HASH> 100644
--- a/packages/ringcentral-widgets/modules/CallLogSection/getCallLogSectionReducer.js
+++ b/packages/ringcentral-widgets/modules/CallLogSection/getCallLogSectionReducer.js
@@ -1,4 +1,4 @@
-import * as R from 'ramda';
+import { assoc } from 'ramda';
import { combineReducers } from 'redux';
import getModuleStatusReducer from 'ringcentral-integration/lib/getModuleStatusReducer';
@@ -6,9 +6,9 @@ function getCallsSavingStatusReducer(types) {
return (state = {}, { type, identify }) => {
switch (type) {
case types.saving:
- return R.assoc(identify, true, state);
+ return assoc(identify, true, state);
case types.saveSuccess: case types.saveError:
- return R.assoc(identify, false, state);
+ return assoc(identify, false, state);
case types.cleanUp:
return {};
default:
diff --git a/packages/ringcentral-widgets/modules/CallLogSection/index.js b/packages/ringcentral-widgets/modules/CallLogSection/index.js
index <HASH>..<HASH> 100644
--- a/packages/ringcentral-widgets/modules/CallLogSection/index.js
+++ b/packages/ringcentral-widgets/modules/CallLogSection/index.js
@@ -1,4 +1,13 @@
-import * as R from 'ramda';
+import {
+ assoc,
+ converge,
+ flip,
+ identity,
+ keys,
+ mergeWith,
+ pick,
+ useWith,
+} from 'ramda';
import RcModule from 'ringcentral-integration/lib/RcModule';
import { Module } from 'ringcentral-integration/lib/di';
import ensureExist from 'ringcentral-integration/lib/ensureExist';
@@ -17,7 +26,7 @@ export default class CallLogSection extends RcModule {
constructor(
{
storage,
- ...options,
+ ...options
}
) {
super(
@@ -118,8 +127,8 @@ export default class CallLogSection extends RcModule {
onError
}
) {
- this._logFunction = this::ensureExist(logFunction, 'logFunction');
- this._readyCheckFunction = this::ensureExist(readyCheckFunction, 'readyCheckFunction');
+ this._logFunction = this:: ensureExist(logFunction, 'logFunction');
+ this._readyCheckFunction = this:: ensureExist(readyCheckFunction, 'readyCheckFunction');
this._onUpdate = onUpdate;
this._onSuccess = onSuccess;
this._onError = onError;
@@ -135,8 +144,8 @@ export default class CallLogSection extends RcModule {
async saveCallLog(identify, ...args) {
if (identify && (
- !this.callsMapping[identify] || !this.callsMapping[identify].isSaving
- )) {
+ !this.callsMapping[identify] || !this.callsMapping[identify].isSaving
+ )) {
this.store.dispatch({
type: this.actionTypes.saving,
identify,
@@ -154,6 +163,7 @@ export default class CallLogSection extends RcModule {
console.warn(e);
}
}
+ return null;
}
handleLogSection(identify) {
@@ -203,7 +213,7 @@ export default class CallLogSection extends RcModule {
expandLogNotification() {
if (!this.show) {
this._showLogSection(this.currentNotificationIdentify);
- this.closeLogNotification()
+ this.closeLogNotification();
} else if (!this.notificationIsExpand) {
this.store.dispatch({
type: this.actionTypes.expandNotification
@@ -225,9 +235,9 @@ export default class CallLogSection extends RcModule {
callsMapping = createSelector(
() => this._callsMapping,
() => this._callsSavingStatus,
- R.converge(
- R.mergeWith(R.flip(R.assoc('isSaving'))),
- [R.identity, R.useWith(R.pick, [R.keys, R.identity])]
+ converge(
+ mergeWith(flip(assoc('isSaving'))),
+ [identity, useWith(pick, [keys, identity])]
)
)
|
[refactor] Refactor some ramda use to only import necessary functions (#<I>)
|
ringcentral_ringcentral-js-widgets
|
train
|
3de19c57eca9864ca0142a643698e5ff2e73b39e
|
diff --git a/dask_ml/_partial.py b/dask_ml/_partial.py
index <HASH>..<HASH> 100644
--- a/dask_ml/_partial.py
+++ b/dask_ml/_partial.py
@@ -168,7 +168,7 @@ def fit(model, x, y, compute=True, **kwargs):
assert x.chunks[0] == y.chunks[0]
assert hasattr(model, 'partial_fit')
if len(x.chunks[1]) > 1:
- x = x.reblock(chunks=(x.chunks[0], sum(x.chunks[1])))
+ x = x.rechunk(chunks=(x.chunks[0], sum(x.chunks[1])))
nblocks = len(x.chunks[0])
@@ -204,7 +204,7 @@ def predict(model, x):
"""
assert x.ndim == 2
if len(x.chunks[1]) > 1:
- x = x.reblock(chunks=(x.chunks[0], sum(x.chunks[1])))
+ x = x.rechunk(chunks=(x.chunks[0], sum(x.chunks[1])))
func = partial(_predict, model)
xx = np.zeros((1, x.shape[1]), dtype=x.dtype)
dt = model.predict(xx).dtype
diff --git a/tests/test_partial.py b/tests/test_partial.py
index <HASH>..<HASH> 100644
--- a/tests/test_partial.py
+++ b/tests/test_partial.py
@@ -1,8 +1,10 @@
from sklearn.linear_model import SGDClassifier
import numpy as np
import dask
-from dask_ml._partial import fit, predict
import dask.array as da
+from dask_ml._partial import fit, predict
+from dask_ml.datasets import make_classification
+from dask_ml.wrappers import Incremental
x = np.array([[1, 0],
@@ -28,7 +30,7 @@ Z = da.from_array(z, chunks=(2, 2))
def test_fit():
with dask.config.set(scheduler='single-threaded'):
- sgd = SGDClassifier()
+ sgd = SGDClassifier(max_iter=5)
sgd = fit(sgd, X, Y, classes=np.array([-1, 0, 1]))
@@ -36,3 +38,14 @@ def test_fit():
result = predict(sgd, Z)
assert result.chunks == ((2, 2),)
assert result.compute().tolist() == sol.tolist()
+
+
+def test_fit_rechunking():
+ n_classes = 2
+ X, y = make_classification(chunks=20, n_classes=n_classes)
+ X = X.rechunk({1: 10})
+
+ assert X.numblocks[1] > 1
+
+ clf = Incremental(SGDClassifier(max_iter=5))
+ clf.fit(X, y, classes=list(range(n_classes)))
|
fix: outstanding occurrences of reblock replaced with rechunk (#<I>)
|
dask_dask-ml
|
train
|
aa7e862894f1ec2e7b8d596db9e2b208830b35f2
|
diff --git a/node.js b/node.js
index <HASH>..<HASH> 100644
--- a/node.js
+++ b/node.js
@@ -267,7 +267,8 @@ export class InlineNode extends Node {
export class TextNode extends InlineNode {
constructor(type, attrs, content, styles) {
- if (typeof content != "string") throw new Error("Passing non-string as text node content")
+ if (typeof content != "string" || !content)
+ throw new Error("Text node content must be a non-empty string")
super(type, attrs, null, styles)
this.text = content
}
|
Fix text parser creating empty text nodes
Issue #<I>
|
ProseMirror_prosemirror-model
|
train
|
e9e5e0ade954e997890bc0321b45550572e6631b
|
diff --git a/src/OneSignal.php b/src/OneSignal.php
index <HASH>..<HASH> 100644
--- a/src/OneSignal.php
+++ b/src/OneSignal.php
@@ -114,6 +114,8 @@ class OneSignal
* @param string $name
*
* @return object
+ *
+ * @throws OneSignalException If an invalid option name is given
*/
public function __get($name)
{
@@ -131,8 +133,6 @@ class OneSignal
$trace = debug_backtrace();
- $error = 'Undefined property via __get(): %s in %s on line %u';
-
- trigger_error(sprintf($error, $name, $trace[0]['file'], $trace[0]['line']), E_USER_NOTICE);
+ throw new OneSignalException(sprintf('Undefined property via __get(): %s in %s on line %u', $name, $trace[0]['file'], $trace[0]['line']));
}
}
|
Throw exception instead of trigger error in __get
|
norkunas_onesignal-php-api
|
train
|
20e39be24d8b81d0bba79ebc888efc75fdda10f8
|
diff --git a/project/library/CM/File/Javascript.php b/project/library/CM/File/Javascript.php
index <HASH>..<HASH> 100644
--- a/project/library/CM/File/Javascript.php
+++ b/project/library/CM/File/Javascript.php
@@ -53,4 +53,8 @@ class CM_File_Javascript extends CM_File {
$indentation = str_repeat("\t", (int) $indentation);
return $indentation . '/** ' . $doc . ' */';
}
+
+ public function minify() {
+ return CM_Util::exec('uglifyjs ' . $this->getPath());
+ }
}
diff --git a/project/library/CM/Response/Resource/JS.php b/project/library/CM/Response/Resource/JS.php
index <HASH>..<HASH> 100644
--- a/project/library/CM/Response/Resource/JS.php
+++ b/project/library/CM/Response/Resource/JS.php
@@ -59,7 +59,10 @@ class CM_Response_Resource_JS extends CM_Response_Resource_Abstract {
foreach ($paths as $path) {
$content .= new CM_File($path);
}
- return $content;
+
+ /** @var $file CM_File_Javascript */
+ $file = CM_File_Javascript::create(DIR_TMP . 'internal.js', $content);
+ return $file->minify();
}
public static function match(CM_Request_Abstract $request) {
|
t<I>: Minification added to /internal.js response
|
cargomedia_cm
|
train
|
23ce3f4227d247c980c4f9264e01e32ea339eb91
|
diff --git a/examples/autonomousSequence.py b/examples/autonomousSequence.py
index <HASH>..<HASH> 100644
--- a/examples/autonomousSequence.py
+++ b/examples/autonomousSequence.py
@@ -127,8 +127,6 @@ def start_position_printing(scf):
def run_sequence(scf, sequence):
cf = scf.cf
- cf.param.set_value('flightmode.posSet', '1')
-
for position in sequence:
print('Setting position {}'.format(position))
for i in range(50):
diff --git a/examples/positioning/initial_position.py b/examples/positioning/initial_position.py
index <HASH>..<HASH> 100644
--- a/examples/positioning/initial_position.py
+++ b/examples/positioning/initial_position.py
@@ -119,8 +119,6 @@ def reset_estimator(scf):
def run_sequence(scf, sequence, base_x, base_y, base_z, yaw):
cf = scf.cf
- cf.param.set_value('flightmode.posSet', '1')
-
for position in sequence:
print('Setting position {}'.format(position))
diff --git a/examples/swarm/swarmSequence.py b/examples/swarm/swarmSequence.py
index <HASH>..<HASH> 100644
--- a/examples/swarm/swarmSequence.py
+++ b/examples/swarm/swarmSequence.py
@@ -246,11 +246,11 @@ def land(cf, position):
print(vz)
- for i in range(steps):
+ for _ in range(steps):
cf.commander.send_velocity_world_setpoint(0, 0, vz, 0)
time.sleep(sleep_time)
- cf.commander.send_setpoint(0, 0, 0, 0)
+ cf.commander.send_stop_setpoint()
# Make sure that the last packet leaves before the link is closed
# since the message queue is not flushed before closing
time.sleep(0.1)
@@ -259,15 +259,15 @@ def land(cf, position):
def run_sequence(scf, sequence):
try:
cf = scf.cf
- cf.param.set_value('flightmode.posSet', '1')
take_off(cf, sequence[0])
for position in sequence:
print('Setting position {}'.format(position))
end_time = time.time() + position[3]
while time.time() < end_time:
- cf.commander.send_setpoint(position[1], position[0], 0,
- int(position[2] * 1000))
+ cf.commander.send_position_setpoint(position[0],
+ position[1],
+ position[2], 0)
time.sleep(0.1)
land(cf, sequence[-1])
except Exception as e:
|
Closes #<I>: Cleanup position setpoint in examples
|
bitcraze_crazyflie-lib-python
|
train
|
063711f2eb530d08a9869ca6662ac3c847dd1631
|
diff --git a/docido_sdk/scripts/dcc_run.py b/docido_sdk/scripts/dcc_run.py
index <HASH>..<HASH> 100644
--- a/docido_sdk/scripts/dcc_run.py
+++ b/docido_sdk/scripts/dcc_run.py
@@ -1,7 +1,9 @@
+from contextlib import contextmanager
import logging
from optparse import OptionParser
import pickle
from pickle import PickleError
+import sys
from .. import loader
from ..env import env
@@ -27,17 +29,6 @@ import docido_sdk.config as docido_config
from ..toolbox.collections_ext import Configuration
-class YamlAPIConfigurationProvider(Component):
- implements(IndexAPIConfigurationProvider)
-
- def get_index_api_conf(self, service, docido_user_id, account_login):
- return {
- 'service': service,
- 'docido_user_id': docido_user_id,
- 'account_login': account_login
- }
-
-
def oauth_tokens_from_file(full=True, config=None):
crawlers = Configuration.from_env('DOCIDO_CC_RUNS', '.dcc-runs.yml',
Configuration())
@@ -102,7 +93,9 @@ class LocalRunner(Component):
self.run(logger, config, c)
-def parse_options(*args):
+def parse_options(args=None):
+ if args is None:
+ args = sys.argv[1:]
parser = OptionParser()
parser.add_option(
'-i',
@@ -117,7 +110,7 @@ def parse_options(*args):
help='set verbosity level',
default=0
)
- (options, args) = parser.parse_args()
+ return parser.parse_args(args)
def configure_loggers(verbose):
@@ -136,18 +129,35 @@ def configure_loggers(verbose):
logging.getLogger(l).setLevel(logging.WARNING)
-def get_crawls_runner():
- loader.load_components(env)
- env[YamlPullCrawlersIndexingConfig]
- env[Elasticsearch]
- env[CheckProcessor]
- env[IndexPipelineProvider]
- env[LocalKV]
- env[LocalDumbIndex]
- return env[LocalRunner]
-
-
-def run(*args):
- options, args = parse_options(*args)
+@contextmanager
+def get_crawls_runner(environment=None):
+
+ class YamlAPIConfigurationProvider(Component):
+ implements(IndexAPIConfigurationProvider)
+
+ def get_index_api_conf(self, service, docido_user_id, account_login):
+ return {
+ 'service': service,
+ 'docido_user_id': docido_user_id,
+ 'account_login': account_login
+ }
+ try:
+ environment = environment or env
+ loader.load_components(environment)
+ from docido_sdk.core import ComponentMeta
+ environment[YamlPullCrawlersIndexingConfig]
+ environment[Elasticsearch]
+ environment[CheckProcessor]
+ environment[IndexPipelineProvider]
+ environment[LocalKV]
+ environment[LocalDumbIndex]
+ yield env[LocalRunner]
+ finally:
+ YamlAPIConfigurationProvider.unregister()
+
+
+def run(args=None, environment=None):
+ options, args = parse_options(args)
configure_loggers(options.verbose)
- get_crawls_runner.run_all(full=not options.incremental)
+ with get_crawls_runner(environment) as runner:
+ runner.run_all(full=not options.incremental)
|
Fixed dcc-run
* custom args were not taken into account
* lazy definition of `YamlAPIConfigurationProvider`,
popped from environment when no longer required.
|
cogniteev_docido-python-sdk
|
train
|
d2bfcb33c44d5c931e7fc9694787f3eba0723d3f
|
diff --git a/js/chips.js b/js/chips.js
index <HASH>..<HASH> 100644
--- a/js/chips.js
+++ b/js/chips.js
@@ -313,3 +313,4 @@
this.handleEvents();
};
}( jQuery ));
+// end
|
triggwr new Travis build
|
Dogfalo_materialize
|
train
|
2030582e7cc2be689e6f538176b752fc2169d8ab
|
diff --git a/lib/letsencrypt.js b/lib/letsencrypt.js
index <HASH>..<HASH> 100644
--- a/lib/letsencrypt.js
+++ b/lib/letsencrypt.js
@@ -38,17 +38,25 @@ function init(certPath, port, logger){
webrootPath: webrootPath,
debug: false
- }
+ };
// we need to proxy for example: 'example.com/.well-known/acme-challenge' -> 'localhost:port/example.com/'
http.createServer(function (req, res){
var uri = url.parse(req.url).pathname;
var filename = path.join(certPath, uri);
+ var isForbiddenPath = uri.length < 3 || filename.indexOf(certPath) !== 0;
+
+ if (isForbiddenPath) {
+ logger && logger.info('Forbidden request on LetsEncrypt port %s: %s', port, filename);
+ res.writeHead(403);
+ res.end();
+ return;
+ }
logger && logger.info('LetsEncrypt CA trying to validate challenge %s', filename);
- fs.exists(filename, function(exists) {
- if (!exists){
+ fs.stat(filename, function(err, stats) {
+ if (err || !stats.isFile()) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404 Not Found\n");
res.end();
@@ -58,6 +66,7 @@ function init(certPath, port, logger){
res.writeHead(200);
fs.createReadStream(filename, "binary").pipe(res);
});
+
}).listen(port);
}
|
fixed: GET / on LetEncrypt port crashes proxy
|
OptimalBits_redbird
|
train
|
c3828f01d84b1afd13a4b52a8e125b7421f34892
|
diff --git a/notrequests.py b/notrequests.py
index <HASH>..<HASH> 100644
--- a/notrequests.py
+++ b/notrequests.py
@@ -102,9 +102,9 @@ class Response(object):
return {c.name: c.value for c in cookies}
- def json(self):
+ def json(self, **kwargs):
"""Decodes response as JSON."""
- return simplejson.loads(self.content)
+ return simplejson.loads(self.content, **kwargs)
class HTTPErrorHandler(urllib2.HTTPDefaultErrorHandler):
|
Response.json(..) takes keyword arguments.
The keyword arguments are passed through to the underlying json.loads(..) call.
This is what Requests does.
|
davidwtbuxton_notrequests
|
train
|
3da06de125c394713a52c00adf18470892b63e3b
|
diff --git a/src/main/java/jcifs/internal/smb1/trans/nt/FileNotifyInformationImpl.java b/src/main/java/jcifs/internal/smb1/trans/nt/FileNotifyInformationImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/jcifs/internal/smb1/trans/nt/FileNotifyInformationImpl.java
+++ b/src/main/java/jcifs/internal/smb1/trans/nt/FileNotifyInformationImpl.java
@@ -84,6 +84,10 @@ public class FileNotifyInformationImpl implements FileNotifyInformation, Decodab
@Override
public int decode ( byte[] buffer, int bufferIndex, int len ) throws SMBProtocolDecodingException {
+ if (len == 0) {
+ // nothing to do
+ return 0;
+ }
int start = bufferIndex;
this.nextEntryOffset = SMBUtil.readInt4(buffer, bufferIndex);
|
support empty notification (can happen if server decides)
|
AgNO3_jcifs-ng
|
train
|
97627d2783f1df24a43edb75c3c94b1e0da8b64a
|
diff --git a/mod/feedback/view.php b/mod/feedback/view.php
index <HASH>..<HASH> 100644
--- a/mod/feedback/view.php
+++ b/mod/feedback/view.php
@@ -139,7 +139,7 @@ if ($feedbackcompletion->can_complete()) {
} else {
$label = get_string('complete_the_form', 'feedback');
}
- echo html_writer::div(html_writer::link($completeurl, $label), 'complete-feedback');
+ echo html_writer::div(html_writer::link($completeurl, $label, array('class' => 'btn btn-default')), 'complete-feedback');
} else {
// Feedback was already submitted.
echo $OUTPUT->notification(get_string('this_feedback_is_already_submitted', 'feedback'));
|
MDL-<I> feedback: add button style for "Answer the questions" link.
|
moodle_moodle
|
train
|
30c3ea6b0536067f67a8309d0800ff8e8b9c3558
|
diff --git a/src/resources/assets/buttons.server-side.js b/src/resources/assets/buttons.server-side.js
index <HASH>..<HASH> 100644
--- a/src/resources/assets/buttons.server-side.js
+++ b/src/resources/assets/buttons.server-side.js
@@ -1,6 +1,64 @@
(function ($, DataTable) {
"use strict";
+ var _buildParams = function (dt, action) {
+ var params = dt.ajax.params();
+ params.action = action;
+ params._token = $.fn.dataTable.defaults.csrf_token;
+
+ return params;
+ };
+
+ var _downloadFromUrl = function (url, params) {
+ var postUrl = url + '/export';
+ var xhr = new XMLHttpRequest();
+ xhr.open('POST', postUrl, true);
+ xhr.responseType = 'arraybuffer';
+ xhr.onload = function () {
+ if (this.status === 200) {
+ var filename = "";
+ var disposition = xhr.getResponseHeader('Content-Disposition');
+ if (disposition && disposition.indexOf('attachment') !== -1) {
+ var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
+ var matches = filenameRegex.exec(disposition);
+ if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
+ }
+ var type = xhr.getResponseHeader('Content-Type');
+
+ var blob = new Blob([this.response], {type: type});
+ if (typeof window.navigator.msSaveBlob !== 'undefined') {
+ // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
+ window.navigator.msSaveBlob(blob, filename);
+ } else {
+ var URL = window.URL || window.webkitURL;
+ var downloadUrl = URL.createObjectURL(blob);
+
+ if (filename) {
+ // use HTML5 a[download] attribute to specify filename
+ var a = document.createElement("a");
+ // safari doesn't support this yet
+ if (typeof a.download === 'undefined') {
+ window.location = downloadUrl;
+ } else {
+ a.href = downloadUrl;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ }
+ } else {
+ window.location = downloadUrl;
+ }
+
+ setTimeout(function () {
+ URL.revokeObjectURL(downloadUrl);
+ }, 100); // cleanup
+ }
+ }
+ };
+ xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
+ xhr.send($.param(params));
+ };
+
var _buildUrl = function(dt, action) {
var url = dt.ajax.url() || '';
var params = dt.ajax.params();
@@ -51,6 +109,21 @@
}
};
+ DataTable.ext.buttons.exportPostCsv = {
+ className: 'buttons-csv',
+
+ text: function (dt) {
+ return '<i class="fa fa-file-excel-o"></i> ' + dt.i18n('buttons.csv', 'CSV');
+ },
+
+ action: function (e, dt, button, config) {
+ var url = dt.ajax.url() || window.location.href;
+ var params = _buildParams(dt, 'csv');
+
+ _downloadFromUrl(url, params);
+ }
+ };
+
DataTable.ext.buttons.pdf = {
className: 'buttons-pdf',
|
Add export CSV with post as a method.
|
yajra_laravel-datatables-buttons
|
train
|
d41648fca5ed041d8115b86965286c2d3a52214a
|
diff --git a/contrib/externs/angular-1.5.js b/contrib/externs/angular-1.5.js
index <HASH>..<HASH> 100644
--- a/contrib/externs/angular-1.5.js
+++ b/contrib/externs/angular-1.5.js
@@ -21,7 +21,6 @@
* $cookieStore
* $httpBackend
* $rootElement
- * $rootScope
*
* @see http://angularjs.org/
* @externs
@@ -925,7 +924,10 @@ angular.Module.prototype.name;
*/
angular.Module.prototype.requires;
-/** @constructor */
+/**
+ * NOTE: $rootScope is the same as angular.Scope.
+ * @constructor
+ */
angular.Scope = function() {};
/** @type {?string} */
|
angular.$rootScope is the same as angular.Scope. Removes TODO and adds note
about the alias.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
f3964d209333a541b3dddd3f474fd25775a19ca6
|
diff --git a/libraries/common/streams/router.js b/libraries/common/streams/router.js
index <HASH>..<HASH> 100644
--- a/libraries/common/streams/router.js
+++ b/libraries/common/streams/router.js
@@ -38,8 +38,10 @@ export const routeWillLeave$ = main$
export const routeDidLeave$ = main$
.filter(({ action }) => action.type === ROUTE_DID_LEAVE);
- /**
+// TODO: fix or remove
+/**
* @type {Observable}
+ * @deprecated use routeDidEnter$
*/
export const routeDidChange$ = routeWillEnter$
.merge(routeDidEnter$)
diff --git a/libraries/tracking/streams/pages.js b/libraries/tracking/streams/pages.js
index <HASH>..<HASH> 100644
--- a/libraries/tracking/streams/pages.js
+++ b/libraries/tracking/streams/pages.js
@@ -1,4 +1,4 @@
-import { routeDidChange$ } from '@shopgate/pwa-common/streams/router';
+import { routeDidEnter$ } from '@shopgate/pwa-common/streams/router';
import { SEARCH_PATH } from '@shopgate/pwa-common-commerce/search/constants';
import { CATEGORY_PATH } from '@shopgate/pwa-common-commerce/category/constants';
import { ITEM_PATH } from '@shopgate/pwa-common-commerce/product/constants';
@@ -22,9 +22,10 @@ export const blacklistedPaths = [
/**
* Emits when one of the tracked paths is entered except some special one.
*/
-export const pagesAreReady$ = routeDidChange$
+export const pagesAreReady$ = routeDidEnter$
.filter(() => isPWAVisible())
.merge(pwaDidAppear$)
- .filter(({ pathname }) => (
- !blacklistedPaths.some(path => (!pathname ? false : pathname.startsWith(path)))
- ));
+ .filter(({ action }) => {
+ const { pathname } = action.route;
+ return !blacklistedPaths.some(path => (!pathname ? false : pathname.startsWith(path)));
+ });
|
PWA-<I> re-activated cart tracking
|
shopgate_pwa
|
train
|
b2b018fac413b8a6d392098c74e35432272e5b14
|
diff --git a/domain.go b/domain.go
index <HASH>..<HASH> 100644
--- a/domain.go
+++ b/domain.go
@@ -1556,7 +1556,7 @@ func (a *DomainAddressSpaprVIO) MarshalXML(e *xml.Encoder, start xml.StartElemen
start.Attr = append(start.Attr, xml.Attr{
xml.Name{Local: "type"}, "spapr-vio",
})
- marshallUint64Attr(&start, "reg", a.Reg, "%x")
+ marshallUint64Attr(&start, "reg", a.Reg, "0x%x")
e.EncodeToken(start)
e.EncodeToken(start.End())
return nil
|
Fix hex formatting of spapr-vio address reg
|
libvirt_libvirt-go-xml
|
train
|
2218b90d786e74026f65565d85e8b611de83eefd
|
diff --git a/webapps/webapp/src/main/webapp/app/cockpit/pages/jobRetries.js b/webapps/webapp/src/main/webapp/app/cockpit/pages/jobRetries.js
index <HASH>..<HASH> 100644
--- a/webapps/webapp/src/main/webapp/app/cockpit/pages/jobRetries.js
+++ b/webapps/webapp/src/main/webapp/app/cockpit/pages/jobRetries.js
@@ -22,8 +22,8 @@ ngDefine('cockpit.pages', function(module, $) {
SUCCESS = 'successful',
FAILED = 'failed';
- var executionIdToInstanceMap = jobRetriesData.observe('executionIdToInstanceMap', function (executionIdToInstanceMap) {
- executionIdToInstanceMap = executionIdToInstanceMap;
+ var executionIdToInstanceMap = jobRetriesData.observe('executionIdToInstanceMap', function (executionMap) {
+ executionIdToInstanceMap = executionMap;
});
$scope.$on('$routeChangeStart', function () {
|
fix(jobs): Show activity scope in jobs table
|
camunda_camunda-bpm-platform
|
train
|
ca3b8e30af9a65c0e6beba91d2f2088b449bfaa5
|
diff --git a/couchrest_model.gemspec b/couchrest_model.gemspec
index <HASH>..<HASH> 100644
--- a/couchrest_model.gemspec
+++ b/couchrest_model.gemspec
@@ -25,7 +25,7 @@ Gem::Specification.new do |s|
s.add_dependency(%q<couchrest>, "~> 1.1.2")
s.add_dependency(%q<mime-types>, "~> 1.15")
- s.add_dependency(%q<activemodel>, "~> 3.1.0")
+ s.add_dependency(%q<activemodel>, "~> 3.2.0")
s.add_dependency(%q<tzinfo>, "~> 0.3.22")
s.add_development_dependency(%q<rspec>, "~> 2.6.0")
s.add_development_dependency(%q<json>, ["~> 1.5.1"])
diff --git a/lib/couchrest/model/base.rb b/lib/couchrest/model/base.rb
index <HASH>..<HASH> 100644
--- a/lib/couchrest/model/base.rb
+++ b/lib/couchrest/model/base.rb
@@ -2,7 +2,8 @@ module CouchRest
module Model
class Base < CouchRest::Document
- extend ActiveModel::Naming
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
include CouchRest::Model::Configuration
include CouchRest::Model::Connection
diff --git a/spec/unit/dirty_spec.rb b/spec/unit/dirty_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/dirty_spec.rb
+++ b/spec/unit/dirty_spec.rb
@@ -33,11 +33,22 @@ describe "Dirty" do
describe "changes" do
- it "should return changes on an attribute" do
- @card = Card.new(:first_name => "matt")
- @card.first_name = "andrew"
- @card.first_name_changed?.should be_true
- @card.changes.should == { "first_name" => ["matt", "andrew"] }
+ context "when new record" do
+ it "should return changes on an attribute" do
+ @card = Card.new(:first_name => "matt")
+ @card.first_name = "andrew"
+ @card.first_name_changed?.should be_true
+ @card.changes.should == { "first_name" => [nil, "andrew"] }
+ end
+ end
+
+ context "when persisted" do
+ it "should return changes on an attribute" do
+ @card = Card.create!(:first_name => "matt")
+ @card.first_name = "andrew"
+ @card.first_name_changed?.should be_true
+ @card.changes.should == { "first_name" => ["matt", "andrew"] }
+ end
end
end
|
Ensure ActiveModel <I>.x compatibility
|
couchrest_couchrest_model
|
train
|
b823b8691efd551c090bcdf006d7958d50568d70
|
diff --git a/tests/test_dummypi.py b/tests/test_dummypi.py
index <HASH>..<HASH> 100644
--- a/tests/test_dummypi.py
+++ b/tests/test_dummypi.py
@@ -17,7 +17,7 @@ def setup_module():
# call os.setsid so that all subprocesses terminate when the
# main process receives SIGTERM
- DAEMON = subprocess.Popen(['databench', '--with-coverage'],
+ DAEMON = subprocess.Popen(['databench', '--with-coverage', '--log=INFO'],
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
|
launch databench with --log=INFO in tests
|
svenkreiss_databench
|
train
|
4861be53c7484b558683231e61e1852a2107050f
|
diff --git a/hydpy/models/dam/dam_model.py b/hydpy/models/dam/dam_model.py
index <HASH>..<HASH> 100644
--- a/hydpy/models/dam/dam_model.py
+++ b/hydpy/models/dam/dam_model.py
@@ -138,10 +138,14 @@ def calc_naturalremotedischarge_v1(self):
Basic equation:
:math:`RemoteDemand =
- \\frac{\\Sigma(LoggedTotalRemoteDischarge - LoggedOutflow)}
- {NmbLogEntries})`
+ max(\\frac{\\Sigma(LoggedTotalRemoteDischarge - LoggedOutflow)}
+ {NmbLogEntries}), 0)`
- Example:
+ Examples:
+
+ Usually, the mean total remote flow should be larger than the mean
+ dam outflows. Then the estimated natural remote discharge is simply
+ the difference of both mean values::
>>> from hydpy.models.dam import *
>>> parameterstep()
@@ -152,6 +156,15 @@ def calc_naturalremotedischarge_v1(self):
>>> fluxes.naturalremotedischarge
naturalremotedischarge(1.0)
+ Due to the wave travel times, the difference between remote discharge
+ and dam outflow mights sometimes be negative. To avoid negative
+ estimates of natural discharge, it its value is set to zero in
+ such cases:
+
+ >>> logs.loggedoutflow(4.0, 3.0, 5.0)
+ >>> model.calc_naturalremotedischarge_v1()
+ >>> fluxes.naturalremotedischarge
+ naturalremotedischarge(0.0)
"""
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
@@ -160,7 +173,10 @@ def calc_naturalremotedischarge_v1(self):
for idx in range(con.nmblogentries):
flu.naturalremotedischarge += (
log.loggedtotalremotedischarge[idx] - log.loggedoutflow[idx])
- flu.naturalremotedischarge /= con.nmblogentries
+ if flu.naturalremotedischarge > 0.:
+ flu.naturalremotedischarge /= con.nmblogentries
+ else:
+ flu.naturalremotedischarge = 0.
def calc_remotedemand_v1(self):
|
Disallow negative estimates of the `natural remote discharge` of the dam model.
For now, this seems to be an improvement. However, this commit results in a discontinuity in the set of process equations. Hence it might not fit perfectly to the dam model and should be revised critically during integration testing.
|
hydpy-dev_hydpy
|
train
|
c741e69e79049cfbe155a4351eb0bc056c404b21
|
diff --git a/hazelcast-client/src/test/java/com/hazelcast/client/map/ClientMapIssueTest.java b/hazelcast-client/src/test/java/com/hazelcast/client/map/ClientMapIssueTest.java
index <HASH>..<HASH> 100644
--- a/hazelcast-client/src/test/java/com/hazelcast/client/map/ClientMapIssueTest.java
+++ b/hazelcast-client/src/test/java/com/hazelcast/client/map/ClientMapIssueTest.java
@@ -31,6 +31,7 @@ import com.hazelcast.spi.EventService;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
+import com.hazelcast.test.annotation.ProblematicTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
@@ -59,6 +60,7 @@ public class ClientMapIssueTest extends HazelcastTestSupport {
}
@Test
+ @Category(ProblematicTest.class)
public void testListenerRegistrations() throws Exception {
HazelcastInstance instance = Hazelcast.newHazelcastInstance();
final HazelcastInstance client = HazelcastClient.newHazelcastClient();
|
mark testListenerRegistrations as problematic
|
hazelcast_hazelcast
|
train
|
62b6b9ab7bc2580dd5d684ace7e29c23e16c37dd
|
diff --git a/selene/elements.py b/selene/elements.py
index <HASH>..<HASH> 100644
--- a/selene/elements.py
+++ b/selene/elements.py
@@ -120,7 +120,7 @@ class InnerListWebElementLocator(ISeleneListWebElementLocator):
def find(self):
# return self._element.get_actual_webelement().find_elements(*self._by)
- return wait_for(self._element, be.visible, config.timeout, config.poll_during_waits)\
+ return wait_for(self._element, be.visible, config.timeout, config.poll_during_waits) \
.find_elements(*self._by)
@@ -155,7 +155,7 @@ class SlicedListWebElementLocator(ISeleneListWebElementLocator):
def description(self):
return "(%s)[%s:%s:%s]" % (self._collection, self._slice.start, self._slice.stop, self._slice.step)
- def __init__(self, slc, collection):
+ def __init__(self, slc, collection):
# type: (slice, SeleneCollection) -> None
self._slice = slc
self._collection = collection
@@ -193,7 +193,6 @@ def _wait_with_screenshot(entity, condition, timeout=None, polling=None):
class SeleneElement(with_metaclass(DelegatingMeta, IWebElement)):
-
@property
def __delegate__(self):
# type: () -> IWebElement
@@ -259,6 +258,7 @@ class SeleneElement(with_metaclass(DelegatingMeta, IWebElement)):
s = element
find = element
+
# todo: consider making find a separate not-lazy method (not alias)
# to be used in such example: s("#element").hover().find(".inner").click()
# over: s("#element").hover().element(".inner").click()
@@ -343,6 +343,11 @@ class SeleneElement(with_metaclass(DelegatingMeta, IWebElement)):
condition=be.visible)
return self
+ def context_click(self):
+ self._execute_on_webelement(lambda it: self._actions_chains.context_click(it).perform(),
+ condition=be.visible)
+ return self
+
def set(self, new_text_value):
def clear_and_send_keys(webelement):
|
context click added to SeleneElement
|
yashaka_selene
|
train
|
ad6c2e03c69adada97aa4165b67d87bbbee552bf
|
diff --git a/elasticsearch-rails/lib/rails/templates/seeds.rb b/elasticsearch-rails/lib/rails/templates/seeds.rb
index <HASH>..<HASH> 100644
--- a/elasticsearch-rails/lib/rails/templates/seeds.rb
+++ b/elasticsearch-rails/lib/rails/templates/seeds.rb
@@ -3,7 +3,8 @@ require 'yaml'
Zlib::GzipReader.open(File.expand_path('../articles.yml.gz', __FILE__)) do |gzip|
puts "Reading articles from gzipped YAML..."
- @documents = YAML.load_documents(gzip.read)
+ @documents = YAML.respond_to?(:load_documents) ? YAML.load_documents(gzip.read) :
+ YAML.load_stream(gzip.read)
end
# Truncate the default ActiveRecord logger output
|
[RAILS] Fix seeds file to stop using outdated YAML method (#<I>)
The expert template was using the outdated YAML.load_documents, which is no longer present in the newer versions of Ruby.
|
elastic_elasticsearch-rails
|
train
|
79a63e70c4d8b2840383d2a8791e41b6830ca9ad
|
diff --git a/autorest/adal/token.go b/autorest/adal/token.go
index <HASH>..<HASH> 100644
--- a/autorest/adal/token.go
+++ b/autorest/adal/token.go
@@ -1030,9 +1030,11 @@ func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource
resp, err = spt.sender.Do(req)
}
+ // don't return a TokenRefreshError here; this will allow retry logic to apply
if err != nil {
- // don't return a TokenRefreshError here; this will allow retry logic to apply
return fmt.Errorf("adal: Failed to execute the refresh request. Error = '%v'", err)
+ } else if resp == nil {
+ return fmt.Errorf("adal: received nil response and error")
}
logger.Instance.WriteResponse(resp, logger.Filter{Body: authBodyFilter})
|
Return an error if resp and err are nil (#<I>)
This will allow retry logic to kick in and also avoid up-stream panics
due to both the response and the error being nil.
|
Azure_go-autorest
|
train
|
56842dcb2a938613b3902dd4043d2b64125ca46f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -32,9 +32,10 @@ from setuptools import setup
install_requires = [
'six', 'pyscard', 'pyusb', 'click', 'cryptography', 'pyopenssl']
tests_require = []
+if sys.version_info < (3, 3):
+ tests_require.append('mock')
if sys.version_info < (3, 4):
install_requires.append('enum34')
- tests_require.append('mock')
if sys.platform == 'win32':
install_requires.append('pypiwin32')
|
Fix Python version condition for adding mock to tests_require
|
Yubico_yubikey-manager
|
train
|
db170ac3e1ceaefcc702d05175b0460c8ea29169
|
diff --git a/src/Map.php b/src/Map.php
index <HASH>..<HASH> 100644
--- a/src/Map.php
+++ b/src/Map.php
@@ -964,7 +964,7 @@ class Map implements \Countable, Arrayable, Jsonable, \ArrayAccess, \IteratorAgg
* Track hashes we've created for non-string keys.
* @var array
*/
- private $map_key_to_hash = [];
+ private $map_hash_to_key = [];
/**
* Lookup the hash for the given key. If a hash does not yet exist, one is
@@ -976,10 +976,6 @@ class Map implements \Countable, Arrayable, Jsonable, \ArrayAccess, \IteratorAgg
*/
private function key_to_hash($key)
{
- if (array_key_exists($key, $this->map_key_to_hash)) {
- return $this->map_key_to_hash[$key];
- }
-
if (is_float($key) || is_int($key) || is_bool($key)) {
$hash = intval($key);
@@ -1002,7 +998,7 @@ class Map implements \Countable, Arrayable, Jsonable, \ArrayAccess, \IteratorAgg
);
}
- $this->map_key_to_hash[$key] = $hash;
+ $this->map_hash_to_key[$hash] = $key;
return $hash;
}
@@ -1014,16 +1010,14 @@ class Map implements \Countable, Arrayable, Jsonable, \ArrayAccess, \IteratorAgg
*/
private function hash_to_key($hash)
{
- foreach ($this->map_key_to_hash as $key => $candidate) {
- if ($hash === $candidate) {
- return $key;
- }
+ if (array_key_exists($hash, $this->map_hash_to_key)) {
+ return $this->map_hash_to_key[$hash];
+ } else {
+ throw new \OutOfBoundsException(sprintf(
+ 'Hash "%s" has not been created',
+ $hash
+ ));
}
-
- throw new \OutOfBoundsException(sprintf(
- 'Hash "%s" has not been created',
- $hash
- ));
}
/**
diff --git a/tests/MapTest.php b/tests/MapTest.php
index <HASH>..<HASH> 100644
--- a/tests/MapTest.php
+++ b/tests/MapTest.php
@@ -212,6 +212,22 @@ class MapTest extends \PHPUnit_Framework_TestCase
);
}
+ public function test_rekey_with_exotics()
+ {
+ $fds = (new Map(range(0, 2)))->rekey(function ($number) {
+ switch ($number) {
+ case 0: return fopen('php://stdin', 'r');
+ case 1: return fopen('php://stdout', 'w');
+ case 2: return fopen('php://stderr', 'w');
+ }
+ });
+ $this->assertCount(3, $fds);
+ $fds->all(function ($id, $fd) {
+ $this->assertInternalType('int', $id);
+ $this->assertInternalType('resource', $fd);
+ });
+ }
+
public function test_into()
{
$map = new Map();
|
Fixes inability to use non-scalar keys in map
|
haldayne_boost
|
train
|
e4dd90a24bdba1d4fb0cc5c0cb40437f37c64246
|
diff --git a/tests/compression_based.py b/tests/compression_based.py
index <HASH>..<HASH> 100644
--- a/tests/compression_based.py
+++ b/tests/compression_based.py
@@ -12,8 +12,8 @@ class ArithNCDTest(unittest.TestCase):
self.assertEqual(probs['a'][1], Fraction(1, 7))
def test_arith_output(self):
- numerator = self.alg._compress('BANANA')
- self.assertEqual(int(numerator, 2), 1525)
+ fraction = self.alg._compress('BANANA')
+ self.assertEqual(fraction.numerator, 1525)
def test_arith_distance(self):
same = self.alg('test', 'test')
diff --git a/textdistance/algorithms/compression_based.py b/textdistance/algorithms/compression_based.py
index <HASH>..<HASH> 100644
--- a/textdistance/algorithms/compression_based.py
+++ b/textdistance/algorithms/compression_based.py
@@ -1,6 +1,7 @@
import codecs
from itertools import groupby, permutations
from fractions import Fraction
+import math
try:
import lzma
@@ -32,6 +33,9 @@ class _NCDBase(_Base):
def maximum(self, *sequences):
return 1
+ def _get_size(self, data):
+ return len(self._compress(data))
+
def __call__(self, *sequences):
if not sequences:
return 0
@@ -39,15 +43,18 @@ class _NCDBase(_Base):
if isinstance(sequences[0], string_types) and not isinstance(self.empty, string_types):
sequences = [s.encode('utf-8') for s in sequences]
- compressed_lengths = [len(self._compress(s)) for s in sequences]
+ compressed_lengths = [self._get_size(s) for s in sequences]
concat_length = float('Inf')
for data in permutations(sequences):
data = self.empty.join(data)
- concat_length = min(concat_length, len(self._compress(data)))
+ concat_length = min(concat_length, self._get_size(data))
return float(concat_length - min(compressed_lengths)) / max(compressed_lengths)
class ArithNCD(_NCDBase):
+ def __init__(self, base=2):
+ self.base = base
+
def _make_probs(self, *sequences):
"""
https://github.com/gw-c/arith/blob/master/arith.py
@@ -90,7 +97,11 @@ class ArithNCD(_NCDBase):
output_numerator = 1 + ((start.numerator * output_denominator) // start.denominator)
output_fraction = Fraction(output_numerator, output_denominator)
output_denominator *= 2
- return bin(output_fraction.numerator)[2:]
+ return output_fraction
+
+ def _get_size(self, data):
+ numerator = self._compress(data).numerator
+ return math.ceil(math.log(numerator, self.base))
class RLENCD(_NCDBase):
|
set up base for arith ncd
|
orsinium_textdistance
|
train
|
4892d3c64d5525e7f43b62b07a0848428a6f574e
|
diff --git a/spec/fixtures/dummy/app/controllers/admin/pets_controller.rb b/spec/fixtures/dummy/app/controllers/admin/pets_controller.rb
index <HASH>..<HASH> 100644
--- a/spec/fixtures/dummy/app/controllers/admin/pets_controller.rb
+++ b/spec/fixtures/dummy/app/controllers/admin/pets_controller.rb
@@ -6,12 +6,6 @@ module Admin
#
def index
end
-
- # return a Pet
- #
- # @query_parameter [Integer] id The ID for the Pet
- def show
- end
-
+
end
end
|
For consistency, remove the show action from the Admin::PetsController since it wasn't referenced in routes
|
adrian-gomez_swaggard
|
train
|
642a2d96849e7b1029b005752b5a73cabd30bac5
|
diff --git a/src/Message/CompletePurchaseRequest.php b/src/Message/CompletePurchaseRequest.php
index <HASH>..<HASH> 100644
--- a/src/Message/CompletePurchaseRequest.php
+++ b/src/Message/CompletePurchaseRequest.php
@@ -16,7 +16,7 @@ class CompletePurchaseRequest extends PurchaseRequest
$data['transactionId'] = $this->httpRequest->query->get('transactionId');
$data['merchantId'] = $this->getMerchantId();
$data['token'] = $this->getPassword();
- $data['operation'] = 'AUTH';
+ $data['operation'] = 'SALE';
if (empty($data['responseCode']) || empty($data['transactionId'])) {
throw new InvalidResponseException;
|
Update CompletePurchaseRequest.php
operation SALE will charge the card via. capture as well.
AUTH will require to run capture via. other api calls or visiting the netaxept backend.
|
thephpleague_omnipay-netaxept
|
train
|
515132a404c312ee0beb9dd86263c15ce0933788
|
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/Configuration.php
+++ b/DependencyInjection/Configuration.php
@@ -17,7 +17,8 @@ class Configuration implements ConfigurationInterface
->arrayNode('chunks')
->addDefaultsIfNotSet()
->children()
- ->scalarNode('directory')->end()
+ ->booleanNode('enabled')->defaultFalse()->end()
+ ->scalarNode('storage')->defaultNull()->end()
->scalarNode('maxage')->defaultValue(604800)->end()
->end()
->end()
|
Added a switch to globally enable and disable chunks. This is necesseray to determine if a developer should provide a storage service.
|
1up-lab_OneupUploaderBundle
|
train
|
303eebcaff6503394ab8c43f350ab777be1f8800
|
diff --git a/lib/thinking_sphinx/rake_interface.rb b/lib/thinking_sphinx/rake_interface.rb
index <HASH>..<HASH> 100644
--- a/lib/thinking_sphinx/rake_interface.rb
+++ b/lib/thinking_sphinx/rake_interface.rb
@@ -1,5 +1,14 @@
class ThinkingSphinx::RakeInterface
- def clear
+ def clear_all
+ [
+ configuration.indices_location,
+ configuration.searchd.binlog_path
+ ].each do |path|
+ FileUtils.rm_r(path) if File.exists?(path)
+ end
+ end
+
+ def clear_real_time
indices = configuration.indices.select { |index| index.type == 'rt' }
indices.each do |index|
index.render
diff --git a/lib/thinking_sphinx/tasks.rb b/lib/thinking_sphinx/tasks.rb
index <HASH>..<HASH> 100644
--- a/lib/thinking_sphinx/tasks.rb
+++ b/lib/thinking_sphinx/tasks.rb
@@ -14,7 +14,12 @@ namespace :ts do
desc 'Clear out Sphinx files'
task :clear => :environment do
- interface.clear
+ interface.clear_all
+ end
+
+ desc 'Clear out real-time index files'
+ task :clear_rt => :environment do
+ interface.clear_real_time
end
desc 'Generate fresh index files for real-time indices'
@@ -27,7 +32,7 @@ namespace :ts do
task :rebuild => [:stop, :clear, :index, :start]
desc 'Stop Sphinx, clear files, reconfigure, start Sphinx, generate files'
- task :regenerate => [:stop, :clear, :configure, :start, :generate]
+ task :regenerate => [:stop, :clear_rt, :configure, :start, :generate]
desc 'Restart the Sphinx daemon'
task :restart => [:stop, :start]
|
Distinguish between full clear (used by rebuild) and real-time-only clear.
|
pat_thinking-sphinx
|
train
|
d856275de4447e56c9638f2ce399be523618c899
|
diff --git a/library/src/android/support/v4/app/ActionBar.java b/library/src/android/support/v4/app/ActionBar.java
index <HASH>..<HASH> 100644
--- a/library/src/android/support/v4/app/ActionBar.java
+++ b/library/src/android/support/v4/app/ActionBar.java
@@ -37,15 +37,15 @@ public abstract class ActionBar {
private static Class<? extends ActionBar> HANDLER_CUSTOM = ActionBarCustom.class;
- /**
- * Register the custom handler for use with a third-party action bar
- * library on Android versions which do not support a native action bar.
- *
- * @param customHandler Custom handler class.
- */
- public static void registerHandler(Class<? extends ActionBar> customHandler) {
- HANDLER_CUSTOM = customHandler;
- }
+ ///**
+ // * Register the custom handler for use with a third-party action bar
+ // * library on Android versions which do not support a native action bar.
+ // *
+ // * @param customHandler Custom handler class.
+ // */
+ //public static void registerHandler(Class<? extends ActionBar> customHandler) {
+ // HANDLER_CUSTOM = customHandler;
+ //}
/**
* Get an instance of the appropriate handler for an action bar.
|
Remove registering of a custom action bar handler for pre-<I> devices. Other classes are far too specialized at the moment to allow for a custom handler to function properly.
|
JakeWharton_ActionBarSherlock
|
train
|
f6d7052ddc94c24102f79fcda49eebd150615bb1
|
diff --git a/TYPO3.Neos/Classes/TYPO3/Neos/Service/HtmlAugmenter.php b/TYPO3.Neos/Classes/TYPO3/Neos/Service/HtmlAugmenter.php
index <HASH>..<HASH> 100644
--- a/TYPO3.Neos/Classes/TYPO3/Neos/Service/HtmlAugmenter.php
+++ b/TYPO3.Neos/Classes/TYPO3/Neos/Service/HtmlAugmenter.php
@@ -51,7 +51,7 @@ class HtmlAugmenter
return sprintf('<%s%s>%s</%s>', $fallbackTagName, $this->renderAttributes($attributes), $html, $fallbackTagName);
}
$this->mergeAttributes($rootElement, $attributes);
- return preg_replace('/<(' . $rootElement->nodeName . ')\b[^>]*>/xi', '<$1' . addcslashes($this->renderAttributes($attributes), '\\') . '>', $html, 1);
+ return preg_replace('/<(' . $rootElement->nodeName . ')\b[^>]*>/xi', '<$1' . addcslashes($this->renderAttributes($attributes), '\\\$') . '>', $html, 1);
}
/**
|
BUGFIX: Escape preg_replace placeholders to prevent accidentally replacements
|
neos_neos-development-collection
|
train
|
fb7750640e35b895e429b4c7f4c02d0621731f67
|
diff --git a/lib/ellen/robot.rb b/lib/ellen/robot.rb
index <HASH>..<HASH> 100644
--- a/lib/ellen/robot.rb
+++ b/lib/ellen/robot.rb
@@ -8,7 +8,7 @@ module Ellen
attr_reader :options
- def initialize(options)
+ def initialize(options = {})
@options = options
end
diff --git a/spec/ellen/adapter_builder_spec.rb b/spec/ellen/adapter_builder_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/ellen/adapter_builder_spec.rb
+++ b/spec/ellen/adapter_builder_spec.rb
@@ -6,11 +6,7 @@ describe Ellen::AdapterBuilder do
end
let(:robot) do
- Ellen::Robot.new(options)
- end
-
- let(:options) do
- {}
+ Ellen::Robot.new
end
describe "#build" do
|
Can simply create a new robot by Ellen::Robot.new
|
r7kamura_ruboty
|
train
|
aa9ca8286e7f9abb55cca64368480bdba610308c
|
diff --git a/ui/src/kapacitor/apis/index.js b/ui/src/kapacitor/apis/index.js
index <HASH>..<HASH> 100644
--- a/ui/src/kapacitor/apis/index.js
+++ b/ui/src/kapacitor/apis/index.js
@@ -1,26 +1,5 @@
import AJAX from 'utils/ajax'
-export const log = async () => {
- try {
- let response = await fetch('http://localhost:9092/kapacitor/v1/logs', {
- method: 'GET',
- headers: {'Content-Type': 'application/json'},
- })
-
- const reader = await response.body.getReader()
- const decoder = new TextDecoder()
- const result = await reader.read()
- const chunk = decoder.decode(result.value || new Uint8Array(), {
- stream: !result.done,
- })
- return chunk
- console.log(chunk)
- return result
- } catch (error) {
- console.log(error)
- }
-}
-
const rangeRule = rule => {
const {value, rangeValue, operator} = rule.values
diff --git a/ui/src/kapacitor/components/Tickscript.js b/ui/src/kapacitor/components/Tickscript.js
index <HASH>..<HASH> 100644
--- a/ui/src/kapacitor/components/Tickscript.js
+++ b/ui/src/kapacitor/components/Tickscript.js
@@ -39,10 +39,18 @@ const Tickscript = ({
</div>
<div className="tickscript-editor">
<div>
- {logs.map((l, i) =>
- <pre key={i}>
- {JSON.stringify(l, null, 2)}
- </pre>
+ {logs.map(({key, ts, lvl, msg}) =>
+ <div key={key}>
+ <span>
+ {ts}
+ </span>
+ <span>
+ {lvl}
+ </span>
+ <pre>
+ {msg}
+ </pre>
+ </div>
)}
</div>
<TickscriptEditor
diff --git a/ui/src/kapacitor/containers/TickscriptPage.js b/ui/src/kapacitor/containers/TickscriptPage.js
index <HASH>..<HASH> 100644
--- a/ui/src/kapacitor/containers/TickscriptPage.js
+++ b/ui/src/kapacitor/containers/TickscriptPage.js
@@ -6,7 +6,6 @@ import Tickscript from 'src/kapacitor/components/Tickscript'
import * as kapactiorActionCreators from 'src/kapacitor/actions/view'
import * as errorActionCreators from 'shared/actions/errors'
import {getActiveKapacitor} from 'src/shared/apis'
-import {log} from 'src/kapacitor/apis'
class TickscriptPage extends Component {
constructor(props) {
@@ -24,7 +23,53 @@ class TickscriptPage extends Component {
},
validation: '',
isEditingID: true,
- logs: [{hai: 'hunter', watts: 'is nice'}, {yoMomma: 'is so nice'}],
+ logs: [],
+ }
+ }
+
+ shouldFetch = null
+
+ logKey = j => (log, i) => ({
+ ...log,
+ key: `${log.ts}-${j}-${i}`,
+ })
+
+ fetchChunkedLogs = async () => {
+ try {
+ const response = await fetch('http://localhost:9092/kapacitor/v1/logs', {
+ method: 'GET',
+ headers: {'Content-Type': 'application/json'},
+ })
+
+ const reader = await response.body.getReader()
+ const decoder = new TextDecoder()
+
+ let result
+ let j = 0
+
+ while (this.shouldFetch === true && !(result && result.done)) {
+ result = await reader.read()
+
+ const chunk = decoder.decode(result.value || new Uint8Array(), {
+ stream: !result.done,
+ })
+
+ // console.log(chunk)
+
+ const json = `[${chunk.split('}{').join('},{')}]`
+
+ const logs = JSON.parse(json).map(this.logKey(j))
+
+ // console.log(log)
+ this.setState({
+ logs: [...this.state.logs, ...logs],
+ })
+
+ j += 1
+ }
+ } catch (error) {
+ // console.log(error)
+ // TODO error handling
}
}
@@ -52,9 +97,15 @@ class TickscriptPage extends Component {
this.setState({task: {tickscript, dbrps, type, status, name, id}})
}
- const logs = await log()
+ this.shouldFetch = true
+
+ this.fetchChunkedLogs()
+
+ this.setState({kapacitor})
+ }
- this.setState({kapacitor, logs})
+ componentWillUnmount() {
+ this.shouldFetch = false
}
handleSave = async () => {
|
Add fetchChunkedLogs. Fetches logs in a while loop. Looping stops on componentWIllUnmount.
|
influxdata_influxdb
|
train
|
ae7e53239a6efb327edef4271d32dc3ecbe7541f
|
diff --git a/examples/with-apollo-auth/lib/withApollo.js b/examples/with-apollo-auth/lib/withApollo.js
index <HASH>..<HASH> 100644
--- a/examples/with-apollo-auth/lib/withApollo.js
+++ b/examples/with-apollo-auth/lib/withApollo.js
@@ -22,8 +22,9 @@ export default App => {
static async getInitialProps(ctx) {
const { Component, router, ctx: { req, res } } = ctx
+ const token = parseCookies(req).token
const apollo = initApollo({}, {
- getToken: () => parseCookies(req).token
+ getToken: () => token
})
ctx.ctx.apolloClient = apollo
@@ -69,7 +70,8 @@ export default App => {
return {
...appProps,
- apolloState
+ apolloState,
+ token
}
}
@@ -78,7 +80,7 @@ export default App => {
// `getDataFromTree` renders the component first, the client is passed off as a property.
// After that rendering is done using Next's normal rendering pipeline
this.apolloClient = initApollo(props.apolloState, {
- getToken: () => parseCookies().token
+ getToken: () => props.token
})
}
|
FIX with-apollo-auth example token access (#<I>)
in some cases access to the token doesn't work in client side. this access to the token once in getInitialProps method and pass it down using props
|
zeit_next.js
|
train
|
58e36f6bbe1537a06565abf43770bd3dccd73a35
|
diff --git a/cid/apps.py b/cid/apps.py
index <HASH>..<HASH> 100644
--- a/cid/apps.py
+++ b/cid/apps.py
@@ -1,10 +1,6 @@
from django.apps import AppConfig
-from django.utils.translation import ugettext_lazy as _
class CidAppConfig(AppConfig):
- """
- Django 1.7+ application configuration
- """
name = 'cid'
- verbose_name = _('Django Correlation Id')
+ verbose_name = 'Django Correlation Id'
|
apps: Remove translation of app name
I am not sure where this verbose name appears, but I am pretty sure
it's not useful to translate it. In fact it wasn't translated because
there are no gettext (*.po) files.
|
Polyconseil_django-cid
|
train
|
0dff237a474aefeb6842d8b7eb2e0e2ea26dc0a0
|
diff --git a/src/MImage.php b/src/MImage.php
index <HASH>..<HASH> 100644
--- a/src/MImage.php
+++ b/src/MImage.php
@@ -145,6 +145,31 @@ class MImage
return $newImage;
}
+ public static function fromFile( $type, $filePath )
+ {
+ switch( $type )
+ {
+ case 'gif':
+ $im = imagecreatefromgif( $filePath );
+ imageAlphaBlending( $im, true );
+ imageSaveAlpha( $im, true );
+ break;
+ case 'jpg':
+ $im = imagecreatefromjpeg( $filePath );
+ break;
+ case 'bmp':
+ $im = imagecreatefromwbmp( $filePath );
+ break;
+ default:
+ $im = imagecreatefrompng( $filePath );
+ imageAlphaBlending( $im, true );
+ imageSaveAlpha( $im, true );
+ break;
+ }
+
+ return MImage::fromResource( $im );
+ }
+
/**
* Resizes the color table to contain colorCount entries.
*
|
Added fromFile methos in MImage.
|
mtoolkit_mtoolkit-view
|
train
|
ffa39030eccd3908ed0d9778165cad3233a14962
|
diff --git a/s3contents/genericmanager.py b/s3contents/genericmanager.py
index <HASH>..<HASH> 100644
--- a/s3contents/genericmanager.py
+++ b/s3contents/genericmanager.py
@@ -217,8 +217,11 @@ class GenericContentsManager(ContentsManager, HasTraits):
async def s3_detail_metadata(s3_detail):
if s3_detail["StorageClass"] == "DIRECTORY":
dir_path = os.path.join(self.fs.path(s3_detail["Key"]), ".s3keep")
- lstat = await self.fs.fs._info(dir_path)
- s3_detail['LastModified'] = lstat['LastModified']
+ try:
+ lstat = await self.fs.fs._info(dir_path)
+ s3_detail['LastModified'] = lstat['LastModified']
+ except FileNotFoundError:
+ pass
st_time = s3_detail.get("LastModified")
if st_time:
s3_detail["ST_MTIME"] = datetime.datetime(
|
catch missing s3keep case (#<I>)
|
danielfrg_s3contents
|
train
|
5a3d01bdfb6c3cde68e2f668a05aa97031600939
|
diff --git a/support/cftree/__init__.py b/support/cftree/__init__.py
index <HASH>..<HASH> 100644
--- a/support/cftree/__init__.py
+++ b/support/cftree/__init__.py
@@ -183,7 +183,7 @@ class cfentry:
linear_part_distance = sum(list_math_multiplication(linear_part_first, linear_part_second));
- general_part_distance = 2.0 * (self.square_sum + entry.square_sum) - 2.0 * linear_part_distance;
+ general_part_distance = 2.0 * (self.number_points + entry.number_points) * (self.square_sum + entry.square_sum) - 2.0 * linear_part_distance;
return (general_part_distance / ( (self.number_points + entry.number_points) * (self.number_points + entry.number_points - 1.0) )) ** 0.5;
@@ -196,16 +196,20 @@ class cfentry:
"Return variance increase distance."
linear_part_12 = list_math_addition(self.linear_sum, entry.linear_sum);
- variance_part_first = -2.0 * ( sum(list_math_multiplication(linear_part_12, linear_part_12)) ) / ( 1.0 / (self.number_points + entry.number_points) );
- variance_part_second = sum(list_math_multiplication(linear_part_12, linear_part_12)) / (1.0 / (self.number_points + entry.number_points)**0.5 );
+ variance_part_first = (self.square_sum + entry.square_sum) - \
+ 2.0 * sum(list_math_multiplication(linear_part_12, linear_part_12)) / (self.number_points + entry.number_points) + \
+ (self.number_points + entry.number_points) * sum(list_math_multiplication(linear_part_12, linear_part_12)) / (self.number_points + entry.number_points)**2.0;
+
linear_part_11 = sum(list_math_multiplication(self.linear_sum, self.linear_sum));
- variance_part_third = (2.0 / self.number_points) * linear_part_11 - (1.0 / self.number_points ** 2.0) * linear_part_11;
+ variance_part_second = -( self.square_sum - (2.0 * linear_part_11 / self.number_points) + (linear_part_11 / self.number_points) );
linear_part_22 = sum(list_math_multiplication(entry.linear_sum, entry.linear_sum));
- variance_part_fourth = (2.0 / entry.number_points) * linear_part_22 - (1.0 / entry.number_points ** 2.0) * linear_part_22;
+ variance_part_third = -( entry.square_sum - (2.0 / entry.number_points) * linear_part_22 + entry.number_points * (1.0 / entry.number_points ** 2.0) * linear_part_22 );
+
+ print(variance_part_first, variance_part_second, variance_part_third);
- return (variance_part_first + variance_part_second + variance_part_third + variance_part_fourth);
+ return (variance_part_first + variance_part_second + variance_part_third);
|
[support.cftree] Fixed bugs with distance calculation
|
annoviko_pyclustering
|
train
|
2a2ea02a901830b9e7c63b5ed4966b98fea9426c
|
diff --git a/time_execution/backends/elasticsearch.py b/time_execution/backends/elasticsearch.py
index <HASH>..<HASH> 100644
--- a/time_execution/backends/elasticsearch.py
+++ b/time_execution/backends/elasticsearch.py
@@ -36,7 +36,7 @@ class ElasticsearchBackend(BaseMetricsBackend):
return self.index_pattern.format(index=self.index, date=datetime.now())
def _setup_index(self):
- return self.client.indices.create(self.index, ignore=400)
+ return self.client.indices.create(self.get_index(), ignore=400)
def _setup_mapping(self):
return self.client.indices.put_template(
|
CHANGED create ElasticSearch index following the index name pattern
|
kpn-digital_py-timeexecution
|
train
|
4ec9e6ba10246a660badcd049368640fab53feaa
|
diff --git a/lib/compiler/passes/report-left-recursion.js b/lib/compiler/passes/report-left-recursion.js
index <HASH>..<HASH> 100644
--- a/lib/compiler/passes/report-left-recursion.js
+++ b/lib/compiler/passes/report-left-recursion.js
@@ -11,9 +11,7 @@ function reportLeftRecursion(ast) {
},
sequence: function(node, appliedRules) {
- if (node.elements.length > 0) {
- check(node.elements[0], appliedRules);
- }
+ check(node.elements[0], appliedRules);
},
rule_ref: function(node, appliedRules) {
|
Remove useless test in the |reportLeftRecursion| pass
Empty sequences are not allowed anymore so we don't have to test for
them.
|
pegjs_pegjs
|
train
|
484f694b4d5f9953f2388687cb291993026b1cbb
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -89,9 +89,10 @@ module.exports = function (spec) {
output.push('\n\n\n');
// Exit if no tests run. This is a result of 1 of 2 things:
- // 1. No tests were written
+ // 1. No tests and asserts were written
// 2. There was some error before the TAP got to the parser
- if (results.tests.length === 0) {
+ if (results.tests.length === 0 &&
+ results.asserts.length === 0) {
process.exit(1);
}
});
@@ -120,7 +121,8 @@ module.exports = function (spec) {
function formatTotals (results) {
- if (results.tests.length === 0) {
+ if (results.tests.length === 0 &&
+ results.asserts.length === 0) {
return pad(format.red(symbols.cross + ' No tests found'));
}
|
also check for asserts.length
Fixed invalid behavoir: on `output` when `results.tests` are empty, but `results.asserts` are not , `process.exit(1);` triggers.
Should trigger only when both are empty.
|
scottcorgan_tap-spec
|
train
|
9da1dd678b00f440063cd9f4b9d38b160e79a40d
|
diff --git a/MANIFEST b/MANIFEST
index <HASH>..<HASH> 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -16,6 +16,7 @@ demo/is_up.py
demo/msg_client.py
demo/msg_server.py
demo/port_scan.py
+demo/server_ssl.py
demo/spawn_process.py
demo/sum.py
demo/telnet_process.py
diff --git a/demo/con_https.py b/demo/con_https.py
index <HASH>..<HASH> 100644
--- a/demo/con_https.py
+++ b/demo/con_https.py
@@ -1,5 +1,4 @@
-from untwisted.client import ClientSSL, SSL_CONNECT, SSL_CONNECT_ERR, \
-SSL_CERTIFICATE_ERR, put, lose
+from untwisted.client import ClientSSL, SSL_CONNECT, SSL_CONNECT_ERR, put, lose
from untwisted.sock_writer import SockWriterSSL
from untwisted.sock_reader import SockReaderSSL, LOAD, CLOSE
from socket import socket, AF_INET, SOCK_STREAM
@@ -24,10 +23,6 @@ def handle_connect_err(ssock, err):
print('Connect err.', err)
die()
-def handle_certificate_err(ssock, err):
- print('Certificate err.', err)
- die()
-
def main(addr, port, host):
sock = socket(AF_INET, SOCK_STREAM)
context = ssl.create_default_context()
@@ -41,7 +36,6 @@ def main(addr, port, host):
ClientSSL(con)
con.add_map(SSL_CONNECT, on_connect, host)
con.add_map(SSL_CONNECT_ERR, handle_connect_err)
- con.add_map(SSL_CERTIFICATE_ERR, handle_certificate_err)
if __name__ == '__main__':
from optparse import OptionParser
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@
from distutils.core import setup
setup(name="untwisted",
- version="3.2.0",
+ version="3.2.1",
packages=["untwisted"],
author="Iury O. G. Figueiredo",
author_email="ioliveira@id.uff.br",
|
Fixing setup.py version.
|
untwisted_untwisted
|
train
|
2169a2a7c778dac7543613d56c505ae5dfd3cdb4
|
diff --git a/src/locale/lang/sk.js b/src/locale/lang/sk.js
index <HASH>..<HASH> 100644
--- a/src/locale/lang/sk.js
+++ b/src/locale/lang/sk.js
@@ -109,14 +109,14 @@ export default {
hasCheckedFormat: '{checked}/{total} označených'
},
image: {
- error: 'FAILED' // to be translated
+ error: 'Chyba načítania'
},
pageHeader: {
- title: 'Back' // to be translated
+ title: 'Späť'
},
popconfirm: {
- confirmButtonText: 'Yes', // to be translated
- cancelButtonText: 'No' // to be translated
+ confirmButtonText: 'Potvrdiť',
+ cancelButtonText: 'Zrušiť'
},
empty: {
description: 'Žiadne dáta'
|
i<I>n: Update Slovak translations (#<I>)
|
ElemeFE_element
|
train
|
1cefcb29907b4a5322de4a4131effd56279f8da1
|
diff --git a/tests/test_document.py b/tests/test_document.py
index <HASH>..<HASH> 100644
--- a/tests/test_document.py
+++ b/tests/test_document.py
@@ -4,6 +4,7 @@ import io
import tempfile
from nose import tools
+from unittest import skipIf as skip_if
from PyPDF2 import PdfFileReader
@@ -33,6 +34,13 @@ METADATA = {
"keywords": "pdf, documents",
}
+try:
+ import __pypy__
+except ImportError:
+ IN_PYPY = False
+else:
+ IN_PYPY = True
+
def _compare_pdf_metadata(pdf_file, assertion):
@@ -54,6 +62,7 @@ def _compare_pdf_metadata(pdf_file, assertion):
assertion(actual_value, expected_value)
+@skip_if(IN_PYPY, "This doesn't work in pypy")
def test_document_creation_without_metadata():
with tempfile.TemporaryFile() as pdf_file:
pisaDocument(
@@ -63,6 +72,7 @@ def test_document_creation_without_metadata():
_compare_pdf_metadata(pdf_file, tools.assert_not_equal)
+@skip_if(IN_PYPY, "This doesn't work in pypy")
def test_document_creation_with_metadata():
with tempfile.TemporaryFile() as pdf_file:
pisaDocument(
|
Skip document tests in pypy
|
xhtml2pdf_xhtml2pdf
|
train
|
2151b4e515af73b6116ee86ca2092f64f2520f01
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,15 +5,15 @@ Created on Oct 15, 2014
@author: tmahrt
'''
+from setuptools import setup
import codecs
-from distutils.core import setup
setup(name='pysle',
version='1.4.0',
author='Tim Mahrt',
author_email='timmahrt@gmail.com',
+ url='https://github.com/timmahrt/pysle',
package_dir={'pysle':'pysle'},
packages=['pysle'],
license='LICENSE',
- long_description=codecs.open('README.rst', 'r', encoding="utf-8").read(),
-# install_requires=[], # No requirements! # requires 'from setuptools import setup'
+ long_description=codecs.open('README.rst', 'r', encoding="utf-8").read()
)
|
DOCUMENTATION: Updates for setup.py
|
timmahrt_pysle
|
train
|
97f71f1da7f5d4adf2ae5921f3436af314695473
|
diff --git a/src/Cleaners/DocumentCleaner.php b/src/Cleaners/DocumentCleaner.php
index <HASH>..<HASH> 100644
--- a/src/Cleaners/DocumentCleaner.php
+++ b/src/Cleaners/DocumentCleaner.php
@@ -284,7 +284,7 @@ class DocumentCleaner {
$fragment->appendXML(htmlentities(implode('', $replacementText), ENT_COMPAT | ENT_XML1));
$el = $doc->createElement('p');
- $el->appendChild($fragment);
+ @$el->appendChild($fragment);
return $el;
}
diff --git a/src/Crawler.php b/src/Crawler.php
index <HASH>..<HASH> 100644
--- a/src/Crawler.php
+++ b/src/Crawler.php
@@ -120,9 +120,16 @@ class Crawler {
$rawHtml = preg_replace_callback('@<([/])?script[^>]*>@i', $fn, $rawHtml);
+ if (mb_detect_encoding($rawHtml, mb_detect_order(), true) === 'UTF-8') {
+ $rawHtml = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function($match) {
+ list($utf8) = $match;
+ return mb_convert_encoding($utf8, 'HTML-ENTITIES', 'UTF-8');
+ }, $rawHtml);
+ }
+
$doc = new DOMDocument(1.0);
$doc->registerNodeClass('DOMElement', 'Goose\\DOM\\DOMElement');
- @$doc->loadHTML(html_entity_decode($rawHtml));
+ @$doc->loadHTML($rawHtml);
libxml_use_internal_errors($internalErrors);
libxml_disable_entity_loader($disableEntities);
|
trying out a better way to handle utf8 documents
<URL>
|
scotteh_php-goose
|
train
|
1f646a39990e8ba12101486ed0c9a79148d6578a
|
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/util/AntlrUtils.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/util/AntlrUtils.java
index <HASH>..<HASH> 100644
--- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/util/AntlrUtils.java
+++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/util/AntlrUtils.java
@@ -37,19 +37,19 @@ public final class AntlrUtils {
*
* @param parser antlr parser
* @param tokenType token type
- * @param idTokenIndex index of id token
- * @return Token
+ * @param identifierTokenIndex index of identifier token
+ * @return matched token
* @throws RecognitionException mismatch throw exception
*/
- public static Token getMatchedToken(final Parser parser, final int tokenType, final int idTokenIndex) throws RecognitionException {
+ public static Token getMatchedToken(final Parser parser, final int tokenType, final int identifierTokenIndex) throws RecognitionException {
Token result = parser.getCurrentToken();
- boolean isIDCompatible = false;
- if (idTokenIndex == tokenType && idTokenIndex > result.getType()) {
- isIDCompatible = true;
+ boolean isIdentifierCompatible = false;
+ if (identifierTokenIndex == tokenType && identifierTokenIndex > result.getType()) {
+ isIdentifierCompatible = true;
}
- if (result.getType() == tokenType || isIDCompatible) {
- if (Token.EOF != tokenType && isIDCompatible && result instanceof CommonToken) {
- ((CommonToken) result).setType(idTokenIndex);
+ if (result.getType() == tokenType || isIdentifierCompatible) {
+ if (Token.EOF != tokenType && isIdentifierCompatible && result instanceof CommonToken) {
+ ((CommonToken) result).setType(identifierTokenIndex);
}
parser.getErrorHandler().reportMatch(parser);
parser.consume();
|
for #<I>, refactor AntlrUtils
|
apache_incubator-shardingsphere
|
train
|
688f72cc52e465eeabc8f6887ad383319cc6a12b
|
diff --git a/tests/TestCase.php b/tests/TestCase.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -47,6 +47,7 @@ abstract class TestCase extends Orchestra
'prefix' => '',
]);
$app['config']->set('app.key', 'sF5r4kJy5HEcOEx3NWxUcYj1zLZLHxuu');
+ $app['config']->set('translator.source', 'database');
}
/**
diff --git a/tests/Traits/TranslatableTest.php b/tests/Traits/TranslatableTest.php
index <HASH>..<HASH> 100644
--- a/tests/Traits/TranslatableTest.php
+++ b/tests/Traits/TranslatableTest.php
@@ -40,10 +40,10 @@ class TranslatableTest extends TestCase
// Check that there is a language entry in the database:
$titleTranslation = $this->translationRepository->findByLangCode('en', $dummy->translationCodeFor('title'));
$this->assertEquals('Dummy title', $titleTranslation->text);
- $this->assertEquals($dummy->translationCodeFor('title'), $dummy->title);
+ $this->assertEquals('Dummy title', $dummy->title);
$textTranslation = $this->translationRepository->findByLangCode('en', $dummy->translationCodeFor('text'));
$this->assertEquals('Dummy text', $textTranslation->text);
- $this->assertEquals($dummy->translationCodeFor('text'), $dummy->text);
+ $this->assertEquals('Dummy text', $dummy->text);
// Delete it:
$deleted = $dummy->delete();
$this->assertTrue($deleted);
|
Fixed issue with translatable test.
|
Waavi_translation
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.