hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
fa5ad7ac5af9c40093810968391f904c235b2198
diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java index <HASH>..<HASH> 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java +++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java @@ -183,13 +183,14 @@ public class OkHttpClient implements Cloneable { * * @see URLConnection#setConnectTimeout(int) */ - public void setConnectTimeout(long timeout, TimeUnit unit) { + public OkHttpClient setConnectTimeout(long timeout, TimeUnit unit) { if (timeout < 0) throw new IllegalArgumentException("timeout < 0"); if (unit == null) throw new IllegalArgumentException("unit == null"); long millis = unit.toMillis(timeout); if (millis > Integer.MAX_VALUE) throw new IllegalArgumentException("Timeout too large."); if (millis == 0 && timeout > 0) throw new IllegalArgumentException("Timeout too small."); connectTimeout = (int) millis; + return this; } /** Default connect timeout (in milliseconds). */ @@ -203,13 +204,14 @@ public class OkHttpClient implements Cloneable { * * @see URLConnection#setReadTimeout(int) */ - public void setReadTimeout(long timeout, TimeUnit unit) { + public OkHttpClient setReadTimeout(long timeout, TimeUnit unit) { if (timeout < 0) throw new IllegalArgumentException("timeout < 0"); if (unit == null) throw new IllegalArgumentException("unit == null"); long millis = unit.toMillis(timeout); if (millis > Integer.MAX_VALUE) throw new IllegalArgumentException("Timeout too large."); if (millis == 0 && timeout > 0) throw new IllegalArgumentException("Timeout too small."); readTimeout = (int) millis; + return this; } /** Default read timeout (in milliseconds). */ @@ -221,13 +223,14 @@ public class OkHttpClient implements Cloneable { * Sets the default write timeout for new connections. A value of 0 means no timeout, otherwise * values must be between 1 and {@link Integer#MAX_VALUE} when converted to milliseconds. */ - public void setWriteTimeout(long timeout, TimeUnit unit) { + public OkHttpClient setWriteTimeout(long timeout, TimeUnit unit) { if (timeout < 0) throw new IllegalArgumentException("timeout < 0"); if (unit == null) throw new IllegalArgumentException("unit == null"); long millis = unit.toMillis(timeout); if (millis > Integer.MAX_VALUE) throw new IllegalArgumentException("Timeout too large."); if (millis == 0 && timeout > 0) throw new IllegalArgumentException("Timeout too small."); writeTimeout = (int) millis; + return this; } /** Default write timeout (in milliseconds). */ @@ -428,8 +431,9 @@ public class OkHttpClient implements Cloneable { } /** Configure this client to follow redirects. If unset, redirects be followed. */ - public void setFollowRedirects(boolean followRedirects) { + public OkHttpClient setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; + return this; } public boolean getFollowRedirects() { @@ -454,8 +458,9 @@ public class OkHttpClient implements Cloneable { * Set this to false to avoid retrying requests when doing so is destructive. In this case the * calling application should do its own recovery of connectivity failures. */ - public void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) { + public OkHttpClient setRetryOnConnectionFailure(boolean retryOnConnectionFailure) { this.retryOnConnectionFailure = retryOnConnectionFailure; + return this; } public boolean getRetryOnConnectionFailure() {
Add missing 'this' returns from setters.
square_okhttp
train
7ca51764d642a97463f4b8ee6b5e0442d7898792
diff --git a/core/client/routes/posts/post.js b/core/client/routes/posts/post.js index <HASH>..<HASH> 100644 --- a/core/client/routes/posts/post.js +++ b/core/client/routes/posts/post.js @@ -35,7 +35,7 @@ var PostsPostRoute = Ember.Route.extend(SimpleAuth.AuthenticatedRouteMixin, load return self.store.find('post', paginationSettings).then(function (records) { var post = records.get('firstObject'); - if (user.get('isAuthor') && post.isAuthoredByUser(user)) { + if (user.get('isAuthor') && !post.isAuthoredByUser(user)) { // do not show the post if they are an author but not this posts author post = null; }
Show posts authored by current user. The current logic allows showing of all EXCEPT the current users posts (when the current user is an author). This fixes that.
TryGhost_Ghost
train
427ee765c3c78e3aa63cd17881a4b70a009e8857
diff --git a/dist.py b/dist.py index <HASH>..<HASH> 100644 --- a/dist.py +++ b/dist.py @@ -537,7 +537,7 @@ Common commands: (see '--help-commands' for more) for (help_option, short, desc, func) in cmd_class.help_options: if hasattr(opts, parser.get_attr_name(help_option)): help_option_found=1 - if hasattr(func, '__call__'): + if callable(func): func() else: raise DistutilsClassError(
Closes #<I>: Use callable() built-in in the standard library.
pypa_setuptools
train
b0ab7f7c202eb7ff7f3204bc6a6db27d9dbc5123
diff --git a/src/Runtime/Auth/AuthenticationContext.php b/src/Runtime/Auth/AuthenticationContext.php index <HASH>..<HASH> 100644 --- a/src/Runtime/Auth/AuthenticationContext.php +++ b/src/Runtime/Auth/AuthenticationContext.php @@ -36,17 +36,14 @@ class AuthenticationContext implements IAuthenticationContext /** * Gets URL of the authorize endpoint including the query parameters. - * @param string $resource Identifier of the target resource that is the recipient of the requested token. + * @param string $authorizeUrl * @param string $clientId * @param string $redirectUrl * @param array $parameters * @return string */ - public function getAuthorizationRequestUrl($resource, $clientId, $redirectUrl, $parameters = []) + public function getAuthorizationRequestUrl($authorizeUrl, $clientId, $redirectUrl, $parameters = []) { - //$authorizeUrl = "https://login.microsoftonline.com/{tenant}/oauth2/authorize"; - $authorizeUrl = "https://login.microsoftonline.com/common/oauth2/authorize"; - $stateGuid = Guid::newGuid(); $parameters = array_merge($parameters, array( 'response_type' => 'code', 'client_id' => $clientId, @@ -121,9 +118,9 @@ class AuthenticationContext implements IAuthenticationContext * @param string $code * @param string $redirectUrl */ - public function acquireTokenByAuthorizationCode($resource, $clientId, $clientSecret, $code, $redirectUrl) + public function acquireTokenByAuthorizationCode($uri,$resource, $clientId, $clientSecret, $code, $redirectUrl) { - $this->provider = new OAuthTokenProvider("https://login.microsoftonline.com/common"); + $this->provider = new OAuthTokenProvider($uri); $parameters = array( 'grant_type' => 'authorization_code', 'client_id' => $clientId,
Hardcode URI's removed. Although investigation if it is possible to connect with Sharepoint Onpremise with current code?
vgrem_phpSPO
train
b7c32ada9bd1614544cd8dbeccffe5c6d1508acb
diff --git a/lib/rlint/parser.rb b/lib/rlint/parser.rb index <HASH>..<HASH> 100644 --- a/lib/rlint/parser.rb +++ b/lib/rlint/parser.rb @@ -80,12 +80,17 @@ module Rlint RETURN_METHOD_EVENTS = [:fcall, :vcall] ## - # Array containing the names of various event callbacks that should return + # Hash containing the names of various event callbacks that should return # a token class containing details about a single line statement. # - # @return [Array] + # @return [Hash] # - MOD_STATEMENT_EVENTS = [:while_mod, :if_mod, :unless_mod, :until_mod] + MOD_STATEMENT_EVENTS = { + :while_mod => :while, + :if_mod => :if, + :unless_mod => :unless, + :until_mod => :until + } ## # Array containing the three method calls that set the visibility of a @@ -147,12 +152,12 @@ module Rlint end end - MOD_STATEMENT_EVENTS.each do |event| - define_method("on_#{event}") do |statement, value| + MOD_STATEMENT_EVENTS.each do |ripper_event, rlint_event| + define_method("on_#{ripper_event}") do |statement, value| value = [value] unless value.is_a?(Array) return Token::StatementToken.new( - :type => event, + :type => rlint_event, :statement => statement, :value => value, :line => lineno, @@ -783,7 +788,7 @@ module Rlint statement = [statement] unless statement.is_a?(Array) return Token::BeginRescueToken.new( - :type => :rescue_mod, + :type => :rescue, :rescue => statement, :value => value, :line => lineno, diff --git a/spec/rlint/parser/statements.rb b/spec/rlint/parser/statements.rb index <HASH>..<HASH> 100644 --- a/spec/rlint/parser/statements.rb +++ b/spec/rlint/parser/statements.rb @@ -94,7 +94,7 @@ describe 'Rlint::Parser' do token = Rlint::Parser.new('foo while bar').parse[0] token.class.should == Rlint::Token::StatementToken - token.type.should == :while_mod + token.type.should == :while token.statement.class.should == Rlint::Token::MethodToken token.statement.name.should == 'bar' @@ -399,7 +399,7 @@ end token = Rlint::Parser.new('foo if bar').parse[0] token.class.should == Rlint::Token::StatementToken - token.type.should == :if_mod + token.type.should == :if token.statement.class.should == Rlint::Token::MethodToken token.statement.name.should == 'bar' @@ -415,7 +415,7 @@ end token = Rlint::Parser.new('foo rescue bar').parse[0] token.class.should == Rlint::Token::BeginRescueToken - token.type.should == :rescue_mod + token.type.should == :rescue token.rescue.class.should == Array token.rescue.length.should == 1 @@ -457,7 +457,7 @@ end token = Rlint::Parser.new('foo unless bar').parse[0] token.class.should == Rlint::Token::StatementToken - token.type.should == :unless_mod + token.type.should == :unless token.statement.class.should == Rlint::Token::MethodToken token.statement.name.should == 'bar' @@ -505,7 +505,7 @@ end token = Rlint::Parser.new('foo until bar').parse[0] token.class.should == Rlint::Token::StatementToken - token.type.should == :until_mod + token.type.should == :until token.statement.class.should == Rlint::Token::MethodToken token.statement.name.should == 'bar'
Merged regular and "mod" statement events.
YorickPeterse_ruby-lint
train
ebf7123b616bf58f5bdb09b664b4b1a94d579fa9
diff --git a/lib/ChainFind.js b/lib/ChainFind.js index <HASH>..<HASH> 100644 --- a/lib/ChainFind.js +++ b/lib/ChainFind.js @@ -38,7 +38,7 @@ function ChainFind(Model, opts) { return this; }, count: function (cb) { - opts.driver.count(opts.table, opts.conditions, opts, function (err, data) { + opts.driver.count(opts.table, opts.conditions, {}, function (err, data) { if (err || data.length === 0) { return cb(err); }
Changes ChainFind.count() to avoid passing opts, no need
dresende_node-orm2
train
148788e652e9f3e1fc1f7b8482d824af0349ff4a
diff --git a/salt/utils/schedule.py b/salt/utils/schedule.py index <HASH>..<HASH> 100644 --- a/salt/utils/schedule.py +++ b/salt/utils/schedule.py @@ -972,7 +972,6 @@ class Schedule(object): # Add up how many seconds between now and then when = 0 seconds = 0 - cron = 0 now = int(time.time()) if 'until' in data: @@ -1183,11 +1182,23 @@ class Schedule(object): now = int(time.mktime(datetime.datetime.now().timetuple())) try: - cron = int(croniter.croniter(data['cron'], now).get_next()) + cron = croniter.croniter(data['cron'], now) + # Get first scheduled time from now on to be able to + # calculate when it was intended to run before. + cron.get_next() except (ValueError, KeyError): log.error('Invalid cron string. Ignoring') continue - seconds = cron - now + # Calculate how many seconds passed from previous run... + data['_cron_prev'] = now - int(cron.get_prev()) + # ...and need to wait till next scheduled job. + data['_cron_next'] = int(cron.get_next()) - now + # If less than one minute left till next job, this will + # increase loop interval to wait for next cycle. + # This prevents setting loop interval to low, which has + # negative performance impact, especially on Master side. + seconds = data['_cron_next'] if data['_cron_next'] >= 60 \ + else int(cron.get_next()) - now else: continue @@ -1200,6 +1211,7 @@ class Schedule(object): if 'when' not in data: if seconds < self.loop_interval: self.loop_interval = seconds + run = False if 'splay' in data: @@ -1223,7 +1235,11 @@ class Schedule(object): data['_when_run'] = False run = True elif 'cron' in data: - if seconds == 1: + # Run the job only if less than or just one second left till + # the scheduled time, or during the next loop interval right after that. + if data['_cron_next'] <= 1 or \ + (data['_cron_prev'] < self.option('loop_interval') and + data['_cron_prev'] < self.loop_interval): run = True else: if job in self.intervals:
Fix Master/Minion scheduled jobs based on Cron expressions
saltstack_salt
train
261619aa6c39047936f3936c8c45d25afb5c3506
diff --git a/src/HtmlForm/Elements/Field.php b/src/HtmlForm/Elements/Field.php index <HASH>..<HASH> 100644 --- a/src/HtmlForm/Elements/Field.php +++ b/src/HtmlForm/Elements/Field.php @@ -84,4 +84,9 @@ abstract class Field implements \HtmlForm\Interfaces\Field { return $this->required; } + + public function getLabel() + { + return $this->label; + } } \ No newline at end of file
Added getLabel() method to Form class.
jenwachter_html-form
train
8a5eb45fcdf8702b556eb78b7c4bf858ff0bac4e
diff --git a/lib/cxxproject/ext/rake.rb b/lib/cxxproject/ext/rake.rb index <HASH>..<HASH> 100644 --- a/lib/cxxproject/ext/rake.rb +++ b/lib/cxxproject/ext/rake.rb @@ -67,10 +67,12 @@ module Rake end def invoke_prerequisites(args, invocation_chain) + super(args, invocation_chain) + Dir.chdir(@bb.project_dir) do - enhance(@bb.create_object_file_tasks) - return unless @prerequisites - Jobs.new(@prerequisites.dup, application.max_parallel_tasks) do |jobs| + file_tasks = @bb.create_object_file_tasks + return if file_tasks.length == 0 + Jobs.new(file_tasks, application.max_parallel_tasks) do |jobs| while true do job = jobs.get_next_or_nil break unless job
fixed prereq working dir of multi tasks
marcmo_cxxproject
train
2b0c96f8828545ea9826dfbefcae9388dffeffc5
diff --git a/daskernetes/__init__.py b/daskernetes/__init__.py index <HASH>..<HASH> 100644 --- a/daskernetes/__init__.py +++ b/daskernetes/__init__.py @@ -66,7 +66,7 @@ class KubeCluster(object): args = [ 'dask-worker', self.scheduler_address, - '--nthreads', self.threads_per_worker, + '--nthreads', str(self.threads_per_worker), ] ) ]
Only pass strings to podspec Does not like integers!
dask_dask-kubernetes
train
e253c5bc0eae3d5d7376ca264094eaf78d306085
diff --git a/Lib/fontmake/font_project.py b/Lib/fontmake/font_project.py index <HASH>..<HASH> 100644 --- a/Lib/fontmake/font_project.py +++ b/Lib/fontmake/font_project.py @@ -199,7 +199,8 @@ class FontProject: ufo, featureCompilerClass=fea_compiler, mtiFeaFiles=mti_paths[name] if mti_paths is not None else None, glyphOrder=ufo.lib[PUBLIC_PREFIX + 'glyphOrder'], - useProductionNames=use_production_names) + useProductionNames=use_production_names, + convertCubics=False) otf.save(otf_path) if subset:
don't call cu2qu twice; call ufo2ft outline compiler with convertCubics=False
googlefonts_fontmake
train
04491ae2b9ca2f491ea524433f34a9a26cb35baf
diff --git a/class.js b/class.js index <HASH>..<HASH> 100644 --- a/class.js +++ b/class.js @@ -5,6 +5,7 @@ var id = require('./id') , core = require('./core') , types = require('./types') , method = require('./method') + , _global = require('./index') , ivar = require('./ivar') , IMP = require('./imp') , SEL = require('./sel') @@ -61,7 +62,7 @@ proto.extend = function extend (className, extraBytes) { */ proto.register = function register () { core.objc_registerClassPair(this.pointer); - // TODO: Attach 'this' to the global exports, for access from there + _global[this.getName()] = this return this }
Attach newly created Classes to the exports after calling register().
TooTallNate_NodObjC
train
8343dc4eb043e52e638f0f0671db1c0eeeb167b1
diff --git a/tests/integration/states/test_lxd.py b/tests/integration/states/test_lxd.py index <HASH>..<HASH> 100644 --- a/tests/integration/states/test_lxd.py +++ b/tests/integration/states/test_lxd.py @@ -1,17 +1,11 @@ -# -*- coding: utf-8 -*- """ Integration tests for the lxd states """ -# Import Python Libs -from __future__ import absolute_import, print_function, unicode_literals -# Import salt utils import salt.utils.path from tests.support.case import ModuleCase from tests.support.helpers import destructiveTest, flaky from tests.support.mixins import SaltReturnAssertsMixin - -# Import Salt Testing Libs from tests.support.unit import skipIf try:
Drop Py2 and six on tests/integration/states/test_lxd.py
saltstack_salt
train
5b940841ec81bf295f6e6f60972ebe10703e0e23
diff --git a/cmd/sup/main.go b/cmd/sup/main.go index <HASH>..<HASH> 100644 --- a/cmd/sup/main.go +++ b/cmd/sup/main.go @@ -246,9 +246,8 @@ func main() { network.Hosts = hosts } - // --env flag sets environment variables and overrides values defined in Supfile + // Parse --env flag environment variables and override values defined in Supfile var vars sup.EnvList - var supEnv string for _, env := range envVars { if len(env) == 0 { continue @@ -262,14 +261,12 @@ func main() { } vars.Set(env[:i], env[i+1:]) } - if len(vars) > 0 { - network.Env = append(network.Env, vars...) - // Separate loop to omit duplicated keys. - for _, v := range vars { - supEnv += fmt.Sprintf(" -e %v=%q", v.Key, v.Value) - } - network.Env.Set("SUP_ENV", strings.TrimSpace(supEnv)) + vars = append(vars, conf.Env...) + vars = append(vars, network.Env...) + if err := vars.ResolveValues(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) } // Create new Stackup app. @@ -282,7 +279,7 @@ func main() { app.Prefix(!disablePrefix) // Run all the commands in the given network. - err = app.Run(network, commands...) + err = app.Run(network, vars, commands...) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) diff --git a/sup.go b/sup.go index <HASH>..<HASH> 100644 --- a/sup.go +++ b/sup.go @@ -13,7 +13,7 @@ import ( "golang.org/x/crypto/ssh" ) -const VERSION = "0.4" +const VERSION = "0.5" type Stackup struct { conf *Supfile @@ -30,17 +30,12 @@ func New(conf *Supfile) (*Stackup, error) { // Run runs set of commands on multiple hosts defined by network sequentially. // TODO: This megamoth method needs a big refactor and should be split // to multiple smaller methods. -func (sup *Stackup) Run(network *Network, commands ...*Command) error { +func (sup *Stackup) Run(network *Network, envVars EnvList, commands ...*Command) error { if len(commands) == 0 { return errors.New("no commands to be run") } - // Process all ENVs into a string of form - // `export FOO="bar"; export BAR="baz";`. - env := `` - for _, v := range append(sup.conf.Env, network.Env...) { - env += v.AsExport() + " " - } + env := envVars.AsExport() // Create clients for every host (either SSH or Localhost). var bastion *SSHClient diff --git a/supfile.go b/supfile.go index <HASH>..<HASH> 100644 --- a/supfile.go +++ b/supfile.go @@ -9,6 +9,8 @@ import ( "os/exec" "strings" + "github.com/pkg/errors" + "gopkg.in/yaml.v2" ) @@ -70,7 +72,7 @@ func (e EnvVar) AsExport() string { // EnvList is a list of environment variables that maps to a YAML map, // but maintains order, enabling late variables to reference early variables. -type EnvList []EnvVar +type EnvList []*EnvVar func (e *EnvList) UnmarshalYAML(unmarshal func(interface{}) error) error { items := []yaml.MapItem{} @@ -91,7 +93,6 @@ func (e *EnvList) UnmarshalYAML(unmarshal func(interface{}) error) error { // Set key to be equal value in this list. func (e *EnvList) Set(key, value string) { - for i, v := range *e { if v.Key == key { (*e)[i].Value = value @@ -99,12 +100,48 @@ func (e *EnvList) Set(key, value string) { } } - *e = append(*e, EnvVar{ + *e = append(*e, &EnvVar{ Key: key, Value: value, }) } +func (e *EnvList) ResolveValues() error { + if len(*e) == 0 { + return nil + } + + exports := "" + for i, v := range *e { + exports += v.AsExport() + + cmd := exec.Command("bash", "-c", exports+"echo -n "+v.Value+";") + cwd, err := os.Getwd() + if err != nil { + return err + } + cmd.Dir = cwd + resolvedValue, err := cmd.Output() + if err != nil { + return errors.Wrapf(err, "resolving env var %v failed", v.Key) + } + + (*e)[i].Value = string(resolvedValue) + } + + return nil +} + +func (e *EnvList) AsExport() string { + // Process all ENVs into a string of form + // `export FOO="bar"; export BAR="baz";`. + exports := `` + for _, v := range *e { + exports += v.AsExport() + " " + } + return exports +} + type ErrMustUpdate struct { Msg string } @@ -173,7 +210,7 @@ func NewSupfile(file string) (*Supfile, error) { fallthrough - case "0.4": + case "0.4", "0.5": default: return nil, ErrMustUpdate{"unsupported version"}
Resolve ENV VARs locally
pressly_sup
train
97c261104f4ae9d1413b3d610ea11f14b4314ec6
diff --git a/jawr-core/src/main/java/net/jawr/web/minification/JSMin.java b/jawr-core/src/main/java/net/jawr/web/minification/JSMin.java index <HASH>..<HASH> 100644 --- a/jawr-core/src/main/java/net/jawr/web/minification/JSMin.java +++ b/jawr-core/src/main/java/net/jawr/web/minification/JSMin.java @@ -125,7 +125,9 @@ public class JSMin { theLookahead = EOF; if (c == EOF) { c = in.read(); - currentByteIndex++; + if (c != EOF){ + currentByteIndex++; + } } if (c == '\n') { line++;
Fix issue #<I> Exception in the error message generation from JSMin processor when an error is located at the end of the file
j-a-w-r_jawr-main-repo
train
c426ad75481d4f0a0bc29e1c89976a001ffa7b45
diff --git a/examples/hardfork_time.py b/examples/hardfork_time.py index <HASH>..<HASH> 100644 --- a/examples/hardfork_time.py +++ b/examples/hardfork_time.py @@ -6,7 +6,7 @@ dtime = datetime.datetime.now() # Add delay # class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) -dtime = dtime + datetime.timedelta(4) +dtime = dtime + datetime.timedelta(60 * 60 * 2) # print timestamp print(time.mktime(dtime.timetuple())) diff --git a/grapheneexchange/exchange.py b/grapheneexchange/exchange.py index <HASH>..<HASH> 100644 --- a/grapheneexchange/exchange.py +++ b/grapheneexchange/exchange.py @@ -858,10 +858,19 @@ class GrapheneExchange(GrapheneClient) : base = self.getObject(debt["call_price"]["base"]["asset_id"]) quote = self.getObject(debt["call_price"]["quote"]["asset_id"]) call_price = self._get_price(debt["call_price"]) + + bitasset = self.getObject(quote["bitasset_data_id"]) + settlement_price = self._get_price(bitasset["current_feed"]["settlement_price"]) + + collateral_amount = int(debt["collateral"]) / 10 ** base["precision"] + debt_amount = int(debt["debt"]) / 10 ** quote["precision"] + r[quote["symbol"]] = {"collateral_asset" : base["symbol"], - "collateral" : int(debt["collateral"]) / 10 ** base["precision"], - "debt" : debt["debt"] / 10 ** quote["precision"], - "call_price" : call_price} + "collateral" : collateral_amount, + "debt" : debt_amount, + "call_price" : call_price, + "settlement_price": settlement_price, + "ratio" : collateral_amount / debt_amount * settlement_price} return r def close_debt_position(self, symbol):
[Exchange] Add collateral ratio to output
xeroc_python-graphenelib
train
d424711cc98f3aa3c15a0e907100b493e73430f6
diff --git a/algolia/transport/transport.go b/algolia/transport/transport.go index <HASH>..<HASH> 100644 --- a/algolia/transport/transport.go +++ b/algolia/transport/transport.go @@ -94,7 +94,11 @@ func (t *Transport) Request( case Failure: return unmarshalToError(body) default: - _ = body.Close() + if body != nil { + if err = body.Close(); err != nil { + return fmt.Errorf("cannot close response's body before retry: %v", err) + } + } } } @@ -189,10 +193,13 @@ func buildRequest( } func unmarshalTo(r io.ReadCloser, v interface{}) error { - defer r.Close() err := json.NewDecoder(r).Decode(&v) + errClose := r.Close() if err != nil { - return fmt.Errorf("cannot deserialize response: %v", err) + return fmt.Errorf("cannot deserialize response's body: %v", err) + } + if errClose != nil { + return fmt.Errorf("cannot close response's body: %v", errClose) } return nil }
fixed: properly close and report errors upon response body closing
algolia_algoliasearch-client-go
train
5e35c60d88da150872e0c67b738f7e51b75355ed
diff --git a/lib/fluent/env_utils.rb b/lib/fluent/env_utils.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/env_utils.rb +++ b/lib/fluent/env_utils.rb @@ -16,12 +16,12 @@ module Fluent OJ_OPTIONS_ALLOWED_VALUES = { 'bigdecimal_load': %i[bigdecimal float auto], - 'mode': %i[strict null concat json rails object custom] + 'mode': %i[strict null compat json rails object custom] } OJ_OPTIONS_DEFAULTS = { 'bigdecimal_load': :float, - 'mode': :concat, + 'mode': :compat, 'use_to_json': true }
It is compat, and not concat
fluent_fluentd
train
638720c1ac740b88fab396d805540ee9bd8b51d3
diff --git a/java/OpenTamil/src/com/ezhillang/LOGO/EvalVisitor.java b/java/OpenTamil/src/com/ezhillang/LOGO/EvalVisitor.java index <HASH>..<HASH> 100644 --- a/java/OpenTamil/src/com/ezhillang/LOGO/EvalVisitor.java +++ b/java/OpenTamil/src/com/ezhillang/LOGO/EvalVisitor.java @@ -36,15 +36,29 @@ class EvalVisitor extends Visitor { } public void visit(ArgList obj) throws Exception { - obj.visit(this); + if ( obj == null) + return; + + // create identifiers of the name in arglist with values on the stack + for(int itr=obj.size()-1; itr >= 0; itr--) { + AST arg_var = obj.m_args.get(itr); + m_int.setInterpreter(arg_var,m_int.pop()); + } } public void visit(Function obj) throws Exception { - obj.visit(this); + /* evaluate function () code + if ( obj.m_args != null ) + obj.m_args.visit(this); + obj.m_function_body.visit(this); + */ + // copy this function body into list of known functions for interpreter. + System.out.println("Registering function => "+obj.m_name); } public void visit(Deref obj) throws Exception { - obj.visit(this); + m_int.push( m_int.getIdentifier( obj.m_var ) ); + return; } public void visit(UserWord obj) throws Exception { diff --git a/java/OpenTamil/src/com/ezhillang/LOGO/Interpreter.java b/java/OpenTamil/src/com/ezhillang/LOGO/Interpreter.java index <HASH>..<HASH> 100644 --- a/java/OpenTamil/src/com/ezhillang/LOGO/Interpreter.java +++ b/java/OpenTamil/src/com/ezhillang/LOGO/Interpreter.java @@ -98,6 +98,15 @@ public class Interpreter extends EvalVisitor implements IRuntimeFunction { // do something - update the state of the interpreter System.out.println("Evaluate function => "+function+ ( nargs > 0 ? " with args "+ ( args[0].toString()) : "")); } + + Object getIdentifier(String m_var) { + System.out.println("ID read =>"+m_var); + return m_var; + } + + void setInterpreter(AST idname, Object pop) { + System.out.println("Create interpreter variable => " + idname.toString() + " = "+pop.toString()); + } public class KnownWordFound { public boolean found;
0) Update interpreter to have mock code for simple evaluations. 1) Need to provide stack unrolling and actual functions for drawing, ops etc.
Ezhil-Language-Foundation_open-tamil
train
99c9311f5f34db7688ae0651a9c0529f5165e249
diff --git a/examples/pmc_mpi.py b/examples/pmc_mpi.py index <HASH>..<HASH> 100644 --- a/examples/pmc_mpi.py +++ b/examples/pmc_mpi.py @@ -72,7 +72,7 @@ parallel_sampler = pypmc.tools.parallel_sampler.MPISampler(SequentialIS, target= # make sure that every process has a different random number generator seed if comm.Get_rank() == 0: - seed = np.random.randint(1e17) + seed = np.random.randint(1e5) else: seed = None seed = comm.bcast(seed) diff --git a/pypmc/density/gauss_test.py b/pypmc/density/gauss_test.py index <HASH>..<HASH> 100644 --- a/pypmc/density/gauss_test.py +++ b/pypmc/density/gauss_test.py @@ -7,7 +7,7 @@ from .student_t_test import fake_rng import numpy as np import unittest -rng_seed = 128501257 +rng_seed = 128501257 % 4294967296 rng_steps = 50000 singular_sigma = np.array([[0.0, 0.0 , 0.0] diff --git a/pypmc/density/mixture_test.py b/pypmc/density/mixture_test.py index <HASH>..<HASH> 100644 --- a/pypmc/density/mixture_test.py +++ b/pypmc/density/mixture_test.py @@ -6,7 +6,7 @@ from .mixture import * import numpy as np import unittest -rng_seed = 12850419774 +rng_seed = 12850419774 % 4294967296 rng_steps = 50000 # dummy proposal component (convenient for testing): @@ -34,6 +34,9 @@ class TestMixtureDensity(unittest.TestCase): mix = MixtureDensity(proposals, weights) + def setUp(self): + np.random.seed(rng_seed) + def test_dimcheck(self): # dimensions of all components have to match @@ -159,6 +162,7 @@ class TestMixtureDensity(unittest.TestCase): prop = MixtureDensity(components) samples = prop.propose(50, shuffle=True) + print(samples) # make sure there is "+1" and "-1" within the first few samples self.assertAlmostEqual(samples[0][0], -1., delta=1.e-15) self.assertAlmostEqual(samples[1][0], +1., delta=1.e-15) diff --git a/pypmc/density/student_t_test.py b/pypmc/density/student_t_test.py index <HASH>..<HASH> 100644 --- a/pypmc/density/student_t_test.py +++ b/pypmc/density/student_t_test.py @@ -6,7 +6,7 @@ from .student_t import * import numpy as np import unittest -rng_seed = 12850419274 +rng_seed = 12850419274 % 4294967296 rng_steps = 50000 singular_sigma = np.array([[0.0, 0.0 , 0.0] diff --git a/pypmc/mix_adapt/pmc_test.py b/pypmc/mix_adapt/pmc_test.py index <HASH>..<HASH> 100644 --- a/pypmc/mix_adapt/pmc_test.py +++ b/pypmc/mix_adapt/pmc_test.py @@ -371,7 +371,7 @@ class TestGaussianPMCMultipleUpdates(unittest.TestCase): [-10.4898097 , 7.48668861, -2.41443733]]) def setUp(self): - np.random.mtrand.seed(345985345634) + np.random.mtrand.seed(345985345634 % 4294967296) def test_invalid_usage(self): self.assertRaisesRegexp(ValueError, r'["\'` ]*rb["\'` ]*must.*["\' `]*True["\'` ]* if["\'` ]*latent["\'` ]*.*not', @@ -487,7 +487,7 @@ class TestGaussianPMCMultipleUpdates(unittest.TestCase): class TestStudentTPMCMultipleUpdates(unittest.TestCase): def setUp(self): - np.random.mtrand.seed(3026281795684) + np.random.mtrand.seed(3026281795684 % 4294967296) @attr('slow') def test_prune(self):
cast all random seeds down to <I>bit, see Issue #<I>
fredRos_pypmc
train
5536a595816da76b7ca2fd1836ad8c3727298a49
diff --git a/lib/spring/test/application_generator.rb b/lib/spring/test/application_generator.rb index <HASH>..<HASH> 100644 --- a/lib/spring/test/application_generator.rb +++ b/lib/spring/test/application_generator.rb @@ -48,7 +48,7 @@ module Spring @version = RailsVersion.new(`ruby -e 'puts Gem::Specification.find_by_name("rails", "#{version_constraint}").version'`.chomp) - skips = %w(--skip-bundle --skip-javascript --skip-sprockets --skip-spring) + skips = %w(--skip-bundle --skip-javascript --skip-sprockets --skip-spring --skip-listen --skip-system-test) system("rails _#{version}_ new #{application.root} #{skips.join(' ')}") raise "application generation failed" unless application.exists?
skip system tests and listen for acceptance tests The listen gem was causing intermittent travis errors. System tests were causing a dependency on capybara, which caused build failures with ruby versions < <I>
rails_spring
train
42a7f11b5745acbf6d2c3a28422ce51dc6c1be3b
diff --git a/devassistant/cache.py b/devassistant/cache.py index <HASH>..<HASH> 100644 --- a/devassistant/cache.py +++ b/devassistant/cache.py @@ -7,6 +7,7 @@ except ImportError: from yaml import Dumper from devassistant import settings +from devassistant import version from devassistant import yaml_loader from devassistant import yaml_snippet_loader @@ -14,12 +15,20 @@ class Cache(object): def __init__(self, cache_file=settings.CACHE_FILE): self.cache_file = cache_file # TODO: try/catch creating the cache file, on failure don't use it - # TODO: version cache? - if not os.path.exists(cache_file): + reset_cache = False + if os.path.exists(self.cache_file): + self.cache = yaml_loader.YamlLoader.load_yaml_by_path(cache_file) or {} + if self.cache.get('version', '0.0.0') != version.VERSION: + reset_cache = True + else: if not os.path.exists(os.path.dirname(cache_file)): os.makedirs(os.path.dirname(cache_file)) - open(cache_file, 'w').close() - self.cache = yaml_loader.YamlLoader.load_yaml_by_path(cache_file) or {} + reset_cache = True + + if reset_cache: + f = open(cache_file, 'w') + self.cache = {'version': version.VERSION} + f.close() def refresh_role(self, role, file_hierarchy): if not role in self.cache: diff --git a/test/test_cache.py b/test/test_cache.py index <HASH>..<HASH> 100644 --- a/test/test_cache.py +++ b/test/test_cache.py @@ -2,8 +2,11 @@ import os import shutil import time +import yaml + from devassistant.cache import Cache from devassistant import settings +from devassistant.version import VERSION from devassistant.yaml_assistant_loader import YamlAssistantLoader # the paths in this dicts are truncated to make tests pass in any location @@ -49,7 +52,8 @@ correct_cache = \ 'source': 'test/fixtures/assistants/creator/f/g.yaml', 'subhierarchy': {}}}}}, 'modifier': {}, - 'preparer': {}} + 'preparer': {}, + 'version': VERSION} class TestCache(object): cf = settings.CACHE_FILE @@ -72,6 +76,11 @@ class TestCache(object): fh = YamlAssistantLoader.get_assistants_file_hierarchy(dirs) self.cch.refresh_role(role, fh) + def create_fake_cache(self, struct): + f = open(self.cch.cache_file, 'w') + yaml.dump(struct, stream=f) + f.close() + def datafile_path(self, path): """Assumes that settings.DATA_DIRECTORIES[0] is test/fixtures""" return os.path.join(settings.DATA_DIRECTORIES[0], path) @@ -167,3 +176,17 @@ class TestCache(object): os.unlink(self.datafile_path('assistants/creator/addme.yaml')) self.create_or_refresh_cache() assert 'addme' not in self.cch.cache['creator'] + + def test_cache_deletes_if_different_version(self): + self.create_fake_cache({'version': '0.0.0'}) + prev_time = os.path.getctime(self.cch.cache_file) + time.sleep(0.1) + Cache() + assert prev_time < os.path.getctime(self.cch.cache_file) + + def test_cache_stays_if_same_version(self): + self.create_fake_cache({'version': VERSION}) + prev_time = os.path.getctime(self.cch.cache_file) + time.sleep(0.1) + Cache() + assert prev_time == os.path.getctime(self.cch.cache_file)
Recreate cache if it was created with different devassistant version. Fixes #<I>
devassistant_devassistant
train
b00c2a0ba3bd7017dba5d547ae9dbe303942d7a2
diff --git a/src/Di/Di.php b/src/Di/Di.php index <HASH>..<HASH> 100644 --- a/src/Di/Di.php +++ b/src/Di/Di.php @@ -150,7 +150,7 @@ class Di /** * Checks if the class is instantiable - * @param mixed $type + * @param string $type * @return bool */ protected static function instantiable(string $type): bool @@ -162,8 +162,6 @@ class Di } return false; - -// return $type != 'Closure' && !is_callable($type) && class_exists($type); } /**
Updating doc-block and removing commented line
softberg_quantum-core
train
c304af0eecd600b9fd6d7342374b40b5d57ca9b1
diff --git a/Neos.Media/Classes/Command/MediaCommandController.php b/Neos.Media/Classes/Command/MediaCommandController.php index <HASH>..<HASH> 100644 --- a/Neos.Media/Classes/Command/MediaCommandController.php +++ b/Neos.Media/Classes/Command/MediaCommandController.php @@ -17,6 +17,7 @@ use Doctrine\ORM\EntityManager; use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; use Neos\Flow\Persistence\PersistenceManagerInterface; +use Neos\Media\Domain\Model\AssetInterface; use Neos\Media\Domain\Model\Image; use Neos\Media\Domain\Repository\AssetRepository; use Neos\Media\Domain\Repository\ThumbnailRepository; @@ -127,6 +128,54 @@ class MediaCommandController extends CommandController } /** + * Remove unused assets + * + * This command iterates over all existing assets, checks their usage count + * and lists the assets which are not reported as used by any AssetUsageStrategies. + * The unused assets can than be removed. + */ + public function removeUnusedCommand() + { + $iterator = $this->assetRepository->findAllIterator(); + $assetCount = $this->assetRepository->countAll(); + $unusedAssets = []; + $unusedAssetInfo = []; + $unusedAssetCount = 0; + + $this->outputLine('<b>Searching for unused assets:</b>'); + + $this->output->progressStart($assetCount); + /** @var AssetInterface $asset */ + foreach ($this->assetRepository->iterate($iterator) as $asset) { + if ($asset->getUsageCount() === 0) { + $unusedAssets[] = $asset; + $unusedAssetInfo[] = sprintf('- %s (%s)', $asset->getIdentifier(), $asset->getResource()->getFilename()); + $unusedAssetCount++; + } + $this->output->progressAdvance(1); + } + + if ($unusedAssetCount === 0) { + $this->output->outputLine(PHP_EOL . sprintf('No unused assets found.', $unusedAssetCount)); + $this->quit(0); + } + + $this->outputLine(PHP_EOL . 'Found the following unused assets: ' . PHP_EOL . implode(PHP_EOL, $unusedAssetInfo)); + + $continue = $this->output->askConfirmation(sprintf('Do you want to remove <b>%s</b> unused assets?', $unusedAssetCount)); + if ($continue !== true) { + $this->quit(0); + } + + $this->output->progressStart($unusedAssetCount); + foreach ($unusedAssets as $asset) { + $this->output->progressAdvance(1); + $this->assetRepository->remove($asset); + } + $this->outputLine(''); + } + + /** * Create thumbnails * * Creates thumbnail images based on the configured thumbnail presets. Optional ``preset`` parameter to only create
FEATURE: Introduce command to remove unused assets This command iterates over all existing assets, checks their usage count and lists the assets which are not reported as used by any AssetUsageStrategies. The unused assets can than be removed.
neos_neos-development-collection
train
a33d567a9f6399ed025a0acb560b4f1c32885c82
diff --git a/tests/ContentTypeMiddlewareTest.php b/tests/ContentTypeMiddlewareTest.php index <HASH>..<HASH> 100644 --- a/tests/ContentTypeMiddlewareTest.php +++ b/tests/ContentTypeMiddlewareTest.php @@ -14,7 +14,6 @@ use Psr\Http\Server\RequestHandlerInterface; use Zend\Diactoros\Response; use Zend\Diactoros\Response\EmptyResponse; use Zend\Diactoros\ServerRequest; -use function json_encode; /** * @coversDefaultClass \Lcobucci\ContentNegotiation\ContentTypeMiddleware @@ -27,6 +26,8 @@ final class ContentTypeMiddlewareTest extends TestCase * @covers ::__construct() * @covers ::fromRecommendedSettings() * @covers ::process() + * + * @uses \Lcobucci\ContentNegotiation\Formatter\Json */ public function processShouldReturnFormattedResponseDirectly(): void { @@ -48,6 +49,7 @@ final class ContentTypeMiddlewareTest extends TestCase * @covers ::formatResponse() * * @uses \Lcobucci\ContentNegotiation\UnformattedResponse + * @uses \Lcobucci\ContentNegotiation\Formatter\Json */ public function processShouldReturnAResponseWithErrorWhenFormatterWasNotFound(): void { @@ -75,6 +77,7 @@ final class ContentTypeMiddlewareTest extends TestCase * @covers ::formatResponse() * * @uses \Lcobucci\ContentNegotiation\UnformattedResponse + * @uses \Lcobucci\ContentNegotiation\Formatter\Json */ public function processShouldReturnAResponseWithFormattedContent(): void { @@ -90,7 +93,7 @@ final class ContentTypeMiddlewareTest extends TestCase self::assertInstanceOf(UnformattedResponse::class, $response); self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode()); self::assertSame('application/json; charset=UTF-8', $response->getHeaderLine('Content-Type')); - self::assertSame('{"id":1,"name":"Testing"}', (string) $response->getBody()); + self::assertJsonStringEqualsJsonString('{"id":1,"name":"Testing"}', (string) $response->getBody()); } /** @@ -103,6 +106,7 @@ final class ContentTypeMiddlewareTest extends TestCase * @covers ::formatResponse() * * @uses \Lcobucci\ContentNegotiation\UnformattedResponse + * @uses \Lcobucci\ContentNegotiation\Formatter\Json */ public function processShouldReturnAResponseWithFormattedContentEvenWithoutForcingTheCharset(): void { @@ -118,7 +122,7 @@ final class ContentTypeMiddlewareTest extends TestCase self::assertInstanceOf(UnformattedResponse::class, $response); self::assertSame(StatusCodeInterface::STATUS_OK, $response->getStatusCode()); self::assertSame('application/json', $response->getHeaderLine('Content-Type')); - self::assertSame('{"id":1,"name":"Testing"}', (string) $response->getBody()); + self::assertJsonStringEqualsJsonString('{"id":1,"name":"Testing"}', (string) $response->getBody()); } private function createRequestHandler(ResponseInterface $response): RequestHandlerInterface @@ -160,18 +164,7 @@ final class ContentTypeMiddlewareTest extends TestCase 'charset' => $forceCharset, ], ], - [ - 'application/json' => new class implements Formatter - { - /** - * {@inheritdoc} - */ - public function format($content): string - { - return (string) json_encode($content); - } - }, - ] + ['application/json' => new Formatter\Json()] ); } }
Use Json formatter in middleware test Just to simplify things a bit.
lcobucci_content-negotiation-middleware
train
b5f4caba18292ffb46cdff07a97cd0cdfbc25227
diff --git a/packages/build-tools/tasks/api-tasks/bolt-versions.js b/packages/build-tools/tasks/api-tasks/bolt-versions.js index <HASH>..<HASH> 100644 --- a/packages/build-tools/tasks/api-tasks/bolt-versions.js +++ b/packages/build-tools/tasks/api-tasks/bolt-versions.js @@ -136,18 +136,15 @@ async function gatherBoltVersionUrls() { let tags = await getBoltTags(); const tagUrls = []; - for (index = 0; index < tags.length; index++) { + for (let index = 0; index < tags.length; index++) { let tag = tags[index].name; let tagString = tag .replace(/\//g, '-') // `/` => `-` .replace('--', '-') // `--` => `-` .replace(/\./g, '-'); // `.` => `-` - const newSiteUrl = `https://${tagString}.boltdesignsystem.com`; - const oldSiteUrl = `https://${tagString}.bolt-design-system.com`; - - urlsToCheck.push(newSiteUrl); - urlsToCheck.push(oldSiteUrl); + const siteUrl = `https://${tagString}.boltdesignsystem.com`; + urlsToCheck.push(siteUrl); } let results; @@ -162,29 +159,25 @@ async function gatherBoltVersionUrls() { await store.save(); } - for (index = 0; index < tags.length; index++) { + for (let index = 0; index < tags.length; index++) { let tag = tags[index].name; let tagString = tag .replace(/\//g, '-') // `/` => `-` .replace('--', '-') // `--` => `-` .replace(/\./g, '-'); // `.` => `-` - const newSiteUrl = `https://${tagString}.boltdesignsystem.com`; - const oldSiteUrl = `https://${tagString}.bolt-design-system.com`; - if (semver.valid(tag)) { - if (results[newSiteUrl].status === 'alive') { - tagUrls.push({ - label: tag, - type: 'option', - value: newSiteUrl, - }); - } else if (results[oldSiteUrl].status === 'alive') { - tagUrls.push({ - label: tag, - type: 'option', - value: oldSiteUrl, - }); - } + const siteUrl = `https://${tagString}.boltdesignsystem.com`; + + if ( + semver.valid(tag) && + results[siteUrl] !== undefined && + results[siteUrl].status === 'alive' + ) { + tagUrls.push({ + label: tag, + type: 'option', + value: siteUrl, + }); } }
Fixing logic issues and removing code pointing the old website url
bolt-design-system_bolt
train
a04aa25f67cdfaaeaee9a162b447f6897fe32b2a
diff --git a/lib/protractor.js b/lib/protractor.js index <HASH>..<HASH> 100644 --- a/lib/protractor.js +++ b/lib/protractor.js @@ -201,8 +201,10 @@ var Protractor = function(webdriverInstance, opt_baseUrl, opt_rootElement) { // Safari accepts data urls, but SafariDriver fails after one is used. // PhantomJS produces a "Detected a page unload event" if we use data urls var browserName = caps.get('browserName'); - if (browserName === 'internet explorer' || browserName === 'safari' || browserName === 'phantomjs') { - self.resetUrl = 'about:blank'; + if (browserName === 'internet explorer' || + browserName === 'safari' || + browserName === 'phantomjs') { + self.resetUrl = 'about:blank'; } });
chore(style): shorten long line, which was affecting tests
angular_protractor
train
6b51bb362d6f618e6d899062b57a704514973b57
diff --git a/guake/terminal.py b/guake/terminal.py index <HASH>..<HASH> 100644 --- a/guake/terminal.py +++ b/guake/terminal.py @@ -72,7 +72,7 @@ except Exception as e: sys.stderr.write( "[WARN] Some feature might not work:\n" "[WARN] - 'exit' command might freeze the terminal instead of closing the tab\n" - "[WARN] - the 'wall' command is know to work badly\n" + "[WARN] - the 'wall' command is known to work badly\n" ) sys.stderr.write("[WARN] Error: " + str(e) + '\n') sys.stderr.write(
Typo in terminal.py Hi team, Got to know about this project while finding alternatives to terminator (somehow I never liked it). I am still trying it out and would love to contribute. And it is in Python (a great plus for me). Hope I can bring some value to the project.
Guake_guake
train
30c6b29ea9f83861bc38bb03255eaac3ac638b48
diff --git a/examples/opencv-face-tracking.js b/examples/opencv-face-tracking.js index <HASH>..<HASH> 100644 --- a/examples/opencv-face-tracking.js +++ b/examples/opencv-face-tracking.js @@ -41,7 +41,7 @@ async.forever( for (var i = 0; i < faces.length; i++) { var face = faces[i]; im.rectangle([face.x, face.y], - [face.x + face.width, face.y + face.height], [0, 255, 0], 2); + [face.width, face.height], [0, 255, 0], 2); } w.show(im);
Don't add face.x and face.y to draw a rectangle
hybridgroup_node-bebop
train
b8e4c9918c46995a1de53336697c2742b35acf56
diff --git a/lib/nancy/base.rb b/lib/nancy/base.rb index <HASH>..<HASH> 100644 --- a/lib/nancy/base.rb +++ b/lib/nancy/base.rb @@ -65,7 +65,7 @@ module Nancy end def route_eval(request_method, path_info) - path_info = "/#{path_info}" unless path_info[0] == "/" + path_info = "/" if path_info == "" self.class.route_set[request_method].each do |matcher, block| if match = path_info.match(matcher[0]) if (captures = match.captures) && !captures.empty?
Set PATH_INFO to '/' when is blank
guilleiguaran_nancy
train
c13a04ad2af78d162eb7b126e9a77ec73c4c063f
diff --git a/chainlet/concurrency/base.py b/chainlet/concurrency/base.py index <HASH>..<HASH> 100644 --- a/chainlet/concurrency/base.py +++ b/chainlet/concurrency/base.py @@ -80,6 +80,64 @@ class StoredFuture(object): raise exception # re-raise exception from execution +class AsyncChainResults(object): + def __init__(self, futures): + self._futures = iter(futures) + self._results = [] + self._exception = None + self._done = False + self._result_lock = threading.Lock() + + def _set_done(self): + if not self._done: + self._done = True + self._futures = None + self._result_lock = None + + def __iter__(self): + if self._done: + for item in self._results: + yield item + else: + for item in self._active_iter(): + yield item + if self._exception is not None: + raise self._exception + + def _active_iter(self): + result_idx = 0 + # fast-forward existing results + for item in self._results: + yield item + result_idx += 1 + # fetch remaining results safely + while self._futures and not self._exception: + # someone may have beaten us before we acquire this lock + # constraints must be rechecked as needed + with self._result_lock: + try: + result = self._results[result_idx] + except IndexError: + try: + future = next(self._futures) + except StopIteration: + break + try: + results = future.result + except Exception as err: + self._exception = err + break + else: + self._results.extend(results) + for item in results: + yield item + result_idx += 1 + else: + yield result + result_idx += 1 + self._done = True + + # canonical send # TODO: move to core as canonical_send(self, chunks) # NOTE: we *cannot* be lazy with generators here, but must diff --git a/chainlet/concurrency/thread.py b/chainlet/concurrency/thread.py index <HASH>..<HASH> 100644 --- a/chainlet/concurrency/thread.py +++ b/chainlet/concurrency/thread.py @@ -11,7 +11,7 @@ except ImportError: import queue from .. import chainlink -from .base import StoredFuture, canonical_send, CPU_CONCURRENCY +from .base import StoredFuture, canonical_send, CPU_CONCURRENCY, AsyncChainResults class ThreadPoolExecutor(object): @@ -97,64 +97,6 @@ class ThreadPoolExecutor(object): DEFAULT_EXECUTOR = ThreadPoolExecutor(CPU_CONCURRENCY * 5, 'chainlet_thread') -class AsyncChainResults(object): - def __init__(self, futures): - self._futures = iter(futures) - self._results = [] - self._exception = None - self._done = False - self._result_lock = threading.Lock() - - def _set_done(self): - if not self._done: - self._done = True - self._futures = None - self._result_lock = None - - def __iter__(self): - if self._done: - for item in self._results: - yield item - else: - for item in self._active_iter(): - yield item - if self._exception is not None: - raise self._exception - - def _active_iter(self): - result_idx = 0 - # fast-forward existing results - for item in self._results: - yield item - result_idx += 1 - # fetch remaining results safely - while self._futures and not self._exception: - # someone may have beaten us before we acquire this lock - # constraints must be rechecked as needed - with self._result_lock: - try: - result = self._results[result_idx] - except IndexError: - try: - future = next(self._futures) - except StopIteration: - break - try: - results = future.result - except Exception as err: - self._exception = err - break - else: - self._results.extend(results) - for item in results: - yield item - result_idx += 1 - else: - yield result - result_idx += 1 - self._done = True - - class ThreadLinkPrimitives(chainlink.LinkPrimitives): pass
moved AsyncChainResult to concurrency base
maxfischer2781_chainlet
train
1bcdfc0aec9a479442a1f38927e7e3a3102d8695
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -1,20 +1,36 @@ 'use strict'; +import accountInformation from './methods/account-information'; +import createEvent from './methods/create-event'; +import createNotificationChannel from './methods/create-notification-channel'; +import accountInformation from './methods/account-information'; +import createEvent from './methods/create-event'; +import createNotificationChannel from './methods/create-notification-channel'; +import deleteEvent from './methods/delete-event'; +import deleteNotificationChannel from './methods/delete-notification-channel'; +import freeBusy from './methods/free-busy'; +import listCalendars from './methods/list-calendars'; +import listNotificationChannels from './methods/list-notification-channels'; +import profileInformation from './methods/profile-information'; +import readEvents from './methods/read-events'; +import refreshAccessToken from './methods/refresh-access-token'; +import requestAccessToken from './methods/request-access-token'; +import revokeAuthorization from './methods/revoke-authorization'; + const methods = { - accountInformation: require('./methods/account-information'), - createEvent: require('./methods/create-event'), - createNotificationChannel: require('./methods/create-notification-channel'), - deleteEvent: require('./methods/delete-event'), - deleteNotificationChannel: require('./methods/delete-notification-channel'), - freeBusy: require('./methods/free-busy'), - listCalendars: require('./methods/list-calendars'), - listNotificationChannels: require('./methods/list-notification-channels'), - profileInformation: require('./methods/profile-information'), - readEvents: require('./methods/read-events'), - refreshAccessToken: require('./methods/refresh-access-token'), - requestAccessToken: require('./methods/request-access-token'), - revokeAuthorization: require('./methods/revoke-authorization') + accountInformation, + createEvent, + createNotificationChannel, + deleteEvent, + deleteNotificationChannel, + freeBusy, + listCalendars, + listNotificationChannels, + profileInformation, + readEvents, + refreshAccessToken, + requestAccessToken, + revokeAuthorization }; -module.exports = methods; - +export default methods;
improves style consistency in index.js
cronofy_cronofy-node
train
26f2563fae08a9abff6d681ba70338430c77e3e0
diff --git a/org.jenetics/src/jmh/java/org/jenetics/util/RandomEnginePerf.java b/org.jenetics/src/jmh/java/org/jenetics/util/RandomEnginePerf.java index <HASH>..<HASH> 100644 --- a/org.jenetics/src/jmh/java/org/jenetics/util/RandomEnginePerf.java +++ b/org.jenetics/src/jmh/java/org/jenetics/util/RandomEnginePerf.java @@ -113,5 +113,4 @@ RandomEnginePerf.ThreadLocalRandomPerf.nextDouble thrpt 20 208.822 ± 2.666 RandomEnginePerf.ThreadLocalRandomPerf.nextFloat thrpt 20 208.813 ± 3.790 ops/us RandomEnginePerf.ThreadLocalRandomPerf.nextInt thrpt 20 255.523 ± 2.263 ops/us RandomEnginePerf.ThreadLocalRandomPerf.nextLong thrpt 20 253.980 ± 3.081 ops/us - */
Update 'Random' performance tests.
jenetics_jenetics
train
2515cef22bb4e9bf1bdc66b5641cdbc51be25b3f
diff --git a/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Notifications.java b/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Notifications.java index <HASH>..<HASH> 100644 --- a/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Notifications.java +++ b/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/Notifications.java @@ -8,7 +8,7 @@ package org.eclipse.xtext.util; import org.eclipse.emf.common.notify.Notification; -import org.eclipse.emf.common.util.Diagnostic; +import org.eclipse.emf.ecore.resource.Resource.Diagnostic; /** * @author Sven Efftinge - Initial contribution and API diff --git a/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/OnChangeEvictingCache.java b/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/OnChangeEvictingCache.java index <HASH>..<HASH> 100644 --- a/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/OnChangeEvictingCache.java +++ b/plugins/org.eclipse.xtext.util/src/org/eclipse/xtext/util/OnChangeEvictingCache.java @@ -154,8 +154,10 @@ public class OnChangeEvictingCache implements IResourceScopeCache, INotification next.onEvict(this); } } - for (INotificationListener notificationListener : notificationListeners) { - notificationListener.notifyChanged(notification); + if (!ignoreNotifications) { + for (INotificationListener notificationListener : notificationListeners) { + notificationListener.notifyChanged(notification); + } } }
[Xtext] more changes about notifications
eclipse_xtext-core
train
b33809b556a72bc885ddd3af623de87830ee00f5
diff --git a/pysos/sos_script.py b/pysos/sos_script.py index <HASH>..<HASH> 100755 --- a/pysos/sos_script.py +++ b/pysos/sos_script.py @@ -577,9 +577,9 @@ class SoS_Workflow: env.locals = WorkflowDict() # initial values try: - env.locals['home'] = os.environ['HOME'] + env.locals['HOME'] = os.environ['HOME'] except: - env.locals['home'] = '.' + env.locals['HOME'] = '.' # env.locals['workflow_name'] = self.name env.locals['workdir'] = os.path.abspath('.') @@ -1159,7 +1159,7 @@ def sos_show(args, argv): else: script.show() except Exception as e: - if args.verbosity and int(args.verbosity) > 2: + if args.verbosity and args.verbosity > 2: print_traceback() env.logger.error(e) sys.exit(1) @@ -1175,7 +1175,7 @@ def sos_run(args, argv): env.run_mode == 'dryrun' workflow.run() except Exception as e: - if args.verbosity and int(args.verbosity) > 2: + if args.verbosity and args.verbosity > 2: print_traceback() env.logger.error(e) sys.exit(1) diff --git a/pysos/utils.py b/pysos/utils.py index <HASH>..<HASH> 100644 --- a/pysos/utils.py +++ b/pysos/utils.py @@ -193,7 +193,7 @@ class RuntimeEnvironments(object): def __init__(self): # logger self._logger = None - self._verbosity = '2' + self._verbosity = 2 self._logfile = None self._set_logger() # @@ -221,11 +221,11 @@ class RuntimeEnvironments(object): # output to standard output cout = logging.StreamHandler() levels = { - '0': logging.ERROR, - '1': logging.WARNING, - '2': logging.INFO, - '3': logging.DEBUG, - '4': logging.TRACE, + 0: logging.ERROR, + 1: logging.WARNING, + 2: logging.INFO, + 3: logging.DEBUG, + 4: logging.TRACE, None: logging.INFO } # @@ -250,7 +250,7 @@ class RuntimeEnvironments(object): # attribute verbosity # def _set_verbosity(self, v): - if v in ['0', '1', '2', '3', '4']: + if v in [0, 1, 2, 3, 4]: self._verbosity = v # reset logger to appropriate logging level self._set_logger() diff --git a/sos b/sos index <HASH>..<HASH> 100755 --- a/sos +++ b/sos @@ -26,7 +26,7 @@ import argparse from pysos import SOS_VERSION, SOS_FULL_VERSION, env, sos_run, sos_show def addCommonArgs(parser): - parser.add_argument('-v', '--verbosity', choices=['0', '1', '2', '3', '4'], + parser.add_argument('-v', '--verbosity', type=int, choices=range(5), help='''Output error (0), warning (1), info (2), debug (3) and trace (4) information to standard output (default to 2).'''), diff --git a/test/test_execute.py b/test/test_execute.py index <HASH>..<HASH> 100644 --- a/test/test_execute.py +++ b/test/test_execute.py @@ -51,6 +51,14 @@ for b in range(5): wf.run() self.assertEqual(env.locals.res, '01234') + def testGlobalVars(self): + '''Test SoS defined variables''' + script = SoS_Script(r""" +""") + wf = script.workflow() + wf.run() + self.assertEqual(env.locals.HOME, os.environ['HOME']) + def testSignature(self): '''Test recognizing the format of SoS script''' env.run_mode = 'run'
1. set args.verbosity to int instead of string. 2. change variable home to HOME.
vatlab_SoS
train
9f61c75f3dbc7c463ac3610844d31b513f4171bb
diff --git a/Classes/Emogrifier.php b/Classes/Emogrifier.php index <HASH>..<HASH> 100644 --- a/Classes/Emogrifier.php +++ b/Classes/Emogrifier.php @@ -304,7 +304,7 @@ class Emogrifier { $cssKey = md5($css); if (!isset($this->caches[self::CACHE_KEY_CSS][$cssKey])) { // process the CSS file for selectors and definitions - preg_match_all('/(?:^|[^{}])\\s*([^{]+){([^}]*)}/mis', $css, $matches, PREG_SET_ORDER); + preg_match_all('/(?:^|[\\s^{}]*)([^{]+){([^}]*)}/mis', $css, $matches, PREG_SET_ORDER); $allSelectors = array(); foreach ($matches as $key => $selectorString) { diff --git a/Tests/Unit/EmogrifierTest.php b/Tests/Unit/EmogrifierTest.php index <HASH>..<HASH> 100644 --- a/Tests/Unit/EmogrifierTest.php +++ b/Tests/Unit/EmogrifierTest.php @@ -489,6 +489,20 @@ class EmogrifierTest extends \PHPUnit_Framework_TestCase { /** * @test */ + public function emogrifyCanMatchMinifiedCss() { + $html = self::HTML5_DOCUMENT_TYPE . self::LF . '<html><p></p></html>' . self::LF; + $this->subject->setHtml($html); + $this->subject->setCss('p{color:blue;}html{color:red;}'); + + $this->assertContains( + '<html style="color:red;">', + $this->subject->emogrify() + ); + } + + /** + * @test + */ public function emogrifyLowercasesAttributeNamesFromStyleAttributes() { $html = self::HTML5_DOCUMENT_TYPE . self::LF . '<html style="COLOR:#ccc;"></html>'; $this->subject->setHtml($html);
[BUGFIX] Wrong selector extraction from minified CSS
MyIntervals_emogrifier
train
e23df9c7e0ba9d1b495292cf8c23c0fe4192b26d
diff --git a/VERSION b/VERSION index <HASH>..<HASH> 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.7.3 +0.7.4 diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -50,9 +50,9 @@ copyright = u'2014, cobrateam' # built documents. # # The short X.Y version. -version = '0.7.3' +version = '0.7.4' # The full version, including alpha/beta/rc tags. -release = '0.7.3' +release = '0.7.4' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ README = codecs.open('README.rst', encoding='utf-8').read() setup( name='splinter', - version='0.7.3', + version='0.7.4', url='https://github.com/cobrateam/splinter', description='browser abstraction for web acceptance testing', long_description=README,
setup: bump to <I>
cobrateam_splinter
train
bc4714c340c3be1a05b6a358c922d6476882b36c
diff --git a/web/src/main/java/uk/ac/ebi/atlas/trader/cache/CacheConfiguration.java b/web/src/main/java/uk/ac/ebi/atlas/trader/cache/CacheConfiguration.java index <HASH>..<HASH> 100644 --- a/web/src/main/java/uk/ac/ebi/atlas/trader/cache/CacheConfiguration.java +++ b/web/src/main/java/uk/ac/ebi/atlas/trader/cache/CacheConfiguration.java @@ -42,15 +42,11 @@ import javax.inject.Inject; @Configuration public class CacheConfiguration { - private static final int BASELINE_EXPERIMENTS_CACHE_MAX_SIZE = 50; - private static final int RNASEQ_DIFF_EXPERIMENTS_CACHE_MAX_SIZE = 100; - private static final int MICROARRAY_EXPERIMENTS_CACHE_MAX_SIZE = 2000; - @Bean(name="baselineExperimentsLoadingCache") @Inject public LoadingCache<String, BaselineExperiment> baselineExperimentsCache(BaselineExperimentsCacheLoader cacheLoader){ - return CacheBuilder.newBuilder().maximumSize(BASELINE_EXPERIMENTS_CACHE_MAX_SIZE).build(cacheLoader); + return CacheBuilder.newBuilder().build(cacheLoader); } @@ -58,7 +54,7 @@ public class CacheConfiguration { @Inject public LoadingCache<String, ProteomicsBaselineExperiment> proteomicsBaselineExperimentsCache(ProteomicsBaselineExperimentsCacheLoader cacheLoader){ - return CacheBuilder.newBuilder().maximumSize(BASELINE_EXPERIMENTS_CACHE_MAX_SIZE).build(cacheLoader); + return CacheBuilder.newBuilder().build(cacheLoader); } @@ -67,7 +63,7 @@ public class CacheConfiguration { @Inject public LoadingCache<String, DifferentialExperiment> differentialExperimentsCache(DifferentialExperimentsCacheLoader cacheLoader){ - return CacheBuilder.newBuilder().maximumSize(RNASEQ_DIFF_EXPERIMENTS_CACHE_MAX_SIZE).build(cacheLoader); + return CacheBuilder.newBuilder().build(cacheLoader); } @@ -75,7 +71,7 @@ public class CacheConfiguration { @Inject public LoadingCache<String, MicroarrayExperiment> microarrayExperimentsCache(MicroarrayExperimentsCacheLoader cacheLoader){ - return CacheBuilder.newBuilder().maximumSize(MICROARRAY_EXPERIMENTS_CACHE_MAX_SIZE).build(cacheLoader); + return CacheBuilder.newBuilder().build(cacheLoader); } @@ -83,7 +79,7 @@ public class CacheConfiguration { @Inject public LoadingCache<String, BarChartTrader> barChartTradersCache(BarChartTradersCacheLoader barChartTradersCacheLoader) { - return CacheBuilder.newBuilder().maximumSize(BASELINE_EXPERIMENTS_CACHE_MAX_SIZE).build(barChartTradersCacheLoader); + return CacheBuilder.newBuilder().build(barChartTradersCacheLoader); }
change to unbounded experiment caches (ie: no max size) so we can always store all experiments in memory (as the number of experiment grows). The only bound will be available memory.
ebi-gene-expression-group_atlas
train
5e7565a8a84a0448a94a95b1da2c7393c9531b0d
diff --git a/src/main/java/org/fit/layout/impl/DefaultLogicalArea.java b/src/main/java/org/fit/layout/impl/DefaultLogicalArea.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/fit/layout/impl/DefaultLogicalArea.java +++ b/src/main/java/org/fit/layout/impl/DefaultLogicalArea.java @@ -61,6 +61,12 @@ public class DefaultLogicalArea extends GenericTreeNode implements LogicalArea } @Override + public Area getFirstArea() + { + return ((Vector<Area>) areas).firstElement(); + } + + @Override public int getAreaCount() { return areas.size(); diff --git a/src/main/java/org/fit/layout/model/LogicalArea.java b/src/main/java/org/fit/layout/model/LogicalArea.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/fit/layout/model/LogicalArea.java +++ b/src/main/java/org/fit/layout/model/LogicalArea.java @@ -21,6 +21,8 @@ public interface LogicalArea extends AreaTreeNode<LogicalArea> public List<Area> getAreas(); + public Area getFirstArea(); + public int getAreaCount(); public void setText(String text);
API extension: first area in a logical area
FitLayout_api
train
219d69834541e14830905c1ea73fbfac3101161f
diff --git a/test/tests/date.js b/test/tests/date.js index <HASH>..<HASH> 100644 --- a/test/tests/date.js +++ b/test/tests/date.js @@ -192,7 +192,8 @@ namespace('Date', function () { equal(params.date, 13, 'Set object should expose date'); // Issue #572 No disambiguation of separated units - assertDateParsed('this week tuesday at 5pm', { future: true}, testGetWeekday(2, 0, 17)); + assertDateParsed('this week tuesday at 5pm', { future: true }, testGetWeekday(2, 0, 17)); + assertDateParsed('today at 5pm', { future: true }, new Date(now.getFullYear(), now.getMonth(), now.getDate(), 17)); });
Added extra test for last commit (#<I>).
andrewplummer_Sugar
train
76464c2b9db103ba5492ea0342de73934ffa7b45
diff --git a/openquake/nrmllib/risk/writers.py b/openquake/nrmllib/risk/writers.py index <HASH>..<HASH> 100644 --- a/openquake/nrmllib/risk/writers.py +++ b/openquake/nrmllib/risk/writers.py @@ -36,6 +36,10 @@ class LossCurveXMLWriter(object): :param float investigation_time: Investigation time (also known as Time Span) defined in the calculation which produced these results (in years). + :param str loss_type: + Loss type used in risk model input for the calculation producing this + output (examples: structural, non-structural, business-interruption, + fatalities) :param str source_model_tree_path: Id of the source model tree path (obtained by concatenating the IDs of the branches the path is made of) for which input hazard curves @@ -194,6 +198,10 @@ class AggregateLossCurveXMLWriter(object): :param float investigation_time: Investigation time (also known as Time Span) defined in the calculation which produced these results (in years). + :param str loss_type: + Loss type used in risk model input for the calculation producing this + output (examples: structural, non-structural, business-interruption, + fatalities) :param str source_model_tree_path: Id of the source model tree path (obtained by concatenating the IDs of the branches the path is made of) for which input hazard curves @@ -319,6 +327,10 @@ class LossMapWriter(object): :param float poe: Probability of exceedance used to interpolate the losses producing this loss map. + :param str loss_type: + Loss type used in risk model input for the calculation producing this + output (examples: structural, non-structural, business-interruption, + fatalities) :param str source_model_tree_path: Id of the source model tree path (obtained by concatenating the IDs of the branches the path is made of) for which input hazard curves @@ -546,8 +558,12 @@ class LossFractionsWriter(object): will be saved into. :attr str variable: The variable used for disaggregation - :attr str unit: + :attr str loss_unit: Attribute describing how the value of the assets has been measured. + :param str loss_type: + Loss type used in risk model input for the calculation producing this + output (examples: structural, non-structural, business-interruption, + fatalities) :attr str loss_category: Attribute describing the category (economic, population, buildings, etc..) of the losses producing this loss map. @@ -653,6 +669,10 @@ class BCRMapXMLWriter(object): The inflation discount rate. :param float asset_life_expectancy: The period of time in which the building is expected to be used. + :param str loss_type: + Loss type used in risk model input for the calculation producing this + output (examples: structural, non-structural, business-interruption, + fatalities) :param str source_model_tree_path: Id of the source model tree path (obtained by concatenating the IDs of the branches the path is made of) for which input hazard curves
Add docstring for loss_type
gem_oq-engine
train
721bffa97b93b362fdb996cf82762849b7ef8ac5
diff --git a/core/block_render_svg_horizontal.js b/core/block_render_svg_horizontal.js index <HASH>..<HASH> 100644 --- a/core/block_render_svg_horizontal.js +++ b/core/block_render_svg_horizontal.js @@ -201,8 +201,7 @@ Blockly.BlockSvg.prototype.updateColour = function() { } // Render block stroke - var colorShift = goog.color.darken(rgb, 0.1); - var strokeColor = goog.color.rgbArrayToHex(colorShift); + var strokeColor = this.getColourTertiary(); this.svgPath_.setAttribute('stroke', strokeColor); // Bump every dropdown to change its colour.
Implement stroke colour as tertiary colour
LLK_scratch-blocks
train
d2ba97d86bc22790dffbbc9b95bdaea0c42ff415
diff --git a/contribs/gmf/src/search/component.js b/contribs/gmf/src/search/component.js index <HASH>..<HASH> 100644 --- a/contribs/gmf/src/search/component.js +++ b/contribs/gmf/src/search/component.js @@ -394,12 +394,6 @@ gmf.search.component.SearchController_ = class { * @type {string} * @export */ - this.placeholder = ''; - - /** - * @type {string} - * @export - */ this.color; /**
Remove extra variable declaration in gmf.search controller
camptocamp_ngeo
train
4e503c9c42d5b1b310b64e079e4c7492fbe5e73a
diff --git a/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php b/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php +++ b/src/Illuminate/Console/Scheduling/ScheduleFinishCommand.php @@ -28,33 +28,14 @@ class ScheduleFinishCommand extends Command protected $hidden = true; /** - * The schedule instance. - * - * @var \Illuminate\Console\Scheduling\Schedule - */ - protected $schedule; - - /** - * Create a new command instance. - * - * @param \Illuminate\Console\Scheduling\Schedule $schedule - * @return void - */ - public function __construct(Schedule $schedule) - { - $this->schedule = $schedule; - - parent::__construct(); - } - - /** * Execute the console command. * + * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ - public function handle() + public function handle(Schedule $schedule) { - collect($this->schedule->events())->filter(function ($value) { + collect($schedule->events())->filter(function ($value) { return $value->mutexName() == $this->argument('id'); })->each->callAfterCallbacks($this->laravel); } diff --git a/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php b/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php +++ b/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php @@ -22,13 +22,6 @@ class ScheduleRunCommand extends Command protected $description = 'Run the scheduled commands'; /** - * The schedule instance. - * - * @var \Illuminate\Console\Scheduling\Schedule - */ - protected $schedule; - - /** * The 24 hour timestamp this scheduler command started running. * * @var \Illuminate\Support\Carbon; @@ -45,13 +38,10 @@ class ScheduleRunCommand extends Command /** * Create a new command instance. * - * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ - public function __construct(Schedule $schedule) + public function __construct() { - $this->schedule = $schedule; - $this->startedAt = Date::now(); parent::__construct(); @@ -60,17 +50,18 @@ class ScheduleRunCommand extends Command /** * Execute the console command. * + * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ - public function handle() + public function handle(Schedule $schedule) { - foreach ($this->schedule->dueEvents($this->laravel) as $event) { + foreach ($schedule->dueEvents($this->laravel) as $event) { if (! $event->filtersPass($this->laravel)) { continue; } if ($event->onOneServer) { - $this->runSingleServerEvent($event); + $this->runSingleServerEvent($schedule, $event); } else { $this->runEvent($event); } @@ -86,12 +77,13 @@ class ScheduleRunCommand extends Command /** * Run the given single server event. * + * @param \Illuminate\Console\Scheduling\Schedule $schedule * @param \Illuminate\Console\Scheduling\Event $event * @return void */ - protected function runSingleServerEvent($event) + protected function runSingleServerEvent($schedule, $event) { - if ($this->schedule->serverShouldRun($event, $this->startedAt)) { + if ($schedule->serverShouldRun($event, $this->startedAt)) { $this->runEvent($event); } else { $this->line('<info>Skipping command (has already run on another server):</info> '.$event->getSummaryForDisplay()); diff --git a/src/Illuminate/Foundation/Console/Kernel.php b/src/Illuminate/Foundation/Console/Kernel.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Foundation/Console/Kernel.php +++ b/src/Illuminate/Foundation/Console/Kernel.php @@ -99,12 +99,10 @@ class Kernel implements KernelContract protected function defineConsoleSchedule() { $this->app->singleton(Schedule::class, function ($app) { - return new Schedule($this->scheduleTimezone()); + return tap(new Schedule($this->scheduleTimezone()), function ($schedule) { + $this->schedule($schedule); + }); }); - - $schedule = $this->app->make(Schedule::class); - - $this->schedule($schedule); } /**
Deferred resolving of scheduler.
laravel_framework
train
44e82d6541a7be1eed08ea155b34946733145e06
diff --git a/src/analyse/callback/iterate/ThroughArray.php b/src/analyse/callback/iterate/ThroughArray.php index <HASH>..<HASH> 100644 --- a/src/analyse/callback/iterate/ThroughArray.php +++ b/src/analyse/callback/iterate/ThroughArray.php @@ -94,8 +94,7 @@ class ThroughArray extends AbstractCallback $output .= $this->pool->routing->analysisHub($model); } - $output .= $this->pool->render->renderSingeChildHr(); - - return $output; + + return $output . $this->pool->render->renderSingeChildHr(); } }
Microoptimizations for the array analysis.
brainworxx_kreXX
train
09cebbdc59c118bb31f7e2fdf328ed60a03385c7
diff --git a/src/core/lombok/javac/JavacResolution.java b/src/core/lombok/javac/JavacResolution.java index <HASH>..<HASH> 100644 --- a/src/core/lombok/javac/JavacResolution.java +++ b/src/core/lombok/javac/JavacResolution.java @@ -12,6 +12,7 @@ import javax.tools.DiagnosticListener; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol.TypeSymbol; +import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.code.Type.CapturedType; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type; @@ -388,6 +389,22 @@ public class JavacResolution { } private static JCExpression typeToJCTree(Type type, TreeMaker maker, JavacAST ast, boolean allowCompound) throws TypeNotConvertibleException { + int dims = 0; + Type type0 = type; + while (type0 instanceof ArrayType) { + dims++; + type0 = ((ArrayType)type0).elemtype; + } + + JCExpression result = typeToJCTree0(type0, maker, ast, allowCompound); + while (dims > 0) { + result = maker.TypeArray(result); + dims--; + } + return result; + } + + private static JCExpression typeToJCTree0(Type type, TreeMaker maker, JavacAST ast, boolean allowCompound) throws TypeNotConvertibleException { // NB: There's such a thing as maker.Type(type), but this doesn't work very well; it screws up anonymous classes, captures, and adds an extra prefix dot for some reason too. // -- so we write our own take on that here. diff --git a/src/core/lombok/javac/handlers/HandleVal.java b/src/core/lombok/javac/handlers/HandleVal.java index <HASH>..<HASH> 100644 --- a/src/core/lombok/javac/handlers/HandleVal.java +++ b/src/core/lombok/javac/handlers/HandleVal.java @@ -33,6 +33,7 @@ import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop; import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCNewArray; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; @ProviderFor(JavacASTVisitor.class) @@ -57,6 +58,11 @@ public class HandleVal extends JavacASTAdapter { return; } + if (local.init instanceof JCNewArray && ((JCNewArray)local.init).elemtype == null) { + localNode.addError("'val' is not compatible with array initializer expressions. Use the full form (new int[] { ... } instead of just { ... })"); + return; + } + local.mods.flags |= Flags.FINAL; JCExpression oldVarType = local.vartype; local.vartype = JavacResolution.createJavaLangObject(localNode.getTreeMaker(), localNode.getAst());
'val' in javac now errors out with an appropriate message on val x = { .. }, and arrays no longer cause "Symbol not found: Array" errors.
rzwitserloot_lombok
train
fab04c059757a2af4484210626fc0afc4271a084
diff --git a/openpnm/core/Base.py b/openpnm/core/Base.py index <HASH>..<HASH> 100644 --- a/openpnm/core/Base.py +++ b/openpnm/core/Base.py @@ -175,17 +175,19 @@ class Base(dict): prop = item.replace('pore.', '').replace('throat.', '') self.__setitem__(key+'.'+prop, value[item]) return - # Ensure that 'pore.foo.bar' does not exist before creating 'pore.foo' - for item in self.keys(): - if len(item.split('.')) > 2: - if key == '.'.join(item.split('.')[:2]): - raise Exception(key + ' is already in use as a subdict') - # Ensure that 'pore.foo' does not exist before creating 'pore.foo.bar' - if len(key.split('.')) > 2: + if key not in self.keys(): + # Ensure 'pore.foo.bar' does not exist before creating 'pore.foo' for item in self.keys(): - if '.'.join(key.split('.')[:2]) == item: - raise Exception(item + ' is already in use, cannot make ' + - 'a subdict') + if len(item.split('.')) > 2: + if key == '.'.join(item.split('.')[:2]): + raise Exception(key + ' is already in use as a ' + + 'subdict') + # Ensure 'pore.foo' does not exist before creating 'pore.foo.bar' + if len(key.split('.')) > 2: + for item in self.keys(): + if '.'.join(key.split('.')[:2]) == item: + raise Exception(item + ' is already in use, cannot ' + + 'make a subdict') value = sp.array(value, ndmin=1) # Convert value to an ndarray
Minor tweak so it only checks conflicts if key does not already exist
PMEAL_OpenPNM
train
4b73e0e9a47a1281e2d0576eef3c2d5edfffd4c4
diff --git a/lib/options.js b/lib/options.js index <HASH>..<HASH> 100644 --- a/lib/options.js +++ b/lib/options.js @@ -94,13 +94,18 @@ function merge(src, dest) { var topKeys = Object.keys(src); for (var i = 0; i < topKeys.length; i++) { var topKey = topKeys[i]; - var child = src[topKey]; - var childKeys = Object.keys(child); - for (var j = 0; j < childKeys.length; j++) { - var childKey = childKeys[j]; - var childValue = child[childKey]; - if (childValue !== undefined) { - dest[topKey][childKey] = childValue; + var srcChild = src[topKey]; + if (dest[topKey] === undefined) { + dest[topKey] = srcChild; + } + else { + var childKeys = Object.keys(srcChild); + for (var j = 0; j < childKeys.length; j++) { + var childKey = childKeys[j]; + var srcChildValue = srcChild[childKey]; + if (srcChildValue !== undefined) { + dest[topKey][childKey] = srcChildValue; + } } } }
Fixed a bug in the the `Options` code
APIDevTools_json-schema-ref-parser
train
338ac6a5b5d7c708279c9cf494b549af9090a57e
diff --git a/modules/page/html/render/private.js b/modules/page/html/render/private.js index <HASH>..<HASH> 100644 --- a/modules/page/html/render/private.js +++ b/modules/page/html/render/private.js @@ -28,6 +28,6 @@ exports.create = function (api) { }) ] - return api.feed.html.rollup(api.feed.pull.private, { prepend, windowSize: 50 }) + return api.feed.html.rollup(api.feed.pull.private, { prepend, windowSize: 200 }) }) }
private: include <I> messages in window
ssbc_patchwork
train
3184fc8ef8db4fbee0ba5f1226e7f82bc766a416
diff --git a/neural/afni.py b/neural/afni.py index <HASH>..<HASH> 100644 --- a/neural/afni.py +++ b/neural/afni.py @@ -132,9 +132,10 @@ def cdf(dset,p,subbrick=0): command = ['cdf','-p2t',info.subbricks[subbrick]['stat'],str(p)] + info.subbricks[subbrick]['params'] return float(subprocess.check_output(command).split()[2]) -def thresh_at(dset,p,subbrick=0,positive_only=False): +def thresh_at(dset,p,subbrick=0,positive_only=False,suffix=None): ''' returns a string containing an inline ``3dcalc`` command that thresholds the - given dataset at the specified *p*-value ''' + given dataset at the specified *p*-value, or will create a new dataset if a + suffix is given ''' t = cdf(dset,p,subbrick) expr = 'astep(a,%f)' % t if positive_only: @@ -142,7 +143,9 @@ def thresh_at(dset,p,subbrick=0,positive_only=False): subref = '-a%d' % subbrick if subbrick==0 and dset[-1]==']': subref = '-a' - return '3dcalc( %s %s -expr %s )' % (subref,dset,expr) + if suffix==None: + return '3dcalc( %s %s -expr %s )' % (subref,dset,expr) + nl.run(['3dcalc',subref,dset,'-expr',expr,'-prefix',suffix(dset,suffix)]) def voxel_count(dset,subbrick=0,p=None,positive_only=False): ''' returns the number of non-zero voxels, or number of voxels exceeding the given *p*-value threshold '''
thresh_at will now create file
azraq27_neural
train
ea3c728e59234ee9724e058494cf7e300990556c
diff --git a/src/main/java/de/btobastian/javacord/DiscordApi.java b/src/main/java/de/btobastian/javacord/DiscordApi.java index <HASH>..<HASH> 100644 --- a/src/main/java/de/btobastian/javacord/DiscordApi.java +++ b/src/main/java/de/btobastian/javacord/DiscordApi.java @@ -100,6 +100,7 @@ public interface DiscordApi { * The method only works for bot accounts! * * @return An invite link for this bot. + * @throws IllegalStateException If the current account is not {@link AccountType#BOT}. */ default String createBotInvite() { return new BotInviteBuilder(getClientId()).build(); @@ -111,6 +112,7 @@ public interface DiscordApi { * * @param permissions The permissions which should be granted to the bot. * @return An invite link for this bot. + * @throws IllegalStateException If the current account is not {@link AccountType#BOT}. */ default String createBotInvite(Permissions permissions) { return new BotInviteBuilder(getClientId()).setPermissions(permissions).build();
Added @throws JavaDoc comment to DiscordApi#createBotInvite()
Javacord_Javacord
train
4b664cba8507aba49e1fa2afe5132d059b3713b4
diff --git a/inbound.go b/inbound.go index <HASH>..<HASH> 100644 --- a/inbound.go +++ b/inbound.go @@ -115,7 +115,7 @@ func (c *Connection) handleCallReq(frame *Frame) bool { response.commonStatsTags = call.commonStatsTags setResponseHeaders(call.headers, response.headers) - go c.dispatchInbound(call) + go c.dispatchInbound(c.connID, call) return false } @@ -141,7 +141,7 @@ func (call *InboundCall) createStatsTags(connectionTags map[string]string) { } // dispatchInbound ispatches an inbound call to the appropriate handler -func (c *Connection) dispatchInbound(call *InboundCall) { +func (c *Connection) dispatchInbound(_ uint32, call *InboundCall) { c.log.Debugf("Received incoming call for %s from %s", call.ServiceName(), c.remotePeerInfo) if err := call.readOperation(); err != nil {
Pass connID to new goroutine for debugging Make it easier to debug from stack traces by adding connID to newly created goroutine.
uber_tchannel-go
train
4173dd5bbf4f67c6171b5473d15059c6b1684d0b
diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -83,10 +83,10 @@ "test:user:watch": "karma start --no-single-run --auto-watch --browsers ChromeHeadlessNoSandbox test/integration/user/karma.conf.js", "test:user:watchc": "karma start --no-single-run --browsers Chrome test/integration/user/karma.conf.js", "test:browser": "karma start --no-single-run --browsers Chrome test/unit/karma.conf.js", - "test:render": "yarn build:dev && mocha test/integration/render/render.test.js", + "test:render": "yarn build:dev && mocha test/integration/render/render.test.js --timeout 5000", "test:render:clean": "rm -rf test/integration/render/scenarios/**/**/reference.png", "test:render:prepare": "yarn build:dev && node test/integration/render/render.prepare.js ", - "test:e2e": "yarn build:dev && mocha test/acceptance/e2e.test.js", + "test:e2e": "yarn build:dev && mocha test/acceptance/e2e.test.js --timeout 10000", "test:e2e:clean": "rm -rf test/acceptance/e2e/**/reference.png", "test:e2e:prepare": "yarn build:dev && node test/acceptance/e2e.prepare.js ", "test:benchmark": "node test/benchmark/benchmark.js", diff --git a/test/acceptance/e2e.test.js b/test/acceptance/e2e.test.js index <HASH>..<HASH> 100644 --- a/test/acceptance/e2e.test.js +++ b/test/acceptance/e2e.test.js @@ -28,7 +28,7 @@ describe('E2E tests:', () => { it(util.getName(file), () => { const actual = util.testSST(file, template, browser); return chai.expect(actual).to.eventually.eq(0); - }).timeout(20000); + }); }); after(done => { diff --git a/test/integration/render/render.test.js b/test/integration/render/render.test.js index <HASH>..<HASH> 100644 --- a/test/integration/render/render.test.js +++ b/test/integration/render/render.test.js @@ -29,7 +29,7 @@ describe('Render tests:', () => { const actual = util.testSST(file, template, browser); // Temporary threshold (1px) to cover small renderer differences between Mac & Linux return chai.expect(actual).to.eventually.be.at.most(1); - }).timeout(10000); + }); }); after(done => {
Set timeouts in mocha cli
CartoDB_carto-vl
train
7d058b4c8198d1f83e30d60b67d33bf6d52a705d
diff --git a/go/vt/vtctld/action_repository.go b/go/vt/vtctld/action_repository.go index <HASH>..<HASH> 100644 --- a/go/vt/vtctld/action_repository.go +++ b/go/vt/vtctld/action_repository.go @@ -51,7 +51,8 @@ type actionTabletRecord struct { // ActionRepository is a repository of actions that can be performed // on a {Keyspace,Shard,Tablet}. -// the http.request object passed to the action will have parse(d)Form. +// Note that the registered action methods will be passed an *http.Request +// on which ParseForm() has already succeeded. type ActionRepository struct { keyspaceActions map[string]actionKeyspaceMethod shardActions map[string]actionShardMethod diff --git a/go/vt/vtctld/api.go b/go/vt/vtctld/api.go index <HASH>..<HASH> 100644 --- a/go/vt/vtctld/api.go +++ b/go/vt/vtctld/api.go @@ -129,22 +129,20 @@ func initAPI(ctx context.Context, ts topo.Server, actions *ActionRepository, rea return ts.GetKeyspace(ctx, keyspace) // Perform an action on a keyspace. case "POST": - time.Sleep(4000 * time.Millisecond) if keyspace == "" { return nil, errors.New("A POST request needs a keyspace in the URL") } if err := r.ParseForm(); err != nil { return nil, err } - //body, _ := ioutil.ReadAll(r.Body) action := r.FormValue("action") if action == "" { - return nil, errors.New("A POST request must specify action" /* + string(body) + " | " + r.Form.Encode() + " |"*/) + return nil, errors.New("A POST request must specify action") } return actions.ApplyKeyspaceAction(ctx, action, keyspace, r), nil default: - return nil, errors.New("The VTCTLD API only supports the GET and POST Methods. Please use a GET request or include the specific action you desire in the body of a POST request") + return nil, fmt.Errorf("unsupported HTTP method: %v", r.Method) } }) diff --git a/go/vt/vtctld/vtctld.go b/go/vt/vtctld/vtctld.go index <HASH>..<HASH> 100644 --- a/go/vt/vtctld/vtctld.go +++ b/go/vt/vtctld/vtctld.go @@ -78,21 +78,15 @@ func InitVtctld(ts topo.Server) { func(ctx context.Context, wr *wrangler.Wrangler, keyspace string, r *http.Request) (string, error) { shardingColumnName := r.FormValue("shardingColumnName") shardingColumnType := r.FormValue("shardingColumnType") - forceString := r.FormValue("force") - force := false - if forceString == "true" { - force = true - } + force := r.FormValue("force") == "true" - kit := topodatapb.KeyspaceIdType_UNSET - var err error kit, err = key.ParseKeyspaceIDType(shardingColumnType) if err != nil { return "", err } - keyspaceIDTypeSet := (kit != topodatapb.KeyspaceIdType_UNSET) - columnNameSet := (shardingColumnName != "") + keyspaceIDTypeSet := kit != topodatapb.KeyspaceIdType_UNSET + columnNameSet := shardingColumnName != "" if (keyspaceIDTypeSet && !columnNameSet) || (!keyspaceIDTypeSet && columnNameSet) { return "", fmt.Errorf("Both <column name> and <column type> must be set, or both must be unset.") } @@ -101,11 +95,7 @@ func InitVtctld(ts topo.Server) { actionRepo.RegisterKeyspaceAction("DeleteKeyspace", func(ctx context.Context, wr *wrangler.Wrangler, keyspace string, r *http.Request) (string, error) { - recursiveString := r.FormValue("recursive") - recursive := false - if recursiveString == "true" { - recursive = true - } + recursive := r.FormValue("recursive") == "true" return "", wr.DeleteKeyspace(ctx, keyspace, recursive) })
Addressed all comments by enisoc and mberlin
vitessio_vitess
train
594eed5d2bd8cbfc4580ba06f828ac32bb01ec53
diff --git a/library/src/main/java/com/coolerfall/download/DownloadManager.java b/library/src/main/java/com/coolerfall/download/DownloadManager.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/coolerfall/download/DownloadManager.java +++ b/library/src/main/java/com/coolerfall/download/DownloadManager.java @@ -38,7 +38,7 @@ public final class DownloadManager { return -1; } - request.setDownloader(downloader); + request.setDownloader(downloader.copy()); /* add download request into download request queue */ return downloadRequestQueue.add(request) ? request.downloadId() : -1; diff --git a/library/src/main/java/com/coolerfall/download/Downloader.java b/library/src/main/java/com/coolerfall/download/Downloader.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/coolerfall/download/Downloader.java +++ b/library/src/main/java/com/coolerfall/download/Downloader.java @@ -41,4 +41,9 @@ public interface Downloader { * Close downloader and stop downloader. */ void close(); + + /** + * Make a copy for this downloader. + */ + Downloader copy(); } diff --git a/library/src/main/java/com/coolerfall/download/OkHttpDownloader.java b/library/src/main/java/com/coolerfall/download/OkHttpDownloader.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/coolerfall/download/OkHttpDownloader.java +++ b/library/src/main/java/com/coolerfall/download/OkHttpDownloader.java @@ -93,6 +93,7 @@ public final class OkHttpDownloader implements Downloader { body = response.body(); switch (statusCode) { case 200: + case 206: return statusCode; case 301: @@ -107,9 +108,6 @@ public final class OkHttpDownloader implements Downloader { } else { throw new DownloadException(statusCode, response.message()); } - - default: - body.close(); } return statusCode; @@ -129,6 +127,10 @@ public final class OkHttpDownloader implements Downloader { } } + @Override public Downloader copy() { + return create(client); + } + /* read response content length from server */ long getContentLength(ResponseBody body) { if (body == null) { diff --git a/library/src/main/java/com/coolerfall/download/URLDownloader.java b/library/src/main/java/com/coolerfall/download/URLDownloader.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/coolerfall/download/URLDownloader.java +++ b/library/src/main/java/com/coolerfall/download/URLDownloader.java @@ -114,6 +114,10 @@ public final class URLDownloader implements Downloader { } } + @Override public Downloader copy() { + return create(); + } + /* read response content length from server */ int getContentLength(HttpURLConnection conn) { String transferEncoding = conn.getHeaderField(TRANSFER_ENCODING);
Fix breakpoint downloading for OkHttpDownloader, and add coy method in Downloader so we can get a new instance when create a new DownloadRequest
Coolerfall_Android-HttpDownloadManager
train
8404a356b2f80cc8ef03dececaaccc8f10e19515
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * [improvement] Add `add` alias for `shelly config create` * [improvement] Add `new` and `create` aliases for `shelly user add` * [improvement] Add `new` alias for `shelly backup create` +* [improvement] Add `new` and `create` aliases for `shelly organization add` ## 0.4.24 / 2014-02-25 diff --git a/lib/shelly/cli/organization.rb b/lib/shelly/cli/organization.rb index <HASH>..<HASH> 100644 --- a/lib/shelly/cli/organization.rb +++ b/lib/shelly/cli/organization.rb @@ -6,7 +6,7 @@ module Shelly namespace :organization include Helpers - before_hook :logged_in?, :only => [:list, :add] + before_hook :logged_in?, :only => [:list, :add, :create, :new] desc "list", "Lists organizations" def list @@ -27,6 +27,8 @@ module Shelly method_option "redeem-code", :type => :string, :aliases => "-r", :desc => "Redeem code for free credits" desc "add", "Add a new organization" + map "create" => :add + map "new" => :add def add create_new_organization(options) rescue Client::ValidationException => e diff --git a/spec/shelly/cli/organization_spec.rb b/spec/shelly/cli/organization_spec.rb index <HASH>..<HASH> 100644 --- a/spec/shelly/cli/organization_spec.rb +++ b/spec/shelly/cli/organization_spec.rb @@ -53,6 +53,21 @@ describe Shelly::CLI::Organization do hooks(@cli, :add).should include(:logged_in?) end + context "for aliases" do + [:new, :create].each do |a| + it "should respond to '#{a}' alias" do + @organization.should_receive(:create) + fake_stdin("org-name") do + invoke(@cli, a) + end + end + + it "should ensure user has logged in for '#{a}' alias" do + hooks(@cli, a).should include(:logged_in?) + end + end + end + it "should create new organization" do @organization.should_receive(:create) $stdout.should_receive(:print).with("Organization name (foo - default): ")
Add `new` and `create` aliases for `shelly organization add` [#<I>]
Ragnarson_shelly
train
d8b04ecb8aa51d21590f3d655775292a045a3ac2
diff --git a/calls.go b/calls.go index <HASH>..<HASH> 100644 --- a/calls.go +++ b/calls.go @@ -179,6 +179,23 @@ func (c *CallService) GetCallsInRange(start time.Time, end time.Time, data url.V } } +// GetNextCallsInRange retrieves the page at the nextPageURI and continues +// retrieving pages until any results are found in the range given by start or +// end, or we determine there are no more records to be found in that range. +// +// If CallPage is non-nil, it will have at least one result. +func (c *CallService) GetNextCallsInRange(ctx context.Context, start time.Time, end time.Time, nextPageURI string) CallPageIterator { + if nextPageURI == "" { + panic("nextpageuri is empty") + } + iter := NewNextPageIterator(c.client, callsPathPart) + return &callDateIterator{ + start: start, + end: end, + p: iter, + } +} + type callDateIterator struct { p *PageIterator start time.Time diff --git a/messages.go b/messages.go index <HASH>..<HASH> 100644 --- a/messages.go +++ b/messages.go @@ -194,6 +194,23 @@ func (c *MessageService) GetMessagesInRange(start time.Time, end time.Time, data } } +// GetNextMessagesInRange retrieves the page at the nextPageURI and continues +// retrieving pages until any results are found in the range given by start or +// end, or we determine there are no more records to be found in that range. +// +// If MessagePage is non-nil, it will have at least one result. +func (c *MessageService) GetNextMessagesInRange(ctx context.Context, start time.Time, end time.Time, nextPageURI string) MessagePageIterator { + if nextPageURI == "" { + panic("nextpageuri is empty") + } + iter := NewNextPageIterator(c.client, messagesPathPart) + return &messageDateIterator{ + start: start, + end: end, + p: iter, + } +} + type messageDateIterator struct { p *PageIterator start time.Time diff --git a/page.go b/page.go index <HASH>..<HASH> 100644 --- a/page.go +++ b/page.go @@ -56,12 +56,13 @@ func (p *PageIterator) SetNextPageURI(npuri types.NullString) { // Next asks for the next page of resources and decodes the results into v. func (p *PageIterator) Next(ctx context.Context, v interface{}) error { var err error - if p.count == 0 { + switch { + case p.nextPageURI.Valid: + err = p.client.GetNextPage(ctx, p.nextPageURI.String, v) + case p.count == 0: err = p.client.ListResource(ctx, p.pathPart, p.data, v) - } else if p.nextPageURI.Valid == false { + default: return NoMoreResults - } else { - err = p.client.GetNextPage(ctx, p.nextPageURI.String, v) } if err != nil { return err @@ -70,6 +71,9 @@ func (p *PageIterator) Next(ctx context.Context, v interface{}) error { return nil } +// NewPageIterator returns a PageIterator that can be used to iterate through +// values. Call Next() to get the first page of values (and again to get +// subsequent pages). If there are no more results, NoMoreResults is returned. func NewPageIterator(client *Client, data url.Values, pathPart string) *PageIterator { return &PageIterator{ data: data, @@ -80,6 +84,24 @@ func NewPageIterator(client *Client, data url.Values, pathPart string) *PageIter } } +// NewNextPageIterator returns a PageIterator based on the provided +// nextPageURI, and is designed for iterating if you have a nextPageURI and not +// a list of query values. +// +// NewNextPageIterator panics if nextPageURI is empty. +func NewNextPageIterator(client *Client, nextPageURI string) *PageIterator { + if nextPageURI == "" { + panic("nextpageuri is empty") + } + return &PageIterator{ + data: url.Values{}, + client: client, + nextPageURI: types.NullString{Valid: true, String: nextPageURI}, + pathPart: "", + count: 0, + } +} + // containsResultsInRange returns true if any results are in the range // [start, end). func containsResultsInRange(start time.Time, end time.Time, results []time.Time) bool {
Add start/end filters if you have a NextPageURI This way you can start with a NextPageURI and still only get resources that match the given time range.
saintpete_twilio-go
train
ae5d46af448fc33ef74eee99c5a3d686c8d26e72
diff --git a/tests/test_mongoengine.py b/tests/test_mongoengine.py index <HASH>..<HASH> 100644 --- a/tests/test_mongoengine.py +++ b/tests/test_mongoengine.py @@ -61,10 +61,20 @@ class MongoEngineTestCase(unittest.TestCase): db_name = os.environ.get('MONGO_DATABASE', 'factory_boy_test') db_host = os.environ.get('MONGO_HOST', 'localhost') db_port = int(os.environ.get('MONGO_PORT', '27017')) + MONGOD_TIMEOUT_MS = 100 @classmethod def setUpClass(cls): - cls.db = mongoengine.connect(cls.db_name, host=cls.db_host, port=cls.db_port) + from pymongo import read_preferences as mongo_rp + cls.db = mongoengine.connect( + db=cls.db_name, + host=cls.db_host, + port=cls.db_port, + # PyMongo>=2.1 requires an explicit read_preference. + read_preference=mongo_rp.ReadPreference.PRIMARY, + # PyMongo>=2.1 has a 20s timeout, use 100ms instead + serverselectiontimeoutms=cls.MONGOD_TIMEOUT_MS, + ) @classmethod def tearDownClass(cls):
Fix tests with latest pymongo/mongoengine. mongoengine>=<I> and pymongo>=<I> require extra parameters: - The server connection timeout was set too high - We have to define a ``read_preference``.
FactoryBoy_factory_boy
train
af046d87b2ed5059b59f14942e7265f7a14067b4
diff --git a/modules/social_features/social_follow_content/src/Plugin/ActivityContext/FollowContentActivityContext.php b/modules/social_features/social_follow_content/src/Plugin/ActivityContext/FollowContentActivityContext.php index <HASH>..<HASH> 100644 --- a/modules/social_features/social_follow_content/src/Plugin/ActivityContext/FollowContentActivityContext.php +++ b/modules/social_features/social_follow_content/src/Plugin/ActivityContext/FollowContentActivityContext.php @@ -4,6 +4,8 @@ namespace Drupal\social_follow_content\Plugin\ActivityContext; use Drupal\activity_creator\Plugin\ActivityContextBase; use Drupal\activity_creator\ActivityFactory; +use Drupal\node\Entity\Node; +use Drupal\social_comment\Entity\Comment; use Drupal\user\UserInterface; /** @@ -73,6 +75,22 @@ class FollowContentActivityContext extends ActivityContextBase { break; } + // The owner of a node automatically follows his / her own content. + // Because of this, we do not want to send a follow notification. + if ($original_related_entity instanceof Comment) { + // What is our original node? + // We need to compare the owner ID of the original node to the one + // being the current recipient. If that is the same, dont send the + // notification. + $original_node = $original_related_entity->getCommentedEntity(); + if ($original_node instanceof \Drupal\social_node\Entity\Node) { + $original_author = $original_node->getOwnerId(); + if ($recipient->id() !== $original_author) { + break; + } + } + } + if ($recipient->id() !== $original_related_entity->getOwnerId() && $original_related_entity->access('view', $recipient)) { $recipients[] = [ 'target_type' => 'user', @@ -80,7 +98,6 @@ class FollowContentActivityContext extends ActivityContextBase { ]; } } - return $recipients; }
Issue #<I> by sjoerdvandervis: Alter the FollowContentActivityContext so that no notification is sent towards the content owner. This because the content owner will receive a notification anyway as there has been activity with his content
goalgorilla_open_social
train
d9fb197300fda426347e57c0bd48aa7c2a47b8d3
diff --git a/splinter/browser.py b/splinter/browser.py index <HASH>..<HASH> 100644 --- a/splinter/browser.py +++ b/splinter/browser.py @@ -1,24 +1,15 @@ # -*- coding: utf-8 -*- -import warnings - from splinter.driver.webdriver.firefox import WebDriver as FirefoxWebDriver from splinter.driver.webdriver.chrome import WebDriver as ChromeWebDriver from splinter.exceptions import DriverNotFoundError +from splinter.utils import deprecate_driver_class -def deprecate(cls, message): - def new_init(self, *args, **kwargs): - cls.__init__(self, *args, **kwargs) - warnings.warn(message, DeprecationWarning) - - cls_dict = dict(cls.__dict__) - cls_dict['__init__'] = new_init - return type("Deprecated%s" % cls.__name__, (cls,), cls_dict) _DRIVERS = { 'firefox': FirefoxWebDriver, 'chrome': ChromeWebDriver, - 'webdriver.chrome': deprecate(ChromeWebDriver, message="'webdriver.chrome' is deprecated, use just 'chrome'"), - 'webdriver.firefox': deprecate(FirefoxWebDriver, message="'webdriver.firefox' is deprecated, use just 'firefox'"), + 'webdriver.chrome': deprecate_driver_class(ChromeWebDriver, message="'webdriver.chrome' is deprecated, use just 'chrome'"), + 'webdriver.firefox': deprecate_driver_class(FirefoxWebDriver, message="'webdriver.firefox' is deprecated, use just 'firefox'"), } try: diff --git a/splinter/utils.py b/splinter/utils.py index <HASH>..<HASH> 100644 --- a/splinter/utils.py +++ b/splinter/utils.py @@ -6,3 +6,13 @@ def warn_deprecated(method, deprecated_method_name): warnings.warn("'%s' is deprecated, use '%s' instead." % (deprecated_method_name, method.__name__), DeprecationWarning, stacklevel=2) return method(*args, **kwargs) return deprecated_method + + +def deprecate_driver_class(cls, message): + def new_init(self, *args, **kwargs): + cls.__init__(self, *args, **kwargs) + warnings.warn(message, DeprecationWarning) + + cls_dict = dict(cls.__dict__) + cls_dict['__init__'] = new_init + return type("Deprecated%s" % cls.__name__, (cls,), cls_dict) diff --git a/tests/test_browser.py b/tests/test_browser.py index <HASH>..<HASH> 100644 --- a/tests/test_browser.py +++ b/tests/test_browser.py @@ -7,6 +7,7 @@ import warnings from nose.tools import assert_equals, raises from splinter.exceptions import DriverNotFoundError +from splinter.utils import deprecate_driver_class class BrowserTest(unittest.TestCase): @@ -23,20 +24,18 @@ class BrowserDeprecationTest(unittest.TestCase): pass def test_should_deprecate_with_the_given_message(self): - from splinter.browser import deprecate with warnings.catch_warnings(record=True) as warnings_list: warnings.simplefilter('default') - cls = deprecate(self.Foo, message="Foo was deprecated") + cls = deprecate_driver_class(self.Foo, message="Foo was deprecated") cls() warning = warnings_list[0] assert type(warning.message) is DeprecationWarning assert_equals("Foo was deprecated", warning.message.args[0]) def test_should_prepend_a_Deprecated_to_class(self): - from splinter.browser import deprecate with warnings.catch_warnings(record=True): warnings.simplefilter('default') - cls = deprecate(self.Foo, message="Foo was deprecated") + cls = deprecate_driver_class(self.Foo, message="Foo was deprecated") assert_equals("DeprecatedFoo", cls.__name__) def test_webdriverfirefox_should_be_deprecated(self):
Refactoring deprecation method for driver classes
cobrateam_splinter
train
2bfc558ec9c83573734efed416e651d486a1243c
diff --git a/lib/resource/index.js b/lib/resource/index.js index <HASH>..<HASH> 100644 --- a/lib/resource/index.js +++ b/lib/resource/index.js @@ -212,12 +212,19 @@ var instnace = new Resource({ pk:'user_id', defaultFormat:'text/xml', collection:'users' - listMethodsAllowed:{ - get:true, - put:false, - post:false - delete:false - }serializer + allowed:{ + list:{ + get:true, + put:false, + post:false + delete:false + }, + detail:{ + get:true, + put:true, + post:false + } + } }) */ Resource = new Class({
fixing up the resource documentaion had the old methodsallowed junk in there
node-tastypie_tastypie
train
a3f7dd396c903409d3f72199e610ab3a9c01dbd0
diff --git a/dateparser/freshness_date_parser.py b/dateparser/freshness_date_parser.py index <HASH>..<HASH> 100644 --- a/dateparser/freshness_date_parser.py +++ b/dateparser/freshness_date_parser.py @@ -69,10 +69,10 @@ class FreshnessDateDataParser(object): break td = relativedelta(**kwargs) - if 'ago' in date_string: - date = self.now - td - elif 'in' in date_string: + if re.search(r'\bin\b', date_string): date = self.now + td + else: + date = self.now - td return date, period def get_kwargs(self, date_string): diff --git a/tests/test_freshness_date_parser.py b/tests/test_freshness_date_parser.py index <HASH>..<HASH> 100644 --- a/tests/test_freshness_date_parser.py +++ b/tests/test_freshness_date_parser.py @@ -314,6 +314,7 @@ class TestFreshnessDateDataParser(BaseTestCase): param('1 day ago at 2 PM', date(2014, 8, 31), time(14, 0)), param('Dnes v 12:40', date(2014, 9, 1), time(12, 40)), param('1 week ago at 12:00 am', date(2014, 8, 25), time(0, 0)), + param('tomorrow at 2 PM', date(2014, 9, 2), time(14, 0)), ]) def test_freshness_date_with_time(self, date_string, date, time): self.given_parser()
parsing future dates - corrections
scrapinghub_dateparser
train
06c185321c4d6feea0894146db0547caf9b4768a
diff --git a/src/fx/fx.js b/src/fx/fx.js index <HASH>..<HASH> 100644 --- a/src/fx/fx.js +++ b/src/fx/fx.js @@ -422,6 +422,13 @@ jQuery.extend({ // The styles var y = z.el.style; + + // Store display property + var oldDisplay = jQuery.css(z.el, 'display'); + // Set display property to block for animation + y.display = "block"; + // Make sure that nothing sneaks out + y.overflow = "hidden"; // Simple function for setting a style value z.a = function(){ @@ -432,8 +439,6 @@ jQuery.extend({ jQuery.attr(y, "opacity", z.now); // Let attr handle opacity else if ( parseInt(z.now) ) // My hate for IE will never die y[prop] = parseInt(z.now) + "px"; - - y.display = "block"; }; // Figure out the maximum number to run to @@ -488,9 +493,6 @@ jQuery.extend({ z.custom(z.el.orig[prop], 0); }; - // Make sure that nothing sneaks out - y.overflow = "hidden"; - // Each step of an animation z.step = function(firstNum, lastNum){ var t = (new Date()).getTime(); @@ -513,13 +515,15 @@ jQuery.extend({ if ( done ) { // Reset the overflow y.overflow = ''; + + // Reset the display + y.display = oldDisplay; + if (jQuery.css(z.el, 'display') == 'none') + y.display = 'block'; // Hide the element if the "hide" operation was done if ( z.o.hide ) y.display = 'none'; - // Otherwise reset the display property - else if ( z.o.show ) - y.display = ''; // Reset the properties, if the item has been hidden or shown if ( z.o.hide || z.o.show )
Restore display property in fx module after animation is completed.
jquery_jquery
train
09bc8259b1b9e21bb636d920fa30130d32ccf859
diff --git a/fulltext/__init__.py b/fulltext/__init__.py index <HASH>..<HASH> 100644 --- a/fulltext/__init__.py +++ b/fulltext/__init__.py @@ -243,21 +243,22 @@ def get(path_or_file, default=SENTINAL, mime=None, name=None, backend=None, Get document full text. Accepts a path or file-like object. - If given, `default` is returned instead of an error. - `backend` is a string specifying which backend to use (e.g. "doc"). - `mime` and `name` should be passed if the information - is available to caller, otherwise a best guess is made. - `kwargs` are passed to the underlying backend. + * If given, `default` is returned instead of an error. + * `backend` is a string specifying which default backend to use + (e.g. "doc"); take a look at backends directory to see a list of + default backends. + * `mime` and `name` should be passed if the information + is available to caller, otherwise a best guess is made. + * `kwargs` are passed to the underlying backend. """ - if not name: - name = getattr(path_or_file, 'name', None) - - if not name and isinstance(path_or_file, string_types): - name = basename(path_or_file) - if backend is None: + if not name: + name = getattr(path_or_file, 'name', None) + if not name and isinstance(path_or_file, string_types): + name = basename(path_or_file) + if name: - ext = splitext(name)[1].lstrip('.') + ext = splitext(name)[1] elif mime: ext = mime.partition('/')[2] else:
docstring + small refactoring
btimby_fulltext
train
86f23c8c37364e2df73c6cd2e42395ced8f4d1fd
diff --git a/cpo-core/src/main/java/org/synchronoss/cpo/meta/domain/CpoAttribute.java b/cpo-core/src/main/java/org/synchronoss/cpo/meta/domain/CpoAttribute.java index <HASH>..<HASH> 100644 --- a/cpo-core/src/main/java/org/synchronoss/cpo/meta/domain/CpoAttribute.java +++ b/cpo-core/src/main/java/org/synchronoss/cpo/meta/domain/CpoAttribute.java @@ -241,9 +241,11 @@ public class CpoAttribute extends CpoAttributeBean { } catch (Exception ce2) { failedMessage.append(ce2.getMessage()); } - - initTransformClass(metaAdapter); - + try { + initTransformClass(metaAdapter); + } catch (Exception ce2) { + failedMessage.append(ce2.getMessage()); + } if (failedMessage.length() > 0) { throw new CpoException(failedMessage.toString()); } @@ -254,7 +256,6 @@ public class CpoAttribute extends CpoAttributeBean { Class<?> transformClass = null; Logger localLogger = className == null ? logger : LoggerFactory.getLogger(className); - try { if (className != null && className.length() > 0) { try { transformClass = Class.forName(className); @@ -265,7 +266,13 @@ public class CpoAttribute extends CpoAttributeBean { throw new CpoException("Invalid Transform Class specified:<" + className + ">:"); } - Object transformObject = transformClass.newInstance(); + Object transformObject; + try { + transformObject = transformClass.newInstance(); + } catch (Exception e) { + localLogger.debug("Error Setting Transform Class: " + ExceptionHelper.getLocalizedMessage(e)); + throw new CpoException(e); + } if (transformObject instanceof CpoTransform) { cpoTransform = (CpoTransform) transformObject; @@ -279,10 +286,5 @@ public class CpoAttribute extends CpoAttributeBean { } } - } catch (Exception e) { - localLogger.debug("Error Setting Transform Class: " + ExceptionHelper.getLocalizedMessage(e)); - throw new CpoException(e); - } - } }
made sure that a bad transform class provides a good error message.
synchronoss_cpo-api
train
dbc37e09f6ff03157f891826ad958155d79dfb53
diff --git a/src/js/utils/helpers.js b/src/js/utils/helpers.js index <HASH>..<HASH> 100644 --- a/src/js/utils/helpers.js +++ b/src/js/utils/helpers.js @@ -354,6 +354,8 @@ export function createIframe(config) { if (isFunction(callback)) { callback(); } + + iframe.onload = null; }; if (appendTo) {
Remove iframe on load after it initialised
biati-digital_glightbox
train
96a548867e5e4eb3f4d766cdd07343f4d8e633e2
diff --git a/giddy/__init__.py b/giddy/__init__.py index <HASH>..<HASH> 100644 --- a/giddy/__init__.py +++ b/giddy/__init__.py @@ -1,4 +1,4 @@ -__version__ = "2.0.0" +__version__ = "2.1.0" # __version__ has to be defined in the first line """
prepare for a new release <I> with new features on rank Markov
pysal_giddy
train
70c162a406b1b508c0e54d8a9b6c48b3cc1b027f
diff --git a/containerizer/system/process_reaper.go b/containerizer/system/process_reaper.go index <HASH>..<HASH> 100644 --- a/containerizer/system/process_reaper.go +++ b/containerizer/system/process_reaper.go @@ -22,7 +22,7 @@ func StartReaper(logger lager.Logger) *ProcessReaper { p := &ProcessReaper{ mu: new(sync.Mutex), waiting: make(map[int]chan int), - sigChld: make(chan os.Signal, 100), + sigChld: make(chan os.Signal, 1000), log: logger, } @@ -36,6 +36,9 @@ func (p *ProcessReaper) Stop() { } func (p *ProcessReaper) Start(cmd *exec.Cmd) error { + // Lock before starting the command to ensure p.waiting is set before Wait attempts to read it. + p.mu.Lock() + defer p.mu.Unlock() if err := cmd.Start(); err != nil { p.log.Error("failed to start", err, lager.Data{"cmd": cmd}) return err @@ -43,20 +46,16 @@ func (p *ProcessReaper) Start(cmd *exec.Cmd) error { p.log.Info("started", lager.Data{"pid": cmd.Process.Pid, "cmd": cmd}) - p.mu.Lock() - defer p.mu.Unlock() p.waiting[cmd.Process.Pid] = make(chan int, 1) return nil } func (p *ProcessReaper) Wait(cmd *exec.Cmd) byte { - p.mu.Lock() - ch, ok := p.waiting[cmd.Process.Pid] + ch, ok := p.waitChan(cmd.Process.Pid) if !ok { panic("waited on a process that was never started") } - p.mu.Unlock() found := ch != nil p.log.Info("wait", lager.Data{"pid": cmd.Process.Pid, "found": found}) return byte(<-ch) @@ -87,10 +86,7 @@ func (p *ProcessReaper) reap() { p.log.Info("reaped", lager.Data{"pid": wpid, "status": status, "rusage": rusage}) - p.mu.Lock() - ch, ok := p.waiting[wpid] - p.mu.Unlock() - if ok { + if ch, ok := p.waitChan(wpid); ok { ch <- status.ExitStatus() p.log.Info("wait-once-sent-exit-status", lager.Data{"pid": wpid, "status": status, "rusage": rusage}) } else { @@ -98,3 +94,10 @@ func (p *ProcessReaper) reap() { } } } + +func (p *ProcessReaper) waitChan(pid int) (chan int, bool) { + p.mu.Lock() + defer p.mu.Unlock() + wChan, ok := p.waiting[pid] + return wChan, ok +} diff --git a/containerizer/system/process_reaper_test.go b/containerizer/system/process_reaper_test.go index <HASH>..<HASH> 100644 --- a/containerizer/system/process_reaper_test.go +++ b/containerizer/system/process_reaper_test.go @@ -50,8 +50,7 @@ var _ = Describe("ProcessReaper", func() { }) }) - // Flakey when run as part of full test suite, so pended.. - PIt("returns correct exit statuses of short-lived processes", func(done Done) { + It("returns correct exit statuses of short-lived processes", func(done Done) { for i := 0; i < 100; i++ { cmd := exec.Command("sh", "-c", "exit 42") Expect(reaper.Start(cmd)).To(Succeed()) @@ -74,8 +73,7 @@ var _ = Describe("ProcessReaper", func() { close(done) }, 10.0) - // Flakey when run as part of full test suite, so pended.. - PIt("reaps processes when they terminate in close succession", func(done Done) { + It("reaps processes when they terminate in close succession", func(done Done) { for i := 0; i < 100; i++ { cmd := exec.Command("sh", "-c", `while true; do sleep 1; done`) Expect(reaper.Start(cmd)).To(Succeed()) diff --git a/integration/lifecycle/lifecycle_test.go b/integration/lifecycle/lifecycle_test.go index <HASH>..<HASH> 100644 --- a/integration/lifecycle/lifecycle_test.go +++ b/integration/lifecycle/lifecycle_test.go @@ -604,7 +604,7 @@ var _ = Describe("Creating a container", func() { Expect(process.Wait()).To(Equal(255)) } close(done) - }, 30.0) + }, 120.0) PIt("collects the process's full output, even if it exits quickly after", func() { for i := 0; i < 100; i++ {
Ensure reaper.Start populates channel map before reaper.Wait runs. Increase SIGCHLD channel buffer size. Increase test timeout (test was taking close to the timeout). [#<I>]
cloudfoundry-attic_garden-linux
train
83732f24ded31bd453c4787c466e6fda35d2b5e8
diff --git a/testing/adapters/gtw_rtr_moke/adapter.go b/testing/adapters/gtw_rtr_moke/adapter.go index <HASH>..<HASH> 100644 --- a/testing/adapters/gtw_rtr_moke/adapter.go +++ b/testing/adapters/gtw_rtr_moke/adapter.go @@ -1,25 +1,51 @@ // Copyright © 2015 The Things Network // Use of this source code is governed by the MIT license that can be found in the LICENSE file. +// package gtw_rtr_moke offers a gateway <-> router moke adapter that can be used to test a router +// implementation. package gtw_rtr_moke import ( + "fmt" "github.com/thethingsnetwork/core" "github.com/thethingsnetwork/core/lorawan/semtech" ) -type Adapter struct{} +type Adapter struct { + FailAck bool + FailConnect bool + connected bool + acks map[core.GatewayAddress][]semtech.Packet +} // New constructs a new Gateway-Router-Moke adapter -func New(router core.Router, port uint) (*Adapter, error) { - return nil, nil +func New() (*Adapter, error) { + return &Adapter{ + FailAck: false, + FailConnect: false, + connected: false, + acks: make(map[core.GatewayAddress][]semtech.Packet), + }, nil } -// Ack implements the core.GatewayRouterAdapter interface -func (a *Adapter) Connect(router core.Router, port uint) error { +// Listen implements the core.Adapter interface +func (a *Adapter) Listen(router core.Router, options interface{}) error { + if a.FailConnect { + return fmt.Errorf("Unable to establish connection") + } + a.connected = true return nil } // Ack implements the core.GatewayRouterAdapter interface func (a *Adapter) Ack(router core.Router, packet semtech.Packet, gateway core.GatewayAddress) { + if a.FailAck { + router.HandleError(core.ErrAck(fmt.Errorf("Unable to ack the given packet"))) + return + } + a.acks[gateway] = append(a.acks[gateway], packet) +} + +func (a *Adapter) GetAcks(gateway core.GatewayAddress) []semtech.Packet { + return a.acks[gateway] }
[router] Implements basic mock upadapter
TheThingsNetwork_ttn
train
b7f807418c5679ed4dcf29e5b316ce98431653fe
diff --git a/bin/phantomas.js b/bin/phantomas.js index <HASH>..<HASH> 100755 --- a/bin/phantomas.js +++ b/bin/phantomas.js @@ -64,6 +64,7 @@ program .describe('viewport', 'phantomJS viewport dimensions [width]x[height [default: 1280x1024]') .describe('wait-for-event', 'wait for a given phantomas event before generating a report') .describe('wait-for-selector', 'wait for an element matching given CSS selector before generating a report') + .describe('stop-at-onload', 'stop phantomas immediately after onload event').boolean('stop-at-onload') .describe('scroll', 'scroll down the page when it\'s loaded').boolean('scroll') .describe('film-strip', 'register film strip when page is loading (a comma separated list of milliseconds can be passed)').boolean('film-strip') .describe('film-strip-dir', 'folder path to output film strip (default is ./filmstrip directory)') diff --git a/core/phantomas.js b/core/phantomas.js index <HASH>..<HASH> 100644 --- a/core/phantomas.js +++ b/core/phantomas.js @@ -381,7 +381,7 @@ phantomas.prototype = { } this.start = Date.now(); - + var self = this; // setup viewport / --viewport=1366x768 @@ -392,7 +392,7 @@ phantomas.prototype = { width: parseInt(parsedViewport[0], 10) || 1366, height: parseInt(parsedViewport[1], 10) || 768 }; - + this.page.viewportSize = viewportSize; this.on('init', function() { @@ -446,39 +446,44 @@ phantomas.prototype = { this.initLoadingProgress(); - // observe HTTP requests - // finish when the last request is completed + one second timeout - this.reportQueue.push(function(done) { - var currentRequests = 0, - requestsUrls = {}, - onFinished = function(entry) { - currentRequests--; - delete requestsUrls[entry.url]; - - if (currentRequests < 1) { - timeoutId = setTimeout(function() { - done(); - }, 1000); - } - }, - timeoutId; - - // update HTTP requests counter - self.on('send', function(entry) { - clearTimeout(timeoutId); - - currentRequests++; - requestsUrls[entry.url] = true; - }); - - self.on('recv', onFinished); - self.on('abort', onFinished); - - // add debug info about pending responses (issue #216) - self.on('timeout', function() { - self.log('Timeout: gave up waiting for %d HTTP response(s): <%s>', currentRequests, Object.keys(requestsUrls).join('>, <')); + // do not wait for any requests, stop immediately after onload event (issue #513) + if (this.getParam('stop-at-onload', false) === true) { + this.log('stop-at-onload: --stop-at-onload passed, will stop immediately after onload event'); + } else { + // observe HTTP requests + // finish when the last request is completed + one second timeout + this.reportQueue.push(function(done) { + var currentRequests = 0, + requestsUrls = {}, + onFinished = function(entry) { + currentRequests--; + delete requestsUrls[entry.url]; + + if (currentRequests < 1) { + timeoutId = setTimeout(function() { + done(); + }, 1000); + } + }, + timeoutId; + + // update HTTP requests counter + self.on('send', function(entry) { + clearTimeout(timeoutId); + + currentRequests++; + requestsUrls[entry.url] = true; + }); + + self.on('recv', onFinished); + self.on('abort', onFinished); + + // add debug info about pending responses (issue #216) + self.on('timeout', function() { + self.log('Timeout: gave up waiting for %d HTTP response(s): <%s>', currentRequests, Object.keys(requestsUrls).join('>, <')); + }); }); - }); + } this.reportQueue.push(function(done) { self.on('loadFinished', done);
stop-at-onload: stop phantomas immediately after onload event (#<I>)
macbre_phantomas
train
1fc3257f6e7627a11e37466cd449ca0533fc0666
diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index <HASH>..<HASH> 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -63,7 +63,7 @@ }, { "ImportPath": "github.com/endophage/gotuf", - "Rev": "5be7693587dc2f3c6b35fd1394fcc4e098b4f643" + "Rev": "5b7f722ae396b27c59ab5be5e7314a51d1813c29" }, { "ImportPath": "github.com/go-sql-driver/mysql", diff --git a/Godeps/_workspace/src/github.com/endophage/gotuf/client/client.go b/Godeps/_workspace/src/github.com/endophage/gotuf/client/client.go index <HASH>..<HASH> 100644 --- a/Godeps/_workspace/src/github.com/endophage/gotuf/client/client.go +++ b/Godeps/_workspace/src/github.com/endophage/gotuf/client/client.go @@ -239,6 +239,8 @@ func (c *Client) downloadTimestamp() error { if err == nil { version = ts.Signed.Version } + } else { + old = nil } } // unlike root, targets and snapshot, always try and download timestamps @@ -247,7 +249,15 @@ func (c *Client) downloadTimestamp() error { raw, err := c.remote.GetMeta(role, maxSize) var s *data.Signed if err != nil || len(raw) == 0 { - if err, ok := err.(*store.ErrMetaNotFound); ok { + if err, ok := err.(store.ErrMetaNotFound); ok { + return err + } + if old == nil { + if err == nil { + // couldn't retrieve data from server and don't have valid + // data in cache. + return store.ErrMetaNotFound{} + } return err } s = old diff --git a/Godeps/_workspace/src/github.com/endophage/gotuf/store/httpstore.go b/Godeps/_workspace/src/github.com/endophage/gotuf/store/httpstore.go index <HASH>..<HASH> 100644 --- a/Godeps/_workspace/src/github.com/endophage/gotuf/store/httpstore.go +++ b/Godeps/_workspace/src/github.com/endophage/gotuf/store/httpstore.go @@ -14,6 +14,24 @@ import ( "github.com/Sirupsen/logrus" ) +type ErrServerUnavailable struct{} + +func (err ErrServerUnavailable) Error() string { + return "Unable to reach trust server at this time." +} + +type ErrShortRead struct{} + +func (err ErrShortRead) Error() string { + return "Trust server returned incompelete response." +} + +type ErrMaliciousServer struct{} + +func (err ErrMaliciousServer) Error() string { + return "Trust server returned a bad response." +} + // HTTPStore manages pulling and pushing metadata from and to a remote // service over HTTP. It assumes the URL structure of the remote service // maps identically to the structure of the TUF repo: @@ -67,12 +85,18 @@ func (s HTTPStore) GetMeta(name string, size int64) ([]byte, error) { return nil, err } defer resp.Body.Close() + if resp.ContentLength > size { + return nil, ErrMaliciousServer{} + } logrus.Debugf("%d when retrieving metadata for %s", resp.StatusCode, name) if resp.StatusCode == http.StatusNotFound { - return nil, &ErrMetaNotFound{} + return nil, ErrMetaNotFound{} } - b := io.LimitReader(resp.Body, int64(size)) + b := io.LimitReader(resp.Body, size) body, err := ioutil.ReadAll(b) + if resp.ContentLength > 0 && int64(len(body)) < resp.ContentLength { + return nil, ErrShortRead{} + } if err != nil { return nil, err diff --git a/client/client.go b/client/client.go index <HASH>..<HASH> 100644 --- a/client/client.go +++ b/client/client.go @@ -308,7 +308,7 @@ func (r *NotaryRepository) Publish() error { // attempt to initialize the repo from the remote store c, err := r.bootstrapClient() if err != nil { - if _, ok := err.(*store.ErrMetaNotFound); ok { + if _, ok := err.(store.ErrMetaNotFound); ok { // if the remote store return a 404 (translated into ErrMetaNotFound), // the repo hasn't been initialized yet. Attempt to load it from disk. err := r.bootstrapRepo() @@ -506,7 +506,7 @@ func (r *NotaryRepository) bootstrapClient() (*tufclient.Client, error) { // if remote store couldn't be setup, or we failed to get a root from it // load the root from cache (offline operation) if err != nil { - if err, ok := err.(*store.ErrMetaNotFound); ok { + if err, ok := err.(store.ErrMetaNotFound); ok { // if the error was MetaNotFound then we successfully contacted // the store and it doesn't know about the repo. return nil, err @@ -514,7 +514,7 @@ func (r *NotaryRepository) bootstrapClient() (*tufclient.Client, error) { rootJSON, err = r.fileStore.GetMeta("root", maxSize) if err != nil { // if cache didn't return a root, we cannot proceed - return nil, &store.ErrMetaNotFound{} + return nil, store.ErrMetaNotFound{} } } root := &data.Signed{}
updating gotuf dep with some better http error handling.
theupdateframework_notary
train
0c440099ce4eb3dc9a9b3e67ceb95450c2c4e492
diff --git a/core/src/main/java/hudson/util/ProcessTree.java b/core/src/main/java/hudson/util/ProcessTree.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/util/ProcessTree.java +++ b/core/src/main/java/hudson/util/ProcessTree.java @@ -428,15 +428,15 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree, public synchronized EnvVars getEnvironmentVariables() { if(env !=null) return env; - env = new EnvVars(); - - try + env = new EnvVars(); + + try { env.putAll(p.getEnvironmentVariables()); } catch (WinpException e) { LOGGER.log(FINE, "Failed to get environment variable ", e); - } + } return env; } }); @@ -604,10 +604,10 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree, PID_FIELD = clazz.getDeclaredField("pid"); PID_FIELD.setAccessible(true); - if (isJava8()) { - DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class, boolean.class); - } else { + if (isPreJava8()) { DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class); + } else { + DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess",int.class, boolean.class); } DESTROY_PROCESS.setAccessible(true); } catch (ClassNotFoundException e) { @@ -626,17 +626,17 @@ public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree, } public static void destroy(int pid) throws IllegalAccessException, InvocationTargetException { - if (isJava8()) { - DESTROY_PROCESS.invoke(null, pid, false); - } else { + if (isPreJava8()) { DESTROY_PROCESS.invoke(null, pid); + } else { + DESTROY_PROCESS.invoke(null, pid, false); } } - private static boolean isJava8() { - return (System.getProperty("java.version").startsWith("1.8")); + private static boolean isPreJava8() { + int javaVersionAsAnInteger = Integer.parseInt(System.getProperty("java.version").replaceAll("\\.", "").replaceAll("_", "").substring(0, 2)); + return javaVersionAsAnInteger < 18; } - }
Ugly hack to fix destroyProcess for Java8
jenkinsci_jenkins
train
9fc25a5723f7e1a6f5c42d25c08cbfe765e6125a
diff --git a/core-bundle/contao/modules/ModuleLogin.php b/core-bundle/contao/modules/ModuleLogin.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/modules/ModuleLogin.php +++ b/core-bundle/contao/modules/ModuleLogin.php @@ -127,18 +127,18 @@ class ModuleLogin extends \Module global $objPage; $this->import('FrontendUser', 'User'); - $strRedirect = \Environment::get(($objPage->protected ? 'base' : 'request')); + $strRedirect = \Environment::get('request'); // Redirect to last page visited if ($this->redirectBack && strlen($_SESSION['LAST_PAGE_VISITED'])) { - $objLastPage = \PageModel::findByIdOrAlias($this->getPageIdFromUrl($_SESSION['LAST_PAGE_VISITED'])); + $strRedirect = $_SESSION['LAST_PAGE_VISITED']; + } - // Check whether the page is protected (see #6210) - if ($objLastPage !== null && !$objLastPage->protected) - { - $strRedirect = $_SESSION['LAST_PAGE_VISITED']; - } + // Redirect home if the page is protected + elseif ($objPage->protected) + { + $strRedirect = \Environment::get('base'); } // Logout and redirect diff --git a/core-bundle/contao/modules/ModuleLogout.php b/core-bundle/contao/modules/ModuleLogout.php index <HASH>..<HASH> 100644 --- a/core-bundle/contao/modules/ModuleLogout.php +++ b/core-bundle/contao/modules/ModuleLogout.php @@ -61,25 +61,16 @@ class ModuleLogout extends \Module } $this->import('FrontendUser', 'User'); - - $blnUseJumpTo = ($this->jumpTo > 0); $strRedirect = \Environment::get('base'); // Redirect to last page visited if ($this->redirectBack && !empty($_SESSION['LAST_PAGE_VISITED'])) { - $objLastPage = \PageModel::findByIdOrAlias($this->getPageIdFromUrl($_SESSION['LAST_PAGE_VISITED'])); - - // Check whether the page is protected (see #6210) - if ($objLastPage !== null && !$objLastPage->protected) - { - $blnUseJumpTo = false; - $strRedirect = $_SESSION['LAST_PAGE_VISITED']; - } + $strRedirect = $_SESSION['LAST_PAGE_VISITED']; } - // Redirect to the jumpTo page - if ($blnUseJumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) + // Redirect to jumpTo page + elseif ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) { $strRedirect = $this->generateFrontendUrl($objTarget->row()); }
[Core] Reverse 'Do not redirect to protected pages after logout (see #<I>)'
contao_contao
train
579f72bacfad84c24c36596a57c86ba050b98dab
diff --git a/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java b/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java index <HASH>..<HASH> 100644 --- a/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java +++ b/sonar-cxx-plugin/src/main/java/org/sonar/plugins/cxx/xunit/CxxXunitSensor.java @@ -193,16 +193,11 @@ public class CxxXunitSensor extends CxxReportSensor { } private org.sonar.api.resources.File getTestFile(Project project, SensorContext context, String fileKey) { - - org.sonar.api.resources.File resource = org.sonar.api.resources.File.fromIOFile(new File(fileKey), project); - if (resource == null) { - // support SQ<4.2 - resource = org.sonar.api.resources.File.fromIOFile(new File(fileKey), fs.testDirs()); - } + org.sonar.api.resources.File resource = fromIOFile(fileKey, project); if (context.getResource(resource) == null) { String filePath = lookupFilePath(fileKey); - resource = org.sonar.api.resources.File.fromIOFile(new File(filePath), fs.testDirs()); + resource = fromIOFile(filePath, project); if (context.getResource(resource) == null) { CxxUtils.LOG.debug("Cannot find the source file for test '{}', creating a dummy one", fileKey); resource = createVirtualFile(context, fileKey); @@ -214,6 +209,18 @@ public class CxxXunitSensor extends CxxReportSensor { return resource; } + + org.sonar.api.resources.File fromIOFile(String filepath, Project project){ + File file = new File(filepath); + org.sonar.api.resources.File resource = org.sonar.api.resources.File.fromIOFile(file, project); + if (resource == null) { + // support SQ<4.2 + resource = org.sonar.api.resources.File.fromIOFile(file, fs.testDirs()); + } + return resource; + } + + private org.sonar.api.resources.File createVirtualFile(SensorContext context, String fileKey) { org.sonar.api.resources.File file = new org.sonar.api.resources.File(fileKey); file.setLanguage(this.lang);
Make the plugin compatible with SonarQube <I> #<I> use the adviced pattern in one place more
SonarOpenCommunity_sonar-cxx
train
2eb7bb15e771f13192968cd4657c78f76b0799fe
diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index <HASH>..<HASH> 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -1233,7 +1233,9 @@ class Trainer: else: debug_overflow = DebugUnderflowOverflow(self.model) # noqa - delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE + delay_optimizer_creation = ( + self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE or is_sagemaker_mp_enabled() + ) if args.deepspeed: deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint @@ -1690,8 +1692,8 @@ class Trainer: xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, SCHEDULER_NAME)) reissue_pt_warnings(caught_warnings) elif is_sagemaker_mp_enabled(): - if smp.dp_rank() == 0: - # Consolidate the state dict on all processed of dp_rank 0 + if smp.rdp_rank() == 0: + # Consolidate the state dict on all processed of rdp_rank 0 opt_state_dict = self.optimizer.state_dict() # Save it and the scheduler on the main process if self.args.should_save: diff --git a/src/transformers/training_args.py b/src/transformers/training_args.py index <HASH>..<HASH> 100644 --- a/src/transformers/training_args.py +++ b/src/transformers/training_args.py @@ -1126,7 +1126,7 @@ class TrainingArguments: if is_torch_tpu_available(): return xm.xrt_world_size() elif is_sagemaker_mp_enabled(): - return smp.dp_size() + return smp.dp_size() if not smp.state.cfg.prescaled_batch else smp.rdp_size() elif is_sagemaker_dp_enabled(): return sm_dist.get_world_size() elif self.local_rank != -1: @@ -1142,7 +1142,7 @@ class TrainingArguments: if is_torch_tpu_available(): return xm.get_ordinal() elif is_sagemaker_mp_enabled(): - return smp.dp_rank() + return smp.dp_rank() if not smp.state.cfg.prescaled_batch else smp.rdp_rank() elif is_sagemaker_dp_enabled(): return sm_dist.get_rank() elif self.local_rank != -1: @@ -1244,12 +1244,14 @@ class TrainingArguments: """ if is_torch_available() and self.world_size > 1: + main_process_desc = "main process" if local: is_main_process = self.local_process_index == 0 main_process_desc = "main local process" + elif is_sagemaker_mp_enabled(): + is_main_process = smp.rank() == 0 else: is_main_process = self.process_index == 0 - main_process_desc = "main process" try: if not is_main_process:
Updates in Trainer to support new features in SM Model Parallel library (#<I>) * Create optimizer after model creation for SMP * update dp_rank to rdp_rank for opt_state_dict * update world_size and process_index for smp * Address comments * Lint fix
huggingface_pytorch-pretrained-BERT
train
7ead685571a44e1f0ec7bb0c5846b4b9e2b932c6
diff --git a/lib/project/ruby_motion_query/app.rb b/lib/project/ruby_motion_query/app.rb index <HASH>..<HASH> 100644 --- a/lib/project/ruby_motion_query/app.rb +++ b/lib/project/ruby_motion_query/app.rb @@ -8,7 +8,7 @@ end end - class RMQApp + class RMQApp < PMApplication class << self def context @@ -23,6 +23,36 @@ PMApplication.current_activity end + def home_screen_class + PMApplication.home_screen_class + end + + def current_fragment + # TODO + end + alias :current_screen :current_fragment + + + # @return [Symbol] Environment the app is running it + def environment + @_environment ||= RUBYMOTION_ENV.to_sym + end + + # @return [Boolean] true if the app is running in the :release environment + def release? + environment == :release + end + alias :production? :release? + + # @return [Boolean] true if the app is running in the :test environment + def test? + environment == :test + end + + # @return [Boolean] true if the app is running in the :development environment + def development? + environment == :development + end end end diff --git a/lib/project/ruby_motion_query/device.rb b/lib/project/ruby_motion_query/device.rb index <HASH>..<HASH> 100644 --- a/lib/project/ruby_motion_query/device.rb +++ b/lib/project/ruby_motion_query/device.rb @@ -27,5 +27,17 @@ version.to_i <= sdk_version end + def display + RMQ.app.context.getSystemService(RMQ.app.context.WINDOW_SERVICE).defaultDisplay + end + + def width + display.width + end + + def height + display.height + end + end end
Added some stuff to rm.app and rm.device
infinitered_bluepotion
train
d85ed0baa3f11ccc14615aa7b5832bc23b124cd9
diff --git a/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java b/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java index <HASH>..<HASH> 100644 --- a/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java +++ b/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java @@ -233,8 +233,7 @@ public class CommandLineProcessTest extends TestCase { } public void testSetProcessInputOutputInterleaved() throws Exception { - String expected = "vpp> " - + "backtrace (bt) init (i) tcov read file " + newLine + String expected = "backtrace (bt) init (i) tcov read file " + newLine + "break (b) dlclose (dlc) tcov write file " + newLine + "classes disable (dis) ident tcov reset " + newLine + "codegen (cg) class [opt] enable (ena) ident script file " + newLine
Fixed test method testSetProcessInputOutputInterleaved by relaxing (even more) the assertion for the expected output. git-svn-id: <URL>
overturetool_overture
train
961450855e530fa58135eec492c9d8ea1898abee
diff --git a/_test/_stub/StubSiteLibraryImpl.php b/_test/_stub/StubSiteLibraryImpl.php index <HASH>..<HASH> 100644 --- a/_test/_stub/StubSiteLibraryImpl.php +++ b/_test/_stub/StubSiteLibraryImpl.php @@ -63,4 +63,60 @@ class StubSiteLibraryImpl implements SiteLibrary } return null; } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Return the current element + * @link http://php.net/manual/en/iterator.current.php + * @return mixed Can return any type. + */ + public function current() + { + // TODO: Implement current() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Move forward to next element + * @link http://php.net/manual/en/iterator.next.php + * @return void Any returned value is ignored. + */ + public function next() + { + // TODO: Implement next() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Return the key of the current element + * @link http://php.net/manual/en/iterator.key.php + * @return mixed scalar on success, or null on failure. + */ + public function key() + { + // TODO: Implement key() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Checks if current position is valid + * @link http://php.net/manual/en/iterator.valid.php + * @return boolean The return value will be casted to boolean and then evaluated. + * Returns true on success or false on failure. + */ + public function valid() + { + // TODO: Implement valid() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Rewind the Iterator to the first element + * @link http://php.net/manual/en/iterator.rewind.php + * @return void Any returned value is ignored. + */ + public function rewind() + { + // TODO: Implement rewind() method. + } } diff --git a/_test/_stub/StubUserLibraryImpl.php b/_test/_stub/StubUserLibraryImpl.php index <HASH>..<HASH> 100644 --- a/_test/_stub/StubUserLibraryImpl.php +++ b/_test/_stub/StubUserLibraryImpl.php @@ -99,4 +99,60 @@ class StubUserLibraryImpl implements UserLibrary { // TODO: Implement getChildren() method. } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Return the current element + * @link http://php.net/manual/en/iterator.current.php + * @return mixed Can return any type. + */ + public function current() + { + // TODO: Implement current() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Move forward to next element + * @link http://php.net/manual/en/iterator.next.php + * @return void Any returned value is ignored. + */ + public function next() + { + // TODO: Implement next() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Return the key of the current element + * @link http://php.net/manual/en/iterator.key.php + * @return mixed scalar on success, or null on failure. + */ + public function key() + { + // TODO: Implement key() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Checks if current position is valid + * @link http://php.net/manual/en/iterator.valid.php + * @return boolean The return value will be casted to boolean and then evaluated. + * Returns true on success or false on failure. + */ + public function valid() + { + // TODO: Implement valid() method. + } + + /** + * (PHP 5 &gt;= 5.0.0)<br/> + * Rewind the Iterator to the first element + * @link http://php.net/manual/en/iterator.rewind.php + * @return void Any returned value is ignored. + */ + public function rewind() + { + // TODO: Implement rewind() method. + } }
Added method stubs to stubs
budde377_Part
train
21239a350dbee13edb4f1aa17ee7c309e3f341ed
diff --git a/hack/.golint_failures b/hack/.golint_failures index <HASH>..<HASH> 100644 --- a/hack/.golint_failures +++ b/hack/.golint_failures @@ -567,12 +567,9 @@ staging/src/k8s.io/client-go/rest/fake staging/src/k8s.io/client-go/rest/watch staging/src/k8s.io/client-go/scale staging/src/k8s.io/client-go/scale/fake -staging/src/k8s.io/client-go/scale/scheme -staging/src/k8s.io/client-go/scale/scheme/appsint staging/src/k8s.io/client-go/scale/scheme/appsv1beta1 staging/src/k8s.io/client-go/scale/scheme/appsv1beta2 staging/src/k8s.io/client-go/scale/scheme/autoscalingv1 -staging/src/k8s.io/client-go/scale/scheme/extensionsint staging/src/k8s.io/client-go/scale/scheme/extensionsv1beta1 staging/src/k8s.io/client-go/scale/scheme/extensionsv1beta1 staging/src/k8s.io/client-go/testing diff --git a/staging/src/k8s.io/client-go/scale/scheme/appsint/register.go b/staging/src/k8s.io/client-go/scale/scheme/appsint/register.go index <HASH>..<HASH> 100644 --- a/staging/src/k8s.io/client-go/scale/scheme/appsint/register.go +++ b/staging/src/k8s.io/client-go/scale/scheme/appsint/register.go @@ -40,8 +40,10 @@ func Resource(resource string) schema.GroupResource { } var ( + // SchemeBuilder points to a list of functions added to Scheme. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to api.Scheme. diff --git a/staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go b/staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go index <HASH>..<HASH> 100644 --- a/staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go +++ b/staging/src/k8s.io/client-go/scale/scheme/extensionsint/register.go @@ -40,8 +40,10 @@ func Resource(resource string) schema.GroupResource { } var ( + // SchemeBuilder points to a list of functions added to Scheme. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to api.Scheme. diff --git a/staging/src/k8s.io/client-go/scale/scheme/register.go b/staging/src/k8s.io/client-go/scale/scheme/register.go index <HASH>..<HASH> 100644 --- a/staging/src/k8s.io/client-go/scale/scheme/register.go +++ b/staging/src/k8s.io/client-go/scale/scheme/register.go @@ -39,8 +39,10 @@ func Resource(resource string) schema.GroupResource { } var ( + // SchemeBuilder points to a list of functions added to Scheme. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme + // AddToScheme applies all the stored functions to the scheme. + AddToScheme = SchemeBuilder.AddToScheme ) // Adds the list of known types to api.Scheme.
fix golint failures in client-go/scale/scheme/appsint, client-go/scale/scheme/extensionsint, client-go/scale/scheme
kubernetes_kubernetes
train
cc1ab92e818ecae54b359c1c2651bbae2ea7855c
diff --git a/test-client.js b/test-client.js index <HASH>..<HASH> 100644 --- a/test-client.js +++ b/test-client.js @@ -1,5 +1,6 @@ var ws = require('./') var test = require('tape') +var Buffer = require('safe-buffer').Buffer test('echo works', function(t) { var stream = ws('ws://localhost:8343') @@ -9,21 +10,21 @@ test('echo works', function(t) { stream.destroy() t.end() }) - stream.write(new Buffer('hello')) + stream.write(Buffer.from('hello')) }) test('echo works two times', function(t) { var stream = ws('ws://localhost:8343') stream.once('data', function(o) { t.equal(o.toString(), 'hello', 'got first hello back') - stream.write(new Buffer('hello')) + stream.write(Buffer.from('hello')) stream.once('data', function(o) { t.equal(o.toString(), 'hello', 'got second hello back') stream.destroy() t.end() }) }) - stream.write(new Buffer('hello')) + stream.write(Buffer.from('hello')) }) test('with bare WebSocket, strings as strings', function (t) { diff --git a/test.js b/test.js index <HASH>..<HASH> 100644 --- a/test.js +++ b/test.js @@ -4,6 +4,7 @@ var echo = require("./echo-server") var WebSocketServer = require('ws').Server var http = require('http') var concat = require('concat-stream') +var Buffer = require('safe-buffer').Buffer test('echo server', function(t) { @@ -147,7 +148,7 @@ test('destroy client pipe should close server pipe', function(t) { client.on('data', function(o) { client.destroy() }) - client.write(new Buffer('hello')) + client.write(Buffer.from('hello')) } var opts = {}
Use safe-buffer also in tests.
maxogden_websocket-stream
train
781d0349568dd5e6ed099f5858f07773b815d9fe
diff --git a/app/scripts/directives/vjs.directive.js b/app/scripts/directives/vjs.directive.js index <HASH>..<HASH> 100644 --- a/app/scripts/directives/vjs.directive.js +++ b/app/scripts/directives/vjs.directive.js @@ -178,6 +178,7 @@ function initVideoJs(vid, params, element, mediaChangedHandler) { var opts = params.vjsSetup || {}, ratio = params.vjsRatio, + isContainer = (element[0].nodeName !== 'VIDEO') ? true : false, mediaWatcher; if (!window.videojs) { @@ -202,15 +203,19 @@ //deregister watcher mediaWatcher(); - window.videojs(vid).dispose(); - $scope.$emit('vjsVideoMediaChanged'); + if (isContainer) { + window.videojs(vid).dispose(); + $scope.$emit('vjsVideoMediaChanged'); + } else { + console.log('element:', element); + } } } ); //bootstrap videojs window.videojs(vid, opts, function () { - if (element[0].nodeName !== 'VIDEO') { + if (isContainer) { applyRatio(element, ratio); } @@ -246,6 +251,8 @@ bindToController: true, link: function postLink(scope, element, attrs, ctrl, transclude) { var vid, + parentContainer, + origContent, params = { vjsSetup: ctrl.vjsSetup }, @@ -265,6 +272,23 @@ }); }; + origContent = element.clone(); + + //we need to wrap the video inside of a div in case + //the video needs to be swapped out + element.after(document.createElement('div')); + parentContainer = element.next(); + parentContainer.append(element); + + console.log('element orig:', element[0]); + scope.$on('vjsVideoMediaChanged', function (e) { + console.log('element new:', element[0]); + //replace element children with orignal content + parentContainer.children().remove(); + parentContainer.append(origContent.clone()); + init(); + }); + init(); } };
Started work on implementing switching media for vjs-video - #5
arm0th_vjs-video
train
297ae831e2615522164b1b431e81f9bf65a9da42
diff --git a/src/DM/AjaxCom/Resources/public/js/ajaxcom.js b/src/DM/AjaxCom/Resources/public/js/ajaxcom.js index <HASH>..<HASH> 100755 --- a/src/DM/AjaxCom/Resources/public/js/ajaxcom.js +++ b/src/DM/AjaxCom/Resources/public/js/ajaxcom.js @@ -3,10 +3,30 @@ (function($) { "use strict"; + $.ajaxcomProperties = {isPopstateEvent: false}; + + var ajaxcomStackOptions = {}; + var ajaxcomLastPushId = null; + $.event.props.push('state'); $(window).on('popstate.ajaxcom', function(event) { if (typeof event.state === 'object' && event.state !== null) { - window.location.reload(); + if (event.state.ajaxcomPushId == null || ajaxcomStackOptions[ajaxcomLastPushId] == undefined) { + window.location.reload(); + } else { + $.ajaxcomProperties.isPopstateEvent = true; + ajaxcomStackOptions[ajaxcomLastPushId]['scrollTop'] = $(document).scrollTop(); + ajaxcomLastPushId = event.state.ajaxcomPushId; + + var firstOnComplete = {}; + if (ajaxcomStackOptions[ajaxcomLastPushId]['scrollTop'] != null) { + firstOnComplete = {firstOnComplete: function (){ + $(document).scrollTop(ajaxcomStackOptions[ajaxcomLastPushId]['scrollTop']); + }}; + } + + ajaxcom($.extend(true, {}, ajaxcomStackOptions[ajaxcomLastPushId]['options'], firstOnComplete)); + } } }); history && history.replaceState && history.replaceState({}, null); @@ -38,12 +58,17 @@ // // Returns the same as $.ajax function ajaxcom(options) { + var ajaxcomOptions = $.extend(true, {}, options); var customBeforeSend = options.beforeSend; delete options.beforeSend; var customSuccess = options.success; delete options.success; var customComplete = options.complete; delete options.complete; + if (typeof options.firstOnComplete != 'undefined') { + var customFirstOnComplete = options.firstOnComplete; + delete options.firstOnComplete; + } var defaults = { dataType: 'json', @@ -66,23 +91,32 @@ if (data.ajaxcom) { $.each(data.ajaxcom, function(index, operation) { - handleOperation(operation); + handleOperation(operation, ajaxcomOptions); }); } }, complete : function(jqXHR, textStatus){ doAutodisableButton(false, options); + if (typeof customFirstOnComplete != 'undefined') { + customFirstOnComplete(jqXHR, textStatus); + } + customComplete(jqXHR, textStatus); if (typeof customComplete === 'function') { customComplete(jqXHR, textStatus); } + + $.ajaxcomProperties.isPopstateEvent = false; } }; - options = $.extend(true, {}, $.ajaxSettings, defaults, options); return $.ajax(options); } + function ajaxcomIsPopEvent() { + return $.ajaxcomProperties.isPopstateEvent; + } + /* * * param boolean disabled @@ -175,7 +209,7 @@ } // Delegates operations to their handler - function handleOperation(operation) { + function handleOperation(operation, ajaxcomOptions) { switch (operation.operation) { case 'container': handleContainer(operation.options) @@ -184,7 +218,7 @@ handleModal(operation.options); break; case 'changeurl': - handleChangeUrl(operation.options); + handleChangeUrl(operation.options, ajaxcomOptions); break; case 'callback': handleCallback(operation.options); @@ -243,11 +277,28 @@ } // Handle change urls - function handleChangeUrl(options) { + function handleChangeUrl(options, ajaxcomOptions) { switch (options.method) { case 'push': + if ($.ajaxcomProperties.isPopstateEvent) { + break; + } + + var scrollPosition = $(document).scrollTop(); + setTimeout(function() { - history && history.pushState && history.pushState({}, null, options.url); + if (ajaxcomLastPushId != null) { + ajaxcomStackOptions[ajaxcomLastPushId]['scrollTop'] = scrollPosition; + } + ajaxcomLastPushId = new Date().getTime() + options.url; + ajaxcomStackOptions[ajaxcomLastPushId] = {options: ajaxcomOptions}; + history && history.pushState && history.pushState( + { + ajaxcomPushId: ajaxcomLastPushId + }, + null, + options.url + ); }, options.wait); break; case 'replace':
set scroller on ajax complete
everlutionsk_AjaxCom
train
0f9dc55dffbaa40d58debde4870015c89997fbb2
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -24,7 +24,7 @@ convert = function(source) { for (i = 0, linesLength = lines.length; i < linesLength; i++) { line = lines[i]; if (line.charAt(0) === " ") { - currentObj[currentKey] += line; + currentObj[currentKey] += line.substr(1); } else { splitAt = line.indexOf(":"); diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ical2json", - "version": "0.1.3", + "version": "0.1.4", "description": "A simple node package to convert ical to JSON", "main": "index.js", "scripts": { diff --git a/test.js b/test.js index <HASH>..<HASH> 100644 --- a/test.js +++ b/test.js @@ -1,5 +1,5 @@ var ical2json = require("./index"), - eventString = "BEGIN:VEVENT\nDTSTART;VALUE=DATE:20130101\nDTEND;VALUE=DATE:20130102\nDTSTAMP:20111213T124028Z\nUID:9d6fa48343f70300fe3109efe@calendarlabs.com\nCREATED:20111213T123901Z\nDESCRIPTION:Visit http://calendarlabs.com/holidays/us/new-years-day.php to know more about New Year's Day. Like us on Facebook: http://fb.com/calendarlabs to get updates.\nLAST-MODIFIED:20111213T123901Z\nLOCATION:\nSEQUENCE:0\nSTATUS:CONFIRMED\nSUMMARY:New Year's Day\nTRANSP:TRANSPARENT\nEND:VEVENT"; + eventString = "BEGIN:VEVENT\nDTSTART;VALUE=DATE:20130101\nDTEND;VALUE=DATE:20130102\nDTSTAMP:20111213T124028Z\nUID:9d6fa48343f70300fe3109efe@calendarlabs.com\nCREATED:20111213T123901Z\nDESCRIPTION:Visit http://calendarlabs.com/holidays/us/new-years-day.php to kn\n ow more about New Year's Day. Like us on Facebook: http://fb.com/calendarlabs to get updates.\nLAST-MODIFIED:20111213T123901Z\nLOCATION:\nSEQUENCE:0\nSTATUS:CONFIRMED\nSUMMARY:New Year's Day\nTRANSP:TRANSPARENT\nEND:VEVENT"; exports.convert = { setUp: function (callback) {
Strip leading space when wrapped lines are joined. From RFC <I>: "a long line can be split between any two characters by inserting a CRLF immediately followed by a single linear white-space character (i.e., SPACE or HTAB). Any sequence of CRLF followed immediately by a single linear white-space character is ignored (i.e., removed) when processing the content type." <URL>
adrianlee44_ical2json
train
cf6cc381f8764d7988d2df048743ba0d84fe286c
diff --git a/mode/yaml-frontmatter/yaml-frontmatter.js b/mode/yaml-frontmatter/yaml-frontmatter.js index <HASH>..<HASH> 100644 --- a/mode/yaml-frontmatter/yaml-frontmatter.js +++ b/mode/yaml-frontmatter/yaml-frontmatter.js @@ -17,55 +17,55 @@ var yamlMode = CodeMirror.getMode(config, "yaml") var innerMode = CodeMirror.getMode(config, parserConfig && parserConfig.base || "gfm") - function curMode(state) { - return state.state == BODY ? innerMode : yamlMode + function localMode(state) { + return state.state == FRONTMATTER ? {mode: yamlMode, state: state.yaml} : {mode: innerMode, state: state.inner} } return { startState: function () { return { state: START, - inner: CodeMirror.startState(yamlMode) + yaml: null, + inner: CodeMirror.startState(innerMode) } }, copyState: function (state) { return { state: state.state, - inner: CodeMirror.copyState(curMode(state), state.inner) + yaml: state.yaml && CodeMirror.copyState(yamlMode, state.yaml), + inner: CodeMirror.copyState(innerMode, state.inner) } }, token: function (stream, state) { if (state.state == START) { if (stream.match('---', false)) { state.state = FRONTMATTER - return yamlMode.token(stream, state.inner) + state.yaml = CodeMirror.startState(yamlMode) + return yamlMode.token(stream, state.yaml) } else { state.state = BODY - state.inner = CodeMirror.startState(innerMode) return innerMode.token(stream, state.inner) } } else if (state.state == FRONTMATTER) { var end = stream.sol() && stream.match(/(---|\.\.\.)/, false) - var style = yamlMode.token(stream, state.inner) + var style = yamlMode.token(stream, state.yaml) if (end) { state.state = BODY - state.inner = CodeMirror.startState(innerMode) + state.yaml = null } return style } else { return innerMode.token(stream, state.inner) } }, - innerMode: function (state) { - return {mode: curMode(state), state: state.inner} - }, + innerMode: localMode, indent: function(state, a, b) { - var mode = curMode(state) - return mode.indent ? mode.indent(state.inner, a, b) : CodeMirror.Pass + var m = localMode(state) + return m.mode.indent ? m.mode.indent(m.state, a, b) : CodeMirror.Pass }, blankLine: function (state) { - var mode = curMode(state) - if (mode.blankLine) return mode.blankLine(state.inner) + var m = localMode(state) + if (m.mode.blankLine) return m.mode.blankLine(m.state) } } })
[yaml-frontmatter mode] Treat the start of the document as being in the base mode For purposes of indentation and such. Issue <URL>
codemirror_CodeMirror
train
f89b9f2a2130ce548ca7ebb20fa1311bf714aa10
diff --git a/src/com/google/javascript/jscomp/DefaultPassConfig.java b/src/com/google/javascript/jscomp/DefaultPassConfig.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/DefaultPassConfig.java +++ b/src/com/google/javascript/jscomp/DefaultPassConfig.java @@ -383,12 +383,13 @@ public final class DefaultPassConfig extends PassConfig { checks.add(dartSuperAccessorsPass); } - if (options.needsTranspilationFrom(ES7)) { + if (options.needsTranspilationFrom(ES8)) { TranspilationPasses.addEs2017Passes(checks); checks.add(setFeatureSet(ES7)); } - if (options.needsTranspilationFrom(ES6) && !options.skipTranspilationAndCrash) { + if ((options.needsTranspilationFrom(ES6) || options.needsTranspilationFrom(ES7)) + && !options.skipTranspilationAndCrash) { checks.add(es6ExternsCheck); TranspilationPasses.addEs6EarlyPasses(checks); }
Fix a couple small mistakes I missed these in "Add a featureSet method..." ------------- Created by MOE: <URL>
google_closure-compiler
train
c0889e1f83ffbc09888b23624522a51f7a5f6aa1
diff --git a/shutit_util.py b/shutit_util.py index <HASH>..<HASH> 100644 --- a/shutit_util.py +++ b/shutit_util.py @@ -231,6 +231,12 @@ def util_raw_input(prompt='', default=None, ispass=False, use_readline=True): sanitize_terminal() if shutit_global.shutit_global_object.interactive == 0: return default + # See: https//github.com/ianmiell/shutit/issues/299 - python3 made input == python 2's raw_input + if not PY3: + try: + input = raw_input + except NameError: + pass if not shutit_global.shutit_global_object.determine_interactive(): return default while True:
bugfix: allow for py2
ianmiell_shutit
train
bd903f35cfbe26cfd73d043544bb40634effa304
diff --git a/src/noselect.js b/src/noselect.js index <HASH>..<HASH> 100644 --- a/src/noselect.js +++ b/src/noselect.js @@ -22,9 +22,9 @@ function yesuserselect() { } export function noselect(selection) { - return ("onselectstart" in event.view ? noselectstart : nouserselect)(selection); + return ("onselectstart" in event.target ? noselectstart : nouserselect)(selection); } export function yesselect(selection) { - return ("onselectstart" in event.view ? yesselectstart : yesuserselect)(selection); + return ("onselectstart" in event.target ? yesselectstart : yesuserselect)(selection); }
Must test an element for onselectstart. The "onselectstart" in window is always false.
d3_d3-drag
train
074c03b7d6b65b3245f5f382fbedc4fa45818cb5
diff --git a/python-xbrl/parser.py b/python-xbrl/parser.py index <HASH>..<HASH> 100644 --- a/python-xbrl/parser.py +++ b/python-xbrl/parser.py @@ -53,7 +53,7 @@ class XBRLParser(object): # Store the headers xbrl_file = XBRLPreprocessedFile(file_handle) xbrl = soup_maker(xbrl_file.fh) - if xbrl.find('xbrl') is None and xbrl.find(name=re.compile("(xbrli:)")) is None: + if xbrl.find('xbrl') is None and xbrl.find(name=re.compile("(xbrl*:)")) is None: raise XBRLParserException('The xbrl file is empty!') return xbrl
another bug where documents can have different forms of xbrl tag
greedo_python-xbrl
train
6f6713669a8a32af90a73d03a7fa24e6154327f2
diff --git a/git/test/test_index.py b/git/test/test_index.py index <HASH>..<HASH> 100644 --- a/git/test/test_index.py +++ b/git/test/test_index.py @@ -801,7 +801,7 @@ class TestIndex(TestBase): def test_add_a_file_with_wildcard_chars(self, rw_dir): # see issue #407 fp = os.path.join(rw_dir, '[.exe') - with open(fp, "w") as f: + with open(fp, "wb") as f: f.write(b'something') r = Repo.init(rw_dir)
fixed unittest of issue #<I> for Python3
gitpython-developers_GitPython
train
26fc8ee2aa3799fb682b67c6ee077c89cd5f3385
diff --git a/core/src/main/java/com/emc/ia/sdk/support/io/SingleHashAssembler.java b/core/src/main/java/com/emc/ia/sdk/support/io/SingleHashAssembler.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/emc/ia/sdk/support/io/SingleHashAssembler.java +++ b/core/src/main/java/com/emc/ia/sdk/support/io/SingleHashAssembler.java @@ -20,7 +20,7 @@ public class SingleHashAssembler extends NoHashAssembler { * Assemble hashes using the default hash function and encoding. */ public SingleHashAssembler() { - this(HashFunction.SHA1, Encoding.BASE64); + this(HashFunction.SHA256, Encoding.BASE64); } /** diff --git a/core/src/test/java/com/emc/ia/sdk/support/io/WhenHashing.java b/core/src/test/java/com/emc/ia/sdk/support/io/WhenHashing.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/com/emc/ia/sdk/support/io/WhenHashing.java +++ b/core/src/test/java/com/emc/ia/sdk/support/io/WhenHashing.java @@ -17,6 +17,7 @@ import com.emc.ia.sdk.support.test.TestCase; public class WhenHashing extends TestCase { + private static final String EXPECTED_HASH_FUNCTION = "SHA-256"; private final HashAssembler hashAssembler = new SingleHashAssembler(); @Test @@ -30,9 +31,9 @@ public class WhenHashing extends TestCase { assertEquals("# hashes", 1, actual.size()); EncodedHash encodedHash = actual.iterator() .next(); - assertEquals("Algorithm", "SHA-1", encodedHash.getHashFunction()); + assertEquals("Algorithm", EXPECTED_HASH_FUNCTION, encodedHash.getHashFunction()); assertEquals("Encoding", "base64", encodedHash.getEncoding()); - assertArrayEquals("Digest", MessageDigest.getInstance("SHA-1") + assertArrayEquals("Digest", MessageDigest.getInstance(EXPECTED_HASH_FUNCTION) .digest(content), Base64.decodeBase64(encodedHash.getValue())); }
Use SHA-<I> by default rather than SHA-1
Enterprise-Content-Management_infoarchive-sip-sdk
train
9bac3616546d13d89480651c50916aa7d8ff6958
diff --git a/src/main/java/org/eobjects/analyzer/connection/CsvDatastore.java b/src/main/java/org/eobjects/analyzer/connection/CsvDatastore.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/eobjects/analyzer/connection/CsvDatastore.java +++ b/src/main/java/org/eobjects/analyzer/connection/CsvDatastore.java @@ -31,6 +31,12 @@ public final class CsvDatastore extends UsageAwareDatastore { private static final long serialVersionUID = 1L; + /** + * The value is '\\uFFFF', the "not a character" value which should not + * occur in any valid Unicode string. + */ + public static final char NOT_A_CHAR = '\uFFFF'; + private final String _name; private final String _filename; private final Character _quoteChar;
Added a "(none)" quote char to CSV datastores
datacleaner_AnalyzerBeans
train
3229b3b35c6e7da68598eb59ac1e50a7239fc078
diff --git a/lib/chef/cookbook/synchronizer.rb b/lib/chef/cookbook/synchronizer.rb index <HASH>..<HASH> 100644 --- a/lib/chef/cookbook/synchronizer.rb +++ b/lib/chef/cookbook/synchronizer.rb @@ -68,6 +68,8 @@ class Chef @eager_segments.freeze @cookbooks_by_name, @events = cookbooks_by_name, events + + @cookbook_full_file_paths = {} end def cache @@ -136,14 +138,20 @@ class Chef files.each do |file| queue << lambda do |lock| - sync_file(file) - lock.synchronize { mark_file_synced(file) } + full_file_path = sync_file(file) + + lock.synchronize { + # Save the full_path of the downloaded file to be restored in the manifest later + save_full_file_path(file, full_file_path) + mark_file_synced(file) + } end end @events.cookbook_sync_start(cookbook_count) queue.process(Chef::Config[:cookbook_sync_threads]) - update_cookbook_filenames + # Update the full file paths in the manifest + update_cookbook_filenames() rescue Exception => e @events.cookbook_sync_failed(cookbooks, e) @@ -153,6 +161,14 @@ class Chef true end + # Saves the full_path to the file of the cookbook to be updated + # in the manifest later + def save_full_file_path(file, full_path) + @cookbook_full_file_paths[file.cookbook] ||= { } + @cookbook_full_file_paths[file.cookbook][file.segment] ||= [ ] + @cookbook_full_file_paths[file.cookbook][file.segment] << full_path + end + # Iterates over cached cookbooks' files, removing files belonging to # cookbooks that don't appear in +cookbook_hash+ def clear_obsoleted_cookbooks @@ -170,14 +186,9 @@ class Chef end def update_cookbook_filenames - files_by_cookbook.each do |cookbook, cookbook_files| - files_by_segment = cookbook_files.group_by { |file| file.segment } - @eager_segments.each do |segment| - segment_files = files_by_segment[segment] - next unless segment_files - - filenames = segment_files.map { |file| file.manifest_record['path'] } - cookbook.replace_segment_filenames(segment, filenames) + @cookbook_full_file_paths.each do |cookbook, file_segments| + file_segments.each do |segment, full_paths| + cookbook.replace_segment_filenames(segment, full_paths) end end end @@ -204,8 +215,8 @@ class Chef Chef::Log.debug("Not storing #{cache_filename}, as the cache is up to date.") end - # Update the manifest with the full path to the cached file - file.manifest_record['path'] = cache.load(cache_filename, false) + # Load the file in the cache and return the full file path to the loaded file + cache.load(cache_filename, false) end def cached_copy_up_to_date?(local_path, expected_checksum)
Do not update the path in the cookbook_manifest with the full file name.
chef_chef
train
ede1e0c17745f52558db2c3f31e48acbc7cb0ba7
diff --git a/lib/ProMotion/table/cell/table_view_cell_module.rb b/lib/ProMotion/table/cell/table_view_cell_module.rb index <HASH>..<HASH> 100644 --- a/lib/ProMotion/table/cell/table_view_cell_module.rb +++ b/lib/ProMotion/table/cell/table_view_cell_module.rb @@ -19,6 +19,17 @@ module ProMotion set_accessory_type end + def layoutSubviews + super + + # Support changing sizes of the image view + if (data_cell[:image] && data_cell[:image].is_a?(Hash) && data_cell[:image][:size]) + self.imageView.bounds = CGRectMake(0, 0, data_cell[:image][:size], data_cell[:image][:size]); + elsif (data_cell[:remote_image] && data_cell[:remote_image][:size]) + self.imageView.bounds = CGRectMake(0, 0, data_cell[:remote_image][:size], data_cell[:remote_image][:size]); + end + end + protected # TODO: Remove this in ProMotion 2.1. Just for migration purposes. diff --git a/spec/unit/tables/table_view_cell_spec.rb b/spec/unit/tables/table_view_cell_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/tables/table_view_cell_spec.rb +++ b/spec/unit/tables/table_view_cell_spec.rb @@ -51,7 +51,8 @@ describe "PM::TableViewCellModule" do { title: "Test 1", properties: { accessory_type: UITableViewCellStateShowingEditControlMask } }, custom_cell, { title: "Test2", accessory: { view: button } }, - attributed_cell + attributed_cell, + { title: "Image Size Test", image: {image: UIImage.imageNamed("list"), size: 20} }, ] } ] @@ -61,6 +62,7 @@ describe "PM::TableViewCellModule" do @custom_ip = NSIndexPath.indexPathForRow(1, inSection: 1) # Cell "Crazy Full Featured Cell" @attributed_ip = NSIndexPath.indexPathForRow(3, inSection: 1) # Attributed Cell + @image_size_ip = NSIndexPath.indexPathForRow(4, inSection: 1) # Attributed Cell @screen.update_table_data @@ -137,6 +139,23 @@ describe "PM::TableViewCellModule" do @subject.imageView.layer.cornerRadius.should == 15.0 end + it "should set an image size" do + cell_for_height = UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:"CellForHeight") + default_cell_height = cell_for_height.frame.size.height + + @subject.layoutSubviews + @subject.imageView.frame.size.should == UIImage.imageNamed("list").size + + image_cell = @screen.tableView(@screen.table_view, cellForRowAtIndexPath: @image_size_ip) + image_cell.layoutSubviews + + image_cell.imageView.frame.origin.should.not == CGPointMake(0,0) + image_cell.imageView.bounds.origin.should == CGPointMake(0,0) + + image_cell.imageView.frame.size.should == CGSizeMake(20,20) + image_cell.imageView.bounds.size.should == CGSizeMake(20,20) + end + it "should have the proper accessory type" do @subject.accessoryType.should == UITableViewCellAccessoryDisclosureIndicator end
Ability to ACTUALLY change image and remote_image size The docs show that you can change the image and remote image size but it's not actually implemented anywhere. Complete with tests.
infinitered_ProMotion
train
1695dc1c2e451bcd301eef5811b7fcd9bb51b342
diff --git a/source/org/jasig/portal/layout/UserLayoutNode.java b/source/org/jasig/portal/layout/UserLayoutNode.java index <HASH>..<HASH> 100644 --- a/source/org/jasig/portal/layout/UserLayoutNode.java +++ b/source/org/jasig/portal/layout/UserLayoutNode.java @@ -33,7 +33,6 @@ * */ - package org.jasig.portal.layout; import java.util.Collections; @@ -42,14 +41,12 @@ import java.util.Set; import org.jasig.portal.layout.restrictions.IUserLayoutRestriction; - /** - * UserLayoutNode summary description sentence goes here. + * Represents a node in the user layout tree. * * @author <a href="mailto:mvi@immagic.com">Michael Ivanov</a> * @version $Revision$ */ - public class UserLayoutNode { protected String parentNodeId; @@ -63,14 +60,12 @@ public class UserLayoutNode { // this object contains the restrictions for this node of ICachingRestrictions type protected Set restrictions = Collections.synchronizedSet(new HashSet()); - public UserLayoutNode() {} public UserLayoutNode ( IUserLayoutNodeDescription nd ) { nodeDescription = nd; } - public String getId() { return nodeDescription.getId(); } @@ -83,7 +78,6 @@ public class UserLayoutNode { return nodeDescription; } - public void setParentNodeId ( String parentNodeId ) { this.parentNodeId = parentNodeId; } @@ -108,75 +102,73 @@ public class UserLayoutNode { return previousNodeId; } - /** - * Sets the hashtable of restrictions bound to this node - * @param restrictions a <code>Hashtable</code> hashtable of restriction expressions - */ + * Sets the hashtable of restrictions bound to this node + * @param restrictions a <code>Hashtable</code> hashtable of restriction expressions + */ public void setRestrictions ( Set restrictions ) { this.restrictions = restrictions; } /** - * Gets the hashtable of restrictions bound to this node - * @return a hashtable of restriction expressions - */ + * Gets the hashtable of restrictions bound to this node + * @return a hashtable of restriction expressions + */ public Set getRestrictions () { return restrictions; } - /** - * Adds the restriction for this node. - * @param restrictionName a <code>String</code> name of the restriction - * @param restriction a <code>IUserLayoutRestriction</code> a restriction - */ + * Adds the restriction for this node. + * @param restriction a <code>IUserLayoutRestriction</code> a restriction + */ public void addRestriction( IUserLayoutRestriction restriction ) { restrictions.add(restriction); } - /** - * Sets the priority for this node. - * @param priority a <code>int</code> priority value - */ + * Sets the priority for this node. + * @param priority a <code>int</code> priority value + */ public void setPriority ( int priority ) { this.priority = priority; } /** - * Gets the priority value for this node. - */ + * Gets the priority value for this node. + */ public int getPriority() { return priority; } - /** - * Sets the tree depth for this node. - * @param depth a <code>int</code> depth value - */ - public void setDepth ( int priority ) { - this.priority = priority; + /** + * Sets the tree depth for this node. + * @param depth a <code>int</code> depth value + */ + public void setDepth ( int depth ) { + this.depth = depth; } /** - * Gets the depth value for this node. - */ + * Gets the depth value for this node. + * @return the depth of this node + */ public int getDepth() { return depth; } /** - * Sets the group name for this node. - * @param groupName a <code>String</code> group name value - */ + * Sets the group name for this node. + * @param groupName a <code>String</code> group name value + */ public void setGroupName ( String groupName ) { this.groupName = groupName; } /** - * Gets the priority value for this node. - */ + * Gets the group name for this node. + * @return the group name + */ public String getGroupName() { return groupName; }
Fix the setDepth method which was erroneously setting the priority instead of the depth. Also fixed javadoc comments. git-svn-id: <URL>
Jasig_uPortal
train
f148ee4ac92dad449e2c3b8e38c998f2e8e95774
diff --git a/fs/copy_linux.go b/fs/copy_linux.go index <HASH>..<HASH> 100644 --- a/fs/copy_linux.go +++ b/fs/copy_linux.go @@ -7,6 +7,7 @@ import ( "github.com/containerd/continuity/sysx" "github.com/pkg/errors" + "golang.org/x/sys/unix" ) func copyFileInfo(fi os.FileInfo, name string) error { @@ -21,7 +22,8 @@ func copyFileInfo(fi os.FileInfo, name string) error { } } - if err := syscall.UtimesNano(name, []syscall.Timespec{st.Atim, st.Mtim}); err != nil { + timespec := []unix.Timespec{unix.Timespec(st.Atim), unix.Timespec(st.Mtim)} + if err := unix.UtimesNanoAt(unix.AT_FDCWD, name, timespec, unix.AT_SYMLINK_NOFOLLOW); err != nil { return errors.Wrapf(err, "failed to utime %s", name) } diff --git a/fs/copy_test.go b/fs/copy_test.go index <HASH>..<HASH> 100644 --- a/fs/copy_test.go +++ b/fs/copy_test.go @@ -32,6 +32,20 @@ func TestCopyDirectory(t *testing.T) { } } +// This test used to fail because link-no-nothing.txt would be copied first, +// then file operations in dst during the CopyDir would follow the symlink and +// fail. +func TestCopyDirectoryWithLocalSymlink(t *testing.T) { + apply := fstest.Apply( + fstest.CreateFile("nothing.txt", []byte{0x00, 0x00}, 0755), + fstest.Symlink("nothing.txt", "link-no-nothing.txt"), + ) + + if err := testCopy(apply); err != nil { + t.Fatalf("Copy test failed: %+v", err) + } +} + func testCopy(apply fstest.Applier) error { t1, err := ioutil.TempDir("", "test-copy-src-") if err != nil {
fs: Change CopyDir's utimes call to not follow symlinks Following symlinks does not look like it was intended behavior here, and fails if the symlink target has not been copied yet.
tonistiigi_fsutil
train
9ab8a19f282f4f2871e122b8dfb06cad87b96ac8
diff --git a/Templating/Tests/Adapter/ValueObjectAdapterTest.php b/Templating/Tests/Adapter/ValueObjectAdapterTest.php index <HASH>..<HASH> 100644 --- a/Templating/Tests/Adapter/ValueObjectAdapterTest.php +++ b/Templating/Tests/Adapter/ValueObjectAdapterTest.php @@ -11,8 +11,9 @@ namespace eZ\Publish\Core\MVC\Legacy\Templating\Tests\Adapter; use eZ\Publish\Core\MVC\Legacy\Templating\Adapter\ValueObjectAdapter; use eZ\Publish\API\Repository\Values\ValueObject; +use PHPUnit_Framework_TestCase; -class ValueObjectAdapterTest extends \PHPUnit_Framework_TestCase +class ValueObjectAdapterTest extends PHPUnit_Framework_TestCase { /** * @var \PHPUnit_Framework_MockObject_MockObject diff --git a/Templating/Tests/Converter/PagePartsConverterTest.php b/Templating/Tests/Converter/PagePartsConverterTest.php index <HASH>..<HASH> 100644 --- a/Templating/Tests/Converter/PagePartsConverterTest.php +++ b/Templating/Tests/Converter/PagePartsConverterTest.php @@ -11,8 +11,9 @@ namespace eZ\Publish\Core\MVC\Legacy\Templating\Tests\Converter; use eZ\Publish\Core\MVC\Legacy\Templating\Converter\PagePartsConverter; use eZ\Publish\API\Repository\Values\ValueObject; +use PHPUnit_Framework_TestCase; -class PagePartsConverterTest extends \PHPUnit_Framework_TestCase +class PagePartsConverterTest extends PHPUnit_Framework_TestCase { /** * @dataProvider convertProvider diff --git a/Templating/Tests/LegacyEngineTest.php b/Templating/Tests/LegacyEngineTest.php index <HASH>..<HASH> 100644 --- a/Templating/Tests/LegacyEngineTest.php +++ b/Templating/Tests/LegacyEngineTest.php @@ -10,8 +10,9 @@ namespace eZ\Publish\Core\MVC\Legacy\Templating\Tests; use eZ\Publish\Core\MVC\Legacy\Templating\LegacyEngine; +use PHPUnit_Framework_TestCase; -class LegacyEngineTest extends \PHPUnit_Framework_TestCase +class LegacyEngineTest extends PHPUnit_Framework_TestCase { /** * @var \eZ\Publish\Core\MVC\Legacy\Templating\LegacyEngine diff --git a/Templating/Tests/Twig/EnvironmentTest.php b/Templating/Tests/Twig/EnvironmentTest.php index <HASH>..<HASH> 100644 --- a/Templating/Tests/Twig/EnvironmentTest.php +++ b/Templating/Tests/Twig/EnvironmentTest.php @@ -10,8 +10,9 @@ namespace eZ\Publish\Core\MVC\Legacy\Templating\Tests\Twig; use eZ\Publish\Core\MVC\Legacy\Templating\Twig\Environment; +use PHPUnit_Framework_TestCase; -class EnvironmentTest extends \PHPUnit_Framework_TestCase +class EnvironmentTest extends PHPUnit_Framework_TestCase { /** * @covers \eZ\Publish\Core\MVC\Legacy\Templating\Twig\Environment::loadTemplate diff --git a/Templating/Tests/Twig/TemplateTest.php b/Templating/Tests/Twig/TemplateTest.php index <HASH>..<HASH> 100644 --- a/Templating/Tests/Twig/TemplateTest.php +++ b/Templating/Tests/Twig/TemplateTest.php @@ -10,8 +10,9 @@ namespace eZ\Publish\Core\MVC\Legacy\Templating\Tests\Twig; use eZ\Publish\Core\MVC\Legacy\Templating\Twig\Template; +use PHPUnit_Framework_TestCase; -class TemplateTest extends \PHPUnit_Framework_TestCase +class TemplateTest extends PHPUnit_Framework_TestCase { const TEMPLATE_NAME = 'design:hello_world.tpl'; diff --git a/Templating/Twig/TokenParser/LegacyIncludeParser.php b/Templating/Twig/TokenParser/LegacyIncludeParser.php index <HASH>..<HASH> 100644 --- a/Templating/Twig/TokenParser/LegacyIncludeParser.php +++ b/Templating/Twig/TokenParser/LegacyIncludeParser.php @@ -11,6 +11,7 @@ namespace eZ\Publish\Core\MVC\Legacy\Templating\Twig\TokenParser; use eZ\Publish\Core\MVC\Legacy\Templating\Twig\Node\LegacyIncludeNode; use Twig_Token; +use Twig_TokenParser; use Twig_Node_Expression_Array; /** @@ -18,7 +19,7 @@ use Twig_Node_Expression_Array; * * @deprecated since 5.1 */ -class LegacyIncludeParser extends \Twig_TokenParser +class LegacyIncludeParser extends Twig_TokenParser { /** diff --git a/Tests/LegacyBasedTestCase.php b/Tests/LegacyBasedTestCase.php index <HASH>..<HASH> 100644 --- a/Tests/LegacyBasedTestCase.php +++ b/Tests/LegacyBasedTestCase.php @@ -9,10 +9,12 @@ namespace eZ\Publish\Core\MVC\Legacy\Tests; +use PHPUnit_Framework_TestCase; + /** * Base test case for legacy based tests. */ -abstract class LegacyBasedTestCase extends \PHPUnit_Framework_TestCase +abstract class LegacyBasedTestCase extends PHPUnit_Framework_TestCase { protected function setUp() {
CS: Fixed several issues not yet reported by Code Sniffer * Missing headers * Using FQ class name instead of importing them
ezsystems_LegacyBridge
train
f85991333f64ddbcfa7c708e30650f0ff6adef45
diff --git a/setup/test_integration.py b/setup/test_integration.py index <HASH>..<HASH> 100644 --- a/setup/test_integration.py +++ b/setup/test_integration.py @@ -41,7 +41,7 @@ def test_brain_jobs(rethink): r.db("Brain").table('Jobs').run(rethink) def test_audit(rethink): - r.db_list().contains('Audit').run() + r.db_list().contains('Audit').run(rethink) def test_audit_jobs(rethink): - r.db("Audit").table('Jobs').run() + r.db("Audit").table('Jobs').run(rethink)
undo what i did wrong added the rethink arguement back into audit
ramrod-project_database-brain
train
54b5fcad972c6733427f08848e997570a68d2da7
diff --git a/buildAll_unix.py b/buildAll_unix.py index <HASH>..<HASH> 100755 --- a/buildAll_unix.py +++ b/buildAll_unix.py @@ -12,7 +12,7 @@ NASSL_INSTALL_DIR = '' if architecture()[0] == '64bit': if platform == 'darwin': OPENSSL_TARGET = 'darwin64-x86_64-cc' - NASSL_INSTALL_DIR = join(BUILD_DIR, 'lib.macosx-10.8-intel-' + PY_VERSION + '/') + NASSL_INSTALL_DIR = join(BUILD_DIR, 'lib.macosx-10.9-intel-' + PY_VERSION + '/') OPENSSL_INSTALL_DIR = join(BUILD_DIR, 'openssl-darwin64') elif platform == 'linux2':
Update build script for OX <I>
nabla-c0d3_nassl
train
7bad8c1665a3dedc05f3724da484842e0db04c7a
diff --git a/octarine-core/src/main/java/com/codepoetics/octarine/records/Record.java b/octarine-core/src/main/java/com/codepoetics/octarine/records/Record.java index <HASH>..<HASH> 100644 --- a/octarine-core/src/main/java/com/codepoetics/octarine/records/Record.java +++ b/octarine-core/src/main/java/com/codepoetics/octarine/records/Record.java @@ -48,7 +48,7 @@ public interface Record { @Override public boolean equals(Object other) { - if (other instanceof Record) { + if (other != null && other instanceof Record) { return ((Record) other).values().equals(values); } return false;
Rune of warding against NPE
poetix_octarine
train
4de39d61986939c1f98ba437ad5166352e352af3
diff --git a/lib/serializer-utils.js b/lib/serializer-utils.js index <HASH>..<HASH> 100644 --- a/lib/serializer-utils.js +++ b/lib/serializer-utils.js @@ -274,7 +274,7 @@ module.exports = function (collectionName, record, payload, opts) { // Top-level data. var data = { type: getType(collectionName, record) }; - if (record[getId()]) { data.id = record[getId()]; } + if (record[getId()]) { data.id = String(record[getId()]); } // Data links. if (opts.dataLinks) {
Regression fixed: Force the ID to be a String
SeyZ_jsonapi-serializer
train