hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
f02669f7005e324b0945991fe4a7383acccea331
|
diff --git a/lib/read_source/version.rb b/lib/read_source/version.rb
index <HASH>..<HASH> 100644
--- a/lib/read_source/version.rb
+++ b/lib/read_source/version.rb
@@ -1,3 +1,3 @@
module ReadSource
- VERSION = "0.2.3"
+ VERSION = "0.2.4"
end
diff --git a/lib/read_source/vim_source.rb b/lib/read_source/vim_source.rb
index <HASH>..<HASH> 100644
--- a/lib/read_source/vim_source.rb
+++ b/lib/read_source/vim_source.rb
@@ -3,10 +3,16 @@
module ReadSource
module VimSource
def vim servername=nil
- file, line_num = send :source_location
+ (file, line_num = send :source_location) || return
read_only = !!/#{ENV["GEM_HOME"]}/.match(file) ? "-M" : ""
remote = "#{('--servername ' + servername.to_s) if servername} --remote-silent"
- exec("vim #{remote} %s +%s %s" % [read_only, line_num, file]) if file
+ serverlist = `vim --serverlist`.split("\n")
+ if serverlist.include?(servername.to_s) || serverlist.include?("VIM")
+ `#{"vim #{remote} %s +%s %s" % [read_only, line_num, file]}`
+ :success
+ else
+ exec("vim #{remote} %s +%s %s" % [read_only, line_num, file])
+ end
end
end
end
|
Add server support for VIM & keep Ruby running
|
danielpclark_read_source
|
train
|
71f416f788f5d117bc511a51dc446d60ad4ebf23
|
diff --git a/controller/DeliveryServer.php b/controller/DeliveryServer.php
index <HASH>..<HASH> 100755
--- a/controller/DeliveryServer.php
+++ b/controller/DeliveryServer.php
@@ -50,7 +50,6 @@ use oat\taoDelivery\models\classes\ReturnUrlService;
use oat\taoDelivery\model\authorization\UnAuthorizedException;
use oat\tao\helpers\Template;
use oat\taoDelivery\model\execution\StateServiceInterface;
-use oat\taoDeliveryRdf\model\DeliveryAssemblyService;
use tao_helpers_I18n;
/**
@@ -62,6 +61,8 @@ use tao_helpers_I18n;
*/
class DeliveryServer extends \tao_actions_CommonModule
{
+ private const PROPERTY_INTERFACE_LANGUAGE = 'http://www.tao.lu/Ontologies/TAODelivery.rdf#InterfaceLanguage';
+
/**
* constructor: initialize the service and the default data
* @security("hide")
@@ -182,7 +183,6 @@ class DeliveryServer extends \tao_actions_CommonModule
/** @var DeliveryExecution $deliveryExecution */
$deliveryExecution = $stateService->createDeliveryExecution($compiledDelivery->getUri(), $user, $compiledDelivery->getLabel());
-
return $deliveryExecution;
}
@@ -432,7 +432,7 @@ class DeliveryServer extends \tao_actions_CommonModule
private function overrideInterfaceLanguage(core_kernel_classes_Resource $delivery): void
{
- $deliveryLanguage = $delivery->getProperty(DeliveryAssemblyService::PROPERTY_INTERFACE_LANGUAGE);
+ $deliveryLanguage = $delivery->getProperty(self::PROPERTY_INTERFACE_LANGUAGE);
if (!$deliveryLanguage->exists()) {
$this->resetOverwrittenLanguage();
|
chore: Remove dependency from "taoDeliveryRdf" extension in DeliveryServer.php
|
oat-sa_extension-tao-delivery
|
train
|
974d540dc2b37df5fe6459b107ae1a589aa12f61
|
diff --git a/lib/dalli/server.rb b/lib/dalli/server.rb
index <HASH>..<HASH> 100644
--- a/lib/dalli/server.rb
+++ b/lib/dalli/server.rb
@@ -207,7 +207,17 @@ module Dalli
def verify_state
failure!(RuntimeError.new('Already writing to socket')) if @inprogress
- failure!(RuntimeError.new('Cannot share client between multiple processes')) if @pid && @pid != Process.pid
+ if @pid && @pid != Process.pid
+ message = 'Fork detected, re-connecting child process...'
+ Dalli.logger.info { message }
+ reconnect! message
+ end
+ end
+
+ def reconnect!(message)
+ close
+ sleep(options[:socket_failure_delay]) if options[:socket_failure_delay]
+ raise Dalli::NetworkError, message
end
def failure!(exception)
@@ -218,9 +228,7 @@ module Dalli
if @fail_count >= options[:socket_max_failures]
down!
else
- close
- sleep(options[:socket_failure_delay]) if options[:socket_failure_delay]
- raise Dalli::NetworkError, "Socket operation failed, retrying..."
+ reconnect! 'Socket operation failed, retrying...'
end
end
|
Do not treat socket sharing as a failure, fixes #<I>
|
petergoldstein_dalli
|
train
|
7f0f76c93944d814924d24dddf0e3d26aecd9f71
|
diff --git a/codenerix_products/views.py b/codenerix_products/views.py
index <HASH>..<HASH> 100644
--- a/codenerix_products/views.py
+++ b/codenerix_products/views.py
@@ -660,7 +660,7 @@ class ProductDetails(GenProductUrl, GenDetail):
class ProductForeign(GenForeignKey):
model = Product
- label = '{name} - {model}'
+ label = '{code} - {<LANGUAGE_CODE>__name} - {<LANGUAGE_CODE>__slug}'
def get_foreign(self, queryset, search, filters):
# Filter with search string
|
Representation of products in GenForeignKey
|
codenerix_django-codenerix-products
|
train
|
48bca6d11bf42e911d71e03df93d3a435952bb0b
|
diff --git a/lib/webpagetest.js b/lib/webpagetest.js
index <HASH>..<HASH> 100644
--- a/lib/webpagetest.js
+++ b/lib/webpagetest.js
@@ -586,11 +586,6 @@ function runTestAndWait(what, options, callback) {
(!data || (data && data.data && data.statusCode !== 200)) &&
!(typeof err === "number" && data === undefined)
) {
- // console.log(
- // data && data.data && data.data.statusText
- // ? data.data.statusText
- // : "Testing in progress"
- // );
polling = setTimeout(
getTestResults.bind(this, testId, resultsOptions, poll.bind(this)),
options.pollResults
|
removed the commented statement for testing against travis-ci
|
marcelduran_webpagetest-api
|
train
|
dc36170a782ab145a4a6aaa7a3f4d4cc360b3137
|
diff --git a/src/Doctrine/Instantiator/Instantiator.php b/src/Doctrine/Instantiator/Instantiator.php
index <HASH>..<HASH> 100644
--- a/src/Doctrine/Instantiator/Instantiator.php
+++ b/src/Doctrine/Instantiator/Instantiator.php
@@ -107,12 +107,10 @@ final class Instantiator implements InstantiatorInterface
}
/**
- * @param string $className
- *
* @throws InvalidArgumentException
* @throws ReflectionException
*/
- private function getReflectionClass($className) : ReflectionClass
+ private function getReflectionClass(string $className) : ReflectionClass
{
if (! class_exists($className)) {
throw InvalidArgumentException::fromNonExistingClass($className);
|
Typehint getReflectionClass
There is no BC since it is a private method and from the onlye caller method (buildFactory) it is asserted that className is `string` already
|
doctrine_instantiator
|
train
|
b2781f753793b38f42946cfeaa3a65673f5a6a41
|
diff --git a/src/Pool.php b/src/Pool.php
index <HASH>..<HASH> 100644
--- a/src/Pool.php
+++ b/src/Pool.php
@@ -63,7 +63,10 @@ class Pool implements FutureInterface
* @param ClientInterface $client Client used to send the requests.
* @param array|\Iterator $requests Requests to send in parallel
* @param array $options Associative array of options
- * - pool_size: (int) Maximum number of requests to send concurrently
+ * - pool_size: (callable|int) Maximum number of requests to send
+ * concurrently, or a callback that receives
+ * the current queue size and returns the
+ * number of new requests to send
* - before: (callable|array) Receives a BeforeEvent
* - complete: (callable|array) Receives a CompleteEvent
* - error: (callable|array) Receives a ErrorEvent
@@ -146,6 +149,26 @@ class Pool implements FutureInterface
(new self($client, $requests, $options))->wait();
}
+ private function getPoolSize()
+ {
+ return is_callable($this->poolSize)
+ ? call_user_func($this->poolSize, count($this->waitQueue))
+ : $this->poolSize;
+ }
+
+ /**
+ * Add as many requests as possible up to the current pool limit.
+ */
+ private function addNextRequests()
+ {
+ $limit = max($this->getPoolSize() - count($this->waitQueue), 0);
+ while ($limit--) {
+ if (!$this->addNextRequest()) {
+ break;
+ }
+ }
+ }
+
public function wait()
{
if ($this->isRealized) {
@@ -153,11 +176,7 @@ class Pool implements FutureInterface
}
// Seed the pool with N number of requests.
- for ($i = 0; $i < $this->poolSize; $i++) {
- if (!$this->addNextRequest()) {
- break;
- }
- }
+ $this->addNextRequests();
// Stop if the pool was cancelled while transferring requests.
if ($this->isRealized) {
@@ -284,7 +303,7 @@ class Pool implements FutureInterface
// Use this function for both resolution and rejection.
$thenFn = function ($value) use ($request, $hash) {
$this->finishResponse($request, $value, $hash);
- $this->addNextRequest();
+ $this->addNextRequests();
};
$promise->then($thenFn, $thenFn);
diff --git a/tests/PoolTest.php b/tests/PoolTest.php
index <HASH>..<HASH> 100644
--- a/tests/PoolTest.php
+++ b/tests/PoolTest.php
@@ -154,6 +154,64 @@ class PoolTest extends \PHPUnit_Framework_TestCase
$this->assertSame($responses[3], $result[2]->getResponse());
}
+ public function testBatchesRequestsWithDynamicPoolSize()
+ {
+ $client = new Client(['handler' => function () {
+ throw new \RuntimeException('No network access');
+ }]);
+
+ $responses = [
+ new Response(301, ['Location' => 'http://foo.com/bar']),
+ new Response(200),
+ new Response(200),
+ new Response(404)
+ ];
+
+ $client->getEmitter()->attach(new Mock($responses));
+ $requests = [
+ $client->createRequest('GET', 'http://foo.com/baz'),
+ $client->createRequest('HEAD', 'http://httpbin.org/get'),
+ $client->createRequest('PUT', 'http://httpbin.org/put'),
+ ];
+
+ $a = $b = $c = $d = 0;
+ $result = Pool::batch($client, $requests, [
+ 'before' => function (BeforeEvent $e) use (&$a) { $a++; },
+ 'complete' => function (CompleteEvent $e) use (&$b) { $b++; },
+ 'error' => function (ErrorEvent $e) use (&$c) { $c++; },
+ 'end' => function (EndEvent $e) use (&$d) { $d++; },
+ 'pool_size' => function ($queueSize) {
+ static $options = [1, 2, 1];
+ static $queued = 0;
+
+ $this->assertEquals(
+ $queued,
+ $queueSize,
+ 'The number of queued requests should be equal to the sum of pool sizes so far.'
+ );
+
+ $next = array_shift($options);
+ $queued += $next;
+
+ return $next;
+ }
+ ]);
+
+ $this->assertEquals(4, $a);
+ $this->assertEquals(2, $b);
+ $this->assertEquals(1, $c);
+ $this->assertEquals(3, $d);
+ $this->assertCount(3, $result);
+ $this->assertInstanceOf('GuzzleHttp\BatchResults', $result);
+
+ // The first result is actually the second (redirect) response.
+ $this->assertSame($responses[1], $result[0]);
+ // The second result is a 1:1 request:response map
+ $this->assertSame($responses[2], $result[1]);
+ // The third entry is the 404 RequestException
+ $this->assertSame($responses[3], $result[2]->getResponse());
+ }
+
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Each event listener must be a callable or
|
Allow dynamic pool sizing.
Allows the number of requests allowed in a pool to vary over time by
retrieving the current pool size from a callback instead of a single
constant number.
This allows us to amend the number of requests ongoing according to our
needs, e.g. by responding to rate limiting information provided by an
upstream API.
Changes are
* Allow a callback to be passed in to specify the pool size instead of a
constant pool size.
* As each request returns, add enough new requests to the queue to fill
up to the current pool size limit.
|
guzzle_guzzle
|
train
|
2fee6a9bc1b042efb98022531819bdd82e42b922
|
diff --git a/src/Delta/Html/Delta.php b/src/Delta/Html/Delta.php
index <HASH>..<HASH> 100644
--- a/src/Delta/Html/Delta.php
+++ b/src/Delta/Html/Delta.php
@@ -47,6 +47,11 @@ abstract class Delta
protected $close = false;
/**
+ * @var boolean $new_line
+ */
+ protected $new_line = false;
+
+ /**
* Should we close the block
*
* @return boolean
@@ -108,6 +113,16 @@ abstract class Delta
}
/**
+ * Return whether or not a new line needs to be added
+ *
+ * @return boolean
+ */
+ public function newLine(): bool
+ {
+ return $this->new_line;
+ }
+
+ /**
* If the delta is a child, what type of tag is the parent
*
* @return string|null
@@ -161,4 +176,16 @@ abstract class Delta
return $this;
}
+
+ /**
+ * Set the new line state
+ *
+ * @return Delta
+ */
+ public function setNewLine(): Delta
+ {
+ $this->new_line = true;
+
+ return $this;
+ }
}
|
New line
* Added new line to base `Delta` class
|
deanblackborough_php-quill-renderer
|
train
|
d8ea9d6f88999f2270c6f4c4229d5ae3b2ecc48f
|
diff --git a/cluster.go b/cluster.go
index <HASH>..<HASH> 100644
--- a/cluster.go
+++ b/cluster.go
@@ -149,6 +149,8 @@ type ClusterConfig struct {
DisableNodeStatusEvents bool
// disable registering for topology events (node added/removed/moved)
DisableTopologyEvents bool
+ // disable registering for schema events (keyspace/table/function removed/created/updated)
+ DisableSchemaEvents bool
}
// internal config for testing
diff --git a/control.go b/control.go
index <HASH>..<HASH> 100644
--- a/control.go
+++ b/control.go
@@ -131,6 +131,9 @@ func (c *controlConn) registerEvents(conn *Conn) error {
if !c.session.cfg.Events.DisableNodeStatusEvents {
events = append(events, "STATUS_CHANGE")
}
+ if !c.session.cfg.Events.DisableSchemaEvents {
+ events = append(events, "SCHEMA_CHANGE")
+ }
if len(events) == 0 {
return nil
diff --git a/events.go b/events.go
index <HASH>..<HASH> 100644
--- a/events.go
+++ b/events.go
@@ -80,6 +80,37 @@ func (e *eventDeouncer) debounce(frame frame) {
e.mu.Unlock()
}
+func (s *Session) handleEvent(framer *framer) {
+ // TODO(zariel): need to debounce events frames, and possible also events
+ defer framerPool.Put(framer)
+
+ frame, err := framer.parseFrame()
+ if err != nil {
+ // TODO: logger
+ log.Printf("gocql: unable to parse event frame: %v\n", err)
+ return
+ }
+
+ if debug {
+ log.Printf("gocql: handling frame: %v\n", frame)
+ }
+
+ // TODO: handle medatadata events
+ switch f := frame.(type) {
+ case *schemaChangeKeyspace, *schemaChangeFunction, *schemaChangeTable:
+ s.schemaEvents.debounce(frame)
+ case *topologyChangeEventFrame, *statusChangeEventFrame:
+ s.nodeEvents.debounce(frame)
+ default:
+ log.Printf("gocql: invalid event frame (%T): %v\n", f, f)
+ }
+}
+
+func (s *Session) handleSchemaEvent(frames []frame) {
+ // for now we dont care about them, just reset the prepared statements
+ s.stmtsLRU.clear()
+}
+
func (s *Session) handleNodeEvent(frames []frame) {
type nodeEvent struct {
change string
@@ -131,34 +162,6 @@ func (s *Session) handleNodeEvent(frames []frame) {
}
}
-func (s *Session) handleEvent(framer *framer) {
- // TODO(zariel): need to debounce events frames, and possible also events
- defer framerPool.Put(framer)
-
- frame, err := framer.parseFrame()
- if err != nil {
- // TODO: logger
- log.Printf("gocql: unable to parse event frame: %v\n", err)
- return
- }
-
- if debug {
- log.Printf("gocql: handling frame: %v\n", frame)
- }
-
- // TODO: handle medatadata events
- switch f := frame.(type) {
- case *schemaChangeKeyspace:
- case *schemaChangeFunction:
- case *schemaChangeTable:
- case *topologyChangeEventFrame, *statusChangeEventFrame:
- s.nodeEvents.debounce(frame)
- default:
- log.Printf("gocql: invalid event frame (%T): %v\n", f, f)
- }
-
-}
-
func (s *Session) handleNewNode(host net.IP, port int, waitForBinary bool) {
// TODO(zariel): need to be able to filter discovered nodes
diff --git a/session.go b/session.go
index <HASH>..<HASH> 100644
--- a/session.go
+++ b/session.go
@@ -48,7 +48,8 @@ type Session struct {
control *controlConn
// event handlers
- nodeEvents *eventDeouncer
+ nodeEvents *eventDeouncer
+ schemaEvents *eventDeouncer
// ring metadata
hosts []HostInfo
@@ -102,6 +103,7 @@ func NewSession(cfg ClusterConfig) (*Session, error) {
s.connCfg = connCfg
s.nodeEvents = newEventDeouncer("NodeEvents", s.handleNodeEvent)
+ s.schemaEvents = newEventDeouncer("SchemaEvents", s.handleSchemaEvent)
s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
|
register for schema events
Register for schema change events and clear the prepared statement cache
so we don't use stale schema information for queries.
|
gocql_gocql
|
train
|
9135ad8b190ca83f008cafe52ecb49cc0622e006
|
diff --git a/src/cluster/cluster_server.go b/src/cluster/cluster_server.go
index <HASH>..<HASH> 100644
--- a/src/cluster/cluster_server.go
+++ b/src/cluster/cluster_server.go
@@ -71,6 +71,5 @@ func (self *ClusterServer) Connect() {
}
func (self *ClusterServer) MakeRequest(request *protocol.Request, responseStream chan *protocol.Response) error {
- self.Connect()
return self.connection.MakeRequest(request, responseStream)
}
|
Make request shouldn't call connect. This happens when the server is added to the cluster config.
|
influxdata_influxdb
|
train
|
32390d2232290ed6622b86a7c4bbbeabb0ba58d5
|
diff --git a/plugins/Admin/src/Controller/OrderDetailsController.php b/plugins/Admin/src/Controller/OrderDetailsController.php
index <HASH>..<HASH> 100644
--- a/plugins/Admin/src/Controller/OrderDetailsController.php
+++ b/plugins/Admin/src/Controller/OrderDetailsController.php
@@ -394,9 +394,6 @@ class OrderDetailsController extends AdminAppController
$bulkOrdersAllowed = $this->Manufacturer->getOptionBulkOrdersAllowed($orderDetail->product->manufacturer->bulk_orders_allowed);
$orderDetail->bulkOrdersAllowed = $bulkOrdersAllowed;
$orderDetail->row_class = [];
- if ($bulkOrdersAllowed) {
- $orderDetail->row_class[] = 'deactivated';
- }
$orderDetail->quantityInUnitsNotYetChanged = false;
if (!empty($orderDetail->order_detail_unit)) {
if (round($orderDetail->order_detail_unit->product_quantity_in_units, 3) == round($orderDetail->order_detail_unit->quantity_in_units * $orderDetail->product_amount, 3)) {
|
products of bulk manufacturers not shown as deactivated
|
foodcoopshop_foodcoopshop
|
train
|
9d00f71f72dd99eac4709e3c4b19cd10949b3adb
|
diff --git a/src/sqlite3History.py b/src/sqlite3History.py
index <HASH>..<HASH> 100644
--- a/src/sqlite3History.py
+++ b/src/sqlite3History.py
@@ -58,14 +58,12 @@ class Sqlite3History(Module):
if not name in self.pc2id_lut:
self.c.execute("INSERT INTO pcs (name) VALUES ( ? )", (name,))
self.pc2id_lut[name] = self.c.lastrowid
- self.conn.commit()
return self.pc2id_lut[name]
def _id_for_source(self, name):
""" Given the name of the source, return the database identifier. """
if not name in self.source2id_lut:
self.c.execute("INSERT INTO sources (name) VALUES ( ? )", (name,))
self.source2id_lut[name] = self.c.lastrowid
- self.conn.commit()
return self.source2id_lut[name]
def get_occupation(self):
@@ -106,7 +104,7 @@ class Sqlite3History(Module):
self.recordCond.acquire()
while self.running or self.recordQueue:
# Check for new entries. If none: wait.
- if not self.recordQueue:
+ if self.running and not self.recordQueue:
self.recordCond.wait()
continue
entries = list(reversed(self.recordQueue))
|
sqlite3History: commit less often and fix a bug in the worker thread
|
bwesterb_tkbd
|
train
|
506ccb890619df7e7c13fe837c6d8583a8a402a8
|
diff --git a/pkg/datapath/linux/node.go b/pkg/datapath/linux/node.go
index <HASH>..<HASH> 100644
--- a/pkg/datapath/linux/node.go
+++ b/pkg/datapath/linux/node.go
@@ -479,16 +479,11 @@ func (n *linuxNodeHandler) enableIPsec(newNode *node.Node) {
}
} else {
if ciliumInternalIPv6 := newNode.GetCiliumInternalIP(true); ciliumInternalIPv6 != nil {
- ipsecLocal := &net.IPNet{IP: n.nodeAddressing.IPv6().Router(), Mask: n.nodeAddressing.IPv6().AllocationCIDR().Mask}
+ ipsecLocalWildcard := &net.IPNet{IP: net.ParseIP(wildcardIPv6), Mask: net.CIDRMask(0, 0)}
ipsecRemote := &net.IPNet{IP: ciliumInternalIPv6, Mask: newNode.IPv6AllocCIDR.Mask}
- ipsecHost := &net.IPNet{IP: n.nodeAddressing.IPv6().PrimaryExternal(), Mask: n.nodeAddressing.IPv6().AllocationCIDR().Mask}
n.replaceNodeIPSecOutRoute(new6Net)
- err := ipsec.UpsertIPSecEndpoint(ipsecLocal, ipsecRemote, linux_defaults.IPSecEndpointSPI, ipsec.IPSecDirOut)
- upsertIPsecLog(err, "IPv6", ipsecLocal, ipsecRemote)
- if !ipsecHost.IP.Equal(ipsecLocal.IP) {
- err := ipsec.UpsertIPSecEndpoint(ipsecHost, ipsecRemote, linux_defaults.IPSecNodeSPI, ipsec.IPSecDirOut)
- upsertIPsecLog(err, "host IPv6", ipsecHost, ipsecRemote)
- }
+ err := ipsec.UpsertIPSecEndpoint(ipsecLocalWildcard, ipsecRemote, linux_defaults.IPSecEndpointSPI, ipsec.IPSecDirOut)
+ upsertIPsecLog(err, "IPv6", ipsecLocalWildcard, ipsecRemote)
}
}
}
|
cilium: ipsec, wildcard out rules and remove localhost rules
Currently, OUT xfrm rules use full (src,dst,spi) tuple. The original
thinking on this was that we wanted to ensure matches only on relavent
IP addresses. However now both state and policy are further restricted
by mark values we can drop the src piece without worrying about having
unintended matches.
|
cilium_cilium
|
train
|
71682fc95c00b94e9c7394b232a59b628f90e128
|
diff --git a/python/dllib/src/test/bigdl/nnframes/test_nn_classifier.py b/python/dllib/src/test/bigdl/nnframes/test_nn_classifier.py
index <HASH>..<HASH> 100644
--- a/python/dllib/src/test/bigdl/nnframes/test_nn_classifier.py
+++ b/python/dllib/src/test/bigdl/nnframes/test_nn_classifier.py
@@ -29,6 +29,8 @@ from pyspark.sql.types import *
from zoo.common.nncontext import *
from zoo.pipeline.nnframes import *
from zoo.pipeline.api.keras.optimizers import Adam as KAdam
+from zoo.pipeline.api.keras import layers as ZLayer
+from zoo.pipeline.api.keras.models import Model as ZModel
from zoo.feature.common import *
from zoo.feature.image import *
from zoo.util.tf import *
@@ -311,6 +313,66 @@ class TestNNClassifer():
if exc.errno != errno.ENOENT: # ENOENT - no such file or directory
raise # re-raise exception
+ def test_NNEstimator_multi_input(self):
+ zx1 = ZLayer.Input(shape=(1, ))
+ zx2 = ZLayer.Input(shape=(1, ))
+ zz = ZLayer.merge([zx1, zx2], mode="concat")
+ zy = ZLayer.Dense(2)(zz)
+ zmodel = ZModel([zx1, zx2], zy)
+
+ criterion = MSECriterion()
+ df = self.get_estimator_df()
+ estimator = NNEstimator(zmodel, criterion, [[1], [1]]).setMaxEpoch(5) \
+ .setBatchSize(4)
+ nnmodel = estimator.fit(df)
+ nnmodel.transform(df).collect()
+
+ def test_NNEstimator_works_with_VectorAssembler_multi_input(self):
+ if self.sc.version.startswith("2"):
+ from pyspark.ml.linalg import Vectors
+ from pyspark.ml.feature import VectorAssembler
+ from pyspark.sql import SparkSession
+
+ spark = SparkSession \
+ .builder \
+ .getOrCreate()
+
+ df = spark.createDataFrame(
+ [(1, 35, 109.0, Vectors.dense([2.0, 5.0, 0.5, 0.5]), 1.0),
+ (2, 58, 2998.0, Vectors.dense([4.0, 10.0, 0.5, 0.5]), 2.0),
+ (3, 18, 123.0, Vectors.dense([3.0, 15.0, 0.5, 0.5]), 1.0)],
+ ["user", "age", "income", "history", "label"])
+
+ assembler = VectorAssembler(
+ inputCols=["user", "age", "income", "history"],
+ outputCol="features")
+
+ df = assembler.transform(df)
+
+ x1 = ZLayer.Input(shape=(1,))
+ x2 = ZLayer.Input(shape=(2,))
+ x3 = ZLayer.Input(shape=(2, 2,))
+
+ user_embedding = ZLayer.Embedding(5, 10)(x1)
+ flatten = ZLayer.Flatten()(user_embedding)
+ dense1 = ZLayer.Dense(2)(x2)
+ gru = ZLayer.LSTM(4, input_shape=(2, 2))(x3)
+
+ merged = ZLayer.merge([flatten, dense1, gru], mode="concat")
+ zy = ZLayer.Dense(2)(merged)
+
+ zmodel = ZModel([x1, x2, x3], zy)
+ criterion = ClassNLLCriterion()
+ classifier = NNClassifier(zmodel, criterion, [[1], [2], [2, 2]]) \
+ .setOptimMethod(Adam()) \
+ .setLearningRate(0.1) \
+ .setBatchSize(2) \
+ .setMaxEpoch(10)
+
+ nnClassifierModel = classifier.fit(df)
+ print(nnClassifierModel.getBatchSize())
+ res = nnClassifierModel.transform(df).collect()
+
def test_NNModel_transform_with_nonDefault_featureCol(self):
model = Sequential().add(Linear(2, 2))
nnModel = NNModel(model, SeqToTensor([2]))\
|
support multi input models for nnframes (#<I>)
* support multi input for nnframes
* update ut
* add doc and unit test
* doc update
* scala style
|
intel-analytics_BigDL
|
train
|
f9f0d0a393721fb2dc457182e5e6b86ab1f974ed
|
diff --git a/jsonfield/fields.py b/jsonfield/fields.py
index <HASH>..<HASH> 100644
--- a/jsonfield/fields.py
+++ b/jsonfield/fields.py
@@ -12,27 +12,40 @@ try:
except ImportError:
from django.utils import simplejson as json
-from django.forms.fields import Field
+from django.forms import fields
from django.forms.util import ValidationError
from .subclassing import SubfieldBase
-class JSONFormField(Field):
- def clean(self, value):
-
- if not value and not self.required:
- return None
-
- value = super(JSONFormField, self).clean(value)
+class JSONFormFieldBase(object):
+ def to_python(self, value):
if isinstance(value, six.string_types):
try:
- json.loads(value)
+ return json.loads(value)
except ValueError:
raise ValidationError(_("Enter valid JSON"))
return value
+ def clean(self, value):
+
+ if not value and not self.required:
+ return None
+
+ # Trap cleaning errors & bubble them up as JSON errors
+ try:
+ return super(JSONFormFieldBase, self).clean(value)
+ except TypeError:
+ raise ValidationError(_("Enter valid JSON"))
+
+
+class JSONFormField(JSONFormFieldBase, fields.Field):
+ pass
+
+class JSONCharFormField(JSONFormFieldBase, fields.CharField):
+ pass
+
class JSONFieldBase(six.with_metaclass(SubfieldBase, base=models.Field)):
@@ -88,7 +101,7 @@ class JSONFieldBase(six.with_metaclass(SubfieldBase, base=models.Field)):
def formfield(self, **kwargs):
if "form_class" not in kwargs:
- kwargs["form_class"] = JSONFormField
+ kwargs["form_class"] = self.form_class
field = super(JSONFieldBase, self).formfield(**kwargs)
@@ -124,6 +137,7 @@ class JSONFieldBase(six.with_metaclass(SubfieldBase, base=models.Field)):
class JSONField(JSONFieldBase, models.TextField):
"""JSONField is a generic textfield that serializes/unserializes JSON objects"""
+ form_class = JSONFormField
def dumps_for_display(self, value):
kwargs = { "indent": 2 }
kwargs.update(self.dump_kwargs)
@@ -134,6 +148,7 @@ class JSONCharField(JSONFieldBase, models.CharField):
"""JSONCharField is a generic textfield that serializes/unserializes JSON objects,
stored in the database like a CharField, which enables it to be used
e.g. in unique keys"""
+ form_class = JSONCharFormField
try:
|
Fix bug where JSONCharField wasn't showing in admin
|
dmkoch_django-jsonfield
|
train
|
15f256c19329bc3de95db5702c79cff432a5e5c1
|
diff --git a/custodian/vasp/handlers.py b/custodian/vasp/handlers.py
index <HASH>..<HASH> 100644
--- a/custodian/vasp/handlers.py
+++ b/custodian/vasp/handlers.py
@@ -510,7 +510,7 @@ class WalltimeHandler(ErrorHandler):
# itself naturally with the STOPCAR.
is_terminating = False
- def __init__(self, wall_time=None, buffer_time=300):
+ def __init__(self, wall_time=None, buffer_time=300, electronic_step_stop=False):
"""
Initializes the handler with a buffer time.
@@ -529,6 +529,11 @@ class WalltimeHandler(ErrorHandler):
complete. But if other operations are being performed after
the run has stopped, the buffer time may need to be increased
accordingly.
+ electronic_step_stop (bool): Whether to check for electronic steps
+ instead of ionic steps (e.g. for static runs on large systems or
+ static HSE runs, ...). Be carefull that results such as density
+ or wavefunctions might not be converged at the electronic level.
+ Should be used with LWAVE = .True. to be useful.
"""
if wall_time is not None:
self.wall_time = wall_time
@@ -538,18 +543,40 @@ class WalltimeHandler(ErrorHandler):
self.wall_time = None
self.buffer_time = buffer_time
self.start_time = datetime.datetime.now()
+ self.electronic_step_stop = electronic_step_stop
+ self.electronic_steps_timings = [0.0]
+ self.previous_check_time = self.start_time
+ self.previous_check_nscf_steps = 0
def check(self):
if self.wall_time:
run_time = datetime.datetime.now() - self.start_time
total_secs = run_time.seconds + run_time.days * 3600 * 24
- try:
- #Intelligently determine time per ionic step.
- o = Oszicar("OSZICAR")
- nsteps = len(o.ionic_steps)
- time_per_step = total_secs / nsteps
- except Exception as ex:
- time_per_step = 0
+ if not self.electronic_step_stop:
+ try:
+ #Intelligently determine time per ionic step.
+ o = Oszicar("OSZICAR")
+ nsteps = len(o.ionic_steps)
+ time_per_step = total_secs / nsteps
+ except Exception as ex:
+ time_per_step = 0
+ else:
+ try:
+ #Intelligently determine approximate time per electronic step.
+ o = Oszicar("OSZICAR")
+ if len(o.ionic_steps) == 0:
+ nsteps = 0
+ else:
+ nsteps = sum([len(ionic_step) for ionic_step in o.electronic_steps])
+ if nsteps > self.previous_check_nscf_steps:
+ steps_time = datetime.datetime.now() - self.previous_check_time
+ steps_secs = steps_time.seconds + steps_time.days * 3600 * 24
+ self.electronic_steps_timings.append(steps_secs / (nsteps - self.previous_check_nscf_steps))
+ self.previous_check_nscf_steps = nsteps
+ self.previous_check_time = datetime.datetime.now()
+ time_per_step = max(self.electronic_steps_timings)
+ except Exception as ex:
+ time_per_step = 0
# If the remaining time is less than average time for 3 ionic
# steps or buffer_time.
|
Modified WalltimeErrorHandler so that it is able to stop for an electronic step (if asked for it). Default behavior is to stop at the next ionic step. Stopping at electronic steps can be useful in case of large systems or HSE computations (in which one scf step can last long)
|
materialsproject_custodian
|
train
|
4f64d2dc02df60ce6e7d2c9d82280dfc77b4cc20
|
diff --git a/servers/src/main/java/tachyon/worker/block/BlockLockManager.java b/servers/src/main/java/tachyon/worker/block/BlockLockManager.java
index <HASH>..<HASH> 100644
--- a/servers/src/main/java/tachyon/worker/block/BlockLockManager.java
+++ b/servers/src/main/java/tachyon/worker/block/BlockLockManager.java
@@ -17,15 +17,17 @@ package tachyon.worker;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Optional;
+
import tachyon.Constants;
+import tachyon.Pair;
import tachyon.worker.block.BlockLock;
/**
@@ -35,36 +37,69 @@ import tachyon.worker.block.BlockLock;
*/
public class BlockLockManager {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
+ /** The unique id of each lock **/
+ static final AtomicLong mCurrentLockId = new AtomicLong(0);
- /** A map from a block ID to its lock **/
+ /** A map from a block ID to its lock */
private final Map<Long, BlockLock> mBlockIdToLockMap = new HashMap<Long, BlockLock>();
+ /** A map from a user ID to all the locks hold by this user */
+ private final Map<Long, Set<Long>> mUserIdToLockIdsMap = new HashMap<Long, Set<Long>>();
+ /** A map from a lock ID to the user ID holding this lock */
+ private final Map<Long, Pair<Long, Lock>> mLockIdToUserIdAndLockMap =
+ new HashMap<Long, Pair<Long, Lock>>();
public BlockLockManager() {}
- /**
- * Get the lock for the given block id. If there is no such a lock yet, create one.
- *
- * @param blockId The id of the block
- * @return the lock for this block
- */
- public synchronized Optional<BlockLock> getBlockLock(long blockId) {
+ public synchronized Optional<Long> lockBlock(long userId, long blockId,
+ BlockLock.BlockLockType blockLockType) {
if (!mBlockIdToLockMap.containsKey(blockId)) {
LOG.error("Cannot get lock for block {}: not exists", blockId);
return Optional.absent();
}
- return Optional.of(mBlockIdToLockMap.get(blockId));
+ BlockLock blockLock = mBlockIdToLockMap.get(blockId);
+ Lock lock = null;
+ if (blockLockType == BlockLock.BlockLockType.READ) {
+ lock = blockLock.readLock();
+ } else if (blockLockType == BlockLock.BlockLockType.WRITE) {
+ lock = blockLock.writeLock();
+ }
+ lock.lock();
+ long lockId = createLockId(userId, lock);
+ return Optional.of(lockId);
}
- public synchronized Lock getBlockReadLock(long blockId) {
- Preconditions.checkArgument(mBlockIdToLockMap.containsKey(blockId),
- "Cannot get lock for block %s: not exists", blockId);
- return mBlockIdToLockMap.get(blockId).readLock();
+ public synchronized boolean unlockBlock(long lockId) {
+ // TODO: implement me
+ // do unlock
+
+ cleanupLockId(lockId);
+ return true;
}
- public synchronized Lock getBlockWriteLock(long blockId) {
- Preconditions.checkArgument(mBlockIdToLockMap.containsKey(blockId),
- "Cannot get lock for block %s: not exists", blockId);
- return mBlockIdToLockMap.get(blockId).writeLock();
+ private synchronized long createLockId(long userId, Lock lock) {
+ // TODO: implement me
+ long lockId = mCurrentLockId.getAndIncrement();
+ // mUserIdToAcquiredLockIdsMap.put(userId, lockID);
+ return lockId;
+ }
+
+ private synchronized boolean cleanupLockId(long lockId) {
+ // TODO: implement me
+ // mUserIdToAcquiredLockIdsMap.put(userId, lockID);
+ return true;
+ }
+
+ /**
+ * Validates the lock is hold by the given user for the given block.
+ *
+ * @param userId The ID of the user
+ * @param blockId The ID of the block
+ * @param lockId The ID of the lock
+ * @return true if validation succeeds, false otherwise
+ */
+ public synchronized boolean validateLockId(long userId, long blockId, long lockId) {
+ // TODO: implement me
+ return true;
}
/**
@@ -82,7 +117,6 @@ public class BlockLockManager {
return true;
}
-
/**
* Remove a lock for the given block id.
*
|
Update BlockLockManager to assign new lockId each time
|
Alluxio_alluxio
|
train
|
aaa5ac15065db7140a39687818c972acd78b809a
|
diff --git a/lib/staccato/tracker.rb b/lib/staccato/tracker.rb
index <HASH>..<HASH> 100644
--- a/lib/staccato/tracker.rb
+++ b/lib/staccato/tracker.rb
@@ -174,13 +174,11 @@ module Staccato
# Useful in testing
class NoopTracker
attr_writer :adapter
- # (see Tracker#initialize)
- def initialize(id = nil, client_id = nil, hit_defaults = {}); end
+ attr_accessor :hit_defaults
- # hit defaults for our noop
- # @return [Hash]
- def hit_defaults
- {}
+ # (see Tracker#initialize)
+ def initialize(id = nil, client_id = nil, hit_defaults = {})
+ self.hit_defaults = hit_defaults
end
# (see Tracker#id)
diff --git a/spec/integration/noop_tracker_spec.rb b/spec/integration/noop_tracker_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/integration/noop_tracker_spec.rb
+++ b/spec/integration/noop_tracker_spec.rb
@@ -20,6 +20,20 @@ describe Staccato::NoopTracker do
end
end
+ describe 'settings' do
+ it 'has an adapter' do
+ expect(tracker.respond_to?(:adapter=)).to eq(true)
+ end
+
+ it 'has hit defaults' do
+ expect(tracker.hit_defaults).to eq({})
+
+ tracker.hit_defaults[:document_hostname] = 'mysite.com'
+
+ expect(tracker.hit_defaults[:document_hostname]).to eq 'mysite.com'
+ end
+ end
+
describe "#event" do
before(:each) do
tracker.event({
|
align noop behavior to better match tracker
|
tpitale_staccato
|
train
|
a03281504979a0a61a3fa6ef19eb10e34508c18f
|
diff --git a/leonardo/module/web/models.py b/leonardo/module/web/models.py
index <HASH>..<HASH> 100644
--- a/leonardo/module/web/models.py
+++ b/leonardo/module/web/models.py
@@ -249,7 +249,7 @@ class Widget(FeinCMSBase):
feincms_item_editor_inline = WidgetInline
prerendered_content = models.TextField(
- verbose_name=_('prerendered content'), blank=True, editable=False)
+ verbose_name=_('prerendered content'), blank=True)
enabled = models.NullBooleanField(verbose_name=_('Is visible?'))
label = models.CharField(
verbose_name=_("Title"), max_length=255, null=True, blank=True)
diff --git a/leonardo/module/web/templates/widget/_create.html b/leonardo/module/web/templates/widget/_create.html
index <HASH>..<HASH> 100644
--- a/leonardo/module/web/templates/widget/_create.html
+++ b/leonardo/module/web/templates/widget/_create.html
@@ -1,7 +1,7 @@
{% extends "leonardo/common/_modal_form.html" %}
-{% load i18n %}
{% load url from future %}
+{% load crispy_forms_tags i18n %}
{% block form_id %}{{ form_id }}{% endblock %}
{% block form_action %}{{ url }}{% endblock %}
@@ -10,7 +10,7 @@
{% block modal-body %}
-{% load crispy_forms_tags %}
+{{ body|safe }}
{% crispy form %}
{% comment %}
diff --git a/leonardo/module/web/urls.py b/leonardo/module/web/urls.py
index <HASH>..<HASH> 100644
--- a/leonardo/module/web/urls.py
+++ b/leonardo/module/web/urls.py
@@ -20,7 +20,7 @@ from feincms.utils.templatetags import (do_simple_assignment_node_with_var_and_a
SimpleAssignmentNodeWithVarAndArgs,
SimpleNodeWithVarAndArgs)
from horizon_contrib.forms.models import create_or_update_and_get
-from horizon_contrib.forms.views import CreateView, UpdateView, ModalFormView, ContextMixin
+from horizon_contrib.forms.views import CreateView, UpdateView, ModalFormView, ContextMixin, ModelFormMixin
from leonardo.module.web.forms import get_widget_update_form, get_widget_create_form
from leonardo.module.web.models import Page
@@ -41,6 +41,17 @@ class UpdateView(ModalFormView, UpdateView):
"""Returns an instance of the form to be used in this view."""
return get_widget_update_form(**self.kwargs)(**self.get_form_kwargs())
+ def form_valid(self, form):
+ response = super(UpdateView, self).form_valid(form)
+ obj = self.object
+ if not obj.prerendered_content:
+ # turn off frontend edit for this redner
+ request = self.request
+ request.frontend_editing = False
+ obj.prerendered_content = obj.render_content(options={'request': request})
+ obj.save()
+ return response
+
class CreateWidgetView(ModalFormView, CreateView):
@@ -62,11 +73,18 @@ class CreateWidgetView(ModalFormView, CreateView):
def form_valid(self, form):
try:
- form.save()
+ obj = form.save()
# invalide page cache
page = Page.objects.get(id = self.kwargs['page_id'])
page.invalidate_cache()
+ if not obj.prerendered_content:
+ # turn off frontend edit for this redner
+ request = self.request
+ request.frontend_editing = False
+ obj.prerendered_content = obj.render_content(options={'request': request})
+ obj.save()
+
success_url = self.get_success_url()
response = HttpResponseRedirect(success_url)
response['X-Horizon-Location'] = success_url
@@ -99,7 +117,7 @@ class CreateView(ModalFormView, CreateView):
return form_class(**kwargs)
-class DeleteWidgetView(ModalFormView, ContextMixin):
+class DeleteWidgetView(ModalFormView, ContextMixin, ModelFormMixin):
form_class = WidgetDeleteForm
@@ -118,12 +136,12 @@ class DeleteWidgetView(ModalFormView, ContextMixin):
context['view_name'] = self.get_label()
context['heading'] = self.get_header()
context['help_text'] = self.get_help_text()
+ context['body'] = self.object.prerendered_content
return context
def form_valid(self, form):
+ obj = self.object
try:
- cls = get_class(self.kwargs['cls_name'])
- obj = cls.objects.get(**{cls._meta.pk.name: self.kwargs['id']})
parent = obj.parent
obj.delete()
# invalide page cache
|
render preprended content in delete dialog
|
django-leonardo_django-leonardo
|
train
|
81fc9dcb7ed3186e288b9bdafcd576bf7e04e006
|
diff --git a/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/Jackson2Parser.java b/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/Jackson2Parser.java
index <HASH>..<HASH> 100644
--- a/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/Jackson2Parser.java
+++ b/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/parser/Jackson2Parser.java
@@ -462,27 +462,28 @@ public class Jackson2Parser extends ModelParser {
final List<EnumMemberModel> enumMembers = new ArrayList<>();
if (sourceClass.type.isEnum()) {
final Class<?> enumClass = (Class<?>) sourceClass.type;
-
- try {
- final Field[] allEnumFields = enumClass.getDeclaredFields();
- final List<Field> constants = Arrays.stream(allEnumFields).filter(Field::isEnumConstant).collect(Collectors.toList());
- for (Field constant : constants) {
+ final Field[] allEnumFields = enumClass.getDeclaredFields();
+ final List<Field> constants = Arrays.stream(allEnumFields).filter(Field::isEnumConstant).collect(Collectors.toList());
+ for (Field constant : constants) {
+ Object value;
+ try {
constant.setAccessible(true);
final String enumJson = objectMapper.writeValueAsString(constant.get(null));
- final Object value = objectMapper.readValue(enumJson, new TypeReference<Object>(){});
-
- final List<String> constantComments = getComments(constant.getAnnotation(JsonPropertyDescription.class));
- if (value instanceof String) {
- enumMembers.add(new EnumMemberModel(constant.getName(), (String) value, constantComments));
- } else if (value instanceof Number) {
- enumMembers.add(new EnumMemberModel(constant.getName(), (Number) value, constantComments));
- } else {
- TypeScriptGenerator.getLogger().warning(String.format("'%s' enum as a @JsonValue that isn't a String or Number, ignoring", enumClass.getName()));
- }
+ value = objectMapper.readValue(enumJson, new TypeReference<Object>(){});
+ } catch (Throwable e) {
+ TypeScriptGenerator.getLogger().error(String.format("Cannot get enum value for constant '%s.%s'", enumClass.getName(), constant.getName()));
+ TypeScriptGenerator.getLogger().verbose(Utils.exceptionToString(e));
+ value = constant.getName();
+ }
+
+ final List<String> constantComments = getComments(constant.getAnnotation(JsonPropertyDescription.class));
+ if (value instanceof String) {
+ enumMembers.add(new EnumMemberModel(constant.getName(), (String) value, constantComments));
+ } else if (value instanceof Number) {
+ enumMembers.add(new EnumMemberModel(constant.getName(), (Number) value, constantComments));
+ } else {
+ TypeScriptGenerator.getLogger().warning(String.format("'%s' enum as a @JsonValue that isn't a String or Number, ignoring", enumClass.getName()));
}
- } catch (Exception e) {
- TypeScriptGenerator.getLogger().error(String.format("Cannot get enum values for '%s' enum", enumClass.getName()));
- e.printStackTrace(System.out);
}
}
diff --git a/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Utils.java b/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Utils.java
index <HASH>..<HASH> 100644
--- a/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Utils.java
+++ b/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Utils.java
@@ -7,6 +7,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.File;
import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
@@ -371,4 +373,10 @@ public class Utils {
}
}
+ public static String exceptionToString(Throwable e) {
+ final StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ return writer.toString();
+ }
+
}
|
Catching error thrown when determining enum value (#<I>)
|
vojtechhabarta_typescript-generator
|
train
|
a12fa399ab71a39c224a727923d4e3ba4a497c80
|
diff --git a/interp/builtin.go b/interp/builtin.go
index <HASH>..<HASH> 100644
--- a/interp/builtin.go
+++ b/interp/builtin.go
@@ -25,12 +25,11 @@ func isBuiltin(name string) bool {
return false
}
-func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
- exit := 0
+func (r *Runner) builtinCode(pos syntax.Pos, name string, args []string) int {
switch name {
case "true", ":":
case "false":
- exit = 1
+ return 1
case "exit":
switch len(args) {
case 0:
@@ -39,8 +38,8 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
if n, err := strconv.Atoi(args[0]); err != nil {
r.runErr(pos, "invalid exit code: %q", args[0])
} else {
- exit = n
r.err = ExitCode(n)
+ return n
}
default:
r.runErr(pos, "exit cannot take multiple arguments")
@@ -59,8 +58,7 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
fallthrough
default:
r.errf("usage: shift [n]\n")
- exit = 2
- break
+ return 2
}
if len(r.args) < n {
n = len(r.args)
@@ -98,8 +96,7 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
case "printf":
if len(args) == 0 {
r.errf("usage: printf format [arguments]\n")
- exit = 2
- break
+ return 2
}
var a []interface{}
for _, arg := range args[1:] {
@@ -122,7 +119,7 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
fallthrough
default:
r.errf("usage: break [n]\n")
- exit = 2
+ return 2
}
case "continue":
if !r.inLoop {
@@ -140,15 +137,14 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
fallthrough
default:
r.errf("usage: continue [n]\n")
- exit = 2
+ return 2
}
case "pwd":
r.outf("%s\n", r.getVar("PWD"))
case "cd":
if len(args) > 1 {
r.errf("usage: cd [dir]\n")
- exit = 2
- break
+ return 2
}
var dir string
if len(args) == 0 {
@@ -161,8 +157,7 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
}
_, err := os.Stat(dir)
if err != nil {
- exit = 1
- break
+ return 1
}
r.Dir = dir
case "wait":
@@ -176,12 +171,12 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
break
}
if !isBuiltin(args[0]) {
- exit = 1
- break
+ return 1
}
// TODO: pos
- r.builtin(0, args[0], args[1:])
+ return r.builtinCode(0, args[0], args[1:])
case "type":
+ anyNotFound := false
for _, arg := range args {
if _, ok := r.funcs[arg]; ok {
r.outf("%s is a function\n", arg)
@@ -195,24 +190,26 @@ func (r *Runner) builtin(pos syntax.Pos, name string, args []string) {
r.outf("%s is %s\n", arg, path)
continue
}
- exit = 1
r.errf("type: %s: not found\n", arg)
+ anyNotFound = true
+ }
+ if anyNotFound {
+ return 1
}
case "eval":
src := strings.Join(args, " ")
file, err := syntax.Parse(strings.NewReader(src), "", 0)
if err != nil {
r.errf("eval: %v\n", err)
- exit = 1
- break
+ return 1
}
r2 := *r
r2.File = file
r2.Run()
- exit = r2.exit
+ return r2.exit
case "trap", "source", "command", "pushd", "popd",
"umask", "alias", "unalias", "fg", "bg", "getopts":
r.runErr(pos, "unhandled builtin: %s", name)
}
- r.exit = exit
+ return 0
}
diff --git a/interp/interp.go b/interp/interp.go
index <HASH>..<HASH> 100644
--- a/interp/interp.go
+++ b/interp/interp.go
@@ -622,7 +622,7 @@ func (r *Runner) call(pos syntax.Pos, name string, args []string) {
return
}
if isBuiltin(name) {
- r.builtin(pos, name, args)
+ r.exit = r.builtinCode(pos, name, args)
return
}
cmd := exec.CommandContext(r.Context, name, args...)
|
interp: simplify builtin exit code logic
|
mvdan_sh
|
train
|
1a40ba65308e148e2948e08063f2efa37fc77c74
|
diff --git a/lib/config.php b/lib/config.php
index <HASH>..<HASH> 100644
--- a/lib/config.php
+++ b/lib/config.php
@@ -13,7 +13,7 @@ add_theme_support('jquery-cdn'); // Enable to load jQuery from the Go
* Configuration values
*/
define('GOOGLE_ANALYTICS_ID', ''); // UA-XXXXX-Y
-define('POST_EXCERPT_LENGTH', 40);
+define('POST_EXCERPT_LENGTH', 40); // words
/**
* .main classes
|
Comment config.php excerpt length is in words
Add comment to POST_EXCERPT_LENGTH to indicate it is in words, not
characters.
|
roots_sage
|
train
|
e0e9152e554ea3d5cdf571f6c08f57fb106dde4e
|
diff --git a/core-bundle/src/Resources/contao/dca/tl_form.php b/core-bundle/src/Resources/contao/dca/tl_form.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/dca/tl_form.php
+++ b/core-bundle/src/Resources/contao/dca/tl_form.php
@@ -497,7 +497,7 @@ class tl_form extends Contao\Backend
// Generate an alias if there is none
if ($varValue == '')
{
- $varValue = Contao\System::getContainer()->get('contao.slug')->generate($dc->activeRecord->title, $dc->activeRecord->jumpTo, $aliasExists);
+ $varValue = Contao\System::getContainer()->get('contao.slug')->generate($dc->activeRecord->title, Contao\Input::post('jumpTo') ?: $dc->activeRecord->jumpTo, $aliasExists);
}
elseif ($aliasExists($varValue))
{
|
Use the jumpTo value from POST data if set (see #<I>)
Description
-----------
Currently, if you create a new form, set the title and select a jumpTo page the slug settings from the selected root page are not used. This PR fixes that issue.
Commits
-------
ad<I>e<I> Use the jumpTo value from post data if set
|
contao_contao
|
train
|
2aafc237a2e8f4b9dce4702437bc3531110f7015
|
diff --git a/depsolver.js b/depsolver.js
index <HASH>..<HASH> 100644
--- a/depsolver.js
+++ b/depsolver.js
@@ -15,7 +15,6 @@ function resolveRpath (libs, file, lib) {
return x.substring(0, x.lastIndexOf('/'));
}));
rpaths.forEach((x) => {
- console.log(file);
try {
const paz = x + realLib;
fs.statSync(paz);
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -23,7 +23,6 @@ module.exports = class Applesign {
bundleid: opt.bundleid || undefined,
identity: opt.identity || undefined,
replaceipa: opt.replaceipa || false,
- graphSortedBins: opt.graphSortedBins || false,
withoutWatchapp: opt.withoutWatchapp || false,
mobileprovision: opt.mobileprovision || undefined,
verifyTwice: opt.verifyTwice || false,
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"macho": "1.0.0",
"fatmacho": "0.1.1",
"macho-is-encrypted": "0.1.0",
- "macho-entitlements": "0.2.2"
+ "macho-entitlements": "0.2.2",
+ "which": "1.2.10"
},
"description": "API to resign IPA files",
"homepage": "https://www.nowsecure.com",
diff --git a/tools.js b/tools.js
index <HASH>..<HASH> 100644
--- a/tools.js
+++ b/tools.js
@@ -2,6 +2,7 @@
const childproc = require('child_process');
const plist = require('simple-plist');
+const which = require('which');
const fs = require('fs');
const cmd = {
@@ -21,7 +22,21 @@ function execProgram (bin, arg, opt, cb) {
}
module.exports = {
- codesign: function (identity, entitlement, keychain, file, cb) {
+ findInPath: function findInPath (cb) {
+ const keys = Object.keys(cmd);
+ let pending = keys.length;
+ for (let key of keys) {
+ which(key, function (err, loc) {
+ if (err !== undefined) {
+ cmd[key] = loc;
+ if (--pending === 0) {
+ cb(null, cmd);
+ }
+ }
+ });
+ }
+ },
+ codesign: function codesign (identity, entitlement, keychain, file, cb) {
/* use the --no-strict to avoid the "resource envelope is obsolete" error */
const args = [ '--no-strict' ]; // http://stackoverflow.com/a/26204757
if (identity === undefined) {
@@ -37,7 +52,7 @@ module.exports = {
args.push(file);
execProgram(cmd.codesign, args, null, cb);
},
- verifyCodesign: function (file, keychain, cb) {
+ verifyCodesign: function verifyCodesign (file, keychain, cb) {
const args = ['-v', '--no-strict'];
if (typeof keychain === 'string') {
args.push('--keychain=' + keychain);
@@ -45,27 +60,27 @@ module.exports = {
args.push(file);
execProgram(cmd.codesign, args, null, cb);
},
- getEntitlementsFromMobileProvision: function (file, cb) {
+ getEntitlementsFromMobileProvision: function getEntitlementsFromMobileProvision (file, cb) {
const args = [ 'cms', '-D', '-i', file ];
execProgram(cmd.security, args, null, (error, stdout) => {
cb(error, plist.parse(stdout)['Entitlements']);
});
},
- zip: function (cwd, ofile, src, cb) {
+ zip: function zip (cwd, ofile, src, cb) {
fs.unlink(ofile, () => {
const args = [ '-qry', ofile, src ];
execProgram(cmd.zip, args, { cwd: cwd }, cb);
});
},
- unzip: function (ifile, odir, cb) {
+ unzip: function unzip (ifile, odir, cb) {
const args = [ '-o', ifile, '-d', odir ];
execProgram(cmd.unzip, args, null, cb);
},
- xcaToIpa: function (ifile, odir, cb) {
+ xcaToIpa: function xcaToIpa (ifile, odir, cb) {
const args = [ '-exportArchive', '-exportFormat', 'ipa', '-archivePath', ifile, '-exportPath', odir ];
execProgram(cmd.xcodebuild, args, null, cb);
},
- getIdentities: function (cb) {
+ getIdentities: function getIdentities (cb) {
const args = [ 'find-identity', '-v', '-p', 'codesigning' ];
execProgram(cmd.security, args, null, (error, stdout) => {
if (error) {
|
Add tools.findInPath() and use named method
|
nowsecure_node-applesign
|
train
|
ee1fcee77349d02f714ddfa91fe7ca0d05f7e8be
|
diff --git a/lib/cidr.js b/lib/cidr.js
index <HASH>..<HASH> 100644
--- a/lib/cidr.js
+++ b/lib/cidr.js
@@ -15,7 +15,6 @@
*
*/
-var net = require('net');
var Buffer = require('buffer').Buffer;
var ipv6 = require('ipv6').v6;
@@ -80,7 +79,10 @@ var makeAddr = function(ad, ver) {
* @param {*} y second paramater.
*/
var CIDR = function(x, y) {
- var ip, bits, arr;
+ var ip,
+ bits,
+ arr,
+ ip6;
if (y === undefined) { // handed a string
arr = x.split('/');
this.subnet = arr[1];
@@ -90,11 +92,9 @@ var CIDR = function(x, y) {
ip = x;
}
- if (ip instanceof ipv6.Address) {
- this.v = 6;
- } else {
- this.v = net.isIP(ip);
- }
+
+ ip6 = (ip instanceof ipv6.Address ? ip : new ipv6.Address(ip));
+ this.v = (ip6.is4() ? 4 : ip6.valid ? 6 : 0);
if (this.v === 6) {
bits = 128;
@@ -114,7 +114,13 @@ var CIDR = function(x, y) {
* @return {bool} if the address is within the CIDR.
*/
CIDR.prototype.isInCIDR = function(x) {
- var ver = net.isIP(x), buf1;
+ var ver,
+ buf1,
+ ip6;
+
+ ip6 = new ipv6.Address(x);
+ ver = (ip6.is4() ? 4 : ip6.valid ? 6 : 0);
+
if (ver !== this.v) {
return false;
}
|
Remove use of net.isIP from cidr
|
racker_node-swiz
|
train
|
9aca0ab77294fdf00a55f7429c09e8278e7b6aed
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -10,13 +10,11 @@ if platform.system() == "Windows":
elif platform.system() == "Darwin":
extras_require = {
'cocoa': ['pyobjc'],
- 'qt4': ['PyQt4'],
'qt5': ['PyQt5'],
}
elif platform.system() == "Linux":
extras_require = {
'gtk3': ['PyGObject'],
- 'qt4': ['PyQt4'],
'qt5': ['PyQt5'],
}
|
Remove pyqt4 from requires in setup.py
|
r0x0r_pywebview
|
train
|
15d599c8e6188c94591ec85f9deb7aba1a696991
|
diff --git a/code/libraries/koowa/libraries/dispatcher/behavior/persistable.php b/code/libraries/koowa/libraries/dispatcher/behavior/persistable.php
index <HASH>..<HASH> 100644
--- a/code/libraries/koowa/libraries/dispatcher/behavior/persistable.php
+++ b/code/libraries/koowa/libraries/dispatcher/behavior/persistable.php
@@ -84,7 +84,7 @@ class KDispatcherBehaviorPersistable extends KControllerBehaviorAbstract
$vars = array();
foreach($state->toArray() as $var)
{
- if(!$var->unique) {
+ if(!$var->unique && !$var->internal) {
$vars[$var->name] = $var->value;
}
}
|
re #<I>: Do not persist internal states
|
timble_kodekit
|
train
|
209bc436fa517e961a6dd77658457c2187474757
|
diff --git a/phe/paillier.py b/phe/paillier.py
index <HASH>..<HASH> 100644
--- a/phe/paillier.py
+++ b/phe/paillier.py
@@ -29,8 +29,9 @@ except ImportError:
from phe.util import invert, powmod, getprimeover
+DEFAULT_KEYSIZE = 2048
-def generate_paillier_keypair(private_keyring=None, n_length=1024):
+def generate_paillier_keypair(private_keyring=None, n_length=DEFAULT_KEYSIZE):
"""Return a new PaillierPublicKey and PaillierPrivateKey.
Add the private key to *private_keyring* if given.
diff --git a/phe/tests/paillier_test.py b/phe/tests/paillier_test.py
index <HASH>..<HASH> 100644
--- a/phe/tests/paillier_test.py
+++ b/phe/tests/paillier_test.py
@@ -44,7 +44,7 @@ class PaillierGeneric(unittest.TestCase):
def testCreateKeypairLengths(self):
- for key_length in [8, 16, 32, 64, 128, 256, 512, 1024, 2048]:
+ for key_length in [8, 16, 32, 64, 128, 256, 512, 1024, 2048, 3072, 4096]:
public_key, private_key = paillier.generate_paillier_keypair(n_length=key_length)
self.assertTrue(hasattr(public_key, 'g'))
@@ -53,6 +53,10 @@ class PaillierGeneric(unittest.TestCase):
self.assertTrue(hasattr(private_key, 'mu'))
self.assertTrue(hasattr(private_key, 'Lambda'))
+ # Check that no exceptions are raised representing these keys
+ repr(public_key)
+ repr(private_key)
+
def testKeyUniqueness(self):
repeats = 100
public_keys = set()
@@ -120,6 +124,7 @@ class PaillierTestRawEncryption(PaillierTest):
self.assertEqual(848742150, enc_num.ciphertext(False))
def testEncryptIsRandom(self):
+ # Check for semantic security
public_key = paillier.PaillierPublicKey(6497955158, 126869)
enc_num = public_key.encrypt(1, r_value=1)
@@ -198,14 +203,14 @@ class PaillierTestEncodedNumber(PaillierTest):
self.assertRaises(ValueError, paillier.EncodedNumber.encode,
self.public_key, self.public_key.max_int + 1)
self.assertRaises(ValueError, paillier.EncodedNumber.encode,
- self.public_key, 2 ** 1023)
+ self.public_key, 2 ** (paillier.DEFAULT_KEYSIZE-1))
def testEncodeIntTooLargeNegative(self):
# check value error is raised on too large a positive input
self.assertRaises(ValueError, paillier.EncodedNumber.encode,
self.public_key, -self.public_key.max_int - 1)
self.assertRaises(ValueError, paillier.EncodedNumber.encode,
- self.public_key, -2 ** 1023)
+ self.public_key, -2 ** (paillier.DEFAULT_KEYSIZE-1))
def testDecodeCorruptEncodedNumber(self):
encoded = paillier.EncodedNumber.encode(self.public_key, 10)
|
Add longer keys to tests. Increase default key size to <I> bits
|
n1analytics_python-paillier
|
train
|
39fcf2150f5a925f56ef57923857fd90ce36d748
|
diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -465,10 +465,14 @@ func (self *Client) Describe() (streams []av.CodecData, err error) {
}
func (self *Client) Options() (err error) {
- if err = self.WriteRequest(Request{
+ req := Request{
Method: "OPTIONS",
- Uri: self.requestUri,
- }); err != nil {
+ Uri: self.requestUri,
+ }
+ if self.session != "" {
+ req.Header = append(req.Header, "Session: "+self.session)
+ }
+ if err = self.WriteRequest(req); err != nil {
return
}
if _, err = self.ReadResponse(); err != nil {
|
more camera check Session keep-alive
fix keep-alive add Session
|
nareix_joy4
|
train
|
e467a7ca52924540e46ea99908446cd9bd021595
|
diff --git a/lib/comfortable_mexican_sofa/view_methods.rb b/lib/comfortable_mexican_sofa/view_methods.rb
index <HASH>..<HASH> 100644
--- a/lib/comfortable_mexican_sofa/view_methods.rb
+++ b/lib/comfortable_mexican_sofa/view_methods.rb
@@ -35,7 +35,7 @@ module ComfortableMexicanSofa::ViewMethods
end
return '' unless snippet
- render :inline => ComfortableMexicanSofa::Tag.process_content(cms_site.pages.build, snippet.content)
+ render :inline => ComfortableMexicanSofa::Tag.process_content(cms_site.pages.build, ComfortableMexicanSofa::Tag.sanitize_irb(snippet.content))
end
# Content of a text based page block. This is the typical method for retrieving content from
@@ -79,7 +79,7 @@ module ComfortableMexicanSofa::ViewMethods
when ComfortableMexicanSofa::Tag::PageFiles
block.files
else
- render :inline => ComfortableMexicanSofa::Tag.process_content(page, block.content)
+ render :inline => ComfortableMexicanSofa::Tag.process_content(page, ComfortableMexicanSofa::Tag.sanitize_irb(block.content))
end
end
end
diff --git a/test/lib/view_methods_test.rb b/test/lib/view_methods_test.rb
index <HASH>..<HASH> 100644
--- a/test/lib/view_methods_test.rb
+++ b/test/lib/view_methods_test.rb
@@ -110,7 +110,13 @@ class ViewMethodsTest < ActionView::TestCase
assert_equal 'default_snippet_content',
action_result('test_cms_snippet_with_default_content_block')
end
-
+
+ def test_cms_snippet_content_with_irb
+ cms_snippets(:default).update_column(:content, '<%= 1+1+1+1+1 %>')
+ assert_equal "<%= 1+1+1+1+1 %>", action_result('test_cms_snippet_content')
+ end
+
+
def test_cms_page_content
assert_equal 'default_field_text_content', action_result('test_cms_page_content')
end
@@ -141,4 +147,9 @@ class ViewMethodsTest < ActionView::TestCase
assert_equal page.blocks.find_by_identifier('files').files, cms_page_content(:files, page)
end
+ def test_cms_page_content_with_irb
+ cms_blocks(:default_field_text).update_column(:content, '<%= 1+1+1+1+1 %>')
+ assert_equal "<%= 1+1+1+1+1 %>", action_result('test_cms_page_content')
+ end
+
end
|
sanitizes irb when calling cms_page_content or cms_snippet_content
|
comfy_comfortable-mexican-sofa
|
train
|
8a58f10cee3fda71be64b2332b19d150556ef203
|
diff --git a/FormulaParser.php b/FormulaParser.php
index <HASH>..<HASH> 100644
--- a/FormulaParser.php
+++ b/FormulaParser.php
@@ -282,36 +282,41 @@ class FormulaParser implements IFormulaParser
} else {
$j = $i+3;
}
- while (true) {
- if (isset($str[$j])) {
- if (((strstr('+-', $str[$j])) && ($arg === null))
- || (strstr('0123456789', $str[$j]))
- || (($str[$j] == '.') && (!strstr($arg, '.')))) {
- $arg .= $str[$j];
- } elseif ((strstr(' ', $str[$j])) && (!strpbrk($arg, '0123456789'))) {
+ if (strpos($str, 'INF')) {
+ $str = 'INF';
+ $strlen = 3;
+ } else {
+ while (true) {
+ if (isset($str[$j])) {
+ if (((strstr('+-', $str[$j])) && ($arg === null))
+ || (strstr('0123456789', $str[$j]))
+ || (($str[$j] == '.') && (!strstr($arg, '.')))) {
+ $arg .= $str[$j];
+ } elseif ((strstr(' ', $str[$j])) && (!strpbrk($arg, '0123456789'))) {
+ } else {
+ $arg = trim($arg);
+ break;
+ }
+ $j++;
} else {
- $arg = trim($arg);
break;
}
- $j++;
- } else {
- break;
}
- }
- if (!is_numeric($arg)) {
- $this->correct = 0;
- } else {
- if ($function == 'exp') {
- $result = pow(M_E, $arg);
+ if (!is_numeric($arg)) {
+ $this->correct = 0;
} else {
- $result = $function($arg);
+ if ($function == 'exp') {
+ $result = pow(M_E, $arg);
+ } else {
+ $result = $function($arg);
+ }
+ }
+ if (($this->correct) && (is_numeric($result))) {
+ $str1 = substr($str, 0, $i);
+ $str2 = substr($str, $j);
+ $str = $str1.' '.$result.$str2;
+ $strlen = strlen($str);
}
- }
- if (($this->correct) && (is_numeric($result))) {
- $str1 = substr($str, 0, $i);
- $str2 = substr($str, $j);
- $str = $str1.' '.$result.$str2;
- $strlen = strlen($str);
}
}
}
|
Improved: parsing an expression containing INF
|
denissimon_formula-parser
|
train
|
675cbc7397cc445f8a161671ff440aa039c3501d
|
diff --git a/safe/metadata/test/test_aggregation_metadata.py b/safe/metadata/test/test_aggregation_metadata.py
index <HASH>..<HASH> 100644
--- a/safe/metadata/test/test_aggregation_metadata.py
+++ b/safe/metadata/test/test_aggregation_metadata.py
@@ -37,12 +37,12 @@ class TestAggregationMetadata(TestCase):
metadata.get_property('organisation')
# from AggregationLayerMetadata
- metadata.get_property('aggregation_attribute')
- metadata.get_property('adult_ratio_attribute')
- metadata.get_property('adult_ratio_default')
- metadata.get_property('elderly_ratio_attribute')
- metadata.get_property('elderly_ratio_default')
- metadata.get_property('female_ratio_attribute')
- metadata.get_property('female_ratio_default')
- metadata.get_property('youth_ratio_attribute')
- metadata.get_property('youth_ratio_default')
+ metadata.get_property('aggregation attribute')
+ metadata.get_property('adult ratio attribute')
+ metadata.get_property('adult ratio default')
+ metadata.get_property('elderly ratio attribute')
+ metadata.get_property('elderly ratio default')
+ metadata.get_property('female ratio attribute')
+ metadata.get_property('female ratio default')
+ metadata.get_property('youth ratio attribute')
+ metadata.get_property('youth ratio default')
|
Revert changes related to new key for aggregation metadata.
|
inasafe_inasafe
|
train
|
668e62cac2495e8fcadb10b2cc787d63d52ee1c5
|
diff --git a/aegean.py b/aegean.py
index <HASH>..<HASH> 100644
--- a/aegean.py
+++ b/aegean.py
@@ -653,12 +653,13 @@ def make_bkg_rms_image(data,beam,mesh_size=20,forced_rms=None):
xcen=int(img_x/2)
ycen=int(img_y/2)
- width_x = mesh_size*int(math.cos(beam.pa)*beam.b + math.sin(beam.pa)*beam.a)
- width_y = mesh_size*int(math.sin(beam.pa)*beam.b + math.cos(beam.pa)*beam.a)
+ width_x = mesh_size*int(max(abs(math.cos(beam.pa)*beam.b), abs(math.sin(beam.pa)*beam.a)))
+ width_y = mesh_size*int(max(abs(math.sin(beam.pa)*beam.b), abs(math.cos(beam.pa)*beam.a)))
rmsimg = np.zeros(data.shape)
bkgimg = np.zeros(data.shape)
logging.debug("image size x,y:{0},{1}".format(img_x,img_y))
+ logging.debug("beam: {0}".format(beam))
logging.debug("mesh width (pix) x,y: {0},{1}".format(width_x,width_y))
#box centered at image center then tilling outwards
|
#<I> Aegean crashes with particular beams when calculating variable background
|
PaulHancock_Aegean
|
train
|
6a26d50f390360ef25c1091d0d266a04bacb8139
|
diff --git a/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java b/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java
+++ b/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java
@@ -221,7 +221,7 @@ public class QueryStateMachine
// don't report failure info is query is marked as success
FailureInfo failureInfo = null;
ErrorCode errorCode = null;
- if (state != FINISHED) {
+ if (state == FAILED) {
ExecutionFailureInfo failureCause = this.failureCause.get();
if (failureCause != null) {
failureInfo = failureCause.toFailureInfo();
@@ -532,8 +532,9 @@ public class QueryStateMachine
recordDoneStats();
- // NOTE: this must be set before triggering the state change, so listeners
- // can be observe the exception
+ // NOTE: The failure cause must be set before triggering the state change, so
+ // listeners can observe the exception. This is safe because the failure cause
+ // can only be observed if the transition to FAILED is successful.
failureCause.compareAndSet(null, toFailure(throwable));
boolean failed = queryState.setIf(FAILED, currentState -> !currentState.isDone());
@@ -552,9 +553,13 @@ public class QueryStateMachine
{
recordDoneStats();
+ // NOTE: The failure cause must be set before triggering the state change, so
+ // listeners can observe the exception. This is safe because the failure cause
+ // can only be observed if the transition to FAILED is successful.
+ failureCause.compareAndSet(null, toFailure(new PrestoException(USER_CANCELED, "Query was canceled")));
+
boolean canceled = queryState.setIf(FAILED, currentState -> !currentState.isDone());
if (canceled) {
- failureCause.compareAndSet(null, toFailure(new PrestoException(USER_CANCELED, "Query was canceled")));
session.getTransactionId().ifPresent(autoCommit ? transactionManager::asyncAbort : transactionManager::fail);
}
|
Fix race condition in Query canncel state change
The failure cause must be recorded before the query state
is changed or a user can observe the FAILED state without
any failure information.
|
prestodb_presto
|
train
|
32a8bbea92bfe2a6fc1948f8c0d2207cd230bf0c
|
diff --git a/spec/support/sandbox.rb b/spec/support/sandbox.rb
index <HASH>..<HASH> 100644
--- a/spec/support/sandbox.rb
+++ b/spec/support/sandbox.rb
@@ -26,12 +26,13 @@ module Bosh
MIGRATIONS_PATH = File.join(DIRECTOR_PATH, "db", "migrations")
attr_reader :name
- alias_method :db_name, :name
- attr_accessor :director_fix_stateful_nodes
-
attr_reader :health_monitor_process
attr_reader :scheduler_process
+ alias_method :db_name, :name
+ attr_reader :blobstore_storage_dir
+ attr_accessor :director_fix_stateful_nodes
+
def initialize
@logger = Logger.new(STDOUT)
@name = SecureRandom.hex(6)
@@ -117,36 +118,7 @@ module Bosh
def reset(name)
time = Benchmark.realtime { do_reset(name) }
- puts "Reset took #{time} seconds"
- end
-
- def do_reset(name)
- @worker_process.stop('QUIT')
- @director_process.stop
- @health_monitor_process.stop
- kill_agents
-
- Redis.new(:host => "localhost", :port => redis_port).flushdb
-
- @postgresql.drop_db
- @postgresql.create_db
- @database_migrator.migrate
-
- FileUtils.rm_rf(blobstore_storage_dir)
- FileUtils.mkdir_p(blobstore_storage_dir)
- FileUtils.rm_rf(director_tmp_path)
- FileUtils.mkdir_p(director_tmp_path)
-
- File.open(File.join(director_tmp_path, "state.json"), "w") do |f|
- f.write(Yajl::Encoder.encode("uuid" => DIRECTOR_UUID))
- end
-
- write_in_sandbox(DIRECTOR_CONFIG, load_config_template(DIRECTOR_CONF_TEMPLATE))
- write_in_sandbox(HM_CONFIG, load_config_template(HM_CONF_TEMPLATE))
-
- @director_process.start
- @worker_process.start
- @director_socket_connector.try_to_connect(50)
+ @logger.info("Reset took #{time} seconds")
end
def reconfigure_director
@@ -206,6 +178,37 @@ module Bosh
@sandbox_root ||= Dir.mktmpdir.tap { |p| @logger.info("sandbox=#{p}") }
end
+ private
+
+ def do_reset(name)
+ @worker_process.stop('QUIT')
+ @director_process.stop
+ @health_monitor_process.stop
+ kill_agents
+
+ Redis.new(:host => "localhost", :port => redis_port).flushdb
+
+ @postgresql.drop_db
+ @postgresql.create_db
+ @database_migrator.migrate
+
+ FileUtils.rm_rf(blobstore_storage_dir)
+ FileUtils.mkdir_p(blobstore_storage_dir)
+ FileUtils.rm_rf(director_tmp_path)
+ FileUtils.mkdir_p(director_tmp_path)
+
+ File.open(File.join(director_tmp_path, "state.json"), "w") do |f|
+ f.write(Yajl::Encoder.encode("uuid" => DIRECTOR_UUID))
+ end
+
+ write_in_sandbox(DIRECTOR_CONFIG, load_config_template(DIRECTOR_CONF_TEMPLATE))
+ write_in_sandbox(HM_CONFIG, load_config_template(HM_CONF_TEMPLATE))
+
+ @director_process.start
+ @worker_process.start
+ @director_socket_connector.try_to_connect(50)
+ end
+
def kill_agents
Dir[File.join(agent_tmp_path, "running_vms", "*")].each do |vm|
begin
@@ -250,9 +253,7 @@ module Bosh
return 61000 + test_number * 100 + offset
end
- private
-
- attr_reader :logs_path, :director_tmp_path, :dns_db_path, :task_logs_dir, :blobstore_storage_dir
+ attr_reader :logs_path, :director_tmp_path, :dns_db_path, :task_logs_dir
end
end
end
|
made more sandbox methods private
|
cloudfoundry_bosh
|
train
|
258ce1acf54d91beaab87783bb0cced8daff8a9a
|
diff --git a/blueprints/ember-cli-visual-acceptance/index.js b/blueprints/ember-cli-visual-acceptance/index.js
index <HASH>..<HASH> 100644
--- a/blueprints/ember-cli-visual-acceptance/index.js
+++ b/blueprints/ember-cli-visual-acceptance/index.js
@@ -18,7 +18,7 @@ module.exports = {
{name: 'resemblejs', target: '2.2.0'},
{name: 'sync-request', target: '^3.0.1'}
])
- })
+ }.bind(this))
}.bind(this))
}
}
|
bind 'this' to blueprint
|
ciena-blueplanet_ember-cli-visual-acceptance
|
train
|
7d989c2461cb335881c9fc2455f6ede8cdf6a882
|
diff --git a/coinkit/address.py b/coinkit/address.py
index <HASH>..<HASH> 100644
--- a/coinkit/address.py
+++ b/coinkit/address.py
@@ -13,8 +13,8 @@ from .b58check import b58check_encode
def bin_hash160_to_address(bin_hash160, version_byte=0):
return b58check_encode(bin_hash160, version_byte=version_byte)
-def hex_hash160_to_address(hash160):
- return bin_hash160_to_address(unhexlify(hash160))
+def hex_hash160_to_address(hash160, version_byte=0):
+ return bin_hash160_to_address(unhexlify(hash160), version_byte=version_byte)
def script_hex_to_address(script, version_byte=0):
if script[0:6] == '76a914' and script[-4:] == '88ac':
diff --git a/coinkit/hash.py b/coinkit/hash.py
index <HASH>..<HASH> 100644
--- a/coinkit/hash.py
+++ b/coinkit/hash.py
@@ -10,6 +10,7 @@
import hashlib
from hashlib import sha256
from binascii import hexlify, unhexlify
+from utilitybelt import is_hex
def bin_sha256(s):
return sha256(s).digest()
diff --git a/coinkit/publickey.py b/coinkit/publickey.py
index <HASH>..<HASH> 100644
--- a/coinkit/publickey.py
+++ b/coinkit/publickey.py
@@ -11,10 +11,11 @@ import os, json, hashlib, ecdsa
from binascii import hexlify, unhexlify
from ecdsa.keys import VerifyingKey
from pybitcointools import decompress, compress, pubkey_to_address
+from utilitybelt import is_hex
from .errors import _errors
from .hash import bin_hash160 as get_bin_hash160
-from .formatcheck import is_hex, is_hex_ecdsa_pubkey, is_binary_ecdsa_pubkey
+from .formatcheck import is_hex_ecdsa_pubkey, is_binary_ecdsa_pubkey
from .b58check import b58check_encode
from .address import bin_hash160_to_address
@@ -96,7 +97,7 @@ class BitcoinPublicKey():
def version_byte(cls):
return cls._version_byte
- def __init__(self, public_key_string, version_byte=0):
+ def __init__(self, public_key_string, version_byte=0, verify=True):
""" Takes in a public key in hex format.
"""
# set the version byte
@@ -108,12 +109,13 @@ class BitcoinPublicKey():
# extract the bin ecdsa public key (uncompressed, w/out a magic byte)
bin_ecdsa_public_key = extract_bin_ecdsa_pubkey(public_key_string)
- try:
- # create the ecdsa key object
- self._ecdsa_public_key = VerifyingKey.from_string(
- bin_ecdsa_public_key, self._curve)
- except AssertionError as e:
- raise ValueError(_errors['IMPROPER_PUBLIC_KEY_FORMAT'])
+ if verify:
+ try:
+ # create the ecdsa key object
+ self._ecdsa_public_key = VerifyingKey.from_string(
+ bin_ecdsa_public_key, self._curve)
+ except AssertionError as e:
+ raise ValueError(_errors['IMPROPER_PUBLIC_KEY_FORMAT'])
def to_bin(self):
return self._bin_public_key
|
add support for creating public keys without verifying them against the ecdsa curve; fix import bug in hash module
|
blockstack_pybitcoin
|
train
|
e74e60d4581e6bfc1702420ccdd15b7065027be6
|
diff --git a/src/Storage/Field/Type/RepeaterType.php b/src/Storage/Field/Type/RepeaterType.php
index <HASH>..<HASH> 100644
--- a/src/Storage/Field/Type/RepeaterType.php
+++ b/src/Storage/Field/Type/RepeaterType.php
@@ -192,17 +192,38 @@ class RepeaterType extends FieldTypeBase
// This block separately handles JSON content for Templatefields
if (isset($data[$key]) && Json::test($data[$key])) {
- $originalMapping[$key]['fields'] = $this->mapping['fields'];
- $originalMapping[$key]['type'] = 'repeater';
+
+ if (isset($this->mapping['fields'])) {
+ $originalMapping[$key]['fields'] = $this->mapping['fields'];
+ $originalMapping[$key]['type'] = 'repeater';
+ } else {
+ $originalMapping[$key]['fields'] = $this->mapping['data']['fields'];
+ $originalMapping[$key]['type'] = 'block';
+ }
+
$mapping = $this->em->getMapper()->getRepeaterMapping($originalMapping);
$decoded = Json::parse($data[$key]);
$collection = new RepeatingFieldCollection($this->em, $mapping);
$collection->setName($key);
- if (isset($decoded) && count($decoded)) {
- foreach ($decoded as $group => $repdata) {
- $collection->addFromArray($repdata, $group);
+ if (isset($this->mapping['fields'])) {
+ if (isset($decoded) && count($decoded)) {
+ foreach ($decoded as $group => $repdata) {
+ $collection->addFromArray($repdata, $group);
+ }
+ }
+ } else {
+ if (isset($decoded) && count($decoded)) {
+ foreach ($decoded as $group => $block) {
+ foreach ($block as $blockName => $fields) {
+ $fields = $fields;
+ array_shift($fields);
+ if (is_array($fields)) {
+ $collection->addFromArray($fields, $group, $entity, $blockName);
+ }
+ }
+ }
}
}
|
Fix for field type blocks with translation extension
|
bolt_bolt
|
train
|
62f2c0443f6fe780e64a4740d8e681f8a8298edf
|
diff --git a/visualops/cmd/app/list.py b/visualops/cmd/app/list.py
index <HASH>..<HASH> 100755
--- a/visualops/cmd/app/list.py
+++ b/visualops/cmd/app/list.py
@@ -16,10 +16,12 @@ class List(Lister):
def take_action(self, parsed_args):
+ region_name = parsed_args.region_name
+ filter_name = parsed_args.filter_name
if parsed_args.list_app_local:
print 'List local app....'
- rlt = db.get_app_list()
+ rlt = db.get_app_list(region_name, filter_name)
return (( 'Name', 'Source Id', 'Region', 'State', 'Create At', 'Change At'), rlt)
else:
@@ -28,13 +30,13 @@ class List(Lister):
(username, session_id) = utils.load_session()
# get app list
- (err, result) = rpc.app_list(username, session_id, parsed_args.region_name)
+ (err, result) = rpc.app_list(username, session_id, region_name)
if err:
print('Get app list failed')
utils.hanlde_error(err,result)
else:
- self.app.stdout.write('get {0} app list succeed!\n'.format(len(result)))
+ self.log.debug('> get {0} app list succeed!'.format(len(result)))
return (('Id', 'Name', 'Region', 'State'),
- ((app["id"], app["name"], app["region"], app["state"]) for app in result if (parsed_args.filter_name.lower() in app['name'].lower() and app["state"] in ["Running"]) )
+ ((app["id"], app["name"], app["region"], app["state"]) for app in result if (filter_name.lower() in app['name'].lower() and app["state"] in ["Running"]) )
)
diff --git a/visualops/utils/db.py b/visualops/utils/db.py
index <HASH>..<HASH> 100755
--- a/visualops/utils/db.py
+++ b/visualops/utils/db.py
@@ -6,6 +6,7 @@ import sqlite3
import os
import datetime
import base64
+import logging
from visualops.utils import utils,constant
@@ -133,18 +134,32 @@ def terminate_app(app_id):
app_update_state(app_id, 'Terminated')
-def get_app_list():
+def get_app_list(region_name=None,filter_name=None):
"""
- get app list
+ get local app list
"""
try:
conn = get_conn()
c = conn.cursor()
- c.execute("SELECT name,source_id,region,state,create_at,change_at FROM app ")
+
+ cond = []
+ where_clause = ""
+ if region_name:
+ cond.append( "region='{0}' ".format(region_name) )
+ if filter_name:
+ cond.append( "lower(name) like '%{0}%' ".format(filter_name.lower()) )
+ if len(cond) > 0:
+ where_clause = 'where ' + 'and '.join( cond )
+
+ sqlcmd = "SELECT name,source_id,region,state,create_at,change_at FROM app %s " % where_clause
+ log = logging.getLogger(__name__)
+ log.debug('> sql : %s' % sqlcmd)
+
+ c.execute(sqlcmd)
rlt = c.fetchall()
conn.commit()
conn.close()
- #print '[app_list]list app succeed!'
+
return rlt
except Exception,e:
raise RuntimeError('list app failed! %s ' % e)
|
[feature/first-release] improve cmd "app list", support filter app
|
VisualOps_cli
|
train
|
2366a70f05485eb43f50f434eeb8da56129b730c
|
diff --git a/stronghold/tests/middleware.py b/stronghold/tests/middleware.py
index <HASH>..<HASH> 100644
--- a/stronghold/tests/middleware.py
+++ b/stronghold/tests/middleware.py
@@ -55,14 +55,14 @@ class LoginRequiredMiddlewareTests(TestCase):
self.assertEqual(response, None)
- def test_redirects_to_login_when_url_is_not_public(self):
+ def test_redirects_to_login_when_url_is_not_in_public_urls(self):
self.request.user.is_authenticated.return_value = False
response = self.middleware.process_view(**self.kwargs)
self.assertEqual(response.status_code, 302)
- def test_returns_none_when_url_is_public(self):
+ def test_returns_none_when_url_is_in_public_urls(self):
self.request.user.is_authenticated.return_value = False
self.middleware.public_view_urls = [re.compile(r'/test-protected-url/')]
|
refactor public urls test names
|
mgrouchy_django-stronghold
|
train
|
7b9dffe426d9ba7e3a97e72e20b546410100d713
|
diff --git a/test/com/google/javascript/jscomp/CheckSideEffectsTest.java b/test/com/google/javascript/jscomp/CheckSideEffectsTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/CheckSideEffectsTest.java
+++ b/test/com/google/javascript/jscomp/CheckSideEffectsTest.java
@@ -130,6 +130,10 @@ public final class CheckSideEffectsTest extends Es6CompilerTestCase {
testSameEs6("function c(a, b = f()) {}; c(1);");
testSameEs6("function c(a, {b, c}) {}; c(1);");
testSameEs6("function c(a, {b, c}) {}; c(1, {b: 2, c: 3});");
+
+ testWarningEs6("var f = s => {key:s}", e);
+ testWarningEs6("var f = s => {key:s + 1}", e);
+ testWarningEs6("var f = s => {s}", e);
}
public void testUselessCodeInFor() {
|
Added test to verify that <URL> was actually caught by our compiler.
Closes #<I>
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
a177375c25cfc26c0c4c27632d06524ab0fcd3f8
|
diff --git a/elasticsearch/helpers/__init__.py b/elasticsearch/helpers/__init__.py
index <HASH>..<HASH> 100644
--- a/elasticsearch/helpers/__init__.py
+++ b/elasticsearch/helpers/__init__.py
@@ -105,10 +105,6 @@ def streaming_bulk(client, actions, chunk_size=500, raise_on_error=True,
for chunk in _chunk_actions(actions, chunk_size):
- # raise on exception means we might need to iterate on chunk twice
- if not raise_on_exception:
- chunk = list(chunk)
-
bulk_actions = []
for action, data in chunk:
bulk_actions.append(action)
@@ -129,11 +125,19 @@ def streaming_bulk(client, actions, chunk_size=500, raise_on_error=True,
# if we are not propagating, mark all actions in current chunk as failed
err_message = str(e)
exc_errors = []
- for action, data in chunk:
- info = {"error": err_message, "status": e.status_code, "exception": e, "data": data}
- op_type, action = action.popitem()
- info.update(action)
- exc_errors.append({op_type: info})
+ bulk_data = iter(bulk_actions)
+ while True:
+ try:
+ # collect all the information about failed actions
+ action = next(bulk_data)
+ op_type, action = action.popitem()
+ info = {"error": err_message, "status": e.status_code, "exception": e}
+ if op_type != 'delete':
+ info['data'] = next(bulk_data)
+ info.update(action)
+ exc_errors.append({op_type: info})
+ except StopIteration:
+ break
# emulate standard behavior for failed actions
if raise_on_error:
|
Don't keep the data twice in bulk helper
|
elastic_elasticsearch-py
|
train
|
4807ad5b9d76d6706dd32806f1c837635ec61ed8
|
diff --git a/openquake/calculators/tests/__init__.py b/openquake/calculators/tests/__init__.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/tests/__init__.py
+++ b/openquake/calculators/tests/__init__.py
@@ -93,6 +93,7 @@ class CalculatorTestCase(unittest.TestCase):
self.edir = tempfile.mkdtemp()
with self.calc._monitor:
result = self.calc.run(export_dir=self.edir)
+ dur1 = self.calc._monitor.duration
if len(inis) == 2:
hc_id = self.calc.datastore.calc_id
self.calc = self.get_calc(
@@ -102,9 +103,13 @@ class CalculatorTestCase(unittest.TestCase):
exported = self.calc.run(export_dir=self.edir,
concurrent_tasks=0)
result.update(exported)
+ dur2 = self.calc._monitor.duration
+ else:
+ dur2 = 0
# reopen datastore, since some tests need to export from it
dstore = datastore.read(self.calc.datastore.calc_id)
self.calc.datastore = dstore
+ self.duration = numpy.array([dur1, dur2])
return result
def execute(self, testfile, job_ini):
diff --git a/openquake/calculators/tests/classical_damage_test.py b/openquake/calculators/tests/classical_damage_test.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/tests/classical_damage_test.py
+++ b/openquake/calculators/tests/classical_damage_test.py
@@ -96,10 +96,15 @@ class ClassicalDamageCase8TestCase(CalculatorTestCase):
class ClassicalDamageTestCase(CalculatorTestCase):
# all the tests here are similar
+ @classmethod
+ def setUpClass(cls):
+ cls.duration = numpy.zeros(2) # hazard, risk
+
def check(self, case):
out = self.run_calc(
case.__file__, 'job_haz.ini,job_risk.ini', exports='csv',
concurrent_tasks='0') # avoid the usual fork issue
+ self.__class__.duration += self.duration
[fname] = out['damages-rlzs', 'csv']
self.assertEqualFiles('expected/damages.csv', fname)
@@ -164,3 +169,7 @@ class ClassicalDamageTestCase(CalculatorTestCase):
@attr('qa', 'risk', 'classical_damage')
def test_case_7c(self):
self.check(case_7c)
+
+ @classmethod
+ def tearDownClass(cls):
+ print('duration (hazard, risk) =', cls.duration)
|
Printed information about hazard/risk times
|
gem_oq-engine
|
train
|
339131c660950cef894b13bc0422c8ae49f7766b
|
diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java b/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java
index <HASH>..<HASH> 100644
--- a/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java
+++ b/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java
@@ -36,6 +36,7 @@ import java.util.Map;
import java.util.NoSuchElementException;
import java.util.WeakHashMap;
import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* The default {@link ChannelPipeline} implementation. It is usually created
@@ -56,6 +57,9 @@ public class DefaultChannelPipeline implements ChannelPipeline {
}
};
+ private static final AtomicReferenceFieldUpdater<DefaultChannelPipeline, MessageSizeEstimator.Handle> ESTIMATOR =
+ AtomicReferenceFieldUpdater.newUpdater(
+ DefaultChannelPipeline.class, MessageSizeEstimator.Handle.class, "estimatorHandle");
final AbstractChannelHandlerContext head;
final AbstractChannelHandlerContext tail;
@@ -65,7 +69,7 @@ public class DefaultChannelPipeline implements ChannelPipeline {
private final boolean touch = ResourceLeakDetector.isEnabled();
private Map<EventExecutorGroup, EventExecutor> childExecutors;
- private MessageSizeEstimator.Handle estimatorHandle;
+ private volatile MessageSizeEstimator.Handle estimatorHandle;
private boolean firstRegistration = true;
/**
@@ -97,10 +101,14 @@ public class DefaultChannelPipeline implements ChannelPipeline {
}
final MessageSizeEstimator.Handle estimatorHandle() {
- if (estimatorHandle == null) {
- estimatorHandle = channel.config().getMessageSizeEstimator().newHandle();
+ MessageSizeEstimator.Handle handle = estimatorHandle;
+ if (handle == null) {
+ handle = channel.config().getMessageSizeEstimator().newHandle();
+ if (!ESTIMATOR.compareAndSet(this, null, handle)) {
+ handle = estimatorHandle;
+ }
}
- return estimatorHandle;
+ return handle;
}
final Object touch(Object msg, AbstractChannelHandlerContext next) {
|
DefaultChannelPipeline.estimatorHandle needs to be volatile
Motivation:
DefaultChannelPipeline.estimatorHandle needs to be volatile as its accessed from different threads.
Modifications:
Make DefaultChannelPipeline.estimatorHandle volatile and correctly init it via CAS
Result:
No more race.
|
netty_netty
|
train
|
8617e1d27349fe55ca9748d85ebdda42fe49345d
|
diff --git a/tests/InvoiceTest.php b/tests/InvoiceTest.php
index <HASH>..<HASH> 100644
--- a/tests/InvoiceTest.php
+++ b/tests/InvoiceTest.php
@@ -27,9 +27,15 @@ class InvoiceTest extends PHPUnit_Framework_TestCase {
*/
function __construct()
{
+ $this->newId1 = '2015-02-14-0001';
+ $this->newId2 = '2015-02-14-0002';
+
$this->customer = m::mock('QuanticTelecom\Invoices\Contracts\CustomerInterface');
- $this->includingTaxInvoice = new IncludingTaxInvoice($this->customer);
- $this->excludingTaxInvoice = new ExcludingTaxInvoice($this->customer);
+ $this->idGenerator = m::mock('QuanticTelecom\Invoices\Contracts\IdGeneratorInterface');
+ $this->idGenerator->shouldReceive('generateNewId')->times(2)->andReturn($this->newId1, $this->newId2);
+
+ $this->includingTaxInvoice = new IncludingTaxInvoice($this->idGenerator, $this->customer);
+ $this->excludingTaxInvoice = new ExcludingTaxInvoice($this->idGenerator, $this->customer);
}
public function tearDown()
@@ -40,6 +46,16 @@ class InvoiceTest extends PHPUnit_Framework_TestCase {
/**
* @test
*/
+ public function it_creates_an_invoice_with_an_id()
+ {
+ $this->assertEquals($this->newId1, $this->includingTaxInvoice->getId());
+
+ $this->assertEquals($this->newId2, $this->excludingTaxInvoice->getId());
+ }
+
+ /**
+ * @test
+ */
public function it_creates_an_invoice_with_O_total()
{
$this->assertEquals(0, $this->includingTaxInvoice->getExcludingTaxTotalPrice());
|
test: create a new invoice with a new ID
|
QuanticTelecom_invoices
|
train
|
d37d0a9829a76333c29d3416f53a15b7bf058167
|
diff --git a/generators/entity/prompts.js b/generators/entity/prompts.js
index <HASH>..<HASH> 100644
--- a/generators/entity/prompts.js
+++ b/generators/entity/prompts.js
@@ -580,7 +580,7 @@ function askForField(done) {
return false;
},
type: 'input',
- name: 'fieldType',
+ name: 'enumType',
validate: input => {
if (input === '') {
return 'Your class name cannot be empty.';
@@ -877,7 +877,7 @@ function askForField(done) {
const field = {
fieldName: props.fieldName,
- fieldType: props.fieldType,
+ fieldType: props.enumType || props.fieldType,
fieldTypeBlobContent: props.fieldTypeBlobContent,
fieldValues: props.fieldValues,
fieldValidateRules: props.fieldValidateRules,
|
Fix enum prompt not asking for type. (#<I>)
|
jhipster_generator-jhipster
|
train
|
7cc4fd6191d8e49b1fba6bd43495df905745b9c3
|
diff --git a/lib/alchemy/resource.rb b/lib/alchemy/resource.rb
index <HASH>..<HASH> 100644
--- a/lib/alchemy/resource.rb
+++ b/lib/alchemy/resource.rb
@@ -115,7 +115,11 @@ module Alchemy
def attributes
@_attributes ||= self.model.columns.collect do |col|
unless self.skip_attributes.include?(col.name)
- { :name => col.name, :type => resource_relation_type(col.name) || col.type, :relation => resource_relation(col.name) }.delete_if { |k, v | v.nil? }
+ {
+ name: col.name,
+ type: resource_column_type(col),
+ relation: resource_relation(col.name)
+ }.delete_if { |k, v| v.nil? }
end
end.compact
end
@@ -152,8 +156,7 @@ module Alchemy
false
end
-
- private
+ private
def guess_model_from_controller_path
resource_array.join('/').classify.constantize
@@ -171,6 +174,10 @@ module Alchemy
resource_relation(column_name).try(:[], :attr_type)
end
+ def resource_column_type(col)
+ resource_relation_type(col.name) || col.array ? :array : col.type
+ end
+
def resource_relation(column_name)
resource_relations[column_name.to_sym] if resource_relations
end
diff --git a/spec/libraries/resource_spec.rb b/spec/libraries/resource_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/libraries/resource_spec.rb
+++ b/spec/libraries/resource_spec.rb
@@ -39,18 +39,20 @@ end
module Alchemy
describe Resource do
+ let(:columns) do
+ [
+ double(:column, {name: 'name', type: :string, array: false}),
+ double(:column, {name: 'hidden_value', type: :string, array: false}),
+ double(:column, {name: 'description', type: :string, array: false}),
+ double(:column, {name: 'id', type: :integer, array: false}),
+ double(:column, {name: 'starts_at', type: :datetime, array: false}),
+ double(:column, {name: 'location_id', type: :integer, array: false}),
+ double(:column, {name: 'organizer_id', type: :integer, array: false}),
+ ]
+ end
before :each do
# stubbing an ActiveRecord::ModelSchema...
- columns = [
- double(:column, {:name => 'name', :type => :string}),
- double(:column, {:name => 'hidden_value', :type => :string}),
- double(:column, {:name => 'description', :type => :string}),
- double(:column, {:name => 'id', :type => :integer}),
- double(:column, {:name => 'starts_at', :type => :datetime}),
- double(:column, {:name => 'location_id', :type => :integer}),
- double(:column, {:name => 'organizer_id', :type => :integer}),
- ]
Party.stub(:columns).and_return columns
end
@@ -188,7 +190,7 @@ module Alchemy
describe "#attributes" do
let(:resource) { Resource.new("admin/parties") }
- it "parses and returns the resource-model's attributes from ActiveRecord::ModelSchema" do
+ it "parses and returns the resource model's attributes from ActiveRecord::ModelSchema" do
resource.attributes.should == [
{:name => "name", :type => :string},
{:name => "hidden_value", :type => :string},
@@ -207,7 +209,6 @@ module Alchemy
end
end
-
describe "#skip_attributes" do
let(:resource) { Resource.new("admin/parties") }
@@ -237,21 +238,35 @@ module Alchemy
custom_skipped_attributes = %W[hidden_name]
resource.skip_attributes = custom_skipped_attributes
end
-
end
describe "#searchable_attributes" do
+ subject { resource.searchable_attributes }
+
+ let(:resource) { Resource.new("admin/parties") }
+ before { resource.skip_attributes = [] }
+
it "returns all attributes of type string" do
- resource = Resource.new("admin/parties")
- resource.skip_attributes = []
- resource.searchable_attributes.should == [
+ should == [
{:name => "name", :type => :string},
{:name => "hidden_value", :type => :string},
{:name => "description", :type => :string}
]
end
- end
+ context "with an array attribute" do
+ let(:columns) do
+ [
+ double(:column, {name: 'name', type: :string, array: false}),
+ double(:column, {name: 'languages', type: :string, array: true})
+ ]
+ end
+
+ it "does not include this column" do
+ should == [{name: "name", type: :string}]
+ end
+ end
+ end
end
end
end
|
Fix search for resources having a postgresql array column.
|
AlchemyCMS_alchemy_cms
|
train
|
f057073552bbd4f2f76f1164ac68d07eefcd0522
|
diff --git a/core/block_dragger.js b/core/block_dragger.js
index <HASH>..<HASH> 100644
--- a/core/block_dragger.js
+++ b/core/block_dragger.js
@@ -189,18 +189,12 @@ Blockly.BlockDragger.prototype.dragBlock = function(e, currentDragDeltaXY) {
this.deleteArea_ = this.workspace_.isDeleteArea(e);
var isOutside = this.workspace_.isOutside(e);
- if (isOutside) {
- // Let mouse events through to GUI
- this.draggingBlock_.svgGroup_.setAttribute("pointer-events", "none");
- } else {
- this.draggingBlock_.svgGroup_.setAttribute("pointer-events", "auto");
- }
this.draggedConnectionManager_.update(delta, this.deleteArea_, isOutside);
if (!this.draggedConnectionManager_.wouldDeleteBlock() && !this.draggedConnectionManager_.closestConnection_) {
this.fireDragEvent_(isOutside);
}
- this.updateCursorDuringBlockDrag_();
+ this.updateCursorDuringBlockDrag_(isOutside);
};
/**
@@ -215,7 +209,7 @@ Blockly.BlockDragger.prototype.endBlockDrag = function(e, currentDragDeltaXY) {
this.dragBlock(e, currentDragDeltaXY);
this.dragIconData_ = [];
this.fireEndDragEvent_();
- this.draggingBlock_.svgGroup_.setAttribute("pointer-events", "auto");
+ this.draggingBlock_.setMouseThroughStyle(false);
Blockly.BlockSvg.disconnectUiStop_();
@@ -332,9 +326,11 @@ Blockly.BlockDragger.prototype.maybeDeleteBlock_ = function() {
/**
* Update the cursor (and possibly the trash can lid) to reflect whether the
* dragging block would be deleted if released immediately.
+ * @param {boolean} isOutside True if the cursor is to the right of the workspace
* @private
*/
-Blockly.BlockDragger.prototype.updateCursorDuringBlockDrag_ = function() {
+Blockly.BlockDragger.prototype.updateCursorDuringBlockDrag_ = function(isOutside) {
+ debugger;
this.wouldDeleteBlock_ = this.draggedConnectionManager_.wouldDeleteBlock();
var trashcan = this.workspace_.trashcan;
if (this.wouldDeleteBlock_) {
@@ -348,6 +344,13 @@ Blockly.BlockDragger.prototype.updateCursorDuringBlockDrag_ = function() {
trashcan.setOpen_(false);
}
}
+
+ if (isOutside) {
+ // Let mouse events through to GUI
+ this.draggingBlock_.setMouseThroughStyle(true);
+ } else {
+ this.draggingBlock_.setMouseThroughStyle(false);
+ }
};
/**
diff --git a/core/block_svg.js b/core/block_svg.js
index <HASH>..<HASH> 100644
--- a/core/block_svg.js
+++ b/core/block_svg.js
@@ -1161,6 +1161,22 @@ Blockly.BlockSvg.prototype.removeSelect = function() {
/**
* Update the cursor over this block by adding or removing a class.
+ * @param {boolean} letMouseEventsThrough True if the blocks should ignore pointer
+ * events, false otherwise.
+ * @package
+ */
+Blockly.BlockSvg.prototype.setMouseThroughStyle = function(letMouseThrough) {
+ if (letMouseThrough) {
+ Blockly.utils.addClass(/** @type {!Element} */ (this.svgGroup_),
+ 'blocklyDraggingMouseThrough');
+ } else {
+ Blockly.utils.removeClass(/** @type {!Element} */ (this.svgGroup_),
+ 'blocklyDraggingMouseThrough');
+ }
+};
+
+/**
+ * Update the cursor over this block by adding or removing a class.
* @param {boolean} enable True if the delete cursor should be shown, false
* otherwise.
* @package
diff --git a/core/css.js b/core/css.js
index <HASH>..<HASH> 100644
--- a/core/css.js
+++ b/core/css.js
@@ -425,6 +425,10 @@ Blockly.Css.CONTENT = [
'cursor: url("<<<PATH>>>/handdelete.cur"), auto;',
'}',
+ '.blocklyDragging.blocklyDraggingMouseThrough {',
+ 'pointer-events: none;',
+ '}',
+
'.blocklyToolboxDelete {',
'cursor: url("<<<PATH>>>/handdelete.cur"), auto;',
'}',
|
Move style change to block css
|
LLK_scratch-blocks
|
train
|
5c53c58169a35b9fc5f795a401137b5613216ff4
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -10,20 +10,20 @@ function isEmpty(object) {
}
module.exports = function(url, callback) {
- if (url.length <= 0 || typeof url != 'string') {
+ if (url.length <= 0 || typeof url !== 'string') {
throw Error("A valid URL is required");
}
- if (typeof callback != "function") {
+ if (typeof callback !== "function") {
throw Error("Callback function is required");
}
var req = https.get({hostname: url, agent: false}, function (res) {
var certificate = res.socket.getPeerCertificate();
if(isEmpty(certificate) || certificate === null) {
- callback({message: 'The website did not provide a certificate'}, null);
+ return callback({message: 'The website did not provide a certificate'}, null);
} else {
- callback(null, certificate);
+ return callback(null, certificate);
}
});
|
uses strict equality operators and adds explicit return
|
johncrisostomo_get-ssl-certificate
|
train
|
a5f913b6b1643443f14aafce5f73fc20ec0a95fa
|
diff --git a/spec/Suite/Reporter/Coverage/MetricsSpec.php b/spec/Suite/Reporter/Coverage/MetricsSpec.php
index <HASH>..<HASH> 100644
--- a/spec/Suite/Reporter/Coverage/MetricsSpec.php
+++ b/spec/Suite/Reporter/Coverage/MetricsSpec.php
@@ -242,7 +242,7 @@ describe("Metrics", function () {
});
- it("doesn't store interfaces in metrics", function () {
+ it("ignores interfaces metrics", function () {
$path = [
'spec/Fixture/Reporter/Coverage/ImplementsCoverage.php',
@@ -261,14 +261,14 @@ describe("Metrics", function () {
$collector->stop();
$metrics = $collector->metrics();
- $actual = $metrics->get()->data();
+ $actual = $metrics->get('Kahlan\Spec\Fixture\Reporter\Coverage\ImplementsCoverage')->data();
$files = $actual['files'];
unset($actual['files']);
expect($actual)->toBe([
- 'loc' => 11,
- 'nlloc' => 10,
+ 'loc' => 6,
+ 'nlloc' => 5,
'lloc' => 1,
'cloc' => 1,
'coverage' => 1,
@@ -280,6 +280,8 @@ describe("Metrics", function () {
$path = realpath('spec/Fixture/Reporter/Coverage/ImplementsCoverage.php');
expect(isset($files[$path]))->toBe(true);
+ expect($metrics->get('Kahlan\Spec\Fixture\Reporter\Coverage\ImplementsCoverageInterface'))->toBe(null);
+
});
describe("->children()", function () {
diff --git a/src/Reporter/Coverage/Collector.php b/src/Reporter/Coverage/Collector.php
index <HASH>..<HASH> 100644
--- a/src/Reporter/Coverage/Collector.php
+++ b/src/Reporter/Coverage/Collector.php
@@ -362,13 +362,14 @@ class Collector
$path = "{$path}" . $node->name . '\\';
$this->_processTree($file, $node->tree, $coverage, $path);
} elseif ($node->hasMethods) {
+ if ($node->type === 'interface') {
+ return;
+ }
$path = "{$path}" . $node->name;
$this->_processTree($file, $node->tree, $coverage, $path);
} elseif ($node->type === 'function') {
$prefix = $node->isMethod ? "{$path}::" : "{$path}";
$path = $prefix . $node->name . '()';
- } elseif ($node->type === 'interface') {
- return;
} else {
$this->_processTree($file, $node->tree, $coverage, '');
}
|
Stop collecting coverage data for interfaces.
|
kahlan_kahlan
|
train
|
3b3ca9f8261c9e8810f5ae1e29afa98de1c98f3e
|
diff --git a/tests/MultiRequestTest.php b/tests/MultiRequestTest.php
index <HASH>..<HASH> 100644
--- a/tests/MultiRequestTest.php
+++ b/tests/MultiRequestTest.php
@@ -13,14 +13,18 @@ namespace chillerlan\TinyCurlTest;
use chillerlan\TinyCurl\{MultiRequest, MultiRequestOptions, URL};
use PHPUnit\Framework\TestCase;
-abstract class MultiRequestTest extends TestCase{
+class MultiRequestTest extends TestCase{
+ /**
+ * @var \chillerlan\TinyCurl\MultiRequestOptions
+ */
protected $options;
protected function setUp(){
- $this->options = new MultiRequestOptions;
- $this->options->handler = MultiResponseHandlerTest::class;
- $this->options->ca_info = __DIR__.'/test-cacert.pem';
+ $this->options = new MultiRequestOptions([
+ 'handler' => MultiResponseHandlerTest::class,
+ 'ca_info' => __DIR__.'/test-cacert.pem',
+ ]);
}
protected function getURLs(){
@@ -43,6 +47,7 @@ abstract class MultiRequestTest extends TestCase{
public function testMultiResponseHandler(){
$this->options->window_size = 3;
+ $this->options->sleep = 60 / 300 * 1000000;
$request = new MultiRequest($this->options);
$request->fetch($this->getURLs());
|
reactivated MultiRequestTest
|
chillerlan_php-curl
|
train
|
c7f705b201c068d205de09a7a3911bccbf9e8916
|
diff --git a/demo/demoPages/components/TimePickerPage.js b/demo/demoPages/components/TimePickerPage.js
index <HASH>..<HASH> 100644
--- a/demo/demoPages/components/TimePickerPage.js
+++ b/demo/demoPages/components/TimePickerPage.js
@@ -63,22 +63,20 @@ class TimePickerPage extends Component {
<h2>TimePicker (basic time): </h2>
<TimePicker
id = "someGiantId1"
- timeFormat = "hh:mm"
inputState = {inputState}
- labelText = "Select time"
+ labelText = "Select time (hh:mm)"
timepickerValue = {timepickerValue1}
changeHandler = {time => this.setState({ timepickerValue1: time })}
infoMessage = {text.textInputInfoMessage}
errorMessage = {text.textInputErrorMessage}
/>
- <p className="code">{`<TimePicker id = "someGiantId" timeFormat = "hh:mm" inputState = "default" labelText = "Select time" timepickerValue = {this.state.timepickerValue3} changeHandler = {() => console.log("TimePicker-(basic)-changed!!")} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
+ <p className="code">{`<TimePicker id = "someGiantId" inputState = "default" labelText = "Select time (hh:mm)" timepickerValue = {this.state.timepickerValue3} changeHandler = {() => console.log("TimePicker-(basic)-changed!!")} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
<h2>TimePicker (basic time range): </h2>
<TimePicker
id = "someGiantId2"
- timeFormat = "hh:mm"
inputState = {inputState}
- labelText = "Select time"
+ labelText = "Select time (hh:mm)"
timepickerValue = {timepickerValue2}
changeHandler = {time => this.setState({ timepickerValue2: time })}
infoMessage = {text.textInputInfoMessage}
@@ -86,15 +84,14 @@ class TimePickerPage extends Component {
/>
<TimePicker
id = "someGiantId3"
- timeFormat = "hh:mm"
inputState = {inputState}
- labelText = "Select time"
+ labelText = "Select time (hh:mm)"
timepickerValue = {timepickerValue3}
changeHandler = {time => this.setState({ timepickerValue3: time })}
infoMessage = {text.textInputInfoMessage}
errorMessage = {text.textInputErrorMessage}
/>
- <p className="code">{`<TimePicker fancy = {true} id = "someGiantId" dateFormat = "hh:mm" inputState = "default" labelText = "Select time" datepickerValue = {this.state.datepickerValue4} changeHandler = {() => console.log("TimePicker-(basic)-changed!!")} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
+ <p className="code">{`<TimePicker fancy = {true} id = "someGiantId" inputState = "default" labelText = "Select time (hh:mm)" datepickerValue = {this.state.datepickerValue4} changeHandler = {() => console.log("TimePicker-(basic)-changed!!")} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
</div>
</div>
diff --git a/src/components/TimePicker/TimePicker.js b/src/components/TimePicker/TimePicker.js
index <HASH>..<HASH> 100644
--- a/src/components/TimePicker/TimePicker.js
+++ b/src/components/TimePicker/TimePicker.js
@@ -51,8 +51,8 @@ export default class TimePicker extends Component {
const { inputStyle, labelStyleTmp, displayOpen, timepickerValue,
containerStyle, placeholder } = this.state;
- const { className, inputState, id, labelText, timeFormat, infoMessage,
- errorMessage, twentyFourHour, TWENTYFOUR_HOURS, HOURS, disableLabel
+ const { className, inputState, id, labelText, infoMessage, errorMessage,
+ twentyFourHour, TWENTYFOUR_HOURS, HOURS, disableLabel
} = this.props;
const em = (inputState === 'error' && errorMessage) ? `errMsg-${id} ` : '';
@@ -70,7 +70,7 @@ export default class TimePicker extends Component {
ref={(dom) => this.container = dom}
>
<label className={`${labelStyleTmp}${labelCheck}`} htmlFor={id}>
- {`${labelText} (${timeFormat})`}
+ {labelText}
</label>
<div className={containerStyle}>
@@ -131,7 +131,6 @@ TimePicker.defaultProps = {
TimePicker.propTypes = {
id : PropTypes.string.isRequired,
labelText : PropTypes.string.isRequired,
- timeFormat : PropTypes.string.isRequired,
changeHandler : PropTypes.func.isRequired,
infoMessage : PropTypes.string,
errorMessage : PropTypes.string,
|
refactor: Consolidate labelText and timeFormat into one prop
|
Pearson-Higher-Ed_elements-sdk
|
train
|
a1fa1fa421cb5ddeeafa2f6d5c830da186e3618b
|
diff --git a/lib/dentaku/bulk_expression_solver.rb b/lib/dentaku/bulk_expression_solver.rb
index <HASH>..<HASH> 100644
--- a/lib/dentaku/bulk_expression_solver.rb
+++ b/lib/dentaku/bulk_expression_solver.rb
@@ -39,7 +39,7 @@ module Dentaku
def load_results(&block)
variables_in_resolve_order.each_with_object({}) do |var_name, r|
begin
- r[var_name] = calculator.evaluate(var_name) || evaluate!(expressions[var_name], r)
+ r[var_name] = calculator.memory[var_name] || evaluate!(expressions[var_name], r)
rescue Dentaku::UnboundVariableError, ZeroDivisionError => ex
r[var_name] = block.call(ex)
end
diff --git a/spec/bulk_expression_solver_spec.rb b/spec/bulk_expression_solver_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/bulk_expression_solver_spec.rb
+++ b/spec/bulk_expression_solver_spec.rb
@@ -28,6 +28,12 @@ RSpec.describe Dentaku::BulkExpressionSolver do
described_class.new(expressions, {}).solve!
}.to raise_error(ZeroDivisionError)
end
+
+ it "does not require keys to be parseable" do
+ expressions = { "the value of x, incremented" => "x + 1" }
+ solver = described_class.new(expressions, "x" => 3)
+ expect(solver.solve!).to eq({ "the value of x, incremented" => 4 })
+ end
end
describe "#solve" do
|
allow arbitrary keys for systems of equations
|
rubysolo_dentaku
|
train
|
d1d1c37807d6f9959b13414f50fcc283b244e711
|
diff --git a/lib/actions/ActionChangeElement.js b/lib/actions/ActionChangeElement.js
index <HASH>..<HASH> 100644
--- a/lib/actions/ActionChangeElement.js
+++ b/lib/actions/ActionChangeElement.js
@@ -9,13 +9,22 @@ const Action = require('./Action');
class ActionChangeElement extends Action {
async perform () {
- const changeStyleOptions = this._options.change || {};
- return this._env.evaluateJs(this._selector, changeStyleOptions, /* istanbul ignore next */ function (selector, changeStyleOptions) {
- const element = Sizzle(selector)[0];
- Object.keys(changeStyleOptions).forEach(function (key) {
- element.style[key] = changeStyleOptions[key];
- });
- });
+ const changeStyleOptions = this._options.change || this._options.style || {};
+ const changeAttrOptions = this._options.attr || {};
+ return this._env.evaluateJs(this._selector, changeStyleOptions, changeAttrOptions,
+ /* istanbul ignore next */
+ function (selector, changeStyleOptions, changeAttrOptions) {
+ const element = Sizzle(selector)[0];
+ if (!element) {
+ return;
+ }
+ Object.keys(changeStyleOptions).forEach(function (key) {
+ element.style[key] = changeStyleOptions[key];
+ });
+ Object.keys(changeAttrOptions).forEach(function (key) {
+ element.setAttribute(key, changeAttrOptions[key]);
+ });
+ });
}
}
diff --git a/test/integration/actions/actions.test.js b/test/integration/actions/actions.test.js
index <HASH>..<HASH> 100644
--- a/test/integration/actions/actions.test.js
+++ b/test/integration/actions/actions.test.js
@@ -427,4 +427,74 @@ describe('Actions', () => {
expect(result).toEqual('12345');
});
});
+
+ describe('ActionChangeElement', () => {
+ test('change style, attr', async () => {
+ setServerResponse({
+ html: `<img src="12345" />`,
+ });
+ const result = await parser.parse({
+ url,
+ actions: [
+ {
+ type: 'changeElement',
+ scope: 'img',
+ style: {
+ display: 'none',
+ },
+ attr: {
+ alt: 'test',
+ },
+ },
+ ],
+ rules: {
+ collection: [
+ {
+ name: 'alt',
+ scope: 'img',
+ attr: 'alt',
+ },
+ {
+ name: 'style',
+ scope: 'img',
+ attr: 'style',
+ },
+ ],
+ },
+ });
+
+ expect(result).toEqual({ alt: 'test', style: 'display: none;' });
+ });
+
+ test('change nothing', async () => {
+ setServerResponse({
+ html: `<img src="12345" />`,
+ });
+ const result = await parser.parse({
+ url,
+ actions: [
+ {
+ type: 'changeElement',
+ scope: 'img',
+ },
+ ],
+ rules: {
+ collection: [
+ {
+ name: 'alt',
+ scope: 'img',
+ attr: 'alt',
+ },
+ {
+ name: 'style',
+ scope: 'img',
+ attr: 'style',
+ },
+ ],
+ },
+ });
+
+ expect(result).toEqual({ alt: null, style: null });
+ });
+ });
});
|
- ActionChangeElement - added ability to change style and attr of any element
:goose:
|
redco_goose-parser
|
train
|
d369821027459197020cb07639cecc50c847632b
|
diff --git a/src/Rollerworks/Bundle/MultiUserBundle/DependencyInjection/Factory/UserServicesFactory.php b/src/Rollerworks/Bundle/MultiUserBundle/DependencyInjection/Factory/UserServicesFactory.php
index <HASH>..<HASH> 100644
--- a/src/Rollerworks/Bundle/MultiUserBundle/DependencyInjection/Factory/UserServicesFactory.php
+++ b/src/Rollerworks/Bundle/MultiUserBundle/DependencyInjection/Factory/UserServicesFactory.php
@@ -434,7 +434,7 @@ class UserServicesFactory
if (isset($config['confirmation']['from_email'])) {
// overwrite the global one
- $fromEmail = $config['email']['from_email'];
+ $fromEmail = $config['confirmation']['from_email'];
unset($config['confirmation']['from_email']);
}
|
fix wrong configuration usage for registration-confirmation
|
rollerworks-graveyard_RollerworksMultiUserBundle
|
train
|
22364d154c9d0a721f7e47b62df5b89a19e3e07b
|
diff --git a/lib/lhc/response.rb b/lib/lhc/response.rb
index <HASH>..<HASH> 100644
--- a/lib/lhc/response.rb
+++ b/lib/lhc/response.rb
@@ -4,8 +4,6 @@ require 'typhoeus'
# In this case we abstract the thphoues response.
class LHC::Response
- @raw
-
attr_accessor :request
def initialize(raw, request)
@@ -61,12 +59,6 @@ class LHC::Response
private
- def raw=(raw)
- @raw = raw
- end
-
- def raw
- @raw
- end
+ attr_accessor :raw
end
|
refactor attr_accessor raw
|
local-ch_lhc
|
train
|
ca53e70c3b46d5876a30ebe8cf2e0e2c656a9e27
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -99,27 +99,25 @@ NodeID3.prototype.read = function(filebuffer) {
filebuffer = fs.readFileSync(filebuffer);
var header = new Buffer(10);
filebuffer.copy(header, 0, getID3Start(filebuffer))
- frameSize = getFrameSize(header);
+ var frameSize = getFrameSize(header);
var ID3Frame = new Buffer(frameSize + 1);
filebuffer.copy(ID3Frame, 0, getID3Start(filebuffer));
- var tags = TIF;
- var frames = Object.keys(tags);
+ var tags = {};
+ var frames = Object.keys(TIF);
for(var i = 0; i < frames.length; i++) {
- var frameStart = ID3Frame.indexOf(tags[frames[i]]);
- if(frameStart > -1) {
- var frameSize = decodeSize(new Buffer([ID3Frame[frameStart + 4], ID3Frame[frameStart + 5], ID3Frame[frameStart + 6], ID3Frame[frameStart + 7]]));
- var offset = 1;
- if(ID3Frame[frameStart + 11] == 0xFF || ID3Frame[frameStart + 12] == 0xFE) {
- offset = 3;
- }
- var frame = new Buffer(frameSize - offset);
- ID3Frame.copy(frame, 0, frameStart + 10 + offset);
-
- tags[frames[i]] = frame.toString('utf8').replace(/\0/g, "");
- } else {
- delete tags[frames[i]];
+ var frameStart = ID3Frame.indexOf(TIF[frames[i]]);
+ if(frameStart == -1) continue;
+
+ frameSize = decodeSize(new Buffer([ID3Frame[frameStart + 4], ID3Frame[frameStart + 5], ID3Frame[frameStart + 6], ID3Frame[frameStart + 7]]));
+ var offset = 1;
+ if(ID3Frame[frameStart + 11] == 0xFF || ID3Frame[frameStart + 12] == 0xFE) {
+ offset = 3;
}
+ var frame = new Buffer(frameSize - offset);
+ ID3Frame.copy(frame, 0, frameStart + 10 + offset);
+
+ tags[frames[i]] = frame.toString('utf8').replace(/\0/g, "");
}
/*if(ID3Frame.indexOf("APIC")) {
|
FIX: Stop read() mutating the TIF object.
The tags variable is a reference to the TIF object. As tags updated with the results from the file so does the TIF object. Further calls to read search the buffer for the last tag results instead of the correct frame information.
|
Zazama_node-id3
|
train
|
b3ba986d5c03085100dee86f6731b7d05f7891d2
|
diff --git a/python/orca/src/bigdl/orca/tfpark/__init__.py b/python/orca/src/bigdl/orca/tfpark/__init__.py
index <HASH>..<HASH> 100644
--- a/python/orca/src/bigdl/orca/tfpark/__init__.py
+++ b/python/orca/src/bigdl/orca/tfpark/__init__.py
@@ -13,3 +13,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+
+from zoo.pipeline.api.net import TFDataset
+from zoo.tfpark.model import KerasModel
diff --git a/python/orca/src/bigdl/orca/tfpark/model.py b/python/orca/src/bigdl/orca/tfpark/model.py
index <HASH>..<HASH> 100644
--- a/python/orca/src/bigdl/orca/tfpark/model.py
+++ b/python/orca/src/bigdl/orca/tfpark/model.py
@@ -23,9 +23,9 @@ import tensorflow as tf
import numpy as np
-class Model(object):
+class KerasModel(object):
- def __init__(self, model=None):
+ def __init__(self, model):
self.model = model
metrics_tensors = [
self.model.metrics_tensors[m] for m in range(len(self.model.metrics_names) - 1)
@@ -40,6 +40,7 @@ class Model(object):
self.metrics_tensors = [repeat(x, batch_size[0]) for x in metrics_tensors]
self.tf_optimizer = None
+ self.tf_optimizer_done_epochs = 0
@classmethod
def from_keras(cls, model):
@@ -114,7 +115,10 @@ class Model(object):
val_spilt=validation_split, **kwargs)
else:
self.tf_optimizer.refresh_weights()
- self.tf_optimizer.optimize(MaxEpoch(epochs))
+
+ end_epoch = self.tf_optimizer_done_epochs + epochs
+ self.tf_optimizer.optimize(MaxEpoch(end_epoch))
+ self.tf_optimizer_done_epochs = end_epoch
def evaluate(self,
x=None,
|
TFPark follow up (#<I>)
* address comments
* fix style
|
intel-analytics_BigDL
|
train
|
b6773373d4bfc50a1c9a2233618154b3b8904613
|
diff --git a/shared/api/event_lifecycle.go b/shared/api/event_lifecycle.go
index <HASH>..<HASH> 100644
--- a/shared/api/event_lifecycle.go
+++ b/shared/api/event_lifecycle.go
@@ -96,6 +96,12 @@ const (
EventLifecycleStoragePoolCreated = "storage-pool-created"
EventLifecycleStoragePoolDeleted = "storage-pool-deleted"
EventLifecycleStoragePoolUpdated = "storage-pool-updated"
+ EventLifecycleStorageBucketCreated = "storage-bucket-created"
+ EventLifecycleStorageBucketUpdated = "storage-bucket-updated"
+ EventLifecycleStorageBucketDeleted = "storage-bucket-deleted"
+ EventLifecycleStorageBucketKeyCreated = "storage-bucket-key-created"
+ EventLifecycleStorageBucketKeyUpdated = "storage-bucket-key-updated"
+ EventLifecycleStorageBucketKeyDeleted = "storage-bucket-key-deleted"
EventLifecycleStorageVolumeCreated = "storage-volume-created"
EventLifecycleStorageVolumeBackupCreated = "storage-volume-backup-created"
EventLifecycleStorageVolumeBackupDeleted = "storage-volume-backup-deleted"
|
shared/api/event/lifecycle: Add bucket constants
|
lxc_lxd
|
train
|
1d9f2a2b984913e2e50f4a2eea2943739fecfc24
|
diff --git a/tests/Application/ApplicationTest.php b/tests/Application/ApplicationTest.php
index <HASH>..<HASH> 100644
--- a/tests/Application/ApplicationTest.php
+++ b/tests/Application/ApplicationTest.php
@@ -55,6 +55,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->route->isMatch('/')->willReturn(true);
$app = new Application([$this->route->reveal()]);
+ $app->setLogger(new VoidLogger);
$response = $app->handle($this->request->reveal());
$this->assertSame(405, $response->getStatusCode());
@@ -70,6 +71,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->route->isMatch('/')->willReturn(true);
$app = new Application([$this->route->reveal()], null, 'basic');
+ $app->setLogger(new VoidLogger);
$response = $app->handle($this->request->reveal());
$this->assertSame(401, $response->getStatusCode());
@@ -89,6 +91,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->route->isMatch('/')->willReturn(true);
$app = new Application([$this->route->reveal()], null, 'basic', 'bearer');
+ $app->setLogger(new VoidLogger);
$response = $app->handle($this->request->reveal());
$this->assertSame(407, $response->getStatusCode());
@@ -108,6 +111,7 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase
$this->route->isMatch('/')->willReturn(true);
$app = new Application([$this->route->reveal()]);
+ $app->setLogger(new VoidLogger);
$response = $app->handle($this->request->reveal());
$this->assertSame(428, $response->getStatusCode());
|
Add missing instance of ViodLogger to tests
|
phOnion_framework
|
train
|
3af80accb9595b9cb84a888d160eb8a29759824c
|
diff --git a/src/org/zaproxy/zap/view/table/HistoryReferencesTable.java b/src/org/zaproxy/zap/view/table/HistoryReferencesTable.java
index <HASH>..<HASH> 100644
--- a/src/org/zaproxy/zap/view/table/HistoryReferencesTable.java
+++ b/src/org/zaproxy/zap/view/table/HistoryReferencesTable.java
@@ -239,10 +239,15 @@ public class HistoryReferencesTable extends ZapTable {
return;
}
+ boolean focusOwner = isFocusOwner();
try {
displayMessage(hRef.getHttpMessage());
} catch (HttpMalformedHeaderException | DatabaseException e) {
LOGGER.error(e.getMessage(), e);
+ } finally {
+ if (focusOwner) {
+ requestFocusInWindow();
+ }
}
}
}
|
Set focus back to table after displaying a message
Change class HistoryReferencesTable.DisplayMessageOnSelectionValueChange
to request focus back to the table after displaying a message to allow
navigate the table entries with the keyboard more easily. The table
could lose focus if the message panel displayed a big request/response
body, requiring the user to transfer the focus through all the
components back to the table.
|
zaproxy_zaproxy
|
train
|
7a647a702c8af81ccf5d37b09c11529c6c0cb1b7
|
diff --git a/src/org/mockito/internal/util/reflection/GenericMaster.java b/src/org/mockito/internal/util/reflection/GenericMaster.java
index <HASH>..<HASH> 100644
--- a/src/org/mockito/internal/util/reflection/GenericMaster.java
+++ b/src/org/mockito/internal/util/reflection/GenericMaster.java
@@ -17,7 +17,12 @@ public class GenericMaster {
Type generic = field.getGenericType();
if (generic != null && generic instanceof ParameterizedType) {
Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
- return (Class) actual;
+ if (actual instanceof Class) {
+ return (Class) actual;
+ } else if (actual instanceof ParameterizedType) {
+ //in case of nested generics we don't go deep
+ return (Class) ((ParameterizedType) actual).getRawType();
+ }
}
return Object.class;
diff --git a/test/org/mockito/internal/util/reflection/GenericMasterTest.java b/test/org/mockito/internal/util/reflection/GenericMasterTest.java
index <HASH>..<HASH> 100644
--- a/test/org/mockito/internal/util/reflection/GenericMasterTest.java
+++ b/test/org/mockito/internal/util/reflection/GenericMasterTest.java
@@ -3,6 +3,7 @@ package org.mockito.internal.util.reflection;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -17,17 +18,25 @@ public class GenericMasterTest {
Set<Integer> two;
Map<Double, String> map;
String nonGeneric;
+ List<Set<String>> nested;
+ List<Set<Collection<String>>> multiNested;
@Test
public void shouldFindGenericClass() throws Exception {
- assertEquals(m.getGenericType(field("one")), String.class);
- assertEquals(m.getGenericType(field("two")), Integer.class);
- assertEquals(m.getGenericType(field("map")), Double.class);
+ assertEquals(String.class, m.getGenericType(field("one")));
+ assertEquals(Integer.class, m.getGenericType(field("two")));
+ assertEquals(Double.class, m.getGenericType(field("map")));
}
@Test
public void shouldGetObjectForNonGeneric() throws Exception {
- assertEquals(m.getGenericType(field("nonGeneric")), Object.class);
+ assertEquals(Object.class, m.getGenericType(field("nonGeneric")));
+ }
+
+ @Test
+ public void shouldDealWithNestedGenerics() throws Exception {
+ assertEquals(Set.class, m.getGenericType(field("nested")));
+ assertEquals(Set.class, m.getGenericType(field("multiNested")));
}
private Field field(String fieldName) throws SecurityException, NoSuchFieldException {
|
Fixed issue <I>
@Captor annotation should work OK with nested parametrized type
--HG--
extra : convert_revision : svn%3Aaa2aecf3-ea3e-<I>-9d<I>-<I>e7c<I>/trunk%<I>
|
mockito_mockito
|
train
|
6ccc4f4c1f8ecef7876a8949364cc29d894603a9
|
diff --git a/Qt.py b/Qt.py
index <HASH>..<HASH> 100644
--- a/Qt.py
+++ b/Qt.py
@@ -124,7 +124,7 @@ def _remap(object, name, value, safe=True):
"""
- if QT_TESTING is not None and safe:
+ if QT_TESTING and safe:
# Cannot alter original binding.
if hasattr(object, name):
raise AttributeError("Cannot override existing name: "
|
test QT_TESTING as boolean variable
|
mottosso_Qt.py
|
train
|
9c8602270df57b1a4929e253fd910d1fc0985f5f
|
diff --git a/ipyrad/analysis/bpp.py b/ipyrad/analysis/bpp.py
index <HASH>..<HASH> 100644
--- a/ipyrad/analysis/bpp.py
+++ b/ipyrad/analysis/bpp.py
@@ -1546,10 +1546,11 @@ class Bpp(object):
)
# do not allow any tips in node_dists:
- for nidx in node_dists:
- if ttre.idx_dict[nidx].is_leaf():
- raise IPyradError(
- "error in node_dists: cannot plot div time for tip nodes")
+ if node_dists:
+ for nidx in node_dists:
+ if ttre.idx_dict[nidx].is_leaf():
+ raise IPyradError(
+ "error in node_dists: cannot plot div time for tip nodes")
# setup plot dims
height = (275 if "height" not in kwargs else kwargs["height"])
|
allow empty node dist in bpp
|
dereneaton_ipyrad
|
train
|
d6aef1bc03e7cc64c2771314c607977d59996e4f
|
diff --git a/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/src/main/java/com/github/dockerjava/api/model/HostConfig.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/dockerjava/api/model/HostConfig.java
+++ b/src/main/java/com/github/dockerjava/api/model/HostConfig.java
@@ -27,6 +27,9 @@ public class HostConfig {
@JsonProperty("Privileged")
private boolean privileged;
+ @JsonProperty("ReadonlyRootfs")
+ private boolean readonlyRootfs;
+
@JsonProperty("Dns")
private String[] dns;
@@ -64,7 +67,7 @@ public class HostConfig {
}
public HostConfig(Bind[] binds, Link[] links, LxcConf[] lxcConf, Ports portBindings, boolean publishAllPorts,
- boolean privileged, String[] dns, String[] dnsSearch, VolumesFrom[] volumesFrom, String containerIDFile,
+ boolean privileged, boolean readonlyRootfs, String[] dns, String[] dnsSearch, VolumesFrom[] volumesFrom, String containerIDFile,
Capability[] capAdd, Capability[] capDrop, RestartPolicy restartPolicy, String networkMode, Device[] devices,
String[] extraHosts, Ulimit[] ulimits) {
this.binds = new Binds(binds);
@@ -73,6 +76,7 @@ public class HostConfig {
this.portBindings = portBindings;
this.publishAllPorts = publishAllPorts;
this.privileged = privileged;
+ this.readonlyRootfs = readonlyRootfs;
this.dns = dns;
this.dnsSearch = dnsSearch;
this.volumesFrom = volumesFrom;
@@ -95,7 +99,7 @@ public class HostConfig {
public LxcConf[] getLxcConf() {
return lxcConf;
}
-
+
public Ports getPortBindings() {
return portBindings;
}
@@ -108,6 +112,10 @@ public class HostConfig {
return privileged;
}
+ public boolean isReadonlyRootfs() {
+ return readonlyRootfs;
+ }
+
public String[] getDns() {
return dns;
}
@@ -183,6 +191,10 @@ public class HostConfig {
this.privileged = privileged;
}
+ public void setReadonlyRootfs(boolean readonlyRootfs) {
+ this.readonlyRootfs = readonlyRootfs;
+ }
+
public void setDns(String[] dns) {
this.dns = dns;
}
|
Added ReadonlyFs option.
|
docker-java_docker-java
|
train
|
f5eb8aa563cb7acb06a96240350737d74e0aec6d
|
diff --git a/common/services/resources/TagService.php b/common/services/resources/TagService.php
index <HASH>..<HASH> 100755
--- a/common/services/resources/TagService.php
+++ b/common/services/resources/TagService.php
@@ -91,14 +91,17 @@ class TagService extends \cmsgears\core\common\services\resources\TagService imp
$content = isset( $config[ 'content' ] ) ? $config[ 'content' ] : null;
- if( isset( $content ) ) {
-
- $config[ 'parent' ] = $model;
- $config[ 'parentType' ] = CoreGlobal::TYPE_TAG;
+ // Model content is required for all the tags to form tag page
+ if( !isset( $content ) ) {
- $this->modelContentService->create( $content, $config );
+ $content = new ModelContent();
}
+ $config[ 'parent' ] = $model;
+ $config[ 'parentType' ] = CoreGlobal::TYPE_TAG;
+
+ $this->modelContentService->create( $content, $config );
+
return $model;
}
|
Fixed missing model content when tags created by csv.
|
cmsgears_module-cms
|
train
|
7e03c1c0d77e0faf9de1822d8de3387655cd995c
|
diff --git a/lib/puppet/pops/adapters.rb b/lib/puppet/pops/adapters.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/pops/adapters.rb
+++ b/lib/puppet/pops/adapters.rb
@@ -126,26 +126,26 @@ module Adapters
# Finds the loader to use when loading originates from the source position of the given argument.
#
- # @param instance [Model::PopsObject] The model object
- # @param scope [Puppet::Parser::Scope] The scope to use
+ # @param [Model::PopsObject] instance The model object
+ # @param [Puppet::Parser::Scope] scope The scope to use
+ # @param [String] file the file from where the model was parsed
# @return [Loader,nil] the found loader or `nil` if it could not be found
#
- def self.loader_for_model_object(model, scope)
+ def self.loader_for_model_object(model, scope, file = nil)
if scope.nil?
loaders = Puppet.lookup(:loaders) { nil }
loaders.nil? ? nil : loaders.private_environment_loader
else
- # find the loader that loaded the code, or use the private_environment_loader (sees env + all modules)
- adapter = Utils.find_adapter(model, self)
- if adapter.nil?
- # Use source location to determine calling module, or use the private_environment_loader (sees env + all modules)
- # This is necessary since not all .pp files are loaded by a Loader (see PUP-1833)
- adapter = adapt_by_source(scope, model)
- end
- adapter.nil? ? scope.compiler.loaders.private_environment_loader : adapter.loader(scope)
+ loaders = scope.compiler.loaders
+ loader_name = loader_name_by_source(scope.environment, model, file)
+ loader_name.nil? ? loaders.private_environment_loader : loaders[loader_name]
end
end
+ class PathsAndNameCacheAdapter < Puppet::Pops::Adaptable::Adapter
+ attr_accessor :cache, :paths
+ end
+
# Attempts to find the module that `instance` originates from by looking at it's {SourcePosAdapter} and
# compare the `locator.file` found there with the module paths given in the environment found in the
# given `scope`. If the file is found to be relative to a path, then the first segment of the relative
@@ -156,32 +156,29 @@ module Adapters
#
# @param scope
# @param instance
- def self.adapt_by_source(scope, instance)
- source_pos = Utils.find_adapter(instance, SourcePosAdapter)
- unless source_pos.nil?
- mod = find_module_for_file(scope.environment, source_pos.locator.file)
- adapter = LoaderAdapter.adapt(source_pos.adapted)
- loaders = scope.compiler.loaders
- if mod.nil?
- adapter.loader_name = loaders.private_environment_loader.loader_name
- else
- adapter.loader_name = "#{mod.name} private"
- end
- return adapter
+ # @api private
+ def self.loader_name_by_source(environment, instance, file)
+ file = find_file(instance) if file.nil?
+ return nil if file.nil?
+ pn_adapter = PathsAndNameCacheAdapter.adapt(environment) do |a|
+ a.paths ||= environment.modulepath.map { |p| Pathname.new(p) }
+ a.cache ||= {}
+ end
+ dir = File.dirname(file)
+ pn_adapter.cache.fetch(dir) do |key|
+ mod = find_module_for_dir(environment, pn_adapter.paths, dir)
+ loader_name = mod.nil? ? nil : "#{mod.name} private"
+ pn_adapter.cache[key] = loader_name
end
- nil
- end
-
- def loader(scope)
- scope.compiler.loaders[loader_name]
end
- def self.find_module_for_file(environment, file)
- return nil if file.nil?
- file_path = Pathname.new(file)
- environment.modulepath.each do |path|
+ # @api private
+ def self.find_module_for_dir(environment, paths, dir)
+ return nil if dir.nil?
+ file_path = Pathname.new(dir)
+ paths.each do |path|
begin
- relative_path = file_path.relative_path_from(Pathname.new(path)).to_s.split(File::SEPARATOR)
+ relative_path = file_path.relative_path_from(path).to_s.split(File::SEPARATOR)
rescue ArgumentError
# file_path was not relative to the module_path. That's OK.
next
@@ -193,7 +190,12 @@ module Adapters
end
nil
end
- private_class_method :find_module_for_file
+
+ # @api private
+ def self.find_file(instance)
+ source_pos = Utils.find_closest_positioned(instance)
+ source_pos.nil? ? nil : source_pos.locator.file
+ end
end
end
end
diff --git a/lib/puppet/pops/evaluator/runtime3_support.rb b/lib/puppet/pops/evaluator/runtime3_support.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/pops/evaluator/runtime3_support.rb
+++ b/lib/puppet/pops/evaluator/runtime3_support.rb
@@ -267,7 +267,7 @@ module Runtime3Support
def call_function(name, args, o, scope, &block)
file, line = extract_file_line(o)
- loader = Adapters::LoaderAdapter.loader_for_model_object(o, scope)
+ loader = Adapters::LoaderAdapter.loader_for_model_object(o, scope, file)
if loader && func = loader.load(:function, name)
Puppet::Util::Profiler.profile(name, [:functions, name]) do
# Add stack frame when calling
|
(PUP-<I>) Speed up how loaders are obtained when doing function calls
Before this commit, profiling revealed a lot of calls involving the
Pathname class. This was due to inefficient caching of loader names
and adapters in the logic that locates a current loader for a particular
AST element. This commit speeds things up.
|
puppetlabs_puppet
|
train
|
7077bbd783f808b4962fdbcd7241b395e9a0a3e5
|
diff --git a/pkg/util/flock/flock_unix.go b/pkg/util/flock/flock_unix.go
index <HASH>..<HASH> 100644
--- a/pkg/util/flock/flock_unix.go
+++ b/pkg/util/flock/flock_unix.go
@@ -23,7 +23,7 @@ import "golang.org/x/sys/unix"
// Acquire acquires a lock on a file for the duration of the process. This method
// is reentrant.
func Acquire(path string) error {
- fd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR, 0600)
+ fd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0600)
if err != nil {
return err
}
diff --git a/pkg/util/mount/mount_linux.go b/pkg/util/mount/mount_linux.go
index <HASH>..<HASH> 100644
--- a/pkg/util/mount/mount_linux.go
+++ b/pkg/util/mount/mount_linux.go
@@ -497,7 +497,7 @@ func ExclusiveOpenFailsOnDevice(pathname string) (bool, error) {
klog.Errorf("Path %q is not referring to a device.", pathname)
return false, nil
}
- fd, errno := unix.Open(pathname, unix.O_RDONLY|unix.O_EXCL, 0)
+ fd, errno := unix.Open(pathname, unix.O_RDONLY|unix.O_EXCL|unix.O_CLOEXEC, 0)
// If the device is in use, open will return an invalid fd.
// When this happens, it is expected that Close will fail and throw an error.
defer unix.Close(fd)
|
Use O_CLOEXEC in util packages
This prevents fd's from leaking to subprocesses.
|
kubernetes_kubernetes
|
train
|
0cc3d27bd30d855e1b6625a7e9f119316ad7549e
|
diff --git a/SoftLayer/CLI/licenses/cancel.py b/SoftLayer/CLI/licenses/cancel.py
index <HASH>..<HASH> 100644
--- a/SoftLayer/CLI/licenses/cancel.py
+++ b/SoftLayer/CLI/licenses/cancel.py
@@ -16,4 +16,7 @@ def cli(env, key, immediate):
licenses = SoftLayer.LicensesManager(env.client)
- env.fout(licenses.cancel_item(key, immediate))
+ item = licenses.cancel_item(key, immediate)
+
+ if item:
+ env.fout("License key: {} was cancelled.".format(key))
|
Improved successful response to command - slcli licenses cancel
|
softlayer_softlayer-python
|
train
|
fe2e479e2397740daae0e565d44904869a37af14
|
diff --git a/lib/run.js b/lib/run.js
index <HASH>..<HASH> 100644
--- a/lib/run.js
+++ b/lib/run.js
@@ -23,7 +23,7 @@ module.exports = function run(options) {
meteorArguments = replaceCommand(meteorArguments, 'test-package', 'test-packages');
if (!meteorEnvironment.VELOCITY_USE_CHECKED_OUT_METEOR && !hasArgument(meteorArguments, '--release')) {
- meteorArguments.push('--release', 'velocity:METEOR@1.1.0.3_1');
+ meteorArguments.push('--release', 'velocity:METEOR@1.2.0.1_1');
}
if (!hasArgument(meteorArguments, '--driver-package')) {
diff --git a/spec/runSpec.js b/spec/runSpec.js
index <HASH>..<HASH> 100644
--- a/spec/runSpec.js
+++ b/spec/runSpec.js
@@ -26,7 +26,7 @@ describe('index', function () {
expect(spawnTestPackagesMeteor).toHaveBeenCalled();
var spawnOptions = spawnTestPackagesMeteor.calls.argsFor(0)[0];
- var expectedArguments = ['--release', 'velocity:METEOR@1.1.0.3_1'];
+ var expectedArguments = ['--release', 'velocity:METEOR@1.2.0.1_1'];
expect(_.intersection(spawnOptions.args.slice(1), expectedArguments)).toEqual(expectedArguments);
})
})
|
Use velocity:METEOR@<I>_1 as default release
|
meteor-velocity_velocity-cli
|
train
|
62a1d576ddbe4b10c7e806df26d9dcaf0a241f47
|
diff --git a/wss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/FileHandler.java b/wss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/FileHandler.java
index <HASH>..<HASH> 100644
--- a/wss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/FileHandler.java
+++ b/wss-agent-hash-calculator/src/main/java/org/whitesource/agent/hash/FileHandler.java
@@ -10,7 +10,7 @@ import java.util.Date;
import java.util.UUID;
/**
- * @author raz.nitzan
+ * @author philip.abed
*/
public class FileHandler {
private static String EMPTY_STRING = "";
|
WSE - <I> PlatformDependent temporary folder is not uniquely created.
|
whitesource_agents
|
train
|
c5edd26effb9d0219794df51b1ed9dd3e28515c8
|
diff --git a/bin/server.js b/bin/server.js
index <HASH>..<HASH> 100755
--- a/bin/server.js
+++ b/bin/server.js
@@ -48,11 +48,21 @@ io.sockets.on('connection', function (socket) {
operation = Operation.fromJSON(operation);
server.receiveOperation(operation);
console.log("new operation: " + operation);
+ if (typeof operation.meta.index === 'number') {
+ updateCursor(operation.meta.index);
+ }
});
+
+ function updateCursor (index) {
+ users[name].cursor = index;
+ socket.broadcast.emit('cursor', {
+ name: name,
+ index: index
+ });
+ }
+
socket.on('cursor', function (obj) {
- users[name].cursor = obj.index;
- obj.name = name;
- socket.broadcast.emit('cursor', obj);
+ updateCursor(obj.index);
});
socket.on('disconnect', function () {
// TODO
diff --git a/integration/codemirror/client.js b/integration/codemirror/client.js
index <HASH>..<HASH> 100644
--- a/integration/codemirror/client.js
+++ b/integration/codemirror/client.js
@@ -16,12 +16,15 @@
// uncomment to simulate more latency
/*(function () {
var emit = socket.emit;
+ var queue = [];
socket.emit = function () {
- var args = arguments;
- setTimeout(function () {
- emit.apply(socket, args);
- }, 800);
+ queue.push(arguments);
};
+ setInterval(function () {
+ if (queue.length) {
+ emit.apply(socket, queue.shift());
+ }
+ }, 800);
})();*/
var client = new Client(revision);
@@ -81,20 +84,36 @@
var operation = client.createOperation();
operation = codeMirrorChangeToOperation(operation, cm, change, oldValue);
console.log("onChange", change, operation);
+ if (cursorBuffer) {
+ operation.meta.index = cursorBuffer.index;
+ cursorBuffer = null;
+ }
client.applyClient(operation);
}
oldValue = cm.getValue();
- onCursorActivity(cm);
}
+ var cursorBuffer = null;
+
function onCursorActivity (cm) {
var cursorPos = cm.getCursor();
- console.log("onCursorActivity", cursorPos.line, cursorPos.ch);
var index = cm.indexFromPos(cursorPos);
- socket.emit('cursor', { index: index });
+ console.log("onCursorActivity", cursorPos, index);
+ if (client.state === 'awaitingWithBuffer') {
+ client.buffer.meta.index = index;
+ } else {
+ cursorBuffer = { index: index };
+ setTimeout(function () {
+ if (cursorBuffer) {
+ socket.emit('cursor', cursorBuffer);
+ cursorBuffer = null;
+ }
+ }, 1);
+ }
}
socket.on('operation', function (operation) {
+ console.log("Operation from server: ", operation);
operation = Operation.fromJSON(operation);
client.applyServer(operation);
});
@@ -113,11 +132,11 @@
socket.on('cursor', function (obj) {
//console.log(obj);
+ console.log(obj.name + " moved his/her cursor: " + obj.index);
users[obj.name].cursor = obj.index;
updateUserElPosition(obj.name);
});
- console.log(users);
for (var name in users) {
if (users.hasOwnProperty(name)) {
users[name].name = name;
|
Fix sending new cursor position before operation (take 2)
|
Operational-Transformation_ot.js
|
train
|
4e2000abfe50b929a6a62f8131e7d509e66d3aa3
|
diff --git a/p2p/conn/connection_test.go b/p2p/conn/connection_test.go
index <HASH>..<HASH> 100644
--- a/p2p/conn/connection_test.go
+++ b/p2p/conn/connection_test.go
@@ -339,8 +339,6 @@ func TestMConnectionTrySend(t *testing.T) {
go func() {
mconn.TrySend(0x01, msg)
resultCh <- "TrySend"
- }()
- go func() {
mconn.Send(0x01, msg)
resultCh <- "Send"
}()
|
control order by sending msgs from one goroutine
|
tendermint_tendermint
|
train
|
75ad6f7c2478c37e0bf424877e0b0ff9e23c14db
|
diff --git a/src/main/java/com/omertron/rottentomatoesapi/tools/WebBrowser.java b/src/main/java/com/omertron/rottentomatoesapi/tools/WebBrowser.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/omertron/rottentomatoesapi/tools/WebBrowser.java
+++ b/src/main/java/com/omertron/rottentomatoesapi/tools/WebBrowser.java
@@ -98,7 +98,8 @@ public final class WebBrowser {
if (in != null) {
in.close();
}
- if (cnx != null && cnx instanceof HttpURLConnection) {
+
+ if (cnx instanceof HttpURLConnection) {
((HttpURLConnection) cnx).disconnect();
}
}
|
No need to check for null before an instanceof
|
Omertron_api-rottentomatoes
|
train
|
218899a26dc0c2071b3dc65b65bce057173bd121
|
diff --git a/src/Exceptions/ClientException.php b/src/Exceptions/ClientException.php
index <HASH>..<HASH> 100644
--- a/src/Exceptions/ClientException.php
+++ b/src/Exceptions/ClientException.php
@@ -12,7 +12,7 @@ class ClientException extends \RuntimeException
/**
* @var UnsuccessfulRequest
*/
- protected $errorRequest = null;
+ protected $errorRequest;
public function __construct(string $message = '', int $code = 0, Throwable $previous = null)
{
|
Don't define values that are already defined as such
|
unreal4u_telegram-api
|
train
|
5d3addb605654f694a3fcc90332fdc995902a346
|
diff --git a/spec/views/tandem/pages/edit.html.slim_spec.rb b/spec/views/tandem/pages/edit.html.slim_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/views/tandem/pages/edit.html.slim_spec.rb
+++ b/spec/views/tandem/pages/edit.html.slim_spec.rb
@@ -11,7 +11,7 @@ module Tandem
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => page_path(@page), :method => "post" do
- assert_select "input#page_parent_id", :name => "page[parent_id]"
+ assert_select "input#page_parent_id_", :name => "page[parent_id]"
assert_select "input#page_title", :name => "page[title]"
assert_select "input#page_page_label", :name => "page[page_label]"
assert_select "input#page_link_label", :name => "page[link_label]"
@@ -23,4 +23,4 @@ module Tandem
end
end
end
-end
\ No newline at end of file
+end
diff --git a/spec/views/tandem/pages/new.html.slim_spec.rb b/spec/views/tandem/pages/new.html.slim_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/views/tandem/pages/new.html.slim_spec.rb
+++ b/spec/views/tandem/pages/new.html.slim_spec.rb
@@ -11,7 +11,7 @@ module Tandem
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => pages_path, :method => "post" do
- assert_select "input#page_parent_id", :name => "page[parent_id]"
+ assert_select "input#page_parent_id_", :name => "page[parent_id]"
assert_select "input#page_title", :name => "page[title]"
assert_select "input#page_page_label", :name => "page[page_label]"
assert_select "input#page_link_label", :name => "page[link_label]"
@@ -23,4 +23,4 @@ module Tandem
end
end
end
-end
\ No newline at end of file
+end
|
Fix view spec after passing blank to radio_button instead of nil.
|
12spokes_tandem
|
train
|
ad0f1d2cc68f563524dff582dedcfa9001c016e4
|
diff --git a/workbench/clients/workbench_shell.py b/workbench/clients/workbench_shell.py
index <HASH>..<HASH> 100644
--- a/workbench/clients/workbench_shell.py
+++ b/workbench/clients/workbench_shell.py
@@ -166,7 +166,7 @@ class WorkbenchShell(object):
# Start up the shell with our namespace
self.ipshell(local_ns=self.namespace)
-def test():
+def not_t():
"""Test the Workbench Interactive Shell"""
work_shell = WorkbenchShell()
try:
@@ -175,4 +175,4 @@ def test():
print 'Expected Fail... have a nice day...'
if __name__ == '__main__':
- test()
+ not_t()
|
removing the test from the new workbench interactive shell
|
SuperCowPowers_workbench
|
train
|
68f1c95ddb19602c1d33deb5aacca68d7bae8ca4
|
diff --git a/src/ZipStreamer.php b/src/ZipStreamer.php
index <HASH>..<HASH> 100644
--- a/src/ZipStreamer.php
+++ b/src/ZipStreamer.php
@@ -51,6 +51,8 @@ class ZipStreamer {
private $extFileAttrFile;
private $extFileAttrDir;
+ /** @var stream output stream zip file is written to */
+ private $outStream;
/** @var array central directory record */
private $cdRec = array();
/** @var int offset of next file to be added */
@@ -61,7 +63,20 @@ class ZipStreamer {
/**
* Constructor.
*/
- function __construct() {
+ function __construct($options = NULL) {
+ $defaultOptions = array(
+ 'outstream' => NULL,
+ );
+ if (is_null($options)) {
+ $options = array();
+ }
+ $options = array_merge($defaultOptions, $options);
+
+ if ($options['outstream']) {
+ $this->outstream = $options['outstream'];
+ } else {
+ $this->outstream = fopen('php://stdout', 'w');
+ }
//TODO: is this advisable/necessary?
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
@@ -112,7 +127,7 @@ class ZipStreamer {
header('Content-Transfer-Encoding: binary');
}
}
- flush();
+ $this->flush();
// turn off output buffering
ob_end_flush();
}
@@ -201,18 +216,18 @@ class ZipStreamer {
// print central directory
$cd = implode('', $this->cdRec);
- echo $cd;
+ $this->write($cd);
// print the zip64 end of central directory record
- echo $this->buildZip64EndOfCentralDirectoryRecord(strlen($cd));
+ $this->write($this->buildZip64EndOfCentralDirectoryRecord(strlen($cd)));
// print the zip64 end of central directory locator
- echo $this->buildZip64EndOfCentralDirectoryLocator(strlen($cd));
+ $this->write($this->buildZip64EndOfCentralDirectoryLocator(strlen($cd)));
// print end of central directory record
- echo $this->buildEndOfCentralDirectoryRecord();
+ $this->write($this->buildEndOfCentralDirectoryRecord());
- flush();
+ $this->flush();
$this->isFinalized = true;
$cd = null;
@@ -223,6 +238,14 @@ class ZipStreamer {
return false;
}
+ private function write($data) {
+ return fwrite($this->outstream, $data);
+ }
+
+ private function flush() {
+ return fflush($this->outstream);
+ }
+
private function beginFile($filePath, $fileComment, $timestamp, $gpFlags = 0x0000, $gzMethod = GZMETHOD::STORE,
$dataLength = 0, $gzLength = 0, $dataCRC32 = 0) {
@@ -237,7 +260,7 @@ class ZipStreamer {
$localFileHeader = $this->buildLocalFileHeader($filePath, $timestamp, $gpFlags, $gzMethod, $dataLength,
$gzLength, $dataCRC32);
- echo $localFileHeader;
+ $this->write($localFileHeader);
return array($gpFlags, strlen($localFileHeader));
}
@@ -256,9 +279,9 @@ class ZipStreamer {
$data = gzdeflate($data);
}
$gzLength->add(strlen($data));
- echo $data;
+ $this->write($data);
- flush();
+ $this->flush();
}
$crc = unpack('N', hash_final($hashCtx, true));
return array($dataLength, $gzLength, $crc[1]);
|
added option to switch to use arbitrary stream as output
|
McNetic_PHPZipStreamer
|
train
|
9897841911e6ab18b51e97861b0545ead0a7a7c0
|
diff --git a/cohorts/load.py b/cohorts/load.py
index <HASH>..<HASH> 100644
--- a/cohorts/load.py
+++ b/cohorts/load.py
@@ -1056,9 +1056,7 @@ class Cohort(Collection):
cache_provenance = None
cache_warnings = ""
this_cache_dir = path.join(self.cache_dir, cache_name)
- if (not(path.exists(this_cache_dir))):
- next
- else:
+ if path.exists(this_cache_dir):
for i, row in df.iterrows():
patient_id = row["patient_id"]
patient_cache_dir = path.join(this_cache_dir, patient_id)
@@ -1098,11 +1096,9 @@ class Cohort(Collection):
first_provenance = None
cache_diff = ""
for cache in provenance_summary:
- if cache == u'dfhash':
- next
- if not(first_provenance):
+ if cache != u'dfhash':
first_provenance = provenance_summary[cache]
- cache_diff += _compare_provenance(provenance_summary[cache], first_provenance)
+ cache_diff += _compare_provenance(provenance_summary[cache], first_provenance)
## compare provenance across cached items
if len(cache_diff) == 0:
prov = first_provenance
|
fix erroneous `next` usage
|
hammerlab_cohorts
|
train
|
66833c63634997f30a5247483b6ddeb654430a37
|
diff --git a/lib/congress/client.rb b/lib/congress/client.rb
index <HASH>..<HASH> 100644
--- a/lib/congress/client.rb
+++ b/lib/congress/client.rb
@@ -123,7 +123,7 @@ module Congress
options = args.last.is_a?(::Hash) ? args.pop : {}
case [args.size, args.first.class]
when [1, Fixnum]
- options.merge(:zip => args.pop)
+ options.merge(:zip => to_zip_code(args.pop))
when [1, String]
placemark = Geocoder.search(args.pop).first
options.merge(:longitude => placemark.longitude, :latitude => placemark.latitude)
@@ -133,5 +133,12 @@ module Congress
fail ArgumentError, 'Must pass a latitude/longitude, zip or address'
end
end
+
+ # Proper zip code from a number, adding leading zeroes if required
+ # @param number [Integer] zip code as an integer
+ # @return [String]
+ def to_zip_code(number)
+ sprintf('%05d', number)
+ end
end
end
diff --git a/spec/congress/client_spec.rb b/spec/congress/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/congress/client_spec.rb
+++ b/spec/congress/client_spec.rb
@@ -23,7 +23,7 @@ describe Congress::Client do
describe '#legislators_locate' do
context 'with a zip code passed' do
before do
- stub_get('/legislators/locate?zip=94107').
+ stub_get('/legislators/locate').with(:query => hash_including('zip')).
to_return(:status => 200, :body => fixture('legislators_locate.json'))
end
it 'fetches representatives and senators for a zip code' do
@@ -32,6 +32,12 @@ describe Congress::Client do
expect(legislators_locate['count']).to eq(3)
expect(legislators_locate['results'].first.bioguide_id).to eq('P000197')
end
+ context 'zip code with leading zeroes' do
+ it 'pads with leading zeroes' do
+ @client.legislators_locate(6511)
+ expect(a_get('/legislators/locate?zip=06511').with(:headers => {'X-APIKEY' => 'abc123'})).to have_been_made
+ end
+ end
end
context 'with a latitude and longitude passed' do
before do
|
Fix bug that breaks zip code lookup for any zip code that starts with a 0
|
codeforamerica_congress
|
train
|
1fe49d76765a11a776331aeb9931e3033bd318a2
|
diff --git a/test/runtest.py b/test/runtest.py
index <HASH>..<HASH> 100644
--- a/test/runtest.py
+++ b/test/runtest.py
@@ -1181,6 +1181,7 @@ class ResourcesTest(unittest.TestCase):
# to the correct local schedulers.
address_info = ray.worker._init(start_ray_local=True,
num_local_schedulers=3,
+ num_workers=1,
num_cpus=[100, 5, 10],
num_gpus=[0, 5, 1])
|
Simplify testMultipleLocalSchedulers by having it start only one worker. (#<I>)
|
ray-project_ray
|
train
|
401433281c6fff8a1fd9c4d251ef258e87f53ded
|
diff --git a/forms.py b/forms.py
index <HASH>..<HASH> 100644
--- a/forms.py
+++ b/forms.py
@@ -22,7 +22,8 @@ class RegistrationForm(forms.Form):
username = forms.CharField(max_length=30,
widget=forms.TextInput(attrs=attrs_dict),
label=u'Username')
- email = forms.EmailField(widget=forms.TextInput(attrs=attrs_dict),
+ email = forms.EmailField(max_length=200,
+ widget=forms.TextInput(attrs=attrs_dict),
label=u'Email address')
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict),
label=u'Password')
|
Trying a better max_length on the email field
|
ubernostrum_django-registration
|
train
|
282fe36b7eae36e82a009dd0237936da07f44a9f
|
diff --git a/dddp/models.py b/dddp/models.py
index <HASH>..<HASH> 100644
--- a/dddp/models.py
+++ b/dddp/models.py
@@ -214,10 +214,17 @@ class AleaIdField(models.CharField):
def __init__(self, *args, **kwargs):
"""Assume max_length of 17 to match Meteor implementation."""
+ kwargs['blank'] = True
kwargs.setdefault('verbose_name', 'Alea ID')
kwargs.setdefault('max_length', 17)
super(AleaIdField, self).__init__(*args, **kwargs)
+ def deconstruct(self):
+ """Return arguments to pass to __init__() to re-create this field."""
+ name, path, args, kwargs = super(AleaIdField, self).deconstruct()
+ del kwargs['blank']
+ return name, path, args, kwargs
+
def get_seeded_value(self, instance):
"""Generate a syncronised value."""
# Django model._meta is public API -> pylint: disable=W0212
|
Set blank=True on AleaIdField, allowing adding items without inventing IDs yourself.
|
jazzband_django-ddp
|
train
|
f3b0dfc81bc561297a271cdcf6f3f8f7ea09cc36
|
diff --git a/infra/aws/docker/index.js b/infra/aws/docker/index.js
index <HASH>..<HASH> 100644
--- a/infra/aws/docker/index.js
+++ b/infra/aws/docker/index.js
@@ -103,24 +103,24 @@ Object.assign(driver, dockerDriver);
* @param options
* @param cb
*/
-driver.deleteService = function(options, cb){
+driver.deleteService = function (options, cb) {
dockerDriver.inspectService(options, (error, deployedServiceDetails) => {
- if(error){
+ if (error) {
return cb(error);
}
- if(!deployedServiceDetails){
+ if (!deployedServiceDetails) {
return cb(null, true);
}
options.params.id = options.params.serviceId;
dockerDriver.deleteService(options, (error) => {
- if(error){
+ if (error) {
return cb(error);
}
let info = helper.getDeploymentFromInfra(options.infra, options.env);
- if(!info){
+ if (!info) {
return cb(null, true);
}
@@ -145,4 +145,37 @@ driver.deleteService = function(options, cb){
});
};
+driver.listServices = function (options, cb) {
+ dockerDriver.listServices(options, (error, services) => {
+ if (error) {
+ return cb(error);
+ }
+
+ let deployment = options.infra.stack;
+ let env = options.env.toUpperCase();
+
+ services.forEach(function (oneService) {
+ if (oneService.env) {
+ if(deployment && oneService.labels && oneService.labels['soajs.service.type'] === 'server' && oneService.labels['soajs.service.subtype'] === 'nginx'){
+ if (deployment.loadBalancers && deployment.loadBalancers[env] && deployment.loadBalancers[env][oneService.labels['soajs.service.name']]) {
+ oneService.ip = deployment.loadBalancers[env][oneService.labels['soajs.service.name']].DNSName;
+ //fix the ports
+ if(oneService.ports && oneService.servicePortType === 'loadBalancer'){
+ oneService.ports.forEach((onePort) => {
+ deployment.loadBalancers[env][oneService.labels['soajs.service.name']].ports.forEach((lbPorts) => {
+ if(lbPorts.published === onePort.published){
+ onePort.published = lbPorts.target
+ }
+ });
+ });
+ }
+ }
+ }
+ }
+ });
+
+ return cb(null, services);
+ });
+};
+
module.exports = driver;
\ No newline at end of file
diff --git a/infra/azure/vm/index.js b/infra/azure/vm/index.js
index <HASH>..<HASH> 100644
--- a/infra/azure/vm/index.js
+++ b/infra/azure/vm/index.js
@@ -371,7 +371,7 @@ const driver = {
* @param {Function} cb Callback function
* @return {void}
*/
- listVMs: function (options, cb) {
+ listServices: function (options, cb) {
options.soajs.log.debug(`Listing all virtual machines in ${options.env} and all custom vms`);
driver.authenticate(options, (error, authData) => {
utils.checkError(error, 700, cb, () => {
|
added support for loadbalancer in list services when using aws. change the name of list VMS to list services.
|
soajs_soajs.core.drivers
|
train
|
52948c8875ca5fa0aa76c02d7ded0373b9b1c95d
|
diff --git a/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/TokenProvider.java b/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/TokenProvider.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/TokenProvider.java
+++ b/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/TokenProvider.java
@@ -35,7 +35,7 @@ public interface TokenProvider {
* Called when a {@code 401 UNAUTHORIZED} is received as part of a request. Since not all {@link TokenProvider}s care about this possibility, the default implementation does nothing.
* Implementations are free to manage internal state with this call if they choose to.
*
- * @param connectionContext A {@link ConnectionContext} to be used if a token needs to be retrieved via a network request
+ * @param connectionContext A {@link ConnectionContext} to be used to identity which connection the tokens should be invalidated for
*/
default void invalidate(ConnectionContext connectionContext) {
}
diff --git a/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/tokenprovider/AbstractUaaTokenProvider.java b/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/tokenprovider/AbstractUaaTokenProvider.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/tokenprovider/AbstractUaaTokenProvider.java
+++ b/cloudfoundry-client-reactor/src/main/java/org/cloudfoundry/reactor/tokenprovider/AbstractUaaTokenProvider.java
@@ -30,9 +30,13 @@ import org.immutables.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponentsBuilder;
+import reactor.core.publisher.DirectProcessor;
+import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.http.client.HttpClientRequest;
import reactor.ipc.netty.http.client.HttpClientResponse;
+import reactor.util.function.Tuple2;
+import reactor.util.function.Tuples;
import java.time.LocalDateTime;
import java.time.ZoneId;
@@ -71,6 +75,8 @@ public abstract class AbstractUaaTokenProvider implements TokenProvider {
private final ConcurrentMap<ConnectionContext, Mono<String>> accessTokens = new ConcurrentHashMap<>(1);
+ private final ConcurrentMap<ConnectionContext, Tuple2<DirectProcessor<String>, Flux<String>>> refreshTokenStreams = new ConcurrentHashMap<>(1);
+
private final ConcurrentMap<ConnectionContext, Mono<String>> refreshTokens = new ConcurrentHashMap<>(1);
/**
@@ -89,6 +95,16 @@ public abstract class AbstractUaaTokenProvider implements TokenProvider {
return "";
}
+ /**
+ * Returns a {@link Flux} of refresh tokens for a connection
+ *
+ * @param connectionContext A {@link ConnectionContext} to be used to identity which connection the refresh tokens be retrieved for
+ * @return a {@link Flux} that emits the last token on subscribe and new refresh tokens as they are negotiated
+ */
+ public Flux<String> getRefreshTokens(ConnectionContext connectionContext) {
+ return getRefreshTokenStream(connectionContext).getT2();
+ }
+
@Override
public final Mono<String> getToken(ConnectionContext connectionContext) {
return this.accessTokens.computeIfAbsent(connectionContext, this::token);
@@ -172,6 +188,7 @@ public abstract class AbstractUaaTokenProvider implements TokenProvider {
}
this.refreshTokens.put(connectionContext, Mono.just(refreshToken));
+ getRefreshTokenStream(connectionContext).getT1().onNext(refreshToken);
});
}
@@ -184,6 +201,13 @@ public abstract class AbstractUaaTokenProvider implements TokenProvider {
.map(AbstractUaaTokenProvider::extractAccessToken);
}
+ private Tuple2<DirectProcessor<String>, Flux<String>> getRefreshTokenStream(ConnectionContext connectionContext) {
+ return this.refreshTokenStreams.computeIfAbsent(connectionContext, c -> {
+ DirectProcessor<String> processor = DirectProcessor.create();
+ return Tuples.of(processor, processor.cache(1));
+ });
+ }
+
private Mono<HttpClientResponse> primaryToken(ConnectionContext connectionContext) {
return requestToken(connectionContext, this::tokenRequestTransformer);
}
|
Get Refresh Token
A previous change removed the refresh token retrieval API that was used by the
STS team. This API needed to be reinstated, but we took the opportunity to
improve it a bit. This change makes that method return a `Flux` allowing a
subscriber to be notified whenever the value changes rather than having to
poll for changes.
[resolves #<I>]
|
cloudfoundry_cf-java-client
|
train
|
7badd682bd58876b561c855c4185c84da405300f
|
diff --git a/lib/ransack/adapters/active_record/context.rb b/lib/ransack/adapters/active_record/context.rb
index <HASH>..<HASH> 100644
--- a/lib/ransack/adapters/active_record/context.rb
+++ b/lib/ransack/adapters/active_record/context.rb
@@ -156,23 +156,18 @@ module Ransack
join_dependency.alias_tracker.aliases[join.left.name.downcase] = 1
end
- if ::ActiveRecord::VERSION::STRING >= "4.1"
+ if ::ActiveRecord::VERSION::STRING >= '4.1'
join_dependency
else
join_dependency.graft(*stashed_association_joins)
end
end
- if ::ActiveRecord::VERSION::STRING >= "4.1"
+ if ::ActiveRecord::VERSION::STRING >= '4.1'
def build_or_find_association(name, parent = @base, klass = nil)
- list = if ::ActiveRecord::VERSION::STRING >= "4.1"
- @join_dependency.join_root.children.detect
- else
- @join_dependency.join_associations
- end
-
- found_association = list.detect do |assoc|
+ found_association = @join_dependency.join_root.children
+ .detect do |assoc|
assoc.reflection.name == name &&
(@associations_pot.nil? || @associations_pot[assoc] == parent) &&
(!klass || assoc.reflection.klass == klass)
@@ -199,7 +194,6 @@ module Ransack
# Leverage the stashed association functionality in AR
@object = @object.joins(jd)
end
-
found_association
end
@@ -207,6 +201,7 @@ module Ransack
@associations_pot ||= {}
@associations_pot[assoc] = parent
end
+
else
def build_or_find_association(name, parent = @base, klass = nil)
@@ -217,16 +212,20 @@ module Ransack
(!klass || assoc.reflection.klass == klass)
end
unless found_association
- @join_dependency.send(:build, Polyamorous::Join.new(
- name, @join_type, klass), parent)
+ @join_dependency.send(
+ :build,
+ Polyamorous::Join.new(name, @join_type, klass),
+ parent
+ )
found_association = @join_dependency.join_associations.last
# Leverage the stashed association functionality in AR
@object = @object.joins(found_association)
end
-
found_association
end
+
end
+
end
end
end
|
Remove unneeded AR version conditional code
It seems to be redundant, and tests pass after removing it…
|
activerecord-hackery_ransack
|
train
|
4f61a35844a1c41299421c71e61452039327e403
|
diff --git a/core.js b/core.js
index <HASH>..<HASH> 100644
--- a/core.js
+++ b/core.js
@@ -732,7 +732,7 @@ const _makeRequestAnimationFrame = window => (fn, priority) => {
const id = ++rafIndex;
fn[symbols.idSymbol] = id;
rafCbs[_findFreeSlot(rafCbs)] = fn;
- rafCbs.sort((a, b) => b[symbols.prioritySymbol] - a[symbols.prioritySymbol]);
+ rafCbs.sort((a, b) => (b ? b[symbols.prioritySymbol] : 0) - (a ? a[symbols.prioritySymbol] : 0));
return id;
};
const _getFakeVrDisplay = window => {
|
Add null check to requestAnimationFrame sorting
|
exokitxr_exokit
|
train
|
8a3314c8cb83faab2ce44fbcf49e2d50b93d955d
|
diff --git a/variation/str.py b/variation/str.py
index <HASH>..<HASH> 100644
--- a/variation/str.py
+++ b/variation/str.py
@@ -75,7 +75,7 @@ DYS635 DYS643 GATA-H4
class STRLine(object):
- def __init__(self, line, named=False):
+ def __init__(self, line):
args = line.split()
self.seqid = args[0]
self.start = int(args[1])
@@ -93,10 +93,7 @@ class STRLine(object):
self.entropy = float(args[13])
self.motif = args[14]
assert self.period == len(self.motif)
- if named:
- self.name = args[15] if len(args) == 16 else None
- else:
- self.name = None
+ self.name = args[15] if len(args) > 15 else None
def __str__(self):
fields = [self.seqid, self.start, self.end,
@@ -110,12 +107,8 @@ class STRLine(object):
@property
def longname(self):
- name = "_".join(str(x) for x in \
- (self.seqid, self.start, self.motif,
- int(float(self.copynum))))
- if self.name is not None:
- name += "_" + self.name
- return name
+ return "_".join(str(x) for x in \
+ (self.seqid, self.start, self.motif))
def is_valid(self, maxperiod=6, maxlength=READLEN, minscore=MINSCORE):
return 1 <= self.period <= maxperiod and \
@@ -547,7 +540,6 @@ def mergecsv(args):
def write_csv_ev(filename, store, cleanup):
lv = LobSTRvcf()
lv.parse(filename, cleanup=cleanup)
- lv.parse(filename.replace(".hg38.", ".hg38-named."), cleanup=cleanup)
csvfile = op.basename(filename) + ".csv"
fw = open(csvfile, "w")
@@ -585,8 +577,7 @@ def compile(args):
Compile vcf results into master spreadsheet.
"""
p = OptionParser(compile.__doc__)
- p.add_option("--db", default="hg38,hg38-named",
- help="Use these lobSTR db")
+ p.add_option("--db", default="hg38", help="Use these lobSTR db")
p.set_home("lobstr")
p.set_cpus()
p.set_aws_opts(store="hli-mv-data-science/htang/str")
@@ -840,14 +831,13 @@ def batchlobstr(args):
sample, s3file = row.strip().split(",")[:2]
bamfile = s3file.replace(".gz", "").replace(".vcf", ".bam")
- gzfile = sample + ".{0}.vcf.gz".format("hg38-named")
+ gzfile = sample + ".{0}.vcf.gz".format("hg38")
if gzfile in computed:
skipped += 1
continue
print opts.sep.join("python -m jcvi.variation.str lobstr".split() + \
- [bamfile, "hg38", "hg38-named",
- "--prefix", sample,
+ [bamfile, "hg38", "--prefix", sample,
"--workdir", opts.workdir, "--cleanup"])
fp.close()
logging.debug("Total skipped: {0}".format(percentage(skipped, total)))
|
[variation] consolidate lobSTR databases into a single db
|
tanghaibao_jcvi
|
train
|
7ff4b643199757f301b9d8f98fd4431044b219ea
|
diff --git a/daemon/logger/journald/read.go b/daemon/logger/journald/read.go
index <HASH>..<HASH> 100644
--- a/daemon/logger/journald/read.go
+++ b/daemon/logger/journald/read.go
@@ -224,8 +224,6 @@ drain:
}
func (s *journald) followJournal(logWatcher *logger.LogWatcher, j *C.sd_journal, cursor *C.char, untilUnixMicro uint64) *C.char {
- defer close(logWatcher.Msg)
-
waitTimeout := C.uint64_t(250000) // 0.25s
LOOP:
@@ -265,6 +263,9 @@ func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon
sinceUnixMicro uint64
untilUnixMicro uint64
)
+
+ defer close(logWatcher.Msg)
+
// Quoting https://www.freedesktop.org/software/systemd/man/sd-journal.html:
// Functions that operate on sd_journal objects are thread
// agnostic — given sd_journal pointer may only be used from one
@@ -277,28 +278,18 @@ func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon
// Get a handle to the journal.
if rc := C.sd_journal_open(&j, C.int(0)); rc != 0 {
logWatcher.Err <- errors.New("error opening journal: " + CErr(rc))
- close(logWatcher.Msg)
return
}
+ defer C.sd_journal_close(j)
+
if config.Follow {
// Initialize library inotify watches early
if rc := C.sd_journal_get_fd(j); rc < 0 {
logWatcher.Err <- errors.New("error getting journald fd: " + CErr(rc))
- close(logWatcher.Msg)
return
}
}
- // If we end up following the log, we can set the journal context
- // pointer and the channel pointer to nil so that we won't close them
- // here, potentially while the goroutine that uses them is still
- // running. Otherwise, close them when we return from this function.
- following := false
- defer func() {
- if !following {
- close(logWatcher.Msg)
- }
- C.sd_journal_close(j)
- }()
+
// Remove limits on the size of data items that we'll retrieve.
if rc := C.sd_journal_set_data_threshold(j, C.size_t(0)); rc != 0 {
logWatcher.Err <- errors.New("error setting journal data threshold: " + CErr(rc))
@@ -365,11 +356,7 @@ func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon
}
if config.Follow {
cursor = s.followJournal(logWatcher, j, cursor, untilUnixMicro)
- // Let followJournal handle freeing the journal context
- // object and closing the channel.
- following = true
}
-
C.free(unsafe.Pointer(cursor))
}
|
logger/journald: simplify control flow
|
moby_moby
|
train
|
689eaec3b5ce8a8c8dc5d4c1654e5d845e6305aa
|
diff --git a/templates/default/consent.php b/templates/default/consent.php
index <HASH>..<HASH> 100644
--- a/templates/default/consent.php
+++ b/templates/default/consent.php
@@ -3,12 +3,13 @@
$this->includeLanguageFile('consent.php');
$this->includeInlineTranslation('spname', $this->data['sp_name']);
+ $this->includeInlineTranslation('IDPNAME', $this->data['idp_name']);
?>
<div id="content">
<p><?php echo htmlspecialchars($this->t('consent_notice')); ?> <strong><?php echo htmlspecialchars($this->t('spname')); ?></strong>.
- <?php echo htmlspecialchars($this->t('consent_accept')) ?>
+ <?php echo htmlspecialchars($this->t('consent_accept', true, true, array('IDPNAME' => ''))) ?>
</p>
<?php if ($this->data['sppp'] !== FALSE) {
@@ -28,7 +29,7 @@
<form style="display: inline; margin-left: .5em;" action="<?php echo htmlspecialchars($this->data['noconsent']); ?>" method="GET">
<input type="submit" value="<?php echo htmlspecialchars($this->t('no')) ?>" />
</form>
-
+ <p>
<table style="font-size: x-small">
<?php
diff --git a/www/saml2/idp/SSOService.php b/www/saml2/idp/SSOService.php
index <HASH>..<HASH> 100644
--- a/www/saml2/idp/SSOService.php
+++ b/www/saml2/idp/SSOService.php
@@ -275,6 +275,7 @@ if($needAuth && !$isPassive) {
$t = new SimpleSAML_XHTML_Template($config, 'consent.php', 'attributes.php');
$t->data['header'] = 'Consent';
$t->data['sp_name'] = $sp_name;
+ $t->data['idp_name'] = (isset($idpmetadata['name']) ? $idpmetadata['name'] : $idpentityid);
$t->data['spentityid'] = $spentityid;
$t->data['attributes'] = $filteredattributes;
$t->data['consenturl'] = SimpleSAML_Utilities::selfURLNoQuery();
|
Made idp_name available for the consent template, translated it and used it as a replacement string for the 'consent_accept' string.
|
simplesamlphp_saml2
|
train
|
542b8f46daef16397d563247dc4719819c6bc61e
|
diff --git a/lib/mongo/repl_set_connection.rb b/lib/mongo/repl_set_connection.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/repl_set_connection.rb
+++ b/lib/mongo/repl_set_connection.rb
@@ -224,7 +224,6 @@ module Mongo
@manager = background_manager
old_manager.close(:soft => true)
@refresh_version += 1
-
return true
end
@@ -324,11 +323,9 @@ module Mongo
else
connect
end
-
begin
socket = get_socket_from_pool(self.read_pool)
-
- if !socket
+ if !socket && @read != :secondary_only
connect
socket = get_socket_from_pool(self.primary_pool)
end
diff --git a/lib/mongo/util/pool_manager.rb b/lib/mongo/util/pool_manager.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/util/pool_manager.rb
+++ b/lib/mongo/util/pool_manager.rb
@@ -232,7 +232,7 @@ module Mongo
# If more than one node is available, use the ping
# time to figure out which nodes to choose from.
def set_read_pool
- if @secondary_pools.empty?
+ if @secondary_pools.empty? && @connection.read_preference != :secondary_only
@read_pool = @primary_pool
elsif @secondary_pools.size == 1
@read_pool = @secondary_pools[0]
diff --git a/lib/mongo/util/support.rb b/lib/mongo/util/support.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/util/support.rb
+++ b/lib/mongo/util/support.rb
@@ -59,11 +59,11 @@ module Mongo
end
def validate_read_preference(value)
- if [:primary, :secondary, nil].include?(value)
+ if [:primary, :secondary, :secondary_only, nil].include?(value)
return true
else
raise MongoArgumentError, "#{value} is not a valid read preference. " +
- "Please specify either :primary or :secondary."
+ "Please specify either :primary or :secondary or :secondary_only."
end
end
diff --git a/test/replica_sets/read_preference_test.rb b/test/replica_sets/read_preference_test.rb
index <HASH>..<HASH> 100644
--- a/test/replica_sets/read_preference_test.rb
+++ b/test/replica_sets/read_preference_test.rb
@@ -13,7 +13,6 @@ class ReadPreferenceTest < Test::Unit::TestCase
:refresh_mode => false, :refresh_interval => 5, :logger => log)
@db = @conn.db(MONGO_TEST_DB)
@db.drop_collection("test-sets")
- col = @db['mongo-test']
end
def teardown
@@ -34,6 +33,20 @@ class ReadPreferenceTest < Test::Unit::TestCase
"Primary port and read port at the same!"
end
+ def test_read_secondary_only
+ @conn = ReplSetConnection.new([@rs.host, @rs.ports[0]], [@rs.host, @rs.ports[1]], :read => :secondary_only)
+ assert_equal @conn.read_preference, :secondary_only
+
+ @db = @conn.db(MONGO_TEST_DB)
+ @coll = @db.collection("test-sets")
+ @coll.save({:a => 20})
+ @rs.kill_all_secondaries
+
+ assert_raise ConnectionFailure do
+ @coll.find_one
+ end
+ end
+
def test_query_secondaries
@secondary = Connection.new(@rs.host, @conn.read_pool.port, :slave_ok => true)
@coll = @db.collection("test-sets", :safe => {:w => 3, :wtimeout => 20000})
|
RUBY-<I> added ReplSetConnection read preference :secondary_only
|
mongodb_mongo-ruby-driver
|
train
|
5b7b18773a2be873427ea7a33817aa9cab0bffb8
|
diff --git a/src/main/java/COSE/EncryptMessage.java b/src/main/java/COSE/EncryptMessage.java
index <HASH>..<HASH> 100644
--- a/src/main/java/COSE/EncryptMessage.java
+++ b/src/main/java/COSE/EncryptMessage.java
@@ -40,6 +40,10 @@ public class EncryptMessage extends EncryptCommon {
return recipientList.get(iRecipient);
}
+ public int getRecipientCount() {
+ return recipientList.size();
+ }
+
public byte[] decrypt(Recipient whom) throws CoseException, InvalidCipherTextException {
byte[] rgbKey = null;
AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm));
diff --git a/src/main/java/COSE/MACMessage.java b/src/main/java/COSE/MACMessage.java
index <HASH>..<HASH> 100644
--- a/src/main/java/COSE/MACMessage.java
+++ b/src/main/java/COSE/MACMessage.java
@@ -33,6 +33,10 @@ public class MACMessage extends MacCommon {
return recipientList.get(iRecipient);
}
+ public int getRecipientCount() {
+ return recipientList.size();
+ }
+
public List<Recipient> getRecipientList() {
return recipientList;
}
diff --git a/src/main/java/COSE/Recipient.java b/src/main/java/COSE/Recipient.java
index <HASH>..<HASH> 100644
--- a/src/main/java/COSE/Recipient.java
+++ b/src/main/java/COSE/Recipient.java
@@ -307,6 +307,10 @@ public class Recipient extends Message {
return recipientList.get(iRecipient);
}
+ public int getRecipientCount() {
+ return recipientList.size();
+ }
+
public int getRecipientType() throws CoseException {
AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm));
switch (alg) {
diff --git a/src/main/java/COSE/SignMessage.java b/src/main/java/COSE/SignMessage.java
index <HASH>..<HASH> 100644
--- a/src/main/java/COSE/SignMessage.java
+++ b/src/main/java/COSE/SignMessage.java
@@ -81,6 +81,10 @@ public class SignMessage extends Message {
return signerList.get(iSigner);
}
+ public int getSignerCount() {
+ return signerList.size();
+ }
+
public void sign() throws CoseException {
if (rgbProtected == null) {
if (objProtected.size() == 0) rgbProtected = new byte[0];
|
Add functions to get count of recipients and signers
|
cose-wg_COSE-JAVA
|
train
|
32ce26a3562e0273eae3faf55b300ca7f89a13e1
|
diff --git a/src/Api/Formats/Json.php b/src/Api/Formats/Json.php
index <HASH>..<HASH> 100644
--- a/src/Api/Formats/Json.php
+++ b/src/Api/Formats/Json.php
@@ -16,7 +16,7 @@ class Json extends Format {
header('Content-Type: application/json');
}
- public function format($data) {
+ public function format($data, $name = null) {
return json_encode($data);
}
|
Json formatter needs blank name, not used but needs to match abstract definition
|
AyeAyeApi_Api
|
train
|
6945a0b4fd096bd378049fd175c6022a04efd02e
|
diff --git a/gitlab/__init__.py b/gitlab/__init__.py
index <HASH>..<HASH> 100644
--- a/gitlab/__init__.py
+++ b/gitlab/__init__.py
@@ -561,7 +561,6 @@ class Gitlab(object):
if request.status_code == 200:
return json.loads((request.content).decode("utf-8"))
else:
-
return False
def listbranch(self, id_, branch):
diff --git a/tests/gitlab_test.py b/tests/gitlab_test.py
index <HASH>..<HASH> 100644
--- a/tests/gitlab_test.py
+++ b/tests/gitlab_test.py
@@ -1,3 +1,13 @@
+"""
+pyapi-gitlab tests
+Covered:
+Ssh keys
+login
+user
+deploy keys
+some list cases
+"""
+
import unittest
import gitlab
@@ -74,3 +84,18 @@ class GitlabTest(unittest.TestCase):
assert isinstance(git.getprojectevents(git.getprojects()[0]['id']), list)
assert isinstance(git.getprojectevents(git.getprojects()[0]['id'], page=3), list)
assert isinstance(git.getprojectevents(git.getprojects()[0]['id'], per_page=4), list)
+ assert isinstance(git.listprojectmembers(id_=2), list)
+ self.assertTrue(git.addprojectmember(id_=2, user_id=3, access_level="reporter"))
+ self.assertTrue(git.deleteprojectmember(id_=2, user_id=3))
+
+ def test_branch(self):
+ git.login(user=user, password=password)
+ assert isinstance(git.listbranches(id_=2), list)
+ assert isinstance(git.listbranch(id_=2,branch="master"), dict)
+
+
+ def test_deploykeys(self):
+ git.login(user=user, password=password)
+ self.assertTrue(git.adddeploykey(id_=2, title="test", key=key))
+ assert isinstance(git.listdeploykey(id_=2, key_id=110), dict)
+ assert isinstance(git.listdeploykeys(id_=2), list)
|
added more project tests, some branch tests and deply keys tests
|
pyapi-gitlab_pyapi-gitlab
|
train
|
d07d78b0282f84dfcdf623855559c255be3f6fba
|
diff --git a/src/main/java/net/dv8tion/jda/entities/impl/GuildImpl.java b/src/main/java/net/dv8tion/jda/entities/impl/GuildImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/entities/impl/GuildImpl.java
+++ b/src/main/java/net/dv8tion/jda/entities/impl/GuildImpl.java
@@ -16,20 +16,22 @@
package net.dv8tion.jda.entities.impl;
import net.dv8tion.jda.JDA;
+import net.dv8tion.jda.Permission;
import net.dv8tion.jda.Region;
import net.dv8tion.jda.entities.*;
import net.dv8tion.jda.exceptions.GuildUnavailableException;
+import net.dv8tion.jda.exceptions.PermissionException;
import net.dv8tion.jda.handle.EntityBuilder;
import net.dv8tion.jda.managers.ChannelManager;
import net.dv8tion.jda.managers.GuildManager;
import net.dv8tion.jda.managers.RoleManager;
+import net.dv8tion.jda.utils.PermissionUtil;
import org.json.JSONObject;
import java.util.*;
public class GuildImpl implements Guild
{
- //TODO: PermissionException for creators
private final String id;
private String name;
private String iconId;
@@ -121,6 +123,10 @@ public class GuildImpl implements Guild
@Override
public ChannelManager createTextChannel(String name)
{
+ if (!PermissionUtil.checkPermission(getJDA().getSelfInfo(), Permission.MANAGE_CHANNEL, this))
+ {
+ throw new PermissionException(Permission.MANAGE_CHANNEL);
+ }
if (name == null)
{
throw new IllegalArgumentException("TextChannel name must not be null");
@@ -153,6 +159,10 @@ public class GuildImpl implements Guild
@Override
public ChannelManager createVoiceChannel(String name)
{
+ if (!PermissionUtil.checkPermission(getJDA().getSelfInfo(), Permission.MANAGE_CHANNEL, this))
+ {
+ throw new PermissionException(Permission.MANAGE_CHANNEL);
+ }
if (name == null)
{
throw new IllegalArgumentException("VoiceChannel name must not be null");
@@ -185,6 +195,10 @@ public class GuildImpl implements Guild
@Override
public RoleManager createRole()
{
+ if (!PermissionUtil.checkPermission(getJDA().getSelfInfo(), Permission.MANAGE_ROLES, this))
+ {
+ throw new PermissionException(Permission.MANAGE_ROLES);
+ }
if (!available)
{
throw new GuildUnavailableException();
diff --git a/src/main/java/net/dv8tion/jda/handle/GuildJoinHandler.java b/src/main/java/net/dv8tion/jda/handle/GuildJoinHandler.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/handle/GuildJoinHandler.java
+++ b/src/main/java/net/dv8tion/jda/handle/GuildJoinHandler.java
@@ -34,6 +34,7 @@ public class GuildJoinHandler extends SocketHandler
Guild guild = new EntityBuilder(api).createGuild(content);
if (guild.isAvailable())
{
+ //TODO: Available-event if previously unavailable
api.getEventManager().handle(
new GuildJoinEvent(
api, responseNumber,
diff --git a/src/main/java/net/dv8tion/jda/handle/ReadyHandler.java b/src/main/java/net/dv8tion/jda/handle/ReadyHandler.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/handle/ReadyHandler.java
+++ b/src/main/java/net/dv8tion/jda/handle/ReadyHandler.java
@@ -41,7 +41,7 @@ public class ReadyHandler extends SocketHandler
@Override
public void handle(JSONObject content)
{
- //TODO: User-Setings; read_state; voice channels
+ //TODO: User-Setings; read_state
builder.createSelfInfo(content.getJSONObject("user"));
JSONArray muted = content.getJSONObject("user_settings").getJSONArray("muted_channels");
List<String> mutedChannelIds = new ArrayList<>();
|
Added PermissionExceptino to the create functions inside Guild
|
DV8FromTheWorld_JDA
|
train
|
b3f73c3aea28ee9cd43236b44f599687e5e91862
|
diff --git a/indra/tests/test_pathfinding.py b/indra/tests/test_pathfinding.py
index <HASH>..<HASH> 100644
--- a/indra/tests/test_pathfinding.py
+++ b/indra/tests/test_pathfinding.py
@@ -50,7 +50,6 @@ def _digraph_setup():
all_ns.add(e[1][0].lower())
edge_by_hash = {
'HASH1': [
- ('A3', 'B2'),
('A4', 'B2'),
('A1', 'B1'),
('B1', 'C1'),
@@ -282,15 +281,16 @@ def test_bfs_multiple_nodes():
def test_shortest_simple_paths_strict_mesh_id_filtering():
- dg = _setup_signed_graph()[0]
- dg.add_edge('A2', 'B3', belief=0.7, weight=-np.log(0.7))
- dg.add_edge('B3', 'B1', belief=0.7, weight=-np.log(0.7))
- dg.graph['edge_by_hash']['HASH1'] += [('A2', 'B3'), ('B3', 'B1')]
+ G = _setup_unsigned_graph()[0]
+ G.add_edge('A2', 'B3', belief=0.7, weight=-np.log(0.7))
+ G.add_edge('B3', 'B1', belief=0.7, weight=-np.log(0.7))
+ G.graph['edge_by_hash']['HASH1'] += [('A2', 'B3'), ('B3', 'B1')]
def count_paths(source, target, hashes):
try:
- paths = [p for p in shortest_simple_paths(dg, source, target,
+ paths = [p for p in shortest_simple_paths(G, source, target,
hashes=hashes,
+ weight='weight',
strict_mesh_id_filtering=True)]
return len(paths)
except nx.NetworkXNoPath:
@@ -315,3 +315,18 @@ def test_shortest_simple_paths_strict_mesh_id_filtering():
assert count_paths('A1', 'C1', ['HASH1', 'HASH2']) == 1
assert count_paths('A2', 'C1', ['HASH1', 'HASH2']) == 3
assert count_paths('A2', 'D1', ['HASH1', 'HASH2']) == 0
+
+
+def test_shortest_simple_paths_weighed_by_mesh_ids():
+ G = _setup_unsigned_graph()[0]
+ G.add_edge('A3', 'B1', belief=0.7, weight=-np.log(0.7))
+ G.graph['edge_by_hash']['HASH1'].append(('A3', 'B1'))
+ source = 'A3'
+ target = 'C1'
+ paths = list(shortest_simple_paths(G, source, target, hashes=['HASH1']))
+ print(paths)
+ assert paths == [['A3', 'B1', 'C1'], ['A3', 'B2', 'C1']]
+ paths = list(shortest_simple_paths(G, source, target, hashes=['HASH2']))
+ assert paths == [['A3', 'B2', 'C1'], ['A3', 'B1', 'C1']]
+ paths = list(shortest_simple_paths(G, source, target, hashes=['HASH1', 'HASH2']))
+ assert paths == [['A3', 'B1', 'C1'], ['A3', 'B2', 'C1']]
|
Add test for mesh-ids edge weighing
|
sorgerlab_indra
|
train
|
f30274310856758edce6e28d405a8e2bad4bcbce
|
diff --git a/allennlp/commands/serve.py b/allennlp/commands/serve.py
index <HASH>..<HASH> 100644
--- a/allennlp/commands/serve.py
+++ b/allennlp/commands/serve.py
@@ -8,10 +8,11 @@ def add_subparser(parser: argparse._SubParsersAction) -> argparse.ArgumentParser
'serve', description=description, help='Run the web service and demo.')
subparser.add_argument('--port', type=int, default=8000)
+ subparser.add_argument('--workers', type=int, default=1)
subparser.set_defaults(func=serve)
return subparser
def serve(args: argparse.Namespace) -> None:
- server_sanic.run(args.port)
+ server_sanic.run(args.port, args.workers)
diff --git a/allennlp/service/server_sanic.py b/allennlp/service/server_sanic.py
index <HASH>..<HASH> 100644
--- a/allennlp/service/server_sanic.py
+++ b/allennlp/service/server_sanic.py
@@ -3,13 +3,13 @@ from allennlp.service.predictors import load_predictors
from sanic import Sanic, response, request
from sanic.exceptions import ServerError
-def run(port: int) -> None:
+def run(port: int, workers: int) -> None:
"""Run the server programatically"""
print("Starting a sanic server on port {}.".format(port))
app = make_app()
# TODO(joelgrus): make this configurable
app.predictors = load_predictors()
- app.run(port=port, host="0.0.0.0")
+ app.run(port=port, host="0.0.0.0", workers=workers)
def make_app() -> Sanic:
app = Sanic(__name__) # pylint: disable=invalid-name
|
Add a flag to configure the number of sanic workers. (#<I>)
|
allenai_allennlp
|
train
|
b887a8ce76a5a3c367bb284928717a11349270ff
|
diff --git a/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/KieServerRouter.java b/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/KieServerRouter.java
index <HASH>..<HASH> 100644
--- a/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/KieServerRouter.java
+++ b/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/KieServerRouter.java
@@ -58,7 +58,7 @@ public class KieServerRouter {
private static final String PORT = System.getProperty(KieServerRouterConstants.ROUTER_PORT, "9000");
private int failedAttemptsInterval = Integer.parseInt(System.getProperty(KieServerRouterConstants.KIE_SERVER_CONTROLLER_ATTEMPT_INTERVAL, "10"));
- private static final String CONTROLLER = System.getProperty(KieServerRouterConstants.CONTROLLER);
+ private String CONTROLLER = System.getProperty(KieServerRouterConstants.CONTROLLER);
private static final Logger log = Logger.getLogger(KieServerRouter.class);
diff --git a/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/handlers/AdminHttpHandler.java b/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/handlers/AdminHttpHandler.java
index <HASH>..<HASH> 100644
--- a/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/handlers/AdminHttpHandler.java
+++ b/kie-server-parent/kie-server-router/kie-server-router-proxy/src/main/java/org/kie/server/router/handlers/AdminHttpHandler.java
@@ -50,7 +50,7 @@ public class AdminHttpHandler implements HttpHandler {
private static final Logger log = Logger.getLogger(AdminHttpHandler.class);
- private static final String CONTROLLER = System.getProperty(KieServerRouterConstants.CONTROLLER);
+ private String CONTROLLER = System.getProperty(KieServerRouterConstants.CONTROLLER);
private int interval = Integer.parseInt(System.getProperty(KieServerRouterConstants.KIE_SERVER_CONTROLLER_ATTEMPT_INTERVAL, "10"));
private int attemptsLimit = Integer.parseInt(System.getProperty(KieServerRouterConstants.KIE_SERVER_RECOVERY_ATTEMPT_LIMIT, "100"));
|
JBPM-<I> - Kie Server Router should retry when updating controller config in case of controller's unavailability - fix random (#<I>)
|
kiegroup_droolsjbpm-integration
|
train
|
9faacb372f9576519125a3400c0474588da2e37a
|
diff --git a/SingularityService/src/main/java/com/hubspot/singularity/data/SingularityValidator.java b/SingularityService/src/main/java/com/hubspot/singularity/data/SingularityValidator.java
index <HASH>..<HASH> 100644
--- a/SingularityService/src/main/java/com/hubspot/singularity/data/SingularityValidator.java
+++ b/SingularityService/src/main/java/com/hubspot/singularity/data/SingularityValidator.java
@@ -488,7 +488,8 @@ public class SingularityValidator {
public void checkResourcesForBounce(SingularityRequest request, boolean isIncremental) {
SlavePlacement placement = request.getSlavePlacement().or(defaultSlavePlacement);
- if (placement == SlavePlacement.SEPARATE_BY_REQUEST) {
+ if ((request.getAllowBounceToSameHost().or(false) && placement == SlavePlacement.SEPARATE_BY_REQUEST)
+ || (placement != SlavePlacement.GREEDY && placement != SlavePlacement.OPTIMISTIC)) {
int currentActiveSlaveCount = slaveManager.getNumObjectsAtState(MachineState.ACTIVE);
int requiredSlaveCount = isIncremental ? request.getInstancesSafe() + 1 : request.getInstancesSafe() * 2;
|
Check bounce resources if not allowing bounce to same host
|
HubSpot_Singularity
|
train
|
871bdb11fb829161ed759c33048ddfcb15c51f21
|
diff --git a/src/pinch-it.js b/src/pinch-it.js
index <HASH>..<HASH> 100644
--- a/src/pinch-it.js
+++ b/src/pinch-it.js
@@ -82,6 +82,7 @@ const pinchIt = (targets: string | Object, options: Object = {}) => {
const touch = first(getTouches(e.target, Array.from(e.touches)));
const dragOffset = drag(touch, lastDragPosition, offset, zoomFactor);
+
offset = sanitizeOffset(e.target, dragOffset, zoomFactor);
lastDragPosition = touch;
} else if (scaling && startTouches) {
@@ -94,7 +95,6 @@ const pinchIt = (targets: string | Object, options: Object = {}) => {
const factor = scaleFactor(scale, zoomFactor, opts);
-
offset = addOffset(offset, {
x: (factor.scale - 1) * (touchCenter.x + offset.x),
y: (factor.scale - 1) * (touchCenter.y + offset.y)
@@ -117,7 +117,6 @@ const pinchIt = (targets: string | Object, options: Object = {}) => {
lastDragPosition = false;
lastZoomCenter = false;
lastScale = 1;
-
if (zoomFactor) {
if (!isWithin(zoomFactor, opts)) {
const isLessThan = (getInitialScale(e.target) * zoomFactor < opts.minScale);
diff --git a/src/utils/handle-drag.js b/src/utils/handle-drag.js
index <HASH>..<HASH> 100644
--- a/src/utils/handle-drag.js
+++ b/src/utils/handle-drag.js
@@ -7,9 +7,13 @@ type Center = {
y: number;
};
+const calcMax = (el: EventTarget, differ: number, zoomFactor: number): Object => ({
+ maxX: (zoomFactor - differ) * getParentX(el),
+ maxY: (zoomFactor - differ) * getParentY(el),
+});
+
export const sanitizeOffset = (el: EventTarget, offset: Center, zoomFactor: number): Object => {
- const maxX = (zoomFactor - 1) * getParentX(el) * zoomFactor;
- const maxY = (zoomFactor - 1) * getParentY(el) * zoomFactor;
+ const { maxX, maxY } = calcMax(el, 1, zoomFactor);
const maxOffsetX = Math.max(maxX, 0);
const maxOffsetY = Math.max(maxY, 0);
const minOffsetX = Math.min(maxX, 0);
@@ -21,11 +25,11 @@ export const sanitizeOffset = (el: EventTarget, offset: Center, zoomFactor: numb
};
};
-export const drag = (center: Center, lastCenter: Center, lastOffset: Object, zoomFactor) => (
+export const drag = (center: Center, lastCenter: Center, lastOffset: Object, zoomFactor: number): Object => (
(Object.prototype.hasOwnProperty.call(lastCenter, 'x'))
? addOffset(lastOffset, {
- x: -((center.x - lastCenter.x) * zoomFactor),
- y: -((center.y - lastCenter.y) * zoomFactor),
+ x: -(((center.x - lastCenter.x) * zoomFactor) / zoomFactor),
+ y: -(((center.y - lastCenter.y) * zoomFactor) / zoomFactor),
})
: lastOffset
);
diff --git a/src/utils/handle-element.js b/src/utils/handle-element.js
index <HASH>..<HASH> 100644
--- a/src/utils/handle-element.js
+++ b/src/utils/handle-element.js
@@ -28,8 +28,15 @@ export default (el: EventTarget, pinch: number, coords: Object, duration: number
const { style } = el;
const zoomFactor = getInitialScale(el) * pinch;
- const offsetX = -coords.x / zoomFactor;
- const offsetY = -coords.y / zoomFactor;
+
+ const offsetX = -coords.x;
+ const offsetY = -coords.y;
+
+ console.log('getInitialScale', getInitialScale(el));
+ console.log('pinch', pinch);
+ console.log('coords.x', coords.x);
+ console.log('offsetx', offsetX);
+ console.log('');
handleAnimation(el, transition, duration, ease);
const scaleProp = (hasScale3d)
|
adds logic for keeping center when pinching
|
houseofradon_pinchit
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.