hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
ce0a1a43de4f0bf0075d0bb4ff9d3f4938a1f0ef
|
diff --git a/lib/pilfer/middleware.rb b/lib/pilfer/middleware.rb
index <HASH>..<HASH> 100644
--- a/lib/pilfer/middleware.rb
+++ b/lib/pilfer/middleware.rb
@@ -30,7 +30,7 @@ module Pilfer
end
def default_profiler
- reporter = Pilfer::Logger.new($stdout, :app_root => ENV['PWD'])
+ reporter = Pilfer::Logger.new($stdout)
Pilfer::Profiler.new(reporter)
end
|
Remove default value for app_root
If PWD is going to be used as the default app root, it should be defined in
the reporters. This implementation only worked when using the middleware and
its default logger.
|
eric_pilfer
|
train
|
1010a4ed3aba647cf414662c73545409a217408b
|
diff --git a/src/AlgorithmTSPMinimumSpanningTreeHeuristic.php b/src/AlgorithmTSPMinimumSpanningTreeHeuristic.php
index <HASH>..<HASH> 100644
--- a/src/AlgorithmTSPMinimumSpanningTreeHeuristic.php
+++ b/src/AlgorithmTSPMinimumSpanningTreeHeuristic.php
@@ -1,50 +1,51 @@
<?php
class AlgorithmTSPMinimumSpanningTreeHeuristic{
-
+
private $graph;
-
+
public function __construct(Graph $inputGraph){
- $this->graph = $inputGraph;
+ $this->graph = $inputGraph;
}
-
+
/**
*
* @param Vertex $startVertex
* @return Graph
*/
public function getResultGraph(){
- $returnGraph = $this->graph->createGraphCloneEdgeless(); //Copy vertices of original graph
-
- $minimumSpanningTreeAlgorithm = new AlgorithmKruskal($this->graph); //Create minimum spanning tree
+ $returnGraph = $this->graph->createGraphCloneEdgeless(); // Copy vertices of original graph
+
+ $minimumSpanningTreeAlgorithm = new AlgorithmKruskal($this->graph); // Create minimum spanning tree
$minimumSpanningTree = $minimumSpanningTreeAlgorithm->getResultGraph();
-
- $depthFirstSearch = $minimumSpanningTree->getAnyVertex()->searchDepthFirst(); //Depth first search in minmum spanning tree (for the eulerian path)
-
+
+ $depthFirstSearch = $minimumSpanningTree->getAnyVertex()->searchDepthFirst(); // Depth first search in minmum spanning tree (for the eulerian path)
+
$startVertex = NULL;
$oldVertex = NULL;
-
- foreach ($depthFirstSearch as $vertex){ //Connect vertices in order of the depth first search
-
- $vertex = $this->graph->getVertex( $vertex->getId() ); //get vertex from the original graph (not from the depth first search)
- //i need to clone the edge from the original graph, therefore i need the original edge
+
+ foreach ($depthFirstSearch as $vertex){ // connect vertices in order of the depth first search
+
+ $vertex = $this->graph->getVertex( $vertex->getId() ); // get vertex from the original graph (not from the depth first search)
+ // need to clone the edge from the original graph, therefore i need the original edge
if ($startVertex === NULL){
- $startVertex = $vertex;
+ $startVertex = $vertex;
}
else {
- foreach ($oldVertex->getEdgesTo( $vertex ) as $edge ){ //Get edge to clone //more edges are possible (returns an array)
+ foreach ($oldVertex->getEdgesTo( $vertex ) as $edge ){ // get edge(s) to clone, multiple edges are possible (returns an array if undirected edge)
$returnGraph->createEdgeClone( $edge );
break;
}
}
-
+
$oldVertex = $vertex;
}
-
- foreach ($oldVertex->getEdgesTo( $startVertex ) as $edge ){ //Connect last vertex with start vertex //retusn an array
+
+ // connect last vertex with start vertex
+ foreach ($oldVertex->getEdgesTo( $startVertex ) as $edge ){ // multiple edges are possible (returns an array if undirected edge)
$returnGraph->createEdgeClone( $edge );
break;
}
-
+
return $returnGraph;
}
}
\ No newline at end of file
|
Changed comments of TSP and nearest neighbour
|
graphp_algorithms
|
train
|
ba87bd5579d39da688245a34ad6e67ddaf974e4e
|
diff --git a/melodist/humidity.py b/melodist/humidity.py
index <HASH>..<HASH> 100644
--- a/melodist/humidity.py
+++ b/melodist/humidity.py
@@ -29,7 +29,7 @@ import melodist.util.util as util
import numpy as np
import pandas as pd
-def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=None, kr=None, month_hour_precip_mean=None):
+def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=None, kr=None, month_hour_precip_mean=None, preserve_daily_mean=False):
"""general function for humidity disaggregation
Args:
@@ -38,6 +38,8 @@ def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=Non
temp: hourly temperature time series (necessary for some methods)
kr: parameter for linear_dewpoint_variation method (6 or 12)
month_hour_precip_mean: [month, hour, precip(y/n)] categorical mean values
+ preserve_daily_mean: if True, correct the daily mean values of the disaggregated
+ data with the observed daily means.
Returns:
Disaggregated hourly values of relative humidity.
@@ -93,6 +95,12 @@ def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=Non
hum_disagg = pd.Series(index=precip_equal.index)
hum_disagg[:] = month_hour_precip_mean.loc[zip(hum_disagg.index.month, hum_disagg.index.hour, precip_equal > 0)].values
+ if preserve_daily_mean:
+ daily_mean_df = pd.DataFrame(data=dict(obs=data_daily.hum, disagg=hum_disagg.resample('D').mean()))
+ bias = melodist.util.distribute_equally(daily_mean_df.disagg - daily_mean_df.obs)
+ bias = bias.fillna(0)
+ hum_disagg -= bias
+
return hum_disagg.clip(0, 100)
diff --git a/melodist/station.py b/melodist/station.py
index <HASH>..<HASH> 100644
--- a/melodist/station.py
+++ b/melodist/station.py
@@ -199,7 +199,7 @@ class Station(object):
"""
self.data_disagg.wind = melodist.disaggregate_wind(self.data_daily.wind, method=method, **self.statistics.wind)
- def disaggregate_humidity(self, method='equal'):
+ def disaggregate_humidity(self, method='equal', preserve_daily_mean=False):
"""
Disaggregate relative humidity.
@@ -229,11 +229,15 @@ class Station(object):
``month_hour_precip_mean``:
Calculates hourly humidity from categorical [month, hour, precip(y/n)] mean values
derived from observations.
+
+ preserve_daily_mean : bool, optional
+ If True, correct the daily mean values of the disaggregated data with the observed daily means.
"""
self.data_disagg.hum = melodist.disaggregate_humidity(
self.data_daily,
temp=self.data_disagg.temp,
method=method,
+ preserve_daily_mean=preserve_daily_mean,
**self.statistics.hum
)
|
Add keyword preserve_daily_mean for humidity disaggregation
|
kristianfoerster_melodist
|
train
|
0ddbc9752ed0e624dd3f41c38921dde2355768b8
|
diff --git a/lib/svtplay_dl/service/urplay.py b/lib/svtplay_dl/service/urplay.py
index <HASH>..<HASH> 100644
--- a/lib/svtplay_dl/service/urplay.py
+++ b/lib/svtplay_dl/service/urplay.py
@@ -66,17 +66,30 @@ class Urplay(Service, OpenGraphThumbMixin):
def find_all_episodes(self, options):
parse = urlparse(self.url)
- match = re.search("/program/\d+-(\w+)-", parse.path)
- if not match:
- log.error("Can't find any videos")
- return None
- keyword = match.group(1)
episodes = []
- all_links = re.findall('card-link" href="([^"]+)"', self.get_urldata())
- for i in all_links:
- match = re.search("/program/\d+-(\w+)-", i)
- if match and match.group(1) == keyword:
- episodes.append(urljoin("http://urplay.se/", i))
+
+ if parse.netloc == "urskola.se":
+ data = self.get_urldata()
+ match = re.search('data-limit="[^"]+" href="([^"]+)"', data)
+ if match:
+ res = self.http.get(urljoin("http://urskola.se", match.group(1)))
+ data = res.text
+ tags = re.findall('<a class="puff tv video" title="[^"]+" href="([^"]+)"', data)
+ for i in tags:
+ url = urljoin("http://urskola.se/", i)
+ if url not in episodes:
+ episodes.append(url)
+ else:
+ match = re.search("/program/\d+-(\w+)-", parse.path)
+ if not match:
+ log.error("Can't find any videos")
+ return None
+ keyword = match.group(1)
+ all_links = re.findall('card-link" href="([^"]+)"', self.get_urldata())
+ for i in all_links:
+ match = re.search("/program/\d+-(\w+)-", i)
+ if match and match.group(1) == keyword:
+ episodes.append(urljoin("http://urplay.se/", i))
episodes_new = []
n = 0
|
urplay: support for -A on urskola.se
fixes #<I>
|
spaam_svtplay-dl
|
train
|
d37ec4ed2f528105185f658bf6ac1c14d327194d
|
diff --git a/lib/socket.js b/lib/socket.js
index <HASH>..<HASH> 100644
--- a/lib/socket.js
+++ b/lib/socket.js
@@ -198,7 +198,8 @@
}
var self = this;
-
+ self.connecting = true;
+
this.handshake(function (sid, heartbeat, close, transports) {
self.sessionid = sid;
self.closeTimeout = close * 1000;
|
Fix for Issue #<I> - multiple connect on reconnect
|
tsjing_socket.io-client
|
train
|
67d295b6ed12d89bee44d31c850f8c92e85d4c69
|
diff --git a/src/Parser.php b/src/Parser.php
index <HASH>..<HASH> 100644
--- a/src/Parser.php
+++ b/src/Parser.php
@@ -152,7 +152,7 @@ class Parser
private function process_mask($mask)
{
foreach ($mask as $key => $value) {
- return '.' . $key . (is_array($value) ? $this->process_item($value) : '');
+ return '.' . $key . (is_array($value) ? $this->process_mask($value) : '');
}
}
diff --git a/tests/ParserTest.php b/tests/ParserTest.php
index <HASH>..<HASH> 100644
--- a/tests/ParserTest.php
+++ b/tests/ParserTest.php
@@ -23,10 +23,10 @@ class ParserTest extends \PHPUnit_Framework_TestCase
->shouldAllowMockingProtectedMethods();
$parser->shouldReceive('getPayload')
- ->andReturn('{"message": {"title": "Hello World", "body": "Some message content"}, "comments": [{ "title": "hello", "message": "hello world"}, {"title": "world", "message": "hello world"}]}');
+ ->andReturn('{"message": {"title": "Hello World", "body": "Some message content"}, "comments": [{ "title": "hello", "message": "hello world", "tags": ["one", "two"]}, {"title": "world", "message": "hello world", "tags": ["red", "green"]}]}');
$this->assertEquals(array("message" => array("title" => "Hello World")), $parser->mask(array('message' => array('title' => '*'))));
- $this->assertEquals(array("comments" => array(array("title" => "hello", "message" => "hello world"), array("title" => "world", "message" => "hello world"))), $parser->mask(array('comments' => '*')));
+ $this->assertEquals(array("comments" => array(array("title" => "hello", "message" => "hello world", "tags" => array("one", "two")), array("title" => "world", "message" => "hello world", "tags" => array("red", "green")))), $parser->mask(array('comments' => '*')));
$this->assertEquals(array('posts' => null), $parser->mask(array('posts' => '*')));
}
|
Fix bug, introduced in refactor.
|
nathanmac_Parser
|
train
|
4ba5ae95c709aef53609c6e8a250f03791b94a50
|
diff --git a/foyer/oplsaa/rules.py b/foyer/oplsaa/rules.py
index <HASH>..<HASH> 100755
--- a/foyer/oplsaa/rules.py
+++ b/foyer/oplsaa/rules.py
@@ -828,16 +828,6 @@ def opls_1007(atom):
for neighbor in atom.bond_partners:
if check_atom(neighbor, [1002,1003,1009,1010,1012]):
return True
- '''
- # Check all neighbors of the silicon...
- for si_neighbor in neighbor.bond_partners:
- # ...except myself...
- if si_neighbor is atom:
- continue
- # ...make sure they've been marked as bulk silica oxygen.
- if not check_atom(si_neighbor, [1001,1011]):
- return False
- '''
@Element('H')
|
Removed commented section in rule for opls_<I>
|
mosdef-hub_foyer
|
train
|
b5b76d81879d7de22f9f214fd7c6ae2f9c72de5a
|
diff --git a/pkg/kubectl/kubectl.go b/pkg/kubectl/kubectl.go
index <HASH>..<HASH> 100644
--- a/pkg/kubectl/kubectl.go
+++ b/pkg/kubectl/kubectl.go
@@ -161,7 +161,8 @@ func ResourceAliases(rs []string) []string {
var plural string
switch {
case r == "endpoints":
- plural = r // exception. "endpoint" does not exist. Why?
+ // Endpoints type itself is plural, unlike every other resource.
+ plural = r
case strings.HasSuffix(r, "y"):
plural = r[0:len(r)-1] + "ies"
case strings.HasSuffix(r, "s"):
|
Document that endpoints is only plural in resource aliases
|
kubernetes_kubernetes
|
train
|
6e11ee75440c2d1ac6c226bae7639478447887ce
|
diff --git a/fastlane/lib/fastlane/plugins/plugin_info_collector.rb b/fastlane/lib/fastlane/plugins/plugin_info_collector.rb
index <HASH>..<HASH> 100644
--- a/fastlane/lib/fastlane/plugins/plugin_info_collector.rb
+++ b/fastlane/lib/fastlane/plugins/plugin_info_collector.rb
@@ -37,9 +37,11 @@ module Fastlane
break if plugin_name_valid?(plugin_name)
- if plugin_name_taken?(plugin_name)
- # Plugin name is already taken on RubyGems
- @ui.message("\nPlugin name '#{plugin_name}' is already taken on RubyGems, please choose a different one.")
+ gem_name = PluginManager::FASTLANE_PLUGIN_PREFIX + plugin_name
+
+ if gem_name_taken?(gem_name)
+ # Gem name is already taken on RubyGems
+ @ui.message("\nThe gem name '#{gem_name}' is already taken on RubyGems, please choose a different plugin name.")
else
# That's a naming error
@ui.message("\nPlugin names can only contain lower case letters, numbers, and underscores")
@@ -56,12 +58,12 @@ module Fastlane
# Does not contain the words 'fastlane' or 'plugin' since those will become
# part of the gem name
[/fastlane/, /plugin/].none? { |regex| regex =~ name } &&
- # Plugin name isn't taken on RubyGems yet
- !plugin_name_taken?(name)
+ # Gem name isn't taken on RubyGems yet
+ !gem_name_taken?(PluginManager::FASTLANE_PLUGIN_PREFIX + name)
end
- # Checks if the plugin name is still free on RubyGems
- def plugin_name_taken?(name)
+ # Checks if the gem name is still free on RubyGems
+ def gem_name_taken?(name)
require 'open-uri'
require 'json'
url = "https://rubygems.org/api/v1/gems/#{name}.json"
diff --git a/fastlane/spec/plugins_specs/plugin_generator_spec.rb b/fastlane/spec/plugins_specs/plugin_generator_spec.rb
index <HASH>..<HASH> 100644
--- a/fastlane/spec/plugins_specs/plugin_generator_spec.rb
+++ b/fastlane/spec/plugins_specs/plugin_generator_spec.rb
@@ -17,9 +17,7 @@ describe Fastlane::PluginGenerator do
let(:summary) { plugin_info.summary }
before(:each) do
- stub_request(:get, "https://rubygems.org/api/v1/gems/tester_thing.json").
- with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby'}).
- to_return(status: 200, body: nil, headers: {})
+ stub_plugin_exists_on_rubygems(plugin_name, false)
unless initialized
test_ui = Fastlane::PluginGeneratorUI.new
diff --git a/fastlane/spec/plugins_specs/plugin_info_collector_spec.rb b/fastlane/spec/plugins_specs/plugin_info_collector_spec.rb
index <HASH>..<HASH> 100644
--- a/fastlane/spec/plugins_specs/plugin_info_collector_spec.rb
+++ b/fastlane/spec/plugins_specs/plugin_info_collector_spec.rb
@@ -9,9 +9,7 @@ describe Fastlane::PluginInfoCollector do
before do
["my plugin", "test_name", "my_", "fastlane-whatever", "whatever"].each do |current|
- stub_request(:get, "https://rubygems.org/api/v1/gems/#{current}.json").
- with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby'}).
- to_return(status: 200, body: nil, headers: {})
+ stub_plugin_exists_on_rubygems(current, false)
end
end
@@ -105,9 +103,8 @@ describe Fastlane::PluginInfoCollector do
end
it "detects if the plugin is already taken on RubyGems.org" do
- stub_request(:get, "https://rubygems.org/api/v1/gems/already_taken.json").
- with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby'}).
- to_return(status: 200, body: {version: "1.0"}.to_json, headers: {})
+ stub_plugin_exists_on_rubygems('already_taken', true)
+
expect(collector.plugin_name_valid?('already_taken')).to be_falsey
end
end
diff --git a/fastlane/spec/spec_helper.rb b/fastlane/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/fastlane/spec/spec_helper.rb
+++ b/fastlane/spec/spec_helper.rb
@@ -43,3 +43,9 @@ def with_verbose(verbose)
ensure
$verbose = orig_verbose
end
+
+def stub_plugin_exists_on_rubygems(plugin_name, exists)
+ stub_request(:get, "https://rubygems.org/api/v1/gems/fastlane-plugin-#{plugin_name}.json").
+ with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby'}).
+ to_return(status: 200, body: (exists ? {version: "1.0"}.to_json : nil), headers: {})
+end
|
Fix the PluginInfoCollector to check RubyGems for the gem_name
Previously this was checking RubyGems for the plugin_name, which
does not contain the 'fastlane-plugin-' prefix, and is not the
full name of the gem.
Fixes up the tests to match this behavior and provides a helper
method for setting up the stubbed web request.
|
fastlane_fastlane
|
train
|
7bb7b11e9aca02852c2c5c537f72abfc24cf6dce
|
diff --git a/skyfield/iokit.py b/skyfield/iokit.py
index <HASH>..<HASH> 100644
--- a/skyfield/iokit.py
+++ b/skyfield/iokit.py
@@ -79,6 +79,7 @@ def download(url, verbose=True, blocksize=128*1024):
length += len(data)
if verbose:
bar.report(length, content_length)
+ w.flush()
os.rename(tempname, filename)
except KeyboardInterrupt:# Exception as e:
raise IOError('error getting {0} - {1}'.format(url, e))
|
Attempt to defeat dodgy test failure with flush()
Example test failure:
<URL>
|
skyfielders_python-skyfield
|
train
|
b0b324f0487a6518782bdc483612298ae80e130b
|
diff --git a/as/json.js b/as/json.js
index <HASH>..<HASH> 100644
--- a/as/json.js
+++ b/as/json.js
@@ -116,7 +116,7 @@ TChannelJSON.prototype.register = function register(
) {
var self = this;
- tchannel.handler.register(arg1, endpointHandler);
+ tchannel.register(arg1, endpointHandler);
function endpointHandler(req, res, arg2, arg3) {
if (req.headers.as !== 'json') {
|
pass in a registrable for json handler
|
uber_tchannel-node
|
train
|
9406ef354aa140d80cc313b11b47999f4bac0344
|
diff --git a/pandas/core/common.py b/pandas/core/common.py
index <HASH>..<HASH> 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -862,7 +862,7 @@ def console_encode(value):
try:
import sys
- return value.encode(sys.stdin.encoding, 'replace')
+ return value.encode(sys.stdin.encoding or 'utf-8', 'replace')
except (AttributeError, TypeError):
return value.encode('ascii', 'replace')
|
re-introduce fix for console_encode()
|
pandas-dev_pandas
|
train
|
7daaa46e6a8606ba16754380c182b25409d85c14
|
diff --git a/src/Illuminate/Log/LogManager.php b/src/Illuminate/Log/LogManager.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Log/LogManager.php
+++ b/src/Illuminate/Log/LogManager.php
@@ -270,7 +270,9 @@ class LogManager implements LoggerInterface
$config['emoji'] ?? ':boom:',
$config['short'] ?? false,
$config['context'] ?? true,
- $this->level($config)
+ $this->level($config),
+ $config['bubble'] ?? true,
+ $config['exclude_fields'] ?? []
)),
]);
}
|
[<I>] Adds missing logging options to slack log driver (#<I>)
* Adds missing logging options to slack log driver
* change to snake case for config values
|
laravel_framework
|
train
|
c3ab954c6e5a424d10ed414f9d0a3449a38300cb
|
diff --git a/salt/states/kapacitor.py b/salt/states/kapacitor.py
index <HASH>..<HASH> 100644
--- a/salt/states/kapacitor.py
+++ b/salt/states/kapacitor.py
@@ -72,16 +72,23 @@ def task_present(name,
with salt.utils.fopen(script_path, 'r') as file:
new_script = file.read().replace('\t', ' ')
- if old_script == new_script:
+ is_up_to_date = old_script == new_script and task_type == task['type'] and \
+ task['dbrps'] == [{'db': database, 'rp': retention_policy}]
+
+ if is_up_to_date:
comments.append('Task script is already up-to-date')
else:
if __opts__['test']:
ret['result'] = None
comments.append('Task would have been updated')
else:
- result = __salt__['kapacitor.define_task'](name, script_path,
- task_type=task_type, database=database,
- retention_policy=retention_policy)
+ result = __salt__['kapacitor.define_task'](
+ name,
+ script_path,
+ task_type=task_type,
+ database=database,
+ retention_policy=retention_policy
+ )
ret['result'] = result['success']
if not ret['result']:
comments.append('Could not define task')
@@ -89,11 +96,25 @@ def task_present(name,
comments.append(result['stderr'])
ret['comment'] = '\n'.join(comments)
return ret
- ret['changes']['TICKscript diff'] = '\n'.join(difflib.unified_diff(
- old_script.splitlines(),
- new_script.splitlines(),
- ))
- comments.append('Task script updated')
+
+ if old_script != new_script:
+ ret['changes']['TICKscript diff'] = '\n'.join(difflib.unified_diff(
+ old_script.splitlines(),
+ new_script.splitlines(),
+ ))
+ comments.append('Task script updated')
+
+ if not task or task['type'] != task_type:
+ ret['changes']['type'] = task_type
+ comments.append('Task type updated')
+
+ if not task or task['dbrps'][0]['db'] != database:
+ ret['changes']['db'] = database
+ comments.append('Task database updated')
+
+ if not task or task['dbrps'][0]['rp'] != retention_policy:
+ ret['changes']['rp'] = retention_policy
+ comments.append('Task retention policy updated')
if enable:
if task and task['enabled']:
|
improvements/fixes to kapacitor task change detection
make sure to check for changes in db/rp/task type as well as the script itself
|
saltstack_salt
|
train
|
a251803c27018d3c4dbfe26e371d6cb9dc4aafb9
|
diff --git a/eZ/Publish/Core/Repository/Tests/Service/Mock/RoleTest.php b/eZ/Publish/Core/Repository/Tests/Service/Mock/RoleTest.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/Repository/Tests/Service/Mock/RoleTest.php
+++ b/eZ/Publish/Core/Repository/Tests/Service/Mock/RoleTest.php
@@ -21,7 +21,7 @@ class RoleTest extends BaseServiceMockTest
* Test for the createRole() method.
*
* @covers \eZ\Publish\Core\Repository\RoleService::createRole
- * @covers \eZ\Publish\Core\Repository\RoleService::validateRoleCreateStructLimitations
+ * @covers \eZ\Publish\Core\Repository\RoleService::validateRoleCreateStruct
* @covers \eZ\Publish\Core\Repository\RoleService::validateLimitations
* @covers \eZ\Publish\Core\Repository\RoleService::validateLimitation
* @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
|
Fix coverage failure by RoleTest::testCreateRoleThrowsLimitationValidationException()
|
ezsystems_ezpublish-kernel
|
train
|
ca5aceb06c8b2c25bcedd653860eee94b9213457
|
diff --git a/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php b/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
+++ b/tests/Doctrine/Tests/DBAL/Functional/ResultCacheTest.php
@@ -195,7 +195,7 @@ class ResultCacheTest extends DbalFunctionalTestCase
}
/**
- * @param array<int, array<int, int|string>> $expectedResult
+ * @param array<int, array<int, int|string>>|list<int> $expectedResult
*/
private function assertCacheNonCacheSelectSameFetchModeAreEqual(array $expectedResult, int $fetchMode) : void
{
|
Account for columnar expected result
This is what is expected with FETCH_COLUMN
|
doctrine_dbal
|
train
|
83dbd5bc3609da75839901b5a6b34d495302b92d
|
diff --git a/app/src/main/java/com/felipecsl/asymmetricgridview/app/MainActivity.java b/app/src/main/java/com/felipecsl/asymmetricgridview/app/MainActivity.java
index <HASH>..<HASH> 100644
--- a/app/src/main/java/com/felipecsl/asymmetricgridview/app/MainActivity.java
+++ b/app/src/main/java/com/felipecsl/asymmetricgridview/app/MainActivity.java
@@ -25,7 +25,7 @@ public class MainActivity extends ActionBarActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (AsymmetricGridView) findViewById(R.id.listView);
- listView.setRequestedColumnWidth(Utils.dpToPx(this, 120));
+ listView.setRequestedColumnCount(2);
adapter = new ListAdapter(this, listView, get100Items());
@@ -53,23 +53,23 @@ public class MainActivity extends ActionBarActivity {
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.one_column) {
- listView.setRequestedColumnWidth(Utils.dpToPx(this, 240));
+ listView.setRequestedColumnCount(1);
listView.determineColumns();
listView.setAdapter(adapter);
} else if (id == R.id.two_columnns) {
- listView.setRequestedColumnWidth(Utils.dpToPx(this, 120));
+ listView.setRequestedColumnCount(2);
listView.determineColumns();
listView.setAdapter(adapter);
} else if (id == R.id.three_columns) {
- listView.setRequestedColumnWidth(Utils.dpToPx(this, 90));
+ listView.setRequestedColumnCount(3);
listView.determineColumns();
listView.setAdapter(adapter);
} else if (id == R.id.four_columns) {
- listView.setRequestedColumnWidth(Utils.dpToPx(this, 70));
+ listView.setRequestedColumnCount(4);
listView.determineColumns();
listView.setAdapter(adapter);
} else if (id == R.id.five_columns) {
- listView.setRequestedColumnWidth(Utils.dpToPx(this, 60));
+ listView.setRequestedColumnCount(5);
listView.determineColumns();
listView.setAdapter(adapter);
} else if (id == R.id.append_items) {
diff --git a/library/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridView.java b/library/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridView.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridView.java
+++ b/library/src/main/java/com/felipecsl/asymmetricgridview/library/widget/AsymmetricGridView.java
@@ -22,6 +22,7 @@ public class AsymmetricGridView<T extends AsymmetricItem> extends ListView {
private final int requestedHorizontalSpacing;
private final int requestedVerticalSpacing;
private int requestedColumnWidth;
+ private int requestedColumnCount;
private AsymmetricGridViewAdapter<T> gridAdapter;
public AsymmetricGridView(final Context context, final AttributeSet attrs) {
@@ -59,6 +60,10 @@ public class AsymmetricGridView<T extends AsymmetricItem> extends ListView {
requestedColumnWidth = width;
}
+ public void setRequestedColumnCount(int requestedColumnCount) {
+ this.requestedColumnCount = requestedColumnCount;
+ }
+
public int getRequestedHorizontalSpacing() {
return requestedHorizontalSpacing;
}
@@ -79,7 +84,9 @@ public class AsymmetricGridView<T extends AsymmetricItem> extends ListView {
if (requestedColumnWidth > 0) {
numColumns = (availableSpace + requestedHorizontalSpacing) /
- (requestedColumnWidth + requestedHorizontalSpacing);
+ (requestedColumnWidth + requestedHorizontalSpacing);
+ } else if (requestedColumnCount > 0) {
+ numColumns = requestedColumnCount;
} else {
// Default to 2 columns
numColumns = DEFAULT_COLUMN_COUNT;
|
Added setRequestedColumnCount to force column count
|
felipecsl_AsymmetricGridView
|
train
|
60a8a7a99ef4358b28d44a494ab7cc1f886fc35d
|
diff --git a/src/main/java/io/vlingo/xoom/http/Response.java b/src/main/java/io/vlingo/xoom/http/Response.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/vlingo/xoom/http/Response.java
+++ b/src/main/java/io/vlingo/xoom/http/Response.java
@@ -7,6 +7,7 @@
package io.vlingo.xoom.http;
+import java.util.Collection;
import java.util.function.Function;
import io.vlingo.xoom.http.Header.Headers;
@@ -111,6 +112,13 @@ public class Response {
return this;
}
+ public Response includeAll(final Collection<ResponseHeader> headers) {
+ for (final Header header : headers) {
+ include(header);
+ }
+ return this;
+ }
+
public ConsumerByteBuffer into(final ConsumerByteBuffer buffer) {
Function<String, byte[]> convert = Converters::textToBytes;
Function<byte[], ConsumerByteBuffer> put = buffer::put;
|
Implemented includeAll() for headers.
|
vlingo_vlingo-http
|
train
|
7d63184b28637f8078a3918afe3473bd155050b4
|
diff --git a/nionswift_plugin/nion_instrumentation_ui/ScanAcquisition.py b/nionswift_plugin/nion_instrumentation_ui/ScanAcquisition.py
index <HASH>..<HASH> 100644
--- a/nionswift_plugin/nion_instrumentation_ui/ScanAcquisition.py
+++ b/nionswift_plugin/nion_instrumentation_ui/ScanAcquisition.py
@@ -8,6 +8,7 @@ import threading
import typing
# local libraries
+from nion.data import xdata_1_0 as xd
from nion.swift import Facade
from nion.swift import HistogramPanel
from nion.swift.model import DataItem
@@ -53,6 +54,10 @@ def create_and_display_data_item(document_window, data_and_metadata, scan_data_l
data_item._data_item.session_id = document_window.library._document_model.session_id
data_item.title = "{} ({})".format(_("Spectrum Image"), scan_channel_name)
+
+ if scan_data_and_metadata.data_shape[0] == 1:
+ scan_data_and_metadata = xd.squeeze(scan_data_and_metadata)
+
data_item.set_data_and_metadata(scan_data_and_metadata)
document_window.display_data_item(data_item)
@@ -108,7 +113,7 @@ class ScanAcquisitionController:
scan_frame_parameters.subscan_pixel_size = (1, line_length / self.__scan_specifier.spacing_px)
# for fraction size/center, the line will start as horizontal and be rotated from there
scan_frame_parameters.subscan_fractional_size = 1 / context_data_shape[0], line_length / context_data_shape[1]
- scan_frame_parameters.subscan_fractional_center = (((line_start[0] + line_end[0]) / 2) / context_data_shape[0], ((line_start[1] + line_end[1]) / 2) / context_data_shape[0])
+ scan_frame_parameters.subscan_fractional_center = (((line_start[0] + line_end[0]) / 2) / context_data_shape[0], ((line_start[1] + line_end[1]) / 2) / context_data_shape[1])
scan_frame_parameters.subscan_rotation = -math.atan2(dy, dx) # radians counterclockwise
# print(f"{scan_frame_parameters}")
elif self.__scan_specifier.rect:
|
Fix coordinate bug in line scan. Display line scan HAADF as line plot.
|
nion-software_nionswift-instrumentation-kit
|
train
|
b1595d3f619169c44281ab7f0ffb245c01fbd22d
|
diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py
index <HASH>..<HASH> 100644
--- a/_pytest/assertion/rewrite.py
+++ b/_pytest/assertion/rewrite.py
@@ -177,6 +177,10 @@ def _write_pyc(co, source_path, pyc):
# This happens when we get a EEXIST in find_module creating the
# __pycache__ directory and __pycache__ is by some non-dir node.
return False
+ elif err == errno.EACCES:
+ # The directory is read-only; this can happen for example when
+ # running the tests in a package installed as root
+ return False
raise
try:
fp.write(imp.get_magic())
diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py
index <HASH>..<HASH> 100644
--- a/testing/test_assertrewrite.py
+++ b/testing/test_assertrewrite.py
@@ -1,4 +1,5 @@
import os
+import stat
import sys
import zipfile
import py
@@ -323,6 +324,18 @@ def test_rewritten():
assert "@py_builtins" in globals()""")
assert testdir.runpytest().ret == 0
+ def test_pycache_is_readonly(self, testdir):
+ cache = testdir.tmpdir.mkdir("__pycache__")
+ old_mode = cache.stat().mode
+ cache.chmod(old_mode ^ stat.S_IWRITE)
+ testdir.makepyfile("""
+def test_rewritten():
+ assert "@py_builtins" in globals()""")
+ try:
+ assert testdir.runpytest().ret == 0
+ finally:
+ cache.chmod(old_mode)
+
def test_zipfile(self, testdir):
z = testdir.tmpdir.join("myzip.zip")
z_fn = str(z)
@@ -346,8 +359,12 @@ import test_gum.test_lizard""" % (z_fn,))
def test_rewritten():
assert "@py_builtins" in globals()
""").encode("utf-8"), "wb")
+ old_mode = sub.stat().mode
sub.chmod(320)
- assert testdir.runpytest().ret == 0
+ try:
+ assert testdir.runpytest().ret == 0
+ finally:
+ sub.chmod(old_mode)
def test_dont_write_bytecode(self, testdir, monkeypatch):
testdir.makepyfile("""
|
Adds a test for and fixes #<I>. If attempting to write to the __pycache__ directory raises a permission error _write_pyc() should just return False to prevent any further write attempts.
|
pytest-dev_pytest
|
train
|
fd80d4955c32ea30bbe8e26664f295873aa7a504
|
diff --git a/MapDWebServer.go b/MapDWebServer.go
index <HASH>..<HASH> 100644
--- a/MapDWebServer.go
+++ b/MapDWebServer.go
@@ -144,6 +144,9 @@ func downloadsHandler(rw http.ResponseWriter, r *http.Request) {
}
func main() {
+ if _, err := os.Stat(dataDir + "/mapd_log/"); os.IsNotExist(err) {
+ os.MkdirAll(dataDir+"/mapd_log/", 0755)
+ }
lf, err := os.OpenFile(dataDir+"/mapd_log/"+getLogName("ALL"), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Fatal("Error opening log file: ", err)
|
Fix: create log dir if it doesn't exist
|
omnisci_mapd-core
|
train
|
71407f99d6643e3d5044d7aa13bb3bffa16be009
|
diff --git a/can/interfaces/usb2can/serial_selector.py b/can/interfaces/usb2can/serial_selector.py
index <HASH>..<HASH> 100644
--- a/can/interfaces/usb2can/serial_selector.py
+++ b/can/interfaces/usb2can/serial_selector.py
@@ -39,7 +39,7 @@ def find_serial_devices(serial_matcher="ED"):
:rtype: List[str]
"""
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
- objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2")
+ objSWbemServices = objWMIService.ConnectServer(".", "root\\cimv2")
items = objSWbemServices.ExecQuery("SELECT * FROM Win32_USBControllerDevice")
ids = (item.Dependent.strip('"')[-8:] for item in items)
return [e for e in ids if e.startswith(serial_matcher)]
|
Fix warning in usb2can
This PR removes [this `DeprecationWarning`](<URL>):
> invalid escape sequence \c
Is this correct to to? It now is like [this example](<URL>).
|
hardbyte_python-can
|
train
|
506a7cba2fe5e036b65ebeae30923d736621f405
|
diff --git a/tests/Unit/Core/BaseTest.php b/tests/Unit/Core/BaseTest.php
index <HASH>..<HASH> 100644
--- a/tests/Unit/Core/BaseTest.php
+++ b/tests/Unit/Core/BaseTest.php
@@ -1855,7 +1855,10 @@ class BaseTest extends \OxidTestCase
$oField2->binary = false;
$oField2->unsigned = false;
$oField2->has_default = true;
- $oField2->default_value = 1;
+ $oField2->default_value = '1';
+ $oField2->comment = 'Shop id (oxshops)';
+ $oField2->characterSet = null;
+ $oField2->collation = '';
$oField3 = new stdClass();
$oField3->name = 'OXTYPE';
|
ESDEV-<I> After rebase to master fix
|
OXID-eSales_oxideshop_ce
|
train
|
e3462fd0c6a3c112be5d1035378c6e38bdd08148
|
diff --git a/lib/danger/ci_source/buildkite.rb b/lib/danger/ci_source/buildkite.rb
index <HASH>..<HASH> 100644
--- a/lib/danger/ci_source/buildkite.rb
+++ b/lib/danger/ci_source/buildkite.rb
@@ -40,7 +40,7 @@ module Danger
self.repo_url = env["BUILDKITE_REPO"]
self.pull_request_id = env["BUILDKITE_PULL_REQUEST"]
- repo_matches = self.repo_url.match(%r{([\/:])([^\/]+\/[^\/.]+)(?:.git)?$})
+ repo_matches = self.repo_url.match(%r{([\/:])([^\/]+\/[^\/]+?)(\.git$|$)})
self.repo_slug = repo_matches[2] unless repo_matches.nil?
end
|
Change regex to handle dots in slug
|
danger_danger
|
train
|
d83a8a6459e15a6940058bf5f7987824dc7793d7
|
diff --git a/ini_test.go b/ini_test.go
index <HASH>..<HASH> 100644
--- a/ini_test.go
+++ b/ini_test.go
@@ -363,3 +363,75 @@ func TestWriteFile(t *testing.T) {
t.Fatalf("Expected file content to be \"%s\" but was \"%s\"", expected, found)
}
}
+
+func TestOverwriteRequiredOptions(t *testing.T) {
+ var tests = []struct {
+ args []string
+ expected []string
+ }{
+ {
+ args: []string{"--value", "from CLI"},
+ expected: []string{
+ "from CLI",
+ "from default",
+ },
+ },
+ {
+ args: []string{"--value", "from CLI", "--default", "from CLI"},
+ expected: []string{
+ "from CLI",
+ "from CLI",
+ },
+ },
+ {
+ args: []string{"--config", "no file name"},
+ expected: []string{
+ "from INI",
+ "from INI",
+ },
+ },
+ {
+ args: []string{"--value", "from CLI before", "--default", "from CLI before", "--config", "no file name"},
+ expected: []string{
+ "from INI",
+ "from INI",
+ },
+ },
+ {
+ args: []string{"--value", "from CLI before", "--default", "from CLI before", "--config", "no file name", "--value", "from CLI after", "--default", "from CLI after"},
+ expected: []string{
+ "from CLI after",
+ "from CLI after",
+ },
+ },
+ }
+
+ for _, test := range tests {
+ var opts struct {
+ Config func(s string) error `long:"config" no-ini:"true"`
+ Value string `long:"value" required:"true"`
+ Default string `long:"default" required:"true" default:"from default"`
+ }
+
+ p := NewParser(&opts, Default)
+
+ opts.Config = func(s string) error {
+ ini := NewIniParser(p)
+
+ return ini.Parse(bytes.NewBufferString("value = from INI\ndefault = from INI"))
+ }
+
+ _, err := p.ParseArgs(test.args)
+ if err != nil {
+ t.Fatalf("Unexpected error %s with args %+v", err, test.args)
+ }
+
+ if opts.Value != test.expected[0] {
+ t.Fatalf("Expected Value to be \"%s\" but was \"%s\" with args %+v", test.expected[0], opts.Value, test.args)
+ }
+
+ if opts.Default != test.expected[1] {
+ t.Fatalf("Expected Default to be \"%s\" but was \"%s\" with args %+v", test.expected[1], opts.Default, test.args)
+ }
+ }
+}
|
Added overwrite required test (test by zimmski)
|
jessevdk_go-flags
|
train
|
15c6269c99a9f83fdbff26b913ef1a91abc072ad
|
diff --git a/plugin/geomajas-plugin-printing/printing/src/main/java/org/geomajas/plugin/printing/component/impl/LegendIconComponentImpl.java b/plugin/geomajas-plugin-printing/printing/src/main/java/org/geomajas/plugin/printing/component/impl/LegendIconComponentImpl.java
index <HASH>..<HASH> 100644
--- a/plugin/geomajas-plugin-printing/printing/src/main/java/org/geomajas/plugin/printing/component/impl/LegendIconComponentImpl.java
+++ b/plugin/geomajas-plugin-printing/printing/src/main/java/org/geomajas/plugin/printing/component/impl/LegendIconComponentImpl.java
@@ -110,31 +110,37 @@ public class LegendIconComponentImpl extends AbstractPrintComponent<LegendIconCo
}
float baseWidth = iconRect.getWidth() / 10;
// draw symbol
- if (layerType.equals(LayerType.RASTER)) {
- Image img = context.getImage("/images/layer-raster.png");
- context.drawImage(img, iconRect, null);
- } else if (layerType.equals(LayerType.POINT) || layerType.equals(LayerType.MULTIPOINT)) {
- SymbolInfo symbol = styleInfo.getSymbol();
- if (symbol.getImage() != null) {
- try {
- Image pointImage = Image.getInstance(symbol.getImage().getHref());
- context.drawImage(pointImage, iconRect, iconRect);
- } catch (Exception ex) {
- log.error("Not able to create image for POINT Symbol", ex);
+ switch (layerType) {
+ case RASTER:
+ Image img = context.getImage("/images/layer-raster.png");
+ context.drawImage(img, iconRect, null);
+ break;
+ case MULTILINESTRING:
+ case LINESTRING:
+ context.drawRelativePath(new float[]{0f, 0.75f, 0.25f, 1f},
+ new float[]{0f, 0.25f, 0.75f, 1f}, iconRect, strokeColor, baseWidth * 2, dashArray);
+ break;
+ case MULTIPOINT:
+ case POINT:
+ SymbolInfo symbol = styleInfo.getSymbol();
+ if (symbol.getImage() != null) {
+ try {
+ Image pointImage = Image.getInstance(symbol.getImage().getHref());
+ context.drawImage(pointImage, iconRect, iconRect);
+ } catch (Exception ex) {
+ log.error("Not able to create image for POINT Symbol", ex);
+ }
+ } else if (symbol.getRect() != null) {
+ context.fillRectangle(iconRect, fillColor);
+ context.strokeRectangle(iconRect, strokeColor, baseWidth / 2);
+ } else {
+ context.fillEllipse(iconRect, fillColor);
+ context.strokeEllipse(iconRect, strokeColor, baseWidth / 2);
}
- } else if (symbol.getRect() != null) {
+ break;
+ default:
context.fillRectangle(iconRect, fillColor);
- context.strokeRectangle(iconRect, strokeColor, baseWidth / 2);
- } else {
- context.fillEllipse(iconRect, fillColor);
- context.strokeEllipse(iconRect, strokeColor, baseWidth / 2);
- }
- } else if (layerType.equals(LayerType.LINESTRING) || layerType.equals(LayerType.MULTIPOINT)) {
- context.drawRelativePath(new float[]{0f, 0.75f, 0.25f, 1f},
- new float[]{0f, 0.25f, 0.75f, 1f}, iconRect, strokeColor, baseWidth * 2, dashArray);
- } else if (layerType.equals(LayerType.POLYGON) || layerType.equals(LayerType.MULTIPOLYGON)) {
- context.fillRectangle(iconRect, fillColor);
- context.strokeRectangle(iconRect, strokeColor, baseWidth, dashArray);
+ context.strokeRectangle(iconRect, strokeColor, baseWidth, dashArray);
}
}
|
SPRINT-<I> updated render method with switch statement which defaults to rectangle
|
geomajas_geomajas-project-server
|
train
|
17a44e76222ede97355dc3bb743b22af7dc5c792
|
diff --git a/src/modules/navigation-model/navigation-model.spec.js b/src/modules/navigation-model/navigation-model.spec.js
index <HASH>..<HASH> 100644
--- a/src/modules/navigation-model/navigation-model.spec.js
+++ b/src/modules/navigation-model/navigation-model.spec.js
@@ -171,10 +171,12 @@ describe('navigation-model', function() {
var secondExpect = getCoordFromCenter(rowOrCol, direction * 4);
var finalExpect = getCoordFromCenter(rowOrCol, direction * 5);
- // contiguous data
+ // test contiguous data
+ // start at the center of the grid and seek; should go all the way to the edge of the grid
expect(model._navFrom(5, 5, forwardEvent)).toEqual(finalExpect);
// non-contiguous data
+ // start at the center of the grid and seek; should stop at the edges of the data
var firstEmpty = getCoordFromCenter(rowOrCol, direction * 2);
firstEmpty.data = '';
var secondEmpty = getCoordFromCenter(rowOrCol, direction * 3);
|
Clarify comments in navigation-model tests
|
gridgrid_grid
|
train
|
d11eeb662871fb6a5794ca07330d098a31f103d3
|
diff --git a/y/watermark.go b/y/watermark.go
index <HASH>..<HASH> 100644
--- a/y/watermark.go
+++ b/y/watermark.go
@@ -178,6 +178,7 @@ func (w *WaterMark) process() {
for _, ch := range toNotify {
close(ch)
}
+ delete(waiters, i) // Release the memory back.
}
if until != doneUntil {
AssertTrue(atomic.CompareAndSwapUint64(&w.doneUntil, doneUntil, until))
|
Watermark: Allow the wait channels to be GCed by deleting them from the map.
|
dgraph-io_badger
|
train
|
8318ad37280ef9471b10576d0086464d11358ac5
|
diff --git a/src/PhrestSDK.php b/src/PhrestSDK.php
index <HASH>..<HASH> 100644
--- a/src/PhrestSDK.php
+++ b/src/PhrestSDK.php
@@ -155,7 +155,7 @@ class PhrestSDK
{
// Set API DI to the default, this is required for models etc.
// As Phalcon will get the default DI to perform actions
- $apiDI = $defaultDI->get('sdk')->app->getDI();
+ $apiDI = self::getInstance()->app->getDI();
DI::setDefault($apiDI);
}
|
Optimisations, use accessor as it was getting a new instance every time
|
phrest_sdk
|
train
|
fdeeb8979cff47fab064d5859028110df8042e70
|
diff --git a/closure/goog/editor/field.js b/closure/goog/editor/field.js
index <HASH>..<HASH> 100644
--- a/closure/goog/editor/field.js
+++ b/closure/goog/editor/field.js
@@ -996,8 +996,7 @@ goog.editor.Field.prototype.disposeInternal = function() {
this.execCommand(goog.editor.Command.CLEAR_LOREM);
}
- this.field = null;
- this.editableDomHelper = null;
+ this.tearDownFieldObject_();
this.clearListeners();
this.clearFieldLoadListener_();
this.originalDomHelper = null;
@@ -1017,10 +1016,6 @@ goog.editor.Field.prototype.disposeInternal = function() {
var plugin = this.plugins_[classId];
if (plugin.isAutoDispose()) {
plugin.dispose();
- } else {
- // When the plugin is not auto-disposable, at least unregister this field
- // object from it.
- plugin.unregisterFieldObject(this);
}
}
delete (this.plugins_);
diff --git a/closure/goog/editor/field_test.js b/closure/goog/editor/field_test.js
index <HASH>..<HASH> 100644
--- a/closure/goog/editor/field_test.js
+++ b/closure/goog/editor/field_test.js
@@ -102,11 +102,10 @@ goog.inherits(TestPlugin, goog.editor.Plugin);
* Tests that calling registerPlugin will add the plugin to the
* plugin map.
*/
-function testRegisterPluginOnEditableField() {
+function testRegisterPlugin() {
var editableField = new FieldConstructor('testField');
var plugin = new TestPlugin();
- editableField.makeEditable();
editableField.registerPlugin(plugin);
assertEquals(
@@ -153,14 +152,7 @@ function testRegisterPluginOnEditableField() {
editableField.indexedPlugins_[goog.editor.Plugin.Op.CLEAN_CONTENTS_HTML]
[0]);
- // Registering the plugin into the editor also enabled the plugin.
- assertTrue(plugin.isEnabled(editableField));
-
editableField.dispose();
-
- // Disposing the editor will also dispose the registered plugin.
- assertFalse(plugin.isEnabled(editableField));
- assertTrue(plugin.isDisposed());
}
@@ -180,10 +172,6 @@ function testUnregisterPlugin() {
editableField.plugins_[plugin.getTrogClassId()]);
editableField.dispose();
-
- // When the editor is disposed, it does not dispose the plugin because it does
- // not have a reference of it anymore.
- assertFalse(plugin.isDisposed());
}
@@ -221,18 +209,10 @@ function testDisposed_PluginAutoDispose() {
editableField.registerPlugin(plugin);
editableField.registerPlugin(noDisposePlugin);
- editableField.makeEditable();
-
- assertTrue(plugin.isEnabled(editableField));
- assertTrue(noDisposePlugin.isEnabled(editableField));
-
editableField.dispose();
-
assert(editableField.isDisposed());
assertTrue(plugin.isDisposed());
assertFalse(noDisposePlugin.isDisposed());
- assertFalse(plugin.isEnabled(editableField));
- assertFalse(noDisposePlugin.isEnabled(editableField));
}
var STRING_KEY = String.fromCharCode(goog.events.KeyCodes.A).toLowerCase();
@@ -296,27 +276,25 @@ function assertClickDefaultActionIsNotCanceled(editableField) {
/**
* Tests that plugins are disabled when the field is made uneditable.
*/
+
function testMakeUneditableDisablesPlugins() {
var editableField = new FieldConstructor('testField');
var plugin = new TestPlugin();
- editableField.registerPlugin(plugin);
-
- // The plugin is not enabled because the field is not editable yet.
- assertTrue(editableField.isUneditable());
- assertFalse(plugin.isEnabled(editableField));
+ var calls = 0;
+ plugin.disable = function(field) {
+ assertEquals(editableField, field);
+ assertTrue(field.isUneditable());
+ calls++;
+ };
+ editableField.registerPlugin(plugin);
editableField.makeEditable();
- assertFalse(editableField.isUneditable());
-
- // The plugin becomes editable.
- assertTrue(plugin.isEnabled(editableField));
+ assertEquals(0, calls);
editableField.makeUneditable();
- assertTrue(editableField.isUneditable());
- // The plugin is not disabled.
- assertFalse(plugin.isEnabled(editableField));
+ assertEquals(1, calls);
editableField.dispose();
}
|
Rollback of changelist <I>.
Fix the lifecycle of the plugins when the field gets disposed.
No point to call tearDownFieldObject_ when disposing the field because it will call disable on all the plugins. However, the plugins are getting disposed below, and they call disable once more internally.
TESTED=unit tests, also with other plugins.
RELNOTES: fixing the lifecycle of editor plugins that are installed in the editor field.
***
-------------
Created by MOE: <URL>
|
google_closure-library
|
train
|
a6da4ba012de756b8b74e233106e9adbe7ba9de2
|
diff --git a/lib/rbnacl/secret_box.rb b/lib/rbnacl/secret_box.rb
index <HASH>..<HASH> 100644
--- a/lib/rbnacl/secret_box.rb
+++ b/lib/rbnacl/secret_box.rb
@@ -70,7 +70,7 @@ module Crypto
#
# @raise [Crypto::LengthError] If the nonce is not valid
#
- # @return [String] The ciphertext without the nonce prepended (BINARY encoded)
+ # @return [Crypto::Ciphertext] The ciphertext without the nonce prepended (BINARY encoded)
def box(nonce, message)
@primitive.box(nonce, message)
end
|
Note that we're returning a Ciphertext
|
crypto-rb_rbnacl
|
train
|
8ef7e21c3cc4c4e1507cc417248c71ed8f7112ea
|
diff --git a/src/browserbox.js b/src/browserbox.js
index <HASH>..<HASH> 100644
--- a/src/browserbox.js
+++ b/src/browserbox.js
@@ -330,7 +330,7 @@
}
});
- self.breakIdle(function() {
+ self.breakIdle().then(function() {
self.client.exec.apply(self.client, args);
});
};
@@ -372,12 +372,10 @@
/**
* Stops actions related idling, if IDLE is supported, sends DONE to stop it
- *
- * @param {Function} callback Function to run after required actions are performed
*/
- BrowserBox.prototype.breakIdle = function(callback) {
+ BrowserBox.prototype.breakIdle = function() {
if (!this._enteredIdle) {
- return callback();
+ return Promise.resolve();
}
clearTimeout(this._idleTimeout);
@@ -389,7 +387,7 @@
console.log(this.options.sessionId + ' idle terminated');
- return callback();
+ return Promise.resolve();
};
/**
diff --git a/test/integration/browserbox-test.js b/test/integration/browserbox-test.js
index <HASH>..<HASH> 100644
--- a/test/integration/browserbox-test.js
+++ b/test/integration/browserbox-test.js
@@ -672,7 +672,7 @@
});
});
- describe('precheck', function() {
+ describe.skip('precheck', function() {
var callCtr;
beforeEach(function() {
diff --git a/test/unit/browserbox-test.js b/test/unit/browserbox-test.js
index <HASH>..<HASH> 100644
--- a/test/unit/browserbox-test.js
+++ b/test/unit/browserbox-test.js
@@ -141,8 +141,8 @@
describe('#exec', function() {
beforeEach(function() {
- sinon.stub(br, 'breakIdle', function(callback) {
- return callback();
+ sinon.stub(br, 'breakIdle', function() {
+ return Promise.resolve();
});
});
@@ -185,14 +185,6 @@
next();
});
});
-
- it('should continue with no callback', function(done) {
- sinon.stub(br.client, 'exec', function() {
- arguments[arguments.length - 1]({}, done);
- });
- br.exec('TEST');
- expect(br.client.exec.callCount).to.equal(1);
- });
});
describe('#enterIdle', function() {
@@ -232,13 +224,10 @@
sinon.stub(br.client.socket, 'send');
br._enteredIdle = 'IDLE';
- br.breakIdle(function() {
-
+ br.breakIdle().then(function() {
expect([].slice.call(new Uint8Array(br.client.socket.send.args[0][0]))).to.deep.equal([0x44, 0x4f, 0x4e, 0x45, 0x0d, 0x0a]);
br.client.socket.send.restore();
-
- done();
- });
+ }).then(done);
});
});
|
Port #breakIdle to Promise
|
emailjs_emailjs-imap-client
|
train
|
c0d5e550a7976b3251d30c8c3089c3c2d7fb2dc6
|
diff --git a/pug/miner/views.py b/pug/miner/views.py
index <HASH>..<HASH> 100644
--- a/pug/miner/views.py
+++ b/pug/miner/views.py
@@ -302,9 +302,7 @@ def follow_double_underscores(obj, field_name=None, excel_dialect=True):
return follow_double_underscores(getattr(obj, split_fields[0]), field_name=split_fields[1:])
if excel_dialect:
if isinstance(value, datetime.datetime):
- value = str(value)
- if isinstance(value, basestring) and value.endswith('+00:00'):
- value = value[:-6]
+ value = value.strftime('%Y-%m-%d %H:%M:%S')
return value
return follow_double_underscores(getattr(obj, split_fields[0]), field_name=split_fields[1:])
|
convert straight to the timezone-free string format that excel likes
|
hobson_pug
|
train
|
e4d6eab845caf6033f630ce975d1de5255994aa7
|
diff --git a/src/test/java/rx/operators/OperationConditionalsTest.java b/src/test/java/rx/operators/OperationConditionalsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/rx/operators/OperationConditionalsTest.java
+++ b/src/test/java/rx/operators/OperationConditionalsTest.java
@@ -15,6 +15,7 @@
*/
package rx.operators;
+import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
@@ -33,8 +34,10 @@ import rx.Observable;
import rx.Observer;
import rx.Statement;
import rx.Subscription;
+import rx.observers.TestObserver;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
+import rx.util.functions.Action1;
import rx.util.functions.Func0;
public class OperationConditionalsTest {
@@ -108,7 +111,7 @@ public class OperationConditionalsTest {
<T> void observe(Observable<? extends T> source, T... values) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -127,7 +130,7 @@ public class OperationConditionalsTest {
<T> void observeSequence(Observable<? extends T> source, Iterable<? extends T> values) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -146,7 +149,7 @@ public class OperationConditionalsTest {
<T> void observeError(Observable<? extends T> source, Class<? extends Throwable> error, T... valuesBeforeError) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -165,7 +168,7 @@ public class OperationConditionalsTest {
<T> void observeSequenceError(Observable<? extends T> source, Class<? extends Throwable> error, Iterable<? extends T> valuesBeforeError) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -400,6 +403,7 @@ public class OperationConditionalsTest {
@Test
public void testDoWhileManyTimes() {
+ fail("deadlocking");
Observable<Integer> source1 = Observable.from(1, 2, 3).subscribeOn(Schedulers.currentThread());
List<Integer> expected = new ArrayList<Integer>(numRecursion * 3);
|
Conditionals: Fix all but 2 tests
|
ReactiveX_RxJavaComputationExpressions
|
train
|
98bae3621c9ebddb7233f9b0d5b447339b30041d
|
diff --git a/test/unit/core.js b/test/unit/core.js
index <HASH>..<HASH> 100644
--- a/test/unit/core.js
+++ b/test/unit/core.js
@@ -22,6 +22,8 @@ $(function() {
ok($.fn.powerTip.defaults.hasOwnProperty('offset'), 'offset exists');
ok($.fn.powerTip.defaults.hasOwnProperty('mouseOnToPopup'), 'mouseOnToPopup exists');
ok($.fn.powerTip.defaults.hasOwnProperty('manual'), 'manual exists');
+ ok($.fn.powerTip.defaults.hasOwnProperty('openEvents'), 'openEvents exists');
+ ok($.fn.powerTip.defaults.hasOwnProperty('closeEvents'), 'closeEvents exists');
});
test('expose smart placement lists', function() {
|
Added openEvents/closeEvents to expose defaults tests.
Part of issue #<I>.
|
stevenbenner_jquery-powertip
|
train
|
217d28c2ffd2c83b2980d01e2e69cd27d2d70935
|
diff --git a/pypika/terms.py b/pypika/terms.py
index <HASH>..<HASH> 100644
--- a/pypika/terms.py
+++ b/pypika/terms.py
@@ -21,10 +21,9 @@ from pypika.utils import (
)
try:
- basestring
+ basestring
except NameError:
- basestring = str
-
+ basestring = str
__author__ = "Timothy Heys"
__email__ = "theys@kayak.com"
@@ -73,7 +72,8 @@ class Term(object):
def for_(self, table):
"""
- Replaces the tables of this term for the table parameter provided. The base implementation returns self because not all terms have a table property.
+ Replaces the tables of this term for the table parameter provided. The base implementation returns self
+ because not all terms have a table property.
:param table:
The table to replace with.
@@ -273,7 +273,7 @@ class ValueWrapper(Term):
class Values(Term):
- def __init__(self, field,):
+ def __init__(self, field, ):
super(Values, self).__init__(None)
self.field = Field(field) if not isinstance(field, Field) else field
@@ -338,7 +338,6 @@ class EmptyCriterion:
return other
-
class Field(Criterion):
def __init__(self, name, alias=None, table=None):
super(Field, self).__init__(alias)
@@ -392,7 +391,7 @@ class Star(Field):
def get_sql(self, with_alias=False, with_namespace=False, quote_char=None, **kwargs):
if self.table and (with_namespace or self.table.alias):
return "{quote}{namespace}{quote}.*".format(
- namespace=self.table.alias or getattr(self.table, '_table_name'),
+ namespace=self.table.alias or getattr(self.table, '_table_name'),
quote=quote_char or ''
)
@@ -411,8 +410,8 @@ class Tuple(Criterion):
def get_sql(self, **kwargs):
return '({})'.format(
- ','.join(term.get_sql(**kwargs)
- for term in self.values)
+ ','.join(term.get_sql(**kwargs)
+ for term in self.values)
)
@property
@@ -424,8 +423,8 @@ class Tuple(Criterion):
class Array(Tuple):
def get_sql(self, **kwargs):
return '[{}]'.format(
- ','.join(term.get_sql(**kwargs)
- for term in self.values)
+ ','.join(term.get_sql(**kwargs)
+ for term in self.values)
)
@@ -433,6 +432,10 @@ class Bracket(Tuple):
def __init__(self, term):
super(Bracket, self).__init__(term)
+ def get_sql(self, **kwargs):
+ sql = super().get_sql(**kwargs)
+ return '{sql} {alias}'.format(sql=sql, alias=self.alias) if self.alias else sql
+
class BasicCriterion(Criterion):
def __init__(self, comparator, left, right, alias=None):
@@ -1040,14 +1043,14 @@ class Interval(object):
else:
# Create the whole expression but trim out the unnecessary fields
expr = "{years}-{months}-{days} {hours}:{minutes}:{seconds}.{microseconds}".format(
- years=getattr(self, 'years', 0),
- months=getattr(self, 'months', 0),
- days=getattr(self, 'days', 0),
- hours=getattr(self, 'hours', 0),
- minutes=getattr(self, 'minutes', 0),
- seconds=getattr(self, 'seconds', 0),
- microseconds=getattr(self, 'microseconds', 0),
- )
+ years=getattr(self, 'years', 0),
+ months=getattr(self, 'months', 0),
+ days=getattr(self, 'days', 0),
+ hours=getattr(self, 'hours', 0),
+ minutes=getattr(self, 'minutes', 0),
+ seconds=getattr(self, 'seconds', 0),
+ microseconds=getattr(self, 'microseconds', 0),
+ )
expr = self.trim_pattern.sub('', expr)
unit = '{largest}_{smallest}'.format(
diff --git a/pypika/tests/test_tuples.py b/pypika/tests/test_tuples.py
index <HASH>..<HASH> 100644
--- a/pypika/tests/test_tuples.py
+++ b/pypika/tests/test_tuples.py
@@ -80,3 +80,10 @@ class BracketTests(unittest.TestCase):
.select(Bracket(self.table_abc.foo / 2) / 2)
self.assertEqual('SELECT ("foo"/2)/2 FROM "abc"', str(q))
+
+ def test_arithmetic_with_brackets_and_alias(self):
+ q = Query \
+ .from_(self.table_abc) \
+ .select(Bracket(self.table_abc.foo / 2).as_('alias'))
+
+ self.assertEqual('SELECT ("foo"/2) alias FROM "abc"', str(q))
|
Added support for alias to Bracket term
|
kayak_pypika
|
train
|
e4f606ebde9aef271455b06b31bdfc81b03ea313
|
diff --git a/aerospike_suite_test.go b/aerospike_suite_test.go
index <HASH>..<HASH> 100644
--- a/aerospike_suite_test.go
+++ b/aerospike_suite_test.go
@@ -2,7 +2,9 @@ package aerospike_test
import (
"flag"
+ "log"
"math/rand"
+ "strings"
"testing"
"time"
@@ -33,3 +35,18 @@ func TestAerospike(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Aerospike Client Library Suite")
}
+
+func featureEnabled(feature string) bool {
+ client, err := NewClientWithPolicy(clientPolicy, *host, *port)
+ if err != nil {
+ log.Fatal("Failed to connect to aerospike: err:", err)
+ }
+
+ node := client.GetNodes()[0]
+ infoMap, err := node.RequestInfo("features")
+ if err != nil {
+ log.Fatal("Failed to connect to aerospike: err:", err)
+ }
+
+ return strings.Contains(infoMap["features"], feature)
+}
diff --git a/large_list_test.go b/large_list_test.go
index <HASH>..<HASH> 100644
--- a/large_list_test.go
+++ b/large_list_test.go
@@ -25,6 +25,10 @@ import (
var _ = Describe("LargeList Test", func() {
initTestVars()
+ if !featureEnabled("ldt") {
+ return
+ }
+
// connection data
var client *Client
var err error
diff --git a/large_map_test.go b/large_map_test.go
index <HASH>..<HASH> 100644
--- a/large_map_test.go
+++ b/large_map_test.go
@@ -24,6 +24,10 @@ import (
var _ = Describe("LargeMap Test", func() {
initTestVars()
+ if !featureEnabled("ldt") {
+ return
+ }
+
// connection data
var client *Client
var err error
diff --git a/large_set_test.go b/large_set_test.go
index <HASH>..<HASH> 100644
--- a/large_set_test.go
+++ b/large_set_test.go
@@ -32,6 +32,10 @@ import (
var _ = Describe("LargeSet Test", func() {
initTestVars()
+ if !featureEnabled("ldt") {
+ return
+ }
+
// connection data
var client *Client
var err error
diff --git a/large_stack_test.go b/large_stack_test.go
index <HASH>..<HASH> 100644
--- a/large_stack_test.go
+++ b/large_stack_test.go
@@ -24,6 +24,10 @@ import (
var _ = Describe("LargeStack Test", func() {
initTestVars()
+ if !featureEnabled("ldt") {
+ return
+ }
+
// connection data
var client *Client
var err error
|
check for ldt feature before running tests
|
aerospike_aerospike-client-go
|
train
|
c6a50419b844dd308a706c4f93cf35b89d0fa49a
|
diff --git a/lib/mean.js b/lib/mean.js
index <HASH>..<HASH> 100644
--- a/lib/mean.js
+++ b/lib/mean.js
@@ -291,9 +291,7 @@ Meanio.prototype.Module = function(name) {
this.config = config;
// bootstrap models
- util.walk(modulePath(this.name, 'server'), 'model', null, function(model) {
- require(model);
- });
+ util.walk(modulePath(this.name, 'server'), 'model', null, require);
this.render = function(view, options, callback) {
swig.renderFile(modulePath(this.name, '/server/views/' + view + '.html'), options, callback);
@@ -522,7 +520,6 @@ function aggregate(ext, asset, options) {
weight: weight,
data: ugly.code
};
-
} else {
group = options.group || 'header';
@@ -530,17 +527,14 @@ function aggregate(ext, asset, options) {
weight: weight,
data: data.toString()
};
-
}
}
function addInlineCode(ext, data) {
-
var md5 = crypto.createHash('md5');
md5.update(data);
var hash = md5.digest('hex');
pushAggregatedData(ext, hash, data);
-
}
diff --git a/lib/util.js b/lib/util.js
index <HASH>..<HASH> 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -2,6 +2,7 @@
var fs = require('fs'),
_ = require('lodash'),
+ glob = require('glob'),
path = require('path');
var baseRgx = /(.*).(js|coffee)$/;
@@ -24,6 +25,13 @@ function walk(wpath, type, excludeDir, callback) {
});
}
+// ability to preload requirements for tests
+function preload(gpath, type) {
+ glob.sync(gpath).forEach(function(file) {
+ walk(file, type, null, require);
+ });
+}
+
function loadConfig() {
// Load configurations
// Set the node environment variable if not set before
@@ -85,4 +93,5 @@ JSON.unflatten = function(data) {
};
exports.walk = walk;
+exports.preload = preload;
exports.loadConfig = loadConfig;
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "meanio",
- "version": "0.5.51",
+ "version": "0.5.6",
"preferGlobal": true,
"description": "Simple command line interface for installing and managing MEAN apps",
"author": {
@@ -50,6 +50,7 @@
"chalk": "^0.4.0",
"commander": "^2.2.0",
"dependable": "^0.2.5",
+ "glob": "^4.0.3",
"lodash": "^2.4.1",
"mongodb": "^1.4.0",
"mongoose": "^3.8.12",
|
move models preload to meanio
|
linnovate_meanio
|
train
|
7894225a85ab955aaf998ff4b97bf6fbc911e6ca
|
diff --git a/tensorboard/backend/http_util.py b/tensorboard/backend/http_util.py
index <HASH>..<HASH> 100644
--- a/tensorboard/backend/http_util.py
+++ b/tensorboard/backend/http_util.py
@@ -44,6 +44,7 @@ _CSP_FONT_DOMAINS_WHITELIST = ["data:"]
_CSP_FRAME_DOMAINS_WHITELIST = []
_CSP_IMG_DOMAINS_WHITELIST = []
_CSP_SCRIPT_DOMAINS_WHITELIST = []
+_CSP_CONNECT_DOMAINS_WHITELIST = []
_CSP_SCRIPT_SELF = True
# numericjs (via projector) uses unsafe-eval :(.
_CSP_SCRIPT_UNSAFE_EVAL = True
@@ -201,6 +202,7 @@ def Respond(
_CSP_FONT_DOMAINS_WHITELIST
_CSP_FRAME_DOMAINS_WHITELIST
_CSP_SCRIPT_DOMAINS_WHITELIST
+ _CSP_CONNECT_DOMAINS_WHITELIST
frags = (
_CSP_SCRIPT_DOMAINS_WHITELIST
@@ -244,6 +246,8 @@ def Respond(
"'unsafe-inline'",
*_CSP_STYLE_DOMAINS_WHITELIST
),
+ "connect-src %s"
+ % _create_csp_string("'self'", *_CSP_CONNECT_DOMAINS_WHITELIST),
"script-src %s" % script_srcs,
]
)
diff --git a/tensorboard/backend/http_util_test.py b/tensorboard/backend/http_util_test.py
index <HASH>..<HASH> 100644
--- a/tensorboard/backend/http_util_test.py
+++ b/tensorboard/backend/http_util_test.py
@@ -242,7 +242,7 @@ class RespondTest(tb_test.TestCase):
"default-src 'self';font-src 'self' data:;frame-ancestors *;"
"frame-src 'self';img-src 'self' data: blob:;object-src 'none';"
"style-src 'self' https://www.gstatic.com data: 'unsafe-inline';"
- "script-src 'self' 'unsafe-eval' 'sha256-abcdefghi'"
+ "connect-src 'self';script-src 'self' 'unsafe-eval' 'sha256-abcdefghi'"
)
self.assertEqual(r.headers.get("Content-Security-Policy"), expected_csp)
@@ -256,7 +256,7 @@ class RespondTest(tb_test.TestCase):
"default-src 'self';font-src 'self' data:;frame-ancestors *;"
"frame-src 'self';img-src 'self' data: blob:;object-src 'none';"
"style-src 'self' https://www.gstatic.com data: 'unsafe-inline';"
- "script-src 'unsafe-eval'"
+ "connect-src 'self';script-src 'unsafe-eval'"
)
self.assertEqual(r.headers.get("Content-Security-Policy"), expected_csp)
@@ -271,7 +271,7 @@ class RespondTest(tb_test.TestCase):
"default-src 'self';font-src 'self' data:;frame-ancestors *;"
"frame-src 'self';img-src 'self' data: blob:;object-src 'none';"
"style-src 'self' https://www.gstatic.com data: 'unsafe-inline';"
- "script-src 'none'"
+ "connect-src 'self';script-src 'none'"
)
self.assertEqual(r.headers.get("Content-Security-Policy"), expected_csp)
@@ -286,7 +286,7 @@ class RespondTest(tb_test.TestCase):
"default-src 'self';font-src 'self' data:;frame-ancestors *;"
"frame-src 'self';img-src 'self' data: blob:;object-src 'none';"
"style-src 'self' https://www.gstatic.com data: 'unsafe-inline';"
- "script-src 'self'"
+ "connect-src 'self';script-src 'self'"
)
self.assertEqual(r.headers.get("Content-Security-Policy"), expected_csp)
@@ -300,7 +300,7 @@ class RespondTest(tb_test.TestCase):
"default-src 'self';font-src 'self' data:;frame-ancestors *;"
"frame-src 'self';img-src 'self' data: blob:;object-src 'none';"
"style-src 'self' https://www.gstatic.com data: 'unsafe-inline';"
- "script-src 'self' 'sha256-abcdefghi'"
+ "connect-src 'self';script-src 'self' 'sha256-abcdefghi'"
)
self.assertEqual(r.headers.get("Content-Security-Policy"), expected_csp)
@@ -328,7 +328,7 @@ class RespondTest(tb_test.TestCase):
"frame-src 'self' https://myframe.com;"
"img-src 'self' data: blob: https://example.com;"
"object-src 'none';style-src 'self' https://www.gstatic.com data: "
- "'unsafe-inline' https://googol.com;script-src "
+ "'unsafe-inline' https://googol.com;connect-src 'self';script-src "
"https://tensorflow.org/tensorboard 'self' 'unsafe-eval' 'sha256-abcd'"
)
self.assertEqual(r.headers.get("Content-Security-Policy"), expected_csp)
|
csp: make connect-src configurable (#<I>)
Google Analytics can use `POST` method and requires `connect-src`.
This change does not add Google Analytics in the allowlist but merely it configurable.
|
tensorflow_tensorboard
|
train
|
5b4f9f3ca35f8c64af0ed99ab544ffdf530945e9
|
diff --git a/lib/offsite_payments/integrations/molpay.rb b/lib/offsite_payments/integrations/molpay.rb
index <HASH>..<HASH> 100644
--- a/lib/offsite_payments/integrations/molpay.rb
+++ b/lib/offsite_payments/integrations/molpay.rb
@@ -4,8 +4,8 @@ module OffsitePayments #:nodoc:
mattr_accessor :acknowledge_url
self.acknowledge_url = 'https://www.onlinepayment.com.my/MOLPay/API/chkstat/returnipn.php'
- def self.notification(post)
- Notification.new(post)
+ def self.notification(post, options = {})
+ Notification.new(post, options)
end
def self.return(query_string, options={})
|
Update molpay.rb
- notification issue.
|
activemerchant_offsite_payments
|
train
|
ac9191552325484e685b2336df6bbb5e7b4ad379
|
diff --git a/src/Kunstmaan/GeneratorBundle/Command/GenerateLayoutCommand.php b/src/Kunstmaan/GeneratorBundle/Command/GenerateLayoutCommand.php
index <HASH>..<HASH> 100644
--- a/src/Kunstmaan/GeneratorBundle/Command/GenerateLayoutCommand.php
+++ b/src/Kunstmaan/GeneratorBundle/Command/GenerateLayoutCommand.php
@@ -52,7 +52,8 @@ EOT
* {@inheritdoc}
*/
protected function doExecute()
- { if (!$this->isSubCommand()) {
+ {
+ if (!$this->isSubCommand()) {
$this->assistant->writeSection('Layout generation');
}
diff --git a/src/Kunstmaan/GeneratorBundle/Generator/KunstmaanGenerator.php b/src/Kunstmaan/GeneratorBundle/Generator/KunstmaanGenerator.php
index <HASH>..<HASH> 100644
--- a/src/Kunstmaan/GeneratorBundle/Generator/KunstmaanGenerator.php
+++ b/src/Kunstmaan/GeneratorBundle/Generator/KunstmaanGenerator.php
@@ -249,6 +249,36 @@ class KunstmaanGenerator extends Generator
}
/**
+ * Render all files in the source directory and copy them to the target directory.
+ *
+ * @param string $sourceDir The source directory where we need to look in
+ * @param string $targetDir The target directory where we need to copy the files too
+ * @param string $filename The name of the file that needs to be rendered
+ * @param array $parameters The parameters that will be passed to the templates
+ * @param bool $override Whether to override an existing file or not
+ */
+ public function renderSingleFile($sourceDir, $targetDir, $filename, array $parameters, $override = false)
+ {
+ // Make sure the source -and target dir contain a trailing slash
+ if (substr($sourceDir, -1) != "/") $sourceDir .= "/";
+ if (substr($targetDir, -1) != "/") $targetDir .= "/";
+
+ $this->setSkeletonDirs(array($sourceDir));
+
+ if (is_file($sourceDir.$filename)) {
+ // Check that we are allowed the overwrite the file if it already exists
+ if (!is_file($targetDir.$filename) || $override == true) {
+ $fileParts = explode('.', $filename);
+ if (end($fileParts) == 'twig') {
+ $this->renderTwigFile($filename, $targetDir.$filename, $parameters, $sourceDir);
+ } else {
+ $this->renderFile($filename, $targetDir.$filename, $parameters);
+ }
+ }
+ }
+ }
+
+ /**
* Copy all files in the source directory to the target directory.
*
* @param string $sourceDir The source directory where we need to look in
diff --git a/src/Kunstmaan/GeneratorBundle/Helper/CommandAssistant.php b/src/Kunstmaan/GeneratorBundle/Helper/CommandAssistant.php
index <HASH>..<HASH> 100644
--- a/src/Kunstmaan/GeneratorBundle/Helper/CommandAssistant.php
+++ b/src/Kunstmaan/GeneratorBundle/Helper/CommandAssistant.php
@@ -46,6 +46,14 @@ class CommandAssistant
}
/**
+ * @return OutputInterface
+ */
+ public function getOutput()
+ {
+ return $this->output;
+ }
+
+ /**
* @return DialogHelper
*/
private function getDialog()
|
added wrapper function to render a single file
|
Kunstmaan_KunstmaanBundlesCMS
|
train
|
016927192befb1d792aec5843f24bc7e22588f7e
|
diff --git a/pkg/workloads/cri.go b/pkg/workloads/cri.go
index <HASH>..<HASH> 100644
--- a/pkg/workloads/cri.go
+++ b/pkg/workloads/cri.go
@@ -52,7 +52,7 @@ func getGRPCCLient(ctx context.Context) (*grpc.ClientConn, error) {
c, cancel := context.WithTimeout(ctx, time.Duration(5*time.Second))
defer cancel()
- conn, err := grpc.DialContext(c, addr, grpc.WithDialer(dialer), grpc.WithInsecure())
+ conn, err := grpc.DialContext(c, addr, grpc.WithDialer(dialer), grpc.WithInsecure(), grpc.WithBackoffMaxDelay(15*time.Second))
if err != nil {
return nil, fmt.Errorf("failed to connect: %s", err)
}
@@ -353,7 +353,6 @@ func (c *criClient) workloadIDsList(ctx context.Context) ([]string, error) {
req := &criRuntime.ListPodSandboxRequest{}
resp, err := c.RuntimeServiceClient.ListPodSandbox(context.Background(), req)
if err != nil {
- log.WithError(err).Errorf("error1")
return nil, err
}
|
workloads: cri allow grpc reconnectivity after failure
|
cilium_cilium
|
train
|
233182fe2b5c76077a3197578aba49fd3fa830bc
|
diff --git a/test/integration/009_data_tests_test/test_data_tests.py b/test/integration/009_data_tests_test/test_data_tests.py
index <HASH>..<HASH> 100644
--- a/test/integration/009_data_tests_test/test_data_tests.py
+++ b/test/integration/009_data_tests_test/test_data_tests.py
@@ -43,7 +43,6 @@ class TestDataTests(DBTIntegrationTest):
self.run_dbt()
test_results = self.run_data_validations()
-
for result in test_results:
# assert that all deliberately failing tests actually fail
if 'fail' in result.model.name:
diff --git a/test/unit/test_graph.py b/test/unit/test_graph.py
index <HASH>..<HASH> 100644
--- a/test/unit/test_graph.py
+++ b/test/unit/test_graph.py
@@ -1,6 +1,9 @@
-from mock import MagicMock, patch, PropertyMock
+from mock import MagicMock
+import os
+import six
import unittest
+import dbt.compilation
import dbt.model
import dbt.project
import dbt.templates
@@ -8,8 +11,6 @@ import dbt.utils
import networkx as nx
-import dbt.compilation
-
from dbt.logger import GLOBAL_LOGGER as logger
class GraphTest(unittest.TestCase):
@@ -59,23 +60,40 @@ class GraphTest(unittest.TestCase):
dbt.utils.dependency_projects = MagicMock(return_value=[])
+ self.mock_models = []
+ self.mock_content = {}
+
+ def mock_find_matching(root_path, relative_paths_to_search,
+ file_pattern):
+ if not 'sql' in file_pattern:
+ return []
+
+ to_return = []
+
+ if 'models' in relative_paths_to_search:
+ to_return = to_return + self.mock_models
+
+ return to_return
- def use_models(self, models):
dbt.clients.system.find_matching = MagicMock(
- return_value=[{'searched_path': 'models',
- 'absolute_path': '/fake/models/{}.sql'.format(k),
- 'relative_path': '{}.sql'.format(k)}
- for k, v in models.items()])
+ side_effect=mock_find_matching)
def mock_load_file_contents(path):
- k = path.split('/')[-1].split('.')[0]
- return models[k]
+ return self.mock_content[path]
dbt.clients.system.load_file_contents = MagicMock(
side_effect=mock_load_file_contents)
-
- def test_single_model(self):
+ def use_models(self, models):
+ for k, v in models.items():
+ path = '/fake/models/{}.sql'.format(k)
+ self.mock_models.append({
+ 'searched_path': 'models',
+ 'absolute_path': os.path.abspath(path),
+ 'relative_path': '{}.sql'.format(k)})
+ self.mock_content[path] = v
+
+ def test__single_model(self):
self.use_models({
'model_one': 'select * from events',
})
@@ -89,7 +107,7 @@ class GraphTest(unittest.TestCase):
self.assertEquals(
self.graph_result.edges(), [])
- def test_two_models_simple_ref(self):
+ def test__two_models_simple_ref(self):
self.use_models({
'model_one': 'select * from events',
'model_two': "select * from {{ref('model_one')}}",
@@ -97,12 +115,12 @@ class GraphTest(unittest.TestCase):
self.compiler.compile(limit_to=['models'])
- self.assertEquals(
+ six.assertCountEqual(self,
self.graph_result.nodes(),
[('test_models_compile', 'model_one'),
('test_models_compile', 'model_two'),])
- self.assertEquals(
+ six.assertCountEqual(self,
self.graph_result.edges(),
[(('test_models_compile', 'model_one'),
('test_models_compile', 'model_two')),])
|
use six for py2/3 compat
|
fishtown-analytics_dbt
|
train
|
2531aad06f6ab6157e492ccffdd5e57f55011ad0
|
diff --git a/lib/pilot-gnuplot/plot.rb b/lib/pilot-gnuplot/plot.rb
index <HASH>..<HASH> 100644
--- a/lib/pilot-gnuplot/plot.rb
+++ b/lib/pilot-gnuplot/plot.rb
@@ -108,7 +108,7 @@ module Gnuplot
value = value[0] if value && value.size == 1
value
else
- Plot.new(@datasets, @options.merge(meth.to_sym => args))
+ self.class.new(@datasets, @options.merge(meth.to_sym => args))
end
end
end
@@ -141,7 +141,7 @@ module Gnuplot
# ==== Example
# TODO add examples (and specs!)
def replace_dataset(position = 0, dataset)
- Plot.new(@datasets.set(position, dataset), @options)
+ self.class.new(@datasets.set(position, dataset), @options)
end
##
@@ -153,7 +153,7 @@ module Gnuplot
# ==== Example
# TODO add examples (and specs!)
def add_dataset(dataset)
- Plot.new(@datasets.add(convert_to_dataset(dataset)), @options)
+ self.class.new(@datasets.add(convert_to_dataset(dataset)), @options)
end
alias_method :<<, :add_dataset
@@ -168,7 +168,7 @@ module Gnuplot
# ==== Example
# TODO add examples (and specs!)
def remove_dataset(position = -1)
- Plot.new(@datasets.delete_at(position), @options)
+ self.class.new(@datasets.delete_at(position), @options)
end
##
@@ -200,7 +200,7 @@ module Gnuplot
if options.empty?
@options
else
- Plot.new(@datasets, @options.merge(options))
+ self.class.new(@datasets, @options.merge(options))
end
end
|
replace Plot with self.class to make methods inheritable
|
dilcom_gnuplotrb
|
train
|
45c8658cfea62947aa7cdf8c51e708d4cba9ca04
|
diff --git a/lib/searchkick/results.rb b/lib/searchkick/results.rb
index <HASH>..<HASH> 100644
--- a/lib/searchkick/results.rb
+++ b/lib/searchkick/results.rb
@@ -26,17 +26,7 @@ module Searchkick
if options[:includes]
records = records.includes(options[:includes])
end
- results[type] =
- if records.respond_to?(:primary_key) and records.primary_key
- # ActiveRecord
- records.where(records.primary_key => grouped_hits.map{|hit| hit["_id"] }).to_a
- elsif records.respond_to?(:all) and records.all.respond_to?(:for_ids)
- # Mongoid 2
- records.all.for_ids(grouped_hits.map{|hit| hit["_id"] }).to_a
- else
- # Mongoid 3+
- records.queryable.for_ids(grouped_hits.map{|hit| hit["_id"] }).to_a
- end
+ results[type] = results_query(records, grouped_hits)
end
# sort
@@ -143,5 +133,25 @@ module Searchkick
@response["hits"]["hits"]
end
+ private
+
+ def results_query(records, grouped_hits)
+ if records.respond_to?(:primary_key) and records.primary_key
+ # ActiveRecord
+ records.where(records.primary_key => grouped_hits.map{|hit| hit["_id"] }).to_a
+ elsif records.respond_to?(:all) and records.all.respond_to?(:for_ids)
+ # Mongoid 2
+ records.all.for_ids(grouped_hits.map{|hit| hit["_id"] }).to_a
+ elsif records.respond_to?(:queryable)
+ # Mongoid 3+
+ records.queryable.for_ids(grouped_hits.map{|hit| hit["_id"] }).to_a
+ else
+ custom_query(records, grouped_hits)
+ end
+ end
+
+ def custom_query(records, grouped_hits)
+ raise 'Query method for records is unknown'
+ end
end
end
|
Separate DB query logic, make it easy to add custom behavior
|
ankane_searchkick
|
train
|
cf273f21bb4ec33673793f43e5164f31f76de5d3
|
diff --git a/pkg/labels/regexp_test.go b/pkg/labels/regexp_test.go
index <HASH>..<HASH> 100644
--- a/pkg/labels/regexp_test.go
+++ b/pkg/labels/regexp_test.go
@@ -83,6 +83,7 @@ func TestOptimizeConcatRegex(t *testing.T) {
{regex: ".*(?i:abc)def.*", prefix: "", suffix: "", contains: "def"},
{regex: "(?i).*(?-i:abc)def", prefix: "", suffix: "", contains: "abc"},
{regex: ".*(?msU:abc).*", prefix: "", suffix: "", contains: "abc"},
+ {regex: "[aA]bc.*", prefix: "", suffix: "", contains: "bc"},
}
for _, c := range cases {
|
Add a testcase for #<I> (#<I>)
This was already fixed by #<I>, but add a test case anyway
in case the regexp engine changes in future.
|
prometheus_prometheus
|
train
|
a565d226a7858df53f382f6eb954eb68da3fa687
|
diff --git a/nxviz/geometry.py b/nxviz/geometry.py
index <HASH>..<HASH> 100644
--- a/nxviz/geometry.py
+++ b/nxviz/geometry.py
@@ -13,7 +13,7 @@ def node_theta(nodelist, node):
assert node in nodelist, 'node must be inside nodelist.'
i = nodelist.index(node)
- theta = i*2*np.pi/len(nodelist)
+ theta = -np.pi + i*2*np.pi/len(nodelist)
if theta > np.pi:
theta = np.pi - theta
|
added bug fix for geometry. nodes are placed from -pi to +pi
|
ericmjl_nxviz
|
train
|
7fa94a9b2d3f206967be99833615c04520252f10
|
diff --git a/src/map/Map.Camera.js b/src/map/Map.Camera.js
index <HASH>..<HASH> 100644
--- a/src/map/Map.Camera.js
+++ b/src/map/Map.Camera.js
@@ -27,7 +27,7 @@ Map.include(/** @lends Map.prototype */{
fov = Math.max(0.01, Math.min(60, fov));
if (this._fov === fov) return this;
var from = this.getFov();
- this._fov = fov / RADIAN;
+ this._fov = fov * RADIAN;
this._calcMatrices();
this._renderLayers();
/*
diff --git a/test/map/MapCameraSpec.js b/test/map/MapCameraSpec.js
index <HASH>..<HASH> 100644
--- a/test/map/MapCameraSpec.js
+++ b/test/map/MapCameraSpec.js
@@ -31,6 +31,20 @@ describe('#Map.Camera', function () {
REMOVE_CONTAINER(container);
});
+ it('getter and setter', function () {
+ map.setBearing(60);
+ map.setPitch(40);
+ expect(map.getBearing()).to.be.approx(60);
+ expect(map.getPitch()).to.be.eql(40);
+
+ expect(map.getFov()).to.be.above(0);
+ map.setFov(60);
+ expect(map.getFov()).to.be.approx(60);
+ // max fov is 60
+ map.setFov(90);
+ expect(map.getFov()).to.be.approx(60);
+ });
+
describe('TileLayer\'s dom rendering', function () {
it('render after composite operations', function () {
map.setBearing(60);
@@ -41,7 +55,7 @@ describe('#Map.Camera', function () {
map.setPitch(0);
const tiles = map.getBaseLayer()._getRenderer()._tiles;
const pos = tiles['53162__108844__17'].pos;
- expect(pos.toArray()).to.be.eql([9373, -11414]);
+ expect(pos.toArray()).to.be.eql([52, -412]);
});
});
@@ -59,6 +73,13 @@ describe('#Map.Camera', function () {
});
map.setBearing(10);
});
+
+ it('should fire fovchange event', function (done) {
+ map.on('fovchange', function () {
+ done();
+ });
+ map.setFov(90);
+ });
});
describe('zoom', function () {
|
fix setFov and add specs
|
maptalks_maptalks.js
|
train
|
125e26dde5a55a849f6ce516824e1d3a7cc9e342
|
diff --git a/deploy/ray-operator/controllers/raycluster_controller.go b/deploy/ray-operator/controllers/raycluster_controller.go
index <HASH>..<HASH> 100644
--- a/deploy/ray-operator/controllers/raycluster_controller.go
+++ b/deploy/ray-operator/controllers/raycluster_controller.go
@@ -18,7 +18,6 @@ import (
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
- "sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
@@ -29,45 +28,14 @@ import (
var log = logf.Log.WithName("RayCluster-Controller")
-// Add creates a new RayCluster Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller
-// and start it when the Manager Started.
-func Add(mgr manager.Manager) error {
- return add(mgr, newReconciler(mgr))
-}
-
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
return &RayClusterReconciler{Client: mgr.GetClient(), Scheme: mgr.GetScheme()}
}
-// add creates a new Controller to mgr with r as the reconcile.Reconciler
-func add(mgr manager.Manager, r reconcile.Reconciler) error {
- // Create a new controller
- c, err := controller.New("ray-operator-RayCluster-controller", mgr, controller.Options{Reconciler: r})
- if err != nil {
- return err
- }
-
- // Watch for changes to RayCluster
- err = c.Watch(&source.Kind{Type: &rayiov1alpha1.RayCluster{}}, &handler.EnqueueRequestForObject{})
- if err != nil {
- return err
- }
-
- err = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{
- IsController: true,
- OwnerType: &rayiov1alpha1.RayCluster{},
- })
- if err != nil {
- return err
- }
-
- return nil
-}
-
var _ reconcile.Reconciler = &RayClusterReconciler{}
-// ReconcileRayCluster reconciles a RayCluster object
+// RayClusterReconciler reconciles a RayCluster object
type RayClusterReconciler struct {
client.Client
Log logr.Logger
@@ -237,9 +205,14 @@ func (r *RayClusterReconciler) buildPods(instance *rayiov1alpha1.RayCluster) []c
return pods
}
+// SetupWithManager builds the reconciler.
func (r *RayClusterReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&rayiov1alpha1.RayCluster{}).
+ Watches(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{
+ IsController: true,
+ OwnerType: &rayiov1alpha1.RayCluster{},
+ }).
Complete(r)
}
|
[ray-operator] Watch the pod resource and remove useless code (#<I>)
|
ray-project_ray
|
train
|
3c426b1f998dfd1d4a630ed8a686abe5b1830634
|
diff --git a/lib/memory_store.js b/lib/memory_store.js
index <HASH>..<HASH> 100644
--- a/lib/memory_store.js
+++ b/lib/memory_store.js
@@ -15,8 +15,8 @@ MemoryStore.prototype.read = function(key, generate, cb) {
else if (generate != null) {
generate(function(err, result){
- if (err == null) { return cb(err); }
- this.data[key] = result;
+ if (err) { return cb(err); }
+ self.data[key] = result;
return cb(null, result)
})
}
@@ -37,7 +37,7 @@ MemoryStore.prototype.exists = function(key, cb) {
cb(null, _.has(this.data, key))
}
-MemoryStore.prototype.clear = function(key, cb) {
+MemoryStore.prototype.clear = function( cb) {
delete this.data;
this.data = {};
if (typeof cb !== 'undefined') { return cb(null); }
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -4,6 +4,7 @@ var _ = require('underscore');
var MemoryStore = require('../lib/memory_store');
describe('MemoryStore', function(){
+ var memory_store = new MemoryStore();
describe('#init', function(){
it('should create an empty store by default', function() {
var memory_store = new MemoryStore();
@@ -11,20 +12,50 @@ describe('MemoryStore', function(){
});
});
describe('#get', function() {
- var memory_store = new MemoryStore();
-
- it('should return null when no data exists for key', function(done) {
+ it('should return null when no data exists for key', function() {
memory_store.read('test-key', function(err, value) {
- console.log(arguments);
if (err) throw err;
- value.should.equal(null);
+ should.not.exist(value);
})
});
- it('should write values into the store when passed a generator', function(done) {
+ it('should write values into the store when passed a generator', function() {
memory_store.read('test-key', function(cb){ cb(null, 'value')}, function(err, value) {
if (err) return done(err);
- done(null, (value == 'value'));
+ value.should.equal('value');
+ });
+ });
+ });
+ describe('#remove', function() {
+ it('should remove values when given key', function() {
+ memory_store.remove('test-key', function(){
+ memory_store.read('test-key', function(err, value){
+ should.not.exist(value)
+ });
+ });
+ });
+ });
+ describe('#write', function(){
+ it('should write values for given key', function(done){
+ memory_store.write('key', 'value', done);
+ })
+ });
+ describe('#exists', function(){
+ it('should return true for existing values', function() {
+ memory_store.exists('key', function(err, result) {
+ result.should.equal(true);
+ });
+ });
+ it('should return false for missing values', function(){
+ memory_store.exists('missing-key', function(err, result) {
+ result.should.equal(false);
+ });
+ });
+ });
+ describe('#clear', function(){
+ it('should empty the store of all values', function() {
+ memory_store.clear(function(){
+ _.keys(memory_store.data).length.should.equal(0);
});
});
});
|
Added testing for the memory_store
Now to make it generic and able to be passed any type of store
|
patrickod_thoroughfare
|
train
|
7d1f55cf49b1005592d6eaad27cab4c8d7f4c2ad
|
diff --git a/pyvisa-sim/parser.py b/pyvisa-sim/parser.py
index <HASH>..<HASH> 100644
--- a/pyvisa-sim/parser.py
+++ b/pyvisa-sim/parser.py
@@ -111,20 +111,20 @@ def get_devices(filename, is_resource):
device_name = resource_dict['device']
new_filename = resource_dict.get('filename', None)
- new_is_resource = resource_dict.get('is_resource', False)
+ new_bundled = resource_dict.get('bundled', False)
if new_filename:
# If the device definition should be loaded from another file
if new_filename not in devices_in_file:
- if new_is_resource:
+ if new_bundled:
new_data = parse_resource(new_filename)
else:
path = os.path.dirname(filename)
new_data = parse_file(os.path.join(path, os.path.normpath(new_filename)))
- devices_in_file[(new_filename, is_resource)] = new_data['devices']
+ devices_in_file[(new_filename, new_bundled)] = new_data['devices']
- device_dict = devices_in_file[(new_filename, is_resource)][device_name]
+ device_dict = devices_in_file[(new_filename, new_bundled)][device_name]
else:
device_dict = data['devices'][device_name]
|
Renamed is_resource to bundled in yaml files
|
pyvisa_pyvisa-sim
|
train
|
ee9cef59b7dcd5d2e3a3d16a8d127c31d1178b91
|
diff --git a/packages/local-cli/link/__fixtures__/android/patchedBuild.gradle b/packages/local-cli/link/__fixtures__/android/patchedBuild.gradle
index <HASH>..<HASH> 100644
--- a/packages/local-cli/link/__fixtures__/android/patchedBuild.gradle
+++ b/packages/local-cli/link/__fixtures__/android/patchedBuild.gradle
@@ -21,6 +21,10 @@ implementationAbc project(':test-impl-abc')
compileDebug project(':test-compile-debug')
compileAbc project(':test-compile-abc')
+ api project(':test-api')
+ apiDebug project(':test-api-debug')
+ apiAbc project(':test-api-abc')
+
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-v7:27.1.1"
implementation "com.facebook.react:react-native:+"
diff --git a/packages/local-cli/link/__tests__/android/isInstalled-test.js b/packages/local-cli/link/__tests__/android/isInstalled-test.js
index <HASH>..<HASH> 100644
--- a/packages/local-cli/link/__tests__/android/isInstalled-test.js
+++ b/packages/local-cli/link/__tests__/android/isInstalled-test.js
@@ -28,6 +28,9 @@ describe('android::isInstalled', () => {
['test-compile', true],
['test-compile-debug', true],
['test-compile-abc', true],
+ ['test-api', true],
+ ['test-api-debug', true],
+ ['test-api-abc', true],
['test-not-there-yet', false],
])(
'properly detects if %p project is already in build.gradle',
diff --git a/packages/local-cli/link/android/patches/makeBuildPatch.js b/packages/local-cli/link/android/patches/makeBuildPatch.js
index <HASH>..<HASH> 100644
--- a/packages/local-cli/link/android/patches/makeBuildPatch.js
+++ b/packages/local-cli/link/android/patches/makeBuildPatch.js
@@ -12,7 +12,7 @@ const normalizeProjectName = require('./normalizeProjectName');
module.exports = function makeBuildPatch(name) {
const normalizedProjectName = normalizeProjectName(name);
const installPattern = new RegExp(
- `(implementation|compile)\\w*\\s*\\(*project\\(['"]:${normalizedProjectName}['"]\\)`
+ `(implementation|api|compile)\\w*\\s*\\(*project\\(['"]:${normalizedProjectName}['"]\\)`
);
return {
|
fix: make link understand 'api project' (#<I>)
|
react-native-community_cli
|
train
|
01e57d918ec6d6110e9ca7879499e6c02b4f0159
|
diff --git a/core/edb/src/main/java/org/openengsb/core/edb/internal/JPAObject.java b/core/edb/src/main/java/org/openengsb/core/edb/internal/JPAObject.java
index <HASH>..<HASH> 100644
--- a/core/edb/src/main/java/org/openengsb/core/edb/internal/JPAObject.java
+++ b/core/edb/src/main/java/org/openengsb/core/edb/internal/JPAObject.java
@@ -34,18 +34,22 @@ import javax.persistence.OneToMany;
import org.openengsb.core.api.edb.EDBObject;
@Entity
+/**
+ * this defines a jpa object in the database. The correlation to the EDBObject is that
+ * the JPAObject can be converted to an EDBObject.
+ */
public class JPAObject {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "jpaobject_id")
private Long id;
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ private List<KeyValuePair> values;
+
private Long timestamp;
private Boolean isDeleted;
private String uid;
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
- private List<KeyValuePair> values;
-
public JPAObject() {
isDeleted = false;
}
|
[OPENENGSB-<I>] added javadoc to the JPAObject class
|
openengsb_openengsb
|
train
|
0d85bf3420c5bdbb10f19954eea945ef1dc2b878
|
diff --git a/lib/schema.js b/lib/schema.js
index <HASH>..<HASH> 100644
--- a/lib/schema.js
+++ b/lib/schema.js
@@ -42,8 +42,8 @@ var getSchema = function() {
schema[AccessToken.type] = AccessToken.schema;
for (i = 0; i < ActivityObject.objectTypes.length; i++) {
- type = Activity.objectTypes[i];
- Cls = Activity.toClass(type);
+ type = ActivityObject.objectTypes[i];
+ Cls = ActivityObject.toClass(type);
if (Cls.schema) {
schema[type] = Cls.schema;
} else {
|
Still more moving Activity. to ActivityObject.
|
pump-io_pump.io
|
train
|
467c665066ccaab2df4c6811937d2664269d1479
|
diff --git a/src/MetarDecoder/MetarDecoder.php b/src/MetarDecoder/MetarDecoder.php
index <HASH>..<HASH> 100644
--- a/src/MetarDecoder/MetarDecoder.php
+++ b/src/MetarDecoder/MetarDecoder.php
@@ -60,10 +60,22 @@ class MetarDecoder
// prepare new remaining metar for next round
$remaining_metar = $decoded['remaining_metar'];
+
+ // hook for report status decoder, abort if nil, but decoded metar is valid though
+ if ($chunk_decoder instanceof ReportStatusChunkDecoder) {
+ if($decoded_metar->getStatus() == 'NIL' ){
+ break;
+ }
+ }
+
+ // hook for CAVOK decoder
+ // TODO
+
}
return $decoded_metar;
}
+
}
diff --git a/src/MetarDecoder/Service/ReportStatusChunkDecoder.php b/src/MetarDecoder/Service/ReportStatusChunkDecoder.php
index <HASH>..<HASH> 100644
--- a/src/MetarDecoder/Service/ReportStatusChunkDecoder.php
+++ b/src/MetarDecoder/Service/ReportStatusChunkDecoder.php
@@ -2,6 +2,8 @@
namespace MetarDecoder\Service;
+use MetarDecoder\Exception\ChunkDecoderException;
+
/**
* Chunk decoder for report statuc section (NIL or AUTO)
*/
@@ -25,11 +27,19 @@ class ReportStatusChunkDecoder extends MetarChunkDecoder implements MetarChunkDe
'status' => $found[1]
);
}
+ $next_remaining_metar = $this->getRemainingMetar($remaining_metar);
+
+ // in the case where status is NIL, check that there is nothing left in the remaining metar
+ if($result != null && $result['status'] == 'NIL' ){
+ if(strlen(trim($next_remaining_metar)) > 0){
+ throw new ChunkDecoderException($remaining_metar, 'No information expected after NIL status', $this);
+ }
+ }
// return result + remaining metar
return array(
'result' => $result,
- 'remaining_metar' => $this->getRemainingMetar($remaining_metar)
+ 'remaining_metar' => $next_remaining_metar
);
}
}
diff --git a/tests/MetarDecoder/MetarDecoderTest.php b/tests/MetarDecoder/MetarDecoderTest.php
index <HASH>..<HASH> 100644
--- a/tests/MetarDecoder/MetarDecoderTest.php
+++ b/tests/MetarDecoder/MetarDecoderTest.php
@@ -25,7 +25,7 @@ class MetarDecoderTest extends PHPUnit_Framework_TestCase
{
// TODO build a big dataset for successful decoding
- // launch decoder
+ // launch decoding for a valid metar
$d = $this->decoder->parse('METAR LFPO 231027Z AUTO blabla');
// compare results
@@ -36,19 +36,33 @@ class MetarDecoderTest extends PHPUnit_Framework_TestCase
$this->assertEquals('AUTO', $d->getStatus());
}
+ public function testParseNil()
+ {
+ // empty metar, valid
+ $d = $this->decoder->parse('METAR LFPO 231027Z NIL');
+ $this->assertEquals('NIL', $d->getStatus());
+
+ }
+
public function testParseErrors()
{
- // TODO build a big dataset for decoding errors
- // launch decoder that should hit an error
- $raw_metar = 'LFPG aaa bbb cccc';
- $d = $this->decoder->parse($raw_metar);
+ $error_dataset = array(
+ array('LFPG aaa bbb cccc', 'DatetimeChunkDecoder', 'AAA BBB CCCC '),
+ array('METAR LFPO 231027Z NIL 1234', 'ReportStatusChunkDecoder', 'NIL 1234 ')
+ );
- // check the error triggered
- $this->assertFalse($d->isValid());
- $error = $d->getException();
- $this->assertEquals('AAA BBB CCCC ', $error->getChunk());
- $this->assertEquals('MetarDecoder\Service\DatetimeChunkDecoder', $error->getChunkDecoder())
-; }
+ foreach($error_dataset as $metar_error){
+ // launch decoding
+ $d = $this->decoder->parse($metar_error[0]);
+
+ // check the error triggered
+ $this->assertFalse($d->isValid());
+ $error = $d->getException();
+ $this->assertEquals('MetarDecoder\Service\\'.$metar_error[1], $error->getChunkDecoder());
+ $this->assertEquals($metar_error[2], $error->getChunk());
+ }
+
+ }
}
diff --git a/tests/MetarDecoder/Service/ReportStatusChunkDecoderTest.php b/tests/MetarDecoder/Service/ReportStatusChunkDecoderTest.php
index <HASH>..<HASH> 100644
--- a/tests/MetarDecoder/Service/ReportStatusChunkDecoderTest.php
+++ b/tests/MetarDecoder/Service/ReportStatusChunkDecoderTest.php
@@ -15,7 +15,7 @@ class ReportStatusChunkDecoderTest extends PHPUnit_Framework_TestCase
public function testParse()
{
$dataset = array(
- 'NIL AAA' => array(array('status' => 'NIL'),'AAA'),
+ 'NIL ' => array(array('status' => 'NIL'),''),
'AUTO AAA' => array(array('status' => 'AUTO'),'AAA')
);
|
Abort decoding if NIL status but check that there is nothing after
|
SafranCassiopee_php-metar-decoder
|
train
|
20bea486bb920e699bdd48f890045231dd2744a7
|
diff --git a/daemons/message/__init__.py b/daemons/message/__init__.py
index <HASH>..<HASH> 100644
--- a/daemons/message/__init__.py
+++ b/daemons/message/__init__.py
@@ -23,7 +23,7 @@ class MessageDaemon(Daemon):
# This alias for sleep is placed here to allow extensions to change the
# idle behaviour of the loop without monkey patching the time library.
- sleep = time.sleep
+ sleep = staticmethod(time.sleep)
def __init__(self, pidfile, idle_time=0.1):
|
Fix: Missing staticmethod decorator for time.sleep
|
kevinconway_daemons
|
train
|
108cb5d529f134101796cc667df9795e76762e19
|
diff --git a/Rakefile b/Rakefile
index <HASH>..<HASH> 100644
--- a/Rakefile
+++ b/Rakefile
@@ -2,6 +2,6 @@ require 'rake/testtask'
Rake::TestTask.new do |t|
t.libs << 'lib' << 'test'
- t.test_files = FileList['test/**/*_test.rb']
+ t.test_files = FileList['test/*_test.rb']
t.verbose = true
end
diff --git a/lib/dynflow/action.rb b/lib/dynflow/action.rb
index <HASH>..<HASH> 100644
--- a/lib/dynflow/action.rb
+++ b/lib/dynflow/action.rb
@@ -72,7 +72,7 @@ module Dynflow
end
def self.trigger(*args)
- Dynflow::Bus.trigger(self.plan(*args))
+ Dynflow::Bus.trigger(self, *args)
end
def self.plan(*args)
diff --git a/lib/dynflow/bus.rb b/lib/dynflow/bus.rb
index <HASH>..<HASH> 100644
--- a/lib/dynflow/bus.rb
+++ b/lib/dynflow/bus.rb
@@ -42,7 +42,8 @@ module Dynflow
super
end
- def trigger(execution_plan)
+ def trigger(action_class, *args)
+ execution_plan = action_class.plan(*args)
outputs = []
execution_plan.actions.each do |action|
outputs << self.process(action)
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -48,6 +48,17 @@ class TestScenarioFinalizer < Dynflow::Action
end
+class MockedAction
+
+ def initialize(mocked_execution_plan)
+ @mocked_execution_plan = mocked_execution_plan
+ end
+
+ def plan
+ @mocked_execution_plan
+ end
+end
+
class BusTestCase < Test::Unit::TestCase
def setup
@@ -64,7 +75,8 @@ class BusTestCase < Test::Unit::TestCase
TestScenarioFinalizer.init_recorded_outputs
execution_plan = self.execution_plan
execution_plan << TestScenarioFinalizer.new({})
- Dynflow::Bus.trigger(execution_plan)
+
+ Dynflow::Bus.trigger(MockedAction.new(execution_plan))
return TestScenarioFinalizer.recorded_outputs
end
end
|
Construct the execution plan in side the Bus.trigger method
Allows us encapsulating the planning into transaction
|
Dynflow_dynflow
|
train
|
70de9d8f2a1212529f65f6647103695034f42311
|
diff --git a/sdk/src/classes.js b/sdk/src/classes.js
index <HASH>..<HASH> 100644
--- a/sdk/src/classes.js
+++ b/sdk/src/classes.js
@@ -4,8 +4,8 @@
*/
F2.extend('', {
/**
- * The App Class is an optional class that can be namespaced onto the
- * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
+ * The App Class is an optional class that can be namespaced onto the
+ * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
* [F2 Docs](../../app-development.html#app-class)
* has more information on the usage of the App Class.
* @class F2.App
@@ -77,9 +77,9 @@ F2.extend('', {
*/
instanceId: '',
/**
- * The language and region specification for this container
+ * The language and region specification for this container
* represented as an IETF-defined standard language tag,
- * e.g. `"en-us"` or `"de-de"`. This is passed during the
+ * e.g. `"en-us"` or `"de-de"`. This is passed during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process.
*
* @property containerLocale
@@ -91,7 +91,7 @@ F2.extend('', {
/**
* The languages and regions supported by this app represented
* as an array of IETF-defined standard language tags,
- * e.g. `["en-us","de-de"]`.
+ * e.g. `["en-us","de-de"]`.
*
* @property localeSupport
* @type array
@@ -220,7 +220,7 @@ F2.extend('', {
* [container](../../container-development.html)
* @class F2.ContainerConfig
*/
- ContainerConfig: {
+ ContainerConfig: {
/**
* True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc.
* @property debugMode
@@ -229,7 +229,7 @@ F2.extend('', {
*/
debugMode: false,
/**
- * The default language and region specification for this container
+ * The default language and region specification for this container
* represented as an IETF-defined standard language tag,
* e.g. `"en-us"` or `"de-de"`. This value is passed to each app
* registered as `containerLocale`.
@@ -250,7 +250,7 @@ F2.extend('', {
/**
* Allows the container to fully override how the AppManifest request is
* made inside of F2.
- *
+ *
* @method xhr
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
@@ -260,9 +260,7 @@ F2.extend('', {
* @param {function} error The function to be called if the request fails
* @param {function} complete The function to be called when the request
* finishes (after success and error callbacks have been executed)
- * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has
- * an `abort` function (such as the jqXHR object in jQuery) to abort the
- * request)
+ * @return {XMLHttpRequest} The XMLHttpRequest object
*
* @example
* F2.init({
@@ -313,8 +311,7 @@ F2.extend('', {
*/
dataType: function(url, appConfigs) {},
/**
- * Allows the container to override the request method that is used (just
- * like the `type` parameter to `jQuery.ajax()`.
+ * Allows the container to override the request method that is used.
* @method xhr.type
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
diff --git a/sdk/src/container.js b/sdk/src/container.js
index <HASH>..<HASH> 100644
--- a/sdk/src/container.js
+++ b/sdk/src/container.js
@@ -880,13 +880,6 @@ F2.extend('', (function() {
F2.log('AppConfig instance:', a);
throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.');
}
- // @Brian ? TODO: if we accept only explicit DOM references, do we still need this?
- //else if (jQuery(a.root).length != 1) {
- // F2.log('AppConfig invalid for pre-load, root not unique');
- // F2.log('AppConfig instance:', a);
- // F2.log('Number of dom node instances:', jQuery(a.root).length);
- // throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.');
- //}
// instantiate F2.App
_createAppInstance(a, {
@@ -1020,9 +1013,9 @@ F2.extend('', (function() {
throw ('Browser does not support the Fetch API.');
}
- var fetchFunc,
+ var fetchFunc,
fetchUrl = url + '?params=' + F2.stringify(req.apps, F2.appConfigReplacer);
-
+
// Fetch API does not support the JSONP calls so making JSON calls using Fetch API and
// JSONP call using fetch-jsonp package (https://www.npmjs.com/package/fetch-jsonp)
if (dataType === 'json') {
@@ -1043,7 +1036,7 @@ F2.extend('', (function() {
fetchFunc = fetchJsonp(fetchUrl, {
timeout: 3000,
jsonpCallbackFunction: jsonpCallback
- });
+ });
}
fetchFunc.then(function(response) {
@@ -1051,7 +1044,7 @@ F2.extend('', (function() {
})
.then(function(data) {
successCallback(data);
- completeCallback();
+ completeCallback();
})
.catch(function(error) {
F2.log('Failed to load app(s)', error.toString(), req.apps);
|
fix: remove some remaining references to jQuery and whitespace
|
OpenF2_F2
|
train
|
de571145b571973c4dff3a37d4a20af5e7e83d3b
|
diff --git a/examples/the-high-street/initialize.py b/examples/the-high-street/initialize.py
index <HASH>..<HASH> 100755
--- a/examples/the-high-street/initialize.py
+++ b/examples/the-high-street/initialize.py
@@ -3,7 +3,7 @@
import random
import logging
-from figment import Entity, Zone, log, ExploreMode
+from figment import Entity, Zone, log, ActionMode
from components import *
log.setLevel(logging.DEBUG)
@@ -27,7 +27,7 @@ if __name__ == '__main__':
Wandering(wanderlust=0.03, destinations=destinations)
],
zone=zone,
- mode=ExploreMode(),
+ mode=ActionMode(),
)
room_.Position.store(pigeon)
@@ -40,7 +40,7 @@ if __name__ == '__main__':
[Position(is_container=True), Emotes()],
zone=zone,
hearing=True,
- mode=ExploreMode()
+ mode=ActionMode()
)
##### Ground level
@@ -264,7 +264,7 @@ if __name__ == '__main__':
'...',
[Position(), Emotes(), ShoosPests(direction='south')],
zone=zone,
- mode=ExploreMode(),
+ mode=ActionMode(),
)
gift_shop.Position.store(gift_shop_manager)
diff --git a/figment/__init__.py b/figment/__init__.py
index <HASH>..<HASH> 100644
--- a/figment/__init__.py
+++ b/figment/__init__.py
@@ -2,4 +2,4 @@ from figment.logger import log
from figment.entity import Entity
from figment.component import Component, action, before, after
from figment.zone import Zone
-from figment.modes import ExploreMode, DebugMode
+from figment.modes import ActionMode, DebugMode
diff --git a/figment/entity.py b/figment/entity.py
index <HASH>..<HASH> 100644
--- a/figment/entity.py
+++ b/figment/entity.py
@@ -205,5 +205,5 @@ class Entity(object):
from figment.utils import upper_first
-from figment.modes import Mode, ExploreMode
+from figment.modes import Mode
from figment.component import Component
diff --git a/figment/modes.py b/figment/modes.py
index <HASH>..<HASH> 100644
--- a/figment/modes.py
+++ b/figment/modes.py
@@ -36,7 +36,7 @@ class Mode(object):
raise NotImplementedError
-class ExploreMode(Mode):
+class ActionMode(Mode):
def perform(self, entity, command_or_action, **kwargs):
event = None
action = None
@@ -93,7 +93,7 @@ class DebugMode(Mode):
def perform(self, entity, command):
if command == 'stop':
entity.tell('OK.')
- entity.mode = ExploreMode()
+ entity.mode = ActionMode()
else:
self.num_commands += 1
entity.tell('You said: {} ({})'.format(command, self.num_commands))
diff --git a/tests/test_entity.py b/tests/test_entity.py
index <HASH>..<HASH> 100644
--- a/tests/test_entity.py
+++ b/tests/test_entity.py
@@ -1,4 +1,4 @@
-from figment import Entity, Zone, ExploreMode
+from figment import Entity, Zone, ActionMode
from tests.helpers import tell, saw, Visible, Colorful, BlackHole
@@ -12,7 +12,7 @@ class TestEntity(object):
self.zone = z = Zone()
self.player = Entity(
'Player', 'A player stands here.', [Visible()], zone=z,
- mode=ExploreMode()
+ mode=ActionMode()
)
self.ball = Entity('a ball', 'A round rubber ball.', [
Visible(), Colorful(color='red')
|
Rename ExploreMode to ActionMode
|
vreon_figment
|
train
|
8fa88d0e187d54e270e0b1fa89e5cf87f1915ad8
|
diff --git a/docroot/modules/custom/mindbody_cache_proxy/mindbody_cache_proxy.services.yml b/docroot/modules/custom/mindbody_cache_proxy/mindbody_cache_proxy.services.yml
index <HASH>..<HASH> 100644
--- a/docroot/modules/custom/mindbody_cache_proxy/mindbody_cache_proxy.services.yml
+++ b/docroot/modules/custom/mindbody_cache_proxy/mindbody_cache_proxy.services.yml
@@ -10,3 +10,4 @@ services:
- '@state'
- '@mindbody_cache_proxy.manager'
- '@config.factory'
+ - '@http_client'
diff --git a/docroot/modules/custom/mindbody_cache_proxy/src/Controller/MindBodyEndPointController.php b/docroot/modules/custom/mindbody_cache_proxy/src/Controller/MindBodyEndPointController.php
index <HASH>..<HASH> 100644
--- a/docroot/modules/custom/mindbody_cache_proxy/src/Controller/MindBodyEndPointController.php
+++ b/docroot/modules/custom/mindbody_cache_proxy/src/Controller/MindBodyEndPointController.php
@@ -15,8 +15,19 @@ use Symfony\Component\HttpFoundation\RequestStack;
*/
class MindBodyEndPointController extends ControllerBase {
+ /**
+ * Request stack.
+ *
+ * @var \Symfony\Component\HttpFoundation\RequestStack
+ */
protected $requestStack;
+ /**
+ * MindBodyEndPointController constructor.
+ *
+ * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
+ * Request stack.
+ */
public function __construct(RequestStack $requestStack) {
$this->requestStack = $requestStack;
}
diff --git a/docroot/modules/custom/mindbody_cache_proxy/src/MindbodyCacheProxy.php b/docroot/modules/custom/mindbody_cache_proxy/src/MindbodyCacheProxy.php
index <HASH>..<HASH> 100644
--- a/docroot/modules/custom/mindbody_cache_proxy/src/MindbodyCacheProxy.php
+++ b/docroot/modules/custom/mindbody_cache_proxy/src/MindbodyCacheProxy.php
@@ -8,6 +8,7 @@ use Drupal\Core\Url;
use Drupal\mindbody\MindbodyClientInterface;
use Drupal\mindbody_cache_proxy\Entity\MindbodyCache;
use Drupal\Core\Entity\Query\QueryFactory;
+use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
/**
@@ -58,6 +59,13 @@ class MindbodyCacheProxy implements MindbodyCacheProxyInterface {
protected $configFactory;
/**
+ * Http client.
+ *
+ * @var \GuzzleHttp\Client
+ */
+ protected $httpClient;
+
+ /**
* MindbodyProxy constructor.
*
* @param MindbodyClientInterface $mindbody_client
@@ -71,19 +79,19 @@ class MindbodyCacheProxy implements MindbodyCacheProxyInterface {
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* Config factory.
*/
- public function __construct(MindbodyClientInterface $mindbody_client, QueryFactory $query_factory, State $state, MindbodyCacheProxyManagerInterface $manager, ConfigFactoryInterface $configFactory) {
+ public function __construct(MindbodyClientInterface $mindbody_client, QueryFactory $query_factory, State $state, MindbodyCacheProxyManagerInterface $manager, ConfigFactoryInterface $configFactory, Client $httpClient) {
$this->mindbodyClient = $mindbody_client;
$this->queryFactory = $query_factory;
$this->state = $state;
$this->manager = $manager;
$this->configFactory = $configFactory;
+ $this->httpClient = $httpClient;
}
/**
* {@inheritdoc}
*/
public function call($service, $endpoint, array $params = [], $cache = TRUE) {
-
$params_str = '';
if ($cache) {
|
[YPTF-<I>] Fix minor issues with code and style
|
ymcatwincities_openy
|
train
|
c32e281f462622d7fb098c76dd0ee5d67604e7fa
|
diff --git a/lib/json-schema/validator.rb b/lib/json-schema/validator.rb
index <HASH>..<HASH> 100644
--- a/lib/json-schema/validator.rb
+++ b/lib/json-schema/validator.rb
@@ -73,7 +73,7 @@ module JSON
def schema_from_fragment(base_schema, fragment)
schema_uri = base_schema.uri
- fragments = fragment.split("/")
+ fragments = fragment.split("/").map { |f| f.gsub('~0', '~').gsub('~1', '/') }
# ensure the first element was a hash, per the fragment spec
if fragments.shift != "#"
diff --git a/test/fragment_resolution_test.rb b/test/fragment_resolution_test.rb
index <HASH>..<HASH> 100644
--- a/test/fragment_resolution_test.rb
+++ b/test/fragment_resolution_test.rb
@@ -80,4 +80,21 @@ class FragmentResolutionTest < Minitest::Test
assert_valid schema, 5, :fragment => "#/properties/a/anyOf/0"
refute_valid schema, 5, :fragment => "#/properties/a/anyOf/1"
end
+
+ def test_fragment_with_escape_sequences_resolution
+ schema = {
+ "content" => {
+ "application/json" => {
+ "type" => "object",
+ "required" => ["a"],
+ "properties" => {
+ "a" => {"type" => "integer"}
+ }
+ }
+ }
+ }
+
+ assert_valid schema, {"a" => 1}, :fragment => "#/content/application~1json"
+ refute_valid schema, {}, :fragment => "#/content/application~1json"
+ end
end
|
Allow resolution of fragments with escaped parts
|
ruby-json-schema_json-schema
|
train
|
806272594fe18ebf5c29c8ffdefca3573bdb1c2c
|
diff --git a/src/frontend/org/voltdb/dtxn/WorkUnit.java b/src/frontend/org/voltdb/dtxn/WorkUnit.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/dtxn/WorkUnit.java
+++ b/src/frontend/org/voltdb/dtxn/WorkUnit.java
@@ -22,6 +22,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import java.util.TreeMap;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
@@ -44,7 +45,8 @@ class WorkUnit
{
class DependencyTracker
{
- HashMap<Integer, VoltTable> m_results;
+ // needs to be a TreeMap so iterator has deterministic order
+ TreeMap<Integer, VoltTable> m_results;
int m_depId;
int m_expectedDeps;
HashSet<Integer> m_expectedSites;
@@ -53,7 +55,7 @@ class WorkUnit
HashSet<Integer> expectedSites)
{
m_depId = depId;
- m_results = new HashMap<Integer, VoltTable>();
+ m_results = new TreeMap<Integer, VoltTable>();
m_expectedDeps = expectedDeps;
m_expectedSites = expectedSites;
}
|
ENG-<I>: Force intermediate results to be fed from Send->Recieve in deterministic order.
Applies to MP txns.
|
VoltDB_voltdb
|
train
|
6ac0c3fa6b52b9674a3d3b0a30deac8684d8db0c
|
diff --git a/input/Value.php b/input/Value.php
index <HASH>..<HASH> 100644
--- a/input/Value.php
+++ b/input/Value.php
@@ -6,11 +6,11 @@ use nyx\core;
/**
* Input Parameter Value Definition
*
- * @package Nyx\Console\Input
+ * @package Nyx\Console
* @version 0.1.0
* @author Michal Chojnacki <m.chojnacki@muyo.io>
- * @copyright 2012-2016 Nyx Dev Team
- * @link http://docs.muyo.io/nyx/console/index.html
+ * @copyright 2012-2017 Nyx Dev Team
+ * @link https://github.com/unyx/nyx
* @todo The "valid" type which will pass through a validator callable, including custom error messages.
*/
class Value
@@ -85,15 +85,15 @@ class Value
* Sets the default value.
*
* @param mixed $default The default value.
- * @throws \LogicException When an incorrect default value is given.
+ * @return $this
+ * @throws \LogicException When an invalid default value is given.
*/
- public function setDefault($default = null)
+ public function setDefault($default = null) : Value
{
- if ($default !== null && !$this->type->is(Value::OPTIONAL)) {
+ if (isset($default) && !$this->type->is(Value::OPTIONAL)) {
throw new \LogicException("Cannot set a default value for non-optional values.");
}
- // If it's null, let potential child classes set the default by simply setting a property's value.
- $this->default = $default ?: $this->default;
+ $this->default = $default;
}
}
diff --git a/input/values/Multiple.php b/input/values/Multiple.php
index <HASH>..<HASH> 100644
--- a/input/values/Multiple.php
+++ b/input/values/Multiple.php
@@ -6,11 +6,11 @@ use nyx\console\input;
/**
* Input Parameter Multiple Values Definition
*
- * @package Nyx\Console\Input
+ * @package Nyx\Console
* @version 0.1.0
* @author Michal Chojnacki <m.chojnacki@muyo.io>
- * @copyright 2012-2016 Nyx Dev Team
- * @link http://docs.muyo.io/nyx/console/index.html
+ * @copyright 2012-2017 Nyx Dev Team
+ * @link https://github.com/unyx/nyx
*/
class Multiple extends input\Value
{
@@ -19,13 +19,13 @@ class Multiple extends input\Value
*
* @throws \LogicException When the given $default value is not an array.
*/
- public function setDefault($default = null)
+ public function setDefault($default = null) : input\Value
{
// Allow null, but otherwise require an array (with preferably actual default values).
- if (null !== $default && !is_array($default)) {
+ if (isset($default) && !is_array($default)) {
throw new \LogicException("The default value for an argument accepting multiple values must be an array.");
}
- parent::setDefault($default);
+ return parent::setDefault($default);
}
}
|
[Console] Get rid of the weird (and bugged) automagic in input\Value::setDefault() in favour of forcing children to go through the validation.
|
unyx_console
|
train
|
56f08239f2ece232df003d6935f0941046c3f92c
|
diff --git a/analysis/memory.py b/analysis/memory.py
index <HASH>..<HASH> 100644
--- a/analysis/memory.py
+++ b/analysis/memory.py
@@ -36,7 +36,7 @@ def main(args):
strings_collection = utils.worst_case_strings_collection(m, n)
ast = base.AST.get_ast(ast_algorithm, strings_collection)
asts.append(ast)
- print("%i\t%.2f" % (n, memory_usage()))
+ print("%i\t%.2f" % (n, memory_usage() / repeats))
for ast in asts:
del ast
gc.collect()
|
Small fix in analysis.memory
The script now takes into account the number of repeats of the experiment.
|
mikhaildubov_AST-text-analysis
|
train
|
84de3bdf3bffbc4fbbf716508aed1821407a7ad1
|
diff --git a/shopify/resources/asset.py b/shopify/resources/asset.py
index <HASH>..<HASH> 100644
--- a/shopify/resources/asset.py
+++ b/shopify/resources/asset.py
@@ -9,9 +9,9 @@ class Asset(ShopifyResource):
def _prefix(cls, options={}):
theme_id = options.get("theme_id")
if theme_id:
- return "/admin/themes/%s/" % theme_id
+ return "/admin/themes/%s" % theme_id
else:
- return "/admin/"
+ return "/admin"
@classmethod
def _element_path(cls, id, prefix_options={}, query_options=None):
diff --git a/test/asset_test.py b/test/asset_test.py
index <HASH>..<HASH> 100644
--- a/test/asset_test.py
+++ b/test/asset_test.py
@@ -2,10 +2,9 @@ import shopify
from test_helper import TestCase
class AssetTest(TestCase):
-
- def test_get_assetss(self):
- # fix extra slash from pyactiveresource
- self.fake("themes/1//assets", method='GET', body=self.load_fixture('assets'))
+
+ def test_get_assets(self):
+ self.fake("themes/1/assets", method='GET', body=self.load_fixture('assets'))
v = shopify.Asset.find(theme_id = 1)
def test_get_asset_namespaced(self):
|
fxed extra slash in asset
|
Shopify_shopify_python_api
|
train
|
1aa456ea3345df2c1c85dbe763cd563b19dec665
|
diff --git a/addon/unless.js b/addon/unless.js
index <HASH>..<HASH> 100644
--- a/addon/unless.js
+++ b/addon/unless.js
@@ -1,5 +1,5 @@
-import curriedComputed from 'ember-macro-helpers/curried-computed';
+import { conditional } from '.';
-export default curriedComputed((condition, expr1, expr2) => {
- return condition ? expr2 : expr1;
-});
+export default function(condition, expr1, expr2) {
+ return conditional(condition, expr2, expr1);
+}
|
use conditional as base for unless
|
kellyselden_ember-awesome-macros
|
train
|
9d158b0fe7cf5467e100679f67cb0789ccb8d60b
|
diff --git a/src/main/java/com/opentok/api/API_Config.java b/src/main/java/com/opentok/api/API_Config.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/opentok/api/API_Config.java
+++ b/src/main/java/com/opentok/api/API_Config.java
@@ -12,6 +12,6 @@ public class API_Config {
public static final String API_SECRET = ""; // Fill this in with generated API Secret in email
- public static final String API_URL = "https://api.opentok.com";
+ public static final String API_URL = "http://api.opentok.com";
}
|
Updating the API_URL to not point to https by default
|
opentok_Opentok-Java-SDK
|
train
|
9c45f4199b2166e7d6b2d8cfda00e80fc00c914d
|
diff --git a/nolds/measures.py b/nolds/measures.py
index <HASH>..<HASH> 100644
--- a/nolds/measures.py
+++ b/nolds/measures.py
@@ -1332,7 +1332,7 @@ def mfhurst_b(data, qvals=[1], dists=range(1, 20),
Calculates the Generalized Hurst Exponent H_q for different q according to
A.-L. Barabási and T. Vicsek.
- Explanation of the General Hurst Exponent:
+ Explanation of the Generalized Hurst Exponent:
The Generalized Hurst Exponent (GHE, H_q or H(q)) can (as the name implies)
be seen as a generalization of the Hurst exponent for data series with
multifractal properties. It's origins are however not directly related
@@ -1344,19 +1344,21 @@ def mfhurst_b(data, qvals=[1], dists=range(1, 20),
h(x) ~= lambda^(-H) h(lambda x)
for any positive real valued lambda and some positive real valued exponent
- H, which is called the Hölder or roughness exponent. In other words you
- can view lambda as a scaling factor or "step size". With lambda < 1 we
- decrease the step size and zoom into our function. In this case lambda^(-H)
- becomes greater than one, meaning that h(lambda x) looks similar to a
- smaller version of h(x). With lambda > 1 we zoom out and get
- lambda^(-H) < 1.
+ H, which is called the Hurst, Hölder, Hurst-Hölder or roughness exponent
+ in the literature. In other words you can view lambda as a scaling factor
+ or "step size". With lambda < 1 we decrease the step size and zoom into our
+ function. In this case lambda^(-H) becomes greater than one, meaning that
+ h(lambda x) looks similar to a smaller version of h(x). With lambda > 1 we
+ zoom out and get lambda^(-H) < 1.
To calculate H, you can use the height-height correlation function (also
called autocorrelation) c(x) = <(h(x') - h(x' + x))^2>_x' where <...>_x'
denotes the expected value over x'. Here, the aforementioned self-affine
- property is equivalent to c(x) ~ x^(2H).
-
- TODO: Can I explain why the autocorrelation has to follow this rule?
+ property is equivalent to c(x) ~ x^(2H). You can also think of x as a step
+ size. Increasing or decreasing x from 1 to some y is the same as setting
+ lambda = y: It increases or decreases the scale of the function by a factor
+ of 1/y^(-H) = y^H. Therefore the squared differences will be proportional
+ to y^2H.
A.-L. Barabási and T. Vicsek extended this notion to an infinite hierarchy
of exponents H_q for the qth-order correlation function with
@@ -1368,9 +1370,38 @@ def mfhurst_b(data, qvals=[1], dists=range(1, 20),
independent of q, which indicates that the function has no multifractal
properties, or different H_q, which is a sign for multifractal behavior.
- T. Di Matteo, T. Aste and M.M. Dacorogna applied this technique to
+ T. Di Matteo, T. Aste and M. M. Dacorogna applied this technique to
financial data series and gave it the name "Generalized Hurst Exponent".
+ Explanation of the Algorithm:
+ Curiously, I could not find any algorithmic description how to calculate
+ H_q in the literature. Researchers seem to just imply that you can obtain
+ the exponent by a line fitting algorithm in a log-log plot, but they do not
+ talk about the actual procedure or the required parameters.
+
+ Essentially, we can calculate c_q(x) of a discrete evenly spaced time
+ series Y = [y_0, y_1, y_2, ... y_(N-1)] by taking the absolute differences
+ [|y_0 - y_x|, |y_1 - y_(x+1)|, ... , |y_(N-x-1) - y_(N-1)|] raising them to
+ the qth power and taking the mean.
+
+ Now we take the logarithm on both sides of our relation c_q(x) ~ x^(q H_q)
+ and get
+
+ log(c_q(x)) ~ log(x) * q H_q
+
+ So in other words if we plot log(c_q(x)) against log(x) for several x we
+ should get a straight line with slope q H_q. This enables us to use a
+ linear least squares algorithm to obtain H_q.
+
+ Note that we consider x as a discrete variable in the range 0 <= x < N.
+ We can do this, because the actual sampling rate of our data series does
+ not alter the result. After taking the logarithm any scaling factor delta_x
+ would only result in an additive term since
+ log(delta_x * x) = log(x) + log(delta_x) and we only care about the slope
+ of the line and not the intercept.
+
+
+
Generalized Hurst exponent
(what I think is correct according to Barabási and Vicsek)
"""
@@ -1542,7 +1573,7 @@ def mfhurst_dm(data, qvals=[1], max_dists=range(5, 20), detrend=True,
measure.
Explanation of the General Hurst Exponent:
- See ``mfhurst_b``.
+ See mfhurst_b.
Generalized Hurst exponent
(reverse engineered from Tomaso Aste's MATLAB code)
|
adds explanation of autocorrelation law and Barabasi and Vicsek algorithm
|
CSchoel_nolds
|
train
|
fe6ad6f68ce976edf796de41bc158561c2263efb
|
diff --git a/src/webroot/cms/content-manager/pagecontent/includes/iframe.js b/src/webroot/cms/content-manager/pagecontent/includes/iframe.js
index <HASH>..<HASH> 100644
--- a/src/webroot/cms/content-manager/pagecontent/includes/iframe.js
+++ b/src/webroot/cms/content-manager/pagecontent/includes/iframe.js
@@ -187,7 +187,12 @@ YUI.add('supra.iframe-handler', function (Y) {
this.contents.render();
//Disable editing
- this.contents.set('highlight', true);
+ var path = Root.router.getPath(),
+ editing = Root.ROUTE_PAGE_EDIT_R.test(path) || Root.ROUTE_PAGE_CONT_R.test(path);
+
+ if (!editing) {
+ this.contents.set('highlight', true);
+ }
this.contents.on('activeChildChange', function (event) {
if (event.newVal) {
|
#<I> Fixed content editing after page load
|
sitesupra_sitesupra
|
train
|
822045db18850a0af152f68b72e203bdec91dee1
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -82,7 +82,7 @@ setup(
zip_safe=False,
install_requires=[
'setuptools',
- "pyDHTMLParser>=2.0.0",
+ "pyDHTMLParser>=2.0.7",
"httpkie>=1.1.0,<2.0.0",
],
extras_require={
|
Added dependency to new version of pyDHTMLParser, because of bug in old.
Bug was found during new testing (#<I>).
|
edeposit_edeposit.amqp.aleph
|
train
|
cfd8af052e2c2faeb82cff5c603e7fa25363d743
|
diff --git a/QUANTAXIS/QAData/data_resample.py b/QUANTAXIS/QAData/data_resample.py
index <HASH>..<HASH> 100755
--- a/QUANTAXIS/QAData/data_resample.py
+++ b/QUANTAXIS/QAData/data_resample.py
@@ -74,12 +74,8 @@ def QA_data_tick_resample_1min(tick, type_='1min'):
_data2.loc[time(15, 0): time(15, 0), 'high'] = _data2.loc[time(15, 0): time(15, 1), 'high'].max()
_data2.loc[time(15, 0): time(15, 0), 'low'] = _data2.loc[time(15, 0): time(15, 1), 'low'].min()
_data2.loc[time(15, 0): time(15, 0), 'close'] = _data2.loc[time(15, 1): time(15, 1), 'close'].values
- _data2.loc[time(15, 0): time(15, 0), 'vol'] = _data2.loc[time(15, 0): time(15, 1), 'vol'].sum()
- _data2.loc[time(15, 0): time(15, 0), 'amount'] = _data2.loc[time(15, 0): time(15, 1), 'amount'].sum()
else:
_data2.loc[time(15, 0): time(15, 0)] = _data2.loc[time(15, 1): time(15, 1)].values
- _data2.loc[time(15, 0): time(15, 0)] = _data2.loc[time(15, 1): time(15, 1)].values
- _data2.loc[time(15, 0): time(15, 0)] = _data2.loc[time(15, 1): time(15, 1)].values
_data2 = _data2.loc[time(13, 1): time(15, 0)]
resx = resx.append(_data1).append(_data2)
resx['vol'] = resx['vol'] * 100.0
|
QA_data_tick_resample_1min test with <I> from <I> to <I>
|
QUANTAXIS_QUANTAXIS
|
train
|
da9b77140def2543f56b85b268811e9a820bff72
|
diff --git a/src/Co.php b/src/Co.php
index <HASH>..<HASH> 100644
--- a/src/Co.php
+++ b/src/Co.php
@@ -2,19 +2,20 @@
namespace Swoft;
-use function count;
-use function go;
use ReflectionException;
-use function sgo;
use Swoft;
use Swoft\Context\Context;
use Swoft\Log\Debug;
use Swoft\Stdlib\Helper\PhpHelper;
use Swoole\Coroutine;
use Throwable;
+use function count;
+use function go;
+use function sgo;
/**
* Class Co
+ *
* @since 2.0
*/
class Co
@@ -68,7 +69,7 @@ class Co
$tid = self::tid();
// return coroutine ID for created.
- return go(function () use ($callable, $tid, $wait) {
+ return Coroutine::create(function () use ($callable, $tid, $wait) {
try {
$id = Coroutine::getCid();
// Storage fd
@@ -80,13 +81,8 @@ class Co
PhpHelper::call($callable);
} catch (Throwable $e) {
- Debug::log(
- "Coroutine internal error: %s\nAt File %s line %d\nTrace:\n%s",
- $e->getMessage(),
- $e->getFile(),
- $e->getLine(),
- $e->getTraceAsString()
- );
+ Debug::log("Coroutine internal error: %s\nAt File %s line %d\nTrace:\n%s", $e->getMessage(),
+ $e->getFile(), $e->getLine(), $e->getTraceAsString());
// Trigger co error event
Swoft::trigger(SwoftEvent::COROUTINE_EXCEPTION, $e);
@@ -148,9 +144,7 @@ class Co
$data = PhpHelper::call($callback);
$channel->push([$key, $data]);
} catch (Throwable $e) {
- Debug::log(
- 'Co multi errro(key=%s) is %s', $key, $e->getMessage()
- );
+ Debug::log('Co multi errro(key=%s) is %s', $key, $e->getMessage());
$channel->push(false);
}
|
fix: swoft-cloud/swoft#<I> use Coroutine::create instead of go() create new coroutine
|
swoft-cloud_swoft-framework
|
train
|
0a51607328603127be67ed3e97d06ef03d0e35a8
|
diff --git a/auto_ml/utils_models.py b/auto_ml/utils_models.py
index <HASH>..<HASH> 100644
--- a/auto_ml/utils_models.py
+++ b/auto_ml/utils_models.py
@@ -42,7 +42,10 @@ def get_model_from_name(model_name, training_params=None):
'PassiveAggressiveRegressor': {'shuffle': False},
'AdaBoostRegressor': {'n_estimators': 10},
'XGBRegressor': {'nthread':-1, 'n_estimators': 200},
- 'XGBClassifier': {'nthread':-1, 'n_estimators': 200}
+ 'XGBClassifier': {'nthread':-1, 'n_estimators': 200},
+ 'LGBMRegressor': {},
+ 'LGBMClassifier': {}
+
}
model_params = all_model_params.get(model_name, None)
@@ -352,6 +355,18 @@ def get_search_params(model_name):
}
+ , 'LGBMRegressor': {
+ # 'max_bin': [25, 50, 100, 200, 250, 300, 400, 500, 750, 1000]
+ 'num_leaves': [10, 20, 30, 40, 50, 200]
+ , 'colsample_bytree': [0.7, 0.9, 1.0]
+ , 'subsample': [0.7, 0.9, 1.0]
+ # , 'subsample_freq': [0.3, 0.5, 0.7, 0.9, 1.0]
+ , 'learning_rate': [0.01, 0.05, 0.1]
+ # , 'subsample_for_bin': [1000, 10000]
+ , 'n_estimators': [5, 20, 50, 200]
+
+ }
+
}
return grid_search_params[model_name]
|
adds hyperparameters for lgbmregressor, and removes our attempts to overwrite their defaults by default
|
ClimbsRocks_auto_ml
|
train
|
0444997e72633196fee8354d54f2416f5630e04c
|
diff --git a/lib/diff-logger.js b/lib/diff-logger.js
index <HASH>..<HASH> 100644
--- a/lib/diff-logger.js
+++ b/lib/diff-logger.js
@@ -35,11 +35,5 @@ exports.log = function(diff, options) {
}
});
- /*
- Это костыль. После многочисленных реплейсов, диффер воспринимает строку '"' как строку '&quot;',
- поэтому заменяю '&' на '&'
- */
- output = output.replace(/&/g, "&");
-
console.log('Differences:' + output);
}
diff --git a/lib/html-differ.js b/lib/html-differ.js
index <HASH>..<HASH> 100644
--- a/lib/html-differ.js
+++ b/lib/html-differ.js
@@ -16,7 +16,8 @@ HtmlDiff.prototype = Diff.prototype;
HtmlDiff.prototype.tokenize = function(value) {
- value = treeToHtml(transform(htmlToTree(value), this.ignoreHtmlAttrs, this.compareHtmlAttrsAsJSON));
+ value = treeToHtml(transform(htmlToTree(value), this.ignoreHtmlAttrs, this.compareHtmlAttrsAsJSON))
+ .replace(/\&quot;/g, '\"'); // Bug in 'html-parser-to-html'. String '"' is converted into '&quot;'
return removeEmpty(value.split(/(\s+|\b)/));
};
@@ -89,7 +90,7 @@ function transform(tree, ignoreHtmlAttrs, compareHtmlAttrsAsJSON) {
(node[leaf][attr] =
JSON
.stringify(sortContent(JSON.parse(node[leaf][attr].replace(/\"/g, '\"'), 'utf-8')), null, '')
- .replace(/\"/g, "\""));
+ .replace(/\"/g, '\"'));
});
ignoreHtmlAttrs.forEach(function(attr) {
|
get rid of crooked nail in logger
|
bem_html-differ
|
train
|
7cd650189157b4ee1e94ee3b52eead2dc23147f4
|
diff --git a/src/Tenant/Comment.php b/src/Tenant/Comment.php
index <HASH>..<HASH> 100755
--- a/src/Tenant/Comment.php
+++ b/src/Tenant/Comment.php
@@ -50,9 +50,19 @@ class Tenant_Comment extends Pluf_Model
'type' => 'Pluf_DB_Field_Foreignkey',
'model' => 'Pluf_User',
'blank' => false,
+ 'is_null' => false,
+ 'editable' => false,
+ 'readable' => true,
+ 'relate_name' => 'author'
+ ),
+ 'ticket' => array(
+ 'type' => 'Pluf_DB_Field_Foreignkey',
+ 'model' => 'Tenant_Ticket',
+ 'blank' => false,
+ 'is_null' => false,
'editable' => false,
'readable' => true,
- 'relate_name' => 'user'
+ 'relate_name' => 'ticket'
)
);
|
relation between Comment and Ticket is defined
|
pluf_tenant
|
train
|
fff686e6a3bd86eb9d7f1e8824d5bb051672b97e
|
diff --git a/lib/node_modules/@stdlib/stats/incr/variance/lib/main.js b/lib/node_modules/@stdlib/stats/incr/variance/lib/main.js
index <HASH>..<HASH> 100644
--- a/lib/node_modules/@stdlib/stats/incr/variance/lib/main.js
+++ b/lib/node_modules/@stdlib/stats/incr/variance/lib/main.js
@@ -141,7 +141,7 @@ function incrvariance( mean ) {
if ( N < 2 ) {
return 0.0;
}
- return M2 / (N-1);
+ return M2 / N;
}
N += 1;
delta = x - mu;
@@ -149,7 +149,7 @@ function incrvariance( mean ) {
if ( N < 2 ) {
return 0.0;
}
- return M2 / (N-1);
+ return M2 / N;
}
}
diff --git a/lib/node_modules/@stdlib/stats/incr/variance/test/test.js b/lib/node_modules/@stdlib/stats/incr/variance/test/test.js
index <HASH>..<HASH> 100644
--- a/lib/node_modules/@stdlib/stats/incr/variance/test/test.js
+++ b/lib/node_modules/@stdlib/stats/incr/variance/test/test.js
@@ -109,11 +109,11 @@ tape( 'the accumulator function incrementally computes an unbiased sample varian
// Test against Julia:
expected = [
0.0,
- 1.0,
- 1.0,
- 1.0,
+ 0.5,
+ 0.6666666666666666,
0.75,
- 0.8
+ 0.6,
+ 0.6666666666666666
];
acc = incrvariance( 3.0 );
@@ -150,7 +150,7 @@ tape( 'if not provided an input value, the accumulator function returns the curr
for ( i = 0; i < data.length; i++ ) {
acc( data[ i ] );
}
- t.equal( acc(), 1.0, 'returns the current accumulated unbiased sample variance' );
+ t.equal( acc(), 0.6666666666666666, 'returns the current accumulated unbiased sample variance' );
t.end();
});
|
Use an unbiased estimator when provided a known mean
|
stdlib-js_stdlib
|
train
|
d00b0114531f1237ffbb372b488559ce512f019b
|
diff --git a/lib/adapters/http.js b/lib/adapters/http.js
index <HASH>..<HASH> 100644
--- a/lib/adapters/http.js
+++ b/lib/adapters/http.js
@@ -201,6 +201,7 @@ function HttpPouch(opts, callback) {
//check if the db exists
if (err) {
if (err.status === 404) {
+ utils.explain404('PouchDB is just detecting if the remote DB exists.');
//if it doesn't, create it
createDB();
} else {
diff --git a/lib/adapters/idb.js b/lib/adapters/idb.js
index <HASH>..<HASH> 100644
--- a/lib/adapters/idb.js
+++ b/lib/adapters/idb.js
@@ -1337,6 +1337,10 @@ function init(api, opts, callback) {
blobSupport = true;
} else {
blobSupport = !!(res && res.type === 'image/png');
+ if (err && err.status === 404) {
+ utils.explain404(
+ 'PouchDB is just detecting blob URL support.');
+ }
}
checkSetupComplete();
});
diff --git a/lib/replicate.js b/lib/replicate.js
index <HASH>..<HASH> 100644
--- a/lib/replicate.js
+++ b/lib/replicate.js
@@ -141,6 +141,10 @@ function genReplicationId(src, target, opts) {
function updateCheckpoint(db, id, checkpoint, returnValue) {
return db.get(id).catch(function (err) {
if (err.status === 404) {
+ if (db.type() === 'http') {
+ utils.explain404(
+ 'PouchDB is just checking if a remote checkpoint exists.');
+ }
return {_id: id};
}
throw err;
diff --git a/lib/utils.js b/lib/utils.js
index <HASH>..<HASH> 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -561,3 +561,12 @@ exports.cancellableFun = function (fun, self, opts) {
};
exports.MD5 = exports.toPromise(require('./deps/md5'));
+
+// designed to give info to browser users, who are disturbed
+// when they see 404s in the console
+exports.explain404 = function (str) {
+ if (process.browser && 'console' in global && 'info' in console) {
+ console.info('The above 404 is totally normal. ' +
+ str + '\n\u2665 the PouchDB team');
+ }
+};
|
(#<I>) - explain normal <I>s in console.info
|
pouchdb_pouchdb
|
train
|
860e93e2bf323d57298f941ec71deacba479d922
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -88,21 +88,21 @@ module.exports = function(trees, options) {
// post order travel
var obj = rs[oid] = [compress ? root.version: id];
- var dep;
- edgeKeys.forEach(function(depName) {
+ for(var i = 0; i < edgeKeys.length; ++i) {
+ var depName = edgeKeys[i];
var deps = root[depName];
if (deps) {
- dep = dep || {};
+ var dep = {};
Object.keys(deps).forEach(function(name) {
var node = deps[name];
dep[node.from] = gid(node);
});
+
+ obj.push(dep);
}
- });
+ }
- if (dep)
- obj.push(dep);
path.pop();
}
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gen-graph",
- "version": "0.1.1",
+ "version": "0.1.2",
"description": "gen-graph",
"main": "index.js",
"scripts": {
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -17,6 +17,7 @@ describe('graph generator', function() {
assertLength(config, 13);
+ assert.equal(getRootNode(config).length, 2);
assertTimes(config, "a@1.0.0", 2);
assertTimes(config, "b@1.0.0", 1);
assertTimes(config, "b@1.0.1", 1);
@@ -36,6 +37,7 @@ describe('graph generator', function() {
});
assertLength(config, 12);
+ assert.equal(getRootNode(config).length, 2);
assertTimes(config, "a@1.0.0", 2);
assertTimes(config, "b@1.0.0", 1);
assertTimes(config, "b@1.0.1", 1);
@@ -47,6 +49,7 @@ describe('graph generator', function() {
var config = graph(tree);
assertLength(config, 3);
+ assert.equal(getRootNode(config).length, 2);
assertUniq(config);
});
@@ -56,6 +59,7 @@ describe('graph generator', function() {
var tree = readJSON('cycle');
var config = graph(tree);
assertLength(config, 9);
+ assert.equal(getRootNode(config).length, 2);
assertUniq(config);
});
@@ -67,6 +71,7 @@ describe('graph generator', function() {
compress: false
});
+ assert.equal(getRootNode(config).length, 1);
assert(config[0] && config[0].length == 1);
assert.equal(config[0][0], 'test-pkg@0.1.0');
});
@@ -93,6 +98,8 @@ describe('graph generator', function() {
});
assertLength(config, 5);
+ assert.equal(getRootNode(config).length, 2);
+
assertTimes(config, "json@1.0.1", 1);
assertTimes(config, "util@1.0.4", 1);
assertTimes(config, "util@1.0.5", 1);
@@ -108,6 +115,9 @@ describe('graph generator', function() {
});
assertLength(config, 6);
+ var root = getRootNode(config);
+ assert.equal(root.length, 3);
+
assertTimes(config, "json@1.0.1", 1);
assertTimes(config, "json@1.0.2", 1);
assertTimes(config, "util@1.0.4", 2);
@@ -134,6 +144,7 @@ describe('graph generator', function() {
});
assertLength(config, 1);
+ assert.equal(getRootNode(config).length, 2);
assertTimes(config, "test-pkg@0.1.0", 1);
assert(config[0] && config[0].length == 2);
assert.equal(config[0][1]['test-pkg@~0.1.0'], 0);
@@ -173,4 +184,15 @@ describe('graph generator', function() {
return JSON.parse(JSON.stringify(require('./fixtures/' + name)));
}
+
+ function getRootNode(config) {
+ var idx;
+ for(var p in config._) {
+ if(idx !== undefined) break;
+ idx = config._[p];
+ }
+
+ return config[idx];
+ }
+
});
|
fix: asyncDependencies key in the same entry of dependencies
|
villadora_gen-graph
|
train
|
989ccbc044c227ecf28f6c0bfbd62935a882e85b
|
diff --git a/lib/actors/scraper.js b/lib/actors/scraper.js
index <HASH>..<HASH> 100644
--- a/lib/actors/scraper.js
+++ b/lib/actors/scraper.js
@@ -28,5 +28,9 @@ Scraper.prototype.setRouter = function(router){
Scraper.prototype.get = function(content){
var route = this.webname + '#' + content;
var extractor = this.router.resolve(route);
- return extractor.operation(this.$,this.url);
+ var result;
+ if(extractor){
+ result = extractor.operation(this.$,this.url);
+ }
+ return result;
}
|
Added check that extractor is truable if not the result returned by get() will be undefined so get() does not throw any error
|
lbdremy_scrapinode
|
train
|
06c4b7e703b75c4b39dc6a1898acb6e46468f51e
|
diff --git a/src/Cartalyst/Sentry/Throttling/Eloquent/Throttle.php b/src/Cartalyst/Sentry/Throttling/Eloquent/Throttle.php
index <HASH>..<HASH> 100644
--- a/src/Cartalyst/Sentry/Throttling/Eloquent/Throttle.php
+++ b/src/Cartalyst/Sentry/Throttling/Eloquent/Throttle.php
@@ -322,22 +322,6 @@ class Throttle extends Model implements ThrottleInterface {
}
/**
- * Set mutator for the last attempt at property.
- *
- * @param mixed $lastAttemptAt
- * @return DateTime
- */
- public function setLastAttemptAt($lastAttemptAt)
- {
- if ($lastAttemptAt and ! $lastAttemptAt instanceof DateTime)
- {
- $lastAttemptAt = new DateTime($lastAttemptAt);
- }
-
- return $lastAttemptAt;
- }
-
- /**
* Get mutator for the last attempt at property.
*
* @param mixed $lastAttemptAt
@@ -345,28 +329,7 @@ class Throttle extends Model implements ThrottleInterface {
*/
public function getLastAttemptAt($lastAttemptAt)
{
- if ($lastAttemptAt and ! $lastAttemptAt instanceof DateTime)
- {
- $lastAttemptAt = new DateTime($lastAttemptAt);
- }
-
- return $lastAttemptAt;
- }
-
- /**
- * Set mutator for the suspended at property.
- *
- * @param mixed $suspendedAt
- * @return DateTime
- */
- public function setSuspendedAt($suspendedAt)
- {
- if ($suspendedAt and ! $suspendedAt instanceof DateTime)
- {
- $suspendedAt = new DateTime($suspendedAt);
- }
-
- return $suspendedAt;
+ return $this->asDateTime('last_attempt_at');
}
/**
@@ -377,12 +340,7 @@ class Throttle extends Model implements ThrottleInterface {
*/
public function getSuspendedAt($suspendedAt)
{
- if ($suspendedAt and ! $suspendedAt instanceof DateTime)
- {
- $suspendedAt = new DateTime($suspendedAt);
- }
-
- return $suspendedAt;
+ return $this->asDateTime('suspended_at');
}
/**
@@ -442,11 +400,11 @@ class Throttle extends Model implements ThrottleInterface {
{
$result = parent::toArray();
- if (isset($result['last_attempt_at']))
+ if (isset($result['last_attempt_at']) and $result['last_attempt_at'] instanceof DateTime)
{
$result['last_attempt_at'] = $result['last_attempt_at']->format('Y-m-d H:i:s');
}
- if (isset($result['suspended_at']))
+ if (isset($result['suspended_at']) and $result['suspended_at'] instanceof DateTime)
{
$result['suspended_at'] = $result['suspended_at']->format('Y-m-d H:i:s');
}
|
Adding a few fixes for latest illuminate/database changes.
|
cartalyst_sentry
|
train
|
85596e6db33d969d52e1d7d7a79b343a9982af52
|
diff --git a/lib/update.js b/lib/update.js
index <HASH>..<HASH> 100644
--- a/lib/update.js
+++ b/lib/update.js
@@ -6,6 +6,7 @@ var clone = require('lodash/clone')
var Promise = require('lie')
var internals = module.exports.internals = {}
+internals.deserialise = require('../utils/deserialise')
internals.request = require('../utils/request')
internals.saveAccount = require('../utils/save-account')
internals.serialise = require('../utils/serialise')
@@ -25,6 +26,19 @@ function update (state, options) {
})
.then(function () {
+ return internals.request({
+ url: state.url + '/session',
+ method: 'PUT',
+ body: internals.serialise('session', options)
+ })
+ })
+
+ .then(function (response) {
+ var data = internals.deserialise(response.body, {
+ include: 'account'
+ })
+ state.account.session.id = data.id
+
merge(state.account, options)
internals.saveAccount({
cacheKey: state.cacheKey,
|
fix: renew session after username / password change
|
hoodiehq_hoodie-account-client
|
train
|
6c4abaee66e6c3cf449bc651e0c4008518ee094d
|
diff --git a/rootpy/plotting/canvas.py b/rootpy/plotting/canvas.py
index <HASH>..<HASH> 100644
--- a/rootpy/plotting/canvas.py
+++ b/rootpy/plotting/canvas.py
@@ -29,19 +29,56 @@ class _PadBase(NamedObject):
keepalive(self, pad)
return pad
- def axes(self, xlimits=None, ylimits=None):
+ def axes(self, ndim=1,
+ xlimits=None, ylimits=None, zlimits=None,
+ xbins=1, ybins=1, zbins=1):
"""
Create and return axes on this pad
"""
- from .hist import Hist
- hist = Hist(1, 0, 1)
+ if ndim == 1:
+ from .hist import Hist
+ if xlimits is not None:
+ hist = Hist(xbins, xlimits[0], xlimits[1])
+ else:
+ hist = Hist(xbins, 0, 1)
+ elif ndim == 2:
+ from .hist import Hist2D
+ args = [xbins, 0, 1, ybins, 0, 1]
+ if xlimits is not None:
+ args[1] = xlimits[0]
+ args[2] = xlimits[1]
+ if ylimits is not None:
+ args[4] = ylimits[0]
+ args[5] = ylimits[1]
+ hist = Hist2D(*args)
+ elif ndim == 3:
+ from .hist import Hist3D
+ args = [xbins, 0, 1, ybins, 0, 1, zbins, 0, 1]
+ if xlimits is not None:
+ args[1] = xlimits[0]
+ args[2] = xlimits[1]
+ if ylimits is not None:
+ args[4] = ylimits[0]
+ args[5] = ylimits[1]
+ if zlimits is not None:
+ args[7] = zlimits[0]
+ args[8] = zlimits[1]
+ hist = Hist3D(*args)
+ else:
+ raise ValueError("ndim must be 1, 2, or 3")
hist.Draw('AXIS')
xaxis = hist.xaxis
yaxis = hist.yaxis
+ if ndim > 1:
+ zaxis = hist.zaxis
if xlimits is not None:
xaxis.limits = xlimits
if ylimits is not None:
yaxis.limits = ylimits
+ if ndim > 1 and zlimits is not None:
+ zaxis.limits = zlimits
+ if ndim > 1:
+ return xaxis, yaxis, zaxis
return xaxis, yaxis
@property
|
pad.axes() will now setup 2d and 3d plots
|
rootpy_rootpy
|
train
|
a55da29a7c159c8f515aca26be0c1888cb9e8f98
|
diff --git a/docs/zh-CN/arr.md b/docs/zh-CN/arr.md
index <HASH>..<HASH> 100644
--- a/docs/zh-CN/arr.md
+++ b/docs/zh-CN/arr.md
@@ -8,8 +8,6 @@ Arr
### 获取数组或对象中指定键名的值
```php
-<?php
-
class Getter
{
public function getKey()
@@ -98,4 +96,4 @@ Array
其他对象
#### arr->sort($array, $key = 'order', $type = SORT_ASC)
-对一个二维数组进行排序,类似SQL的ORDER BY语句
+对一个二维数组进行排序,类似SQL的ORDER BY语句
\ No newline at end of file
diff --git a/lib/Widget/App.php b/lib/Widget/App.php
index <HASH>..<HASH> 100644
--- a/lib/Widget/App.php
+++ b/lib/Widget/App.php
@@ -51,13 +51,11 @@ class App extends AbstractWidget
/**
* The name of controller
- /
+ *
* @var string
*/
protected $controller;
- protected $controllerClass = '';
-
/**
* The name of action
*
@@ -66,6 +64,13 @@ class App extends AbstractWidget
protected $action;
/**
+ * The controller class format
+ *
+ * @var string
+ */
+ protected $controllerFormat = '%module%\%controller%Controller';
+
+ /**
* The controller instances
*
* @var array
@@ -287,7 +292,11 @@ class App extends AbstractWidget
return false;
}
- $class = ucfirst($module) . '\Controller\\' . ucfirst($controller) . 'Controller';
+ $class = str_replace(
+ array('%module%', '%controller%'),
+ array(ucfirst($module), ucfirst($controller)),
+ $this->controllerFormat
+ );
if (isset($this->controllers[$class])) {
return $this->controllers[$class];
diff --git a/tests/WidgetTest/AppTest.php b/tests/WidgetTest/AppTest.php
index <HASH>..<HASH> 100644
--- a/tests/WidgetTest/AppTest.php
+++ b/tests/WidgetTest/AppTest.php
@@ -12,6 +12,7 @@ class AppTest extends TestCase
parent::setUp();
$this->app
+ ->setOption('controllerFormat', '%module%\Controller\\%controller%Controller')
// Change avaiable modules
->setOption('modules', array('WidgetTest\AppTest'))
// Set default module
|
added controller format property, simplfied controller class name
|
twinh_wei
|
train
|
b037ecb82ba5f8791433f57de31a90fb57fe986d
|
diff --git a/src/util.js b/src/util.js
index <HASH>..<HASH> 100644
--- a/src/util.js
+++ b/src/util.js
@@ -190,9 +190,10 @@ util.getFileReplacement = function( src, settings, callback )
{
var fileName = util.getInlineFilePath( src, settings.relativeTo );
var mimetype = mime.getType( fileName );
- var base64 = fs.readFileSync( fileName, 'base64' );
- var datauri = `data:${mimetype};base64,${base64}`;
- callback( null, datauri );
+ fs.readFile( fileName, 'base64', function( err, base64 ) {
+ var datauri = `data:${mimetype};base64,${base64}`;
+ callback( err, datauri );
+ } );
}
};
|
Use callback version of readFile
|
jrit_web-resource-inliner
|
train
|
cbfacf5becc2d4e5b495c246a367abd9c5683bf0
|
diff --git a/src/Forms/Group.php b/src/Forms/Group.php
index <HASH>..<HASH> 100644
--- a/src/Forms/Group.php
+++ b/src/Forms/Group.php
@@ -119,7 +119,7 @@ class Group extends HtmlContainer
*
* @return $this
*/
- protected function setField(HtmlContainer $field = null) : self
+ protected function setField($field = null) : self
{
$index = $this->getIndex($this->container);
$this->container = $field;
|
FormGroup : SetGroup must follow parent signature
|
cawaphp_html
|
train
|
4b4a9115265eb65d3ff1cbe1080423b3b8ad9680
|
diff --git a/lib/LittleWeasel/metadata/metadatable.rb b/lib/LittleWeasel/metadata/metadatable.rb
index <HASH>..<HASH> 100644
--- a/lib/LittleWeasel/metadata/metadatable.rb
+++ b/lib/LittleWeasel/metadata/metadatable.rb
@@ -7,6 +7,8 @@ module LittleWeasel
module Metadata
# This module defines methods to support objects that manage other objects
# that manage metadata related to a dictionary/ies.
+ # rubocop: disable Lint/UnusedMethodArgument, ignored - Methods in this
+ # module need to keep their argument names because of specs.
module Metadatable
def self.included(base)
base.extend ClassMethods
@@ -52,8 +54,6 @@ module LittleWeasel
# self.metadata = Services::InvalidWordsService.new(dictionary_words).execute
# self
# end
- #
- # :reek:UnusedParameters, ignored - This method is meant to be called with the given argument and raises an error if not overridden
def init(params: nil)
raise Errors::MustOverrideError
end
@@ -73,7 +73,6 @@ module LittleWeasel
# init unless metadata.present?
# self
# end
- # :reek:UnusedParameters, ignored - This method is meant to be called with the given argument and raises an error if not overridden
def refresh(params: nil)
raise Errors::MustOverrideError
end
@@ -124,10 +123,12 @@ module LittleWeasel
# dictionary_cache_service.dictionary_metadata_set(
# metadata_key: metadata_key, value: value)
# end
- # :reek:UnusedParameters, ignored - This method is meant to be called with the given argument and raises an error if not overridden
+ # :reek:UnusedParameters, ignored - This method is meant to be called with the given argument and raises an
+ # error if not overridden
def update_dictionary_metadata(value:)
raise Errors::MustOverrideError
end
end
+ # rubocop: enable Lint/UnusedMethodArgument
end
end
|
Change rubocop Lint/UnusedMethodArgument violations
Methods in this module need to keep their argument names
because of specs.
|
gangelo_LittleWeasel
|
train
|
45327783abc3d3bc66b631014a3b1490d2225413
|
diff --git a/src/main/java/com/dlsc/preferencesfx/util/PreferencesFxUtils.java b/src/main/java/com/dlsc/preferencesfx/util/PreferencesFxUtils.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/dlsc/preferencesfx/util/PreferencesFxUtils.java
+++ b/src/main/java/com/dlsc/preferencesfx/util/PreferencesFxUtils.java
@@ -92,6 +92,7 @@ public class PreferencesFxUtils {
/**
* Compares three objects with decreasing priority from the first to the last object.
* {@see developer reference} for further information
+ *
* @param o1
* @param o2
* @param o3
diff --git a/src/main/java/com/dlsc/preferencesfx/util/formsfx/PreferencesGroupRenderer.java b/src/main/java/com/dlsc/preferencesfx/util/formsfx/PreferencesGroupRenderer.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/dlsc/preferencesfx/util/formsfx/PreferencesGroupRenderer.java
+++ b/src/main/java/com/dlsc/preferencesfx/util/formsfx/PreferencesGroupRenderer.java
@@ -97,6 +97,7 @@ public class PreferencesGroupRenderer extends VBox implements ViewMixin {
/**
* Adds a style class to the control.
+ *
* @param name of the style class to be added to the control
*/
public void addStyleClass(String name) {
@@ -105,6 +106,7 @@ public class PreferencesGroupRenderer extends VBox implements ViewMixin {
/**
* Removes a style class from the control.
+ *
* @param name of the class to be removed from the control
*/
public void removeStyleClass(String name) {
|
optimized imports, reformatted code
|
dlemmermann_PreferencesFX
|
train
|
61759f1f7fee07b5f0ddc5ee38bcc14d7b112dca
|
diff --git a/elasticsearch-model/test/integration/multiple_models_test.rb b/elasticsearch-model/test/integration/multiple_models_test.rb
index <HASH>..<HASH> 100644
--- a/elasticsearch-model/test/integration/multiple_models_test.rb
+++ b/elasticsearch-model/test/integration/multiple_models_test.rb
@@ -56,7 +56,7 @@ module Elasticsearch
end
should "find matching documents across multiple models" do
- response = Elasticsearch::Model.search("greatest", [Series, Episode])
+ response = Elasticsearch::Model.search("\"The greatest Episode\"^2 OR \"The greatest Series\"", [Series, Episode])
assert response.any?, "Response should not be empty: #{response.to_a.inspect}"
@@ -75,22 +75,15 @@ module Elasticsearch
end
should "provide access to results" do
- q = {query: {query_string: {query: 'A great *'}}, highlight: {fields: {name: {}}}}
- response = Elasticsearch::Model.search(q, [Series, Episode])
+ response = Elasticsearch::Model.search("\"A great Episode\"^2 OR \"A great Series\"", [Series, Episode])
assert_equal 'A great Episode', response.results[0].name
assert_equal true, response.results[0].name?
assert_equal false, response.results[0].boo?
- assert_equal true, response.results[0].highlight?
- assert_equal true, response.results[0].highlight.name?
- assert_equal false, response.results[0].highlight.boo?
assert_equal 'A great Series', response.results[1].name
assert_equal true, response.results[1].name?
assert_equal false, response.results[1].boo?
- assert_equal true, response.results[1].highlight?
- assert_equal true, response.results[1].highlight.name?
- assert_equal false, response.results[1].highlight.boo?
end
should "only retrieve records for existing results" do
@@ -144,7 +137,7 @@ module Elasticsearch
end
should "find matching documents across multiple models" do
- response = Elasticsearch::Model.search("greatest", [Episode, Image])
+ response = Elasticsearch::Model.search("\"greatest Episode\" OR \"greatest Image\"^2", [Episode, Image])
assert response.any?, "Response should not be empty: #{response.to_a.inspect}"
|
[MODEL] Fixed unreliable order of returned results/records in the integration test for the multiple adapter
Related: #<I>
|
elastic_elasticsearch-rails
|
train
|
f785cec68b2b008e83975451b346d07d65f3a421
|
diff --git a/edeposit/amqp/daemonwrapper.py b/edeposit/amqp/daemonwrapper.py
index <HASH>..<HASH> 100644
--- a/edeposit/amqp/daemonwrapper.py
+++ b/edeposit/amqp/daemonwrapper.py
@@ -47,7 +47,7 @@ class DaemonRunnerWrapper(object):
sys.exit(0)
def onIsRunning(self):
- if "stop" not in sys.argv or "restart" not in sys.argv:
+ if "stop" not in sys.argv and "restart" not in sys.argv:
print 'It looks like a daemon is already running!'
sys.exit(1)
|
Fixed bug which blocked stopping the daemon.
|
edeposit_edeposit.amqp
|
train
|
c714c2baa26713092fa8c3e04ea1b1636d6ebac0
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,6 @@
'use strict';
-exports.VERSION = '7.0.3';
+exports.VERSION = '7.0.4';
exports.JID = require('xmpp-jid').JID;
exports.Client = require('./lib/client');
diff --git a/lib/transports/old-websocket.js b/lib/transports/old-websocket.js
index <HASH>..<HASH> 100644
--- a/lib/transports/old-websocket.js
+++ b/lib/transports/old-websocket.js
@@ -3,15 +3,12 @@
var WSConnection = require('./websocket');
var _ = require('underscore');
var util = require('util');
-var stanza = require('jxt');
function OldWSConnection(sm, stanzas) {
WSConnection.call(this, sm, stanzas);
- this.stanzas.Stream = stanzas.getDefinition('stream', 'http://etherx.jabber.org/streams');
-
var self = this;
@@ -39,7 +36,7 @@ function OldWSConnection(sm, stanzas) {
return self.disconnect();
} else if (self.hasStream) {
try {
- streamData = stanza.parse(wrap(data), this.stanzas.Stream);
+ streamData = stanzas.parse(wrap(data));
} catch (e) {
err = new this.stanzas.StreamError({
condition: 'invalid-xml'
@@ -56,10 +53,10 @@ function OldWSConnection(sm, stanzas) {
ended = false;
try {
- streamData = stanza.parse(data + self.streamEnd, this.stanzas.Stream);
+ streamData = stanzas.parse(data + self.streamEnd);
} catch (e) {
try {
- streamData = stanza.parse(data, this.stanzas.Stream);
+ streamData = stanzas.parse(data);
ended = true;
} catch (e2) {
err = new this.stanzas.StreamError({
|
Fix parsing issue for old websockets
|
legastero_stanza.io
|
train
|
aab7419d64f3d694e4bdff6c1bcac011f77bc16f
|
diff --git a/lib/influxdb.js b/lib/influxdb.js
index <HASH>..<HASH> 100644
--- a/lib/influxdb.js
+++ b/lib/influxdb.js
@@ -90,7 +90,7 @@ InfluxdbBackend.prototype.logDebug = function (msg) {
InfluxdbBackend.prototype.process = function (packet, rinfo) {
var self = this,
- ts = new Date();
+ ts = (new Date()).valueOf();
/* Stolen from statsd's stats.js. */
var packet_data = packet.toString(),
@@ -202,14 +202,9 @@ InfluxdbBackend.prototype.assembleEvent = function (name, events) {
points = [];
for (var cidx in payload.columns) {
- var column = payload.columns[cidx],
- v = event[column];
+ var column = payload.columns[cidx];
- if (column == 'time' && v instanceof Date) {
- v = v.valueOf();
- }
-
- points.push(v);
+ points.push(event[column]);
}
payload.points.push(points);
|
Remove useless condition for the time column.
Also avoids passing around a date object.
|
bernd_statsd-influxdb-backend
|
train
|
ed304cf6f9cf5ef1997e00bac45fb9cbdf15c3fa
|
diff --git a/responsys/tests/test_types.py b/responsys/tests/test_types.py
index <HASH>..<HASH> 100644
--- a/responsys/tests/test_types.py
+++ b/responsys/tests/test_types.py
@@ -116,3 +116,18 @@ class RecordDataTests(unittest.TestCase):
self.assertTrue(
self.record_data.records == [[1, 2], [3, 4]] or
self.record_data.records == [[2, 1], [4, 3]])
+
+
+class MergeResultTests(unittest.TestCase):
+ def setUp(self):
+ self.error_message = 'These failed: Record 1 = Test, Record 2 = What'
+ self.merge_result = MergeResult(Mock(
+ insertCount=1,
+ updateCount=1,
+ rejectedCount=2,
+ totalCount=4,
+ errorMessage=self.error_message,
+ ))
+
+ def test_failed_property_returns_list_of_ids_from_error_string(self):
+ self.assertEqual(self.merge_result.failed, [1, 2])
diff --git a/responsys/types.py b/responsys/types.py
index <HASH>..<HASH> 100644
--- a/responsys/types.py
+++ b/responsys/types.py
@@ -1,3 +1,6 @@
+import re
+
+
class InteractType(object):
""" InteractType class
@@ -196,8 +199,12 @@ class MergeResult(InteractType):
@property
def failed(self):
- # TODO: Implement ability to parse error message for failed ids
- return []
+ failed = None
+ if self.error_message:
+ failed = re.findall(r'Record ([0-9]*) =', self.error_message)
+ failed = [f.isnumeric() and int(f) or f for f in failed]
+
+ return failed or []
class RecipientResult(InteractType):
|
Add failed property on MergeResult
Provides a list of failed ids for convenience
|
jslang_responsys
|
train
|
fb83af71950ec701ad42926c17d41aeba6c37a24
|
diff --git a/Command/SmokeTestRunCommand.php b/Command/SmokeTestRunCommand.php
index <HASH>..<HASH> 100644
--- a/Command/SmokeTestRunCommand.php
+++ b/Command/SmokeTestRunCommand.php
@@ -24,7 +24,7 @@ class SmokeTestRunCommand extends ContainerAwareCommand
{
$this
->setName('smartbox:smoke-test')
- ->setDescription('Run all services tagged with "smartbox.smoke_test"')
+ ->setDescription('Run all services tagged with "smartcore.smoke_test"')
->addOption('silent', null, InputOption::VALUE_NONE, 'If in silent mode this command will return only exit code (0 or 1)')
->addOption('json', null, InputOption::VALUE_NONE, 'Show output in JSON format.')
->addOption('output', null, InputOption::VALUE_REQUIRED, 'File path to write')
diff --git a/DependencyInjection/SmokeTestCompilerPass.php b/DependencyInjection/SmokeTestCompilerPass.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/SmokeTestCompilerPass.php
+++ b/DependencyInjection/SmokeTestCompilerPass.php
@@ -20,7 +20,7 @@ class SmokeTestCompilerPass implements CompilerPassInterface
{
$smokeTestCommand = $container->getDefinition('smartcore.command.smoke_test');
- $serviceIds = $container->findTaggedServiceIds('smartbox.smoke_test');
+ $serviceIds = $container->findTaggedServiceIds('smartcore.smoke_test');
foreach ($serviceIds as $serviceId => $tags) {
foreach($tags as $tag => $attr){
$runMethod = 'run';
diff --git a/Resources/config/services.yml b/Resources/config/services.yml
index <HASH>..<HASH> 100644
--- a/Resources/config/services.yml
+++ b/Resources/config/services.yml
@@ -77,7 +77,7 @@ services:
tags:
- { name: jms_serializer.serialization_visitor, format: array }
- smartbox.array_deserialization_visitor_mongo:
+ smartcore.array_deserialization_visitor_mongo:
class: %smartcore.array_deserialization_visitor.class%
arguments:
- @jms_serializer.naming_strategy
@@ -86,7 +86,7 @@ services:
tags:
- { name: jms_serializer.deserialization_visitor, format: mongo_array }
- smartbox.array_serialization_visitor_mongo:
+ smartcore.array_serialization_visitor_mongo:
class: %smartcore.array_serialization_visitor.class%
arguments: [@jms_serializer.naming_strategy]
tags:
|
Fixed a few prefixes
|
smartboxgroup_core-bundle
|
train
|
c32bc08c19ce2da479d7fca54651d61fa5152340
|
diff --git a/aws-sdk-core/lib/aws-sdk-core/signers/s3.rb b/aws-sdk-core/lib/aws-sdk-core/signers/s3.rb
index <HASH>..<HASH> 100644
--- a/aws-sdk-core/lib/aws-sdk-core/signers/s3.rb
+++ b/aws-sdk-core/lib/aws-sdk-core/signers/s3.rb
@@ -11,7 +11,7 @@ module Aws
acl delete cors lifecycle location logging notification partNumber
policy requestPayment restore tagging torrent uploadId uploads
- versionId versioning versions website
+ versionId versioning versions website replication requestPayment
response-content-type response-content-language
response-expires response-cache-control
|
Signer fix for classic s3 signature and get bucket replication.
|
aws_aws-sdk-ruby
|
train
|
9cb4642b2513cc8cdcc5cec471f8ff792fa8d3fc
|
diff --git a/tinman/utilities/initialize.py b/tinman/utilities/initialize.py
index <HASH>..<HASH> 100644
--- a/tinman/utilities/initialize.py
+++ b/tinman/utilities/initialize.py
@@ -141,10 +141,10 @@ setup(name='%(project)s',
self._create_package_setup()
-def initialize_project():
+def main():
initializer = Project()
initializer.run()
if __name__ == '__main__':
- initialize_project()
+ main()
|
Fix the method name to invoke the app
|
gmr_tinman
|
train
|
cd29a473681cf7f1beedc21004850f5770a470db
|
diff --git a/pyregion/core.py b/pyregion/core.py
index <HASH>..<HASH> 100644
--- a/pyregion/core.py
+++ b/pyregion/core.py
@@ -255,7 +255,8 @@ def open(fname):
shapes : `ShapeList`
List of `~pyregion.Shape`
"""
- region_string = _builtin_open(fname).read()
+ with _builtin_open(fname) as fh:
+ region_string = fh.read()
return parse(region_string)
|
Use with open to avoid keeping filehandles open indefinitely
|
astropy_pyregion
|
train
|
49d3600d1231f31179226e94a459b9888836d8d2
|
diff --git a/lib/queue_classic.rb b/lib/queue_classic.rb
index <HASH>..<HASH> 100644
--- a/lib/queue_classic.rb
+++ b/lib/queue_classic.rb
@@ -91,12 +91,18 @@ module QC
puts(out) if ENV["DEBUG"]
return result
end
-
+
def self.measure(data)
if ENV['QC_MEASURE']
$stdout.puts("measure#qc.#{data}")
end
end
+
+ # This will unlock all jobs any postgres' PID that is not existing anymore
+ # to prevent any infinitely locked jobs
+ def self.unlock_jobs_of_dead_workers
+ @conn_adapter.execute("UPDATE #{QC::TABLE_NAME} SET locked_at = NULL, locked_by = NULL WHERE locked_by NOT IN (SELECT pid FROM pg_stat_activity);")
+ end
end
require_relative "queue_classic/queue"
diff --git a/lib/queue_classic/worker.rb b/lib/queue_classic/worker.rb
index <HASH>..<HASH> 100644
--- a/lib/queue_classic/worker.rb
+++ b/lib/queue_classic/worker.rb
@@ -39,7 +39,8 @@ module QC
# The canonical example of starting a worker is as follows:
# QC::Worker.new.start
def start
- unlock_jobs_of_dead_workers()
+ QC.unlock_jobs_of_dead_workers
+
while @running
@fork_worker ? fork_and_work : work
end
@@ -95,12 +96,6 @@ module QC
end
end
- # This will unlock all jobs any postgres' PID that is not existing anymore
- # to prevent any infinitely locked jobs
- def unlock_jobs_of_dead_workers
- @conn_adapter.execute("UPDATE #{QC::TABLE_NAME} SET locked_at = NULL, locked_by = NULL WHERE locked_by NOT IN (SELECT pid FROM pg_stat_activity);")
- end
-
# A job is processed by evaluating the target code.
# if the job is evaluated with no exceptions
# then it is deleted from the queue.
diff --git a/test/lib/queue_classic_test.rb b/test/lib/queue_classic_test.rb
index <HASH>..<HASH> 100644
--- a/test/lib/queue_classic_test.rb
+++ b/test/lib/queue_classic_test.rb
@@ -10,4 +10,23 @@ class QueueClassicTest < QCTest
QC.default_conn_adapter = connection
assert_equal(QC.default_conn_adapter, connection)
end
+
+ def test_unlock_jobs_of_dead_workers
+ # Insert a locked job
+ adapter = QC::ConnAdapter.new
+ query = "INSERT INTO #{QC::TABLE_NAME} (q_name, method, args, locked_by, locked_at) VALUES ('whatever', 'Kernel.puts', '[\"ok?\"]', 0, (CURRENT_TIMESTAMP))"
+ adapter.execute(query)
+
+ # We should have no unlocked jobs
+ query_locked_jobs = "SELECT * FROM #{QC::TABLE_NAME} WHERE locked_at IS NULL"
+ res = adapter.connection.exec(query_locked_jobs)
+ assert_equal(0, res.count)
+
+ # Unlock the job
+ QC.unlock_jobs_of_dead_workers
+
+ # We should have an unlocked job now
+ res = adapter.connection.exec(query_locked_jobs)
+ assert_equal(1, res.count)
+ end
end
diff --git a/test/worker_test.rb b/test/worker_test.rb
index <HASH>..<HASH> 100644
--- a/test/worker_test.rb
+++ b/test/worker_test.rb
@@ -174,24 +174,4 @@ class WorkerTest < QCTest
assert_equal(42, r)
assert_equal(0, worker.failed_count)
end
-
- def test_unlock_jobs_of_dead_workers
- # Insert a locked job
- adapter = QC::ConnAdapter.new
- query = "INSERT INTO #{QC::TABLE_NAME} (q_name, method, args, locked_by, locked_at) VALUES ('whatever', 'Kernel.puts', '[\"ok?\"]', 0, (CURRENT_TIMESTAMP))"
- adapter.execute(query)
-
- # We should have no unlocked jobs
- query_locked_jobs = "SELECT * FROM #{QC::TABLE_NAME} WHERE locked_at IS NULL"
- res = adapter.connection.exec(query_locked_jobs)
- assert_equal(0, res.count)
-
- # Unlock the job
- QC::Worker.new.unlock_jobs_of_dead_workers
-
- # We should have an unlocked job now
- res = adapter.connection.exec(query_locked_jobs)
- assert_equal(1, res.count)
- end
-
end
|
move unlock_jobs_of_dead_workers
Reason for this are:
- it has nothing to do with the QC::Worker class
- we want to be able to call that in other circumstances than from the
Worker class
|
QueueClassic_queue_classic
|
train
|
7e198a9209c07b3317e4e0c75510f927e6c949d6
|
diff --git a/assets/javascripts/swfupload/handlers.js b/assets/javascripts/swfupload/handlers.js
index <HASH>..<HASH> 100755
--- a/assets/javascripts/swfupload/handlers.js
+++ b/assets/javascripts/swfupload/handlers.js
@@ -1,15 +1,5 @@
-/* Demo Note: This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
-The FileProgress class is not part of SWFUpload.
-*/
-
-
/* **********************
- Event Handlers
- These are my custom event handlers to make my
- web application behave the way I went when SWFUpload
- completes different tasks. These aren't part of the SWFUpload
- package. They are part of my application. Without these none
- of the actions SWFUpload makes will show up in my application.
+ Alchemy SWFUpload Event Handlers
********************** */
function fileQueued(file) {
try {
@@ -177,4 +167,5 @@ function queueComplete(numFilesUploaded) {
status.show();
status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
$('btnCancel').hide();
+ alchemy_window.close();
}
|
Feature: closing upload overlay after upload queue completes
|
AlchemyCMS_alchemy_cms
|
train
|
f828b8e66087f7b57a63721ace42acd5f98dc35b
|
diff --git a/src/main/java/org/boon/core/Conversions.java b/src/main/java/org/boon/core/Conversions.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/boon/core/Conversions.java
+++ b/src/main/java/org/boon/core/Conversions.java
@@ -397,8 +397,11 @@ public class Conversions {
}
public static <T extends Enum> T toEnum( Class<T> cls, String value ) {
- return (T) Enum.valueOf( cls, value );
-
+ try {
+ return (T) Enum.valueOf( cls, value );
+ } catch ( Exception ex ) {
+ return (T) Enum.valueOf( cls, value.toUpperCase().replace( '-', '_' ) );
+ }
}
diff --git a/src/main/java/org/boon/core/reflection/BeanUtils.java b/src/main/java/org/boon/core/reflection/BeanUtils.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/boon/core/reflection/BeanUtils.java
+++ b/src/main/java/org/boon/core/reflection/BeanUtils.java
@@ -718,10 +718,11 @@ public class BeanUtils {
}
}
+
private static <T> T fieldByFieldCopy( T item ) {
final Class<T> aClass = (Class<T>) item.getClass();
- Map<String, FieldAccess> fields = Reflection.getAllAccessorFields( item.getClass() );
+ Map<String, FieldAccess> fields = Reflection.getAllAccessorFields( aClass );
T clone = Reflection.newInstance( aClass );
@@ -742,7 +743,6 @@ public class BeanUtils {
}
} else if (field.isPrimitive()) {
field.setValue( clone, field.getValue( item ) );
-
} else {
Object value = field.getObject( item );
@@ -761,4 +761,93 @@ public class BeanUtils {
}
+
+
+ public static void copyProperties( Object src, Object dest ) {
+ fieldByFieldCopy( src, dest );
+ }
+
+ private static void fieldByFieldCopy( Object src, Object dst ) {
+
+ final Class<?> srcClass = src.getClass();
+ Map<String, FieldAccess> srcFields = Reflection.getAllAccessorFields( srcClass );
+
+
+ final Class<?> dstClass = dst.getClass();
+ Map<String, FieldAccess> dstFields = Reflection.getAllAccessorFields ( dstClass );
+
+ for ( FieldAccess srcField : srcFields.values() ) {
+ try {
+ if ( srcField.isStatic() ) {
+ continue;
+ }
+
+ FieldAccess dstField = dstFields.get ( srcField.getName() );
+ if (dstField == null ) {
+ continue;
+ }
+
+ if (!srcField.isPrimitive() && !Typ.isBasicType( srcField.getType() )) {
+
+
+
+ Object srcValue = srcField.getObject( src );
+ if (srcValue == null) {
+ if ( !dstField.isPrimitive () ) {
+ dstField.setObject(dst, null);
+ }
+ } else {
+
+ /* if the field is compatible then set it. */
+ if ( dstField.getType() == srcValue.getClass() ||
+ Typ.isSuperType ( dstField.getType(), srcValue.getClass() ) ) {
+
+ dstField.setObject(dst, copy( srcField.getObject ( src ) ));
+ } else {
+ if ( srcValue instanceof Collection && dstField.getComponentClass() != null
+ && Typ.isCollection ( dstField.getType () ) ) {
+ Collection srcCollection = (Collection) srcValue;
+
+ Collection dstCollection = Reflection.createCollection( dstField.getType(), srcCollection.size() );
+ for ( Object srcComponentValue : srcCollection ) {
+
+ Object newInstance = Reflection.newInstance( dstField.getComponentClass() );
+ fieldByFieldCopy( srcComponentValue, newInstance );
+ dstCollection.add ( newInstance );
+ }
+
+ dstField.setObject ( dst, dstCollection );
+
+ } else {
+ if (dstField.typeEnum () == Type.ABSTRACT || dstField.typeEnum () == Type.INTERFACE) {
+ //no op
+ } else {
+ Object newInstance = Reflection.newInstance( dstField.getType() );
+ fieldByFieldCopy( srcField.getObject( src ), newInstance );
+ dstField.setObject ( dst, newInstance );
+ }
+ }
+ }
+ }
+ } else if (srcField.isPrimitive()) {
+ dstField.setValue( dst, srcField.getValue( src ) );
+
+ } else {
+ Object value = srcField.getObject( src );
+
+ if (value == null) {
+ if ( !dstField.isPrimitive () ) {
+ dstField.setObject(dst, null);
+ }
+ } else {
+ dstField.setValue( dst, value );
+ }
+
+ }
+ }catch (Exception ex) {
+ Exceptions.handle( ex );
+ }
+ }
+ }
+
}
|
Added a new feature to copy large JSON feeds into smaller JSON feeds or rather Large Java objects into smaller once. It walks the tree recursively. This allows you to have DTOs that are smaller than what you have in memory but have the structure. I also made Conversion handle enum conversion a bit easier for common cases.
|
boonproject_boon
|
train
|
e4f061f7c9e1a8f35e5f02d1c7543dbf13c40b0a
|
diff --git a/src/language/CSSUtils.js b/src/language/CSSUtils.js
index <HASH>..<HASH> 100644
--- a/src/language/CSSUtils.js
+++ b/src/language/CSSUtils.js
@@ -1089,6 +1089,17 @@ define(function (require, exports, module) {
if (/[\{\}\;]/.test(ctx.token.string)) {
break;
}
+
+ // Stop once we've reached a <style ...> tag
+ if (ctx.token.string === "<style") {
+ // Remove everything up to end-of-tag from selector
+ var eotIndex = selector.indexOf(">");
+ if (eotIndex !== -1) {
+ selector = selector.substring(eotIndex + 1);
+ }
+ break;
+ }
+
selector = ctx.token.string + selector;
}
if (!TokenUtils.movePrevToken(ctx)) {
|
fix parsing of first selector in embedded style block
|
adobe_brackets
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.