hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
c200f4df2c873fafdf3c96f45aad3eb1f86643bc
diff --git a/mainwindow.py b/mainwindow.py index <HASH>..<HASH> 100644 --- a/mainwindow.py +++ b/mainwindow.py @@ -26,28 +26,6 @@ class Window(QtGui.QMainWindow): self.model.setHorizontalHeaderLabels(['Name', 'NodeId', 'NodeClass']) self.ui.treeView.setModel(self.model) self.ui.treeView.setUniformRowHeights(True) - # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - # populate data - - #for i in range(3): - #parent1 = for j in range(3): - #child1 = QtGui.QStandardItem('Child {}'.format(i*3+j)) - #child2 = QtGui.QStandardItem('row: {}, col: {}'.format(i, j+1)) - #child3 = QtGui.QStandardItem('row: {}, col: {}'.format(i, j+2)) - #parent1.appendRow([child1, child2, child3]) - #model.appendRow(parent1) - # span container columns - #self.ui.treeView.setFirstColumnSpanned(i, , True) - # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - # expand third container - #index = model.indexFromItem(parent1) - #self.ui.treeView.expand(index) - # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - # select last row - #selmod = self.ui.treeView.selectionModel() - #index2 = model.indexFromItem(child3) - #selmod.select(index2, QtGui.QItemSelectionModel.Select|QtGui.QItemSelectionModel.Rows) - # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.uaclient = UaClient() self.ui.connectButton.clicked.connect(self._connect) @@ -59,6 +37,7 @@ class Window(QtGui.QMainWindow): print("expanded ", idx) def _connect(self): + self._disconnect() uri = self.ui.addrLineEdit.text() self.uaclient.connect(uri) self.model.client = self.uaclient @@ -81,13 +60,11 @@ class MyModel(QtGui.QStandardItemModel): self._fetched = [] def add_item(self, attrs, parent=None): - print("add item ", attrs, " to ", parent) data = [QtGui.QStandardItem(str(attr)) for attr in attrs[1:]] data[0].setData(attrs[0]) if parent: return parent.appendRow(data) else: - print("adding: ", data) return self.appendRow(data) def canFetchMore(self, idx): @@ -110,10 +87,7 @@ class MyModel(QtGui.QStandardItemModel): return True def fetchMore(self, idx): - print("Fetch more", idx) - parent = self.itemFromIndex(idx) - print(parent) if not parent: print("No item for ids: ", idx) else: diff --git a/uaclient.py b/uaclient.py index <HASH>..<HASH> 100644 --- a/uaclient.py +++ b/uaclient.py @@ -18,9 +18,10 @@ class UaClient(object): self.client = None def connect(self, uri): + #if self.client: + #print("we are already connected, disconnecting from current server") + #self.client.disconnect() print("Connecting to ", uri) - if self.client: - self.client.disconnect() self.client = Client(uri) self.client.connect() print("Connected, root is: ", self.client.get_root_node()) @@ -30,6 +31,7 @@ class UaClient(object): if self.client: print("Disconnecting from server") self.client.disconnect() + self.client = None def browse(self, nodeid): """ @@ -53,7 +55,6 @@ class UaClient(object): children = [] for desc in descs: children.append([self.client.get_node(desc.NodeId), desc.DisplayName.Text, desc.NodeId, desc.BrowseName]) - print(children) return children
correctly handle mutliple clicks on connect and disconnect
FreeOpcUa_opcua-client-gui
train
4b4d4d33326965edc36d5c48e1fa09fe8c8fea69
diff --git a/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java b/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java +++ b/core/src/main/java/org/acegisecurity/intercept/AbstractSecurityInterceptor.java @@ -210,30 +210,24 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, Assert.notNull(this.obtainObjectDefinitionSource(), "An ObjectDefinitionSource is required"); - if (!this.obtainObjectDefinitionSource() - .supports(getSecureObjectClass())) { - throw new IllegalArgumentException( + Assert.isTrue(this.obtainObjectDefinitionSource() + .supports(getSecureObjectClass()), "ObjectDefinitionSource does not support secure object class: " - + getSecureObjectClass()); - } + + getSecureObjectClass() + ); - if (!this.runAsManager.supports(getSecureObjectClass())) { - throw new IllegalArgumentException( + Assert.isTrue(this.runAsManager.supports(getSecureObjectClass()), "RunAsManager does not support secure object class: " - + getSecureObjectClass()); - } + + getSecureObjectClass() ); - if (!this.accessDecisionManager.supports(getSecureObjectClass())) { - throw new IllegalArgumentException( + Assert.isTrue(this.accessDecisionManager.supports(getSecureObjectClass()), "AccessDecisionManager does not support secure object class: " + getSecureObjectClass()); - } - if ((this.afterInvocationManager != null) - && !this.afterInvocationManager.supports(getSecureObjectClass())) { - throw new IllegalArgumentException( - "AfterInvocationManager does not support secure object class: " - + getSecureObjectClass()); + if (this.afterInvocationManager != null) { + Assert.isTrue(this.afterInvocationManager.supports(getSecureObjectClass()), + "AfterInvocationManager does not support secure object class: " + + getSecureObjectClass()); } if (this.validateConfigAttributes) { @@ -281,12 +275,13 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, protected InterceptorStatusToken beforeInvocation(Object object) { Assert.notNull(object, "Object was null"); - Assert.isTrue(getSecureObjectClass() - .isAssignableFrom(object.getClass()), - "Security invocation attempted for object " + + if(!getSecureObjectClass().isAssignableFrom(object.getClass())) { + throw new IllegalArgumentException ("Security invocation attempted for object " + object.getClass().getName() + " but AbstractSecurityInterceptor only configured to support secure objects of type: " + getSecureObjectClass()); + } ConfigAttributeDefinition attr = this.obtainObjectDefinitionSource() .getAttributes(object);
Added some uses of Spring Assert class and removed one to prevent unnecessary StringBuffer creation.
spring-projects_spring-security
train
b6d7e2427799adcb5f0bbc32f418fd1f8ceac610
diff --git a/modularodm/tests/backrefs/test_many_to_many.py b/modularodm/tests/backrefs/test_many_to_many.py index <HASH>..<HASH> 100644 --- a/modularodm/tests/backrefs/test_many_to_many.py +++ b/modularodm/tests/backrefs/test_many_to_many.py @@ -96,6 +96,34 @@ class ManyToManyFieldTestCase(PickleStorageTestCase): {'foo': {'my_bar': []}} ) + def test_replace_backref(self): + """ Replace an existing item in the ForeignList field with another + remote object. + """ + + # create a new bar + new_bar = self.Bar(_id=9) + new_bar.save() + + # replace the first bar in the list with it. + old_bar_id = self.foo.my_bar[0]._id + self.foo.my_bar[0] = new_bar + self.foo.save() + + # the old Bar should no longer have a backref to foo + old_bar = self.Bar.load(old_bar_id) + self.assertEqual( + old_bar._backrefs, + {'my_foo': {'foo': {'my_bar': []}}} + ) + + # the new Bar should have a backref to foo + self.assertEqual( + new_bar._backrefs, + {'my_foo': {'foo': {'my_bar': [1]}}} + ) + print new_bar._backrefs + def test_delete_backref_attribute_from_remote_via_pop(self): """ Delete a backref from its attribute on the remote object by calling .pop().
Adds test for assignment by index of a ForeignList
cos-archives_modular-odm
train
d000e422d55d28ea79f035a9714c0b7274cf0f61
diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -6,12 +6,12 @@ <groupId>org.whitesource</groupId> <artifactId>whitesource-fs-agent</artifactId> - <version>1.4.1-SNAPSHOT</version> + <version>1.5-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <agent.api.version>2.1.0</agent.api.version> + <agent.api.version>2.2.0-SNAPSHOT</agent.api.version> <slf4j.version>1.7.7</slf4j.version> </properties> diff --git a/src/main/java/org/whitesource/fs/Constants.java b/src/main/java/org/whitesource/fs/Constants.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/whitesource/fs/Constants.java +++ b/src/main/java/org/whitesource/fs/Constants.java @@ -45,6 +45,6 @@ public final class Constants { public static final String SCM_TAG_PROPERTY_KEY = "scm.tag"; public static final String AGENT_TYPE = "fs-agent"; - public static final String AGENT_VERSION = "2.0.1"; + public static final String AGENT_VERSION = "2.2.0"; } diff --git a/src/main/java/org/whitesource/fs/DependencyInfoFactory.java b/src/main/java/org/whitesource/fs/DependencyInfoFactory.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/whitesource/fs/DependencyInfoFactory.java +++ b/src/main/java/org/whitesource/fs/DependencyInfoFactory.java @@ -79,6 +79,10 @@ public class DependencyInfoFactory { dependencyInfo.setSystemPath(dependencyFile.getAbsolutePath()); } + // calculate sha1 for file header and footer (for partial matching) + ChecksumUtils.calculateHeaderAndFooterSha1(dependencyFile, dependencyInfo); + + // scan for licenses try { Set<String> licenses = scanLicenses(dependencyFile); dependencyInfo.getLicenses().addAll(licenses);
calculate sha1 for file header and footer (for partial matching)
whitesource_fs-agent
train
ff108b9df16abc3e3e7e9ad811ad150f52fb41c7
diff --git a/src/com/invertor/modbus/slave/RequestHandlerSerial.java b/src/com/invertor/modbus/slave/RequestHandlerSerial.java index <HASH>..<HASH> 100644 --- a/src/com/invertor/modbus/slave/RequestHandlerSerial.java +++ b/src/com/invertor/modbus/slave/RequestHandlerSerial.java @@ -73,6 +73,7 @@ class RequestHandlerSerial extends RequestHandler { transport.send(response); if (commStatus.isRestartCommunicationsOption()) { commStatus.restartCommunicationsOption(); + getSlave().shutdown(); getSlave().listen(); } } catch (RuntimeException re) {
fix handling of RestartCommunicationsOption.
kochedykov_jlibmodbus
train
1a4020bfb3738dbd89657a04c31d13d473a93caa
diff --git a/lib/RMagick.rb b/lib/RMagick.rb index <HASH>..<HASH> 100644 --- a/lib/RMagick.rb +++ b/lib/RMagick.rb @@ -1,4 +1,4 @@ -# $Id: RMagick.rb,v 1.74 2008/08/28 23:25:46 rmagick Exp $ +# $Id: RMagick.rb,v 1.75 2008/09/28 00:24:41 rmagick Exp $ #============================================================================== # Copyright (C) 2008 by Timothy P. Hunter # Name: RMagick.rb @@ -734,6 +734,8 @@ end # module Magick::IPTC class Image include Comparable + alias_method :affinity, :remap + # Provide an alternate version of Draw#annotate, for folks who # want to find it in this class. def annotate(draw, width, height, x, y, text, &block) @@ -1467,6 +1469,9 @@ public alias_method :map!, :collect! alias_method :__map__!, :collect! + # ImageMagic used affinity in 6.4.3, switch to remap in 6.4.4. + alias_method :affinity, :remap + def compact current = get_current() ilist = self.class.new
alias affinity to remap for backward compatibility
rmagick_rmagick
train
4ae3b7ad9299e2039ad1118e815089fc4c4dab7d
diff --git a/openquake/baselib/parallel.py b/openquake/baselib/parallel.py index <HASH>..<HASH> 100644 --- a/openquake/baselib/parallel.py +++ b/openquake/baselib/parallel.py @@ -514,7 +514,7 @@ class IterResult(object): tot = sum(self.received) max_per_output = max(self.received) logging.info( - 'Received %s from %d %r outputs in %d seconds, biggest ' + 'Received %s from %d %s outputs in %d seconds, biggest ' 'output=%s', humansize(tot), len(self.received), '|'.join(names), time.time() - t0, humansize(max_per_output)) if nbytes: diff --git a/openquake/commonlib/readinput.py b/openquake/commonlib/readinput.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/readinput.py +++ b/openquake/commonlib/readinput.py @@ -262,7 +262,8 @@ def read_csv(fname, sep=','): """ with open(fname, encoding='utf-8-sig') as f: header = next(f).strip().split(sep) - dt = numpy.dtype([(h, float) for h in header]) + dt = numpy.dtype([(h, numpy.bool if h == 'vs30measured' else float) + for h in header]) return numpy.loadtxt(f, dt, delimiter=sep) @@ -354,7 +355,10 @@ def get_site_model(oqparam): if 'site_id' in sm.dtype.names: raise InvalidFile('%s: you passed a sites.csv file instead of ' 'a site_model.csv file!' % fname) - arrays.append(sm) + z = numpy.zeros(len(sm), sorted(sm.dtype.descr)) + for name in z.dtype.names: # reorder the fields + z[name] = sm[name] + arrays.append(z) continue nodes = nrml.read(fname).siteModel params = [valid.site_param(node.attrib) for node in nodes]
Fixed an ordering bug while reading the site models [skip hazardlib] Former-commit-id: 7fbcad<I>e3dd8ad<I>adc7dc<I>ced<I>e<I>
gem_oq-engine
train
b06121bdfdef6bcbbd08087413d7add52c143978
diff --git a/src/Plugin/Manager.php b/src/Plugin/Manager.php index <HASH>..<HASH> 100644 --- a/src/Plugin/Manager.php +++ b/src/Plugin/Manager.php @@ -37,6 +37,13 @@ class Manager use \Jaxon\Utils\Traits\Translator; /** + * The response type. + * + * @var string + */ + const RESPONSE_TYPE = 'JSON'; + + /** * All plugins, indexed by priority * * @var array @@ -119,9 +126,6 @@ class Manager $this->bAutoloadEnabled = true; $this->xAutoloader = null; - // Set response type to JSON - $this->sResponseType = 'JSON'; - // Javascript confirm function $this->xConfirm = null; $this->xDefaultConfirm = new \Jaxon\Request\Support\Confirm(); @@ -719,7 +723,7 @@ class Manager private function getOptionVars() { return array( - 'sResponseType' => $this->sResponseType, + 'sResponseType' => self::RESPONSE_TYPE, 'sVersion' => $this->getOption('core.version'), 'sLanguage' => $this->getOption('core.language'), 'bLanguage' => $this->hasOption('core.language') ? true : false,
Changed the response type to a constant.
jaxon-php_jaxon-core
train
fe8b45d33b9d1a1e5e9955c394ce6d59291cffcd
diff --git a/src/includes/classes/Core/Utils/Markdown.php b/src/includes/classes/Core/Utils/Markdown.php index <HASH>..<HASH> 100644 --- a/src/includes/classes/Core/Utils/Markdown.php +++ b/src/includes/classes/Core/Utils/Markdown.php @@ -88,8 +88,12 @@ class Markdown extends Classes\Core\Base\Core $anchorize = (bool) $args['anchorize']; $anchor_rels = (array) $args['anchor_rels']; - if ($cache) { // Cache markdown? - $cache_sha1 = sha1($string.$post_id.serialize($args)); + if ($cache) { // Cache? + $cache_args = $args; + // Cannot serialize closures. + unset($cache_args['header_id_func']); + + $cache_sha1 = sha1($string.$post_id.serialize($cache_args)); $cache_sha1_shard_id = $this->c::sha1ModShardId($cache_sha1, true); $cache_dir = $this->App->Config->©fs_paths['©cache_dir'].'/markdown/'.$cache_sha1_shard_id;
Avoid serializing callback closures.
wpsharks_core
train
2d25f97f997675da511c1f54bed7a4d9c4a87224
diff --git a/artifacts/source_type.py b/artifacts/source_type.py index <HASH>..<HASH> 100644 --- a/artifacts/source_type.py +++ b/artifacts/source_type.py @@ -176,6 +176,18 @@ class WindowsRegistryValueSourceType(SourceType): if not key_value_pairs: raise errors.FormatError(u'Missing key value pairs value.') + if not isinstance(key_value_pairs, list): + raise errors.FormatError(u'key_value_pairs must be a list, got: %s' % + key_value_pairs) + + for pair in key_value_pairs: + if not isinstance(pair, dict): + raise errors.FormatError(u'key_value_pair must be a dict, got: %s' % + key_value_pairs) + if set(pair.keys()) != set(['key', 'value']): + raise errors.FormatError(u'key_value_pair missing "key" and "value"' + u' keys, got: %s' % key_value_pairs) + super(WindowsRegistryValueSourceType, self).__init__() self.key_value_pairs = key_value_pairs diff --git a/artifacts/source_type_test.py b/artifacts/source_type_test.py index <HASH>..<HASH> 100644 --- a/artifacts/source_type_test.py +++ b/artifacts/source_type_test.py @@ -3,6 +3,7 @@ import unittest +from artifacts import errors from artifacts import source_type @@ -79,14 +80,23 @@ class WindowsRegistryValueSourceTypeTest(unittest.TestCase): def testInitialize(self): """Tests the __init__ function.""" source_type.WindowsRegistryValueSourceType( - key_value_pairs={'key': u'test', 'value': u'test'}) + key_value_pairs=[{'key': u'test', 'value': u'test'}]) with self.assertRaises(TypeError): source_type.WindowsRegistryValueSourceType(bogus=u'bogus') with self.assertRaises(TypeError): source_type.WindowsRegistryValueSourceType( - key_value_pairs={'key': u'test', 'value': u'test'}, bogus=u'bogus') + key_value_pairs=[{'key': u'test', 'value': u'test'}], bogus=u'bogus') + + with self.assertRaises(errors.FormatError): + source_type.WindowsRegistryValueSourceType( + key_value_pairs=[{'bad': u'test', 'value': u'test'}]) + + with self.assertRaises(errors.FormatError): + source_type.WindowsRegistryValueSourceType( + key_value_pairs={'bad': u'test', 'value': u'test'}) + class WMIQuerySourceType(unittest.TestCase): diff --git a/definitions/windows.yaml b/definitions/windows.yaml index <HASH>..<HASH> 100644 --- a/definitions/windows.yaml +++ b/definitions/windows.yaml @@ -607,7 +607,7 @@ name: WinRARExternalViewer doc: Executable run when a file is opened by WinRAR inside an archive. sources: - type: REGISTRY_VALUE - attributes: {key_value_pairs: {key: 'HKEY_USERS\%%users.sid%%\Software\WinRAR\Viewer\', value: 'ExternalViewer'}} + attributes: {key_value_pairs: [{key: 'HKEY_USERS\%%users.sid%%\Software\WinRAR\Viewer\', value: 'ExternalViewer'}]} supported_os: [Windows] urls: - 'http://www.hexacorn.com/blog/2012/09/16/beyond-good-ol-run-key-part-2/' @@ -617,7 +617,7 @@ name: WinRARAVScan doc: Executable run to scan a file when it is opened by WinRAR. sources: - type: REGISTRY_VALUE - attributes: {key_value_pairs: {key: 'HKEY_USERS\%%users.sid%%\Software\WinRAR\VirusScan\', value: 'Name'}} + attributes: {key_value_pairs: [{key: 'HKEY_USERS\%%users.sid%%\Software\WinRAR\VirusScan\', value: 'Name'}]} supported_os: [Windows] urls: - 'http://www.hexacorn.com/blog/2012/09/16/beyond-good-ol-run-key-part-2/'
Fix WinRAR artifacts, add better validation.
ForensicArtifacts_artifacts
train
0d93a2911454b0b6b35a71b879a2edf59d288697
diff --git a/ykman/device.py b/ykman/device.py index <HASH>..<HASH> 100644 --- a/ykman/device.py +++ b/ykman/device.py @@ -271,14 +271,18 @@ class YubiKey(object): self.device_name = 'YubiKey Preview' elif self.version >= (5, 1, 0): logger.debug('Identified YubiKey 5') - if config.form_factor == FORM_FACTOR.USB_A_KEYCHAIN: - self.device_name = 'YubiKey 5 NFC' + self.device_name = 'YubiKey 5' + if config.form_factor == FORM_FACTOR.USB_A_KEYCHAIN \ + and not config.nfc_supported: + self.device_name += 'A' + elif config.form_factor == FORM_FACTOR.USB_A_KEYCHAIN: + self.device_name += ' NFC' elif config.form_factor == FORM_FACTOR.USB_A_NANO: - self.device_name = 'YubiKey 5 Nano' + self.device_name += ' Nano' elif config.form_factor == FORM_FACTOR.USB_C_KEYCHAIN: - self.device_name = 'YubiKey 5C' + self.device_name += 'C' elif config.form_factor == FORM_FACTOR.USB_C_NANO: - self.device_name = 'YubiKey 5C Nano' + self.device_name += 'C Nano' elif self.is_fips: self.device_name = 'YubiKey FIPS'
add support for YubiKey 5A
Yubico_yubikey-manager
train
1f6eed75731b4df88e1f37392ae87502b5e28cac
diff --git a/client/client.go b/client/client.go index <HASH>..<HASH> 100644 --- a/client/client.go +++ b/client/client.go @@ -346,7 +346,7 @@ func (r *RPC) connectBatchedConnection(ctx context.Context, name string) (Connec closer := func() { select { case <-ctx.Done(): - r.log.Debug("Closing connection") + r.log.Debugf("Closing batched connection %s", name) connector.Close() } }
(#<I>) ensure subscription copiers exit correctly The subscription copiers would not always exit correctly which as they are being closed in the Close() call would lead to stale NATS connections and a leak in go routines when using the client in a long running program This ensures that they will exit properly and stops the leaks
choria-io_go-choria
train
6e3c78c71ed6a41790b9c2b4c5279a1597d90a86
diff --git a/src/classes/connection.php b/src/classes/connection.php index <HASH>..<HASH> 100644 --- a/src/classes/connection.php +++ b/src/classes/connection.php @@ -294,7 +294,9 @@ class phpillowConnection } $metaData = stream_get_meta_data( $httpFilePointer ); - $rawHeaders = $metaData['wrapper_data']['headers']; + // @TODO: This seems to have changed in last CVS versions of PHP 5.3, + // should be removeable, once there is a next release of PHP 5.3 + $rawHeaders = isset( $metaData['wrapper_data']['headers'] ) ? $metaData['wrapper_data']['headers'] : $metaData['wrapper_data']; $headers = array(); foreach ( $rawHeaders as $lineContent )
# Handle both types of metadata information, differing between different # revisions of PHP <I>-alpha2-dev git-svn-id: svn://arbitracker.org/phpillow/trunk@<I> c<I>fd1-f2a0-<I>e-a8e5-<I>dc<I>
Arbitracker_PHPillow
train
863f7fcd067efd2bfbd58cc7829953768c2a6685
diff --git a/openstack_dashboard/dashboards/admin/instances/views.py b/openstack_dashboard/dashboards/admin/instances/views.py index <HASH>..<HASH> 100644 --- a/openstack_dashboard/dashboards/admin/instances/views.py +++ b/openstack_dashboard/dashboards/admin/instances/views.py @@ -193,6 +193,7 @@ class LiveMigrateView(forms.ModalFormView): class DetailView(views.DetailView): redirect_url = 'horizon:admin:instances:index' + image_url = 'horizon:admin:images:detail' def _get_actions(self, instance): table = project_tables.AdminInstancesTable(self.request) diff --git a/openstack_dashboard/dashboards/project/instances/templates/instances/_detail_overview.html b/openstack_dashboard/dashboards/project/instances/templates/instances/_detail_overview.html index <HASH>..<HASH> 100644 --- a/openstack_dashboard/dashboards/project/instances/templates/instances/_detail_overview.html +++ b/openstack_dashboard/dashboards/project/instances/templates/instances/_detail_overview.html @@ -113,11 +113,10 @@ {% with formatted_default_key_name="<em>"|add:default_key_name|add:"</em>" %} <dd>{{ instance.key_name|default:formatted_default_key_name }}</dd> {% endwith %} - {% url 'horizon:project:images:images:detail' instance.image.id as image_url %} <dt>{% trans "Image Name" %}</dt> <dd> {% if instance.image %} - <a href="{{ image_url }}">{{ instance.image_name }}</a> + <a href="{{ instance.image_url }}">{{ instance.image_name }}</a> {% else %} <em>{% trans "None" %}</em> {% endif %} diff --git a/openstack_dashboard/dashboards/project/instances/views.py b/openstack_dashboard/dashboards/project/instances/views.py index <HASH>..<HASH> 100644 --- a/openstack_dashboard/dashboards/project/instances/views.py +++ b/openstack_dashboard/dashboards/project/instances/views.py @@ -292,10 +292,14 @@ class DetailView(tabs.TabView): template_name = 'project/instances/detail.html' redirect_url = 'horizon:project:instances:index' page_title = _("Instance Details: {{ instance.name }}") + image_url = 'horizon:project:images:images:detail' def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) instance = self.get_data() + if instance.image: + instance.image_url = reverse(self.image_url, + args=[instance.image['id']]) context["instance"] = instance context["url"] = reverse(self.redirect_url) context["actions"] = self._get_actions(instance)
corrected the wrong url in admin instance detail In admin instance detail page, the image url pointing to image detail page in project panel. This behavior is wrong, it should be link to admin panel only. This patch corrected the url to point to the admin panel image detail page. Change-Id: I4ec<I>cc<I>e<I>b2be<I>dc<I>e<I>f<I>fa8a1a<I> Closes-Bug: #<I>
openstack_horizon
train
1885954e6e456616e895520e61c0b07308d23a97
diff --git a/src/Persistence.php b/src/Persistence.php index <HASH>..<HASH> 100644 --- a/src/Persistence.php +++ b/src/Persistence.php @@ -51,6 +51,7 @@ class Persistence switch (strtolower(isset($args['driver']) ?: $driver)) { case 'mysql': + case 'oci': // Omitting UTF8 is always a bad problem, so unless it's specified we will do that // to prevent nasty problems. This is un-tested on other databases, so moving it here. // It gives problem with sqlite
Oracle also should have charset=utf8 set
atk4_data
train
13fd91eadb7e5912c5f4a6f3cd74a5320548d1af
diff --git a/lib/dragonfly/data_storage/file_data_store.rb b/lib/dragonfly/data_storage/file_data_store.rb index <HASH>..<HASH> 100644 --- a/lib/dragonfly/data_storage/file_data_store.rb +++ b/lib/dragonfly/data_storage/file_data_store.rb @@ -52,6 +52,7 @@ module Dragonfly path = absolute(relative_path) FileUtils.rm path FileUtils.rm_f meta_data_path(path) + FileUtils.rm_f deprecated_meta_data_path(path) purge_empty_directories(relative_path) rescue Errno::ENOENT => e raise DataNotFound, e.message @@ -95,6 +96,10 @@ module Dragonfly "#{data_path}.meta" end + def deprecated_meta_data_path(data_path) + "#{data_path}.extra" + end + def relative_path_for(filename) time = Time.now msec = time.usec / 1000 @@ -109,7 +114,12 @@ module Dragonfly def retrieve_meta_data(data_path) path = meta_data_path(data_path) - File.exist?(path) ? File.open(path,'rb'){|f| Marshal.load(f.read) } : {} + if File.exist?(path) + File.open(path,'rb'){|f| Marshal.load(f.read) } + else + deprecated_path = deprecated_meta_data_path(data_path) + File.exist?(deprecated_path) ? File.open(deprecated_path,'rb'){|f| Marshal.load(f.read) } : {} + end end def prepare_path(path) diff --git a/spec/dragonfly/data_storage/file_data_store_spec.rb b/spec/dragonfly/data_storage/file_data_store_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dragonfly/data_storage/file_data_store_spec.rb +++ b/spec/dragonfly/data_storage/file_data_store_spec.rb @@ -159,6 +159,12 @@ describe Dragonfly::DataStorage::FileDataStore do pathname.read.should == 'hey dog' meta.should == {} end + it "should work even if meta is stored in old .extra file" do + uid = @data_store.store(@temp_object, :meta => {:dog => 'food'}) + FileUtils.mv("#{@data_store.root_path}/#{uid}.meta", "#{@data_store.root_path}/#{uid}.extra") + pathname, meta = @data_store.retrieve(uid) + meta.should == {:dog => 'food'} + end end describe "destroying" do @@ -177,6 +183,15 @@ describe Dragonfly::DataStorage::FileDataStore do }.should raise_error(Dragonfly::DataStorage::DataNotFound) end + it "should also destroy old .extra files" do + uid = @data_store.store(@temp_object) + FileUtils.cp("#{@data_store.root_path}/#{uid}.meta", "#{@data_store.root_path}/#{uid}.extra") + @data_store.destroy(uid) + File.exist?("#{@data_store.root_path}/#{uid}").should be_false + File.exist?("#{@data_store.root_path}/#{uid}.meta").should be_false + File.exist?("#{@data_store.root_path}/#{uid}.extra").should be_false + end + end describe "relative paths" do
File data store works gracefully with old xxx.extra files (now deprecated - xxx.meta instead)
markevans_dragonfly
train
8c31975cd91f2d8a8f22466256fccd3207ff7ba1
diff --git a/airflow/models.py b/airflow/models.py index <HASH>..<HASH> 100644 --- a/airflow/models.py +++ b/airflow/models.py @@ -1156,7 +1156,8 @@ class DAG(Base): env = jinja2.Environment( loader=jinja2.FileSystemLoader(searchpath), - extensions=["jinja2.ext.do"]) + extensions=["jinja2.ext.do"], + cache_size=0) if self.user_defined_macros: env.globals.update(self.user_defined_macros) diff --git a/airflow/www/app.py b/airflow/www/app.py index <HASH>..<HASH> 100644 --- a/airflow/www/app.py +++ b/airflow/www/app.py @@ -472,6 +472,9 @@ class Airflow(BaseView): @expose('/dag_stats') def dag_stats(self): states = [State.SUCCESS, State.RUNNING, State.FAILED] + task_ids = [] + for dag in dagbag.dags.values(): + task_ids += dag.task_ids data = {} TI = models.TaskInstance session = Session() @@ -479,7 +482,7 @@ class Airflow(BaseView): TI.dag_id, TI.state, sqla.func.count(TI.task_id) - ).group_by(TI.dag_id, TI.state) + ).filter(TI.task_id.in_(task_ids)).group_by(TI.dag_id, TI.state) for dag_id, state, count in qry: if dag_id not in data: data[dag_id] = {} @@ -506,7 +509,6 @@ class Airflow(BaseView): response=json.dumps(payload, indent=4), status=200, mimetype="application/json") - @expose('/code') def code(self): dag_id = request.args.get('dag_id') @@ -603,15 +605,14 @@ class Airflow(BaseView): content = getattr(task, template_field) if template_field in special_attrs: html_dict[template_field] = highlight( - content, - special_attrs[template_field](), # Lexer call - HtmlFormatter(noclasses=True) + content, + special_attrs[template_field](), # Lexer call + HtmlFormatter(noclasses=True) ) else: html_dict[template_field] = ( "<pre><code>" + content + "</pre></code>") - return self.render( 'airflow/dag_code.html', html_dict=html_dict, @@ -1065,7 +1066,7 @@ def log_link(v, c, m, p): execution_date=m.execution_date.isoformat()) return Markup( '<a href="{url}">' - '<span class="glyphicon glyphicon-book" aria-hidden="true">' + ' <span class="glyphicon glyphicon-book" aria-hidden="true">' '</span></a>').format(**locals()) @@ -1152,6 +1153,7 @@ class UserModelView(LoginMixin, ModelView): mv = UserModelView(models.User, Session, name="Users", category="Admin") admin.add_view(mv) + class DagModelView(ModelView): column_list = ('dag_id', 'is_paused') column_editable_list = ('is_paused',) @@ -1159,6 +1161,7 @@ mv = DagModelView( models.DAG, Session, name="Pause DAGs", category="Admin") admin.add_view(mv) + class ReloadTaskView(BaseView): @expose('/') def index(self):
Making sure task_ids are in range, disabling template caching And some flaking...
apache_airflow
train
147e75096f05feea60960c4963dd99e22db9d862
diff --git a/classes/Middleware/SaveRedirect.php b/classes/Middleware/SaveRedirect.php index <HASH>..<HASH> 100644 --- a/classes/Middleware/SaveRedirect.php +++ b/classes/Middleware/SaveRedirect.php @@ -28,10 +28,7 @@ class SaveRedirect { Session::keep(['success', 'errors']); return Redirect::to(Session::get('save_redirect')); } - - // Only act on save values of 'back' or 'new' - if (!Input::has('_save') || Input::get('_save') == 'save') return; - + // Go back to the listing if (Input::get('_save') == 'back') { Session::flash('save_redirect', Breadcrumbs::smartBack());
Unnecessary check was screwin up middleware chaining
BKWLD_decoy
train
6d654b8ca2b5a7dc3adf2a7231deb06840a223c8
diff --git a/Lib/fontParts/test/test_component.py b/Lib/fontParts/test/test_component.py index <HASH>..<HASH> 100644 --- a/Lib/fontParts/test/test_component.py +++ b/Lib/fontParts/test/test_component.py @@ -486,6 +486,7 @@ class TestComponent(unittest.TestCase): from .legacyPointPen import LegacyPointPen component = self.getComponent_generic() component.transformation = (1, 2, 3, 4, 5, 6) + component.getIdentifier() pointPen = LegacyPointPen() component.drawPoints(pointPen) expected = [('addComponent', (u'A', (1.0, 2.0, 3.0, 4.0, 5.0, 6.0)), {})]
Putting back in getting of identifier
robotools_fontParts
train
e85b7e78655c038fd29df19bfea81adb3dc4819c
diff --git a/lib/boxlib.php b/lib/boxlib.php index <HASH>..<HASH> 100644 --- a/lib/boxlib.php +++ b/lib/boxlib.php @@ -144,7 +144,7 @@ class boxclient { '__login'=>1 ); try { - $ret = $c->post($this->_box_api_auth_url.$ticket, $param); + $ret = $c->post($this->_box_api_auth_url.'/'.$ticket, $param); } catch (moodle_exception $e) { $this->setError(0, 'connection time-out or invalid url'); return false; @@ -245,7 +245,7 @@ class boxclient { 'size'=>display_size((int)$file->attributes()->size), 'thumbnail'=>$thumbnail, 'date'=>userdate((int)$file->attributes()->updated), - 'source'=> $this->_box_api_download_url + 'source'=> $this->_box_api_download_url .'/' .$this->auth_token.'/'.(string)$file->attributes()->id, 'url'=>(string)$file->attributes()->shared_link); $tree[] = $tmp;
MDL-<I> - Repositories - Fixing missing slash from the URL path
moodle_moodle
train
ac2a366a200ba2d806c22bf5d80b706d91664140
diff --git a/src/Illuminate/Testing/Fluent/AssertableJson.php b/src/Illuminate/Testing/Fluent/AssertableJson.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Testing/Fluent/AssertableJson.php +++ b/src/Illuminate/Testing/Fluent/AssertableJson.php @@ -86,7 +86,7 @@ class AssertableJson implements Arrayable PHPUnit::assertIsArray($props, sprintf('Property [%s] is not scopeable.', $path)); - $scope = new self($props, $path); + $scope = new static($props, $path); $callback($scope); $scope->interacted(); @@ -125,7 +125,7 @@ class AssertableJson implements Arrayable */ public static function fromArray(array $data): self { - return new self($data); + return new static($data); } /** @@ -136,7 +136,7 @@ class AssertableJson implements Arrayable */ public static function fromAssertableJsonString(AssertableJsonString $json): self { - return self::fromArray($json->json()); + return static::fromArray($json->json()); } /**
Make AssertableJson easier to extend by replacing `self` with `static` (#<I>) * Replace `self` -> `static` in AssertableJson * Change return type back to `self`
laravel_framework
train
9ba66e6a2e4f6ca08fa3bfb2a313545007a856a6
diff --git a/bundles/org.eclipse.orion.client.core/web/orion/i18n.js b/bundles/org.eclipse.orion.client.core/web/orion/i18n.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.core/web/orion/i18n.js +++ b/bundles/org.eclipse.orion.client.core/web/orion/i18n.js @@ -103,7 +103,7 @@ define(["orion/Deferred" return; } - if (parentRequire.specified && !parentRequire.specified("orion/bootstrap")) { + if (parentRequire.specified && (!parentRequire.specified("orion/bootstrap") || parentRequire.specified("orion/plugin"))) { onLoad({}); return; }
do not use the orion i<I>n support when running in a plugin
eclipse_orion.client
train
04ee74688e6ac5018626a8de78b61c29b2b0ad12
diff --git a/service/model/model_test.go b/service/model/model_test.go index <HASH>..<HASH> 100644 --- a/service/model/model_test.go +++ b/service/model/model_test.go @@ -315,8 +315,10 @@ func TestRead(t *testing.T) { t.Fatal(err) } + // TODO: remove this test since Read only returns 1 record + // from the store now rather than all err = table.Read(QueryEquals("age", 25), &user) - if err != ErrorMultipleRecordsFound { + if err == ErrorMultipleRecordsFound { t.Fatal(err) } } diff --git a/service/model/store.go b/service/model/store.go index <HASH>..<HASH> 100644 --- a/service/model/store.go +++ b/service/model/store.go @@ -373,8 +373,15 @@ func (d *model) Read(query Query, resultPointer interface{}) error { if d.options.Debug { fmt.Printf("Listing key '%v'\n", k) } - // TODO: set the table name in the query - recs, err := d.options.Store.Read(k, store.ReadPrefix(), store.ReadFrom(d.database, d.table)) + + // TODO: should we actually be reading prefix? + opts := []store.ReadOption{ + store.ReadPrefix(), + store.ReadFrom(d.database, d.table), + store.ReadLimit(1), + } + + recs, err := d.options.Store.Read(k, opts...) if err != nil { return err } @@ -387,6 +394,7 @@ func (d *model) Read(query Query, resultPointer interface{}) error { if d.options.Debug { fmt.Printf("Found value '%v'\n", string(recs[0].Value)) } + return json.Unmarshal(recs[0].Value, resultPointer) } if query.Type == queryTypeAll { @@ -419,8 +427,23 @@ func (d *model) list(query Query, resultSlicePointer interface{}) error { if d.options.Debug { fmt.Printf("Listing key '%v'\n", k) } + + // TODO: should we actually be reading prefix? + opts := []store.ReadOption{ + store.ReadPrefix(), + store.ReadFrom(d.database, d.table), + } + + if query.Limit > 0 { + opts = append(opts, store.ReadLimit(uint(query.Limit))) + } + + if query.Offset > 0 { + opts = append(opts, store.ReadOffset(uint(query.Offset))) + } + // TODO: set the table name in the query - recs, err := d.options.Store.Read(k, store.ReadPrefix(), store.ReadFrom(d.database, d.table)) + recs, err := d.options.Store.Read(k, opts...) if err != nil { return err }
Add support for limit/offset (#<I>)
micro_micro
train
72936496d5da7f25c61c3fa32e4167c5591423fa
diff --git a/firefox/test/java/org/openqa/selenium/firefox/internal/SocketLockTest.java b/firefox/test/java/org/openqa/selenium/firefox/internal/SocketLockTest.java index <HASH>..<HASH> 100644 --- a/firefox/test/java/org/openqa/selenium/firefox/internal/SocketLockTest.java +++ b/firefox/test/java/org/openqa/selenium/firefox/internal/SocketLockTest.java @@ -33,14 +33,14 @@ import org.openqa.selenium.WebDriverException; public class SocketLockTest extends TestCase { @Test - public void wellKnownLockLocation() { + public void testWellKnownLockLocation() { Lock lock = new SocketLock(12345); lock.lock(TimeUnit.SECONDS.toMillis(1)); lock.unlock(); } @Test - public void serialLockOnSamePort() { + public void testSerialLockOnSamePort() { for (int i = 0; i < 20; i++) { Lock lock = new SocketLock(24567); lock.lock(TimeUnit.SECONDS.toMillis(1)); @@ -49,7 +49,7 @@ public class SocketLockTest extends TestCase { } @Test - public void attemptToReuseLocksFails() { + public void testAttemptToReuseLocksFails() { Lock lock = new SocketLock(23456); lock.lock(TimeUnit.SECONDS.toMillis(1)); lock.unlock();
EranMes: Changing test names so they are junit3 friendly. r<I>
SeleniumHQ_selenium
train
1b1efb350d4a55548b72262467b8a3ae55b7de14
diff --git a/bin/style/main.go b/bin/style/main.go index <HASH>..<HASH> 100644 --- a/bin/style/main.go +++ b/bin/style/main.go @@ -25,6 +25,8 @@ type warningPrinter struct { } func (w warningPrinter) print(writer io.Writer) { + w.sortWarnings() + for _, warning := range w.warnings { coloredVars := make([]interface{}, len(warning.vars)) for i, v := range warning.vars { @@ -41,6 +43,29 @@ func (w warningPrinter) print(writer io.Writer) { } } +func (w warningPrinter) sortWarnings() { + sort.Slice(w.warnings, func(i int, j int) bool { + if w.warnings[i].Position.Filename < w.warnings[j].Position.Filename { + return true + } + if w.warnings[i].Position.Filename > w.warnings[j].Position.Filename { + return false + } + + if w.warnings[i].Position.Line < w.warnings[j].Position.Line { + return true + } + if w.warnings[i].Position.Line > w.warnings[j].Position.Line { + return false + } + + iMessage := fmt.Sprintf(w.warnings[i].format, w.warnings[i].vars...) + jMessage := fmt.Sprintf(w.warnings[j].format, w.warnings[j].vars...) + + return iMessage < jMessage + }) +} + type visitor struct { fileSet *token.FileSet @@ -186,18 +211,28 @@ func (v *visitor) typeDefinedInFile(typeName string) bool { return false } -func main() { - var allWarnings []warning +func check(fileSet *token.FileSet, path string) ([]warning, error) { + stat, err := os.Stat(path) + if err != nil { + return nil, err + } - fileSet := token.NewFileSet() + if stat.IsDir() { + return checkDir(fileSet, path) + } else { + return checkFile(fileSet, path) + } +} - err := filepath.Walk(os.Args[1], func(path string, info os.FileInfo, err error) error { +func checkDir(fileSet *token.FileSet, path string) ([]warning, error) { + var warnings []warning + + err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { return nil } - base := filepath.Base(path) - if base == "vendor" || base == ".git" || strings.HasSuffix(base, "fakes") { + if shouldSkipDir(path) { return filepath.SkipDir } @@ -206,39 +241,43 @@ func main() { return err } - var packageNames []string - for packageName, _ := range packages { - packageNames = append(packageNames, packageName) - } - sort.Strings(packageNames) - - for _, packageName := range packageNames { - var fileNames []string - for fileName, _ := range packages[packageName].Files { - fileNames = append(fileNames, fileName) - } - sort.Strings(fileNames) - - for _, fileName := range fileNames { - firstPass := visitor{ - fileSet: fileSet, - } - ast.Walk(&firstPass, packages[packageName].Files[fileName]) - - v := visitor{ - fileSet: fileSet, - previousPass: &firstPass, - } - ast.Walk(&v, packages[packageName].Files[fileName]) - allWarnings = append(allWarnings, v.warnings...) + for _, packag := range packages { + for _, file := range packag.Files { + warnings = append(warnings, walkFile(fileSet, file)...) } } return nil }) + return warnings, err +} + +func checkFile(fileSet *token.FileSet, path string) ([]warning, error) { + file, err := parser.ParseFile(fileSet, path, nil, 0) if err != nil { - panic(err) + return nil, err + } + + return walkFile(fileSet, file), nil +} + +func main() { + var allWarnings []warning + + args := os.Args[1:] + if args[0] == "--" { + args = args[1:] + } + + fileSet := token.NewFileSet() + + for _, arg := range args { + warnings, err := check(fileSet, arg) + if err != nil { + panic(err) + } + allWarnings = append(allWarnings, warnings...) } warningPrinter := warningPrinter{ @@ -254,3 +293,23 @@ func main() { func shouldParseFile(info os.FileInfo) bool { return !strings.HasSuffix(info.Name(), "_test.go") } + +func shouldSkipDir(path string) bool { + base := filepath.Base(path) + return base == "vendor" || base == ".git" || strings.HasSuffix(base, "fakes") +} + +func walkFile(fileSet *token.FileSet, file *ast.File) []warning { + firstPass := visitor{ + fileSet: fileSet, + } + ast.Walk(&firstPass, file) + + v := visitor{ + fileSet: fileSet, + previousPass: &firstPass, + } + ast.Walk(&v, file) + + return v.warnings +}
command line arguments are now any number of files or directories Sort during display instead of during traversal.
cloudfoundry_cli
train
3dc771ee754dff9d4032bad93c0b2af1590ab8e8
diff --git a/ReText/__init__.py b/ReText/__init__.py index <HASH>..<HASH> 100644 --- a/ReText/__init__.py +++ b/ReText/__init__.py @@ -38,12 +38,16 @@ if not str(settings.fileName()).endswith('.conf'): try: import enchant - enchant.Dict() -except: + import enchant.errors +except ImportError: enchant_available = False enchant = None else: enchant_available = True + try: + enchant.Dict() + except enchant.errors.Error: + enchant_available = False icon_path = "icons/"
Get rid of "Except:" statement in __init__.py
retext-project_retext
train
f42c581ad0020de994afdf969c197f7e1853a90c
diff --git a/query/dependency.go b/query/dependency.go index <HASH>..<HASH> 100644 --- a/query/dependency.go +++ b/query/dependency.go @@ -27,7 +27,8 @@ func (b *BucketLookup) Lookup(orgID platform.ID, name string) (platform.ID, bool } bucket, err := b.BucketService.FindBucket(context.Background(), filter) if err != nil { - return nil, false + var id platform.ID + return id, false } return bucket.ID, true } @@ -50,7 +51,8 @@ func (o *OrganizationLookup) Lookup(ctx context.Context, name string) (platform. ) if err != nil { - return nil, false + var id platform.ID + return id, false } return org.ID, true } diff --git a/query/functions/compspecs/compspecs.go b/query/functions/compspecs/compspecs.go index <HASH>..<HASH> 100644 --- a/query/functions/compspecs/compspecs.go +++ b/query/functions/compspecs/compspecs.go @@ -16,7 +16,6 @@ import ( "github.com/influxdata/platform" "github.com/influxdata/platform/mock" "github.com/influxdata/platform/query/influxql" - "github.com/influxdata/platform/query/semantic/semantictest" platformtesting "github.com/influxdata/platform/testing" "github.com/google/go-cmp/cmp" diff --git a/query/service_test.go b/query/service_test.go index <HASH>..<HASH> 100644 --- a/query/service_test.go +++ b/query/service_test.go @@ -8,8 +8,8 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/flux" - "github.com/influxdata/platform" "github.com/influxdata/platform/query" + platformtesting "github.com/influxdata/platform/testing" ) var CmpOpts = []cmp.Option{ @@ -59,7 +59,7 @@ func TestRequest_JSON(t *testing.T) { name: "simple", data: `{"organization_id":"aaaaaaaaaaaaaaaa","compiler":{"a":"my custom compiler"},"compiler_type":"compilerA"}`, want: query.Request{ - OrganizationID: platform.ID{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, + OrganizationID: platformtesting.MustIDFromString("aaaaaaaaaaaaaaaa"), Compiler: &compilerA{ A: "my custom compiler", }, @@ -97,7 +97,7 @@ func TestProxyRequest_JSON(t *testing.T) { data: `{"request":{"organization_id":"aaaaaaaaaaaaaaaa","compiler":{"a":"my custom compiler"},"compiler_type":"compilerA"},"dialect":{"b":42},"dialect_type":"dialectB"}`, want: query.ProxyRequest{ Request: query.Request{ - OrganizationID: platform.ID{0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA}, + OrganizationID: platformtesting.MustIDFromString("aaaaaaaaaaaaaaaa"), Compiler: &compilerA{ A: "my custom compiler", },
fix(query): edits for uint<I> IDs
influxdata_influxdb
train
b34c39b6a631bab351452059a30cf4e220258287
diff --git a/test/formats.spec.js b/test/formats.spec.js index <HASH>..<HASH> 100644 --- a/test/formats.spec.js +++ b/test/formats.spec.js @@ -54,13 +54,17 @@ describe('Formats', function () { it('should validate a date correctly', function () { var res1 = val.formats.date('2013-01-09'); - var res2 = val.formats.date('234'); + var res2 = val.formats.date('09.01.2013'); + var res3 = val.formats.date('234'); expect(res1.valid).toBe(true); expect(res1.errors.length).toBe(0); expect(res2.valid).toBe(false); expect(res2.errors.length).toBe(1); + + expect(res3.valid).toBe(false); + expect(res3.errors.length).toBe(1); }); it('should validate a time correctly', function () {
chore(test): add test for german date
litixsoft_lx-valid
train
f2658672eb82ab060bd732199b144ffc1b3527c5
diff --git a/src/test/java/com/siemens/ct/exi/grammars/persistency/Grammars2JavaSourceCodeTest.java b/src/test/java/com/siemens/ct/exi/grammars/persistency/Grammars2JavaSourceCodeTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/siemens/ct/exi/grammars/persistency/Grammars2JavaSourceCodeTest.java +++ b/src/test/java/com/siemens/ct/exi/grammars/persistency/Grammars2JavaSourceCodeTest.java @@ -22,6 +22,8 @@ public class Grammars2JavaSourceCodeTest extends TestCase { static String WORKSPACE_DIR = System.getProperty("workspace"); static String FILE_SEPARATOR = System.getProperty("file.separator"); static String OS = System.getProperty("os.name").toLowerCase(); + + static final String EXIFICIENT_CORE_JAR = "/.m2/repository/com/siemens/ct/exi/exificient-core/1.0.2-SNAPSHOT/exificient-core-1.0.2-SNAPSHOT.jar"; XSDGrammarsBuilder grammarBuilder = XSDGrammarsBuilder.newInstance(); @@ -86,8 +88,7 @@ public class Grammars2JavaSourceCodeTest extends TestCase { static String getEXIficientCoreJar() { // String url = // "https://repository.sonatype.org/service/local/artifact/maven/redirect?r=central-proxy&g=com.siemens.ct.exi&a=exificient-core&v=LATEST"; - final String DEFAULT_EXIFICIENT_CORE_JAR = USER_HOME - + "/.m2/repository/com/siemens/ct/exi/exificient-core/1.0.0-SNAPSHOT/exificient-core-1.0.0-SNAPSHOT.jar"; + final String DEFAULT_EXIFICIENT_CORE_JAR = USER_HOME + EXIFICIENT_CORE_JAR; return DEFAULT_EXIFICIENT_CORE_JAR; }
fix: issue with resolving the right exificient-core library for Java source code generation tests
EXIficient_exificient-grammars
train
66d8acbf89d02c20c7909b33f7076005a304b10e
diff --git a/acme/http.go b/acme/http.go index <HASH>..<HASH> 100644 --- a/acme/http.go +++ b/acme/http.go @@ -31,14 +31,14 @@ const ( func httpHead(url string) (resp *http.Response, err error) { req, err := http.NewRequest("HEAD", url, nil) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to head %q: %v", url, err) } req.Header.Set("User-Agent", userAgent()) resp, err = HTTPClient.Do(req) if err != nil { - return resp, err + return resp, fmt.Errorf("failed to do head %q: %v", url, err) } resp.Body.Close() return resp, err @@ -49,7 +49,7 @@ func httpHead(url string) (resp *http.Response, err error) { func httpPost(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { req, err := http.NewRequest("POST", url, body) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to post %q: %v", url, err) } req.Header.Set("Content-Type", bodyType) req.Header.Set("User-Agent", userAgent()) @@ -62,7 +62,7 @@ func httpPost(url string, bodyType string, body io.Reader) (resp *http.Response, func httpGet(url string) (resp *http.Response, err error) { req, err := http.NewRequest("GET", url, nil) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to get %q: %v", url, err) } req.Header.Set("User-Agent", userAgent()) @@ -74,7 +74,7 @@ func httpGet(url string) (resp *http.Response, err error) { func getJSON(uri string, respBody interface{}) (http.Header, error) { resp, err := httpGet(uri) if err != nil { - return nil, fmt.Errorf("failed to get %q: %v", uri, err) + return nil, fmt.Errorf("failed to get json %q: %v", uri, err) } defer resp.Body.Close() diff --git a/acme/jws.go b/acme/jws.go index <HASH>..<HASH> 100644 --- a/acme/jws.go +++ b/acme/jws.go @@ -37,7 +37,7 @@ func keyAsJWK(key interface{}) *jose.JsonWebKey { func (j *jws) post(url string, content []byte) (*http.Response, error) { signedContent, err := j.signContent(content) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to sign content -> %s", err.Error()) } resp, err := httpPost(url, "application/jose+json", bytes.NewBuffer([]byte(signedContent.FullSerialize()))) @@ -54,14 +54,14 @@ func (j *jws) post(url string, content []byte) (*http.Response, error) { // In case of a nonce error - retry once resp, err = httpPost(url, "application/jose+json", bytes.NewBuffer([]byte(signedContent.FullSerialize()))) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to HTTP POST to %s -> %s", url, err.Error()) } default: - return nil, err + return nil, fmt.Errorf("Failed to HTTP POST to %s -> %s", url, err.Error()) } } - return resp, err + return resp, nil } func (j *jws) signContent(content []byte) (*jose.JsonWebSignature, error) { @@ -80,13 +80,13 @@ func (j *jws) signContent(content []byte) (*jose.JsonWebSignature, error) { signer, err := jose.NewSigner(alg, j.privKey) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create jose signer -> %s", err.Error()) } signer.SetNonceSource(j) signed, err := signer.Sign(content) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to sign content -> %s", err.Error()) } return signed, nil } @@ -126,7 +126,7 @@ func (n *nonceManager) Push(nonce string) { func getNonce(url string) (string, error) { resp, err := httpHead(url) if err != nil { - return "", err + return "", fmt.Errorf("Failed to get nonce from HTTP HEAD -> %s", err.Error()) } return getNonceFromResponse(resp)
Add some better error messages to http and jws
go-acme_lego
train
8964addd881ee4f454acd41f8bbb4186205a35a8
diff --git a/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java b/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java index <HASH>..<HASH> 100644 --- a/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java +++ b/account/src/main/java/com/ning/billing/account/api/DefaultAccount.java @@ -22,12 +22,22 @@ import org.joda.time.DateTimeZone; import com.google.common.base.Objects; import com.google.common.base.Optional; -import com.google.common.base.Strings; import com.ning.billing.catalog.api.Currency; import com.ning.billing.junction.api.BlockingState; import com.ning.billing.util.entity.EntityBase; public class DefaultAccount extends EntityBase implements Account { + // Default values. When updating an account object, null values are + // interpreted as "no change". You can use these defaults to reset + // some fields + public static final String DEFAULT_STRING_VALUE = ""; + public static final Integer DEFAULT_INTEGER_VALUE = 0; + public static final Integer DEFAULT_BCD_VALUE = DEFAULT_INTEGER_VALUE; + public static final Currency DEFAULT_CURRENCY_VALUE = Currency.USD; + public static final DateTimeZone DEFAULT_TIMEZONE_VALUE = DateTimeZone.UTC; + private static final Boolean DEFAULT_MIGRATED_VALUE = true; + private static final Boolean DEFAULT_NOTIFIED_FOR_INVOICES_VALUE = false; + private final String externalKey; private final String email; private final String name; @@ -102,97 +112,98 @@ public class DefaultAccount extends EntityBase implements Account { @Override public String getExternalKey() { - return Strings.nullToEmpty(externalKey); + return Objects.firstNonNull(externalKey, DEFAULT_STRING_VALUE); } @Override public String getName() { - return Strings.nullToEmpty(name); + return Objects.firstNonNull(name, DEFAULT_STRING_VALUE); } @Override public String getEmail() { - return Strings.nullToEmpty(email); + return Objects.firstNonNull(email, DEFAULT_STRING_VALUE); } @Override public Integer getFirstNameLength() { - return Objects.firstNonNull(firstNameLength, 0); + return Objects.firstNonNull(firstNameLength, DEFAULT_INTEGER_VALUE); } @Override public Currency getCurrency() { - return currency; + return Objects.firstNonNull(currency, DEFAULT_CURRENCY_VALUE); } @Override public Integer getBillCycleDay() { - return Objects.firstNonNull(billCycleDay, 0); + return Objects.firstNonNull(billCycleDay, DEFAULT_BCD_VALUE); } @Override public UUID getPaymentMethodId() { + // Null if non specified return paymentMethodId; } @Override public DateTimeZone getTimeZone() { - return timeZone; + return Objects.firstNonNull(timeZone, DEFAULT_TIMEZONE_VALUE); } @Override public String getLocale() { - return Strings.nullToEmpty(locale); + return Objects.firstNonNull(locale, DEFAULT_STRING_VALUE); } @Override public String getAddress1() { - return Strings.nullToEmpty(address1); + return Objects.firstNonNull((address1, DEFAULT_STRING_VALUE); } @Override public String getAddress2() { - return Strings.nullToEmpty(address2); + return Objects.firstNonNull(address2, DEFAULT_STRING_VALUE); } @Override public String getCompanyName() { - return Strings.nullToEmpty(companyName); + return Objects.firstNonNull(companyName, DEFAULT_STRING_VALUE); } @Override public String getCity() { - return Strings.nullToEmpty(city); + return Objects.firstNonNull(city, DEFAULT_STRING_VALUE); } @Override public String getStateOrProvince() { - return Strings.nullToEmpty(stateOrProvince); + return Objects.firstNonNull(stateOrProvince, DEFAULT_STRING_VALUE); } @Override public String getPostalCode() { - return Strings.nullToEmpty(postalCode); + return Objects.firstNonNull(postalCode, DEFAULT_STRING_VALUE); } @Override public String getCountry() { - return Strings.nullToEmpty(country); + return Objects.firstNonNull(country, DEFAULT_STRING_VALUE); } @Override public Boolean isMigrated() { - return Objects.firstNonNull(this.isMigrated, true); + return Objects.firstNonNull(this.isMigrated, DEFAULT_MIGRATED_VALUE); } @Override public Boolean isNotifiedForInvoices() { - return Objects.firstNonNull(isNotifiedForInvoices, false); + return Objects.firstNonNull(isNotifiedForInvoices, DEFAULT_NOTIFIED_FOR_INVOICES_VALUE); } @Override public String getPhone() { - return Strings.nullToEmpty(phone); + return Objects.firstNonNull(phone, DEFAULT_STRING_VALUE); } @Override
account: refactor handling of defaults
killbill_killbill
train
a46553cbacf0e4012df89fe55385dec5beaa680a
diff --git a/python/pyspark/sql/tests.py b/python/pyspark/sql/tests.py index <HASH>..<HASH> 100644 --- a/python/pyspark/sql/tests.py +++ b/python/pyspark/sql/tests.py @@ -318,6 +318,11 @@ class SQLTests(ReusedPySparkTestCase): [row] = self.spark.sql("SELECT double(add(1, 2)), add(double(2), 1)").collect() self.assertEqual(tuple(row), (6, 5)) + def test_udf_without_arguments(self): + self.sqlCtx.registerFunction("foo", lambda: "bar") + [row] = self.sqlCtx.sql("SELECT foo()").collect() + self.assertEqual(row[0], "bar") + def test_udf_with_array_type(self): d = [Row(l=list(range(3)), d={"key": list(range(5))})] rdd = self.sc.parallelize(d) diff --git a/python/pyspark/sql/types.py b/python/pyspark/sql/types.py index <HASH>..<HASH> 100644 --- a/python/pyspark/sql/types.py +++ b/python/pyspark/sql/types.py @@ -1401,11 +1401,7 @@ class Row(tuple): if args and kwargs: raise ValueError("Can not use both args " "and kwargs to create Row") - if args: - # create row class or objects - return tuple.__new__(self, args) - - elif kwargs: + if kwargs: # create row objects names = sorted(kwargs.keys()) row = tuple.__new__(self, [kwargs[n] for n in names]) @@ -1413,7 +1409,8 @@ class Row(tuple): return row else: - raise ValueError("No args or kwargs") + # create row class or objects + return tuple.__new__(self, args) def asDict(self, recursive=False): """
[SPARK-<I>] [SQL] fix Python UDF without arguments (for <I>) Fix the bug for Python UDF that does not have any arguments. Added regression tests.
apache_spark
train
b3a8ac3f3f0c27225afdbf62703273180a4e4bc7
diff --git a/src/ErrorCodes.php b/src/ErrorCodes.php index <HASH>..<HASH> 100644 --- a/src/ErrorCodes.php +++ b/src/ErrorCodes.php @@ -47,9 +47,9 @@ class ErrorCodes $locales = $i18n->loadLocale(I18n::getCurrentLocale()); $errorCodes = fnGet($locales, 'packages.error_codes', []); foreach ($errorCodes as $code => $message) { - $name = 'get' . Text::camelize($code); + $name = 'get' . Text::camelize((string)$code); $parameters = array_map(function ($field) { - return '$' . lcfirst(Text::camelize($field)); + return '$' . lcfirst(Text::camelize((string)$field)); }, static::detectPlaceholders($message)); $parameters = implode(', ', $parameters); $classContent[] = <<<METHOD diff --git a/src/I18n.php b/src/I18n.php index <HASH>..<HASH> 100644 --- a/src/I18n.php +++ b/src/I18n.php @@ -1,4 +1,5 @@ <?php + namespace Phwoolcon; use Phalcon\Di; @@ -127,8 +128,8 @@ class I18n extends Adapter implements ServiceAwareInterface in_array($package, ['error_code']) and $package = 'error_codes'; $packageLocale = (array)include $file; isset($packages[$package]) or $packages[$package] = []; - $packages[$package] = array_merge($packages[$package], $packageLocale); - $package == 'error_codes' or $combined = array_merge($combined, $packageLocale); + $packages[$package] = array_replace($packages[$package], $packageLocale); + $package == 'error_codes' or $combined = array_replace($combined, $packageLocale); } $this->locale[$locale] = compact('combined', 'packages'); $useCache and Cache::set($cacheKey, $this->locale[$locale]);
fix(error_codes): preserve numeric locale keys [ci skip]
phwoolcon_phwoolcon
train
5461c0ad0503bf2520569ef516eb096841fb146b
diff --git a/src/pages/class-papi-post-page.php b/src/pages/class-papi-post-page.php index <HASH>..<HASH> 100644 --- a/src/pages/class-papi-post-page.php +++ b/src/pages/class-papi-post-page.php @@ -10,7 +10,7 @@ class Papi_Post_Page extends Papi_Core_Page { * * @var string */ - const TYPE = 'page'; + const TYPE = 'post'; /** * The WordPress post.
Update post page type to `post`
wp-papi_papi
train
e8f4e47798d22a68bcf469c9ab747ae90517db0c
diff --git a/expression/builtin_string.go b/expression/builtin_string.go index <HASH>..<HASH> 100644 --- a/expression/builtin_string.go +++ b/expression/builtin_string.go @@ -3817,7 +3817,35 @@ type loadFileFunctionClass struct { } func (c *loadFileFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (builtinFunc, error) { - return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", "load_file") + if err := c.verifyArgs(args); err != nil { + return nil, err + } + bf, err := newBaseBuiltinFuncWithTp(ctx, c.funcName, args, types.ETString, types.ETString) + if err != nil { + return nil, err + } + bf.tp.Charset, bf.tp.Collate = ctx.GetSessionVars().GetCharsetInfo() + bf.tp.Flen = 64 + sig := &builtinLoadFileSig{bf} + return sig, nil +} + +type builtinLoadFileSig struct { + baseBuiltinFunc +} + +func (b *builtinLoadFileSig) evalString(row chunk.Row) (d string, isNull bool, err error) { + d, isNull, err = b.args[0].EvalString(b.ctx, row) + if isNull || err != nil { + return d, isNull, err + } + return "", true, nil +} + +func (b *builtinLoadFileSig) Clone() builtinFunc { + newSig := &builtinLoadFileSig{} + newSig.cloneFrom(&b.baseBuiltinFunc) + return newSig } type weightStringPadding byte diff --git a/expression/builtin_string_test.go b/expression/builtin_string_test.go index <HASH>..<HASH> 100644 --- a/expression/builtin_string_test.go +++ b/expression/builtin_string_test.go @@ -1642,6 +1642,37 @@ func (s *testEvaluatorSuite) TestInstr(c *C) { } } +func (s *testEvaluatorSuite) TestLoadFile(c *C) { + cases := []struct { + arg interface{} + isNil bool + getErr bool + res string + }{ + {"", true, false, ""}, + {"/tmp/tikv/tikv.frm", true, false, ""}, + {"tidb.sql", true, false, ""}, + {nil, true, false, ""}, + } + for _, t := range cases { + f, err := newFunctionForTest(s.ctx, ast.LoadFile, s.primitiveValsToConstants([]interface{}{t.arg})...) + c.Assert(err, IsNil) + d, err := f.Eval(chunk.Row{}) + if t.getErr { + c.Assert(err, NotNil) + } else { + c.Assert(err, IsNil) + if t.isNil { + c.Assert(d.Kind(), Equals, types.KindNull) + } else { + c.Assert(d.GetString(), Equals, t.res) + } + } + } + _, err := funcs[ast.LoadFile].getFunction(s.ctx, []Expression{NewZero()}) + c.Assert(err, IsNil) +} + func (s *testEvaluatorSuite) TestMakeSet(c *C) { tbl := []struct { argList []interface{}
expression: no-op implementation for `load_file` to support Navicat (#<I>)
pingcap_tidb
train
0e3941cd1f14d0322165504974eeefab7e1ddc6d
diff --git a/github/github_test.go b/github/github_test.go index <HASH>..<HASH> 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -474,7 +474,7 @@ func TestDo_rateLimit_rateLimitError(t *testing.T) { } reset := time.Date(2013, 7, 1, 17, 47, 53, 0, time.UTC) if rateLimitErr.Rate.Reset.UTC() != reset { - t.Errorf("rateLimitErr rate reset = %v, want %v", client.Rate().Reset, reset) + t.Errorf("rateLimitErr rate reset = %v, want %v", rateLimitErr.Rate.Reset.UTC(), reset) } }
Improve test error message. Print the actual value that doesn't match. Minor followup fix for c3f<I>ad1dfe8c2c5aad4a7bbe<I>cbdc4a<I> (#<I>).
google_go-github
train
8538c0e8eafef5104cac95aa88f49b9394203a3f
diff --git a/lib/Cake/Console/ShellDispatcher.php b/lib/Cake/Console/ShellDispatcher.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Console/ShellDispatcher.php +++ b/lib/Cake/Console/ShellDispatcher.php @@ -276,7 +276,11 @@ class ShellDispatcher { if (isset($params['working'])) { $params['working'] = trim($params['working']); } - if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) { + + if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0][0] !== '.')) { + if ($params['working'][0] === '.') { + $params['working'] = realpath($params['working']); + } if (empty($this->params['app']) && $params['working'] != $params['root']) { $params['root'] = dirname($params['working']); $params['app'] = basename($params['working']);
Avoiding problems with relative paths in shell dispatcher
cakephp_cakephp
train
5ceffd512a0b01ea49d2a771847c78b9c6bf0e5c
diff --git a/src/Http/Filter/RateLimitFilter.php b/src/Http/Filter/RateLimitFilter.php index <HASH>..<HASH> 100644 --- a/src/Http/Filter/RateLimitFilter.php +++ b/src/Http/Filter/RateLimitFilter.php @@ -54,6 +54,9 @@ class RateLimitFilter extends Filter return null; } + $limit = $route->getRateLimit($limit); + $expires = $route->getLimitExpiration($expires); + $this->limiter->rateLimitRequest($request, $limit, $expires); if (! $this->limiter->requestWasRateLimited()) { diff --git a/src/Routing/Route.php b/src/Routing/Route.php index <HASH>..<HASH> 100644 --- a/src/Routing/Route.php +++ b/src/Routing/Route.php @@ -83,4 +83,26 @@ class Route extends IlluminateRoute { return (array) array_get($this->action, 'providers', []); } + + /** + * Get the rate limit. + * + * @param int $default + * @return int + */ + public function getRateLimit($default) + { + return array_get($this->action, 'limit', $default); + } + + /** + * Get the rate limit expiration time. + * + * @param int $default + * @return int + */ + public function getLimitExpiration($default) + { + return array_get($this->action, 'expires', $default); + } } diff --git a/tests/Http/Filter/RateLimitFilterTest.php b/tests/Http/Filter/RateLimitFilterTest.php index <HASH>..<HASH> 100644 --- a/tests/Http/Filter/RateLimitFilterTest.php +++ b/tests/Http/Filter/RateLimitFilterTest.php @@ -81,4 +81,24 @@ class RateLimitFilterTest extends PHPUnit_Framework_TestCase $this->filter->filter($route, $request); } + + + public function testRateLimitingWithRouteLimiter() + { + $request = Request::create('test', 'GET'); + $route = new Route(['GET'], 'test', ['protected' => true, 'limit' => 5, 'expires' => 10, 'uses' => function () { + return 'test'; + }]); + + $this->router->getRoutes()->add($route); + + $this->assertNull($this->filter->filter($route, $request)); + + $response = $this->router->dispatch($request); + $this->assertArrayHasKey('x-ratelimit-limit', $response->headers->all()); + $this->assertArrayHasKey('x-ratelimit-remaining', $response->headers->all()); + $this->assertArrayHasKey('x-ratelimit-reset', $response->headers->all()); + $this->assertEquals(4, $response->headers->get('x-ratelimit-remaining')); + $this->assertEquals(5, $response->headers->get('x-ratelimit-limit')); + } }
Allow rate limit and expiration time to be set as route options.
dingo_api
train
9afb85714a922af7c975087366e5c8f1759330d6
diff --git a/cmd/ipfs2/main.go b/cmd/ipfs2/main.go index <HASH>..<HASH> 100644 --- a/cmd/ipfs2/main.go +++ b/cmd/ipfs2/main.go @@ -160,7 +160,7 @@ func (i *cmdInvocation) Run() (output io.Reader, err error) { func (i *cmdInvocation) Parse(args []string) error { var err error - i.req, i.root, i.cmd, i.path, err = cmdsCli.Parse(args, Root) + i.req, i.cmd, i.path, err = cmdsCli.Parse(args, Root) if err != nil { return err } diff --git a/commands/cli/parse.go b/commands/cli/parse.go index <HASH>..<HASH> 100644 --- a/commands/cli/parse.go +++ b/commands/cli/parse.go @@ -15,38 +15,36 @@ var ErrInvalidSubcmd = errors.New("subcommand not found") // Parse parses the input commandline string (cmd, flags, and args). // returns the corresponding command Request object. // Parse will search each root to find the one that best matches the requested subcommand. -// TODO: get rid of extraneous return values (e.g. we ended up not needing the root value anymore) -// TODO: get rid of multiple-root support, we should only need one now -func Parse(input []string, root *cmds.Command) (cmds.Request, *cmds.Command, *cmds.Command, []string, error) { +func Parse(input []string, root *cmds.Command) (cmds.Request, *cmds.Command, []string, error) { // use the root that matches the longest path (most accurately matches request) path, input, cmd := parsePath(input, root) opts, stringArgs, err := parseOptions(input) if err != nil { - return nil, root, cmd, path, err + return nil, cmd, path, err } if len(path) == 0 { - return nil, root, nil, path, ErrInvalidSubcmd + return nil, nil, path, ErrInvalidSubcmd } args, err := parseArgs(stringArgs, cmd) if err != nil { - return nil, root, cmd, path, err + return nil, cmd, path, err } optDefs, err := root.GetOptions(path) if err != nil { - return nil, root, cmd, path, err + return nil, cmd, path, err } req := cmds.NewRequest(path, opts, args, cmd, optDefs) err = cmd.CheckArguments(req) if err != nil { - return req, root, cmd, path, err + return req, cmd, path, err } - return req, root, cmd, path, nil + return req, cmd, path, nil } // parsePath separates the command path and the opts and args from a command string
commands/cli: Don't return root in Parse
ipfs_go-ipfs
train
616975d401a0c8f81a32506451210d7121998322
diff --git a/recursivetree.go b/recursivetree.go index <HASH>..<HASH> 100644 --- a/recursivetree.go +++ b/recursivetree.go @@ -109,22 +109,10 @@ func watchIsRecursive(nd node) bool { ok := nd.Watch.IsRecursive() // TODO(rjeczalik): add a test for len(wp) != 0 change the condition. if wp := nd.Child[""].Watch; len(wp) != 0 { - ok = ok || wp.IsRecursive() // If a watchpoint holds inactive watchpoints, it means it's a parent // one, which is recursive by nature even though it may be not recursive - // itself. It currently does not work due to some watchpoints being - // registered twice - one for actual watchpoint and one for an inactive - // one. - // - // ok = true - // - // TODO(rjeczalik): fix this hack: - for c, _ := range wp { - if _, b := nd.Watch[c]; !b { - ok = true - break - } - } + // itself. + ok = true } return ok } @@ -210,9 +198,11 @@ func (t *recursiveTree) Watch(path string, c chan<- EventInfo, events ...Event) // // Look for parent watch which already covers the given path. parent := node{} - err = t.root.WalkPath(path, func(nd node, _ bool) error { + self := false + err = t.root.WalkPath(path, func(nd node, isbase bool) error { if watchTotal(nd) != 0 { parent = nd + self = isbase return skip } return nil @@ -222,7 +212,13 @@ func (t *recursiveTree) Watch(path string, c chan<- EventInfo, events ...Event) // Parent watch found. Register inactive watchpoint, so we have enough // information to shrink the eventset on eventual Stop. // return t.resetwatchpoint(parent, parent, c, eventset|inactive) - switch diff := watchAddInactive(parent, c, eventset); { + var diff eventDiff + if self { + diff = watchAdd(cur, c, eventset) + } else { + diff = watchAddInactive(parent, c, eventset) + } + switch { case diff == none: // the parent watchpoint already covers requested subtree with its // eventset @@ -241,7 +237,9 @@ func (t *recursiveTree) Watch(path string, c chan<- EventInfo, events ...Event) // TODO(rjeczalik): traverse tree instead; eventually track minimum // subtree root per each chan } - watchAdd(cur, c, eventset) + if !self { + watchAdd(cur, c, eventset) + } return nil } // case 2: cur is new parent
proper fix for broken traverse skip for Stop() Removes hack introduced by <I>da<I>.
rjeczalik_notify
train
79434d106330a7a99e30193dc098d8da1000c9bb
diff --git a/article.py b/article.py index <HASH>..<HASH> 100644 --- a/article.py +++ b/article.py @@ -52,7 +52,7 @@ class Article(object): titlestring = u'{0}_{1}{2}'.format(self.front.journal_meta.identifier['pmc'], self.front.article_meta.art_auths[0].surname, - self.front.article_meta.art_dates['collection'][2]) + self.front.article_meta.art_dates['collection'].year) return titlestring diff --git a/epub_date.py b/epub_date.py index <HASH>..<HASH> 100644 --- a/epub_date.py +++ b/epub_date.py @@ -19,8 +19,13 @@ class DateInfo(object): self.day = 0 self.parse(datenode) - self.date = datetime.date(self.year, self.month, self.day) - + try: + self.date = datetime.date(self.year, self.month, self.day) + except ValueError: + if self.day == 0: + pass + else: + raise ValueError('day is out of range for month') def parse(self, datenode): """Handle the node contents datenode -- the XML Element containing the date info diff --git a/metadata.py b/metadata.py index <HASH>..<HASH> 100644 --- a/metadata.py +++ b/metadata.py @@ -155,15 +155,9 @@ class ArticleMeta(object): self.art_eloc_id = elocation_id.firstChild.data pub_dates = node.getElementsByTagName('pub-date') - for pd in pub_dates: - day = 0 - month = getTagData(pd.getElementsByTagName('month')) - year = getTagData(pd.getElementsByTagName('year')) - if pd.getAttribute('pub-type') == u'collection': - self.art_dates['collection'] = [day, month, year] - elif pd.getAttribute('pub-type') == u'epub': - day = getTagData(pd.getElementsByTagName('day')) - self.art_dates['epub'] = [day, month, year] + for entry in pub_dates: + entry_date = epub_date.DateInfo(entry) + self.art_dates[entry.getAttribute('pub-type')] = entry_date class ArticleCategories(object): """Article Categories information""" diff --git a/output.py b/output.py index <HASH>..<HASH> 100644 --- a/output.py +++ b/output.py @@ -123,8 +123,13 @@ def generateOPF(article, dirname): #metadata.appendChild(createDCElement(mydoc, 'dc:coverage', None)) metadata.appendChild(createDCElement(mydoc, 'dc:date', artmeta.history['accepted'].dateString(), {'opf:event': 'creation'})) - - + metadata.appendChild(createDCElement(mydoc, 'dc:date', artmeta.art_dates['epub'].dateString(), + {'opf:event': 'publication'})) + try: + metadata.appendChild(createDCElement(mydoc, 'dc:date', artmeta.art_dates['ecorrected'].dateString(), + {'opf:event': 'modification'})) + except KeyError: + pass contentpath = os.path.join(dirname,'OPS','content.opf') with open(contentpath, 'w') as output: output.write(mydoc.toprettyxml(encoding = 'UTF-8'))
Added support for all dc:date and opf:event tags, reworked metadata.py to use epub_date.DateInfo class for art_dates
SavinaRoja_OpenAccess_EPUB
train
5c00d4d9f151f1075bb30fa24556658708f7e068
diff --git a/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPing.java b/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPing.java index <HASH>..<HASH> 100644 --- a/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPing.java +++ b/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPing.java @@ -40,14 +40,16 @@ public class TransferToPing final FileChannel sendFileChannel = Common.createTmpFileChannel(); final ByteBuffer sendByteBuffer = sendFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT); final DatagramChannel sendDatagramChannel = DatagramChannel.open(); + sendDatagramChannel.bind(new InetSocketAddress("localhost", 40123)); init(sendDatagramChannel); - sendDatagramChannel.connect(new InetSocketAddress("localhost", Common.PING_PORT)); + sendDatagramChannel.connect(new InetSocketAddress("localhost", 40124)); final FileChannel receiveFileChannel = Common.createTmpFileChannel(); final ByteBuffer receiveByteBuffer = receiveFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT); final DatagramChannel receiveDatagramChannel = DatagramChannel.open(); + receiveDatagramChannel.bind(new InetSocketAddress("localhost", 40126)); init(receiveDatagramChannel); - receiveDatagramChannel.connect(new InetSocketAddress("localhost", Common.PONG_PORT)); + receiveDatagramChannel.connect(new InetSocketAddress("localhost", 40125)); final AtomicBoolean running = new AtomicBoolean(true); SigInt.register(() -> running.set(false)); diff --git a/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPong.java b/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPong.java index <HASH>..<HASH> 100644 --- a/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPong.java +++ b/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/raw/TransferToPong.java @@ -32,17 +32,19 @@ public class TransferToPong { public static void main(final String[] args) throws IOException { - final FileChannel sendFileChannel = Common.createTmpFileChannel(); - final ByteBuffer sendByteBuffer = sendFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT); - final DatagramChannel sendDatagramChannel = DatagramChannel.open(); - init(sendDatagramChannel); - sendDatagramChannel.connect(new InetSocketAddress("localhost", Common.PONG_PORT)); - final FileChannel receiveFileChannel = Common.createTmpFileChannel(); final ByteBuffer receiveByteBuffer = receiveFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT); final DatagramChannel receiveDatagramChannel = DatagramChannel.open(); + receiveDatagramChannel.bind(new InetSocketAddress("localhost", 40124)); init(receiveDatagramChannel); - receiveDatagramChannel.connect(new InetSocketAddress("localhost", Common.PING_PORT)); + receiveDatagramChannel.connect(new InetSocketAddress("localhost", 40123)); + + final FileChannel sendFileChannel = Common.createTmpFileChannel(); + final ByteBuffer sendByteBuffer = sendFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT); + final DatagramChannel sendDatagramChannel = DatagramChannel.open(); + sendDatagramChannel.bind(new InetSocketAddress("localhost", 40125)); + init(sendDatagramChannel); + sendDatagramChannel.connect(new InetSocketAddress("localhost", 40126)); final AtomicBoolean running = new AtomicBoolean(true); SigInt.register(() -> running.set(false));
[Java]: Attempt with connect and bind on raw channel test.
real-logic_aeron
train
f893489d28a44ca752fa32df645983e8aa9f3d1b
diff --git a/circuit/circuit.py b/circuit/circuit.py index <HASH>..<HASH> 100644 --- a/circuit/circuit.py +++ b/circuit/circuit.py @@ -6,6 +6,8 @@ logical circuits. from __future__ import annotations from typing import Sequence +from math import log2 +from itertools import product from parts import parts import doctest @@ -51,10 +53,30 @@ class operation(tuple): } def __call__(self: operation, *arguments) -> int: + """ + Apply the operator to an input tuple. + + >>> operation((1,0))(1) + 0 + >>> operation((1,0,0,1))(0,0) + 1 + >>> operation((1,0,0,1))(1,1) + 1 + >>> operation((1,0,0,1))(1,0) + 0 + >>> operation((1,0,0,1))(0,1) + 0 + >>> operation((1,0,0,1,0,1,0,1))(1,1,0) + 0 + + """ if len(arguments) == 1: return self[[0, 1].index(arguments[0])] elif len(arguments) == 2: return self[[(0,0),(0,1),(1,0),(1,1)].index(tuple(arguments))] + else: + inputs = list(product(*[(0,1)]*int(log2(len(self))))) + return self[inputs.index(tuple(arguments))] def name(self: operation) -> str: return dict(operation.names)[self] diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ with open("README.rst", "r") as fh: setup( name="circuit", - version="0.1.0.3", + version="0.1.0.4", packages=["circuit",], install_requires=["parts",], license="MIT",
Operation data structure should support any arity.
lapets_circuit
train
1b4a743e7d96d5b33a24db29fb2be45daeab37da
diff --git a/src/Meinhof/Model/Post/FilesystemPostLoader.php b/src/Meinhof/Model/Post/FilesystemPostLoader.php index <HASH>..<HASH> 100644 --- a/src/Meinhof/Model/Post/FilesystemPostLoader.php +++ b/src/Meinhof/Model/Post/FilesystemPostLoader.php @@ -52,6 +52,7 @@ class FilesystemPostLoader extends PostLoader foreach ($finder as $file) { $path = $file->getRelativePathname(); $config = $this->loadMatter($path); + $config['path'] = $path; if (!isset($config['key'])) { $parts = explode('.', $path); $config['key'] = reset($parts); @@ -65,24 +66,23 @@ class FilesystemPostLoader extends PostLoader protected function createPost($data) { if (is_array($data)) { - if (!isset($data['updated']) && isset($data['key'])) { - $data['updated'] = $this->getKeyPathUpdated($data['key']); + if (!isset($data['updated']) && isset($data['path'])) { + $data['updated'] = $this->getKeyPathUpdated($data['path']); } } return parent::createPost($data); } - protected function getKeyPathUpdated($key) + protected function getKeyPathUpdated($file) { - $path = $this->path.'/'.$key; + $path = $this->path.'/'.$file; if (!is_readable($path)) { return null; } $timestamp = filemtime($path); $date = new \DateTime(); $date->setTimestamp($timestamp); - return $date; } } diff --git a/src/Meinhof/Model/Post/PostLoader.php b/src/Meinhof/Model/Post/PostLoader.php index <HASH>..<HASH> 100644 --- a/src/Meinhof/Model/Post/PostLoader.php +++ b/src/Meinhof/Model/Post/PostLoader.php @@ -9,6 +9,8 @@ use Meinhof\Templating\Finder\FinderInterface; class PostLoader extends AbstractLoader { + const FIX_DATE_REGEX = '@(\d+)/(\d+)/(\d+)@'; + protected $templating; protected $finder; protected $posts = array(); @@ -81,7 +83,7 @@ class PostLoader extends AbstractLoader protected function createPost($data) { if (is_array($data)) { - if (isset($data['updated']) && $this->fixDate && preg_match('@(\d+)/(\d+)/(\d+)@', $data['updated'], $m)) { + if ($this->fixDate && isset($data['updated']) && is_string($data['updated']) && preg_match(self::FIX_DATE_REGEX, $data['updated'], $m)) { // fix date format d/m/Y $data['updated'] = str_replace($m[0], $m[2].'/'.$m[1].'/'.$m[3], $data['updated']); } @@ -106,7 +108,6 @@ class PostLoader extends AbstractLoader } $ua = $a->getUpdated(); $ub = $b->getUpdated(); - return $ua === $ub ? 0 : ($ua > $ub ? -1 : 1); }); }
fixed bug in filesystem post loader not setting date correctly
miguelibero_meinhof
train
e0701bb0f68f2adb3c597950769ef9f10ed7de45
diff --git a/swift-service/src/main/java/com/facebook/swift/service/ThriftServer.java b/swift-service/src/main/java/com/facebook/swift/service/ThriftServer.java index <HASH>..<HASH> 100644 --- a/swift-service/src/main/java/com/facebook/swift/service/ThriftServer.java +++ b/swift-service/src/main/java/com/facebook/swift/service/ThriftServer.java @@ -182,6 +182,7 @@ public class ThriftServer implements Closeable .withSecurityFactory(securityFactoryHolder.niftySecurityFactory) .using(workerExecutor) .taskTimeout(config.getTaskExpirationTimeout()) + .queueTimeout(config.getQueueTimeout()) .build(); NettyServerConfigBuilder nettyServerConfigBuilder = NettyServerConfig.newBuilder(); diff --git a/swift-service/src/main/java/com/facebook/swift/service/ThriftServerConfig.java b/swift-service/src/main/java/com/facebook/swift/service/ThriftServerConfig.java index <HASH>..<HASH> 100644 --- a/swift-service/src/main/java/com/facebook/swift/service/ThriftServerConfig.java +++ b/swift-service/src/main/java/com/facebook/swift/service/ThriftServerConfig.java @@ -55,6 +55,7 @@ public class ThriftServerConfig private int ioThreadCount = DEFAULT_IO_WORKER_THREAD_COUNT; private Duration idleConnectionTimeout = Duration.valueOf("60s"); private Duration taskExpirationTimeout = Duration.valueOf("5s"); + private Duration queueTimeout = Duration.valueOf("5s"); private Optional<Integer> workerThreads = Optional.absent(); private Optional<Integer> maxQueuedRequests = Optional.absent(); private Optional<ExecutorService> workerExecutor = Optional.absent(); @@ -192,6 +193,26 @@ public class ThriftServerConfig return this; } + public Duration getQueueTimeout() + { + return queueTimeout; + } + + /** + * Sets a timeout period between receiving a request and the pulling the request off the queue. + * If the timeout expires before the request reaches the front of the queue and begins + * processing, the server will discard the request instead of processing it. + * + * @param queueTimeout The timeout + * @return This {@link ThriftServerConfig} instance + */ + @Config("thrift.queue-timeout") + public ThriftServerConfig setQueueTimeout(Duration queueTimeout) + { + this.queueTimeout = queueTimeout; + return this; + } + public Duration getTaskExpirationTimeout() { return taskExpirationTimeout;
Expose queueTimeout in swift
facebookarchive_swift
train
b2e88be39d1873faeee40d203b924962047be9f2
diff --git a/libs/verysimple/Phreeze/GenericRouter.php b/libs/verysimple/Phreeze/GenericRouter.php index <HASH>..<HASH> 100644 --- a/libs/verysimple/Phreeze/GenericRouter.php +++ b/libs/verysimple/Phreeze/GenericRouter.php @@ -251,14 +251,17 @@ class GenericRouter implements IRouter $uri = $this->GetUri(); $count = 0; $routeMap = $this->matchedRoute["key"]; - + $returnVal = ''; + if( isset($this->matchedRoute["params"][$paramKey]) ) { $indexLocation = $this->matchedRoute["params"][$paramKey]; - return $params[$indexLocation]; + $returnVal = $params[$indexLocation]; } else - return RequestUtil::Get($paramKey,""); + $returnVal = RequestUtil::Get($paramKey); + + return $returnVal != '' ? $returnVal : $default; } } ?>
fix bug with generic router not returning default
jasonhinkle_phreeze
train
be0ad01df772a17c1beea92635fb7b0b9b7c5b16
diff --git a/packages/ember-runtime/lib/system/namespace.js b/packages/ember-runtime/lib/system/namespace.js index <HASH>..<HASH> 100644 --- a/packages/ember-runtime/lib/system/namespace.js +++ b/packages/ember-runtime/lib/system/namespace.js @@ -116,7 +116,7 @@ function findNamespaces() { for (var prop in lookup) { // These don't raise exceptions but can cause warnings - if (prop === "parent" || prop === "top" || prop === "frameElement") { continue; } + if (prop === "parent" || prop === "top" || prop === "frameElement" || prop === "webkitStorageInfo") { continue; } // get(window.globalStorage, 'isNamespace') would try to read the storage for domain isNamespace and cause exception in Firefox. // globalStorage is a storage obsoleted by the WhatWG storage specification. See https://developer.mozilla.org/en/DOM/Storage#globalStorage
Ignore webkitStorageInfo during namespace lookup to avoid warning
emberjs_ember.js
train
4708f7dca0ae5e0ade2a93672f32373e0cc403ec
diff --git a/lib/json/jwt.rb b/lib/json/jwt.rb index <HASH>..<HASH> 100644 --- a/lib/json/jwt.rb +++ b/lib/json/jwt.rb @@ -31,7 +31,16 @@ module JSON # I'd like to make :RS256 default. # However, by histrical reasons, :HS256 was default. # This code is needed to keep legacy behavior. - algorithm = private_key_or_secret.is_a?(String) ? :HS256 : :RS256 + algorithm = case private_key_or_secret + when String + :HS256 + when OpenSSL::PKey::RSA + :RS256 + when OpenSSL::PKey::EC + :ES256 + else + raise UnexpectedAlgorithm.new('Signature algorithm auto-detection failed') + end end jws = JWS.new self jws.kid ||= private_key_or_secret[:kid] if private_key_or_secret.is_a? JSON::JWK
improve JWT#sign signature auto-detection feature so that it can handle EC keys NOTE: might be better to handle EC curves
nov_json-jwt
train
9b99b94bcba9a9fb8be0392ce5dbf0a66fb4cbef
diff --git a/src/Reference.php b/src/Reference.php index <HASH>..<HASH> 100644 --- a/src/Reference.php +++ b/src/Reference.php @@ -163,7 +163,7 @@ class Reference $p = $this->owner->persistence; - return $p->add($p->normalizeClassName($model, 'Model'), $defaults); + return $p->add($model, $defaults); } /** diff --git a/tests/RandomTest.php b/tests/RandomTest.php index <HASH>..<HASH> 100644 --- a/tests/RandomTest.php +++ b/tests/RandomTest.php @@ -25,7 +25,7 @@ class Model_Item extends \atk4\data\Model { parent::init(); $this->addField('name'); - $this->hasOne('parent_item_id', '\atk4\data\tests\Item') + $this->hasOne('parent_item_id', '\atk4\data\tests\Model_Item') ->addTitle(); } } @@ -295,7 +295,7 @@ class RandomSQLTests extends SQLTestCase $db = new Persistence_SQL($this->db->connection); $m = new Model_Item($db); - $m->hasOne('Person', 'atk4/data/tests/Person'); + $m->hasOne('Person', 'atk4/data/tests/Model_Person'); $person = $m->ref('Person'); } }
fixed test-suite (#<I>)
atk4_data
train
ced12010277bb7109a4327f3e5bfe15ed59f656e
diff --git a/publicBucketACL/function.js b/publicBucketACL/function.js index <HASH>..<HASH> 100644 --- a/publicBucketACL/function.js +++ b/publicBucketACL/function.js @@ -15,14 +15,16 @@ module.exports.fn = function(event, context, callback) { function publicPermissions(event) { let permissions = []; - let grants = event.detail.requestParameters.AccessControlPolicy.AccessControlList.Grant; - if (typeof grants === 'undefined') { // Catches edge case in which a bucket is created that nobody has permissions to - return permissions; - } - - for (let i = 0; i < grants.length; i++) { - if (grants[i].Grantee.URI === 'http://acs.amazonaws.com/groups/global/AllUsers') { - permissions.push(grants[i].Permission); + let accessControlPolicy = event.detail.requestParameters.AccessControlPolicy; + if (accessControlPolicy) { + let grants = accessControlPolicy.AccessControlList.Grant; + if (typeof grants === 'undefined') { // Catches edge case in which a bucket is created that nobody has permissions to + return permissions; + } + for (let i = 0; i < grants.length; i++) { + if (grants[i].Grantee.URI === 'http://acs.amazonaws.com/groups/global/AllUsers') { + permissions.push(grants[i].Permission); + } } }
Fix undefined AccessControlList (#<I>)
mapbox_patrol-rules-aws
train
807626d6623b9b6f301f99ebe503a78c32dc028f
diff --git a/src/sap.ui.layout/test/sap/ui/layout/qunit/form/changes/RenameSimpleForm.qunit.js b/src/sap.ui.layout/test/sap/ui/layout/qunit/form/changes/RenameSimpleForm.qunit.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.layout/test/sap/ui/layout/qunit/form/changes/RenameSimpleForm.qunit.js +++ b/src/sap.ui.layout/test/sap/ui/layout/qunit/form/changes/RenameSimpleForm.qunit.js @@ -258,7 +258,10 @@ sap.ui.define([ .then(function() { assert.equal(this.oXmlLabel0.getAttribute("text"), this.sNewValue, "the label has changed"); var oExpectedChangeVizInfo = { - affectedControls: ["__element0"], + affectedControls: [ + // as the FormElements in a SimpeForm don't get stable IDs, we have to cheat + sap.ui.getCore().byId("component---Label0").getParent().getId() + ], payload: { originalLabel: "oldLabel0", newLabel: this.sNewValue
[INTERNAL] sap.ui.layout: fix unstable change handler test The test suffered from an unstable ID (__element0). Luckily, the first retry always worked as QUnit then reorders the tests and the element gets the expected ID. With this change, the test uses fixture knowledge to determine the right ID in advance. Change-Id: Ic7dd<I>f7a5fcebdecceceb7d<I>f4a<I>aa
SAP_openui5
train
fb3a5dc04cb65f401a271b292828ffa5653c1e5d
diff --git a/src/Sulu/Component/Rest/ListBuilder/ListRepresentation.php b/src/Sulu/Component/Rest/ListBuilder/ListRepresentation.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Component/Rest/ListBuilder/ListRepresentation.php +++ b/src/Sulu/Component/Rest/ListBuilder/ListRepresentation.php @@ -33,7 +33,7 @@ use Hateoas\Configuration\Annotation\Route; * "filter", * href = @Route( * "expr(object.getRoute())", - * parameters = "expr(object.getParameters() + { fields: '{fieldsList}' })", + * parameters = "expr({ fields: '{fieldsList}' } + object.getParameters())", * absolute = "expr(object.isAbsolute())", * ) * ) @@ -41,7 +41,7 @@ use Hateoas\Configuration\Annotation\Route; * "find", * href = @Route( * "expr(object.getRoute())", - * parameters = "expr(object.getParameters() + { fields: '{searchString}{&searchFields}' })", + * parameters = "expr({ search: '{searchString}{&searchFields}' } + object.getParameters())", * absolute = "expr(object.isAbsolute())", * ) * ) @@ -49,7 +49,7 @@ use Hateoas\Configuration\Annotation\Route; * "pagination", * href = @Route( * "expr(object.getRoute())", - * parameters = "expr(object.getParameters() + { page: '{page}', pageSize: '{pageSize}' })", + * parameters = "expr({ page: '{page}', limit: '{limit}'} + object.getParameters())", * absolute = "expr(object.isAbsolute())", * ) * ) @@ -57,7 +57,7 @@ use Hateoas\Configuration\Annotation\Route; * "sortable", * href = @Route( * "expr(object.getRoute())", - * parameters = "expr(object.getParameters() + { sortBy: '{sortBy}', sortOrder: '{sortOrder}' })", + * parameters = "expr({ sortBy: '{sortBy}', sortOrder: '{sortOrder}' } + object.getParameters())", * absolute = "expr(object.isAbsolute())", * ) * )
corrected the links in the ListRepresentation
sulu_sulu
train
6c954eac60eaaeef8394109ba3faf0edef5caebd
diff --git a/javascript/example/DRACOLoader.js b/javascript/example/DRACOLoader.js index <HASH>..<HASH> 100644 --- a/javascript/example/DRACOLoader.js +++ b/javascript/example/DRACOLoader.js @@ -24,8 +24,6 @@ THREE.DRACOLoader = function(manager) { this.verbosity = 0; this.attributeOptions = {}; this.drawMode = THREE.TrianglesDrawMode; - // User defined unique id for attributes. - this.attributeUniqueIdMap = {}; // Native Draco attribute type to Three.JS attribute type. this.nativeAttributeMap = { 'position' : 'POSITION', @@ -104,14 +102,15 @@ THREE.DRACOLoader.prototype = { */ decodeDracoFile: function(rawBuffer, callback, attributeUniqueIdMap) { var scope = this; - this.attributeUniqueIdMap = attributeUniqueIdMap || {}; THREE.DRACOLoader.getDecoderModule() .then( function ( module ) { - scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback ); + scope.decodeDracoFileInternal( rawBuffer, module.decoder, callback, + attributeUniqueIdMap ); }); }, - decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback) { + decodeDracoFileInternal: function(rawBuffer, dracoDecoder, callback, + attributeUniqueIdMap) { /* * Here is how to use Draco Javascript decoder and get the geometry. */ @@ -137,7 +136,7 @@ THREE.DRACOLoader.prototype = { throw new Error(errorMsg); } callback(this.convertDracoGeometryTo3JS(dracoDecoder, decoder, - geometryType, buffer)); + geometryType, buffer, attributeUniqueIdMap)); }, addAttributeToGeometry: function(dracoDecoder, decoder, dracoGeometry, @@ -168,7 +167,7 @@ THREE.DRACOLoader.prototype = { }, convertDracoGeometryTo3JS: function(dracoDecoder, decoder, geometryType, - buffer) { + buffer, attributeUniqueIdMap) { if (this.getAttributeOptions('position').skipDequantization === true) { decoder.SkipAttributeTransform(dracoDecoder.POSITION); } @@ -236,7 +235,7 @@ THREE.DRACOLoader.prototype = { for (var attributeName in this.nativeAttributeMap) { // The native attribute type is only used when no unique Id is // provided. For example, loading .drc files. - if (this.attributeUniqueIdMap[attributeName] === undefined) { + if (attributeUniqueIdMap[attributeName] === undefined) { var attId = decoder.GetAttributeId(dracoGeometry, dracoDecoder[this.nativeAttributeMap[attributeName]]); if (attId !== -1) { @@ -251,8 +250,8 @@ THREE.DRACOLoader.prototype = { } // Add attributes of user specified unique id. E.g. GLTF models. - for (var attributeName in this.attributeUniqueIdMap) { - var attributeId = this.attributeUniqueIdMap[attributeName]; + for (var attributeName in attributeUniqueIdMap) { + var attributeId = attributeUniqueIdMap[attributeName]; var attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeId); this.addAttributeToGeometry(dracoDecoder, decoder, dracoGeometry,
DRACOLoader: Support requests for multiple files in parallel.
google_draco
train
c02aa5efaf28ac21915c6fc427fc9b099aabee23
diff --git a/h2o-algos/src/main/java/hex/tree/SharedTree.java b/h2o-algos/src/main/java/hex/tree/SharedTree.java index <HASH>..<HASH> 100755 --- a/h2o-algos/src/main/java/hex/tree/SharedTree.java +++ b/h2o-algos/src/main/java/hex/tree/SharedTree.java @@ -2,6 +2,8 @@ package hex.tree; import hex.*; import jsr166y.CountedCompleter; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; import water.*; import water.H2O.H2OCountedCompleter; import water.fvec.Chunk; @@ -471,6 +473,8 @@ public abstract class SharedTree<M extends SharedTreeModel<M,P,O>, P extends Sha List<String> colHeaders = new ArrayList<>(); List<String> colTypes = new ArrayList<>(); List<String> colFormat = new ArrayList<>(); + colHeaders.add("Timestamp"); colTypes.add("string"); colFormat.add("%s"); + colHeaders.add("Duration"); colTypes.add("string"); colFormat.add("%s"); colHeaders.add("Number of Trees"); colTypes.add("long"); colFormat.add("%d"); colHeaders.add("Training MSE"); colTypes.add("double"); colFormat.add("%.5f"); if (valid() != null) { @@ -490,6 +494,9 @@ public abstract class SharedTree<M extends SharedTreeModel<M,P,O>, P extends Sha int col = 0; assert(row < table.getRowDim()); assert(col < table.getColDim()); + DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); + table.set(row, col++, fmt.print(_output._training_time_ms[i])); + table.set(row, col++, PrettyPrint.msecs(_output._training_time_ms[i] - _start_time, true)); table.set(row, col++, i); table.set(row, col++, _output._mse_train[i]); if (_valid != null) table.set(row, col++, _output._mse_valid[i]); diff --git a/h2o-algos/src/main/java/hex/tree/SharedTreeModel.java b/h2o-algos/src/main/java/hex/tree/SharedTreeModel.java index <HASH>..<HASH> 100755 --- a/h2o-algos/src/main/java/hex/tree/SharedTreeModel.java +++ b/h2o-algos/src/main/java/hex/tree/SharedTreeModel.java @@ -65,6 +65,9 @@ public abstract class SharedTreeModel<M extends SharedTreeModel<M,P,O>, P extend public double _mse_train[/*_ntrees+1*/]; public double _mse_valid[/*_ntrees+1*/]; + /** Training time */ + public long _training_time_ms[/*ntrees+1*/] = new long[]{System.currentTimeMillis()}; + /** * Variable importances computed during training */ @@ -97,6 +100,7 @@ public abstract class SharedTreeModel<M extends SharedTreeModel<M,P,O>, P extend // 1-based for errors; _mse_train[0] is for zero trees, not 1 tree _mse_train = ArrayUtils.copyAndFillOf(_mse_train, _ntrees+1, Double.NaN); _mse_valid = _validation_metrics != null ? ArrayUtils.copyAndFillOf(_mse_valid, _ntrees+1, Double.NaN) : null; + _training_time_ms = ArrayUtils.copyAndFillOf(_training_time_ms, _ntrees+1, System.currentTimeMillis()); fs.blockForPending(); }
PUBDEV-<I>: Add timestamp/duration for DRF/GBM.
h2oai_h2o-3
train
b870f87d238fe4627fcbb274eae2e018c71c9504
diff --git a/test/GitWrapper/Test/GitWorkingCopyTest.php b/test/GitWrapper/Test/GitWorkingCopyTest.php index <HASH>..<HASH> 100644 --- a/test/GitWrapper/Test/GitWorkingCopyTest.php +++ b/test/GitWrapper/Test/GitWorkingCopyTest.php @@ -429,4 +429,25 @@ PATCH; stream_filter_remove($stdoutSuppress); } + + public function testCommitWithAuthor() + { + $git = $this->getWorkingCopy(); + file_put_contents(self::WORKING_DIR . '/commit.txt', "created\n"); + + $this->assertTrue($git->hasChanges()); + + $git + ->add('commit.txt') + ->commit(array( + 'm' => 'Committed testing branch.', + 'a' => true, + 'author' => 'test <[email protected]>' + )) + ; + + $output = (string) $git->log(); + $this->assertContains('Committed testing branch', $output); + $this->assertContains('Author: test <[email protected]>', $output); + } }
Add a test on author parameter Here is a working test/example on how to use the author parameter with the commit command Related #<I>
cpliakas_git-wrapper
train
c414408b9a07dd36cb8cca1a857764ab19e0f170
diff --git a/teknek-stream-stack/src/main/java/io/teknek/streamstack/StandAloneKafkaServer.java b/teknek-stream-stack/src/main/java/io/teknek/streamstack/StandAloneKafkaServer.java index <HASH>..<HASH> 100644 --- a/teknek-stream-stack/src/main/java/io/teknek/streamstack/StandAloneKafkaServer.java +++ b/teknek-stream-stack/src/main/java/io/teknek/streamstack/StandAloneKafkaServer.java @@ -17,7 +17,7 @@ public class StandAloneKafkaServer { public static final String EMBED_KAFKA = "starter.embeddedkafka"; public static final String EMBED_KAFKA_LOG = "starter.embeddedkafka.log"; - public static final String EMBED_KAFKA_LOG_DIR = "./kflog"; + public static final String EMBED_KAFKA_LOG_DIR = "./target/kflog"; public static KafkaServer server; @@ -58,7 +58,7 @@ public class StandAloneKafkaServer { } - +/** This is a copy if we get the deps correct we should not need this*/ class TimeImpl implements Time { public TimeImpl(){
Comment about copy and adjust kf dir
edwardcapriolo_teknek-core
train
62d3b78219763fa8906fe91db5dc0fda2c6b5b0c
diff --git a/lib/rtanque/heading.rb b/lib/rtanque/heading.rb index <HASH>..<HASH> 100644 --- a/lib/rtanque/heading.rb +++ b/lib/rtanque/heading.rb @@ -67,7 +67,7 @@ module RTanque # Creates a new RTanque::Heading # @param [#to_f] radians degree to wrap (in radians) def initialize(radians = NORTH) - @radians = self.extract_radians_from_value(radians) % FULL_ANGLE + @radians = radians.to_f % FULL_ANGLE @memoized = {} # allow memoization since @some_var ||= x doesn't work when frozen self.freeze end @@ -108,7 +108,7 @@ module RTanque # @param [#to_f] other_heading # @return [RTanque::Heading] def +(other_heading) - self.class.new(self.radians + self.extract_radians_from_value(other_heading)) + self.class.new(self.radians + other_heading.to_f) end # @param [#to_f] other_heading @@ -120,7 +120,7 @@ module RTanque # @param [#to_f] other_heading # @return [RTanque::Heading] def *(other_heading) - self.class.new(self.radians * self.extract_radians_from_value(other_heading)) + self.class.new(self.radians * other_heading.to_f) end # @param [#to_f] other_heading @@ -158,15 +158,5 @@ module RTanque def to_degrees @memoized[:to_degrees] ||= (self.radians * 180.0) / Math::PI end - - protected - - def extract_radians_from_value(value) - if value.respond_to?(:radians) - value.radians - else - value.to_f - end - end end end \ No newline at end of file
removes unneeded method from Heading, relying on duck typing of headings
awilliams_RTanque
train
e3dfadace04afa123b30fcd19e1422a8d8cfe01f
diff --git a/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/resource/NIOFileResource.java b/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/resource/NIOFileResource.java index <HASH>..<HASH> 100644 --- a/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/resource/NIOFileResource.java +++ b/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/resource/NIOFileResource.java @@ -28,10 +28,13 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URI; +import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashSet; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; @@ -56,7 +59,9 @@ public class NIOFileResource extends FileResource { return; } - java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { + Set<FileVisitOption> options = new HashSet<FileVisitOption>(); + options.add(FileVisitOption.FOLLOW_LINKS); + java.nio.file.Files.walkFileTree(file.toPath(), options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { @@ -90,7 +95,7 @@ public class NIOFileResource extends FileResource { } @Override public boolean isFolder() { - return attrs.isDirectory(); + return attrs.isDirectory() || attrs.isSymbolicLink() && file.isDirectory(); } @Override public URI getURI() {
Fix issues with NIOFileResource and symbolic links
OpenNTF_JavascriptAggregator
train
bc7604837100095d51841fa56953de6de7076dc1
diff --git a/tsdb/engine/tsm1/cache.go b/tsdb/engine/tsm1/cache.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/cache.go +++ b/tsdb/engine/tsm1/cache.go @@ -334,21 +334,27 @@ func (c *Cache) DeleteRange(keys []string, min, max int64) { defer c.mu.Unlock() for _, k := range keys { - origSize := c.store[k].size() + // Make sure key exist in the cache, skip if it does not + e, ok := c.store[k] + if !ok { + continue + } + + origSize := e.size() if min == math.MinInt64 && max == math.MaxInt64 { c.size -= uint64(origSize) delete(c.store, k) continue } - c.store[k].filter(min, max) - if c.store[k].count() == 0 { + e.filter(min, max) + if e.count() == 0 { delete(c.store, k) c.size -= uint64(origSize) continue } - c.size -= uint64(origSize - c.store[k].size()) + c.size -= uint64(origSize - e.size()) } } diff --git a/tsdb/engine/tsm1/cache_test.go b/tsdb/engine/tsm1/cache_test.go index <HASH>..<HASH> 100644 --- a/tsdb/engine/tsm1/cache_test.go +++ b/tsdb/engine/tsm1/cache_test.go @@ -146,6 +146,7 @@ func TestCache_DeleteRange_NoValues(t *testing.T) { t.Fatalf("cache values mismatch: got %v, exp %v", got, exp) } } + func TestCache_Cache_Delete(t *testing.T) { v0 := NewValue(1, 1.0) v1 := NewValue(2, 2.0) @@ -185,6 +186,16 @@ func TestCache_Cache_Delete(t *testing.T) { } } +func TestCache_Cache_Delete_NonExistent(t *testing.T) { + c := NewCache(1024, "") + + c.Delete([]string{"bar"}) + + if got, exp := c.Size(), uint64(0); exp != got { + t.Fatalf("cache size incorrect after 2 writes, exp %d, got %d", exp, got) + } +} + // This tests writing two batches to the same series. The first batch // is sorted. The second batch is also sorted but contains duplicates. func TestCache_CacheWriteMulti_Duplicates(t *testing.T) {
Fix panic in cache.DeleteRange Deleting keys that did not exist in the cache could cause a panic because the entry returned would be nil and was not checked.
influxdata_influxdb
train
160a14567f093a7406fd7713c1c644d6c0533dd3
diff --git a/tests/pay_to_test.py b/tests/pay_to_test.py index <HASH>..<HASH> 100755 --- a/tests/pay_to_test.py +++ b/tests/pay_to_test.py @@ -152,5 +152,10 @@ class ScriptTypesTest(unittest.TestCase): tx2.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup) self.assertEqual(tx2.bad_signature_count(), 0) + def test_weird_tx(self): + # this is from tx 12a8d1d62d12307eac6e62f2f14d7e826604e53c320a154593845aa7c8e59fbf + st = script_obj_from_script(b'Q') + self.assertNotEqual(st, None) + if __name__ == "__main__": unittest.main()
Add a new (failing) test.
richardkiss_pycoin
train
bf4bce9aca4dee2eded4bcbe9d78d23f964189cc
diff --git a/instabot/api/api.py b/instabot/api/api.py index <HASH>..<HASH> 100644 --- a/instabot/api/api.py +++ b/instabot/api/api.py @@ -72,9 +72,9 @@ class API(object): if generate_uuid is True: # This field should be stores in json, data and cookie in json file. # Next step! self.phone_id = self.generate_UUID(uuid_type=True) self.uuid = self.generate_UUID(uuid_type=True) - self.session_id = self.generate_UUID(uuid_type=True) + self.client_session_id = self.generate_UUID(uuid_type=True) self.device_id = self.generate_device_id(self.get_seed(username, password)) - # self.logger.info("uuid GENERATE! phone_id={}, uuid={}, session_id={}, device_id={}".format( self.phone_id, self.uuid, self.session_id, self.device_id )) + # self.logger.info("uuid GENERATE! phone_id={}, uuid={}, session_id={}, device_id={}".format( self.phone_id, self.uuid, self.client_session_id, self.device_id )) def sync_device_features(self, login=False): data = { 'id': self.uuid, 'server_config_retrieval': '1', 'experiments': config.LOGIN_EXPERIMENTS } @@ -121,7 +121,7 @@ class API(object): self.get_suggested_searches('blended') else: if random.randint(1, 100) % 2 == 0: # Randomly change session_id (should be change every x times!) - self.session_id = self.generate_UUID(uuid_type=True) + self.client_session_id = self.generate_UUID(uuid_type=True) self.get_timeline_feed(options=['is_pull_to_refresh'] if random.randint(1, 100) % 2 == 0 else [] ) # Random pull_to_refresh :) @@ -453,7 +453,7 @@ class API(object): 'is_prefetch': '0', 'phone_id': self.phone_id, 'device_id': self.uuid, - 'client_session_id': self.session_id, + 'client_session_id': self.client_session_id, 'battery_level': random.randint(25, 100), 'is_charging': '0', 'will_sound_on': '1',
rename session_id prevent multiple variable with the same name
instagrambot_instabot
train
27a886f29e33c73b335691e448a19ffd48bc591f
diff --git a/library/src/main/java/de/mrapp/android/bottomsheet/view/DraggableView.java b/library/src/main/java/de/mrapp/android/bottomsheet/view/DraggableView.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/de/mrapp/android/bottomsheet/view/DraggableView.java +++ b/library/src/main/java/de/mrapp/android/bottomsheet/view/DraggableView.java @@ -39,8 +39,6 @@ import de.mrapp.android.bottomsheet.animation.DraggableViewAnimation; import de.mrapp.android.util.DisplayUtil.DeviceType; import de.mrapp.android.util.gesture.DragHelper; -import static de.mrapp.android.util.Condition.ensureAtLeast; -import static de.mrapp.android.util.Condition.ensureAtMaximum; import static de.mrapp.android.util.DisplayUtil.getDeviceType; /** @@ -474,17 +472,6 @@ public class DraggableView extends LinearLayout implements ViewTreeObserver.OnGl } /** - * Returns the relative width of the view in relation to the display width. The relative width - * is only used on tablet devices or in landscape mode. - * - * @return The relative width of the view in relation to the display width as a {@link Float} - * value - */ - public final float getRelativeWidth() { - return relativeWidth; - } - - /** * Sets the relative width of the view in relation to the display width. The relative width is * only used on tablet devices or in landscape mode. * @@ -493,23 +480,10 @@ public class DraggableView extends LinearLayout implements ViewTreeObserver.OnGl * be at least 0 and at maximum 1 */ public final void setRelativeWidth(final float relativeWidth) { - ensureAtLeast(relativeWidth, 0, "The relative width must be at least 0"); - ensureAtMaximum(relativeWidth, 1, "The relative width must be at maximum 1"); this.relativeWidth = relativeWidth; } /** - * Returns the minimum width of the view. The minimum width is only used on tablet devices or in - * landscape mode. - * - * @return The minimum width of the view in pixels as an {@link Integer} value or -1, if no - * minimum width has been set - */ - public final int getMinWidth() { - return minWidth; - } - - /** * Sets the minimum width of the view. The minimum width is only used on tablet devices or in * landscape mode. * @@ -518,25 +492,10 @@ public class DraggableView extends LinearLayout implements ViewTreeObserver.OnGl * if no minimum width should be set */ public final void setMinWidth(final int minWidth) { - if (minWidth != -1) { - ensureAtLeast(minWidth, 1, "The minimum width must be at least 1"); - } - this.minWidth = minWidth; } /** - * Returns the maximum width of the view. The maximum width is only used on tablet devices or in - * landscape mode. - * - * @return The maximum width of the view in pixels as an {@link Integer} value or -1, if no - * maximum width has been set - */ - public final int getMaxWidth() { - return maxWidth; - } - - /** * Sets the maximum width of the view. The maximum width is only used on tablet devices or in * landscape mode. * @@ -545,10 +504,6 @@ public class DraggableView extends LinearLayout implements ViewTreeObserver.OnGl * if no maximum width should be set */ public final void setMaxWidth(final int maxWidth) { - if (maxWidth != -1) { - ensureAtLeast(maxWidth, 1, "The maximum width must be at least 1"); - } - this.maxWidth = maxWidth; }
Removed unused getter methods.
michael-rapp_AndroidBottomSheet
train
a3ba88f522ed898aef6a52f6b96a65d10ad0df65
diff --git a/lib/multirepo/commands/clone-command.rb b/lib/multirepo/commands/clone-command.rb index <HASH>..<HASH> 100644 --- a/lib/multirepo/commands/clone-command.rb +++ b/lib/multirepo/commands/clone-command.rb @@ -1,6 +1,7 @@ require "multirepo/utility/console" require "multirepo/utility/utils" require "multirepo/git/repo" +require_relative "install-command" module MultiRepo class CloneCommand < Command @@ -27,7 +28,7 @@ module MultiRepo end def run - Console.log_step("Cloning #{url} ...") + Console.log_step("Cloning #{@url} ...") raise MultiRepoException, "A directory named #{@name} already exists" if Dir.exists?(@name) @@ -37,8 +38,13 @@ module MultiRepo main_repo = Repo.new(main_repo_path) main_repo.clone(@url) - - # TODO: Perform a multi install in the target main repo directory + + original_path = Dir.pwd + Dir.chdir(main_repo_path) + + InstallCommand.new(CLAide::ARGV.new([])).install_internal + + Dir.chdir(original_path) Console.log_step("Done!") rescue MultiRepoException => e diff --git a/lib/multirepo/commands/install-command.rb b/lib/multirepo/commands/install-command.rb index <HASH>..<HASH> 100644 --- a/lib/multirepo/commands/install-command.rb +++ b/lib/multirepo/commands/install-command.rb @@ -13,6 +13,14 @@ module MultiRepo Console.log_step("Cloning dependencies and installing hook...") + install_internal + + Console.log_step("Done!") + rescue MultiRepoException => e + Console.log_error(e.message) + end + + def install_internal config_entries = ConfigFile.load Console.log_info("There are #{config_entries.count} dependencies to install"); @@ -20,10 +28,6 @@ module MultiRepo config_entries.each { |e| install(e) } self.install_pre_commit_hook - - Console.log_step("Done!") - rescue MultiRepoException => e - Console.log_error(e.message) end def install(entry)
Performing an install after the main repo clone in CloneCommand.
fortinmike_git-multirepo
train
36b35a957a7c93d7efcb88082361c3dad5bd6ba1
diff --git a/lib/Scvmm/miq_scvmm_vm_ssa_info.rb b/lib/Scvmm/miq_scvmm_vm_ssa_info.rb index <HASH>..<HASH> 100644 --- a/lib/Scvmm/miq_scvmm_vm_ssa_info.rb +++ b/lib/Scvmm/miq_scvmm_vm_ssa_info.rb @@ -18,17 +18,6 @@ class MiqScvmmVmSSAInfo @parser = MiqScvmmParsePowershell.new end - def vm_host(vm_name) - host_script = <<-HOST_EOL -Get-SCVirtualMachine -VMMServer localhost -Name "#{vm_name}" | \ - Select-Object -ExpandProperty Hostname -HOST_EOL - - @hostname, stderr = @parser.parse_single_powershell_value(@winrm.run_powershell_script(host_script)) - raise "Unable to obtain Host for #{vm_name}" if stderr =~ /At line:/ - @hostname - end - # Note the following method returns *all* hard disks and some common attributes from the Hyper-V host def vm_all_harddisks(vm_name, snapshot = nil, check_snapshot = TRUE) vhds = vm_get_disks(vm_name, snapshot, check_snapshot) @@ -47,17 +36,6 @@ HOST_EOL new_vhds end - def vm_vhdtype(vm_name) - vhdtype_script = <<-VHDTYPE_EOL -Get-SCVirtualHardDisk -VMMServer localhost -VM "#{vm_name}" | \ - Select-Object -ExpandProperty VHDType -VHDTYPE_EOL - - @vhd_type, stderr = @parser.parse_single_powershell_value(@winrm.run_powershell_script(vhdtype_script)) - raise "Unable to obtain VHD Type for #{vm_name}" if stderr =~ /At line:/ - @vhd_type - end - def vm_get_checkpoint(vm_name, snapshot) get_checkpoint_script = <<-GETCHECKPOINT_EOL Get-VMSnapShot -ComputerName localhost -VMName "#{vm_name}" -Name "#{snapshot}"| \
Remove unused MiqScvmmVmSSAInfo Methods Remove unused methods vm_host() and vm_vhdtype. These were used in earlier versions of the HyperV SSA code but are no longer used. (transferred from ManageIQ/manageiq-gems-pending@c<I>ff9a<I>ae<I>a<I>e<I>d<I>fccd1f<I>a<I>)
ManageIQ_manageiq-smartstate
train
329c0a8ae6fde575a7d9077f1013fa4a86112d0c
diff --git a/flex/core.py b/flex/core.py index <HASH>..<HASH> 100644 --- a/flex/core.py +++ b/flex/core.py @@ -66,7 +66,7 @@ def load_source(source): pass try: - return yaml.load(raw_source) + return yaml.safe_load(raw_source) except (yaml.scanner.ScannerError, yaml.parser.ParserError): pass except NameError: diff --git a/tests/core/test_load_source.py b/tests/core/test_load_source.py index <HASH>..<HASH> 100644 --- a/tests/core/test_load_source.py +++ b/tests/core/test_load_source.py @@ -27,7 +27,7 @@ def test_json_string(): def test_yaml_string(): - native = {'foo': 'bar'} + native = {b'foo': b'bar'} source = yaml.dump(native) result = load_source(source) @@ -62,7 +62,7 @@ def test_json_file_path(): def test_yaml_file_object(): - native = {'foo': 'bar'} + native = {b'foo': b'bar'} source = yaml.dump(native) tmp_file = tempfile.NamedTemporaryFile(mode='w') @@ -76,7 +76,7 @@ def test_yaml_file_object(): def test_yaml_file_path(): - native = {'foo': 'bar'} + native = {b'foo': b'bar'} source = yaml.dump(native) tmp_file = tempfile.NamedTemporaryFile(mode='w', suffix='.yaml')
Fix remote code execution issue with yaml.load
pipermerriam_flex
train
08ccf7b5dc1b58c833445b7d39f636b0526abc07
diff --git a/holoviews/element/raster.py b/holoviews/element/raster.py index <HASH>..<HASH> 100644 --- a/holoviews/element/raster.py +++ b/holoviews/element/raster.py @@ -420,6 +420,10 @@ class RGB(Matrix): sliced = data[:,:,:-1] alpha = data[:,:,-1] + if len(params.get('value_dimensions',[])) == 4: + alpha_dim = params['value_dimensions'].pop(3) + params['alpha_dimension'] = alpha_dim + super(RGB, self).__init__(data if sliced is None else sliced, **params) if sliced is not None: self.value_dimensions.append(self.alpha_dimension)
Fixed constructor of RGB to handle four value dimensions as input
pyviz_holoviews
train
cf842f9b5bae590af9514f55a63166d9b2e4a49f
diff --git a/lib/cloud_crowd/models/node_record.rb b/lib/cloud_crowd/models/node_record.rb index <HASH>..<HASH> 100644 --- a/lib/cloud_crowd/models/node_record.rb +++ b/lib/cloud_crowd/models/node_record.rb @@ -47,7 +47,7 @@ module CloudCrowd rescue RestClient::RequestFailed => e raise e unless e.http_code == 503 && e.http_body == Node::OVERLOADED_MESSAGE update_attribute(:busy, true) && false - rescue RestClient::Exception, Errno::ECONNREFUSED, Timeout::Error + rescue RestClient::Exception, Errno::ECONNREFUSED, Timeout::Error, RestClient::RequestTimeout, Errno::ECONNRESET # Couldn't post to node, assume it's gone away. destroy && false end
Adding more exceptions to be rescued when communication between server and node has failed.
documentcloud_cloud-crowd
train
791fafd9dcaabd92a0c212d6f2bf30c3c0651a09
diff --git a/eZ/Publish/API/Repository/Values/Content/ContentUpdateStruct.php b/eZ/Publish/API/Repository/Values/Content/ContentUpdateStruct.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/API/Repository/Values/Content/ContentUpdateStruct.php +++ b/eZ/Publish/API/Repository/Values/Content/ContentUpdateStruct.php @@ -8,12 +8,7 @@ use eZ\Publish\API\Repository\Values\ValueObject; */ abstract class ContentUpdateStruct extends ValueObject { - /** - * @var mixed modifier of the new version. If not set the current authenticated user is used. - */ - public $userId; - - + /** * The language code of the version. In 4.x this code will be used as the language code of the translation * (which is shown in the admin interface). @@ -29,9 +24,11 @@ abstract class ContentUpdateStruct extends ValueObject * $fields[$fieldDefIdentifier][$language] = $value or without language $fields[$fieldDefIdentifier] = $value * is an equivalent call. * + * @throws \eZ\Publish\API\Repository\Exceptions\BasStateException if the field is translatable and $initialLanguageCode is not set and $languageCode is NULL + * * @param string $fieldDefIdentifier the identifier of the field definition * @param mixed $value Either a plain value which is understandable by the field type or an instance of a Value class provided by the field type * @param bool|string $languageCode If not given on a translatable field the initial language is used, */ - abstract public function setField( $fieldDefIdentifier, $value, $languageCode = false ); + abstract public function setField( $fieldDefIdentifier, $value, $languageCode = NULL ); }
removed user id and added exception in set Fields
ezsystems_ezpublish-kernel
train
85796629e460c18df9506df48128ccb8b7b14f18
diff --git a/estnltk/tests/test_taggers/test_standard_taggers/test_gap_tagger.py b/estnltk/tests/test_taggers/test_standard_taggers/test_gap_tagger.py index <HASH>..<HASH> 100644 --- a/estnltk/tests/test_taggers/test_standard_taggers/test_gap_tagger.py +++ b/estnltk/tests/test_taggers/test_standard_taggers/test_gap_tagger.py @@ -59,8 +59,8 @@ def test_bad_trim(): def test_tagger(): tagger = GapTagger(input_layers=['test_1', 'test_2', 'test_3'], output_layer='gaps') - input_file = rel_path('tests/test_taggers/test_gaps_tagging/gap_tagger_input.json') - target_file = rel_path('tests/test_taggers/test_gaps_tagging/gap_tagger_target.json') + input_file = rel_path('tests/test_taggers/test_standard_taggers/gap_tagger_input.json') + target_file = rel_path('tests/test_taggers/test_standard_taggers/gap_tagger_target.json') tester = TaggerTester(tagger, input_file, target_file) tester.load()
moved gaps tagger tests to test_standard_taggers/
estnltk_estnltk
train
dec606433b4475e5f67dcde0731e17353fe46b92
diff --git a/src/Hodor/JobQueue/BufferQueue.php b/src/Hodor/JobQueue/BufferQueue.php index <HASH>..<HASH> 100644 --- a/src/Hodor/JobQueue/BufferQueue.php +++ b/src/Hodor/JobQueue/BufferQueue.php @@ -2,6 +2,7 @@ namespace Hodor\JobQueue; +use Hodor\MessageQueue\IncomingMessage; use Hodor\MessageQueue\Queue; class BufferQueue @@ -52,7 +53,7 @@ class BufferQueue public function processBuffer() { - $this->message_queue->consume(function ($message) { + $this->message_queue->consume(function (IncomingMessage $message) { $superqueue = $this->queue_manager->getSuperqueue(); $superqueue->bufferJobFromBufferQueueToDatabase($message); }); diff --git a/src/Hodor/JobQueue/WorkerQueue.php b/src/Hodor/JobQueue/WorkerQueue.php index <HASH>..<HASH> 100644 --- a/src/Hodor/JobQueue/WorkerQueue.php +++ b/src/Hodor/JobQueue/WorkerQueue.php @@ -3,6 +3,7 @@ namespace Hodor\JobQueue; use DateTime; +use Hodor\MessageQueue\IncomingMessage; use Hodor\MessageQueue\Queue; class WorkerQueue @@ -46,18 +47,23 @@ class WorkerQueue */ public function runNext(callable $job_runner) { - $this->message_queue->consume(function ($message) use ($job_runner) { + $this->message_queue->consume(function (IncomingMessage $message) use ($job_runner) { $start_time = new DateTime; - register_shutdown_function(function ($message, $start_time, $queue_manager) { - if (error_get_last()) { - $queue_manager->getSuperqueue()->markJobAsFailed( - $message, - $start_time - ); - exit(1); - } - }, $message, $start_time, $this->queue_manager); + register_shutdown_function( + function (IncomingMessage $message, DateTime $start_time, QueueManager $queue_manager) { + if (error_get_last()) { + $queue_manager->getSuperqueue()->markJobAsFailed( + $message, + $start_time + ); + exit(1); + } + }, + $message, + $start_time, + $this->queue_manager + ); $content = $message->getContent(); $name = $content['name'];
Add type hints to JobQueue's MQ#consume() callbacks Without the type hints, IDEs have a hard time following and autocompleting the objects
lightster_hodor
train
822a4132d2bb0e85372e8f7790b9bd4db9c5f17e
diff --git a/test/pnut.js b/test/pnut.js index <HASH>..<HASH> 100644 --- a/test/pnut.js +++ b/test/pnut.js @@ -11,12 +11,13 @@ const pnut = require('../lib/pnut'); describe('The pnut API wrapper', function () { before(function() { - let root = 'https://api.pnut.io' - nock(root) + let base = 'https://api.pnut.io'; + + nock(base) .get('/v0') .reply(200, {}) - nock(root) + nock(base) .get('/v0/posts/streams/global') .reply(200, {posts: 1}) });
Rename variable for more consitency
kaiwood_pnut-butter
train
db7419f88f84a9e4e0de5cde4918788f477fa1a6
diff --git a/lib/components/form/settings-selector-panel.js b/lib/components/form/settings-selector-panel.js index <HASH>..<HASH> 100644 --- a/lib/components/form/settings-selector-panel.js +++ b/lib/components/form/settings-selector-panel.js @@ -26,7 +26,7 @@ class SettingsSelectorPanel extends Component { } for (const m of queryModes) { - if (m.startsWith(mode.mode)) return true + if (m === mode.mode) return true } return false } @@ -145,6 +145,10 @@ class SettingsSelectorPanel extends Component { label: 'Bike + Transit' }, { + mode: 'BICYCLE_RENT', + label: 'Biketown + Transit' + }, + { mode: 'CAR_PARK', label: 'Park & Ride' }, @@ -278,7 +282,7 @@ class SettingsSelectorPanel extends Component { <div style={{ fontSize: 18, margin: '16px 0px' }}>Travel Preferences</div> {/* The bike trip type selector */} - {hasBike(mode) && (<div style={{ marginBottom: 16 }}> + {hasBike(mode) && !hasTransit(mode) && (<div style={{ marginBottom: 16 }}> <div className='setting-label' style={{ float: 'left' }}>Use</div> <div style={{ textAlign: 'right' }}> <ButtonGroup>
feat(form): Add Biketown+Transit to mode selector form
opentripplanner_otp-react-redux
train
a0638bd5e3bb439eb906e110a0bca8a04627ae42
diff --git a/facepy/graph_api.py b/facepy/graph_api.py index <HASH>..<HASH> 100755 --- a/facepy/graph_api.py +++ b/facepy/graph_api.py @@ -295,3 +295,8 @@ class GraphAPI(object): class HTTPError(FacepyError): """Exception for transport errors.""" + +# Define the nested Exception in the module scope so they can be pickled +FacebookError = GraphAPI.FacebookError +OAuthError = GraphAPI.OAuthError +HTTPError = GraphAPI.HTTPError \ No newline at end of file diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index <HASH>..<HASH> 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -3,9 +3,29 @@ from nose.tools import * from facepy import * +from facepy.graph_api import GraphAPI +import cPickle def test_facepy_error(): try: raise FacepyError('<message>') except FacepyError as exception: assert exception.message == '<message>' + +def test_facebookerror_can_be_pickled(): + try: + raise GraphAPI.FacebookError('<message>', '<code>') + except FacepyError as exception: + cPickle.dumps(exception) + +def test_oautherror_can_be_pickled(): + try: + raise GraphAPI.OAuthError('<message>', '<code>') + except FacepyError as exception: + cPickle.dumps(exception) + +def test_httperror_can_be_pickled(): + try: + raise GraphAPI.HTTPError('<message>') + except FacepyError as exception: + cPickle.dumps(exception)
GraphAPI nested exception can't be pickled, which fails on celery tasks. Fixed and added regression tests.
jgorset_facepy
train
fb310f0e32eef9bab9672a590f79e1f176e09b98
diff --git a/core/graph.py b/core/graph.py index <HASH>..<HASH> 100644 --- a/core/graph.py +++ b/core/graph.py @@ -110,6 +110,10 @@ def plotFCM(data, channel_names, transform=(None, None), plot2d_type='dot2d', ax if len(channelIndexList) == 1: # 1d so histogram plot + kwargs.setdefault('color', 'gray') + kwargs.setdefault('histtype', 'stepfilled') + #kwargs.setdefault('facecolor', 'green') + ch1i = channelIndexList[0] pHandle = ax.hist(data[:, ch1i], **kwargs)
Updated defaults for histogram plots
eyurtsev_FlowCytometryTools
train
27eb574c5835bd490784d24ecdcd75a92417fa70
diff --git a/CMakeLists.txt b/CMakeLists.txt index <HASH>..<HASH> 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -482,7 +482,7 @@ if(${BUILD_TESTING}) set(TANGELO_EXECUTABLE ${VENV_DIR}/bin/tangelo) add_custom_command( OUTPUT ${TANGELO_EXECUTABLE} - COMMAND ${PIP_EXECUTABLE} install --upgrade --force-reinstall ${TANGELO_PACKAGE} + COMMAND ${PIP_EXECUTABLE} install --upgrade ${TANGELO_PACKAGE} DEPENDS ${PIP_EXECUTABLE} ${TANGELO_PACKAGE} COMMENT "Installing Tangelo" ) diff --git a/tangelo/tangelo/__init__.py b/tangelo/tangelo/__init__.py index <HASH>..<HASH> 100644 --- a/tangelo/tangelo/__init__.py +++ b/tangelo/tangelo/__init__.py @@ -204,6 +204,18 @@ def return_type(rettype): error will be raised. """ def wrap(f): - f.return_type = rettype - return f + @functools.wraps(f) + def converter(*pargs, **kwargs): + # Run the function to capture the output. + result = f(*pargs, **kwargs) + + # Convert the result using the return type function. + try: + result = rettype(result) + except ValueError as e: + return {"error": "could not convert return value: %s" % (str(e))} + + return result + + return converter return wrap diff --git a/testing/py-unit-tests/tangelo-types.py b/testing/py-unit-tests/tangelo-types.py index <HASH>..<HASH> 100644 --- a/testing/py-unit-tests/tangelo-types.py +++ b/testing/py-unit-tests/tangelo-types.py @@ -78,10 +78,10 @@ class Tester(unittest.TestCase): data["foo"] = "bar" return data - result = dump({"bar": "baz"}) + test_data = {"bar": "baz"} + result = dump(test_data) - self.assertTrue("return_type" in dump.__dict__) - self.assertEqual(dump.return_type, excite) + self.assertEqual(result, json.dumps(test_data) + "!!!") if __name__ == "__main__":
Simplifying approach for return_type decorator. No longer requires changes to the server infrastructure - just automatically runs the requested function on the output from the service function, and returns an error if something went wrong.
Kitware_tangelo
train
f04d503958a4fe854c1b41667c73f8813c9dd9c3
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # CHANGELOG +## v10.11.2 + +### Bug Fixes + +- Validation for integers handles int and int64 types. + ## v10.11.1 ### Bug Fixes diff --git a/autorest/validation/validation.go b/autorest/validation/validation.go index <HASH>..<HASH> 100644 --- a/autorest/validation/validation.go +++ b/autorest/validation/validation.go @@ -136,29 +136,29 @@ func validatePtr(x reflect.Value, v Constraint) error { func validateInt(x reflect.Value, v Constraint) error { i := x.Int() - r, ok := v.Rule.(int) + r, ok := toInt64(v.Rule) if !ok { return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) } switch v.Name { case MultipleOf: - if i%int64(r) != 0 { + if i%r != 0 { return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) } case ExclusiveMinimum: - if i <= int64(r) { + if i <= r { return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) } case ExclusiveMaximum: - if i >= int64(r) { + if i >= r { return createError(x, v, fmt.Sprintf("value must be less than %v", r)) } case InclusiveMinimum: - if i < int64(r) { + if i < r { return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) } case InclusiveMaximum: - if i > int64(r) { + if i > r { return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) } default: @@ -388,6 +388,17 @@ func createError(x reflect.Value, v Constraint, err string) error { v.Target, v.Name, getInterfaceValue(x), err) } +func toInt64(v interface{}) (int64, bool) { + if i64, ok := v.(int64); ok { + return i64, true + } + // older generators emit max constants as int, so if int64 fails fall back to int + if i32, ok := v.(int); ok { + return int64(i32), true + } + return 0, false +} + // NewErrorWithValidationError appends package type and method name in // validation error. // diff --git a/autorest/validation/validation_test.go b/autorest/validation/validation_test.go index <HASH>..<HASH> 100644 --- a/autorest/validation/validation_test.go +++ b/autorest/validation/validation_test.go @@ -1090,7 +1090,7 @@ func TestValidateInt_inclusiveMaximumConstraintValid(t *testing.T) { c := Constraint{ Target: "str", Name: InclusiveMaximum, - Rule: 2, + Rule: int64(2), Chain: nil, } require.Nil(t, validateInt(reflect.ValueOf(1), c)) @@ -1101,7 +1101,7 @@ func TestValidateInt_inclusiveMaximumConstraintInvalid(t *testing.T) { c := Constraint{ Target: "str", Name: InclusiveMaximum, - Rule: 1, + Rule: int64(1), Chain: nil, } require.Equal(t, validateInt(reflect.ValueOf(x), c).Error(), @@ -1112,7 +1112,7 @@ func TestValidateInt_inclusiveMaximumConstraintBoundary(t *testing.T) { c := Constraint{ Target: "str", Name: InclusiveMaximum, - Rule: 1, + Rule: int64(1), Chain: nil, } require.Nil(t, validateInt(reflect.ValueOf(1), c)) diff --git a/autorest/version.go b/autorest/version.go index <HASH>..<HASH> 100644 --- a/autorest/version.go +++ b/autorest/version.go @@ -16,5 +16,5 @@ package autorest // Version returns the semantic version (see http://semver.org). func Version() string { - return "v10.11.1" + return "v10.11.2" }
Validation code handles int and int<I> (#<I>) Ensure that integer validation can handle int and int<I>.
Azure_go-autorest
train
0868db5bf17223bb551db1ac0720a339fef1c536
diff --git a/test/e2e_node/util.go b/test/e2e_node/util.go index <HASH>..<HASH> 100644 --- a/test/e2e_node/util.go +++ b/test/e2e_node/util.go @@ -172,7 +172,6 @@ func setKubeletConfiguration(f *framework.Framework, kubeCfg *kubeletconfig.Kube ConfigMap: &apiv1.ConfigMapNodeConfigSource{ Namespace: "kube-system", Name: cm.Name, - UID: cm.UID, KubeletConfigKey: "kubelet", }, }
fix the e2e node helpers that let tests reconfigure Kubelet The dynamic config tests were updated with the validation change, but the tests that try to use dynamic config via this helper were not.
kubernetes_kubernetes
train
d86dd0c37572a15614758d8baaca95b6524030dc
diff --git a/lib/crawler/webcrawler.rb b/lib/crawler/webcrawler.rb index <HASH>..<HASH> 100644 --- a/lib/crawler/webcrawler.rb +++ b/lib/crawler/webcrawler.rb @@ -39,7 +39,7 @@ module Crawler next_uri = uri + t.attribute("href").to_s.strip next_uri unless @crawled.include?(next_uri) or next_uri == uri end - @queue = @queue.uniq.compact + @queue = @queue.compact.uniq @crawled << uri end }
Switched order to play nice when multiple nils
tylercunnion_crawler
train
f4acbc92f3c15f00a683ada70ab1da913c265902
diff --git a/ideascaly/binder.py b/ideascaly/binder.py index <HASH>..<HASH> 100644 --- a/ideascaly/binder.py +++ b/ideascaly/binder.py @@ -63,7 +63,10 @@ def bind_api(**config): def execute(self): # Build the URL of the end-point url = self.api.url + self.path - full_url = 'http://' + self.api.community_url + url + if self.api.community_url.find("http") == -1: + full_url = 'http://' + self.api.community_url + url + else: + full_url = self.api.community_url + url # Execute request try:
Modify statement that creates end-point url
joausaga_ideascaly
train
b877a9d2edebb20bda4fbdef04605bc1a02b0ef4
diff --git a/spec/requests/removing_blocks_spec.rb b/spec/requests/removing_blocks_spec.rb index <HASH>..<HASH> 100644 --- a/spec/requests/removing_blocks_spec.rb +++ b/spec/requests/removing_blocks_spec.rb @@ -30,4 +30,33 @@ describe NoCms::Admin::Pages do end end + + context "when removing nested blocks", js: true do + + let(:nocms_page) { create :nocms_page } + let(:block_container) { create :nocms_block, layout: 'container_with_background', page: nocms_page } + let(:block_nested) { create :nocms_block, layout: 'logo-caption', page: nocms_page, caption: Faker::Lorem.sentence, parent: block_container } + + subject { page } + + before do + + block_nested + + visit no_cms_admin_pages.edit_page_path(nocms_page) + + within("#content_block_#{block_nested.id}") do + click_link I18n.t('no_cms.admin.pages.blocks.form.remove') + end + + click_button(I18n.t('no_cms.admin.pages.pages.toolbar_right.submit')) + + end + + it "should not show the removed contents" do + visit nocms_page.path + expect(page).to_not have_selector('.caption', text: block_nested.caption) + end + + end end
Tested removing nested blocks
simplelogica_nocms-admin-pages
train
a4d575f81ee37d61bfb7a762af7c4dc44cd78d2d
diff --git a/library/src/net/simonvt/widget/BuildLayerFrameLayout.java b/library/src/net/simonvt/widget/BuildLayerFrameLayout.java index <HASH>..<HASH> 100644 --- a/library/src/net/simonvt/widget/BuildLayerFrameLayout.java +++ b/library/src/net/simonvt/widget/BuildLayerFrameLayout.java @@ -22,17 +22,23 @@ public class BuildLayerFrameLayout extends FrameLayout { public BuildLayerFrameLayout(Context context) { super(context); - setLayerType(LAYER_TYPE_HARDWARE, null); + if (MenuDrawer.USE_TRANSLATIONS) { + setLayerType(LAYER_TYPE_HARDWARE, null); + } } public BuildLayerFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); - setLayerType(LAYER_TYPE_HARDWARE, null); + if (MenuDrawer.USE_TRANSLATIONS) { + setLayerType(LAYER_TYPE_HARDWARE, null); + } } public BuildLayerFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - setLayerType(LAYER_TYPE_HARDWARE, null); + if (MenuDrawer.USE_TRANSLATIONS) { + setLayerType(LAYER_TYPE_HARDWARE, null); + } } void setHardwareLayersEnabled(boolean enabled) {
Check API level before enabling hardware layers.
SimonVT_android-menudrawer
train
01b255d20fabfeff0e6dd405d1da5cc0f3713c85
diff --git a/evernode/__init__.py b/evernode/__init__.py index <HASH>..<HASH> 100644 --- a/evernode/__init__.py +++ b/evernode/__init__.py @@ -1 +1 @@ -__version__ = "1.4.2" +__version__ = "1.5.0" diff --git a/evernode/models/base_user_model.py b/evernode/models/base_user_model.py index <HASH>..<HASH> 100644 --- a/evernode/models/base_user_model.py +++ b/evernode/models/base_user_model.py @@ -15,18 +15,12 @@ class BaseUserModel(BaseModel): __tablename__ = 'users' __table_args__ = {'extend_existing': True} + fullname = Column(String(255)) email = Column(String(255), unique=True) password = Column(String(1000)) - firstname = Column(String(255)) - lastname = Column(String(255)) json_exclude_list = ['password', 'updated_at', 'created_at', 'id'] @classmethod - def where_username(cls, username): - """ Get db model by username """ - return cls.query.filter_by(email=username).first() - - @classmethod def where_email(cls, email): """ Get db model by email """ return cls.query.filter_by(email=email).first()
<I> - remove of first and last name in favour of a unified field. <I> update to support all non english names
AtomHash_evernode
train
54c9e140167f15be2fd96cdf13bdd746817e4342
diff --git a/em73xx/sms.py b/em73xx/sms.py index <HASH>..<HASH> 100644 --- a/em73xx/sms.py +++ b/em73xx/sms.py @@ -3,6 +3,7 @@ from datetime import datetime from .utils import unquote + def parse_date_time(date, time): date_format = "%y/%m/%d %H:%M:%S" date_and_time = (date + " " + time)[:-3] @@ -48,7 +49,7 @@ class SMS(object): "sms_id": self.sms_id, "status": self.status, "sender": self.sender, - "date_received": self.date_received.isoformat()[:-10], + "date_received": self.date_received, "message": self.message, "read": self.read }
bad truncate, and no need to do it in the low-level code - formatting should be at presentation level
smcl_py-em73xx
train
f477b9266ac8aa1762b4543f16bd8c5ec0f8a494
diff --git a/lib/dpl/provider/heroku/anvil.rb b/lib/dpl/provider/heroku/anvil.rb index <HASH>..<HASH> 100644 --- a/lib/dpl/provider/heroku/anvil.rb +++ b/lib/dpl/provider/heroku/anvil.rb @@ -2,6 +2,8 @@ module DPL class Provider module Heroku class Anvil < Git + HEROKU_BUILDPACKS = ['ruby', 'nodejs', 'clojure', 'python', 'java', 'gradle', 'grails', 'scala', 'play'] + HEROKU_BUILDPACK_PREFIX = "https://github.com/heroku/heroku-buildpack-" requires 'anvil-cli', :load => 'anvil/engine' requires 'excon' # comes with heroku requires 'json' @@ -40,6 +42,9 @@ module DPL @slug_url ||= begin ::Anvil.headers["X-Heroku-User"] = user ::Anvil.headers["X-Heroku-App"] = option(:app) + if HEROKU_BUILDPACKS.include? options[:buildpack] + options[:buildpack] = HEROKU_BUILDPACK_PREFIX + options[:buildpack] + end ::Anvil::Engine.build ".", :buildpack => options[:buildpack] rescue ::Anvil::Builder::BuildError => e raise Error, "deploy failed, anvil build error: #{e.message}"
Automatically expand URL for recognized buildpacks
travis-ci_dpl
train
95dc1e42d5743e406a13dc08d22dd7c86e0a3014
diff --git a/backup/cc/cc2moodle.php b/backup/cc/cc2moodle.php index <HASH>..<HASH> 100644 --- a/backup/cc/cc2moodle.php +++ b/backup/cc/cc2moodle.php @@ -338,7 +338,7 @@ class cc2moodle { $replace_values = array($i, $i - 1, - $topic['title'], + entities::safexml($topic['title']), $node_node_course_sections_section_mods_mod); } else {
MDL-<I> backup: Escape section summary for XML This was causing the parsing of the XML to fail because things like & were not escaped.
moodle_moodle
train
0f116a1aee39e0ff041b45064919c7256ee57432
diff --git a/src/NaturalLanguage/NaturalLanguageClient.php b/src/NaturalLanguage/NaturalLanguageClient.php index <HASH>..<HASH> 100644 --- a/src/NaturalLanguage/NaturalLanguageClient.php +++ b/src/NaturalLanguage/NaturalLanguageClient.php @@ -128,7 +128,8 @@ class NaturalLanguageClient * `PLAIN_TEXT` or `HTML`. **Defaults to** `"PLAIN_TEXT"`. * @type string $language The language of the document. Both ISO * (e.g., en, es) and BCP-47 (e.g., en-US, es-ES) language codes - * are accepted. Defaults to `"en"` (English). + * are accepted. If no value is provided, the language will be + * detected by the service. * @type string $encodingType The text encoding type used by the API to * calculate offsets. Acceptable values are `"NONE"`, `"UTF8"`, * `"UTF16"` and `"UTF32"`. **Defaults to** `"UTF8"`.
correct doc string to represent the fact the service detects the language of the provided content (#<I>)
googleapis_google-cloud-php
train
e9f25b2097b9c1ed35b01170603b9ff7787ef320
diff --git a/account/middleware.py b/account/middleware.py index <HASH>..<HASH> 100644 --- a/account/middleware.py +++ b/account/middleware.py @@ -38,6 +38,6 @@ class TimezoneMiddleware(object): templates to the user's timezone. """ def process_request(self, request): - tz = request.user.account.timezone - if tz: - timezone.activate(tz) \ No newline at end of file + account = getattr(request.user, 'account', None) + if account: + timezone.activate(account.timezone)
Anonymous users don't have an account
pinax_django-user-accounts
train
d0c1dd69cad0b911a603680432eaa8143fbb531b
diff --git a/mbed/mbed.py b/mbed/mbed.py index <HASH>..<HASH> 100755 --- a/mbed/mbed.py +++ b/mbed/mbed.py @@ -47,6 +47,7 @@ import time import zipfile import argparse from random import randint +from contextlib import contextmanager # Application version @@ -1228,9 +1229,8 @@ class Repo(object): os.makedirs(os.path.split(path)[0]) info("Carbon copy from \"%s\" to \"%s\"" % (cache, path)) - self.cache_lock(url) - shutil.copytree(cache, path) - self.cache_unlock(url) + with self.cache_lock_held(url): + shutil.copytree(cache, path) with cd(path): scm.seturl(formaturl(url, protocol)) @@ -1260,9 +1260,8 @@ class Repo(object): self.url = url self.path = os.path.abspath(path) self.ignores() - self.cache_lock(url) - self.set_cache(url) - self.cache_unlock(url) + with self.cache_lock_held(url): + self.set_cache(url) return True if offline: @@ -1431,6 +1430,14 @@ class Repo(object): pass return True + @contextmanager + def cache_lock_held(self, url): + self.cache_lock(url) + try: + yield + finally: + self.cache_unlock(url) + def pid_exists(self, pid): try: os.kill(int(pid), 0)
Use a context manager for locking the cache Should help reduce the amount of programmer errors
ARMmbed_mbed-cli
train
924a51bdba34ec66ec9629594a5e5507aaae7dae
diff --git a/stellar_base/utils.py b/stellar_base/utils.py index <HASH>..<HASH> 100644 --- a/stellar_base/utils.py +++ b/stellar_base/utils.py @@ -157,7 +157,8 @@ def encode_check(version_byte_name, data): def calculate_checksum(payload): # This code calculates CRC16-XModem checksum of payload checksum = crc16.crc16xmodem(payload) - checksum = struct.pack('H', checksum) + # Ensure that the checksum is in LSB order. + checksum = struct.pack('<H', checksum) return checksum
Ensure that checksum is always in LSB order.
StellarCN_py-stellar-base
train
fd18eeb62c4c5ebe88cc647c90a3a1b3098c0ce6
diff --git a/system/src/Grav/Common/Twig/TwigExtension.php b/system/src/Grav/Common/Twig/TwigExtension.php index <HASH>..<HASH> 100644 --- a/system/src/Grav/Common/Twig/TwigExtension.php +++ b/system/src/Grav/Common/Twig/TwigExtension.php @@ -837,6 +837,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn $loader = new \Twig_Loader_Filesystem('.'); $env = new \Twig_Environment($loader); + $env->addExtension($this); $template = $env->createTemplate($twig);
Add grav twig extensions to its own `evaluate` and `evaluate_twig` filters (#<I>) I wanted to use `evaluate_twig()` with a template the uses `theme_var()` or also a simpler twig function `string`. I made them available with this simple call.
getgrav_grav
train
0b1c9b6f57f57fed47a415c1762da9f83ee58f5c
diff --git a/test/raw-repo.js b/test/raw-repo.js index <HASH>..<HASH> 100644 --- a/test/raw-repo.js +++ b/test/raw-repo.js @@ -12,7 +12,7 @@ var helper = { // This ensures the repo is actually a derivative of the Function [[Class]] test( toString.call( obj ), '[object Function]', label +' [[Class]] is of type function.' ); }, - // Test code and handle exception thrown + // Test code and handle exception thrown testException: function( test, fun, label ) { try { fun(); @@ -30,7 +30,7 @@ exports.constructor = function( test ){ // Test for function helper.testFunction( test.equals, git.Repo, 'Repo' ); - + // Ensure we get an instance of Repo test.ok( new git.Repo() instanceof git.Repo, 'Invocation returns an instance of Repo' ); @@ -38,34 +38,31 @@ exports.constructor = function( test ){ }; // Repo::Open -exports.open = function( test ) { +exports.open = function(test) { var testRepo = new git.Repo(); - test.expect( 6 ); + test.expect(6); // Test for function - helper.testFunction( test.equals, testRepo.open, 'Repo::Open' ); + helper.testFunction(test.equals, testRepo.open, 'Repo::Open'); // Test path argument existence helper.testException( test.ok, function() { testRepo.open(); }, 'Throw an exception if no path' ); - + // Test callback argument existence - helper.testException( test.ok, function() { - testRepo.open( "some/path" ); - }, 'Throw an exception if no callback' ); + helper.testException(test.ok, function() { + testRepo.open('some/path'); + }, 'Throw an exception if no callback'); // Test invalid repository - testRepo.open( '/etc/hosts', function( err ) { - test.equals( -7, err, 'Invalid repository error code' ); + testRepo.open('/etc/hosts', function(error) { + test.equals(git.Error.codes.GIT_ERROR, error.klass, 'Invalid repository error code'); // Test valid repository - testRepo.open( path.resolve( '../.git' ), function( err ) { - test.equals( 0, err, 'Valid repository error code' ); - -// testRepo.free(); - + testRepo.open(path.resolve('../.git'), function(error) { + test.equals(0, error, 'Valid repository error code'); test.done(); }); }); @@ -73,13 +70,13 @@ exports.open = function( test ) { // TODO: Figure out how write unit tests for free // Repo::Free -exports.free = function( test ) { +exports.free = function(test) { var testRepo = new git.Repo(); - test.expect( 2 ); + test.expect(2); // Test for function - helper.testFunction( test.equals, testRepo.free, 'Repo::Free' ); + helper.testFunction(test.equals, testRepo.free, 'Repo::Free'); test.done(); }; @@ -97,7 +94,7 @@ exports.init = function( test ) { helper.testException( test.ok, function() { testRepo.init(); }, 'Throw an exception if no path' ); - + // Test is_bare argument existence helper.testException( test.ok, function() { testRepo.init( "some/path" ); @@ -117,7 +114,7 @@ exports.init = function( test ) { testRepo.open( './test.git', function(err, path) { test.equals( 0, err, 'Valid repository created' ); - testRepo.free(); + testRepo.free(); // Cleanup, remove test repo directory rimraf( './test.git', function() {
Updated raw-repo test
nodegit_nodegit
train
0dca77cf3bad965302fbf82926c592ca016190bb
diff --git a/claripy/ast/base.py b/claripy/ast/base.py index <HASH>..<HASH> 100644 --- a/claripy/ast/base.py +++ b/claripy/ast/base.py @@ -373,19 +373,9 @@ class Base(ana.Storable): a_args = tuple((a.to_claripy() if isinstance(a, BackendObject) else a) for a in args) f_op, f_args, f_kwargs = _finalize(claripy, op, a_args, kwargs) -# if h = Base._calc_hash(claripy, f_op, f_args, f_kwargs) - #if f_kwargs['length'] is None: - # __import__('ipdb').set_trace() - - - #print "got hash",h - #print "... claripy:", hash(claripy.name) - #print "... op (%r):" % op, hash(op) - #print "... args (%r):" % (args,), hash(args) - self = cls._hash_cache.get(h, None) if self is None: self = super(Base, cls).__new__(cls, claripy, f_op, f_args, **f_kwargs) @@ -413,7 +403,7 @@ class Base(ana.Storable): @returns a hash ''' to_hash = claripy.name + ' ' + op + ' ' + ','.join(str(hash(a)) for a in args) + ' ' + \ - str(k['symbolic']) + ' ' + str(hash(frozenset(k['variables']))) + ' ' + str(k['length']) + str(k['symbolic']) + ' ' + str(hash(frozenset(k['variables']))) + ' ' + str(k.get('length', None)) hd = hashlib.md5(to_hash).hexdigest() return int(hd[:16], 16) # 64 bits diff --git a/claripy/claripy.py b/claripy/claripy.py index <HASH>..<HASH> 100644 --- a/claripy/claripy.py +++ b/claripy/claripy.py @@ -145,6 +145,11 @@ class Claripy(object): else: raise ClaripyTypeError("can't convert {} to {}".format(type(args[2]), ty)) + if self.is_true(args[0]): + return args[1] + elif self.is_false(args[0]): + return args[2] + if issubclass(ty, Bits): return ty(self, 'If', tuple(args), length=args[1].length) else:
semi-hacky fix for eagerness with If
angr_claripy
train
dc8442a8a743beb6903bc643a305e4fc9f5c9a7d
diff --git a/core/src/main/java/lucee/runtime/osgi/OSGiUtil.java b/core/src/main/java/lucee/runtime/osgi/OSGiUtil.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/lucee/runtime/osgi/OSGiUtil.java +++ b/core/src/main/java/lucee/runtime/osgi/OSGiUtil.java @@ -601,23 +601,27 @@ public class OSGiUtil { } String bundleError = ""; + String parentBundle = String.join(",", parents); if (versionsFound.length() > 0){ - bundleError = "The OSGi Bundle with name [" + name + "] is not available in version [" + bundleError = "The OSGi Bundle with name [" + name + "] for [" + parentBundle + "] is not available in version [" + version + "] locally [" + localDir + "] or from the update provider [" + upLoc + "], the following versions are available locally [" + versionsFound + "]."; - } else if (version != null){ + } + else if (version != null){ bundleError = "The OSGi Bundle with name [" + name + "] in version [" + version - + "] is not available locally [" + localDir + "] or from the update provider" + upLoc + "."; + + "] for [" + parentBundle + "] is not available locally [" + localDir + "] or from the update provider" + upLoc + "."; throw new BundleException(bundleError); - } else { - bundleError = "The OSGi Bundle with name [" + name + "] is not available locally [" + localDir + } + else { + bundleError = "The OSGi Bundle with name [" + name + "] for [" + parentBundle + "] is not available locally [" + localDir + "] or from the update provider [" + upLoc + "]."; } boolean printExceptions = Caster.toBooleanValue(SystemUtil.getSystemPropOrEnvVar("lucee.cli.printExceptions", null), false); try { throw new BundleException(bundleError); - } catch (BundleException be){ + } + catch (BundleException be){ if (printExceptions) be.printStackTrace(); throw be; } @@ -631,7 +635,8 @@ public class OSGiUtil { + " it will need to be manually downloaded and placed in the {{lucee-server}}/context/bundles directory."; try { throw new RuntimeException(bundleError); - } catch (RuntimeException re){ + } + catch (RuntimeException re){ if (printExceptions) re.printStackTrace(); throw re; }
LDEV-<I> include bundle name, if available, in OSGI exceptions
lucee_Lucee
train
605debeec2168351595d7949ec94b328ab63c189
diff --git a/djstripe/contrib/rest_framework/serializers.py b/djstripe/contrib/rest_framework/serializers.py index <HASH>..<HASH> 100644 --- a/djstripe/contrib/rest_framework/serializers.py +++ b/djstripe/contrib/rest_framework/serializers.py @@ -28,7 +28,7 @@ class CreateSubscriptionSerializer(serializers.Serializer): stripe_token = serializers.CharField(max_length=200) plan = serializers.CharField(max_length=50) - charge_immediately = serializers.NullBooleanField(required=False) + charge_immediately = serializers.BooleanField(required=False, allow_null=True, default=None) tax_percent = serializers.DecimalField( required=False, max_digits=5, decimal_places=2 )
serializers: Remove deprecated NullBooleanField Replace with BooleanField.
dj-stripe_dj-stripe
train
7c7de65aa0b7e92122713a7171d6cfe3f0229878
diff --git a/sas_kernel/doc/source/conf.py b/sas_kernel/doc/source/conf.py index <HASH>..<HASH> 100644 --- a/sas_kernel/doc/source/conf.py +++ b/sas_kernel/doc/source/conf.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # -# SASPY documentation build configuration file, created by +# SAS kernel documentation build configuration file, created by # sphinx-quickstart on Fri Oct 28 10:08:55 2016. # # This file is execfile()d with the current directory set to its @@ -258,7 +258,7 @@ latex_elements = { # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'saspy.tex', 'SASpy Documentation', + (master_doc, 'sas_kernel.tex', 'SAS Kernel Documentation', 'SAS', 'manual'), ] @@ -288,7 +288,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'saspy', 'SASpy Documentation', + (master_doc, 'sas_kernel', 'SAS Kernel Documentation', [author], 1) ] @@ -302,8 +302,8 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'saspy', 'SASpy Documentation', - author, 'SASpy', 'One line description of project.', + (master_doc, 'sas_kernel', 'SAS Kernel Documentation', + author, 'sas_kernel', 'Provides a SAS kernel for use with Jupyter Notebook.', 'Miscellaneous'), ] @@ -321,4 +321,4 @@ texinfo_documents = [ # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'https://docs.python.org/': None} \ No newline at end of file +intersphinx_mapping = {'https://docs.python.org/': None}
project name in conf.py
sassoftware_sas_kernel
train
7296feb6c56ae579c93fb0a7187997fe581fc07f
diff --git a/src/NewTwitchApi/Resources/StreamsApi.php b/src/NewTwitchApi/Resources/StreamsApi.php index <HASH>..<HASH> 100644 --- a/src/NewTwitchApi/Resources/StreamsApi.php +++ b/src/NewTwitchApi/Resources/StreamsApi.php @@ -153,4 +153,17 @@ class StreamsApi extends AbstractResource return $this->callApi('channels', $bearer, $queryParamsMap); } + + /** + * @throws GuzzleException + * @link https://dev.twitch.tv/docs/api/reference#get-stream-tags + */ + public function getStreamTags(string $bearer, string $broadcasterId): ResponseInterface + { + $queryParamsMap = []; + + $queryParamsMap[] = ['key' => 'broadcaster_id', 'value' => $broadcasterId]; + + return $this->callApi('streams/tags', $bearer, $queryParamsMap); + } }
Add Get Stream Tags endpoint support (#<I>)
nicklaw5_twitch-api-php
train
a7ca9d659c1825a867b1284489c7746b93ceaea1
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -49,7 +49,7 @@ setup( author='Simon Jagoe', author_email='[email protected]', classifiers=[ - 'Development Status :: 1 - Planning', + 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS',
Change Development Status in setup.py
scalative_haas
train
497a6f1df9c63afc9a065a005c733b8b428babad
diff --git a/superset/db_engine_specs.py b/superset/db_engine_specs.py index <HASH>..<HASH> 100644 --- a/superset/db_engine_specs.py +++ b/superset/db_engine_specs.py @@ -687,6 +687,16 @@ class HiveEngineSpec(PrestoEngineSpec): db, datasource_type, force=force) @classmethod + def convert_dttm(cls, target_type, dttm): + tt = target_type.upper() + if tt == 'DATE': + return "CAST('{}' AS DATE)".format(dttm.isoformat()[:10]) + elif tt == 'TIMESTAMP': + return "CAST('{}' AS TIMESTAMP)".format( + dttm.strftime('%Y-%m-%d %H:%M:%S')) + return "'{}'".format(dttm.strftime('%Y-%m-%d %H:%M:%S')) + + @classmethod def adjust_database_uri(cls, uri, selected_schema=None): if selected_schema: uri.database = selected_schema
[hive] fix date casting in explore view (#<I>)
apache_incubator-superset
train
63955613ff929e4b7c8b11985830d440d8e59004
diff --git a/syntax/filetests_test.go b/syntax/filetests_test.go index <HASH>..<HASH> 100644 --- a/syntax/filetests_test.go +++ b/syntax/filetests_test.go @@ -3418,7 +3418,7 @@ func clearPosRecurse(tb testing.TB, src string, v interface{}) { endOff, src[endOff], string(src)) } setPos(&x.Position) - if x.SemiPos > 0 { + if x.SemiPos.IsValid() { setPos(&x.SemiPos, ";") } if x.Cmd != nil { diff --git a/syntax/nodes.go b/syntax/nodes.go index <HASH>..<HASH> 100644 --- a/syntax/nodes.go +++ b/syntax/nodes.go @@ -27,6 +27,8 @@ type File struct { // file. type Pos uint32 +func (p Pos) IsValid() bool { return p > 0 } + const maxPos = Pos(^uint32(0)) // Position describes a position within a source file including the line @@ -37,6 +39,8 @@ type Position struct { Column int // column number, starting at 1 (in bytes) } +func (p Position) IsValid() bool { return p.Line > 0 } + func (f *File) Pos() Pos { if len(f.Stmts) == 0 { return 0 @@ -106,7 +110,7 @@ type Stmt struct { func (s *Stmt) Pos() Pos { return s.Position } func (s *Stmt) End() Pos { - if s.SemiPos > 0 { + if s.SemiPos.IsValid() { return s.SemiPos + 1 } end := s.Position diff --git a/syntax/printer.go b/syntax/printer.go index <HASH>..<HASH> 100644 --- a/syntax/printer.go +++ b/syntax/printer.go @@ -252,7 +252,7 @@ func (p *printer) commentsUpTo(pos Pos) { return } c := p.comments[0] - if pos > 0 && c.Hash >= pos { + if pos.IsValid() && c.Hash >= pos { return } p.comments = p.comments[1:] @@ -527,7 +527,7 @@ func (p *printer) stmt(s *Stmt) { } } p.wroteSemi = false - if s.SemiPos > 0 && s.SemiPos > p.nline { + if s.SemiPos.IsValid() && s.SemiPos > p.nline { p.incLevel() p.bslashNewl() p.indent() @@ -583,7 +583,7 @@ func (p *printer) command(cmd Command, redirs []*Redirect) (startRedirs int) { if len(x.ElseStmts) > 0 { p.semiRsrv("else", x.Else, true) p.nestedStmts(x.ElseStmts, 0) - } else if x.Else > 0 { + } else if x.Else.IsValid() { p.incLines(x.Else) } p.semiRsrv("fi", x.Fi, true)
syntax: add .IsValid() to Pos and Position
mvdan_sh
train
e3c98cd5292f985841e9f140195faf11ab090d9a
diff --git a/neo/Prompt/Commands/Withdraw.py b/neo/Prompt/Commands/Withdraw.py index <HASH>..<HASH> 100644 --- a/neo/Prompt/Commands/Withdraw.py +++ b/neo/Prompt/Commands/Withdraw.py @@ -94,13 +94,12 @@ def RedeemWithdraw(prompter, wallet, args): scripthash_to = wallet.ToScriptHash(to_address) scripthash_from = wallet.ToScriptHash(from_address) - contract = Blockchain.Default().GetContract(scripthash_from) + contract = Blockchain.Default().GetContract(scripthash_from.ToBytes()) - requested_vins = get_contract_holds_for_address(wallet,scripthash_from,to_address) - - print("contract.. %s " % contract) + requested_vins = get_contract_holds_for_address(wallet,scripthash_from,scripthash_to) print("requested vins %s " % requested_vins) + def construct_contract_withdrawal(prompter, wallet, arguments, fee=Fixed8.FromDecimal(.001), check_holds=False): @@ -175,21 +174,14 @@ def construct_contract_withdrawal(prompter, wallet, arguments, fee=Fixed8.FromDe def get_contract_holds_for_address(wallet, contract_hash, addr): - print("contract hash %s " % contract_hash) - contract = Blockchain.Default().GetContract( contract_hash.ToBytes()) - - print("contract: %s " % contract) - - invoke_args = [contract_hash.ToString(), parse_param('getHolds'), [addr]] + invoke_args = [contract_hash.ToString(), parse_param('getHold'), [addr.Data]] tx, fee, results, num_ops = TestInvokeContract(wallet, invoke_args, None, False) if tx is not None and len(results) > 0: - print("results!!! %s " % results) holds = results[0].GetByteArray() holdlen = len(holds) numholds = int( holdlen/33) - print("holds, holdlen, numholds %s %s " % (holds, numholds)) vins = [] for i in range(0, numholds): hstart = i*33 @@ -198,12 +190,9 @@ def get_contract_holds_for_address(wallet, contract_hash, addr): vin_index = item[0] vin_tx_id = UInt256(data=item[1:]) - print("VIN INDEX, VIN TX ID: %s %s" % (vin_index,vin_tx_id)) t_input = TransactionInput(prevHash=vin_tx_id,prevIndex=vin_index) - print("found tinput: %s " % json.dumps(t_input.ToJson(), indent=4)) - vins.append(t_input) return vins diff --git a/prompt.py b/prompt.py index <HASH>..<HASH> 100644 --- a/prompt.py +++ b/prompt.py @@ -103,11 +103,11 @@ class PromptInterface(object): 'nodes', 'state', 'config log {on/off}', - 'build {path/to/file.py} (test {params} {returntype} {needs_storage} {test_params})' + 'build {path/to/file.py} (test {params} {returntype} {needs_storage} {test_params})', 'import wif {wif}', 'import contract {path/to/file.avm} {params} {returntype} {needs_storage}', 'import contract_addr {contract_hash} {pubkey}', - 'import watch_addr {address}' + 'import watch_addr {address}', 'export wif {address}', 'open wallet {path}', 'create wallet {path}',
update help. update building of withdrawal request
CityOfZion_neo-python
train