hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
ad9dd5150d5f1c3aef55371ecbe89a9abe0b3edb
diff --git a/sprd/entity/TextConfiguration.js b/sprd/entity/TextConfiguration.js index <HASH>..<HASH> 100644 --- a/sprd/entity/TextConfiguration.js +++ b/sprd/entity/TextConfiguration.js @@ -517,7 +517,7 @@ define(['sprd/entity/Configuration', "flow", 'sprd/entity/Size', 'underscore', ' var lineElement = line.children[l].item; var tspan = { - content: [lineElement.$.text.replace(/\xa0/g)], + content: [lineElement.$.text.replace(/\xa0/g, "")], lineWidth: text.width };
Forgot second parameter, which would use replace it with 'undefined '.
spreadshirt_rAppid.js-sprd
train
08668f363f65e63774935cf185a9bc5dfedbf985
diff --git a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestFormatMacro.java b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestFormatMacro.java index <HASH>..<HASH> 100644 --- a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestFormatMacro.java +++ b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestFormatMacro.java @@ -30,6 +30,7 @@ import org.xwiki.component.annotation.Component; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.FormatBlock; import org.xwiki.rendering.block.WordBlock; +import org.xwiki.rendering.block.match.ClassBlockMatcher; import org.xwiki.rendering.listener.Format; import org.xwiki.rendering.macro.AbstractNoParameterMacro; import org.xwiki.rendering.macro.MacroExecutionException; @@ -56,7 +57,8 @@ public class TestFormatMacro extends AbstractNoParameterMacro public List<Block> execute(Object parameters, String content, MacroTransformationContext context) throws MacroExecutionException { - int wordCount = context.getXDOM().getChildrenByType(WordBlock.class, true).size(); + int wordCount = context.getXDOM().getBlocks( + new ClassBlockMatcher(WordBlock.class), Block.Axes.DESCENDANT).size(); return Arrays.<Block>asList(new FormatBlock(Arrays.<Block>asList( new WordBlock("formatmacro" + wordCount)), Format.NONE, Collections.singletonMap("param", "value"))); } diff --git a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleInlineMacro.java b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleInlineMacro.java index <HASH>..<HASH> 100644 --- a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleInlineMacro.java +++ b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleInlineMacro.java @@ -29,6 +29,7 @@ import org.xwiki.component.annotation.Component; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.ParagraphBlock; import org.xwiki.rendering.block.WordBlock; +import org.xwiki.rendering.block.match.ClassBlockMatcher; import org.xwiki.rendering.macro.AbstractNoParameterMacro; import org.xwiki.rendering.macro.MacroExecutionException; import org.xwiki.rendering.transformation.MacroTransformationContext; @@ -53,7 +54,8 @@ public class TestSimpleInlineMacro extends AbstractNoParameterMacro public List<Block> execute(Object parameters, String content, MacroTransformationContext context) throws MacroExecutionException { - int wordCount = context.getXDOM().getChildrenByType(WordBlock.class, true).size(); + int wordCount = context.getXDOM().getBlocks( + new ClassBlockMatcher(WordBlock.class), Block.Axes.DESCENDANT).size(); List<Block> result = Arrays.<Block> asList(new WordBlock("simpleinlinemacro" + wordCount)); return context.isInline() ? result : Arrays.<Block> asList(new ParagraphBlock(result)); diff --git a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleMacro.java b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleMacro.java index <HASH>..<HASH> 100644 --- a/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleMacro.java +++ b/xwiki-rendering-transformations/xwiki-rendering-transformation-macro/src/test/java/org/xwiki/rendering/internal/transformation/macro/TestSimpleMacro.java @@ -29,6 +29,7 @@ import org.xwiki.component.annotation.Component; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.ParagraphBlock; import org.xwiki.rendering.block.WordBlock; +import org.xwiki.rendering.block.match.ClassBlockMatcher; import org.xwiki.rendering.macro.AbstractNoParameterMacro; import org.xwiki.rendering.macro.MacroExecutionException; import org.xwiki.rendering.transformation.MacroTransformationContext; @@ -53,7 +54,8 @@ public class TestSimpleMacro extends AbstractNoParameterMacro public List<Block> execute(Object parameters, String content, MacroTransformationContext context) throws MacroExecutionException { - int wordCount = context.getXDOM().getChildrenByType(WordBlock.class, true).size(); + int wordCount = context.getXDOM().getBlocks( + new ClassBlockMatcher(WordBlock.class), Block.Axes.DESCENDANT).size(); return Arrays.<Block>asList(new ParagraphBlock(Arrays.<Block>asList(new WordBlock("simplemacro" + wordCount)))); }
[Misc] Remove deprecated usages
xwiki_xwiki-rendering
train
1f22701151be5af60297a352c8f03686627ff7aa
diff --git a/test/integration/buildclient_test.go b/test/integration/buildclient_test.go index <HASH>..<HASH> 100644 --- a/test/integration/buildclient_test.go +++ b/test/integration/buildclient_test.go @@ -170,13 +170,16 @@ func NewTestBuildOpenshift(t *testing.T) *testBuildOpenshift { t.Fatalf("Unable to configure Kubelet client: %v", err) } - kmaster := master.New(&master.Config{ + handlerContainer := master.NewHandlerContainer(osMux) + + _ = master.New(&master.Config{ Client: kubeClient, EtcdHelper: etcdHelper, HealthCheckMinions: false, KubeletClient: kubeletClient, - APIPrefix: "/api/v1beta1", + APIPrefix: "/api", AdmissionControl: admit.NewAlwaysAdmit(), + RestfulContainer: handlerContainer, }) interfaces, _ := latest.InterfacesFor(latest.Version) @@ -188,9 +191,6 @@ func NewTestBuildOpenshift(t *testing.T) *testBuildOpenshift { "buildConfigs": buildconfigregistry.NewREST(buildEtcd), } - handlerContainer := master.NewHandlerContainer(osMux) - apiserver.NewAPIGroupVersion(kmaster.API_v1beta1()).InstallREST(handlerContainer, "/api", "v1beta1") - osPrefix := "/osapi/v1beta1" apiserver.NewAPIGroupVersion(storage, latest.Codec, osPrefix, interfaces.MetadataAccessor, admit.NewAlwaysAdmit()).InstallREST(handlerContainer, "/osapi", "v1beta1") @@ -207,11 +207,13 @@ func NewTestBuildOpenshift(t *testing.T) *testBuildOpenshift { DockerBuildStrategy: &buildstrategy.DockerBuildStrategy{ Image: "test-docker-builder", UseLocalImages: false, + Codec: latest.Codec, }, STIBuildStrategy: &buildstrategy.STIBuildStrategy{ Image: "test-sti-builder", TempDirectoryCreator: buildstrategy.STITempDirectoryCreator, UseLocalImages: false, + Codec: latest.Codec, }, Stop: openshift.stop, } diff --git a/test/integration/deploy_trigger_test.go b/test/integration/deploy_trigger_test.go index <HASH>..<HASH> 100644 --- a/test/integration/deploy_trigger_test.go +++ b/test/integration/deploy_trigger_test.go @@ -337,13 +337,16 @@ func NewTestOpenshift(t *testing.T) *testOpenshift { t.Fatalf("Unable to configure Kubelet client: %v", err) } - kmaster := master.New(&master.Config{ + handlerContainer := master.NewHandlerContainer(osMux) + + _ = master.New(&master.Config{ Client: kubeClient, EtcdHelper: etcdHelper, HealthCheckMinions: false, KubeletClient: kubeletClient, - APIPrefix: "/api/v1beta1", + APIPrefix: "/api", AdmissionControl: admit.NewAlwaysAdmit(), + RestfulContainer: handlerContainer, }) interfaces, _ := latest.InterfacesFor(latest.Version) @@ -372,9 +375,6 @@ func NewTestOpenshift(t *testing.T) *testOpenshift { "buildConfigs": buildconfigregistry.NewREST(buildEtcd), } - handlerContainer := master.NewHandlerContainer(osMux) - apiserver.NewAPIGroupVersion(kmaster.API_v1beta1()).InstallREST(handlerContainer, "/api", "v1beta1") - osPrefix := "/osapi/v1beta1" apiserver.NewAPIGroupVersion(storage, v1beta1.Codec, osPrefix, interfaces.MetadataAccessor, admit.NewAlwaysAdmit()).InstallREST(handlerContainer, "/osapi", "v1beta1") diff --git a/test/integration/imageclient_test.go b/test/integration/imageclient_test.go index <HASH>..<HASH> 100644 --- a/test/integration/imageclient_test.go +++ b/test/integration/imageclient_test.go @@ -225,12 +225,15 @@ func NewTestImageOpenShift(t *testing.T) *testImageOpenshift { t.Fatalf("Unable to configure Kubelet client: %v", err) } - kmaster := master.New(&master.Config{ + handlerContainer := master.NewHandlerContainer(osMux) + + _ = master.New(&master.Config{ Client: kubeClient, EtcdHelper: etcdHelper, HealthCheckMinions: false, KubeletClient: kubeletClient, APIPrefix: "/api/v1beta1", + RestfulContainer: handlerContainer, }) interfaces, _ := latest.InterfacesFor(latest.Version) @@ -244,9 +247,6 @@ func NewTestImageOpenShift(t *testing.T) *testImageOpenshift { "imageRepositoryTags": imagerepositorytag.NewREST(imageEtcd, imageEtcd), } - handlerContainer := master.NewHandlerContainer(osMux) - apiserver.NewAPIGroupVersion(kmaster.API_v1beta1()).InstallREST(handlerContainer, "/api", "v1beta1") - osPrefix := "/osapi/v1beta1" apiserver.NewAPIGroupVersion(storage, latest.Codec, osPrefix, interfaces.MetadataAccessor, admit.NewAlwaysAdmit()).InstallREST(handlerContainer, "/osapi", "v1beta1")
Integration tests should let master load its own API
openshift_origin
train
0a49de4eb551510cf4aafa7d212ec2bb8041f642
diff --git a/image/tarexport/save.go b/image/tarexport/save.go index <HASH>..<HASH> 100644 --- a/image/tarexport/save.go +++ b/image/tarexport/save.go @@ -6,6 +6,7 @@ import ( "io" "io/ioutil" "os" + "path" "path/filepath" "runtime" "time" @@ -219,7 +220,11 @@ func (s *saveSession) save(outStream io.Writer) error { } for _, l := range imageDescr.layers { - layers = append(layers, filepath.Join(l, legacyLayerFileName)) + // IMPORTANT: We use path, not filepath here to ensure the layers + // in the manifest use Unix-style forward-slashes. Otherwise, a + // Linux image saved from LCOW won't be able to be imported on + // LCOL. + layers = append(layers, path.Join(l, legacyLayerFileName)) } manifest = append(manifest, manifestItem{
LCOW: Write saved manifest.json in Unix paths
moby_moby
train
20d0145b868b6f1648aabaa46d1caced25e46a46
diff --git a/src/Aura/View/Helper/AbstractHelper.php b/src/Aura/View/Helper/AbstractHelper.php index <HASH>..<HASH> 100644 --- a/src/Aura/View/Helper/AbstractHelper.php +++ b/src/Aura/View/Helper/AbstractHelper.php @@ -47,10 +47,12 @@ abstract class AbstractHelper * @param array|Traversable $attribs From this array, each key-value pair * is converted to an attribute name and value. * + * @param array $skip Skip attributes listed in this array. + * * @return string The attribute string. * */ - protected function attribs($attribs) + protected function attribs($attribs, array $skip = []) { // pre-empt processing if (! $attribs) { @@ -60,6 +62,11 @@ abstract class AbstractHelper $html = []; foreach ($attribs as $key => $val) { + // skip this attribute? + if (in_array($key, $skip)) { + continue; + } + // space-separate multiple values if (is_array($val)) { $val = implode(' ', $val); diff --git a/src/Aura/View/Helper/Attribs.php b/src/Aura/View/Helper/Attribs.php index <HASH>..<HASH> 100644 --- a/src/Aura/View/Helper/Attribs.php +++ b/src/Aura/View/Helper/Attribs.php @@ -24,11 +24,13 @@ class Attribs extends AbstractHelper * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * + * @param array $skip Skip attributes listed in this array. + * * @return string The string of attributes. * */ - public function __invoke($attribs) + public function __invoke($attribs, array $skip = []) { - return $this->attribs($attribs); + return $this->attribs($attribs, $skip); } }
for attribs helper, add a param that allows you to skip (blacklist) attribs in the array
auraphp_Aura.View
train
35807f07648925bbd8d7848260e424a052fa344c
diff --git a/lib/transpiler.js b/lib/transpiler.js index <HASH>..<HASH> 100644 --- a/lib/transpiler.js +++ b/lib/transpiler.js @@ -22,6 +22,7 @@ function shimSelector(selector, elementName) { selectorRegexes = [ [/^:host\(([^:]+)\)$/, elementName+'$1'], [/^:host(:hover|:active|:focus)$/, elementName+'$1'], + [/^:host(\[[^:]+\])$/, elementName+'$1'], [/^:host$/, elementName], [/^:ancestor\(([^:]+)\)$/, '$1 '+elementName], // deprecated; replaced by :host-context [/^:host-context\(([^:]+)\)$/, '$1 '+elementName], diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bosonic-transpiler", - "version": "0.3.1", + "version": "0.3.2", "description": "A node.js library that transpiles to-the-spec Web Components into polyfilled JavaScript", "main": "index.js", "scripts": { diff --git a/test/transpiler.js b/test/transpiler.js index <HASH>..<HASH> 100644 --- a/test/transpiler.js +++ b/test/transpiler.js @@ -39,6 +39,7 @@ exports.testStylesShiming = function(test) { var tests = [ [':host', 'b-dummy'], [':host:hover', 'b-dummy:hover'], + [':host[visible]', 'b-dummy[visible]'], [':host(.cssClass)', 'b-dummy.cssClass'], [':ancestor(.cssClass)', '.cssClass b-dummy'], [':host-context(.cssClass)', '.cssClass b-dummy'],
Added :host[<attribute>] support
bosonic-labs_transpiler
train
75e2dbbfccff84aa1eebde69b33c79e534f4054a
diff --git a/tests/test_gitcommit.py b/tests/test_gitcommit.py index <HASH>..<HASH> 100644 --- a/tests/test_gitcommit.py +++ b/tests/test_gitcommit.py @@ -65,3 +65,74 @@ def test_commit_reading(repo): assert c.get_path_data('sub/dir/dest.txt') == 'baz' assert c.get_path_mode('sub/dir/dest.txt') == 0100644 + + with pytest.raises(KeyError): + assert c.get_path_data('does.not.exist') + + # directories return None and have just the dir flag set + assert c.get_path_data('sub') is None + assert c.get_path_mode('sub') == 0040000 + + +def test_commit_id_setting(repo): + master = repo.refs['refs/heads/master'] + + c = MalleableCommit.from_existing(repo, master) + baz = c.get_path_id('sub/dir/dest.txt') + + old_tree_id = c.tree.id + + c.set_path_id('foo.txt', baz) + assert c.get_path_data('foo.txt') == 'baz' + assert c.tree.id != old_tree_id + + +def test_commit_content_writing(repo): + master = repo.refs['refs/heads/master'] + + c = MalleableCommit.from_existing(repo, master) + c.set_path_data('foo.txt', 'NEW') + assert c.get_path_data('foo.txt') == 'NEW' + + c.set_path_data('new_stuff.txt', 'two') + assert c.get_path_data('new_stuff.txt') == 'two' + + c.set_path_data('with/path/new', 'three') + assert c.get_path_data('with/path/new') == 'three' + assert c.get_path_data('with/path') is None + assert c.get_path_data('with') is None + + +def test_commit_overwrites_files_with_dirs(repo): + master = repo.refs['refs/heads/master'] + + c = MalleableCommit.from_existing(repo, master) + assert c.get_path_data('foo.txt') == 'bar' + + c.set_path_data('foo.txt/bla', 'NEW') + assert c.get_path_data('foo.txt/bla') == 'NEW' + assert c.get_path_data('foo.txt') is None + + +def test_commit_changes_mode(repo): + master = repo.refs['refs/heads/master'] + + c = MalleableCommit.from_existing(repo, master) + c.set_path_data('xyz.txt', 'NEW', mode=0100755) + assert c.get_path_data('xyz.txt') == 'NEW' + assert c.get_path_mode('xyz.txt') == 0100755 + + +def test_commit_persists_changes(dummy_repo, repo): + master = repo.refs['refs/heads/master'] + + c = MalleableCommit.from_existing(repo, master) + c.set_path_data('xyz.txt', 'NEW', mode=0100755) + tree_id = c.tree.id + c.save() + + r = Repo(dummy_repo) + t = r[tree_id] + + b_id = t['xyz.txt'][1] + assert r[b_id].data == 'NEW'
More tests for new Git Interface.
mbr_unleash
train
b26ede3bc4750bb38fe58a20563ea9932808a521
diff --git a/src/org/openscience/cdk/graph/rebond/Bspt.java b/src/org/openscience/cdk/graph/rebond/Bspt.java index <HASH>..<HASH> 100644 --- a/src/org/openscience/cdk/graph/rebond/Bspt.java +++ b/src/org/openscience/cdk/graph/rebond/Bspt.java @@ -471,26 +471,3 @@ public final class Bspt { } } -class Point implements Bspt.Tuple { - double x; - double y; - double z; - - Point(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - public double getDimValue(int dim) { - if (dim == 0) - return x; - if (dim == 1) - return y; - return z; - } - - public String toString() { - return "<" + x + "," + y + "," + z + ">"; - } -}
Removed Point class which is now in separate source file git-svn-id: <URL>
cdk_cdk
train
1b076e383a92246446f5c81088fd12313eebded8
diff --git a/bookstore/tests/test_archive.py b/bookstore/tests/test_archive.py index <HASH>..<HASH> 100644 --- a/bookstore/tests/test_archive.py +++ b/bookstore/tests/test_archive.py @@ -2,6 +2,7 @@ import asyncio import pytest import json +import logging from bookstore.archive import ArchiveRecord, BookstoreContentsArchiver from nbformat.v4 import new_notebook @@ -28,14 +29,18 @@ async def test_archive_failure_on_no_lock(): @pytest.mark.asyncio -async def test_archive_abort_with_lock(): +async def test_archive_abort_with_lock(caplog): + """Acquire a lock in advance so that when the archiver attempts to archive, it will abort.""" + archiver = BookstoreContentsArchiver() record = ArchiveRecord('my_notebook_path.ipynb', json.dumps(new_notebook()), 100.2) lock = asyncio.Lock() archiver.path_locks['my_notebook_path.ipynb'] = lock async with lock: - await archiver.archive(record) + with caplog.at_level(logging.INFO): + await archiver.archive(record) + assert 'Skipping archive of my_notebook_path.ipynb' in caplog.text def test_pre_save_hook():
Add log capture to skip test to more strongly ensure code-path is hit
nteract_bookstore
train
cd5faf0e89f3b7fb787c5a2b64d74805f8f6b5c8
diff --git a/src/Keboola/StorageApi/Client.php b/src/Keboola/StorageApi/Client.php index <HASH>..<HASH> 100644 --- a/src/Keboola/StorageApi/Client.php +++ b/src/Keboola/StorageApi/Client.php @@ -857,7 +857,8 @@ class Client /** * - * Parse CSV into array + * Parse CSV string into array + * uses str_getcsv function * * @static * @param $string @@ -866,7 +867,7 @@ class Client * @param $enclosure string CSV field enclosure * @return array */ - public static function parseCSV($csv, $header=true, $delimiter=",", $enclosure='"', $escape=null) + public static function parseCsv($csv, $header=true, $delimiter=",", $enclosure='"', $escape=null) { $data = array(); $headers = array(); diff --git a/tests/Keboola/StorageApi/TablesTest.php b/tests/Keboola/StorageApi/TablesTest.php index <HASH>..<HASH> 100644 --- a/tests/Keboola/StorageApi/TablesTest.php +++ b/tests/Keboola/StorageApi/TablesTest.php @@ -194,8 +194,10 @@ class Keboola_StorageApi_Buckets_TablesTest extends PHPUnit_Framework_TestCase public function testParseCsv() { $csvData = '"column1","column2"' . "\n" . '"value1","value2"'; - $data1 = \Keboola\StorageApi\Client::parseCSV($csvData); - $data2 = \Keboola\StorageApi\Client::parseCSV($csvData, false); + + $data1 = \Keboola\StorageApi\Client::parseCsv($csvData); + $data2 = \Keboola\StorageApi\Client::parseCsv($csvData, false); + $this->assertEquals($data1[0]["column1"], "value1", 'Parse CSV'); $this->assertEquals($data1[0]["column2"], "value2", 'Parse CSV'); $this->assertEquals($data2[0][0], "column1", 'Parse CSV');
corrected camelcase for parseCsv method
keboola_storage-api-php-client
train
e28fe5b1cb6210aa8fdc6ca5100418c916eee891
diff --git a/pymatgen/io/gwwrapper/GWhelpers.py b/pymatgen/io/gwwrapper/GWhelpers.py index <HASH>..<HASH> 100644 --- a/pymatgen/io/gwwrapper/GWhelpers.py +++ b/pymatgen/io/gwwrapper/GWhelpers.py @@ -33,7 +33,7 @@ def now(): def s_name(structure): - name_ = str(structure.composition.reduced_formula) + '_' + str(structure.item) + name_ = str(structure.composition.reduced_formula) # + '_' + str(structure.item) return name_ @@ -250,7 +250,7 @@ def is_converged(hartree_parameters, structure, return_values=False): def store_conv_results(name, folder): print "| Storing results for %s" % name os.mkdir(folder) - for data_file in ['conv_res', 'full_res', 'log', 'conv.log', 'str']: + for data_file in ['conv_res', 'full_res', 'log', 'conv.log', 'str', 'fitdat', 'convdat']: try: os.rename(name+'.'+data_file, os.path.join(folder, name+'.'+data_file)) except OSError:
saving output in a central place Former-commit-id: fb<I>e<I>ae5dec<I>e6 [formerly <I>c5fd9de1d<I>f<I>aa8db<I>b<I>dd<I>e0] Former-commit-id: <I>c<I>d4c<I>ea<I>b4daa4da<I>e4ca<I>
materialsproject_pymatgen
train
4d4f8637d830ba9a72806fc127fe3497f7c0f23c
diff --git a/lib/plugins/aws/utils/credentials.js b/lib/plugins/aws/utils/credentials.js index <HASH>..<HASH> 100644 --- a/lib/plugins/aws/utils/credentials.js +++ b/lib/plugins/aws/utils/credentials.js @@ -44,7 +44,7 @@ const parseFileProfiles = (content) => { return profiles; }; -const writeCredentialsContent = (content) => +const writeCredentialsContent = async (content) => new BbPromise((resolve, reject) => writeFile( credentialsFilePath, @@ -72,7 +72,7 @@ const writeCredentialsContent = (content) => ); module.exports = { - resolveFileProfiles() { + async resolveFileProfiles() { return new BbPromise((resolve, reject) => { if (!credentialsFilePath) { resolve(new Map()); @@ -100,7 +100,7 @@ module.exports = { }; }, - saveFileProfiles(profiles) { + async saveFileProfiles(profiles) { return new BbPromise((resolve) => { if (!credentialsFilePath) { throw new ServerlessError( diff --git a/lib/plugins/aws/utils/resolveCfImportValue.js b/lib/plugins/aws/utils/resolveCfImportValue.js index <HASH>..<HASH> 100644 --- a/lib/plugins/aws/utils/resolveCfImportValue.js +++ b/lib/plugins/aws/utils/resolveCfImportValue.js @@ -2,7 +2,7 @@ const ServerlessError = require('../../../serverless-error'); -function resolveCfImportValue(provider, name, sdkParams = {}) { +async function resolveCfImportValue(provider, name, sdkParams = {}) { return provider.request('CloudFormation', 'listExports', sdkParams).then((result) => { const targetExportMeta = result.Exports.find((exportMeta) => exportMeta.Name === name); if (targetExportMeta) return targetExportMeta.Value; diff --git a/lib/plugins/aws/utils/resolveCfRefValue.js b/lib/plugins/aws/utils/resolveCfRefValue.js index <HASH>..<HASH> 100644 --- a/lib/plugins/aws/utils/resolveCfRefValue.js +++ b/lib/plugins/aws/utils/resolveCfRefValue.js @@ -2,7 +2,7 @@ const ServerlessError = require('../../../serverless-error'); -function resolveCfRefValue(provider, resourceLogicalId, sdkParams = {}) { +async function resolveCfRefValue(provider, resourceLogicalId, sdkParams = {}) { return provider .request( 'CloudFormation',
refactor: Configure promise returning functions as async (#<I>)
serverless_serverless
train
02f36cd5488b1331d9e41f7917c874c2444ef712
diff --git a/raiden/network/transport/matrix.py b/raiden/network/transport/matrix.py index <HASH>..<HASH> 100644 --- a/raiden/network/transport/matrix.py +++ b/raiden/network/transport/matrix.py @@ -681,8 +681,6 @@ class MatrixTransport(Runnable): return True def _receive_delivered(self, delivered: Delivered): - # FIXME: check if UDPTransport also checks Delivered sender and message presence - # checks there's a respective message on sender's queue for queue_identifier, events in self._queueids_to_queues.items(): if delivered.sender != queue_identifier.recipient: continue @@ -697,7 +695,7 @@ class MatrixTransport(Runnable): return self._raiden_service.handle_state_change( - ReceiveDelivered(delivered.delivered_message_identifier), + ReceiveDelivered(delivered.sender, delivered.delivered_message_identifier), ) self.log.debug( diff --git a/raiden/network/transport/udp/udp_transport.py b/raiden/network/transport/udp/udp_transport.py index <HASH>..<HASH> 100644 --- a/raiden/network/transport/udp/udp_transport.py +++ b/raiden/network/transport/udp/udp_transport.py @@ -19,8 +19,10 @@ from raiden.network.transport.udp.udp_utils import ( ) from raiden.raiden_service import RaidenService from raiden.settings import CACHE_TTL +from raiden.transfer import views from raiden.transfer.mediated_transfer.events import CHANNEL_IDENTIFIER_GLOBAL_QUEUE from raiden.transfer.queue_identifier import QueueIdentifier +from raiden.transfer.state import QueueIdsToQueues from raiden.transfer.state_change import ActionChangeNodeNetworkState, ReceiveDelivered from raiden.utils import pex, typing from raiden.utils.notifying_queue import NotifyingQueue @@ -543,7 +545,20 @@ class UDPTransport(Runnable): protocol, but it's required by this transport to provide the required properties. """ - processed = ReceiveDelivered(delivered.delivered_message_identifier) + for queue_identifier, events in self._queueids_to_queues.items(): + if delivered.sender != queue_identifier.recipient: + continue + if any(delivered.sender == event.recipient for event in events): + break + else: + self.log.debug( + 'Delivered message unknown', + sender=pex(delivered.sender), + message=delivered, + ) + return + + processed = ReceiveDelivered(delivered.sender, delivered.delivered_message_identifier) self.raiden.handle_state_change(processed) message_id = delivered.delivered_message_identifier @@ -618,3 +633,8 @@ class UDPTransport(Runnable): def set_node_network_state(self, node_address: typing.Address, node_state): state_change = ActionChangeNodeNetworkState(node_address, node_state) self.raiden.handle_state_change(state_change) + + @property + def _queueids_to_queues(self) -> QueueIdsToQueues: + chain_state = views.state_from_raiden(self._raiden_service) + return views.get_all_messagequeues(chain_state) diff --git a/raiden/tests/unit/test_node_queue.py b/raiden/tests/unit/test_node_queue.py index <HASH>..<HASH> 100644 --- a/raiden/tests/unit/test_node_queue.py +++ b/raiden/tests/unit/test_node_queue.py @@ -43,7 +43,7 @@ def test_delivered_message_must_clean_unordered_messages(chain_id): ) chain_state.queueids_to_queues[queue_identifier] = [first_message, second_message] - delivered_message = state_change.ReceiveDelivered(message_identifier) + delivered_message = state_change.ReceiveDelivered(recipient, message_identifier) iteration = node.handle_delivered(chain_state, delivered_message) new_queue = iteration.new_state.queueids_to_queues.get(queue_identifier, []) diff --git a/raiden/transfer/node.py b/raiden/transfer/node.py index <HASH>..<HASH> 100644 --- a/raiden/transfer/node.py +++ b/raiden/transfer/node.py @@ -482,7 +482,8 @@ def handle_delivered(chain_state: ChainState, state_change: ReceiveDelivered) -> filtered_queue = [ message for message in queue - if message.message_identifier != state_change.message_identifier + if message.message_identifier != state_change.message_identifier and + message.recipient != state_change.sender ] if not filtered_queue:
Update handle_delivered to verify sender
raiden-network_raiden
train
1c6e61cac6fa6bf54e19969c12f6ce52d0e2bd67
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ with open(os.path.join(os.path.dirname(__file__), 'CHANGES')) as fp: setup( name = 'pex', - version = '0.7.0', + version = '0.7.0-rc0', description = "The PEX packaging toolchain.", long_description = LONG_DESCRIPTION, url = 'https://github.com/pantsbuild/pex',
Make pex an rc0 release.
pantsbuild_pex
train
0be9a19da3051c0f6e912bc08e8d170d81373d8b
diff --git a/astrobase/lcproc.py b/astrobase/lcproc.py index <HASH>..<HASH> 100644 --- a/astrobase/lcproc.py +++ b/astrobase/lcproc.py @@ -44,10 +44,10 @@ import os.path import sys try: import cPickle as pickle - from cStringIO import StringIO as strio + from cStringIO import StringIO as StrIO except Exception as e: import pickle - from io import BytesIO as strio + from io import BytesIO as StrIO import gzip import glob import shutil @@ -5131,8 +5131,8 @@ def add_cmd_to_checkplot(cpx, cmdpkl, plt.title('%s - $%s$ CMD' % (cpdict['objectid'], thiscmd_title)) plt.gca().invert_yaxis() - # now save the figure to strio and put it back in the checkplot - cmdpng = strio() + # now save the figure to StrIO and put it back in the checkplot + cmdpng = StrIO() plt.savefig(cmdpng, bbox_inches='tight', pad_inches=0.0, format='png') cmdpng.seek(0)
lcproc: minor fix
waqasbhatti_astrobase
train
74fc3fb0cc4ea1ad5b60f2668810bdc32ff5c26f
diff --git a/core.py b/core.py index <HASH>..<HASH> 100755 --- a/core.py +++ b/core.py @@ -372,13 +372,13 @@ class Harvester: processor = _ProcessorPayloadTypeMultiPart() return processor - def connect_device(self, index): + def connect_device(self, item_id=0): if self.connecting_device or self.device_info_list is None: return # Instantiate a GenTL Device module. self._connecting_device = self.device_info_list[ - index].create_device() + item_id].create_device() # Then open it. try:
Allow clients to specify a set of unique information to connect a device
genicam_harvesters
train
866a9d89739c27086f42bc0b46caead682c83e07
diff --git a/client/components/navigation/browsable-list/browsable-list-item.js b/client/components/navigation/browsable-list/browsable-list-item.js index <HASH>..<HASH> 100644 --- a/client/components/navigation/browsable-list/browsable-list-item.js +++ b/client/components/navigation/browsable-list/browsable-list-item.js @@ -1,6 +1,6 @@ import PropTypes from 'prop-types' import React from 'react' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import classnames from 'classnames' if (require('exenv').canUseDOM) { diff --git a/client/components/navigation/sidenav/sidenav-list-item.js b/client/components/navigation/sidenav/sidenav-list-item.js index <HASH>..<HASH> 100644 --- a/client/components/navigation/sidenav/sidenav-list-item.js +++ b/client/components/navigation/sidenav/sidenav-list-item.js @@ -1,6 +1,6 @@ import PropTypes from 'prop-types' import React, { Component } from 'react' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import classnames from 'classnames' class SidenavListItem extends Component { diff --git a/client/components/navigation/sidenav/sidenav.js b/client/components/navigation/sidenav/sidenav.js index <HASH>..<HASH> 100644 --- a/client/components/navigation/sidenav/sidenav.js +++ b/client/components/navigation/sidenav/sidenav.js @@ -1,6 +1,6 @@ import PropTypes from 'prop-types' import React from 'react' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import { FormattedMessage } from 'react-intl' import * as paths from '~client/paths' diff --git a/client/mobilizations/components/list/items/more/menu-action.js b/client/mobilizations/components/list/items/more/menu-action.js index <HASH>..<HASH> 100644 --- a/client/mobilizations/components/list/items/more/menu-action.js +++ b/client/mobilizations/components/list/items/more/menu-action.js @@ -1,6 +1,6 @@ import PropTypes from 'prop-types' import React from 'react' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import classnames from 'classnames' const MenuAction = ({ diff --git a/routes/admin/authenticated/sidebar/templates-list/page.js b/routes/admin/authenticated/sidebar/templates-list/page.js index <HASH>..<HASH> 100644 --- a/routes/admin/authenticated/sidebar/templates-list/page.js +++ b/routes/admin/authenticated/sidebar/templates-list/page.js @@ -1,7 +1,7 @@ import PropTypes from 'prop-types' import React from 'react' import { FormattedMessage } from 'react-intl' -import { Link } from 'react-router' +import { Link } from 'react-router-dom' import classnames from 'classnames' import * as paths from '~client/paths'
chore: get react-router link component from react-router-dom
nossas_bonde-client
train
62948dcc437151a90de02f9671e7275854e8f3d0
diff --git a/sql-bricks.js b/sql-bricks.js index <HASH>..<HASH> 100644 --- a/sql-bricks.js +++ b/sql-bricks.js @@ -115,21 +115,29 @@ proto.offset = function offset(count) { return this; }; -proto.union = function union() { - var stmts = argsToArray(arguments); - if (!stmts.length) { - var stmt = new Statement('select'); - stmt.prev_stmt = this; - stmts = [stmt]; - } +var compounds = { + 'union': 'UNION', 'unionAll': 'UNION ALL', + 'intersect': 'INTERSECT', 'intersectAll': 'INTERSECT ALL', + 'minus': 'MINUS', 'minusAll': 'MINUS ALL', + 'except': 'EXCEPT', 'exceptAll': 'EXCEPT ALL' +}; +_.forEach(compounds, function(value, key) { + proto[key] = function() { + var stmts = argsToArray(arguments); + if (!stmts.length) { + var stmt = new Statement('select'); + stmt.prev_stmt = this; + stmts = [stmt]; + } - this.add(stmts, '_union'); - - if (stmt) - return stmt; - else - return this; -}; + this.add(stmts, '_' + key); + + if (stmt) + return stmt; + else + return this; + }; +}); proto.forUpdate = proto.forUpdateOf = function forUpdate() { this.for_update = true; @@ -290,12 +298,15 @@ proto.selectToString = function selectToString(opts) { if (this._offset != null) result += 'OFFSET ' + this._offset + ' '; - if (this._union != null) { - result += 'UNION '; - result += this._union.map(function(stmt) { - return stmt.toString(opts); - }).join(' UNION '); - } + _.forEach(compounds, function(value, key) { + var arr = this['_' + key]; + if (arr) { + result += value + ' '; + result += arr.map(function(stmt) { + return stmt.toString(opts); + }).join(' ' + value + ' '); + } + }.bind(this)); if (this.for_update) { result += 'FOR UPDATE ';
Added INTERSECT, MINUS, EXCEPT
CSNW_sql-bricks
train
67bfe6efa6de1837695286a609b13e734cfb517d
diff --git a/halo/halo.py b/halo/halo.py index <HASH>..<HASH> 100644 --- a/halo/halo.py +++ b/halo/halo.py @@ -77,7 +77,7 @@ class Halo(object): return Spinners['line'].value def clear(self): - if self._enabled is None: + if not self._enabled: return self sys.stdout.write('\r') @@ -112,7 +112,7 @@ class Halo(object): if text is not None: self._text = text - if self._enabled is None: + if not self._enabled: return self if sys.stdout.isatty() is True: @@ -125,7 +125,7 @@ class Halo(object): return self def stop(self): - if self._enabled is None: + if not self._enabled: return self if self._spinner_thread:
Halo: Enabled property is now a boolean
manrajgrover_halo
train
647d158b1722ce232b7ffced7a72cbd2f22b7dbb
diff --git a/dwave/cloud/solver.py b/dwave/cloud/solver.py index <HASH>..<HASH> 100644 --- a/dwave/cloud/solver.py +++ b/dwave/cloud/solver.py @@ -389,16 +389,18 @@ class BaseUnstructuredSolver(BaseSolver): "we need to upload it first.") problem_id = self.upload_problem(problem).result() - body = json.dumps({ + body = { 'solver': self.id, 'data': encode_problem_as_ref(problem_id), 'type': problem_type, - 'params': params, - 'label': label, - }) - logger.trace("Sampling request encoded as: %s", body) + 'params': params + } + if label is not None: + body['label'] = label + body_data = json.dumps(body) + logger.trace("Sampling request encoded as: %s", body_data) - return body + return body_data def sample_problem(self, problem, problem_type=None, label=None, **params): """Sample from the specified problem. @@ -917,14 +919,16 @@ class StructuredSolver(BaseSolver): # transform some of the parameters in-place self._format_params(type_, combined_params) - body_data = json.dumps({ + body_dict = { 'solver': self.id, 'data': encode_problem_as_qp(self, linear, quadratic, offset, undirected_biases=undirected_biases), 'type': type_, - 'params': combined_params, - 'label': label, - }) + 'params': combined_params + } + if label is not None: + body_dict['label'] = label + body_data = json.dumps(body_dict) logger.trace("Encoded sample request: %s", body_data) body = Present(result=body_data)
Submit problem label only if specified by caller
dwavesystems_dwave-cloud-client
train
963cac046263b4444a14dd90e6f439c70b1b25f0
diff --git a/glad/parse.py b/glad/parse.py index <HASH>..<HASH> 100644 --- a/glad/parse.py +++ b/glad/parse.py @@ -33,7 +33,7 @@ class Spec(object): @classmethod def from_svn(cls): - return cls.from_url(cls.URL + cls.NAME + '.xml') + return cls.from_url(cls.API + cls.NAME + '.xml') @classmethod def fromstring(cls, string):
glad: fixed downlooading of specs
Dav1dde_glad
train
22f232ed4d6c82d649b02d0fea26978726659646
diff --git a/src/Forms/DateField.php b/src/Forms/DateField.php index <HASH>..<HASH> 100644 --- a/src/Forms/DateField.php +++ b/src/Forms/DateField.php @@ -7,6 +7,7 @@ use SilverStripe\i18n\i18n; use InvalidArgumentException; use SilverStripe\ORM\FieldType\DBDate; use SilverStripe\ORM\FieldType\DBDatetime; +use SilverStripe\ORM\ValidationResult; /** * Form used for editing a date stirng @@ -403,8 +404,16 @@ class DateField extends TextField _t( 'DateField.VALIDDATEMINDATE', "Your date has to be newer or matching the minimum allowed date ({date})", - ['date' => $this->internalToFrontend($min)] - ) + [ + 'date' => sprintf( + '<time datetime="%s">%s</time>', + $min, + $this->internalToFrontend($min) + ) + ] + ), + ValidationResult::TYPE_ERROR, + ValidationResult::CAST_HTML ); return false; } @@ -420,8 +429,16 @@ class DateField extends TextField _t( 'DateField.VALIDDATEMAXDATE', "Your date has to be older or matching the maximum allowed date ({date})", - ['date' => $this->internalToFrontend($max)] - ) + [ + 'date' => sprintf( + '<time datetime="%s">%s</time>', + $max, + $this->internalToFrontend($max) + ) + ] + ), + ValidationResult::TYPE_ERROR, + ValidationResult::CAST_HTML ); return false; } diff --git a/src/Forms/DatetimeField.php b/src/Forms/DatetimeField.php index <HASH>..<HASH> 100644 --- a/src/Forms/DatetimeField.php +++ b/src/Forms/DatetimeField.php @@ -6,6 +6,7 @@ use IntlDateFormatter; use InvalidArgumentException; use SilverStripe\i18n\i18n; use SilverStripe\ORM\FieldType\DBDatetime; +use SilverStripe\ORM\ValidationResult; /** * Form field used for editing date time strings. @@ -586,8 +587,16 @@ class DatetimeField extends TextField _t( 'DatetimeField.VALIDDATETIMEMINDATE', "Your date has to be newer or matching the minimum allowed date and time ({datetime})", - ['datetime' => $this->internalToFrontend($min)] - ) + [ + 'datetime' => sprintf( + '<time datetime="%s">%s</time>', + $min, + $this->internalToFrontend($min) + ) + ] + ), + ValidationResult::TYPE_ERROR, + ValidationResult::CAST_HTML ); return false; } @@ -603,8 +612,16 @@ class DatetimeField extends TextField _t( 'DatetimeField.VALIDDATEMAXDATETIME', "Your date has to be older or matching the maximum allowed date and time ({datetime})", - ['datetime' => $this->internalToFrontend($max)] - ) + [ + 'datetime' => sprintf( + '<time datetime="%s">%s</time>', + $max, + $this->internalToFrontend($max) + ) + ] + ), + ValidationResult::TYPE_ERROR, + ValidationResult::CAST_HTML ); return false; }
Mark up <time> in validation errors Allow better localisation of values in JS
silverstripe_silverstripe-framework
train
f7b0b2d06b0b4a5731370c88112ebe2713c7f2fa
diff --git a/src/dropbox-api.js b/src/dropbox-api.js index <HASH>..<HASH> 100644 --- a/src/dropbox-api.js +++ b/src/dropbox-api.js @@ -25,7 +25,7 @@ const updateRequestOptsFnList = [ } }, /* If resource requires upload stream, provide valid header */ - (requestOpts, {requiresReadableStream}, userOpts) => { + (requestOpts, {requiresReadableStream}, userOpts) => { if(requiresReadableStream) { requestOpts.headers['Content-Type']= 'application/octet-stream'; } @@ -42,7 +42,7 @@ const updateRequestOptsFnList = [ //if not RPC, then we have 2 options: download or uplad type request requestOpts.headers[DB_HEADER_API_ARGS] = isObject(userParameters) ? JSON.stringify(userParameters): ''; } - } + } ]; let config = {}; @@ -61,7 +61,7 @@ function generateResourcesHandlingFunctions(resourcesDescriptionList){ const requestOpts = createDefaultRequestOptObject(resourceDescription); //prepare requestOpts based on userOpts, config, etc. - updateRequestOptsFnList.forEach( + updateRequestOptsFnList.forEach( (updateRequestOptsFn) => updateRequestOptsFn(requestOpts, resourceDescription, userOpts, config) ); @@ -80,12 +80,16 @@ function generateResourcesHandlingFunctions(resourcesDescriptionList){ }else if(resourceCategory === DOWNLOAD_RESOURCE_CATEGORY) { return request(requestOpts, callback).pipe(createTransformStream()); }else { - //ordinary api call request + //ordinary api call request return request(requestOpts, callback); } function prepareCallback(userCb) { return (err, response, body) => { + if (err) { + return userCb(err); + } + const responseContentType = response.headers['content-type']; const statusCode = response.statusCode; @@ -103,7 +107,7 @@ function generateResourcesHandlingFunctions(resourcesDescriptionList){ }else { json.code = statusCode; return userCb(json); - } + } }, /* text type response */ 'text/plain; charset=utf-8': () => { @@ -115,7 +119,7 @@ function generateResourcesHandlingFunctions(resourcesDescriptionList){ code: statusCode, text: text }); - } + } } }; @@ -140,14 +144,14 @@ function generateAPIByResourcesDescriptionList(resourcesDescriptionList){ resource: userOpt.resource || '', readStream: userOpt.readStream }; - + const resourceName = opt.resource; if(resourceHandlingFunctions[resourceName]){ return resourceHandlingFunctions[resourceName](opt, cb); }else{ throwError(`resource "${opt.resource}" is invalid.`); } - }; + }; dropboxApi.authenticate = function(_config) { config = _config; return {
check for error before accessing response (#3)
adasq_dropbox-v2-api
train
e2825d22d0291c7024867fb80fa11eecba4b16bf
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -82,8 +82,8 @@ function partialApplier() { } } -methodPromify.partial = partialApplier.bind(methodPromify) -functionPromify.partial = partialApplier.bind(functionPromify) +methodPromify.part = partialApplier.bind(methodPromify) +functionPromify.part = partialApplier.bind(functionPromify) module.exports = functionPromify module.exports.method = methodPromify diff --git a/readme.md b/readme.md index <HASH>..<HASH> 100644 --- a/readme.md +++ b/readme.md @@ -17,6 +17,18 @@ var adapt = require('ugly-adapter') , promise = adapt(fs.readFile, 'data.text', 'utf8') ``` +```js +// helper to make partial application less verbose + +// less typing +var read = adapt.part(fs.readFile) + , promise = read('data.txt', 'utf8') + +// more typing +var read = adapt.bind(null, fs.readFile) + , promise = read('data.txt', 'utf8') +``` + # API ## Call a bare function @@ -37,7 +49,7 @@ var adapt = require('ugly-adapter') ```js var adapt = require('ugly-adapter') - , fn = adapt.partial(someFunction, ...someArgs) + , fn = adapt.part(someFunction, ...someArgs) , promise = fn(...someMoreArgs) ``` @@ -45,7 +57,7 @@ var adapt = require('ugly-adapter') ```js var adapt = require('ugly-adapter') - , fn = adapt.method.partial(object, methodName, ...someArgs) + , fn = adapt.method.part(object, methodName, ...someArgs) , promise = fn(...someMoreArgs) ``` @@ -53,9 +65,9 @@ Note about partial application. You can basically just move the `)(` around will ```js // these behave identically -var promise = adapt.partial(a, b)() -var promise = adapt.partial(a)(b) -var promise = adapt.partial()(a, b) +var promise = adapt.part(a, b)() +var promise = adapt.part(a)(b) +var promise = adapt.part()(a, b) ``` ## FAQ diff --git a/test/tests.js b/test/tests.js index <HASH>..<HASH> 100644 --- a/test/tests.js +++ b/test/tests.js @@ -233,7 +233,7 @@ describe(pkg.name, function(){ it('should partially apply', function(done){ co(function*(){ - var applied = adapt.partial(say, 'hi') + var applied = adapt.part(say, 'hi') var m = yield applied() assert.equal(m, 'hi') done() @@ -243,7 +243,7 @@ describe(pkg.name, function(){ it('should partially apply just one arg', function(done){ co(function*(){ - var applied = adapt.partial(say) + var applied = adapt.part(say) var m = yield applied('hi') assert.equal(m, 'hi') done() @@ -253,7 +253,7 @@ describe(pkg.name, function(){ it('should partially apply no args', function(done){ co(function*(){ - var applied = adapt.partial() + var applied = adapt.part() var m = yield applied(say, 'hi') assert.equal(m, 'hi') done() @@ -263,7 +263,7 @@ describe(pkg.name, function(){ it('partial application should error', function(done){ co(function*(){ - yield adapt.partial()(fail) + yield adapt.part()(fail) done(new Error('failed to fail')) }).catch(function(){ done() @@ -375,7 +375,7 @@ describe(pkg.name, function(){ co(function*(){ var fakeLib = { say: say } - var applied = adapt.method.partial(fakeLib, 'say', 'hi') + var applied = adapt.method.part(fakeLib, 'say', 'hi') var m = yield applied() assert.equal(m, 'hi') done() @@ -386,7 +386,7 @@ describe(pkg.name, function(){ co(function*(){ var fakeLib = { say: say } - var applied = adapt.method.partial(fakeLib, 'say') + var applied = adapt.method.part(fakeLib, 'say') var m = yield applied('hi') assert.equal(m, 'hi') done() @@ -397,7 +397,7 @@ describe(pkg.name, function(){ co(function*(){ var fakeLib = { say: say } - var applied = adapt.method.partial(fakeLib) + var applied = adapt.method.part(fakeLib) var m = yield applied('say', 'hi') assert.equal(m, 'hi') done() @@ -408,7 +408,7 @@ describe(pkg.name, function(){ co(function*(){ var fakeLib = { say: say } - var applied = adapt.method.partial() + var applied = adapt.method.part() var m = yield applied(fakeLib, 'say', 'hi') assert.equal(m, 'hi') done() @@ -419,7 +419,7 @@ describe(pkg.name, function(){ co(function*(){ var fakeLib = { fail: fail } - yield adapt.partial()(fakeLib, 'fail') + yield adapt.part()(fakeLib, 'fail') done(new Error('failed to fail')) }).catch(function(){ done()
renamed partial() to part() for brevity
greim_ugly-adapter
train
63cb3dc51d4c9544eaa72ab03484a2522933d654
diff --git a/api/v1/api.go b/api/v1/api.go index <HASH>..<HASH> 100644 --- a/api/v1/api.go +++ b/api/v1/api.go @@ -63,28 +63,28 @@ func compressionFilter(req *restful.Request, resp *restful.Response, chain *rest } // Labels used by the target schema. A target schema uniquely identifies a container. -var targetLabelNames = []string{ - sinksApi.LabelPodId, - sinksApi.LabelPodName, - sinksApi.LabelPodNamespace, - sinksApi.LabelPodNamespaceUID, - sinksApi.LabelContainerName, - sinksApi.LabelLabels, - sinksApi.LabelHostname, - sinksApi.LabelExternalID, +var targetLabelNames = map[string]struct{}{ + sinksApi.LabelPodId: struct{}{}, + sinksApi.LabelPodName: struct{}{}, + sinksApi.LabelPodNamespace: struct{}{}, + sinksApi.LabelContainerName: struct{}{}, + sinksApi.LabelLabels: struct{}{}, + sinksApi.LabelHostname: struct{}{}, + sinksApi.LabelHostID: struct{}{}, + sinksApi.LabelPodNamespaceUID: struct{}{}, } // Separates target schema labels from other labels. func separateLabels(labels map[string]string) (map[string]string, map[string]string) { targetLabels := make(map[string]string, len(targetLabelNames)) otherLabels := make(map[string]string, len(labels)-len(targetLabels)) - for _, label := range targetLabelNames { + for label, _ := range labels { // Ignore blank labels. - if labels[label] == "" { + if label == "" { continue } - if _, ok := labels[label]; ok { + if _, ok := targetLabelNames[label]; ok { targetLabels[label] = labels[label] } else { otherLabels[label] = labels[label] diff --git a/sinks/api/decoder.go b/sinks/api/decoder.go index <HASH>..<HASH> 100644 --- a/sinks/api/decoder.go +++ b/sinks/api/decoder.go @@ -63,7 +63,7 @@ func (self *defaultDecoder) getPodLabels(pod *source_api.Pod) map[string]string labels[LabelPodName] = pod.Name labels[LabelLabels] = LabelsToString(pod.Labels, ",") labels[LabelHostname] = pod.Hostname - labels[LabelExternalID] = pod.ExternalID + labels[LabelHostID] = pod.ExternalID return labels } @@ -84,7 +84,7 @@ func (self *defaultDecoder) getContainerSliceMetrics(containers []source_api.Con var result []Timeseries for index := range containers { labels[LabelHostname] = containers[index].Hostname - labels[LabelExternalID] = containers[index].ExternalID + labels[LabelHostID] = containers[index].ExternalID result = append(result, self.getContainerMetrics(&containers[index], copyLabels(labels))...) } diff --git a/sinks/api/decoder_v2.go b/sinks/api/decoder_v2.go index <HASH>..<HASH> 100644 --- a/sinks/api/decoder_v2.go +++ b/sinks/api/decoder_v2.go @@ -61,7 +61,7 @@ func (self *v2Decoder) getPodLabels(pod *cache.PodElement) map[string]string { labels[LabelPodName] = pod.Name labels[LabelLabels] = LabelsToString(pod.Labels, ",") labels[LabelHostname] = pod.Hostname - labels[LabelExternalID] = pod.ExternalID + labels[LabelHostID] = pod.ExternalID return labels } @@ -93,7 +93,7 @@ func (self *v2Decoder) getContainerMetrics(container *cache.ContainerElement, la return nil } labels[LabelContainerName] = container.Name - labels[LabelExternalID] = container.ExternalID + labels[LabelHostID] = container.ExternalID // One metric value per data point. var result []Timeseries labelsAsString := LabelsToString(labels, ",") diff --git a/sinks/api/supported_labels.go b/sinks/api/supported_labels.go index <HASH>..<HASH> 100644 --- a/sinks/api/supported_labels.go +++ b/sinks/api/supported_labels.go @@ -23,7 +23,7 @@ const ( LabelLabels = "labels" LabelHostname = "hostname" LabelResourceID = "resource_id" - LabelExternalID = "external_id" + LabelHostID = "host_id" ) // TODO(vmarmol): Things we should consider adding (note that we only get 10 labels): @@ -63,8 +63,8 @@ var allLabels = []LabelDescriptor{ Description: "Identifier(s) specific to a metric", }, { - Key: LabelExternalID, - Description: "Identifier specific to a node. Set by cloud provider or user", + Key: LabelHostID, + Description: "Identifier specific to a host. Set by cloud provider or user", }, }
Fix issue in handling metric specific labels in the API.
kubernetes-retired_heapster
train
b056b4a2b72c1835b7039c434fc286c3bb85ac97
diff --git a/src/components/lists/ListTile.js b/src/components/lists/ListTile.js index <HASH>..<HASH> 100755 --- a/src/components/lists/ListTile.js +++ b/src/components/lists/ListTile.js @@ -32,6 +32,13 @@ export default { }, computed: { + classes () { + return { + 'list__tile': true, + 'list__tile--disabled': this.disabled || this.item.disabled + } + }, + listUID () { return closestParentTag.call(this, 'v-list') } @@ -59,12 +66,11 @@ export default { }) } - let el, - list = [] + let el let data = { attrs: {}, - class: {}, + class: this.classes, props: {}, directives: [ { @@ -74,8 +80,6 @@ export default { ] } - data.class['list__tile'] = true - if (this.item.href && (this.router || this.item.router)) { el = 'router-link' data.props.to = this.item.href @@ -138,8 +142,6 @@ export default { children.push(this.$slots.default) - list.push(createElement(el, data, children)) - - return createElement('li', { 'class': { 'disabled': this.disabled || this.item.disabled } }, list) + return createElement(el, data, children) } } \ No newline at end of file diff --git a/src/components/lists/index.js b/src/components/lists/index.js index <HASH>..<HASH> 100755 --- a/src/components/lists/index.js +++ b/src/components/lists/index.js @@ -3,7 +3,7 @@ import { createSimpleFunctional } from '../../util/helpers' import ListGroup from './ListGroup.vue' import ListTile from './ListTile' -const ListRow = createSimpleFunctional('list__row', 'div') +const ListRow = createSimpleFunctional('list__row', 'li') const ListTileActionText = createSimpleFunctional('list__tile__action-text', 'span') const ListTileAvatar = createSimpleFunctional('list__tile__avatar', 'div') const ListTileContent = createSimpleFunctional('list__tile__content', 'div') @@ -13,11 +13,16 @@ const List = { name: 'list', props: { - twoLine: Boolean, - dense: Boolean, - threeLine: Boolean + items: { + type: Array, + default: () => [] + }, + + threeLine: Boolean, + + twoLine: Boolean }, computed: { @@ -39,6 +44,16 @@ const List = { } } + // if (this.items) { + // let items = [] + + // this.items.forEach(obj => { + // items.push( + // createElement('div') + // ) + // }) + // } + return createElement('ul', data, this.$slots.default) } } diff --git a/src/stylus/components/_lists.styl b/src/stylus/components/_lists.styl index <HASH>..<HASH> 100755 --- a/src/stylus/components/_lists.styl +++ b/src/stylus/components/_lists.styl @@ -40,6 +40,7 @@ line-height: 1 font-weight: 500 transition: $primary-transition + position: relative &:not(:only-child) margin-bottom: 4px @@ -151,7 +152,7 @@ font-weight: 500 &__header - .list__tile + &.list__tile .list__tile__title color: inherit
moved row from div to li
vuetifyjs_vuetify
train
f4f2a7b51a5693c027cce42ee310d61ba4b5eebf
diff --git a/lxd/backup.go b/lxd/backup.go index <HASH>..<HASH> 100644 --- a/lxd/backup.go +++ b/lxd/backup.go @@ -229,20 +229,28 @@ func backupGetInfo(r io.ReadSeeker) (*backupInfo, error) { // fixBackupStoragePool changes the pool information in the backup.yaml. This // is done only if the provided pool doesn't exist. In this case, the pool of // the default profile will be used. -func backupFixStoragePool(c *db.Cluster, b backupInfo) error { - // Get the default profile - _, profile, err := c.ProfileGet("default", "default") - if err != nil { - return err - } +func backupFixStoragePool(c *db.Cluster, b backupInfo, useDefaultPool bool) error { + var poolName string - _, v, err := shared.GetRootDiskDevice(profile.Devices) - if err != nil { - return err + if useDefaultPool { + // Get the default profile + _, profile, err := c.ProfileGet("default", "default") + if err != nil { + return err + } + + _, v, err := shared.GetRootDiskDevice(profile.Devices) + if err != nil { + return err + } + + poolName = v["pool"] + } else { + poolName = b.Pool } // Get the default's profile pool - _, pool, err := c.StoragePoolGet(v["pool"]) + _, pool, err := c.StoragePoolGet(poolName) if err != nil { return err } @@ -256,7 +264,24 @@ func backupFixStoragePool(c *db.Cluster, b backupInfo) error { // Change the pool in the backup.yaml backup.Pool = pool - backup.Container.Devices["root"]["pool"] = "default" + if backup.Container.Devices != nil { + devName, _, err := shared.GetRootDiskDevice(backup.Container.Devices) + if err != nil { + return err + } + + backup.Container.Devices[devName]["pool"] = poolName + + } + + if backup.Container.ExpandedDevices != nil { + devName, _, err := shared.GetRootDiskDevice(backup.Container.ExpandedDevices) + if err != nil { + return err + } + + backup.Container.ExpandedDevices[devName]["pool"] = poolName + } file, err := os.Create(path) if err != nil { diff --git a/lxd/container.go b/lxd/container.go index <HASH>..<HASH> 100644 --- a/lxd/container.go +++ b/lxd/container.go @@ -689,7 +689,8 @@ func containerCreateAsEmpty(d *Daemon, args db.ContainerArgs) (container, error) return c, nil } -func containerCreateFromBackup(s *state.State, info backupInfo, data io.ReadSeeker) error { +func containerCreateFromBackup(s *state.State, info backupInfo, data io.ReadSeeker, + customPool bool) error { var pool storage var fixBackupFile = false @@ -740,10 +741,9 @@ func containerCreateFromBackup(s *state.State, info backupInfo, data io.ReadSeek return err } - if fixBackupFile { - // Use the default pool since the pool provided in the backup.yaml - // doesn't exist. - err = backupFixStoragePool(s.Cluster, info) + if fixBackupFile || customPool { + // Update the pool + err = backupFixStoragePool(s.Cluster, info, !customPool) if err != nil { return err } diff --git a/lxd/containers_post.go b/lxd/containers_post.go index <HASH>..<HASH> 100644 --- a/lxd/containers_post.go +++ b/lxd/containers_post.go @@ -575,7 +575,7 @@ func createFromCopy(d *Daemon, project string, req *api.ContainersPost) Response return OperationResponse(op) } -func createFromBackup(d *Daemon, project string, data io.Reader) Response { +func createFromBackup(d *Daemon, project string, data io.Reader, pool string) Response { // Write the data to a temp file f, err := ioutil.TempFile("", "lxd_backup_") if err != nil { @@ -598,12 +598,17 @@ func createFromBackup(d *Daemon, project string, data io.Reader) Response { } bInfo.Project = project + // Override pool + if pool != "" { + bInfo.Pool = pool + } + run := func(op *operation) error { defer f.Close() // Dump tarball to storage f.Seek(0, 0) - err = containerCreateFromBackup(d.State(), *bInfo, f) + err = containerCreateFromBackup(d.State(), *bInfo, f, pool != "") if err != nil { return errors.Wrap(err, "Create container from backup") } @@ -659,7 +664,7 @@ func containersPost(d *Daemon, r *http.Request) Response { // If we're getting binary content, process separately if r.Header.Get("Content-Type") == "application/octet-stream" { - return createFromBackup(d, project, r.Body) + return createFromBackup(d, project, r.Body, r.Header.Get("X-LXD-pool")) } // Parse the request
lxd: Support overriding pool when importing backups
lxc_lxd
train
9ed5480ec221b44788cac8756a9cb8c40bdd56ce
diff --git a/src/Orchestra/View/FileViewFinder.php b/src/Orchestra/View/FileViewFinder.php index <HASH>..<HASH> 100644 --- a/src/Orchestra/View/FileViewFinder.php +++ b/src/Orchestra/View/FileViewFinder.php @@ -12,6 +12,8 @@ class FileViewFinder extends \Illuminate\View\FileViewFinder { { list($namespace, $view) = $this->getNamespaceSegments($name); + // Prepend global view paths to namespace hints path. This would + // allow theme to take priority if such view exist. $generatePath = function ($path) use ($namespace) { return "{$path}/packages/{$namespace}"; }; @@ -23,10 +25,11 @@ class FileViewFinder extends \Illuminate\View\FileViewFinder { /** * Set the active view paths. - * + * + * @param array $paths * @return array */ - public function setPaths($paths) + public function setPaths(array $paths) { $this->paths = $paths; }
Add additional docblock and typehint as array.
orchestral_view
train
a216f968c17358665dde6d062f8c0b59568b0423
diff --git a/src/frontend/org/voltdb/compiler/ProcedureCompiler.java b/src/frontend/org/voltdb/compiler/ProcedureCompiler.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/compiler/ProcedureCompiler.java +++ b/src/frontend/org/voltdb/compiler/ProcedureCompiler.java @@ -357,7 +357,7 @@ public abstract class ProcedureCompiler { String shortName = parts[parts.length - 1]; // add an entry to the catalog (using the full className) - final Procedure procedure = db.getProcedures().add(className); + final Procedure procedure = db.getProcedures().add(shortName); for (String groupName : procedureDescriptor.m_authGroups) { final Group group = db.getGroups().get(groupName); if (group == null) {
ENG-<I>: revert stmt-proc name change
VoltDB_voltdb
train
af11c8f140a01bd71a5c7b275a986d83a59d181e
diff --git a/lib/algoliasearch-rails.rb b/lib/algoliasearch-rails.rb index <HASH>..<HASH> 100644 --- a/lib/algoliasearch-rails.rb +++ b/lib/algoliasearch-rails.rb @@ -97,6 +97,7 @@ module AlgoliaSearch def use_serializer(serializer) @serializer = serializer + # instance_variable_set("@serializer", serializer) end def attribute(*names, &block) @@ -145,15 +146,7 @@ module AlgoliaSearch end def get_attribute_names(object) - res = if @attributes.nil? || @attributes.length == 0 - get_default_attributes(object).keys - else - @attributes.keys - end - - res += @additional_attributes.keys if @additional_attributes - - res + get_attributes(object).keys end def attributes_to_hash(attributes, object) @@ -165,25 +158,26 @@ module AlgoliaSearch end def get_attributes(object) - attributes = if @attributes.nil? || @attributes.length == 0 - if @serializer.nil? - get_default_attributes(object) - else - {} - end + # If a serializer is set, we ignore attributes + # everything should be done via the serializer + if not @serializer.nil? + attributes = @serializer.new(object).attributes else - if is_active_record?(object) - object.class.unscoped do - attributes_to_hash(@attributes, object) - end + if @attributes.nil? || @attributes.length == 0 + attributes = get_default_attributes(object) else - attributes_to_hash(@attributes, object) + if is_active_record?(object) + object.class.unscoped do + attributes = attributes_to_hash(@attributes, object) + end + else + attributes = attributes_to_hash(@attributes, object) + end + + attributes.merge!(attributes_to_hash(@additional_attributes, object)) end end - attributes.merge!(@serializer.new(object).attributes) if @serializer - attributes.merge!(attributes_to_hash(@additional_attributes, object)) - if @options[:sanitize] sanitizer = begin ::HTML::FullSanitizer.new diff --git a/spec/integration_spec.rb b/spec/integration_spec.rb index <HASH>..<HASH> 100644 --- a/spec/integration_spec.rb +++ b/spec/integration_spec.rb @@ -454,7 +454,7 @@ if defined?(ActiveModel::Serializer) class SerializedObject < ActiveRecord::Base include AlgoliaSearch - algoliasearch do + algoliasearch :index_name => safe_index_name('SerializedObject') do use_serializer SerializedObjectSerializer end end
Only use serializer if it's set
algolia_algoliasearch-rails
train
2c7c63e2fe8ca2e0204d3c422e0fe7eda0e35148
diff --git a/packages/@vue/cli-service/lib/Service.js b/packages/@vue/cli-service/lib/Service.js index <HASH>..<HASH> 100644 --- a/packages/@vue/cli-service/lib/Service.js +++ b/packages/@vue/cli-service/lib/Service.js @@ -91,7 +91,6 @@ module.exports = class Service { './commands/build', './commands/inspect', './commands/help', - './commands/ui', // config plugins are order sensitive './config/base', './config/css',
fix(ui): remove ui from built in plugin list
vuejs_vue-cli
train
40ed224749a9a1ab2ef80e2a44617600e30e3f0d
diff --git a/packages/babel-preset/index.js b/packages/babel-preset/index.js index <HASH>..<HASH> 100644 --- a/packages/babel-preset/index.js +++ b/packages/babel-preset/index.js @@ -229,9 +229,7 @@ function preset(api, explicitOptions = {}) { messagesDir: 'build/messages', }; - if (!development) { - presets.push([intlPreset, intlOpts]); - } + presets.push([intlPreset, intlOpts]); } return {
fix: include intl in dev mode Must be included all the time for ID generation to work
4Catalyzer_javascript
train
4bef264241d24aa1abdff01a11c138c0c0c2af51
diff --git a/lib/database/index.js b/lib/database/index.js index <HASH>..<HASH> 100644 --- a/lib/database/index.js +++ b/lib/database/index.js @@ -17,7 +17,11 @@ var log = require('../log') var exports = module.exports = function (env_config, callback) { if (!env_config.couch.run) { - return exports.checkExternalCouch(env_config.couch.url, callback) + return async.series([ + async.apply(mkdirp, env_config.hoodie.data_path), + async.apply(exports.checkExternalCouch, env_config.couch.url), + async.apply(install, env_config) + ], callback) } var project_dir = env_config.project_dir
fix(database): run full setup for external couch * * * This commit was sponsored by The Hoodie Firm. You can hire The Hoodie Firm: <URL>
hoodiehq_hoodie
train
b6c30d70e1dd3f123f8e07a41762a193d4bef3d3
diff --git a/sqlg-core/src/main/java/org/umlg/sqlg/structure/SqlgGraph.java b/sqlg-core/src/main/java/org/umlg/sqlg/structure/SqlgGraph.java index <HASH>..<HASH> 100644 --- a/sqlg-core/src/main/java/org/umlg/sqlg/structure/SqlgGraph.java +++ b/sqlg-core/src/main/java/org/umlg/sqlg/structure/SqlgGraph.java @@ -232,7 +232,13 @@ public class SqlgGraph implements Graph { } public static <G extends Graph> G open(final Configuration configuration) { - return open(configuration, createDataSource(configuration)); + SqlgDataSource dataSource = createDataSource(configuration); + try { + return open(configuration, dataSource); + } catch (Exception ex) { + dataSource.close(); + throw ex; + } } @SuppressWarnings("unchecked") @@ -246,7 +252,7 @@ public class SqlgGraph implements Graph { SqlgStartupManager sqlgStartupManager = new SqlgStartupManager(sqlgGraph); sqlgStartupManager.loadSqlgSchema(); sqlgGraph.buildVersion = sqlgStartupManager.getBuildVersion(); - return (G) sqlgGraph; + return (G)sqlgGraph; } public static <G extends Graph> G open(final String pathToSqlgProperties) { @@ -255,7 +261,13 @@ public class SqlgGraph implements Graph { Configuration configuration; try { configuration = new PropertiesConfiguration(pathToSqlgProperties); - return open(configuration, createDataSource(configuration)); + SqlgDataSource dataSource = createDataSource(configuration); + try { + return open(configuration, dataSource); + } catch (Exception ex) { + dataSource.close(); + throw ex; + } } catch (ConfigurationException e) { throw new RuntimeException(e); }
Close data source in case of error while opening sqlg graph
pietermartin_sqlg
train
9b157570e050daea7ecae1074ddc36ad2eed0184
diff --git a/anndata/base.py b/anndata/base.py index <HASH>..<HASH> 100644 --- a/anndata/base.py +++ b/anndata/base.py @@ -13,6 +13,7 @@ from copy import deepcopy import numpy as np from numpy import ma import pandas as pd +from numpy.lib.recfunctions import rec_drop_fields from pandas.core.index import RangeIndex from pandas.api.types import is_string_dtype, is_categorical from scipy import sparse @@ -156,6 +157,17 @@ class BoundRecArr(np.recarray): new = BoundRecArr(new, self._parent, self._attr) setattr(self._parent, self._attr, new) + def __delitem__(self, key): + """Delete field with name.""" + if key not in self.dtype.names: + raise ValueError( + 'Currently, can only delete single names from {}.' + .format(self.dtype.names) + ) + new_array = rec_drop_fields(self, key) + new = BoundRecArr(new_array, self._parent, self._attr) + setattr(self._parent, self._attr, new) + def to_df(self): """Convert to pandas dataframe.""" df = pd.DataFrame(index=RangeIndex(0, self.shape[0], name=None)) diff --git a/anndata/tests/base.py b/anndata/tests/base.py index <HASH>..<HASH> 100644 --- a/anndata/tests/base.py +++ b/anndata/tests/base.py @@ -187,6 +187,15 @@ def test_append_col(): adata.obs['new4'] = 'far too long'.split() +def test_delete_col(): + adata = AnnData(np.array([[1, 2, 3], [4, 5, 6]]), dict(o1=[1, 2], o2=[3, 4])) + assert ['o1', 'o2'] == adata.obs_keys() + + del adata.obs['o1'] + assert ['o2'] == adata.obs_keys() + assert [3, 4] == adata.obs['o2'].tolist() + + def test_set_obs(): adata = AnnData(np.array([[1, 2, 3], [4, 5, 6]]))
Allow deleting obs/var cols Fixes #<I>
theislab_anndata
train
1d147e169a0eebb50cae1085b94c31df6fb1093d
diff --git a/db.class.php b/db.class.php index <HASH>..<HASH> 100644 --- a/db.class.php +++ b/db.class.php @@ -36,6 +36,7 @@ class DB { public static $throw_exception_on_nonsql_error = false; public static $nested_transactions = false; public static $usenull = true; + public static $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => ''); // internal protected static $mdb = null; @@ -48,7 +49,7 @@ class DB { } static $variables_to_sync = array('param_char', 'named_param_seperator', 'success_handler', 'error_handler', 'throw_exception_on_error', - 'nonsql_error_handler', 'throw_exception_on_nonsql_error', 'nested_transactions', 'usenull'); + 'nonsql_error_handler', 'throw_exception_on_nonsql_error', 'nested_transactions', 'usenull', 'ssl'); $db_class_vars = get_class_vars('DB'); // the DB::$$var syntax only works in 5.3+ @@ -129,6 +130,7 @@ class MeekroDB { public $throw_exception_on_nonsql_error = false; public $nested_transactions = false; public $usenull = true; + public $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => ''); // internal public $internal_mysql = null; @@ -162,7 +164,14 @@ class MeekroDB { if (!($mysql instanceof MySQLi)) { if (! $this->port) $this->port = ini_get('mysqli.default_port'); $this->current_db = $this->dbName; - $mysql = new mysqli($this->host, $this->user, $this->password, $this->dbName, $this->port); + $mysql = new mysqli(); + $connect_flags = 0; + if ($this->ssl['key']) { + $mysql->ssl_set($this->ssl['key'], $this->ssl['cert'], $this->ssl['ca_cert'], $this->ssl['ca_path'], $this->ssl['cipher']); + $connect_flags |= MYSQLI_CLIENT_SSL; + } + $mysql->real_connect($this->host, $this->user, $this->password, $this->dbName, $this->port, null, $connect_flags); + if ($mysql->connect_error) { $this->nonSQLError('Unable to connect to MySQL server! Error: ' . $mysql->connect_error);
ssl support (still untested)
SergeyTsalkov_meekrodb
train
6037dee8519eb749e468c7eb684e0ee537f3747d
diff --git a/api/api.go b/api/api.go index <HASH>..<HASH> 100644 --- a/api/api.go +++ b/api/api.go @@ -27,22 +27,21 @@ const ( defBucketPageSize = 100 ) -// Handler returns a handler that serves the Chain HTTP API. -func Handler() chainhttp.Handler { +// Handler returns a handler that serves the Chain HTTP API. Param nouserSecret +// will be used as the password for routes starting with /nouser/. +func Handler(nouserSecret string) chainhttp.Handler { h := chainhttp.PatServeMux{PatternServeMux: pat.New()} - noauth := httpjson.NewServeMux(writeHTTPError) - noauth.HandleFunc("GET", "/v3/invitations/:invID", appdb.GetInvitation) - h.AddFunc("GET", "/v3/invitations/:invID", noauth.ServeHTTPContext) - noauth.HandleFunc("POST", "/v3/invitations/:invID/create-user", createUserFromInvitation) - h.AddFunc("POST", "/v3/invitations/:invID/create-user", noauth.ServeHTTPContext) - noauth.HandleFunc("POST", "/v3/invitations/:invID/add-existing", addMemberFromInvitation) - h.AddFunc("POST", "/v3/invitations/:invID/add-existing", noauth.ServeHTTPContext) - pwHandler := httpjson.NewServeMux(writeHTTPError) pwHandler.HandleFunc("POST", "/v3/login", login) h.AddFunc("POST", "/v3/login", userCredsAuthn(pwHandler.ServeHTTPContext)) + nouserHandler := chainhttp.HandlerFunc(nouserAuthn(nouserSecret, nouserHandler())) + h.Add("GET", "/nouser/", nouserHandler) + h.Add("PUT", "/nouser/", nouserHandler) + h.Add("POST", "/nouser/", nouserHandler) + h.Add("DELETE", "/nouser/", nouserHandler) + tokenHandler := chainhttp.HandlerFunc(tokenAuthn(tokenAuthedHandler())) h.Add("GET", "/", tokenHandler) h.Add("PUT", "/", tokenHandler) @@ -52,6 +51,18 @@ func Handler() chainhttp.Handler { return h } +func nouserHandler() chainhttp.HandlerFunc { + h := httpjson.NewServeMux(writeHTTPError) + + // These routes must trust the client to enforce access control. + // Think twice before adding something here. + h.HandleFunc("GET", "/nouser/invitations/:invID", appdb.GetInvitation) + h.HandleFunc("POST", "/nouser/invitations/:invID/create-user", createUserFromInvitation) + h.HandleFunc("POST", "/nouser/invitations/:invID/add-existing", addMemberFromInvitation) + + return h.ServeHTTPContext +} + func tokenAuthedHandler() chainhttp.HandlerFunc { h := httpjson.NewServeMux(writeHTTPError) h.HandleFunc("GET", "/v3/applications", listApplications) diff --git a/api/api_test.go b/api/api_test.go index <HASH>..<HASH> 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -30,7 +30,7 @@ func TestMux(t *testing.T) { t.Fatal("unexpected panic:", err) } }() - Handler() + Handler("") } func TestLogin(t *testing.T) { diff --git a/api/authn.go b/api/authn.go index <HASH>..<HASH> 100644 --- a/api/authn.go +++ b/api/authn.go @@ -1,6 +1,7 @@ package api import ( + "crypto/subtle" "database/sql" "time" @@ -27,6 +28,19 @@ func userCredsAuthn(f chainhttp.HandlerFunc) chainhttp.HandlerFunc { }.ServeHTTPContext } +func nouserAuthn(secret string, f chainhttp.HandlerFunc) chainhttp.HandlerFunc { + return authn.BasicHandler{ + Auth: func(_ context.Context, _, p string) (string, error) { + if subtle.ConstantTimeCompare([]byte(p), []byte(secret)) != 1 { + return "", authn.ErrNotAuthenticated + } + return "", nil + }, + Next: f, + Realm: "x.chain.com", + }.ServeHTTPContext +} + func tokenAuthn(f chainhttp.HandlerFunc) chainhttp.HandlerFunc { return authn.BasicHandler{ Auth: authenticateToken, diff --git a/cmd/api/main.go b/cmd/api/main.go index <HASH>..<HASH> 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -29,6 +29,7 @@ var ( maxDBConns = 100 maxIdleConns = 100 samplePer = env.Duration("SAMPLEPER", 10*time.Second) + nouserSecret = env.String("NOUSER_SECRET", "") db *sql.DB buildTag = "dev" @@ -60,7 +61,7 @@ func main() { appdb.Init(db) var h chainhttp.Handler - h = api.Handler() + h = api.Handler(*nouserSecret) h = metrics.Handler{Handler: h} h = gzip.Handler{Handler: h}
api: nouser endpoint authentication This commit creates a "nouser" namespace for API endpoints that transmit sensitive data, but cannot be authenticated with an auth token. Internal clients must have a shared secret in order to access these endpoints. Closes chain/chainprv#<I>. Reviewers: @kr
chain_chain
train
179a62d96e3dc6ffa29c504692510affb48bb0f5
diff --git a/neo/SmartContract/Contract.py b/neo/SmartContract/Contract.py index <HASH>..<HASH> 100644 --- a/neo/SmartContract/Contract.py +++ b/neo/SmartContract/Contract.py @@ -158,7 +158,14 @@ class Contract(SerializableMixin, VerificationCode): def Deserialize(self, reader): self.PublicKeyHash = reader.ReadUInt160() self.ParameterList = reader.ReadVarBytes() - script = bytearray(reader.ReadVarBytes()) + # TODO: fix this. This is supposed to be `reader.ReadVarBytes`, + # however that no longer works after the internal implementation changed to verify the length of data to read. + # There has always been a bug that went unnoticed because previously we'd ask e.g. 70 bytes and it could return 35 without problems. + # Now that will fail. The test `neo.Wallets.test_wallet.test_privnet_wallet` thinks it should read 70 bytes because it expects b'AABB' data + # while in reality it gets b'\xAA\xBB` data and is thus only half the size. It's spread in so many places that I don't want to fix it in this already + # huge VM update PR. We work around it by manually reconstructing the old `ReadVarBytes`` + length = reader.ReadVarInt() + script = bytearray(reader.ReadBytes(length)) self.Script = script def Serialize(self, writer):
Lock contract.Deserialize to old ReadVarBytes (#<I>)
CityOfZion_neo-python
train
2e1f92344d7416a847c552a498fa30fd704e8adb
diff --git a/web/concrete/core/helpers/mail.php b/web/concrete/core/helpers/mail.php index <HASH>..<HASH> 100644 --- a/web/concrete/core/helpers/mail.php +++ b/web/concrete/core/helpers/mail.php @@ -42,6 +42,7 @@ class Concrete5_Helper_Mail { $this->to = array(); $this->cc = array(); $this->bcc = array(); + $this->replyto = array(); $this->from = array(); $this->data = array(); $this->subject = ''; @@ -401,4 +402,4 @@ class Concrete5_Helper_Mail { } -?> \ No newline at end of file +?>
reset replyto in mail helper as mentioned here <URL>
concrete5_concrete5
train
a5e0aeb1a7a267273df11e5b1292e515ec4c5736
diff --git a/flow-typed/debugger-html.js b/flow-typed/debugger-html.js index <HASH>..<HASH> 100644 --- a/flow-typed/debugger-html.js +++ b/flow-typed/debugger-html.js @@ -2,35 +2,35 @@ declare module "debugger-html" { /** - * Breakpoint ID - * - * @memberof types - * @static - */ + * Breakpoint ID + * + * @memberof types + * @static + */ declare type BreakpointId = string; /** - * Source ID - * - * @memberof types - * @static - */ + * Source ID + * + * @memberof types + * @static + */ declare type SourceId = string; /** - * Actor ID - * - * @memberof types - * @static - */ + * Actor ID + * + * @memberof types + * @static + */ declare type ActorId = string; /** - * Source File Location - * - * @memberof types - * @static - */ + * Source File Location + * + * @memberof types + * @static + */ declare type Location = { sourceId: SourceId, line: number, @@ -53,11 +53,11 @@ declare module "debugger-html" { |}; /** - * Breakpoint - * - * @memberof types - * @static - */ + * Breakpoint + * + * @memberof types + * @static + */ declare type Breakpoint = { id: BreakpointId, location: Location, @@ -71,33 +71,33 @@ declare module "debugger-html" { }; /** - * Breakpoint sync data - * - * @memberof types - * @static - */ + * Breakpoint sync data + * + * @memberof types + * @static + */ declare type BreakpointSyncData = { previousLocation: Location | null, breakpoint: Breakpoint }; /** - * Breakpoint Result is the return from an add/modify Breakpoint request - * - * @memberof types - * @static - */ + * Breakpoint Result is the return from an add/modify Breakpoint request + * + * @memberof types + * @static + */ declare type BreakpointResult = { id: ActorId, actualLocation: Location }; /** - * PendingBreakpoint - * - * @memberof types - * @static - */ + * PendingBreakpoint + * + * @memberof types + * @static + */ declare type PendingBreakpoint = { location: PendingLocation, astLocation: ASTLocation, @@ -109,18 +109,18 @@ declare module "debugger-html" { }; /** - * Frame ID - * - * @memberof types - * @static - */ + * Frame ID + * + * @memberof types + * @static + */ declare type FrameId = string; /** - * Frame - * @memberof types - * @static - */ + * Frame + * @memberof types + * @static + */ declare type Frame = { id: FrameId, displayName: string, @@ -148,10 +148,10 @@ declare module "debugger-html" { }; /** - * why - * @memberof types - * @static - */ + * why + * @memberof types + * @static + */ declare type Why = | {| exception: string | Grip, @@ -164,14 +164,14 @@ declare module "debugger-html" { }; /** - * Why is the Debugger Paused? - * This is the generic state handling the reason the debugger is paused. - * Reasons are usually related to "breakpoint" or "debuggerStatement" - * and should eventually be specified here as an enum. For now we will - * just offer it as a string. - * @memberof types - * @static - */ + * Why is the Debugger Paused? + * This is the generic state handling the reason the debugger is paused. + * Reasons are usually related to "breakpoint" or "debuggerStatement" + * and should eventually be specified here as an enum. For now we will + * just offer it as a string. + * @memberof types + * @static + */ declare type WhyPaused = { type: string }; @@ -184,10 +184,10 @@ declare module "debugger-html" { }; /** - * Pause - * @memberof types - * @static - */ + * Pause + * @memberof types + * @static + */ declare type Pause = { frame: Frame, frames: Frame[], @@ -195,10 +195,10 @@ declare module "debugger-html" { loadedObjects?: LoadedObject[] }; /** - * Expression - * @memberof types - * @static - */ + * Expression + * @memberof types + * @static + */ declare type Expression = { input: string, value: Object, @@ -206,10 +206,10 @@ declare module "debugger-html" { }; /** - * Grip - * @memberof types - * @static - */ + * Grip + * @memberof types + * @static + */ declare type Grip = { actor: string, class: string, @@ -272,25 +272,25 @@ declare module "debugger-html" { }; /** - * Script - * This describes scripts which are sent to the debug server to be eval'd - * @memberof types - * @static - * FIXME: This needs a real type definition - */ + * Script + * This describes scripts which are sent to the debug server to be eval'd + * @memberof types + * @static + * FIXME: This needs a real type definition + */ declare type Script = any; /** - * Describes content of the binding. - * FIXME Define these type more clearly - */ + * Describes content of the binding. + * FIXME Define these type more clearly + */ declare type BindingContents = { value: any }; /** - * Defines map of binding name to its content. - */ + * Defines map of binding name to its content. + */ declare type ScopeBindings = { [name: string]: BindingContents }; @@ -301,10 +301,10 @@ declare module "debugger-html" { }; /** - * Scope - * @memberof types - * @static - */ + * Scope + * @memberof types + * @static + */ declare type Scope = { actor: ActorId, parent: ?Scope,
Prettify types (#<I>)
firefox-devtools_debugger
train
c5e4db13c6ee49d1ba6b5b87b16c3b28247e5d64
diff --git a/config/default/FeatureFlagChecker.conf.php b/config/default/FeatureFlagChecker.conf.php index <HASH>..<HASH> 100644 --- a/config/default/FeatureFlagChecker.conf.php +++ b/config/default/FeatureFlagChecker.conf.php @@ -5,6 +5,6 @@ use oat\taoLti\models\classes\FeatureFlag\LtiFeatures; return new FeatureFlagChecker( [ - FeatureFlagChecker::OPTION_ENABLED_FEATURES => LtiFeatures::LTI_1P3 + FeatureFlagChecker::OPTION_MANUALLY_ENABLED_FEATURES => LtiFeatures::LTI_1P3 ] ); diff --git a/migrations/Version202009221232112234_tao.php b/migrations/Version202009221232112234_tao.php index <HASH>..<HASH> 100644 --- a/migrations/Version202009221232112234_tao.php +++ b/migrations/Version202009221232112234_tao.php @@ -28,7 +28,7 @@ final class Version202009221232112234_tao extends AbstractMigration FeatureFlagChecker::SERVICE_ID, new FeatureFlagChecker( [ - FeatureFlagChecker::OPTION_ENABLED_FEATURES => LtiFeatures::LTI_1P3 + FeatureFlagChecker::OPTION_MANUALLY_ENABLED_FEATURES => LtiFeatures::LTI_1P3 ] ) ); diff --git a/models/classes/featureFlag/FeatureFlagChecker.php b/models/classes/featureFlag/FeatureFlagChecker.php index <HASH>..<HASH> 100644 --- a/models/classes/featureFlag/FeatureFlagChecker.php +++ b/models/classes/featureFlag/FeatureFlagChecker.php @@ -27,10 +27,10 @@ use oat\oatbox\service\ConfigurableService; class FeatureFlagChecker extends ConfigurableService implements FeatureFlagCheckerInterface { public const SERVICE_ID = 'tao/FeatureFlagChecker'; - public const OPTION_ENABLED_FEATURES = 'optionEnabledFeatures'; + public const OPTION_MANUALLY_ENABLED_FEATURES = 'optionEnabledFeatures'; public function isEnabled(string $feature): bool { - return in_array($feature, $this->getOption(self::OPTION_ENABLED_FEATURES), true); + return in_array($feature, $this->getOption(self::OPTION_MANUALLY_ENABLED_FEATURES), true); } } diff --git a/models/classes/menu/Perspective.php b/models/classes/menu/Perspective.php index <HASH>..<HASH> 100755 --- a/models/classes/menu/Perspective.php +++ b/models/classes/menu/Perspective.php @@ -111,7 +111,7 @@ class Perspective extends MenuElement implements PhpSerializable */ public function addSection(Section $section) { - if (!$this->getSectionVisibilityFilter()->isVisible($section->getId())) { + if ($this->getSectionVisibilityFilter()->isHidden($section->getId())) { return; } diff --git a/models/classes/menu/SectionVisibilityFilter.php b/models/classes/menu/SectionVisibilityFilter.php index <HASH>..<HASH> 100644 --- a/models/classes/menu/SectionVisibilityFilter.php +++ b/models/classes/menu/SectionVisibilityFilter.php @@ -32,9 +32,9 @@ class SectionVisibilityFilter extends ConfigurableService implements SectionVisi /** * @throws \Exception */ - public function isVisible(string $section): bool + public function isHidden(string $section): bool { - return !in_array($section, $this->getExcludedSections(), true); + return in_array($section, $this->getExcludedSections(), true); } /** diff --git a/models/classes/menu/SectionVisibilityFilterInterface.php b/models/classes/menu/SectionVisibilityFilterInterface.php index <HASH>..<HASH> 100644 --- a/models/classes/menu/SectionVisibilityFilterInterface.php +++ b/models/classes/menu/SectionVisibilityFilterInterface.php @@ -24,5 +24,5 @@ namespace oat\tao\model\menu; interface SectionVisibilityFilterInterface { - public function isVisible(string $section): bool; + public function isHidden(string $section): bool; } \ No newline at end of file
SectionVisibilityFilterInterface method is hidden OPTION_ENABLED_FEATURES => OPTION_MANUALLY_ENABLED_FEATURES
oat-sa_tao-core
train
a2df827486a49db212fef60ad8fa4d13a3c2f721
diff --git a/tests/lib/rules/require-object-in-propequal.js b/tests/lib/rules/require-object-in-propequal.js index <HASH>..<HASH> 100644 --- a/tests/lib/rules/require-object-in-propequal.js +++ b/tests/lib/rules/require-object-in-propequal.js @@ -38,7 +38,7 @@ function createInvalid(assertionCode, invalidValue) { const ruleTester = new RuleTester({ parserOptions: { - ecmaVersion: 2015, + ecmaVersion: 2020, ecmaFeatures: { jsx: true } } }); @@ -75,16 +75,12 @@ ruleTester.run("require-object-in-propequal", rule, { wrap("assert.deepEqual(actual, foo++);"), wrap("assert.deepEqual(actual, --foo);"), wrap("assert.deepEqual(actual, foo--);"), - wrap("assert.deepEqual(actual, <JSX />);") + wrap("assert.deepEqual(actual, <JSX />);"), - // eslint-disable-next-line no-warning-comments - // TODO: Uncomment when support for ESLint 5 is dropped - // wrap("assert.deepEqual(actual, 0n);"), + wrap("assert.deepEqual(actual, 0n);"), - // eslint-disable-next-line no-warning-comments - // TODO: Uncomment when support for ESLint 5 is dropped - // wrap("assert.propEqual(actual, foo?.bar);"), - // wrap("assert.propEqual(actual, foo?.bar?.());") + wrap("assert.propEqual(actual, foo?.bar);"), + wrap("assert.propEqual(actual, foo?.bar?.());") ], invalid: [ @@ -100,10 +96,7 @@ ruleTester.run("require-object-in-propequal", rule, { createInvalid("assert.propEqual(actual, foo++);", "foo++"), createInvalid("assert.propEqual(actual, --foo);", "--foo"), createInvalid("assert.propEqual(actual, foo--);", "foo--"), - createInvalid("assert.propEqual(actual, <JSX />)", "<JSX />") - - // eslint-disable-next-line no-warning-comments - // TODO: Uncomment when support for ESLint 5 is dropped - // createInvalid("assert.propEqual(actual, 0n);", "0n"), + createInvalid("assert.propEqual(actual, <JSX />)", "<JSX />"), + createInvalid("assert.propEqual(actual, 0n);", "0n") ] });
Chore: Uncomment ES<I> tests in require-object-in-propequal (#<I>)
platinumazure_eslint-plugin-qunit
train
bdd285748d8b8fc409f4d2139ee544a3f436bd28
diff --git a/dBug.php b/dBug.php index <HASH>..<HASH> 100755 --- a/dBug.php +++ b/dBug.php @@ -2,7 +2,7 @@ /*********************************************************************************************************************\ * LAST UPDATE * ============ - * August 2nd, 2012 + * August 6th, 2012 * * * AUTHOR @@ -483,9 +483,15 @@ class dBug { </script> <style type="text/css"> - table.dBug_array,table.dBug_object,table.dBug_resource,table.dBug_resourceC,table.dBug_xml { - font-family:Verdana, Arial, Helvetica, sans-serif; color:#000000; font-size:12px; - } + table.dBug_array,table.dBug_object,table.dBug_resource,table.dBug_resourceC,table.dBug_xml + { font-family:Verdana, Arial, Helvetica, sans-serif; color:#000000; font-size:12px; border-spacing:2px; display:table; border-collapse:separate; } + + table.dBug_array td, + table.dBug_object td, + table.dBug_resource td, + table.dBug_resourceC td, + table.dBug_xml td + { line-height:1.3; padding:3px; vertical-align:top; } .dBug_arrayHeader, .dBug_objectHeader,
Added CSS to combat breakage when used with a CSS Reset Specifically modeled against Eric A. Meyer's CSS reset (Available here: <URL>
ospinto_dBug
train
165839931d5c95cb9f3fdfbbc46aae53605a979d
diff --git a/packages/react-ui-components/src/Icon/mapper.js b/packages/react-ui-components/src/Icon/mapper.js index <HASH>..<HASH> 100644 --- a/packages/react-ui-components/src/Icon/mapper.js +++ b/packages/react-ui-components/src/Icon/mapper.js @@ -486,20 +486,19 @@ const mapper = icon => { 'youtube-square' ]; - if (!icon.startsWith('icon-')) { - return icon; + if (icon.startsWith('icon-')) { + icon = icon.substr(5); } - const iconWithoutPrefix = icon.substr(5); - if (map[iconWithoutPrefix]) { - return map[iconWithoutPrefix]; + if (map[icon]) { + return map[icon]; } - if (brands.includes(iconWithoutPrefix)) { - return 'fab fa-' + iconWithoutPrefix; + if (brands.includes(icon)) { + return 'fab fa-' + icon; } - return 'fas fa-' + iconWithoutPrefix; + return 'fas fa-' + icon; }; export default mapper;
TASK: add support for unprefixed icons
neos_neos-ui
train
40cee967e6b567a0e3f739fb84db9d19ef94d461
diff --git a/src/lib/KevinGH/Box/Console/Command/Create.php b/src/lib/KevinGH/Box/Console/Command/Create.php index <HASH>..<HASH> 100644 --- a/src/lib/KevinGH/Box/Console/Command/Create.php +++ b/src/lib/KevinGH/Box/Console/Command/Create.php @@ -98,7 +98,7 @@ $output->writeln(' - Adding files'); } - foreach ($config->getFiles() as $file) + foreach ($files = $config->getFiles() as $file) { $relative = $config->relativeOf($file); @@ -109,6 +109,14 @@ $box->importFile($relative, $file); } + + if ($this->verbose) + { + if (empty($files)) + { + $output->writeln(' - No files found'); + } + } $this->end($box); @@ -119,7 +127,15 @@ else { - $output->writeln(' done.'); + if ($files) + { + $output->writeln(' done.'); + } + + else + { + $output->writeln(' no files found.'); + } } } diff --git a/src/tests/KevinGH/Box/Console/Command/CreateTest.php b/src/tests/KevinGH/Box/Console/Command/CreateTest.php index <HASH>..<HASH> 100644 --- a/src/tests/KevinGH/Box/Console/Command/CreateTest.php +++ b/src/tests/KevinGH/Box/Console/Command/CreateTest.php @@ -61,6 +61,29 @@ $this->assertEquals($rand, $metadata['rand']); } + public function testExecuteNoFiles() + { + $this->prepareApp('phpunit'); + + $file = $this->setConfig(array()); + + $this->tester->execute(array( + 'command' => self::COMMAND, + '--config' => $file + ), array( + 'verbosity' => OutputInterface::VERBOSITY_VERBOSE + )); + + $this->assertRegExp('/No files found/', $this->tester->getDisplay()); + + $this->tester->execute(array( + 'command' => self::COMMAND, + '--config' => $file + )); + + $this->assertRegExp('/no files found/', $this->tester->getDisplay()); + } + public function testExecuteDefaultStub() { $this->prepareApp('phpunit');
Warning user when no files were added. (closes #<I>)
box-project_box2
train
437bc24b49d1707756c98bd2a158ec87ce9e8af3
diff --git a/lib/reporter.js b/lib/reporter.js index <HASH>..<HASH> 100644 --- a/lib/reporter.js +++ b/lib/reporter.js @@ -45,11 +45,6 @@ var BaseReporter = function(adapter) { this.writeCommonMsg = this.write; - this.onRunStart = function(browsers) { - this.browsers_ = browsers; - }; - - this.onBrowserError = function(browser, error) { this.writeCommonMsg(util.format(this.ERROR, browser) + u.formatError(error, '\t')); }; @@ -183,14 +178,22 @@ var ProgressReporter = function(adapter) { var DotsReporter = function(adapter) { BaseReporter.call(this, adapter); + var DOTS_WRAP = 80; + + this.onRunStart = function(browsers) { + this.browsers_ = browsers; + this.dotsCount_ = 0; + }; this.writeCommonMsg = function(msg) { this.write('\n' + msg); + this.dotsCount_ = 0; }; this.specSuccess = function() { - this.write('.'); + this.dotsCount_ = (this.dotsCount_ + 1) % DOTS_WRAP; + this.write(this.dotsCount_ ? '.' : '.\n'); };
DOTS reporter - wrap at <I> [changelog]
karma-runner_karma
train
c8d58f0bbefddad57c1ae8fdb2b1fb7f763f73ef
diff --git a/Services/Twilio.php b/Services/Twilio.php index <HASH>..<HASH> 100644 --- a/Services/Twilio.php +++ b/Services/Twilio.php @@ -25,6 +25,7 @@ class Services_Twilio extends Services_Twilio_Resource const USER_AGENT = 'twilio-php/3.5.2'; protected $http; + protected $retryAttempts; protected $version; protected $versions = array('2008-08-01', '2010-04-01');
Make retryAttempts a protected object var
twilio_twilio-php
train
abac2023bcc3d2da4ccf8afa1bc843324b8829ab
diff --git a/lib/webrat/selenium/selenium_session.rb b/lib/webrat/selenium/selenium_session.rb index <HASH>..<HASH> 100644 --- a/lib/webrat/selenium/selenium_session.rb +++ b/lib/webrat/selenium/selenium_session.rb @@ -150,7 +150,7 @@ module Webrat begin value = yield - rescue ::Spec::Expectations::ExpectationNotMetError, ::Selenium::CommandError, Webrat::WebratError + rescue ::Selenium::CommandError, Webrat::WebratError value = nil end
removed reference to Rspec from common code
brynary_webrat
train
8e9bc58ac53b09f3353c9fd9476e9120ff0655f5
diff --git a/src/Http/Controllers/Support/FastLookupController.php b/src/Http/Controllers/Support/FastLookupController.php index <HASH>..<HASH> 100644 --- a/src/Http/Controllers/Support/FastLookupController.php +++ b/src/Http/Controllers/Support/FastLookupController.php @@ -28,6 +28,7 @@ use Seat\Eveapi\Models\Alliances\Alliance; use Seat\Eveapi\Models\Character\CharacterInfo; use Seat\Eveapi\Models\Corporation\CorporationInfo; use Seat\Eveapi\Models\Sde\InvType; +use Seat\Eveapi\Models\Sde\MapDenormalize; use Seat\Web\Http\Controllers\Controller; use Seat\Web\Models\User; @@ -329,4 +330,40 @@ class FastLookupController extends Controller 'results' => $skills, ]); } + + /*** + * @param \Illuminate\Http\Request $request + * @return \Illuminate\Http\JsonResponse + */ + public function getRegions(Request $request) + { + if ($request->query('_type', 'query') == 'find') { + $region = MapDenormalize::find($request->query('q', 0)); + + if (is_null($region)) { + return response()->json(); + } + + return response()->json([ + 'id' => $region->itemID, + 'text' => $region->itemName, + ]); + } + + $regions = MapDenormalize::where('typeID', 3) + ->whereRaw('itemName LIKE ?', ["%{$request->query('q', '')}%"]) + ->select('itemID', 'itemName') + ->orderBy('itemName') + ->get() + ->map(function ($region) { + return [ + 'id' => $region->itemID, + 'text' => $region->itemName, + ]; + }); + + return response()->json([ + 'results' => $regions, + ]); + } } diff --git a/src/Http/Routes/Support/FastLookup.php b/src/Http/Routes/Support/FastLookup.php index <HASH>..<HASH> 100644 --- a/src/Http/Routes/Support/FastLookup.php +++ b/src/Http/Routes/Support/FastLookup.php @@ -60,3 +60,8 @@ Route::get('/skills', [ 'as' => 'fastlookup.skills', 'uses' => 'FastLookupController@getSkills', ]); + +Route::get('/regions', [ + 'as' => 'fastlookup.regions', + 'uses' => 'FastLookupController@getRegions', +]);
feat(lookups): implement a region lookup endpoint
eveseat_web
train
8db8a763ae8c5c0456a161c93a765483887d9130
diff --git a/dist.py b/dist.py index <HASH>..<HASH> 100644 --- a/dist.py +++ b/dist.py @@ -752,9 +752,6 @@ class Distribution: Returns the reinitialized command object. """ - print "reinitialize_command: command=%s" % command - print " before: have_run =", self.have_run - from distutils.cmd import Command if not isinstance(command, Command): command_name = command @@ -769,11 +766,7 @@ class Distribution: self.have_run[command_name] = 0 self._set_command_options(command) - print " after: have_run =", self.have_run - if reinit_subcommands: - print (" reinitializing sub-commands: %s" % - command.get_sub_commands()) for sub in command.get_sub_commands(): self.reinitialize_command(sub, reinit_subcommands)
Remove some debugging output from the last change.
pypa_setuptools
train
e64cf876de7f87b68d59aa22fb2048ffbbd32104
diff --git a/vent/api/plugins.py b/vent/api/plugins.py index <HASH>..<HASH> 100644 --- a/vent/api/plugins.py +++ b/vent/api/plugins.py @@ -160,7 +160,7 @@ class Plugin: matches.remove(match) matches.append(override_t) if len(matches) > 0: - self.build_manifest(matches) + self._build_manifest(matches) else: response = (False, status) return response @@ -187,7 +187,7 @@ class Plugin: matches.append((match, match_version)) return matches - def build_manifest(self, matches): + def _build_manifest(self, matches): """ Builds and writes the manifest for the tools being added """ # !! TODO check for pre-existing that conflict with request and disable and/or remove image template = Template(template=self.manifest)
build_manifest should only be called internally
CyberReboot_vent
train
1515df08109fca86f9d0bc2af3885d7f1436553d
diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index <HASH>..<HASH> 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -145,6 +145,9 @@ class CoreRequestHandlingTest(helper.CPWebCase): def fragment(self, frag): raise cherrypy.HTTPRedirect("/some/url#%s" % frag) + + def url_with_quote(self): + raise cherrypy.HTTPRedirect("/some\"url/that'we/want") def login_redir(): if not getattr(cherrypy.request, "login", None): @@ -414,6 +417,25 @@ class CoreRequestHandlingTest(helper.CPWebCase): loc = self.assertHeader('Location') assert 'Set-Cookie' in loc self.assertNoHeader('Set-Cookie') + + def assertValidXHTML(): + from xml.etree import ElementTree + try: + ElementTree.fromstring('<html><body>%s</body></html>' % self.body) + except ElementTree.ParseError as e: + self._handlewebError('automatically generated redirect ' + 'did not generate well-formed html') + + # check redirects to URLs generated valid HTML - we check this + # by seeing if it appears as valid XHTML. + self.getPage("/redirect/by_code?code=303") + self.assertStatus(303) + assertValidXHTML() + + # do the same with a url containing quote characters. + self.getPage("/redirect/url_with_quote") + self.assertStatus(303) + assertValidXHTML() def test_InternalRedirect(self): # InternalRedirect
Test demonstrating auto-generated response content for redirects can produce malformed HTML. For #<I>.
cherrypy_cheroot
train
b7f43974fa7bfa18323ac7f8ac73a714b0b20385
diff --git a/km3pipe/io/aanet.py b/km3pipe/io/aanet.py index <HASH>..<HASH> 100644 --- a/km3pipe/io/aanet.py +++ b/km3pipe/io/aanet.py @@ -166,7 +166,7 @@ class AanetPump(Pump): return wgt1, wgt2, wgt3, wgt4 def _parse_tracks(self, tracks): - out = {} + out = defaultdict(list) for i, trk in enumerate(tracks): self.log.debug('Reading Track #{}...'.format(i)) trk_type = trk.rec_type @@ -179,10 +179,19 @@ class AanetPump(Pump): "Setting to '{}'".format(trk_name) ) trk_dict = self._read_track(trk) - out[trk_name] = Table( + out[trk_name].append(Table( trk_dict, h5loc='/reco/{}'.format(trk_name.lower()), name=trk_name) + ) + for key in out: + name = out[key][0].name + h5loc = out[key][0].h5loc + out[key] = Table( + np.concatenate(out[key]), + name=name, + h5loc=h5loc, + ) self.log.debug(out) return out diff --git a/km3pipe/kp-data/test_data/aanet/aapump.py b/km3pipe/kp-data/test_data/aanet/aapump.py index <HASH>..<HASH> 100755 --- a/km3pipe/kp-data/test_data/aanet/aapump.py +++ b/km3pipe/kp-data/test_data/aanet/aapump.py @@ -1,17 +1,13 @@ #!/usr/bin/env python +import sys import km3pipe as kp log = kp.logger.get_logger('km3pipe.io.aanet') log.setLevel('INFO') -fname = 'Corsika-74005_EPOS_NO_Charmed_VOLUMEDET_p_107.propa.km3v5r4.JTERun5009Eff05.JGandalf.aanet.root' +fname = sys.argv[-1] p = kp.Pipeline() p.attach(kp.io.AanetPump, filename=fname, ignore_hits=True) p.attach(kp.io.HDF5Sink, filename=fname + '.h5') p.drain() - -p = kp.Pipeline() -p.attach(kp.io.AanetPump, filename=fname, ignore_hits=False) -p.attach(kp.io.HDF5Sink, filename=fname + '.withhits.h5') -p.drain()
FIX actually read *all* tracks in AanetPump
tamasgal_km3pipe
train
b23d4d0c0903fcf5025a96bc6ea7b00a84e80c3a
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ }, "autoload": { "psr-4": { - "ActiveCollab\\Utils\\": "src", + "ActiveCollab\\CurrentTimestamp\\": "src/CurrentTimestamp", "ActiveCollab\\Utils\\Test\\": "test/src" } } diff --git a/composer.lock b/composer.lock index <HASH>..<HASH> 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "d51759e2f34bd7dac5e2e9e9d3adfef3", + "hash": "74fe08bec37289a8fe002a217127c9ac", "content-hash": "dbe1bd906534049672393d51286cf103", "packages": [], "packages-dev": [ diff --git a/src/CurrentTimestamp/CurrentTimestamp.php b/src/CurrentTimestamp/CurrentTimestamp.php index <HASH>..<HASH> 100644 --- a/src/CurrentTimestamp/CurrentTimestamp.php +++ b/src/CurrentTimestamp/CurrentTimestamp.php @@ -6,7 +6,7 @@ * (c) A51 doo <info@activecollab.com>. All rights reserved. */ -namespace ActiveCollab\Utils\CurrentTimestamp; +namespace ActiveCollab\CurrentTimestamp; /** * @package ActiveCollab\Utils\CurrentTimestamp diff --git a/src/CurrentTimestamp/CurrentTimestampInterface.php b/src/CurrentTimestamp/CurrentTimestampInterface.php index <HASH>..<HASH> 100644 --- a/src/CurrentTimestamp/CurrentTimestampInterface.php +++ b/src/CurrentTimestamp/CurrentTimestampInterface.php @@ -6,10 +6,10 @@ * (c) A51 doo <info@activecollab.com>. All rights reserved. */ -namespace ActiveCollab\Utils\CurrentTimestamp; +namespace ActiveCollab\CurrentTimestamp; /** - * @package ActiveCollab\Utils\CurrentTimestamp + * @package ActiveCollab\CurrentTimestamp */ interface CurrentTimestampInterface { diff --git a/test/src/CurrentTimestampTest.php b/test/src/CurrentTimestampTest.php index <HASH>..<HASH> 100644 --- a/test/src/CurrentTimestampTest.php +++ b/test/src/CurrentTimestampTest.php @@ -8,7 +8,7 @@ namespace ActiveCollab\Utils\Test; -use ActiveCollab\Utils\CurrentTimestamp\CurrentTimestamp; +use ActiveCollab\CurrentTimestamp\CurrentTimestamp; use ActiveCollab\Utils\Test\Base\TestCase; /**
Make sure that util classes can "grow up" to full packages
activecollab_utils
train
f704dbcdc384226783f01874d82b574c7814fa3a
diff --git a/pyontutils/namespaces.py b/pyontutils/namespaces.py index <HASH>..<HASH> 100644 --- a/pyontutils/namespaces.py +++ b/pyontutils/namespaces.py @@ -15,9 +15,12 @@ def nsExact(namespace, slash=True): uri = uri[:-1] return rdflib.URIRef(uri) -def _loadPrefixes(): + +def getCuries(curies_location): + # FIXME this will 'fail' silently ... + # probably need to warn? try: - with open(devconfig.curies, 'rt') as f: + with open(curies_location, 'rt') as f: curie_map = yaml.safe_load(f) except (FileNotFoundError, NotADirectoryError) as e: # retrieving stuff over the net is bad @@ -27,6 +30,11 @@ def _loadPrefixes(): curie_map = requests.get(master_blob + raw_path) curie_map = yaml.safe_load(curie_map.text) + return curie_map + + +def _loadPrefixes(): + curie_map = getCuries(devconfig.curies) # holding place for values that are not in the curie map full = { # interlex predicates PROVISIONAL diff --git a/pyontutils/ontload.py b/pyontutils/ontload.py index <HASH>..<HASH> 100755 --- a/pyontutils/ontload.py +++ b/pyontutils/ontload.py @@ -66,6 +66,7 @@ from joblib import Parallel, delayed from pyontutils.core import makeGraph from pyontutils.utils import noneMembers, TODAY, setPS1, refile, TermColors as tc from pyontutils.utils_extra import memoryCheck +from pyontutils.namespaces import getCuries from pyontutils.namespaces import makePrefixes, definition # TODO make prefixes needs an all... from pyontutils.hierarchies import creatTree from pyontutils.closed_namespaces import rdf, rdfs, owl, skos, oboInOwl, dc @@ -590,11 +591,6 @@ def deploy_scp(local_path, remote_spec): #os.system(command) #os.system(update_latest) -def getCuries(curies_location): - with open(curies_location, 'rt') as f: - curies = yaml.safe_load(f) - curie_prefixes = set(curies.values()) - return curies, curie_prefixes def make_post_clone(git_local, repo_name, remote_base): local_go = jpth(git_local, repo_name, 'ttl/external/go.owl') @@ -650,7 +646,8 @@ def run(args): if remote_base == 'NIF': remote_base = 'http://ontology.neuinfo.org/NIF' - curies, curie_prefixes = getCuries(curies_location) + curies = getCuries(curies_location) + curie_prefixes = set(curies.values()) itrips = None diff --git a/pyontutils/ontutils.py b/pyontutils/ontutils.py index <HASH>..<HASH> 100755 --- a/pyontutils/ontutils.py +++ b/pyontutils/ontutils.py @@ -42,7 +42,8 @@ from joblib import Parallel, delayed from git.repo import Repo from pyontutils.core import makeGraph, createOntology from pyontutils.utils import noneMembers, anyMembers, Async, deferred, TermColors as tc -from pyontutils.ontload import loadall, getCuries +from pyontutils.ontload import loadall +from pyontutils.namespaces import getCuries from pyontutils.namespaces import makePrefixes, definition from pyontutils.closed_namespaces import rdf, rdfs, owl, skos from IPython import embed @@ -738,8 +739,10 @@ def graph_todo(graph, curie_prefixes, get_values): embed() def main(): - from docopt import docopt + from docopt import docopt, parse_defaults args = docopt(__doc__, version='ontutils 0.0.1') + defaults = {o.name:o.value if o.argcount else None + for o in parse_defaults(__doc__)} verbose = args['--verbose'] debug = args['--debug'] @@ -751,7 +754,8 @@ def main(): epoch = args['--epoch'] curies_location = args['--curies'] - curies, curie_prefixes = getCuries(curies_location) + curies = getCuries(curies_location) + curie_prefixes = set(curies.values()) filenames = args['<file>'] filenames.sort(key=lambda f: os.path.getsize(f), reverse=True) # make sure the big boys go first
getCuries moved to namespaces and combined with the equivalent implementation in _loadPrefixes
tgbugs_pyontutils
train
bdf2377364ebfcd37498c7906d60310607470122
diff --git a/app.js b/app.js index <HASH>..<HASH> 100644 --- a/app.js +++ b/app.js @@ -20,11 +20,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. */ -(function() { - "use strict"; - var fs = require("fs"), - sax = require("sax"); +var fs = require("fs"), + sax = require("sax"); +exports.parse = function(path, callback) { + "use strict"; // We use the steam functionality of sax since the MEDLINE files tend to be quite large and to load a 100MB large XML file // into memory is a bad idea when Node.js can process it on the go saving memory. var XMLParser = sax.createStream(true, { // true means XML parsing @@ -34,6 +34,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. var json = new Array(), whereAmI = new Array(), + errorHappened = false, + fileSteam, lastDateTag = "", nodeData = null, ignoreTags = [ "MedlineCitationSet", "Journal", "Pagination", "PublicationTypeList", "MedlineJournalInfo" ], // tags to ignore text processing on @@ -360,11 +362,34 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. } }); XMLParser.on("end", function(text) { // Runs when all the XML processing is done. - console.log("\nEND JSON:"); - console.log(JSON.stringify(json)); // Output to JSON in the console. + callback(null, JSON.stringify(json)); + }); + XMLParser.on("error", function(error) { // Error happended + // Stop it from calling callback more than once. + // You can't stop the parsing (what I know of) since it's a continous stream, you can stop the stream from writing though + if(errorHappened) { + return; + } + errorHappened = true; + fileSteam.unpipe(XMLParser); // Unpipe the stream to avoid writing more data to it. + callback("File is not a correct XML file.", null); + }); + + fs.stat(path, function(err, stats) { + if(err) { + return callback("File does not exist!", null); + } + if(stats.isFile()) { + try { + fileSteam = fs.createReadStream(path); + fileSteam.pipe(XMLParser); // Pipes the readstream of path to the XML parser. + } catch (error) { + callback("File does not exist!", null); + } + } else { + callback("Path is not a file!", null); + } }); - - fs.createReadStream('./extensive-test.xml').pipe(XMLParser); // Pipes the readstream of example.xml to the XML parser. function dateInsertion(text, type) { if(["created", "completed", "revised"].indexOf(lastDateTag) !== -1) { @@ -389,4 +414,4 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. function grantInsertion(text, type) { json[json.length-1].grantList.list[json[json.length-1].grantList.list.length-1][type] = text; } -}()); \ No newline at end of file +} \ No newline at end of file
made project into a module for node.js
ldbib_MEDLINEXMLToJSON
train
c45de9d9e91f1819f3335fd0695d246e32c76fd9
diff --git a/lib/phonelib/data_importer.rb b/lib/phonelib/data_importer.rb index <HASH>..<HASH> 100644 --- a/lib/phonelib/data_importer.rb +++ b/lib/phonelib/data_importer.rb @@ -18,7 +18,7 @@ module Phonelib include Phonelib::DataImporterHelper # countries that can have double country prefix in number - DOUBLE_COUNTRY_CODES_COUNTRIES = %w(IN DE BR IT NO PL) + DOUBLE_COUNTRY_CODES_COUNTRIES = %w(IN DE BR IT NO PL CU) # main data file in repo MAIN_FILE = 'resources/PhoneNumberMetadata.xml'
added cuba for allowed double prefix countries
daddyz_phonelib
train
a87789e64dc9af98f6ce0047c74f22cb95d777fd
diff --git a/MANIFEST.in b/MANIFEST.in index <HASH>..<HASH> 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -2,5 +2,6 @@ include README.md include LICENSE include setup.py include MANIFEST.in +recursive-exclude test * recursive-include uqbar * recursive-exclude *.pyc diff --git a/uqbar/graphs/Attributes.py b/uqbar/graphs/Attributes.py index <HASH>..<HASH> 100644 --- a/uqbar/graphs/Attributes.py +++ b/uqbar/graphs/Attributes.py @@ -78,7 +78,7 @@ class Attributes(collections.Mapping): _styles = frozenset() - _word_pattern = re.compile('^\w[\w\-:]*$') + _word_pattern = re.compile('^\w+$') ### GRAPH OBJECT SPECIFICS ### diff --git a/uqbar/version.py b/uqbar/version.py index <HASH>..<HASH> 100644 --- a/uqbar/version.py +++ b/uqbar/version.py @@ -1,2 +1,2 @@ -__version_info__ = (0, 1, 0) +__version_info__ = (0, 1, 1) __version__ = '.'.join(str(x) for x in __version_info__)
Hardened Graphviz word pattern.
josiah-wolf-oberholtzer_uqbar
train
672ea75c149852319f806854a7016bb64327e3ce
diff --git a/tests/Go/Aop/Pointcut/PointcutParserTest.php b/tests/Go/Aop/Pointcut/PointcutParserTest.php index <HASH>..<HASH> 100644 --- a/tests/Go/Aop/Pointcut/PointcutParserTest.php +++ b/tests/Go/Aop/Pointcut/PointcutParserTest.php @@ -77,6 +77,8 @@ class PointcutParserTest extends \PHPUnit_Framework_TestCase array('within(Go\Aspects\Blog\Package\DemoClass)'), // This will match all the methods which are in classes which implement DemoInterface. array('within(DemoInterface+)'), + // This will match all the methods in the class with specific annotation. + array('@within(First\Second\Annotation\Class)'), // Access pointcuts array('access(* Example\Aspect\*->property*)'),
Add a smoke test for the new pointcut syntax
goaop_framework
train
e951b7a5955d288c77b488401d5a15a64eb99145
diff --git a/src/Resources/public/u2f.js b/src/Resources/public/u2f.js index <HASH>..<HASH> 100644 --- a/src/Resources/public/u2f.js +++ b/src/Resources/public/u2f.js @@ -8,7 +8,7 @@ jQuery(function ($) { */ var ERROR_CODE_OK = 0; - $('form#surfnet-stepup-u2f-register-device').forEach(function () { + $('form#surfnet-stepup-u2f-register-device').each(function () { var $form = $(this), $errorCode = $form.find('input[data-u2f-register-response-field="errorCode"]'), $registrationData = $form.find('input[data-u2f-register-response-field="registrationData"]'), @@ -23,7 +23,7 @@ jQuery(function ($) { }); }); - $('form#surfnet-stepup-u2f-verify-device-authentication').forEach(function () { + $('form#surfnet-stepup-u2f-verify-device-authentication').each(function () { var $form = $(this), $errorCode = $form.find('input[data-u2f-sign-response-field="errorCode"]'), $keyHandle = $form.find('input[data-u2f-sign-response-field="keyHandle"]'),
Use jQuery.fn.each() instead of Array.prototype.forEach Array.prototype.forEach doesn't exist in every browser. jQuery's each is cross-browser.
OpenConext_Stepup-u2f-bundle
train
50bafe2d457ae6ce0bba7f77a8557aed5a98d847
diff --git a/dispatch/static/manager/gulpfile.js b/dispatch/static/manager/gulpfile.js index <HASH>..<HASH> 100644 --- a/dispatch/static/manager/gulpfile.js +++ b/dispatch/static/manager/gulpfile.js @@ -4,21 +4,26 @@ var webpack = require('webpack-stream'); var sass = require('gulp-sass'); var clean = require('gulp-clean'); -gulp.task('sass', ['clean'], function () { +gulp.task('sass', ['clean-css'], function () { return gulp.src('./src/styles/**/*.scss') .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError)) .pipe(gulp.dest('./dist/css/')); }); -gulp.task('webpack', ['clean'], function () { +gulp.task('webpack', ['clean-js'], function () { return gulp.src('./src/js/**/*.jsx') .pipe(webpack( require('./webpack.config.js') )) .pipe(gulp.dest('./dist/js/')); }); -gulp.task('clean', function () { - return gulp.src('./dist/', {read: false}) +gulp.task('clean-css', function () { + return gulp.src('./dist/css/', {read: false}) .pipe(clean()); }); -gulp.task('default', ['clean', 'webpack', 'sass']); +gulp.task('clean-js', function () { + return gulp.src('./dist/js/', {read: false}) + .pipe(clean()); +}); + +gulp.task('default', ['webpack', 'sass']);
Separate clean functions in gulp file
ubyssey_dispatch
train
cfd986c55db8243c527dd186ff6189c320cb66c0
diff --git a/pip_accel/tests.py b/pip_accel/tests.py index <HASH>..<HASH> 100644 --- a/pip_accel/tests.py +++ b/pip_accel/tests.py @@ -42,6 +42,7 @@ import unittest # External dependencies. import coloredlogs +import pytest from humanfriendly import coerce_boolean from pip.commands.install import InstallCommand from pip.exceptions import DistributionNotFound @@ -49,7 +50,7 @@ from pip.exceptions import DistributionNotFound # Modules included in our package. from pip_accel import PatchedAttribute, PipAccelerator from pip_accel.cli import main -from pip_accel.compat import StringIO +from pip_accel.compat import is_win, StringIO from pip_accel.config import Config from pip_accel.deps import DependencyInstallationRefused, SystemPackageManager from pip_accel.exceptions import EnvironmentMismatchError @@ -568,9 +569,13 @@ class PipAccelTestCase(unittest.TestCase): .. _issue 47: https://github.com/paylogic/pip-accel/issues/47 """ - returncode = test_cli('pip-accel', 'install', '--requirement', '/dev/null') + # Create first temporary empty file. + empty_file = os.path.join(create_temporary_directory(), 'empty_file') + open(empty_file, 'a').close() + returncode = test_cli('pip-accel', 'install', '--requirement', empty_file) assert returncode == 0, "pip-accel command line interface failed on empty requirements file!" + @pytest.mark.skipif(is_win, reason='Not applicable on Windows') def test_system_package_dependency_installation(self): """ Test the (automatic) installation of required system packages. @@ -682,7 +687,11 @@ def try_program(program_name): :py:data:`sys.prefix` and this argument. :raises: :py:exc:`~exceptions.AssertionError` when a test fails. """ - program_path = os.path.join(sys.prefix, 'bin', program_name) + if is_win: + # On Windows append .exe suffix and executable are in directory 'Scripts' + program_path = os.path.join(sys.prefix, 'Scripts', program_name + '.exe') + else: + program_path = os.path.join(sys.prefix, 'bin', program_name) logger.debug("Making sure %s is installed ..", program_path) assert os.path.isfile(program_path), \ ("Missing program file! (%s)" % program_path) @@ -690,7 +699,10 @@ def try_program(program_name): assert os.access(program_path, os.X_OK), \ ("Program file not executable! (%s)" % program_path) logger.debug("Making sure %s --help works ..", program_path) - assert os.system('%s --help 1>/dev/null 2>&1' % pipes.quote(program_path)) == 0, \ + with open(os.devnull, 'wb') as DEVNULL: + # Redirect stdout to /dev/null and stderr to stdout. + assert subprocess.call([program_path, '--help'], stdout=DEVNULL, + stderr=subprocess.STDOUT) == 0, \ ("Program doesn't run! (%s --help failed)" % program_path) def generate_nonexisting_pathname():
Fix some tests for Windows (issue #<I>)
paylogic_pip-accel
train
fab5759ebd9a4cd5cbaf01634b19e50f5ba5497e
diff --git a/src/Sylius/Bundle/CoreBundle/Fixture/Factory/ShopUserExampleFactory.php b/src/Sylius/Bundle/CoreBundle/Fixture/Factory/ShopUserExampleFactory.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/CoreBundle/Fixture/Factory/ShopUserExampleFactory.php +++ b/src/Sylius/Bundle/CoreBundle/Fixture/Factory/ShopUserExampleFactory.php @@ -17,7 +17,7 @@ use Sylius\Bundle\CoreBundle\Fixture\OptionsResolver\LazyOption; use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\Customer\Model\CustomerGroupInterface; -use Sylius\Component\Customer\Model\CustomerInterface as CustotmerComponent; +use Sylius\Component\Customer\Model\CustomerInterface as CustomerComponent; use Sylius\Component\Resource\Factory\FactoryInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Symfony\Component\OptionsResolver\Options; @@ -97,10 +97,10 @@ class ShopUserExampleFactory extends AbstractExampleFactory implements ExampleFa ->setDefault('customer_group', LazyOption::randomOneOrNull($this->customerGroupRepository, 100)) ->setAllowedTypes('customer_group', ['null', 'string', CustomerGroupInterface::class]) ->setNormalizer('customer_group', LazyOption::findOneBy($this->customerGroupRepository, 'code')) - ->setDefault('gender', CustotmerComponent::UNKNOWN_GENDER) + ->setDefault('gender', CustomerComponent::UNKNOWN_GENDER) ->setAllowedValues( 'gender', - [CustotmerComponent::UNKNOWN_GENDER, CustotmerComponent::MALE_GENDER, CustotmerComponent::FEMALE_GENDER] + [CustomerComponent::UNKNOWN_GENDER, CustomerComponent::MALE_GENDER, CustomerComponent::FEMALE_GENDER] ) ->setDefault('phone_number', function (Options $options): string { return $this->faker->phoneNumber;
Fix CustomerComponent Typo The `Sylius\Component\Customer\Model\CustomerInterface` was imported as **CustotmerComponent**. This is just to change that typo to **CustomerComponent**. It was also used 4 times in the class so I have changed those occurrences as well.
Sylius_Sylius
train
dfd3e99dece2a3fc8daf3eeff0486ed63efc34c2
diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -60,12 +60,12 @@ abstract class Kernel implements KernelInterface, TerminableInterface protected $startTime; protected $loadClassCache; - const VERSION = '2.3.5'; - const VERSION_ID = '20305'; + const VERSION = '2.3.6-DEV'; + const VERSION_ID = '20306'; const MAJOR_VERSION = '2'; const MINOR_VERSION = '3'; - const RELEASE_VERSION = '5'; - const EXTRA_VERSION = ''; + const RELEASE_VERSION = '6'; + const EXTRA_VERSION = 'DEV'; /** * Constructor.
bumped Symfony version to <I>
symfony_symfony
train
0aa0b0a06af390f3a0f98f0477bdf2f707430c43
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -27,6 +27,8 @@ h.check_version(name, majorv=2, minorv=7) setup_dir = op.abspath(op.dirname(__file__)) requirements = [x.strip() for x in open(op.join(setup_dir, "requirements.txt"))] h.install_requirements(requires=["cython", "numpy"]) +cmdclass = {"build_ext": build_ext} +cmdclass.update(versioneer.get_cmdclass()) # Now these are available @@ -51,7 +53,7 @@ setup( license=h.license, long_description=h.long_description, long_description_content_type="text/markdown", - cmdclass={"build_ext": build_ext, **versioneer.get_cmdclass()}, + cmdclass=cmdclass, packages=[name] + [".".join((name, x)) for x in find_packages("jcvi", exclude=["test*.py"])], include_package_data=True,
[CI] Fix cmdclass for Py2
tanghaibao_jcvi
train
5699bf2a869ee1ceefa43c8bf9f2ac4d90a37fae
diff --git a/closure/goog/ui/ac/richremotearraymatcher_test.js b/closure/goog/ui/ac/richremotearraymatcher_test.js index <HASH>..<HASH> 100644 --- a/closure/goog/ui/ac/richremotearraymatcher_test.js +++ b/closure/goog/ui/ac/richremotearraymatcher_test.js @@ -7,6 +7,7 @@ goog.module('goog.ui.ac.RichRemoteArrayMatcherTest'); goog.setTestOnly(); +const ArgumentMatcher = goog.require('goog.testing.mockmatchers.ArgumentMatcher'); const MockControl = goog.require('goog.testing.MockControl'); const NetXhrIo = goog.require('goog.testing.net.XhrIo'); const RichRemoteArrayMatcher = goog.require('goog.ui.ac.RichRemoteArrayMatcher'); @@ -18,8 +19,26 @@ const url = 'http://www.google.com'; const token = 'goog'; const maxMatches = 5; -const responseJsonText = '[["type1", "eric", "larry", "sergey"]]'; -const responseJsonType1 = ['eric', 'larry', 'sergey']; +const responseJsonText = + '[["type1", {"name":"eric"}, {"name":"larry"}, {"name":"sergey"}]]'; +// This matcher is used to match the value used in the `matchHandler` callback +// in tests. +// The `RichRemoteArrayMatcher` takes in the parsed `responseJsonTest` +// above and augments each object within the array with methods that it defines. +// By default mocks do === comparison between the expected and actual value, +// so to avoid copying those method implementations into the test, we instead +// implement a matcher that checks to see that the value given to the callback +// is roughly what we expected it to be: an array whose objects have the names +// listed above. +// Effectively, this is structurally matching the following: +// [{name: 'eric'},{name:'larry'},{name:'sergey'}] +const ignoresRenderAndSelectMatcher = new ArgumentMatcher((arg) => { + if (!Array.isArray(arg)) { + return false; + } + return arg[0].name === 'eric' && arg[1].name === 'larry' && + arg[2].name === 'sergey'; +}, 'matchesType1'); let mockControl; let mockMatchHandler; @@ -42,7 +61,7 @@ testSuite({ testRequestMatchingRows() { const matcher = new RichRemoteArrayMatcher(url); - mockMatchHandler(token, responseJsonType1); + mockMatchHandler(token, ignoresRenderAndSelectMatcher); mockControl.$replayAll(); matcher.requestMatchingRows(token, maxMatches, mockMatchHandler); matcher.xhr_.simulateResponse(200, responseJsonText); @@ -56,7 +75,7 @@ testSuite({ assertEquals('type1', type); return response; }); - mockMatchHandler(token, responseJsonType1); + mockMatchHandler(token, ignoresRenderAndSelectMatcher); mockControl.$replayAll(); matcher.requestMatchingRows(token, maxMatches, mockMatchHandler); matcher.xhr_.simulateResponse(200, responseJsonText);
Adjust Autocomplete test that fails in strict mode. RELNOTES: n/a PiperOrigin-RevId: <I>
google_closure-library
train
599d7c191c8b8422b0dda7f4aee846ed04a43322
diff --git a/graylog2-web-interface/karma.shared.js b/graylog2-web-interface/karma.shared.js index <HASH>..<HASH> 100644 --- a/graylog2-web-interface/karma.shared.js +++ b/graylog2-web-interface/karma.shared.js @@ -28,7 +28,6 @@ module.exports = function(config) { files: [ 'config.js', 'build/vendor.js', - 'build/shared.js', 'test/shim/es5-shim.js', 'test/shim/server-side-global-vars.js', 'test/src/*.js',
Remove shared bundle from karma config.
Graylog2_graylog2-server
train
587b5dadb25456ed18d079187269c6a1dae802f9
diff --git a/build/travis-greenkeeper.js b/build/travis-greenkeeper.js index <HASH>..<HASH> 100644 --- a/build/travis-greenkeeper.js +++ b/build/travis-greenkeeper.js @@ -12,7 +12,7 @@ if (!BRANCH.startsWith('greenkeeper/')) { syncAll() -const run = command => childProcess.spawnSync(command) +const run = command => console.log(childProcess.spawnSync(command).output.map(b => (b || '').toString()).join('\n')) run('git config --global user.email "travis@travis-ci.org"') run('git config --global user.name "Travis CI"')
chore(build/update-nested-deps): log output of commands
vk-x_vk-x
train
c91f427a8b701af811e954cf36c537308202e992
diff --git a/core/src/com/google/zxing/qrcode/detector/Detector.java b/core/src/com/google/zxing/qrcode/detector/Detector.java index <HASH>..<HASH> 100644 --- a/core/src/com/google/zxing/qrcode/detector/Detector.java +++ b/core/src/com/google/zxing/qrcode/detector/Detector.java @@ -334,6 +334,10 @@ public final class Detector { int allowance = (int) (allowanceFactor * overallEstModuleSize); int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance); int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance); + if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { + throw new ReaderException("Alignment pattern is too small to search"); + } + int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance); int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
Added a bit of defensive programming in the AlignmentPattern code. There were real world examples where the width passed to AlignmentPatternFinder was zero, which causes BitArray to throw when built with a size of zero. I'm going a little bit farther and not searching extremely small areas either. Sean, please review. git-svn-id: <URL>
zxing_zxing
train
c10cdb0afbd74efdcb532b97134c3837943ea365
diff --git a/jbehave-core/src/main/java/org/jbehave/core/failures/BeforeOrAfterFailed.java b/jbehave-core/src/main/java/org/jbehave/core/failures/BeforeOrAfterFailed.java index <HASH>..<HASH> 100755 --- a/jbehave-core/src/main/java/org/jbehave/core/failures/BeforeOrAfterFailed.java +++ b/jbehave-core/src/main/java/org/jbehave/core/failures/BeforeOrAfterFailed.java @@ -1,19 +1,31 @@ package org.jbehave.core.failures; +import java.lang.annotation.Annotation; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; import static java.text.MessageFormat.format; -import static java.util.Arrays.asList; /** - * Thrown when methods with before or after annotations (story or scenario) + * Thrown when methods, annotated with before or after annotations (story or scenario), * fail. */ @SuppressWarnings("serial") public class BeforeOrAfterFailed extends RuntimeException { public BeforeOrAfterFailed(Method method, Throwable cause) { - super(format("Method {0}, annotated with {1}, failed: {2}", method, asList(method.getAnnotations()), cause), cause); + super(format("Method {0} (annotated with {1} in class {2}) failed: {3}", method.getName(), toAnnotationNames(method.getAnnotations()), method.getDeclaringClass().getName(), cause), cause); + } + + private static String toAnnotationNames(Annotation[] annotations) { + List<String> names = new ArrayList<String>(); + for (Annotation annotation : annotations) { + names.add("@"+annotation.annotationType().getSimpleName()); + } + return StringUtils.join(names, ","); } public BeforeOrAfterFailed(Throwable cause) { diff --git a/jbehave-core/src/test/java/org/jbehave/core/steps/SomeSteps.java b/jbehave-core/src/test/java/org/jbehave/core/steps/SomeSteps.java index <HASH>..<HASH> 100755 --- a/jbehave-core/src/test/java/org/jbehave/core/steps/SomeSteps.java +++ b/jbehave-core/src/test/java/org/jbehave/core/steps/SomeSteps.java @@ -10,6 +10,7 @@ import java.util.HashMap; import java.util.List; import java.util.Set; +import org.jbehave.core.annotations.BeforeScenario; import org.jbehave.core.annotations.Named; import org.jbehave.core.failures.PendingStepFound; import org.jbehave.core.failures.UUIDExceptionWrapper; @@ -29,6 +30,11 @@ public class SomeSteps extends Steps { throw new RuntimeException(); } + @BeforeScenario + public void aFailingBeforeScenarioMethod() { + throw new RuntimeException(); + } + public void aPendingMethod() { throw new PendingStepFound("a step"); } diff --git a/jbehave-core/src/test/java/org/jbehave/core/steps/StepCreatorBehaviour.java b/jbehave-core/src/test/java/org/jbehave/core/steps/StepCreatorBehaviour.java index <HASH>..<HASH> 100755 --- a/jbehave-core/src/test/java/org/jbehave/core/steps/StepCreatorBehaviour.java +++ b/jbehave-core/src/test/java/org/jbehave/core/steps/StepCreatorBehaviour.java @@ -6,28 +6,29 @@ import java.util.Date; import java.util.Map; import java.util.Properties; -import com.thoughtworks.paranamer.BytecodeReadingParanamer; -import com.thoughtworks.paranamer.CachingParanamer; import org.jbehave.core.annotations.AfterScenario; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.failures.BeforeOrAfterFailed; import org.jbehave.core.failures.UUIDExceptionWrapper; import org.jbehave.core.model.Meta; import org.jbehave.core.parsers.StepMatcher; -import org.jbehave.core.steps.AbstractStepResult.Skipped; import org.jbehave.core.steps.AbstractStepResult.Failed; import org.jbehave.core.steps.AbstractStepResult.Ignorable; import org.jbehave.core.steps.AbstractStepResult.Pending; +import org.jbehave.core.steps.AbstractStepResult.Skipped; import org.jbehave.core.steps.StepCreator.ParameterNotFound; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; +import com.thoughtworks.paranamer.BytecodeReadingParanamer; +import com.thoughtworks.paranamer.CachingParanamer; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; - import static org.hamcrest.Matchers.is; + import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; @@ -54,7 +55,7 @@ public class StepCreatorBehaviour { StepCreator stepCreator = new StepCreator(stepsInstance.getClass(), stepsFactory, configuration.parameterConverters(), null, new SilentStepMonitor()); // When - Method method = SomeSteps.methodFor("aFailingMethod"); + Method method = SomeSteps.methodFor("aFailingBeforeScenarioMethod"); StepResult stepResult = stepCreator.createBeforeOrAfterStep(method, Meta.EMPTY).perform(null); // Then
JBEHAVE-<I>: Compactified failure message to include only short names.
jbehave_jbehave-core
train
1e0f5c960f460bf742e17b2415db1af10b823c8e
diff --git a/fuel/datasets/hdf5.py b/fuel/datasets/hdf5.py index <HASH>..<HASH> 100644 --- a/fuel/datasets/hdf5.py +++ b/fuel/datasets/hdf5.py @@ -564,7 +564,11 @@ class H5PYDataset(Dataset): raise ValueError() data = [] shapes = [] - handle = self._file_handle + try: + handle = self._file_handle + except IOError: + self._out_of_memory_open() + handle = self._file_handle for source_name, subset in zip(self.sources, self.subsets): # Process the data request within the context of the data source # subset diff --git a/tests/test_hdf5.py b/tests/test_hdf5.py index <HASH>..<HASH> 100644 --- a/tests/test_hdf5.py +++ b/tests/test_hdf5.py @@ -429,3 +429,12 @@ class TestH5PYDataset(object): (self.vlen_features[0], self.vlen_targets[0])) assert_equal(next(iter_), (self.vlen_features[1], self.vlen_targets[1])) + + def test_dataset_get_data_without_open(self): + dataset = H5PYDataset(self.h5file, which_sets=('train',), + load_in_memory=False) + try: + dataset.get_data(request=(slice(0, 2))) + except IOError: + assert False + dataset.close(None)
Auto-open out-of-memory HDF5 files.
mila-iqia_fuel
train
41afc31432f68669a730880e5b2f86685849dbe1
diff --git a/src/Command/WsServerCommand.php b/src/Command/WsServerCommand.php index <HASH>..<HASH> 100644 --- a/src/Command/WsServerCommand.php +++ b/src/Command/WsServerCommand.php @@ -12,7 +12,11 @@ use Swoft\WebSocket\Server\WebSocketServer; /** * Class WsServerCommand - * @Command("http", desc="provide some commands to operate WebSocket Server") + * @Command("ws", + * coroutine=false, + * alias="ws-server,wsserver", + * desc="provide some commands to operate WebSocket Server" + * ) */ class WsServerCommand { @@ -29,7 +33,7 @@ class WsServerCommand * @throws \Swoft\Bean\Exception\ContainerException * @throws \Swoft\Server\Exception\ServerException */ - public function start() + public function start(): void { $server = $this->createServer(); @@ -40,7 +44,6 @@ class WsServerCommand return; } - // Startup settings $this->configStartOption($server); @@ -56,22 +59,17 @@ class WsServerCommand // TCP 启动参数 // $tcpStatus = $server->getTcpSetting(); - $tcpStatus = []; - $tcpEnable = $serverStatus['tcpable'] ?? false; - $tcpHost = $tcpStatus['host'] ?? 'unknown'; - $tcpPort = $tcpStatus['port'] ?? 'unknown'; - $tcpType = $tcpStatus['type'] ?? 'unknown'; - $tcpEnable = $tcpEnable ? '<info>Enabled</info>' : '<warning>Disabled</warning>'; - // 信息面板 - $lines = [ - ' Server Information ', - '********************************************************************', - "* HTTP | host: <note>$mainHost</note>, port: <note>$mainPort</note>, type: <note>$typeName</note>, worker: <note>$workerNum</note>, mode: <note>$modeName</note>", - "* TCP | host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, type: <note>$tcpType</note>, worker: <note>$workerNum</note> ($tcpEnable)", - '********************************************************************', - ]; - - \output()->writeln(implode("\n", $lines)); + + Show::panel([ + 'WebSocket' => [ + 'listen' => $mainHost . ':' . $mainPort, + 'type' => $typeName, + 'mode' => $modeName, + 'worker' => $workerNum, + ], + ]); + + \output()->writef('<success>Server start success !</success>'); // Start the server $server->start();
revert comment option 'coroutine'
swoft-cloud_swoft-websocket-server
train
02c1f75bc97ec20d8d024c381a433b34c797a008
diff --git a/pyxel/image.py b/pyxel/image.py index <HASH>..<HASH> 100644 --- a/pyxel/image.py +++ b/pyxel/image.py @@ -22,7 +22,9 @@ class Image: return self._data def set(self, x, y, width, height, data): - self._data[y:y + height, x:x + width] = data + self._data[y:y + height, x:x + width] = [ + list(map(lambda x: int(x, 16), line)) for line in data + ] self._tex.refresh() def save(self):
Enabled to set string data to the Image
kitao_pyxel
train
e6f0fb5669ed006c7ba0a87e3dedcd1ef4b126f3
diff --git a/danceschool/payments/square/models.py b/danceschool/payments/square/models.py index <HASH>..<HASH> 100644 --- a/danceschool/payments/square/models.py +++ b/danceschool/payments/square/models.py @@ -84,6 +84,9 @@ class SquarePaymentRecord(PaymentRecord): amount = sum([x.amount_money.amount / 100 for x in transaction.tenders or []]) - \ sum([x.amount_money.amount / 100 for x in transaction.refunds or []]) + refundData = [] + print('Beginning refund process.') + remains_to_refund = amount tender_index = 0 while remains_to_refund > 0: @@ -111,10 +114,23 @@ class SquarePaymentRecord(PaymentRecord): ) if response.errors: logger.error('Error in providing Square refund: %s' % response.errors) - continue + refundData.append({'status': 'error', 'status': response.errors}) + break except ApiException: logger.error('Error in providing Square refund.') - continue + refundData.append({'status': 'error', 'errors': response.errors}) + break + + print('Refund was successful? Data is: %s' % response) + + # Note that fees are often 0 or missing here, but we enqueue the task + # retrieve and update them afterward. + refundData.append({ + 'status': 'success', + 'refund_id': response.refund.id, + 'refundAmount': float(response.refund.amount_money.amount) / 100, + 'fees': float(getattr(getattr(response.refund,'processing_fee_money',None),'amount',0)) / 100, + }) remains_to_refund -= to_refund tender_index += 1 @@ -124,6 +140,9 @@ class SquarePaymentRecord(PaymentRecord): # in the future. updateSquareFees.schedule(args=(self,), delay=60) + print('Ready to return: %s' % refundData) + return refundData + class Meta: permissions = ( ('handle_pos_payments',_('Has access to point-of-sale payment functionality')), diff --git a/danceschool/payments/square/views.py b/danceschool/payments/square/views.py index <HASH>..<HASH> 100644 --- a/danceschool/payments/square/views.py +++ b/danceschool/payments/square/views.py @@ -181,16 +181,26 @@ def processPointOfSalePayment(request): return JsonResponse({'errorCode': errorCode,'errorDescription': errorDescription}) if 'registration__' in metadata: - pass - # TemporaryRegistration.objects.get(id=) + try: + tr = TemporaryRegistration.objects.get(id=int(metadata.replace('registration__',''))) + except (ValueError, TypeError, ObjectDoesNotExist): + pass elif 'invoice__' in metadata: - pass + try: + inv = Invoice.objects.get(id=int(metadata.replace('invoice__',''))) + except (ValueError, TypeError, ObjectDoesNotExist): + pass elif apps.is_installed('danceschool.financial'): RevenueItem = apps.get_model('financial','RevenueItem') - RevenueItem.objects.create( - # Enter here + # The Revenue Item is created using the save() method so that + # other apps can potentially listen for the RevenueItem pre_save + # and post_save signals to handle this case. + ri = RevenueItem( + category=getConstant(), + description=metadata, ) + ri.save() else: - logger.warning('Unkown Square payment record received. Because this transaction is not') + logger.warning('Unkown Square payment record received; it will be ignored.') return HttpResponseRedirect('/') diff --git a/danceschool/payments/stripe/models.py b/danceschool/payments/stripe/models.py index <HASH>..<HASH> 100644 --- a/danceschool/payments/stripe/models.py +++ b/danceschool/payments/stripe/models.py @@ -78,7 +78,7 @@ class StripeCharge(PaymentRecord): }) else: logger.error('Error processing refund.') - refundData.append({'status': 'error', 'status': refund.status}) + refundData.append({'status': 'error', 'errors': refund.status}) return refundData
Square online checkout is now operational and tested, including refunds. Point of sale integration still in progress.
django-danceschool_django-danceschool
train
ee6bcd158157ce2bc971f2d4e59d2baa0cae44c8
diff --git a/db/db.go b/db/db.go index <HASH>..<HASH> 100644 --- a/db/db.go +++ b/db/db.go @@ -61,7 +61,7 @@ func (db *DB) load() error { // Get number of partitions from the text file if numParts, err := ioutil.ReadFile(numPartsFilePath); err != nil { return err - } else if db.numParts, err = strconv.Atoi(string(numParts)); err != nil { + } else if db.numParts, err = strconv.Atoi(strings.Trim(string(numParts), "\r\n ")); err != nil { return err } // Look for collection directories
trim num_partitions file content from spaces and newline
HouzuoGuo_tiedot
train
093c5c8601ef5d46ee2a042426c317e31353f65f
diff --git a/lib/LitleOnlineRequest.rb b/lib/LitleOnlineRequest.rb index <HASH>..<HASH> 100755 --- a/lib/LitleOnlineRequest.rb +++ b/lib/LitleOnlineRequest.rb @@ -252,7 +252,7 @@ module LitleOnline request.authentication = authentication request.merchantId = get_merchant_id(options) - request.version = '9.00' + request.version = '8.27' request.loggedInUser = get_logged_in_user(options) request.xmlns = "http://www.litle.com/schema" request.merchantSdk = get_merchant_sdk(options) @@ -283,7 +283,7 @@ module LitleOnline end def get_merchant_sdk(options) - options['merchantSdk'] || 'Ruby;9.00.0' + options['merchantSdk'] || 'Ruby;8.27.0' end def get_report_group(options)
Updating version to <I>
Vantiv_litle-sdk-for-ruby
train
92205b39ae65b724cd9eeac605cfe000ad878381
diff --git a/tests/test_go_print.py b/tests/test_go_print.py index <HASH>..<HASH> 100755 --- a/tests/test_go_print.py +++ b/tests/test_go_print.py @@ -22,7 +22,7 @@ def test_go_print(prt=sys.stdout): def prt_pypath(prt): """Print PYTHONPATH contents.""" - pypathes = os.environ['PYTHONPATH'] + pypathes = os.environ.get('PYTHONPATH', None) if pypathes: prt.write("\nPYTHONPATH:\n") for idx, pypath in enumerate(pypathes.split(os.pathsep)):
Use get for dict w/default is None
tanghaibao_goatools
train
3058fa3af1d70b1512dba6fda7cb00b023f8b4c4
diff --git a/js/rainbow.js b/js/rainbow.js index <HASH>..<HASH> 100644 --- a/js/rainbow.js +++ b/js/rainbow.js @@ -324,8 +324,7 @@ window.Rainbow = (function() { */ function _replaceAtPosition(position, replace, replace_with, code) { var sub_string = code.substr(position); - code = code.replace(sub_string, sub_string.replace(replace, replace_with)); - return code; + return code.substr(0, position) + sub_string.replace(replace, replace_with); } /**
Fix bug with substring replace Substring replacements were not always correct if there were multiple matches for the same pattern in the string. This makes sure they always replace at the same position.
ccampbell_rainbow
train
d3d81752bcd148b477ef9d9c4d8dd5ce36c8a912
diff --git a/manticore/ethereum/__init__.py b/manticore/ethereum/__init__.py index <HASH>..<HASH> 100644 --- a/manticore/ethereum/__init__.py +++ b/manticore/ethereum/__init__.py @@ -11,6 +11,7 @@ from ..core.smtlib import ConstraintSet, Operators, solver, BitVec, Array, Array from ..platforms import evm from ..core.state import State, TerminateState from ..utils.helpers import issymbolic, PickleSerializer +from ..utils.log import init_logging import tempfile from subprocess import Popen, PIPE, check_output from multiprocessing import Process, Queue @@ -28,8 +29,11 @@ from .account import EVMAccount, EVMContract from .abi import ABI from .solidity import SolidityMetadata + logger = logging.getLogger(__name__) +init_logging() # FIXME(mark): emitting a warning in abi.py does not work unless this is called a second time here + def flagged(flag): """ diff --git a/manticore/ethereum/abi.py b/manticore/ethereum/abi.py index <HASH>..<HASH> 100644 --- a/manticore/ethereum/abi.py +++ b/manticore/ethereum/abi.py @@ -1,12 +1,16 @@ import re import uuid import sha3 +import logging from .. import abitypes, issymbolic from ..core.smtlib import Array, Operators, BitVec, ArrayVariable, ArrayProxy from ..exceptions import EthereumError +logger = logging.getLogger(__name__) + + class ABI(object): """ This class contains methods to handle the ABI. @@ -35,6 +39,14 @@ class ABI(object): raise ValueError @staticmethod + def _check_and_warn_num_args(type_spec, *args): + num_args = len(args) + num_sig_args = len(type_spec.split(',')) + if num_args != num_sig_args: + logger.warning(f'Number of provided arguments ({num_args}) does not match number of arguments in signature: {type_spec}') + + + @staticmethod def function_call(type_spec, *args): """ Build transaction data from function signature and arguments @@ -43,6 +55,8 @@ class ABI(object): if not m: raise EthereumError("Function signature expected") + ABI._check_and_warn_num_args(type_spec, *args) + result = ABI.function_selector(type_spec) # Funcid result += ABI.serialize(m.group('type'), *args) return result diff --git a/manticore/ethereum/account.py b/manticore/ethereum/account.py index <HASH>..<HASH> 100644 --- a/manticore/ethereum/account.py +++ b/manticore/ethereum/account.py @@ -1,9 +1,13 @@ +from collections import namedtuple from typing import Optional from .abi import ABI from ..exceptions import EthereumError +HashesEntry = namedtuple('HashesEntry', 'signature func_id') + + class EVMAccount(object): def __init__(self, address=None, manticore=None, name=None): """ Encapsulates an account. @@ -62,12 +66,13 @@ class EVMContract(EVMAccount): if func_name.startswith('__') or func_name in {'add_function', 'address', 'name'}: # TODO(mark): is this actually true? is there anything actually wrong with a solidity name beginning w/ an underscore? raise EthereumError("Function name ({}) is internally reserved".format(func_name)) + entry = HashesEntry(signature, func_id) if func_name in self._hashes: - self._hashes[func_name].append((signature, func_id)) + self._hashes[func_name].append(entry) return - if func_id in {h[1] for names in self._hashes.values() for h in names}: + if func_id in {entry.func_id for entries in self._hashes.values() for entry in entries}: raise EthereumError("A function with the same hash as {} is already defined".format(func_name)) - self._hashes[func_name] = [(signature, func_id)] + self._hashes[func_name] = [entry] def __null_func(self): pass @@ -99,21 +104,22 @@ class EVMContract(EVMAccount): def f(*args, signature: Optional[str]=None, caller=None, value=0, **kwargs): try: if signature: - if f'{name}{signature}' not in {h[0] for names in self._hashes.values() for h in names}: + if f'{name}{signature}' not in {entry.signature for entries in self._hashes.values() for entry in entries}: raise EthereumError( f'Function: `{name}` has no such signature`\n' - f'Known signatures: {[x[0][len(name):] for x in self._hashes[name]]}') + f'Known signatures: {[entry.signature[len(name):] for entry in self._hashes[name]]}') tx_data = ABI.function_call(f'{name}{signature}', *args) else: - if len(self._hashes[name]) > 1: - sig = self._hashes[name][0][0][len(name):] + entries = self._hashes[name] + if len(entries) > 1: + sig = entries[0].signature[len(name):] raise EthereumError( f'Function: `{name}` has multiple signatures but `signature` is not ' f'defined! Example: `account.{name}(..., signature="{sig}")`\n' - f'Known signatures: {[x[0][len(name):] for x in self._hashes[name]]}') + f'Known signatures: {[entry.signature[len(name):] for entry in self._hashes[name]]}') - tx_data = ABI.function_call(str(self._hashes[name][0][0]), *args) + tx_data = ABI.function_call(str(entries[0].signature), *args) except KeyError as e: raise e
Add check and warning for mismatched args (#<I>) * Port code to namedtuple to make more readable self._hashes[0][0][0][0][0][0][0] X_x * fmt * Port * rm * hack to make logging work :( * add check and warn * rm prints * better msg
trailofbits_manticore
train
e5a21fba86dcf859064888df853441967f3dd78d
diff --git a/spec/selenium_spec_chrome.rb b/spec/selenium_spec_chrome.rb index <HASH>..<HASH> 100644 --- a/spec/selenium_spec_chrome.rb +++ b/spec/selenium_spec_chrome.rb @@ -40,8 +40,10 @@ RSpec.describe "Capybara::Session with chrome" do @session.find(:css, '#set-storage').click @session.reset! @session.visit('/with_js') - expect(@session.driver.browser.local_storage.keys).not_to be_empty - expect(@session.driver.browser.session_storage.keys).not_to be_empty + # expect(@session.driver.browser.local_storage.keys).not_to be_empty + # expect(@session.driver.browser.session_storage.keys).not_to be_empty + expect(@session.evaluate_script('Object.keys(localStorage)')).not_to be_empty + expect(@session.evaluate_script('Object.keys(sessionStorage)')).not_to be_empty end it "clears storage when set" do @@ -50,8 +52,10 @@ RSpec.describe "Capybara::Session with chrome" do @session.find(:css, '#set-storage').click @session.reset! @session.visit('/with_js') - expect(@session.driver.browser.local_storage.keys).to be_empty - expect(@session.driver.browser.session_storage.keys).to be_empty + # expect(@session.driver.browser.local_storage.keys).to be_empty + # expect(@session.driver.browser.session_storage.keys).to be_empty + expect(@session.evaluate_script('Object.keys(localStorage)')).to be_empty + expect(@session.evaluate_script('Object.keys(sessionStorage)')).to be_empty end end end
Workaround issue with checking empty storage on Chrome <I>
teamcapybara_capybara
train
b7ad315ea5f51565017516b54111e534d54d6240
diff --git a/ttorrent-client/src/main/java/com/turn/ttorrent/client/Client.java b/ttorrent-client/src/main/java/com/turn/ttorrent/client/Client.java index <HASH>..<HASH> 100644 --- a/ttorrent-client/src/main/java/com/turn/ttorrent/client/Client.java +++ b/ttorrent-client/src/main/java/com/turn/ttorrent/client/Client.java @@ -163,15 +163,13 @@ public class Client implements AnnounceResponseListener, PeerActivityListener, T seeder); this.torrentsStorage.addAnnounceableTorrent(torrent.getHexInfoHash(), announceableTorrent); - // Initial completion test - final boolean finished = torrent.isFinished(); if (seeder) { announceableTorrent.getTorrentStatistic().setLeft(0); } else { announceableTorrent.getTorrentStatistic().setLeft(torrent.getSize()); } - forceAnnounceAndLogError(torrent, finished ? COMPLETED : STARTED, announceableTorrent.getDotTorrentFilePath()); + forceAnnounceAndLogError(announceableTorrent, seeder ? COMPLETED : STARTED, announceableTorrent.getDotTorrentFilePath()); logger.info(String.format("Added torrent %s (%s)", torrent.getName(), torrent.getHexInfoHash())); return torrent.getHexInfoHash(); }
now announceable torrent instance is used for force announcing
mpetazzoni_ttorrent
train
b228d02465321215e807080c9813ec05b609920d
diff --git a/src/test/java/org/jfree/svg/TestSVGGraphics2D.java b/src/test/java/org/jfree/svg/TestSVGGraphics2D.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/jfree/svg/TestSVGGraphics2D.java +++ b/src/test/java/org/jfree/svg/TestSVGGraphics2D.java @@ -37,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import java.awt.BasicStroke; import java.awt.Color; @@ -114,7 +115,7 @@ public class TestSVGGraphics2D { // in spite of the docs saying that null is accepted this gives // a NullPointerException with SunGraphics2D. //g2.setTransform(null); - //Assert.assertEquals(new AffineTransform(), g2.getTransform()); + //assertEquals(new AffineTransform(), g2.getTransform()); } /** @@ -265,7 +266,7 @@ public class TestSVGGraphics2D { } /** - * The default user clip should be <code>null</code>. + * The default user clip should be {@code null}. */ @Test public void checkDefaultClip() { @@ -392,6 +393,27 @@ public class TestSVGGraphics2D { } /** + * Clipping with a null argument is "not recommended" according to the + * latest API docs (https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6206189). + */ + @Test + public void checkClipWithNullArgument() { + + // when there is a current clip set, a null pointer exception is expected + this.g2.setClip(new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0)); + Exception exception = assertThrows(NullPointerException.class, () -> { + this.g2.clip(null); + }); + + this.g2.setClip(null); + try { + this.g2.clip(null); + } catch (Exception e) { + fail("No exception expected."); + } + } + + /** * A simple check for a call to clipRect(). */ @Test @@ -700,7 +722,7 @@ public class TestSVGGraphics2D { } /** - * Check that a null GlyphVector throws a <code>NullPointerException</code>. + * Check that a null GlyphVector throws a {@code NullPointerException}. */ @Test public void drawGlyphVectorNull() {
Add test for clip method with null argument.
jfree_jfreesvg
train
0b53100ddf03d5d49cb167bc2871706c75dbf1d7
diff --git a/Library/Phalcon/Migrations.php b/Library/Phalcon/Migrations.php index <HASH>..<HASH> 100644 --- a/Library/Phalcon/Migrations.php +++ b/Library/Phalcon/Migrations.php @@ -778,7 +778,7 @@ class " . $className . " extends Migration\n" . $sqlconstraint = $this->getPGSQLConstraint($tableName, $fieldName); $results = $connection->query($sqlconstraint); foreach ($results->fetchAll() as $r) { - $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME']; + $ignoreDropForeignKeys[] = $r['constraint_name']; $rawSql = $dialect->dropForeignKey($r['table_name'], $schema, $r['constraint_name']); if ($rawSql !== '') { $sql[] = '$this->' . $dbAdapter . '->execute(\'' . $rawSql . '\');';
Drop column - constraint name key case In drop column section, "constraint_name" key should be lower case
SachaMorard_phalcon-console-migration
train
2f5b9f1cb96beb6b4d80500b5df5c8952a91466d
diff --git a/gnosis/eth/ethereum_client.py b/gnosis/eth/ethereum_client.py index <HASH>..<HASH> 100644 --- a/gnosis/eth/ethereum_client.py +++ b/gnosis/eth/ethereum_client.py @@ -182,6 +182,9 @@ class Erc20Manager: class ParityManager: + class TraceDecodeException(Exception): + pass + def __init__(self, ethereum_client, slow_provider_timeout: int = 100): self.ethereum_client = ethereum_client self.w3 = ethereum_client.w3 @@ -227,6 +230,8 @@ class ParityManager: def _decode_traces(self, traces: List[Dict[str, any]]) -> List[Dict[str, any]]: new_traces = [] for trace in traces: + if not isinstance(trace, dict): + raise ParityTraceDecodeException('Expected dictionary, but found unexpected trace %s' % trace) trace_copy = trace.copy() new_traces.append(trace_copy) trace_copy['result'] = self._decode_trace_result(trace['result']) @@ -304,7 +309,11 @@ class ParityManager: if count: parameters['count'] = count - return self._decode_traces(self.slow_w3.parity.traceFilter(parameters)) + try: + return self._decode_traces(self.slow_w3.parity.traceFilter(parameters)) + except ParityTraceDecodeException as exc: + logger.warning('Problem decoding trace: %s - Retrying', exc) + return self._decode_traces(self.slow_w3.parity.traceFilter(parameters)) class EthereumClient:
Detect problem with traces - Sometimes Parity node returns invalid traces
gnosis_gnosis-py
train
b10ce05189222ab3ed50fc5b9026018711873c4d
diff --git a/modules/wycs/src/wycs/lang/SemanticType.java b/modules/wycs/src/wycs/lang/SemanticType.java index <HASH>..<HASH> 100644 --- a/modules/wycs/src/wycs/lang/SemanticType.java +++ b/modules/wycs/src/wycs/lang/SemanticType.java @@ -2,6 +2,7 @@ package wycs.lang; import java.io.IOException; +import java.util.Map; import wyautl.core.*; import wyautl.io.PrettyAutomataWriter; import static wycs.lang.Types.*; @@ -84,7 +85,13 @@ public abstract class SemanticType { throw new IllegalArgumentException("Invalid atom kind"); } int root = automaton.add(new Automaton.Term(kind)); - automaton.setRoot(0,root); + automaton.setRoot(0, root); + } + + @Override + public SemanticType substitute(Map<java.lang.String, SemanticType> binding) { + // atom can never have anything substituted. + return this; } } @@ -319,6 +326,42 @@ public abstract class SemanticType { } return false; } + + /** + * Substitute type variables for concrete types according to a given + * binding. + * + * @param binding + * --- a map from type variable's to concrete types. + * @return + */ + public SemanticType substitute(Map<java.lang.String,SemanticType> binding) { + Automaton nAutomaton = new Automaton(automaton); + + int[] keys = new int[binding.size()]; + int[] types = new int[binding.size()]; + + int i=0; + for(Map.Entry<java.lang.String, SemanticType> e : binding.entrySet()) { + java.lang.String key = e.getKey(); + SemanticType type = e.getValue(); + keys[i] = Types.Var(nAutomaton, key); + types[i++] = nAutomaton.addAll(type.automaton.getRoot(0), type.automaton); + } + + int root = nAutomaton.getRoot(0); + int[] mapping = new int[nAutomaton.nStates()]; + for(i=0;i!=mapping.length;++i) { + mapping[i] = i; + } + for(i=0;i!=keys.length;++i) { + mapping[keys[i]] = types[i]; + } + nAutomaton.setRoot(0, nAutomaton.substitute(root, mapping)); + return construct(nAutomaton); + } + + public java.lang.String toString() { int root = automaton.getRoot(0); diff --git a/modules/wycs/src/wycs/transforms/TypePropagation.java b/modules/wycs/src/wycs/transforms/TypePropagation.java index <HASH>..<HASH> 100644 --- a/modules/wycs/src/wycs/transforms/TypePropagation.java +++ b/modules/wycs/src/wycs/transforms/TypePropagation.java @@ -321,10 +321,30 @@ public class TypePropagation implements Transform<WycsFile> { Pair<NameID,WycsFile.Function> p = builder.resolveAs(e.name,WycsFile.Function.class,context); WycsFile.Function fn = p.second(); SemanticType.Tuple funType = getFunctionType(fn); - SemanticType argument = propagate(e.operand,environment,generics,context); -// // TODO: generate generic binding here - checkIsSubtype(funType.element(0),argument,e.operand); - return funType.element(1); + SemanticType parameter = funType.element(0); + SemanticType ret = funType.element(1); + + if(fn.generics.size() != e.generics.length) { + // could resolve this with inference in the future. + syntaxError("incorrect number of generic arguments provided", + context.file().filename(), e); + } + + SemanticType argument = propagate(e.operand,environment,generics,context); + HashMap<String,SemanticType> binding = new HashMap<String,SemanticType>(); + SemanticType[] genericParameters = new SemanticType[e.generics.length]; + for (int i = 0; i != e.generics.length; ++i) { + binding.put(fn.generics.get(i), + convert(e.generics[i], generics)); + } + + parameter = parameter.substitute(binding); + ret = ret.substitute(binding); + + System.out.println("GOT: " + parameter); + + checkIsSubtype(parameter,argument,e.operand); + return ret; } catch (ResolveError re) { syntaxError(re.getMessage(), context.file().filename(), e); return null;
WYCS: working on substitution of generic variables.
Whiley_WhileyCompiler
train
bb46490306434d743b0639ab24be726fda0d0c75
diff --git a/blockstack_cli_0.14.1/blockstack_client/backend/registrar.py b/blockstack_cli_0.14.1/blockstack_client/backend/registrar.py index <HASH>..<HASH> 100644 --- a/blockstack_cli_0.14.1/blockstack_client/backend/registrar.py +++ b/blockstack_cli_0.14.1/blockstack_client/backend/registrar.py @@ -398,6 +398,8 @@ class RegistrarWorker(threading.Thread): # use the data keypair if name_data.has_key('profile') and name_data['profile'] is not None: _, data_privkey = get_data_keypair( zonefile_data, wallet_keys=wallet_data, config_path=config_path ) + assert data_privkey is not None, "No data private key" + log.info("Replicate profile data for %s to %s" % (name_data['fqu'], ",".join(storage_drivers))) rc = put_mutable_data( name_data['fqu'], name_data['profile'], data_privkey, required=storage_drivers ) if not rc:
data_privkey is not allowed to be None
blockstack_blockstack-core
train
93fd69a297b05162647cf3e3f00570f6febaa933
diff --git a/slack_sdk/audit_logs/v1/logs.py b/slack_sdk/audit_logs/v1/logs.py index <HASH>..<HASH> 100644 --- a/slack_sdk/audit_logs/v1/logs.py +++ b/slack_sdk/audit_logs/v1/logs.py @@ -102,6 +102,22 @@ class RetentionPolicy: self.unknown_fields = kwargs +class ConversationPref: + type: Optional[List[str]] + user: Optional[List[str]] + + def __init__( + self, + *, + type: Optional[List[str]] = None, + user: Optional[List[str]] = None, + **kwargs, + ) -> None: + self.type = type + self.user = user + self.unknown_fields = kwargs + + class Details: name: Optional[str] new_value: Optional[Union[str, List[str], Dict[str, Any]]] @@ -159,6 +175,8 @@ class Details: is_token_rotation_enabled_app: Optional[bool] old_retention_policy: Optional[RetentionPolicy] new_retention_policy: Optional[RetentionPolicy] + who_can_post: Optional[ConversationPref] + can_thread: Optional[ConversationPref] def __init__( self, @@ -218,6 +236,8 @@ class Details: is_token_rotation_enabled_app: Optional[bool] = None, old_retention_policy: Optional[Union[Dict[str, Any], RetentionPolicy]] = None, new_retention_policy: Optional[Union[Dict[str, Any], RetentionPolicy]] = None, + who_can_post: Optional[Union[Dict[str, List[str]], ConversationPref]] = None, + can_thread: Optional[Union[Dict[str, List[str]], ConversationPref]] = None, **kwargs, ) -> None: self.name = name @@ -284,6 +304,16 @@ class Details: if isinstance(new_retention_policy, RetentionPolicy) else RetentionPolicy(**new_retention_policy) ) + self.who_can_post = ( + who_can_post + if isinstance(who_can_post, ConversationPref) + else ConversationPref(**who_can_post) + ) + self.can_thread = ( + can_thread + if isinstance(can_thread, ConversationPref) + else ConversationPref(**can_thread) + ) class App: diff --git a/tests/slack_sdk/audit_logs/test_response.py b/tests/slack_sdk/audit_logs/test_response.py index <HASH>..<HASH> 100644 --- a/tests/slack_sdk/audit_logs/test_response.py +++ b/tests/slack_sdk/audit_logs/test_response.py @@ -133,6 +133,10 @@ class TestAuditLogsClient(unittest.TestCase): self.assertEqual(entry.details.new_retention_policy.type, "new") self.assertEqual(entry.details.is_internal_integration, True) self.assertEqual(entry.details.cleared_resolution, "approved") + self.assertEqual(entry.details.who_can_post.type, ["owner", "admin"]) + self.assertEqual(entry.details.who_can_post.user, ["W111"]) + self.assertEqual(entry.details.can_thread.type, ["admin", "org_admin"]) + self.assertEqual(entry.details.can_thread.user, ["W222"]) logs_response_data = """{ @@ -335,7 +339,25 @@ logs_response_data = """{ "duration_days": 222 }, "is_internal_integration": true, - "cleared_resolution": "approved" + "cleared_resolution": "approved", + "who_can_post": { + "type": [ + "owner", + "admin" + ], + "user": [ + "W111" + ] + }, + "can_thread": { + "type": [ + "admin", + "org_admin" + ], + "user": [ + "W222" + ] + } } } ]
Add new details properties for channel_posting_permissions_updated action (#<I>)
slackapi_python-slackclient
train
91b2c3301701ae4851bc5084c1b8eeb7a0ce6f9d
diff --git a/connector/setup.py b/connector/setup.py index <HASH>..<HASH> 100755 --- a/connector/setup.py +++ b/connector/setup.py @@ -184,7 +184,8 @@ setup( 'ncclient >= 0.6.6', 'grpcio', 'cisco-gnmi >= 1.0.13', - 'protobuf ~= 3.20', + 'protobuf ~= 3.20;python_version>="3.7"', + 'protobuf < 3.20;python_version<"3.7"', ], # any additional groups of dependencies. diff --git a/connector/src/yang/connector/__init__.py b/connector/src/yang/connector/__init__.py index <HASH>..<HASH> 100644 --- a/connector/src/yang/connector/__init__.py +++ b/connector/src/yang/connector/__init__.py @@ -7,7 +7,7 @@ Restconf implementation is coming next. """ # metadata -__version__ = '22.6' +__version__ = '22.6.2' __author__ = ( 'Jonathan Yang <yuekyang@cisco.com>', 'Siming Yuan <siyuan@cisco.com',
fixed version pinning for protobuf
CiscoTestAutomation_yang
train
ff71f2555626339f0810daca23de1f1e26791375
diff --git a/db/jig/mapper.php b/db/jig/mapper.php index <HASH>..<HASH> 100644 --- a/db/jig/mapper.php +++ b/db/jig/mapper.php @@ -324,12 +324,12 @@ class Mapper extends \DB\Cursor { \Base::instance()->call($this->trigger['beforeinsert'], array($this,$pkey)); $db->write($this->file,$data); - parent::reset(); $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '. $this->file.' [insert] '.json_encode($this->document)); if (isset($this->trigger['afterinsert'])) \Base::instance()->call($this->trigger['afterinsert'], array($this,$pkey)); + $this->load(array('@_id=?',$this->id)); return $this->document; } diff --git a/db/mongo/mapper.php b/db/mongo/mapper.php index <HASH>..<HASH> 100644 --- a/db/mongo/mapper.php +++ b/db/mongo/mapper.php @@ -236,6 +236,7 @@ class Mapper extends \DB\Cursor { if (isset($this->trigger['afterinsert'])) \Base::instance()->call($this->trigger['afterinsert'], array($this,$pkey)); + $this->load(array('_id'=>$this->document['_id'])); return $this->document; } diff --git a/db/sql/mapper.php b/db/sql/mapper.php index <HASH>..<HASH> 100644 --- a/db/sql/mapper.php +++ b/db/sql/mapper.php @@ -314,7 +314,9 @@ class Mapper extends \DB\Cursor { $ctr=0; $fields=''; $values=''; + $filter=''; $pkeys=array(); + $nkeys=array(); $inc=NULL; foreach ($this->fields as $key=>&$field) { if ($field['pkey']) { @@ -323,6 +325,8 @@ class Mapper extends \DB\Cursor { if (!$inc && $field['pdo_type']==\PDO::PARAM_INT && empty($field['value']) && !$field['nullable']) $inc=$key; + $filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?'; + $nkeys[$ctr+1]=array($field['value'],$field['pdo_type']); } if ($field['changed'] && $key!=$inc) { $fields.=($ctr?',':'').$this->db->quotekey($key); @@ -349,11 +353,11 @@ class Mapper extends \DB\Cursor { } if ($this->engine!='oci') $this->_id=$this->db->lastinsertid($seq); - if ($inc) - // Reload to obtain default and auto-increment field values - $this->load(array($inc.'=?', - $this->db->value($this->fields[$inc]['pdo_type'], - $this->_id))); + // Reload to obtain default and auto-increment field values + $this->load($inc? + array($inc.'=?', + $this->db->value($this->fields[$inc]['pdo_type'],$this->_id)): + array($filter,$nkeys)); if (isset($this->trigger['afterinsert'])) \Base::instance()->call($this->trigger['afterinsert'], array($this,$pkeys));
Bug fix: Mapper is dry after save()
bcosca_fatfree-core
train
33c075d91b70fb737474c2f1699df5cd814bb62b
diff --git a/federation/pkg/kubefed/init/init.go b/federation/pkg/kubefed/init/init.go index <HASH>..<HASH> 100644 --- a/federation/pkg/kubefed/init/init.go +++ b/federation/pkg/kubefed/init/init.go @@ -340,16 +340,16 @@ func (i *initFederation) Run(cmdOut io.Writer, config util.AdminConfig) error { } glog.V(4).Info("Credentials secret successfully created") - glog.V(4).Info("Creating a persistent volume and a claim to store the federation API server's state, including etcd data") var pvc *api.PersistentVolumeClaim if i.options.etcdPersistentStorage { + glog.V(4).Info("Creating a persistent volume and a claim to store the federation API server's state, including etcd data") pvc, err = createPVC(hostClientset, i.commonOptions.FederationSystemNamespace, svc.Name, i.commonOptions.Name, i.options.etcdPVCapacity, i.options.etcdPVStorageClass, i.options.dryRun) if err != nil { return err } + glog.V(4).Info("Persistent volume and claim created") + fmt.Fprintln(cmdOut, " done") } - glog.V(4).Info("Persistent volume and claim created") - fmt.Fprintln(cmdOut, " done") // Since only one IP address can be specified as advertise address, // we arbitrarily pick the first available IP address
Move logs related to etcd pvc creation inside conditional
kubernetes_kubernetes
train
37e895ddde173a2d1ce3714d95928f6641b1d3fc
diff --git a/spyderlib/widgets/qscieditor/qscieditor.py b/spyderlib/widgets/qscieditor/qscieditor.py index <HASH>..<HASH> 100644 --- a/spyderlib/widgets/qscieditor/qscieditor.py +++ b/spyderlib/widgets/qscieditor/qscieditor.py @@ -471,7 +471,8 @@ class QsciEditor(TextEditBaseWidget): self.occurences = [] # Scrollbar flag area - self.scrollflagarea = None + self.scrollflagarea = ScrollFlagArea(self) + self.scrollflagarea.hide() self.setup_editor_args = None @@ -527,10 +528,10 @@ class QsciEditor(TextEditBaseWidget): #=========================================================================== def set_scrollflagarea_enabled(self, state): if state: - self.scrollflagarea = ScrollFlagArea(self) + self.scrollflagarea.show() self.setViewportMargins(0, 0, 10, 0) else: - self.scrollflagarea = None + self.scrollflagarea.hide() self.setViewportMargins(0, 0, 0, 0) def scrollflagarea_paint_event(self, event): @@ -567,7 +568,7 @@ class QsciEditor(TextEditBaseWidget): def resizeEvent(self, event): """Reimplemented Qt method to handle line number area resizing""" super(QsciEditor, self).resizeEvent(event) - if self.scrollflagarea is not None: + if self.scrollflagarea.isVisible(): cr = self.contentsRect() vsbw = self.verticalScrollBar().contentsRect().width() self.scrollflagarea.setGeometry(\ @@ -976,7 +977,7 @@ class QsciEditor(TextEditBaseWidget): self.SendScintilla(QsciScintilla.SCI_INDICATORCLEARRANGE, 0, self.length()) self.occurences = [] - if self.scrollflagarea is not None: + if self.scrollflagarea.isVisible(): self.scrollflagarea.repaint() def __mark_occurences(self): @@ -1004,7 +1005,7 @@ class QsciEditor(TextEditBaseWidget): ok = self.__find_next(text) line, _index = self.lineindex_from_position(spos) self.occurences.append(line) - if self.scrollflagarea is not None: + if self.scrollflagarea.isVisible(): self.scrollflagarea.repaint() def __lines_changed(self):
Editor/scrollbar flags area widget: area was not visible for widgets created after starting up Spyder
spyder-ide_spyder
train
ea7a8caa9dc9fcb868103f0b171034f98e700152
diff --git a/packages/openneuro-server/datalad/snapshots.js b/packages/openneuro-server/datalad/snapshots.js index <HASH>..<HASH> 100644 --- a/packages/openneuro-server/datalad/snapshots.js +++ b/packages/openneuro-server/datalad/snapshots.js @@ -96,6 +96,14 @@ export const createSnapshot = async (datasetId, tag, user) => { }) ) }) + .catch(err => { + // Also delete the keys if any step fails to trigger a recheck + // this avoids inconsistent cache state after failures + redis.del(sKey) + redis.del(indexKey) + // Pass the actual error back to caller + throw err + }) } // TODO - deleteSnapshot
Clear snapshot redis keys on any failures during creation. Fixes #<I>
OpenNeuroOrg_openneuro
train
74db05f44e024c99b007124624776f7a8a28cf92
diff --git a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1141Test.php b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1141Test.php index <HASH>..<HASH> 100644 --- a/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1141Test.php +++ b/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/GH1141Test.php @@ -37,12 +37,33 @@ class GH1141Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest $book = $this->dm->getRepository(GH1141Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); // Verify we see chapters A and B. - $discoveredChapterTitles = array(); - foreach ($book->chapters as $thisChapter) { - $discoveredChapterTitles[] = $thisChapter->name; - } - $this->assertTrue(in_array('First chapter A', $discoveredChapterTitles)); - $this->assertTrue(in_array('Second chapter B', $discoveredChapterTitles)); + $this->assertEquals('First chapter A', $book->chapters[0]->name); + $this->assertEquals('Second chapter B', $book->chapters[1]->name); + } + + public function testReplacementOfIdentifiedEmbedManyElements() + { + $book = new GH1141Book(); + $book->identifiedChapters->add(new GH1141IdentifiedChapter('A')); + + $this->dm->persist($book); + $this->dm->flush(); + $this->dm->clear(); + + $book = $this->dm->getRepository(GH1141Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $firstChapter = $book->identifiedChapters->first(); + $firstChapter->name = "First chapter A"; + $replacementChapters = new ArrayCollection(); + $replacementChapters->add($firstChapter); + $replacementChapters->add(new GH1141IdentifiedChapter('Second chapter B')); + $book->identifiedChapters = $replacementChapters; + + $this->dm->flush(); + $this->dm->clear(); + + $book = $this->dm->getRepository(GH1141Book::CLASSNAME)->findOneBy(array('_id' => $book->id)); + $this->assertEquals('First chapter A', $book->identifiedChapters[0]->name); + $this->assertEquals('Second chapter B', $book->identifiedChapters[1]->name); } } @@ -57,9 +78,13 @@ class GH1141Book /** @ODM\EmbedMany(targetDocument="GH1141Chapter", strategy="atomicSet") */ public $chapters; + /** @ODM\EmbedMany(targetDocument="GH1141IdentifiedChapter", strategy="atomicSet") */ + public $identifiedChapters; + public function __construct() { $this->chapters = new ArrayCollection(); + $this->identifiedChapters = new ArrayCollection(); } } @@ -74,3 +99,18 @@ class GH1141Chapter $this->name = $name; } } + +/** @ODM\EmbeddedDocument */ +class GH1141IdentifiedChapter +{ + /** @ODM\Id */ + public $id; + + /** @ODM\String */ + public $name; + + public function __construct($name) + { + $this->name = $name; + } +}
Add regression test for #<I> with identified embedded docs This addresses an earlier hypothesis that embedded documents are never scheduled for upsert (due to logic in UnitOfWork::persistNew()).
doctrine_mongodb-odm
train
ec506a9d47ff418eefb80b28b97f790b5e65ccf6
diff --git a/src/main/java/water/DKV.java b/src/main/java/water/DKV.java index <HASH>..<HASH> 100644 --- a/src/main/java/water/DKV.java +++ b/src/main/java/water/DKV.java @@ -18,12 +18,10 @@ public abstract class DKV { static public Value put( Key key, Value val, Futures fs, boolean dontCache ) { assert val==null || val._key == key:"non-matching keys " + ((Object)key).toString() + " != " + ((Object)val._key).toString(); while( true ) { - Value old = H2O.get(key); - if( old != null && val != null ) // Have an old value? - key = val._key = old._key; // Use prior key in val + Value old = H2O.raw_get(key); // Raw-get: do not lazy-manifest if overwriting Value res = DputIfMatch(key,val,old,fs,dontCache); if( res == old ) return old; // PUT is globally visible now? - if(res != null) key = val._key = res._key; + if( val != null && val._key != key ) key = val._key; } } static public Value put( Key key, Iced v ) { return put(key,v,null); } diff --git a/src/main/java/water/TaskPutKey.java b/src/main/java/water/TaskPutKey.java index <HASH>..<HASH> 100644 --- a/src/main/java/water/TaskPutKey.java +++ b/src/main/java/water/TaskPutKey.java @@ -31,9 +31,9 @@ public class TaskPutKey extends DTask<TaskPutKey> { //if( _val != null && !_dontCache ) _val.initReplicaHome(sender,_key); if( _val != null ) _val.initReplicaHome(sender,_key); // Spin, until we update something. - Value old = H2O.get(_key); + Value old = H2O.raw_get(_key); // Raw-get: do not lazy-manifest if overwriting while( H2O.putIfMatch(_key,_val,old) != old ) - old = H2O.get(_key); // Repeat until we update something. + old = H2O.raw_get(_key); // Repeat until we update something. // Invalidate remote caches. Block, so that all invalidates are done // before we return to the remote caller. if( _key.home() && old != null )
Use raw-get instead of get when overwriting keys avoids lazy-chunk-key creation, only to have it deleted.
h2oai_h2o-2
train
cd936bd85002e82bb6df7baf00cf392ffde5464f
diff --git a/console/progress.py b/console/progress.py index <HASH>..<HASH> 100644 --- a/console/progress.py +++ b/console/progress.py @@ -13,7 +13,7 @@ import time from console import fg, bg, fx, _CHOSEN_PALETTE from console.screen import sc -from console.utils import clear_line, len_stripped +from console.utils import len_stripped # clear_line, from console.detection import (detect_unicode_support, get_available_palettes, get_size) @@ -153,7 +153,6 @@ class ProgressBar: debug = None done = False oob_error = False # out of bounds - full_width = False label_fmt = '%2.0f%%' label_mode = True min_width = 12 @@ -187,20 +186,16 @@ class ProgressBar: elif key == 'styles': self.styles = styles[val] elif key == 'expand': - from .detection import get_size width = get_size()[0] if self.label_mode != 'internal': width -= len(self.label_fmt) self.width = width - else: setattr(self, key, val) padding = len(self.icons[_if]) + len(self.icons[-1]) if self.width < self.min_width: self.width = self.min_width - if self.full_width: - self.width = get_size()[0] self.iwidth = self.width - padding # internal width # configure styles @@ -411,7 +406,6 @@ if __name__ == '__main__': ] from console.utils import cls - from console.screen import sc # print each in progress cls()
fix progress full_width, expand
mixmastamyk_console
train
fe08631815ab6edbb1c05ddb879da652ce796ede
diff --git a/app/controllers/integral/backend/block_lists_controller.rb b/app/controllers/integral/backend/block_lists_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/integral/backend/block_lists_controller.rb +++ b/app/controllers/integral/backend/block_lists_controller.rb @@ -38,7 +38,7 @@ module Integral # Maybe able to get rid of the content here def block_lists - res = BlockEditor::BlockList.reusable.map { |block_list| { id: block_list.id, title: block_list.name, content: block_list.content } } + res = BlockEditor::BlockList.reusable.map { |block_list| { id: block_list.id, title: { raw: block_list.name }, content: block_list.content } } render json: res, status: 200, layout: false end
Update block list endpoint to match expected by Gutenberg
yamasolutions_integral
train
f92c1c29dd1da347debdcec2ecd87cee4f54ccec
diff --git a/templates/default/logout-iframe.php b/templates/default/logout-iframe.php index <HASH>..<HASH> 100644 --- a/templates/default/logout-iframe.php +++ b/templates/default/logout-iframe.php @@ -20,8 +20,13 @@ for (j=1; j<=10; j++) { ?> <div id="content"> - - <p>You have initiated a <strong>global logout</strong> from the service <strong><?php echo $this->data['requesterName']; ?></strong>. Global logout means you will be logged out from all services connected to this identity provider. This page will show the status of the logout proccess for all of the services you are logged into.</p> + <?php + + $requestername = is_array($this->data['requesterName']) ? + $this->getTranslation($this->data['requesterName']) : $this->data['requesterName']; + + ?> + <p>You have initiated a <strong>global logout</strong> from the service <strong><?php echo $requestername; ?></strong>. Global logout means you will be logged out from all services connected to this identity provider. This page will show the status of the logout proccess for all of the services you are logged into.</p> <?php
Adding translation of which SP you arrived from (iframe SLO)
simplesamlphp_saml2
train
a5d205f973531f74438efe8aa36e81be96730b4f
diff --git a/generators/docker-compose/index.js b/generators/docker-compose/index.js index <HASH>..<HASH> 100644 --- a/generators/docker-compose/index.js +++ b/generators/docker-compose/index.js @@ -20,6 +20,7 @@ const chalk = require('chalk'); const shelljs = require('shelljs'); const jsyaml = require('js-yaml'); const pathjs = require('path'); +const normalize = require('normalize-path'); const BaseDockerGenerator = require('../generator-base-docker'); const { INITIALIZING_PRIORITY, PROMPTING_PRIORITY, CONFIGURING_PRIORITY, LOADING_PRIORITY, PREPARING_PRIORITY, WRITING_PRIORITY } = @@ -175,7 +176,7 @@ module.exports = class extends BaseDockerGenerator { // Add database configuration const database = appConfig.prodDatabaseType; if (database !== NO_DATABASE && database !== ORACLE) { - const relativePath = pathjs.relative(this.destinationRoot(), `${path}/src/main/docker`); + const relativePath = normalize(pathjs.relative(this.destinationRoot(), `${path}/src/main/docker`)); const databaseYaml = jsyaml.load(this.fs.read(`${path}/src/main/docker/${database}.yml`)); const databaseServiceName = `${lowercaseBaseName}-${database}`; let databaseYamlConfig = databaseYaml.services[databaseServiceName]; @@ -193,7 +194,7 @@ module.exports = class extends BaseDockerGenerator { cassandraMigrationConfig.build.context = relativePath; const createKeyspaceScript = cassandraClusterYaml.services[`${databaseServiceName}-migration`].environment[0]; cassandraMigrationConfig.environment.push(createKeyspaceScript); - const cqlFilesRelativePath = pathjs.relative(this.destinationRoot(), `${path}/src/main/resources/config/cql`); + const cqlFilesRelativePath = normalize(pathjs.relative(this.destinationRoot(), `${path}/src/main/resources/config/cql`)); cassandraMigrationConfig.volumes[0] = `${cqlFilesRelativePath}:/cql:ro`; parentConfiguration[`${databaseServiceName}-migration`] = cassandraMigrationConfig;
Normalize docker-compose paths
jhipster_generator-jhipster
train
4c287c4d0971f5a7e312b1ea3cccfcf572c63b16
diff --git a/examples/3_subcomponents/subcomponents.js b/examples/3_subcomponents/subcomponents.js index <HASH>..<HASH> 100644 --- a/examples/3_subcomponents/subcomponents.js +++ b/examples/3_subcomponents/subcomponents.js @@ -40,8 +40,8 @@ export class Dashboard extends TanokDispatcher { export class TwoCounters extends React.Component { render() { return <div> - <Counter {...this.props.top} eventStream={this.sub('top')} /> - <Counter {...this.props.bottom} eventStream={this.sub('bottom')} /> + <Counter {...this.props.top} tanokStream={this.sub('top')} /> + <Counter {...this.props.bottom} tanokStream={this.sub('bottom')} /> </div> } } diff --git a/examples/4_subcomponent_collection/subcomponents.js b/examples/4_subcomponent_collection/subcomponents.js index <HASH>..<HASH> 100644 --- a/examples/4_subcomponent_collection/subcomponents.js +++ b/examples/4_subcomponent_collection/subcomponents.js @@ -1,5 +1,5 @@ import React from 'react'; -import {on, TanokDispatcher, effectWrapper, tanokComponent} from '../../lib/tanok.js'; +import {on, TanokDispatcher, effectWrapper, subcomponentFx, rethrowFx, tanokComponent} from '../../lib/tanok.js'; import {init as counterInit, CounterDispatcher, Counter} from './counter-collection.js'; @@ -12,30 +12,32 @@ export function init() { } export class Dashboard extends TanokDispatcher { + @on('init') + init(payload, state) { + return [state, + subcomponentFx('countersChange', (new CounterDispatcher).collect()), + ] + } + @on('countersChange') countersChange(payload, state, {metadata}) { const [newState, ...effects] = payload(state.counters[metadata]); state.counters[metadata] = newState; return [state, ...effects.map((e) => effectWrapper(e, 'countersChange'))] } + + @on('rerender') + rerender(payload, state) { + return [state]; + } } @tanokComponent export class CountersCollection extends React.Component { - componentWillMount() { - this.setState({ - countersChange: this.subStream('countersChange', (new CounterDispatcher).collect()), - }); - } - - componentWillUnmount() { - this.state.countersChange.disposable(); - } - render() { return <div> {this.props.counters.map((counter) => - <Counter key={counter.id} {...counter} eventStream={this.state.countersChange} /> + <Counter key={counter.id} tanokStream={this.sub('countersChange')} {...counter} /> )} </div> } diff --git a/examples/main.js b/examples/main.js index <HASH>..<HASH> 100644 --- a/examples/main.js +++ b/examples/main.js @@ -27,25 +27,24 @@ import { } from './4_subcomponent_collection/subcomponents.js'; // basic usage -tanok(init_1(), (new CounterDispatcher1).collect(), Counter1); +tanok(init_1(), (new CounterDispatcher1), Counter1); // Using effects (asynchronous events) -tanok(init_2(), (new CounterDispatcher2).collect(), Counter2); +tanok(init_2(), (new CounterDispatcher2), Counter2); // Simple subcomponents -tanok(init_3(), (new Dashboard).collect(), TwoCounters); +tanok(init_3(), (new Dashboard), TwoCounters); // Subcomponents for handling collection of subitems -tanok(init_4(), (new Dashboard2).collect(), CountersCollection); +tanok(init_4(), (new Dashboard2), CountersCollection); // Outer event stream example import Rx from 'rx'; -const ticks = Rx.Observable.interval(1000).map({ +const ticks = Rx.Observable.interval(1000).map(() => { return { parent: null, action: 'inc' -}); - -tanok(init_1(), (new CounterDispatcher1).collect(), Counter1, {outerEventStream: ticks}); +}}); +tanok(init_1(), (new CounterDispatcher1), Counter1, {outerEventStream: ticks});
Tweak examples to fit new sugaring
brabadu_tanok
train
7c162f0152ff27b2806f30aa2979171badfdef00
diff --git a/name_cleaver/name_cleaver.py b/name_cleaver/name_cleaver.py index <HASH>..<HASH> 100644 --- a/name_cleaver/name_cleaver.py +++ b/name_cleaver/name_cleaver.py @@ -4,7 +4,7 @@ SUFFIX_RE = '([js]r\.?|[IVX]{2,})' class Name(object): - scottish_re = r'(?i)\b(?P<mc>ma?c)(?P<first_letter>\w)\w+' + scottish_re = r'(?i)\b(?P<mc>ma?c)(?!hin)(?P<first_letter>\w)\w+' def primary_name_parts(self): raise NotImplementedError("Subclasses of Name must implement primary_name_parts.") diff --git a/name_cleaver/test_name_cleaver.py b/name_cleaver/test_name_cleaver.py index <HASH>..<HASH> 100644 --- a/name_cleaver/test_name_cleaver.py +++ b/name_cleaver/test_name_cleaver.py @@ -108,6 +108,9 @@ class TestOrganizationNameCleaver(unittest.TestCase): self.assertEqual('McDonnell Douglas', str(OrganizationNameCleaver('MCDONNELL DOUGLAS').parse())) self.assertEqual('MacDonnell Douglas', str(OrganizationNameCleaver('MACDONNELL DOUGLAS').parse())) + def test_dont_capitalize_just_anything_starting_with_mac(self): + self.assertEqual('Machinists/Aerospace Workers Union', str(OrganizationNameCleaver('MACHINISTS/AEROSPACE WORKERS UNION').parse())) + def test_expand(self): self.assertEqual('Raytheon Corporation', OrganizationNameCleaver('Raytheon Corp.').parse().expand()) self.assertEqual('Massachusetts Institute of Technology', OrganizationNameCleaver('Massachusetts Inst. of Technology').parse().expand())
[#<I>] Fix overzealous Scottish name detection for "Machinists"
sunlightlabs_name-cleaver
train