hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
07d8c0b74779e8a2a7fda01655743521d950f76d
|
diff --git a/datastore-core/src/main/java/org/opencb/datastore/core/ObjectMap.java b/datastore-core/src/main/java/org/opencb/datastore/core/ObjectMap.java
index <HASH>..<HASH> 100644
--- a/datastore-core/src/main/java/org/opencb/datastore/core/ObjectMap.java
+++ b/datastore-core/src/main/java/org/opencb/datastore/core/ObjectMap.java
@@ -180,20 +180,21 @@ public class ObjectMap implements Map<String, Object>, Serializable {
* @param field the field
* @param clazz the class to cast the value to
* @param <T> the type of the class
- * @return the value of the given key, or null if the instance does not contain this key.
- * @throws ClassCastException if the value of the given key is not of type T
+ * @return the value of the given key, or null if the instance does not contain this key, or defaultValue if the object
+ * is not of type T.
*/
- @SuppressWarnings("unchecked")
- public <T> T get(final Object field, final Class<T> clazz) {
- return (T) objectMap.get(field);
+ public <T> T get(final String field, final Class<T> clazz) {
+ return get(field, clazz, null);
}
- @SuppressWarnings("unchecked")
- public <T> T get(final Object field, final Class<T> clazz, T defaultvalue) {
+ public <T> T get(final String field, final Class<T> clazz, T defaultValue) {
if(objectMap.containsKey(field)) {
- return (T) objectMap.get(field);
+ Object obj = objectMap.get(field);
+ if (clazz.isInstance(obj)) {
+ return clazz.cast(obj);
+ }
}
- return defaultvalue;
+ return defaultValue;
}
/**
@@ -232,6 +233,7 @@ public class ObjectMap implements Map<String, Object>, Serializable {
public List<Integer> getAsIntegerList(String field) {
return getAsIntegerList(field, ",");
}
+
public List<Integer> getAsIntegerList(String field, String separator) {
List list = getAsList(field, separator);
if (!list.isEmpty() && list.get(0) instanceof Integer) {
|
core: ObjectMap get(key, clazz) added clazz.instanceOf() in order to avoid ClassCastException
|
opencb_datastore
|
train
|
4185d1c231cbf911f5adb68072733209aeb4375a
|
diff --git a/gwpy/timeseries/core.py b/gwpy/timeseries/core.py
index <HASH>..<HASH> 100644
--- a/gwpy/timeseries/core.py
+++ b/gwpy/timeseries/core.py
@@ -1471,7 +1471,9 @@ class TimeSeries(Series):
raise ValueError("TimeSeries sampling rates do not match: "
"%s vs %s." % (self.sample_rate,
other.sample_rate))
- if not self.unit == other.unit:
+ if not self.unit == other.unit and not (
+ self.unit in [units.dimensionless_unscaled, None] and
+ other.unit in [units.Unit(''), None]):
raise ValueError("TimeSeries units do not match: %s vs %s."
% (str(self.unit), str(other.unit)))
else:
|
TimeSeries.is_compatible: treat '' and None units the same
|
gwpy_gwpy
|
train
|
b310df571b2e9d6fd729217f7a124c7984f91512
|
diff --git a/src/de/mrapp/android/dialog/MaterialDialogBuilder.java b/src/de/mrapp/android/dialog/MaterialDialogBuilder.java
index <HASH>..<HASH> 100644
--- a/src/de/mrapp/android/dialog/MaterialDialogBuilder.java
+++ b/src/de/mrapp/android/dialog/MaterialDialogBuilder.java
@@ -387,8 +387,8 @@ public class MaterialDialogBuilder extends AlertDialog.Builder {
public MaterialDialogBuilder setItems(final int resourceId,
OnClickListener listener) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
- listAdapter = new ArrayAdapter<CharSequence>(context, resourceId);
- listViewClickListener = listener;
+ this.setItems(context.getResources().getTextArray(resourceId),
+ listener);
} else {
super.setItems(resourceId, listener);
}
|
Fixed the functionality to load list items from an array resource.
|
michael-rapp_AndroidMaterialDialog
|
train
|
86c1f8adf21b8c4d0b792ba716461eb7bfef331a
|
diff --git a/lib/epp/server.rb b/lib/epp/server.rb
index <HASH>..<HASH> 100644
--- a/lib/epp/server.rb
+++ b/lib/epp/server.rb
@@ -85,7 +85,7 @@ module Epp #:nodoc:
extensions_container.add_element("extURI").text = uri
end
- command.add_element("clTRID").text = @clTRID
+ command.add_element("clTRID").text = "ABC-12345"
# Receive the login response
response = Hpricot.XML(send_request(xml.to_s))
|
Updated login transaction ID; can't be blank
|
ultraspeed_epp
|
train
|
3f3a8a6f868e1bfeac8b117198784075cde2c7ee
|
diff --git a/mishmash/commands/sync/sync.py b/mishmash/commands/sync/sync.py
index <HASH>..<HASH> 100644
--- a/mishmash/commands/sync/sync.py
+++ b/mishmash/commands/sync/sync.py
@@ -170,7 +170,7 @@ class SyncPlugin(LoaderPlugin):
# stash the album though, we'll look for artwork
# updates later
album = track.album
- return
+ return album
# Either adding the track (track == None)
# or modifying (track != None)
|
fix: Pick up new image files when rescanning and no audio files changed.
|
nicfit_MishMash
|
train
|
c79079347cc16014efd81589cb37c8852d782f9a
|
diff --git a/tasks.py b/tasks.py
index <HASH>..<HASH> 100644
--- a/tasks.py
+++ b/tasks.py
@@ -1,3 +1,5 @@
+from os.path import join
+
from invocations import docs
from invocations.testing import test, integration, watch_tests
from invocations.packaging import release
@@ -13,5 +15,9 @@ ns.configure({
'packaging': {
'sign': True,
'wheel': True,
+ 'changelog_file': join(
+ docs.ns.configuration()['sphinx']['source'],
+ 'changelog.rst',
+ ),
},
})
|
Tweak for new invocations release tasks
|
bitprophet_releases
|
train
|
e574981318b3f61c99a58f6cd9b5651a42275c1d
|
diff --git a/lib/rom/commands/abstract.rb b/lib/rom/commands/abstract.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/commands/abstract.rb
+++ b/lib/rom/commands/abstract.rb
@@ -10,15 +10,14 @@ module ROM
option :target
option :validator, reader: true
option :input, reader: true
- option :args, type: Array, reader: true
+ option :curry_args, type: Array, reader: true, default: []
attr_reader :relation
# @api private
def initialize(relation, options = {})
- super
@relation = relation
- @options[:args] ||= []
+ super
end
# Execute the command
@@ -39,7 +38,7 @@ module ROM
#
# @api public
def call(*args)
- tuples = execute(*(args + options[:args]))
+ tuples = execute(*(args + curry_args))
if result == :one
tuples.first
@@ -50,7 +49,7 @@ module ROM
# @api public
def curry(*args)
- self.class.new(relation, options.merge(args: args))
+ self.class.new(relation, options.merge(curry_args: args))
end
# Compose a command with another one
diff --git a/lib/rom/support/class_builder.rb b/lib/rom/support/class_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/support/class_builder.rb
+++ b/lib/rom/support/class_builder.rb
@@ -3,7 +3,7 @@ module ROM
include Options
option :name, type: String, reader: true
- option :parent, type: Class, reader: true
+ option :parent, type: Class, reader: true, parent: Object
def call
klass = Class.new(parent)
diff --git a/lib/rom/support/options.rb b/lib/rom/support/options.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/support/options.rb
+++ b/lib/rom/support/options.rb
@@ -20,19 +20,24 @@ module ROM
end
class Option
- attr_reader :name, :type, :allow
+ attr_reader :name, :type, :allow, :default
def initialize(name, options = {})
@name = name
@type = options.fetch(:type) { Object }
@reader = options.fetch(:reader) { false }
@allow = options.fetch(:allow) { [] }
+ @default = options[:default] if options.key?(:default)
end
def reader?
@reader
end
+ def default?
+ !@default.nil?
+ end
+
def type_matches?(value)
value.is_a?(type)
end
@@ -57,6 +62,16 @@ module ROM
end
end
+ def set_defaults(object, options)
+ each do |name, option|
+ if option.default? && !options.key?(name)
+ default = option.default
+ value = default.is_a?(Proc) ? default.call(object) : default
+ options.update(name => value)
+ end
+ end
+ end
+
def each(&block)
@options.each(&block)
end
@@ -94,9 +109,11 @@ module ROM
end
def initialize(*args)
- @options = args.last
- self.class.option_definitions.validate_options(@options)
- self.class.option_definitions.each do |name, option|
+ @options = args.last.dup
+ definitions = self.class.option_definitions
+ definitions.set_defaults(self, @options)
+ definitions.validate_options(@options)
+ definitions.each do |name, option|
instance_variable_set("@#{name}", @options[name]) if option.reader?
end
end
|
Add support for setting a default value in Options
|
rom-rb_rom
|
train
|
323605d169affeb9f2243b6eb142d44370390d28
|
diff --git a/dashboard/modules/job/tests/test_job_manager.py b/dashboard/modules/job/tests/test_job_manager.py
index <HASH>..<HASH> 100644
--- a/dashboard/modules/job/tests/test_job_manager.py
+++ b/dashboard/modules/job/tests/test_job_manager.py
@@ -3,6 +3,7 @@ import os
import psutil
import tempfile
import sys
+import urllib.request
from uuid import uuid4
import signal
@@ -270,6 +271,24 @@ class TestShellScriptExecution:
job_manager.get_job_logs(job_id) == "Executing main() from script.py !!\n"
)
+ async def test_submit_with_file_runtime_env(self, job_manager):
+ with tempfile.NamedTemporaryFile(suffix=".zip") as f:
+ filename, _ = urllib.request.urlretrieve(
+ "https://runtime-env-test.s3.amazonaws.com/script_runtime_env.zip",
+ filename=f.name,
+ )
+ job_id = job_manager.submit_job(
+ entrypoint="python script.py",
+ runtime_env={"working_dir": "file://" + filename},
+ )
+ await async_wait_for_condition(
+ check_job_succeeded, job_manager=job_manager, job_id=job_id
+ )
+ assert (
+ job_manager.get_job_logs(job_id)
+ == "Executing main() from script.py !!\n"
+ )
+
@pytest.mark.asyncio
class TestRuntimeEnv:
diff --git a/python/ray/_private/runtime_env/packaging.py b/python/ray/_private/runtime_env/packaging.py
index <HASH>..<HASH> 100644
--- a/python/ray/_private/runtime_env/packaging.py
+++ b/python/ray/_private/runtime_env/packaging.py
@@ -55,12 +55,13 @@ class Protocol(Enum):
HTTPS = "https", "Remote https path, assumes everything packed in one zip file."
S3 = "s3", "Remote s3 path, assumes everything packed in one zip file."
GS = "gs", "Remote google storage path, assumes everything packed in one zip file."
+ FILE = "file", "File storage path, assumes everything packed in one zip file."
@classmethod
def remote_protocols(cls):
- # Returns a lit of protocols that support remote storage
+ # Returns a list of protocols that support remote storage
# These protocols should only be used with paths that end in ".zip"
- return [cls.HTTPS, cls.S3, cls.GS]
+ return [cls.HTTPS, cls.S3, cls.GS, cls.FILE]
def _xor_bytes(left: bytes, right: bytes) -> bytes:
@@ -174,6 +175,15 @@ def parse_uri(pkg_uri: str) -> Tuple[Protocol, str]:
)
-> ("gs",
"gs_public-runtime-env-test_test_module.zip")
+ For FILE URIs, the path will have '/' replaced with '_'. The package name
+ will be the adjusted path with 'file_' prepended.
+ urlparse("file:///path/to/test_module.zip")
+ -> ParseResult(
+ scheme='file',
+ netloc='path',
+ path='/path/to/test_module.zip'
+ )
+ -> ("file", "file__path_to_test_module.zip")
"""
uri = urlparse(pkg_uri)
protocol = Protocol(uri.scheme)
@@ -184,6 +194,11 @@ def parse_uri(pkg_uri: str) -> Tuple[Protocol, str]:
protocol,
f"https_{uri.netloc.replace('.', '_')}{uri.path.replace('/', '_')}",
)
+ elif protocol == Protocol.FILE:
+ return (
+ protocol,
+ f"file_{uri.path.replace('/', '_')}",
+ )
else:
return (protocol, uri.netloc)
@@ -575,7 +590,7 @@ def download_and_unpack_package(
if protocol == Protocol.S3:
try:
- from smart_open import open
+ from smart_open import open as open_file
import boto3
except ImportError:
raise ImportError(
@@ -586,7 +601,7 @@ def download_and_unpack_package(
tp = {"client": boto3.client("s3")}
elif protocol == Protocol.GS:
try:
- from smart_open import open
+ from smart_open import open as open_file
from google.cloud import storage # noqa: F401
except ImportError:
raise ImportError(
@@ -594,17 +609,23 @@ def download_and_unpack_package(
"`pip install google-cloud-storage` "
"to fetch URIs in Google Cloud Storage bucket."
)
+ elif protocol == Protocol.FILE:
+ pkg_uri = pkg_uri[len("file://") :]
+
+ def open_file(uri, mode, *, transport_params=None):
+ return open(uri, mode)
+
else:
try:
- from smart_open import open
+ from smart_open import open as open_file
except ImportError:
raise ImportError(
"You must `pip install smart_open` "
f"to fetch {protocol.value.upper()} URIs."
)
- with open(pkg_uri, "rb", transport_params=tp) as package_zip:
- with open(pkg_file, "wb") as fin:
+ with open_file(pkg_uri, "rb", transport_params=tp) as package_zip:
+ with open_file(pkg_file, "wb") as fin:
fin.write(package_zip.read())
unzip_package(
|
Support file:// for runtime_env working directories in jobs (#<I>)
This makes it possible to use an NFS file system that is shared on a cluster for runtime_env working directories.
|
ray-project_ray
|
train
|
0df76b5f2941beb303c7d29128e592dde0a3eb12
|
diff --git a/Gemfile.lock b/Gemfile.lock
index <HASH>..<HASH> 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
- xcake (0.4.8)
+ xcake (0.5.0)
claide (~> 0.9.1)
hooks (~> 0.4.1)
tty (~> 0.3.2)
@@ -42,9 +42,9 @@ GEM
minitest (5.8.3)
necromancer (0.3.0)
netrc (0.11.0)
- pastel (0.5.2)
- equatable (~> 0.5)
- tty-screen (~> 0.4)
+ pastel (0.5.3)
+ equatable (~> 0.5.0)
+ tty-screen (~> 0.4.3)
pry (0.10.3)
coderay (~> 1.1.0)
method_source (~> 0.8.1)
diff --git a/lib/xcake.rb b/lib/xcake.rb
index <HASH>..<HASH> 100644
--- a/lib/xcake.rb
+++ b/lib/xcake.rb
@@ -8,8 +8,6 @@ require "xcake/version"
require "xcake/informative"
require "xcake/command"
-require "xcake/command/init"
-require "xcake/command/make"
require "xcake/configuration"
require "xcake/configuration/sugar"
diff --git a/lib/xcake/command.rb b/lib/xcake/command.rb
index <HASH>..<HASH> 100644
--- a/lib/xcake/command.rb
+++ b/lib/xcake/command.rb
@@ -3,26 +3,13 @@ require "claide"
module Xcake
class Command < CLAide::Command
+ require "xcake/command/init"
+ require "xcake/command/make"
+
+ self.abstract_command = true
self.command = "xcake"
self.version = VERSION
self.description = "Create and maintain Xcode project files easily."
-
- def run
- file_path = "#{Dir.pwd}/Cakefile"
-
- unless File.exist?(file_path)
- raise Xcake::Informative, "Couldn't find Cakefile"
- end
-
- puts "Reading Cakefile..."
- file_contents = File.read(file_path)
- cakefile = eval(file_contents)
-
- resolver = ProjectStructureResolver.new
- cakefile.accept(resolver)
-
- generator = Generator::Project.new
- cakefile.accept(generator)
- end
+ self.plugin_prefixes = %w(claide xcake)
end
end
diff --git a/lib/xcake/command/init.rb b/lib/xcake/command/init.rb
index <HASH>..<HASH> 100644
--- a/lib/xcake/command/init.rb
+++ b/lib/xcake/command/init.rb
@@ -1,28 +1,13 @@
require "claide"
module Xcake
- class InitCommnd < CLAide::Command
+ class Command
+ class InitCommand < Command
+ self.description = "Initilises an example Cakefile for creating a project"
- self.command = "xcake"
- self.version = VERSION
- self.description = "Create and maintain Xcode project files easily."
-
- def run
- file_path = "#{Dir.pwd}/Cakefile"
-
- unless File.exist?(file_path)
- raise Xcake::Informative, "Couldn't find Cakefile"
+ def run
+ puts "Make me a cakefile dammit"
end
-
- puts "Reading Cakefile..."
- file_contents = File.read(file_path)
- cakefile = eval(file_contents)
-
- resolver = ProjectStructureResolver.new
- cakefile.accept(resolver)
-
- generator = Generator::Project.new
- cakefile.accept(generator)
end
end
end
diff --git a/lib/xcake/command/make.rb b/lib/xcake/command/make.rb
index <HASH>..<HASH> 100644
--- a/lib/xcake/command/make.rb
+++ b/lib/xcake/command/make.rb
@@ -1,28 +1,27 @@
require "claide"
module Xcake
- class MakeCommnd < CLAide::Command
+ class Command
+ class MakeCommnd < Command
+ self.description = "Makes the Xcode project from a Cakefile"
- self.command = "xcake"
- self.version = VERSION
- self.description = "Create and maintain Xcode project files easily."
+ def run
+ file_path = "#{Dir.pwd}/Cakefile"
- def run
- file_path = "#{Dir.pwd}/Cakefile"
+ unless File.exist?(file_path)
+ raise Xcake::Informative, "Couldn't find Cakefile"
+ end
- unless File.exist?(file_path)
- raise Xcake::Informative, "Couldn't find Cakefile"
- end
-
- puts "Reading Cakefile..."
- file_contents = File.read(file_path)
- cakefile = eval(file_contents)
+ puts "Reading Cakefile..."
+ file_contents = File.read(file_path)
+ cakefile = eval(file_contents)
- resolver = ProjectStructureResolver.new
- cakefile.accept(resolver)
+ resolver = ProjectStructureResolver.new
+ cakefile.accept(resolver)
- generator = Generator::Project.new
- cakefile.accept(generator)
+ generator = Generator::Project.new
+ cakefile.accept(generator)
+ end
end
end
end
diff --git a/lib/xcake/version.rb b/lib/xcake/version.rb
index <HASH>..<HASH> 100644
--- a/lib/xcake/version.rb
+++ b/lib/xcake/version.rb
@@ -1,3 +1,3 @@
module Xcake
- VERSION = "0.4.8"
+ VERSION = "0.5.0"
end
|
Wires up Xcake plugins.
|
igor-makarov_xcake
|
train
|
7708b1c5b538862707d873329ef64a3f8e230d55
|
diff --git a/elifetools/tests/test_parse_jats.py b/elifetools/tests/test_parse_jats.py
index <HASH>..<HASH> 100644
--- a/elifetools/tests/test_parse_jats.py
+++ b/elifetools/tests/test_parse_jats.py
@@ -397,6 +397,16 @@ class TestParseJats(unittest.TestCase):
[OrderedDict([('type', 'person'), ('name', OrderedDict([('preferred', u'Welcome Bender'), ('index', u'Bender, Welcome')])), ('affiliations', [OrderedDict([('name', [u'Department of Biological Chemistry and Molecular Pharmacology', u'Harvard Medical School']), ('address', OrderedDict([('formatted', [u'Boston', u'United States']), ('components', OrderedDict([('locality', [u'Boston']), ('country', u'United States')]))]))])]), ('phoneNumbers', [u'+16174321906']), ('contribution', u'WB, Conception and design, Acquisition of data, Analysis and interpretation of data, Drafting and revising the article'), ('competingInterests', u'The authors declare that no competing interests exist.')])]
),
+ # 02935 v1, group authors (collab) but no members of those groups
+ ('<root xmlns:xlink="http://www.w3.org/1999/xlink"><front><article-meta><contrib-group><contrib contrib-type="author"><collab>ICGC Breast Cancer Group</collab></contrib></contrib-group></article-meta></front></root>',
+ [OrderedDict([('type', 'group'), ('name', u'ICGC Breast Cancer Group'), ('people', [])])]
+ ),
+
+ # 02935 v2, excerpt for group author parsing
+ ('<root xmlns:xlink="http://www.w3.org/1999/xlink"><front><article-meta><contrib-group><contrib contrib-type="author"><contrib-id contrib-id-type="group-author-key">group-author-id1</contrib-id><collab>ICGC Breast Cancer Group</collab><xref ref-type="aff" rid="aff1"/></contrib><aff id="aff1"><institution content-type="dept">Cancer Genome Project</institution>, <institution>Wellcome Trust Sanger Institute</institution>, <addr-line><named-content content-type="city">Hinxton</named-content></addr-line>, <country>United Kingdom</country></aff></contrib-group><contrib-group><contrib contrib-type="author non-byline"><contrib-id contrib-id-type="group-author-key">group-author-id1</contrib-id><name><surname>Provenzano</surname><given-names>Elena</given-names></name><aff><institution content-type="dept">Cambridge Breast Unit</institution>, <institution>Addenbrooke’s Hospital, Cambridge University Hospital NHS Foundation Trust and NIHR Cambridge Biomedical Research Centre</institution>, <addr-line><named-content content-type="city">Cambridge CB2 2QQ</named-content></addr-line>, <country>UK</country></aff></contrib></contrib-group></article-meta></front></root>',
+ [OrderedDict([('type', 'group'), ('name', u'ICGC Breast Cancer Group'), ('affiliations', [OrderedDict([('name', [u'Cancer Genome Project', u'Wellcome Trust Sanger Institute']), ('address', OrderedDict([('formatted', [u'Hinxton', u'United Kingdom']), ('components', OrderedDict([('locality', [u'Hinxton']), ('country', u'United Kingdom')]))]))])]), ('people', [OrderedDict([('type', 'person'), ('name', OrderedDict([('preferred', u'Elena Provenzano'), ('index', u'Provenzano, Elena')])), ('affiliations', [OrderedDict([('name', [u'Cambridge Breast Unit', u'Addenbrooke\u2019s Hospital, Cambridge University Hospital NHS Foundation Trust and NIHR Cambridge Biomedical Research Centre']), ('address', OrderedDict([('formatted', [u'Cambridge CB2 2QQ', u'UK']), ('components', OrderedDict([('locality', [u'Cambridge CB2 2QQ']), ('country', u'UK')]))]))])])])])])]
+ ),
+
)
def test_authors_json_edge_cases(self, xml_content, expected):
soup = parser.parse_xml(xml_content)
|
Tests for a couple articles with group authors.
|
elifesciences_elife-tools
|
train
|
80d4234369e22ac346bf3e3f17323a7ad5c0f766
|
diff --git a/src/js/select2/selection/single.js b/src/js/select2/selection/single.js
index <HASH>..<HASH> 100644
--- a/src/js/select2/selection/single.js
+++ b/src/js/select2/selection/single.js
@@ -37,6 +37,7 @@ define([
.attr('role', 'textbox')
.attr('aria-readonly', 'true');
this.$selection.attr('aria-labelledby', id);
+ this.$selection.attr('aria-controls', id);
this.$selection.on('mousedown', function (evt) {
// Only respond to left clicks
|
Add aria-controls to combobox (#<I>)
|
select2_select2
|
train
|
2386f9da6d2b863abeecdc550ff6c6c04aba9ff9
|
diff --git a/PodioAPI.php b/PodioAPI.php
index <HASH>..<HASH> 100644
--- a/PodioAPI.php
+++ b/PodioAPI.php
@@ -91,16 +91,17 @@ class PodioBaseAPI {
protected $last_error;
private static $instance;
- private function __construct($url, $client_id, $client_secret, $frontend_token = '') {
+ private function __construct($url, $client_id, $client_secret, $upload_end_point, $frontend_token = '') {
$this->url = $url;
$this->client_id = $client_id;
$this->secret = $client_secret;
$this->frontend_token = $frontend_token;
+ $this->upload_end_point = $upload_end_point;
}
- public static function instance($url = '', $client_id = '', $client_secret = '', $frontend_token = '') {
+ public static function instance($url = '', $client_id = '', $client_secret = '', $upload_end_point = '', $frontend_token = '') {
if (!self::$instance) {
- self::$instance = new PodioBaseAPI($url, $client_id, $client_secret, $frontend_token);
+ self::$instance = new PodioBaseAPI($url, $client_id, $client_secret, $upload_end_point, $frontend_token);
}
return self::$instance;
}
@@ -119,7 +120,57 @@ class PodioBaseAPI {
public function getError() {
return $this->last_error;
}
-
+
+ /**
+ * Upload a file for later use.
+ */
+ public function upload($file, $name) {
+ $logger = &Log::singleton('error_log', '', 'HTTP_UPLOAD');
+ $oauth = PodioOAuth::instance();
+ $request = new HTTP_Request2($this->upload_end_point, HTTP_Request2::METHOD_POST, array(
+ 'ssl_verify_peer' => false,
+ 'ssl_verify_host' => false
+ ));
+
+ $request->setConfig('use_brackets', FALSE);
+ $request->setConfig('follow_redirects', TRUE);
+ $request->setHeader('User-Agent', 'Podio API Client/1.0');
+ $request->setHeader('Accept', 'application/json');
+ $request->setHeader('AccessToken', $oauth->access_token);
+ $request->setHeader('RefreshToken', $oauth->refresh_token);
+
+ $request->addUpload('file', $file);
+ $request->addPostParameter('name', $name);
+
+ try {
+ $response = $request->send();
+ switch ($response->getStatus()) {
+ case 200 :
+ case 201 :
+ case 204 :
+ return json_decode($response->getBody(), TRUE);
+ break;
+ case 401 :
+ case 400 :
+ case 403 :
+ case 404 :
+ case 410 :
+ case 500 :
+ case 503 :
+ $logger->log($request->getMethod() .' '. $response->getStatus().' '.$response->getReasonPhrase().' '.$request->getUrl(), PEAR_LOG_ERR);
+ $logger->log('*** '.$response->getBody(), PEAR_LOG_ERR);
+ $this->last_error = json_decode($response->getBody(), TRUE);
+ return FALSE;
+ break;
+ default :
+ break;
+ }
+ } catch (HTTP_Request2_Exception $e) {
+ $logger->log($e->getMessage(), PEAR_LOG_ERR);
+ }
+
+ }
+
/**
* Build and perform the request.
*/
|
Adding file upload method to API client
|
podio-community_podio-php
|
train
|
6e870fa2cbfc04c0cb173d6cd6b55b7418efc27b
|
diff --git a/build.gradle b/build.gradle
index <HASH>..<HASH> 100644
--- a/build.gradle
+++ b/build.gradle
@@ -36,7 +36,7 @@ ext {
gradleVersion = '2.8'
gradleScriptDir = "${rootProject.projectDir}/gradle"
- reactorVersion = '3.0.5.RELEASE'
+ reactorVersion = '3.0.6.RELEASE'
// Logging
slf4jVersion = '1.7.12'
diff --git a/src/main/java/reactor/ipc/stream/StreamSetup.java b/src/main/java/reactor/ipc/stream/StreamSetup.java
index <HASH>..<HASH> 100644
--- a/src/main/java/reactor/ipc/stream/StreamSetup.java
+++ b/src/main/java/reactor/ipc/stream/StreamSetup.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
+ * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -191,7 +191,7 @@ abstract class StreamSetup {
connect.subscribe(connectedState -> sink.success((API) connectedState),
sink::error);
}
- sink.setCancellation(c);
+ sink.onCancel(c);
}
}
}
diff --git a/src/test/java/reactor/ipc/socket/SimpleClient.java b/src/test/java/reactor/ipc/socket/SimpleClient.java
index <HASH>..<HASH> 100644
--- a/src/test/java/reactor/ipc/socket/SimpleClient.java
+++ b/src/test/java/reactor/ipc/socket/SimpleClient.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
+ * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,7 +65,7 @@ public final class SimpleClient extends SimplePeer {
try {
socket = new Socket(address, port);
- sink.setCancellation(() -> {
+ sink.onCancel(() -> {
try {
socket.close();
}
diff --git a/src/test/java/reactor/ipc/socket/SimpleServer.java b/src/test/java/reactor/ipc/socket/SimpleServer.java
index <HASH>..<HASH> 100644
--- a/src/test/java/reactor/ipc/socket/SimpleServer.java
+++ b/src/test/java/reactor/ipc/socket/SimpleServer.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
+ * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -88,7 +88,7 @@ public final class SimpleServer extends SimplePeer {
acceptor.schedule(() -> socketAccept(ioHandler, connectedState,
acceptor));
- sink.setCancellation(() -> connectedState.close(c));
+ sink.onCancel(() -> connectedState.close(c));
});
}
|
update Mono.setCancellation to onCancel
|
reactor-attic_reactor-ipc
|
train
|
95d0db8d7133253ad00e4507af07825cc2b341f9
|
diff --git a/Kwf/Controller/Front.php b/Kwf/Controller/Front.php
index <HASH>..<HASH> 100644
--- a/Kwf/Controller/Front.php
+++ b/Kwf/Controller/Front.php
@@ -124,6 +124,14 @@ class Kwf_Controller_Front extends Zend_Controller_Front
{
if ($request === null) {
if (PHP_SAPI == 'cli') {
+ $argv = $_SERVER['argv'];
+ if (isset($argv[1]) && $argv[1] == 'symfony') {
+ unset($argv[0]);
+ unset($argv[1]);
+ $cmd = './symfony/bin/console --ansi '.implode(' ', array_map('escapeshellarg', $argv));
+ passthru($cmd, $retVar);
+ exit($retVar);
+ }
$request = new Kwf_Controller_Request_Cli();
} else {
$request = new Kwf_Controller_Request_Http();
|
Add vps symfony command that starts a child process with symfony console
|
koala-framework_koala-framework
|
train
|
e59f08cce08aa889203835f333659c848766146a
|
diff --git a/src/Viserio/Component/Mail/Transport/MailgunTransport.php b/src/Viserio/Component/Mail/Transport/MailgunTransport.php
index <HASH>..<HASH> 100644
--- a/src/Viserio/Component/Mail/Transport/MailgunTransport.php
+++ b/src/Viserio/Component/Mail/Transport/MailgunTransport.php
@@ -36,17 +36,28 @@ class MailgunTransport extends AbstractTransport
protected $url;
/**
+ * Mailgun base url.
+ *
+ * @see https://documentation.mailgun.com/en/latest/api-intro.html#mailgun-regions
+ *
+ * @var string
+ */
+ protected $baseUrl;
+
+ /**
* Create a new Mailgun transport instance.
*
* @param \GuzzleHttp\Client $client
* @param string $key
* @param string $domain
+ * @param null|string $baseUrl
*/
- public function __construct(Client $client, string $key, string $domain)
+ public function __construct(Client $client, string $key, string $domain, ?string $baseUrl = null)
{
$this->client = $client;
$this->key = $key;
$this->setDomain($domain);
+ $this->baseUrl = $baseUrl ?? 'https://api.mailgun.net';
}
/**
@@ -125,7 +136,7 @@ class MailgunTransport extends AbstractTransport
*/
public function setDomain(string $domain): self
{
- $this->url = 'https://api.mailgun.net/v3/' . $domain . '/messages.mime';
+ $this->url = $this->baseUrl . '/v3/' . $domain . '/messages.mime';
$this->domain = $domain;
diff --git a/src/Viserio/Component/Mail/TransportFactory.php b/src/Viserio/Component/Mail/TransportFactory.php
index <HASH>..<HASH> 100644
--- a/src/Viserio/Component/Mail/TransportFactory.php
+++ b/src/Viserio/Component/Mail/TransportFactory.php
@@ -225,7 +225,8 @@ class TransportFactory implements LoggerAwareInterface
return new MailgunTransport(
$this->getHttpClient($config),
$config['secret'],
- $config['domain']
+ $config['domain'],
+ $config['base_url'] ?? null
);
}
|
Allow user-defined base url for mailgun
|
narrowspark_framework
|
train
|
e9a8ee8915c390e3316cd135aaf4167d737a92d1
|
diff --git a/Joomla/Sniffs/Commenting/FunctionCommentSniff.php b/Joomla/Sniffs/Commenting/FunctionCommentSniff.php
index <HASH>..<HASH> 100644
--- a/Joomla/Sniffs/Commenting/FunctionCommentSniff.php
+++ b/Joomla/Sniffs/Commenting/FunctionCommentSniff.php
@@ -147,7 +147,7 @@ class Joomla_Sniffs_Commenting_FunctionCommentSniff extends PEAR_Sniffs_Commenti
{
if ($tokens[$returnToken]['code'] === T_CLOSURE
|| $tokens[$returnToken]['code'] === T_ANON_CLASS
- )
+ )
{
$returnToken = $tokens[$returnToken]['scope_closer'];
continue;
@@ -156,7 +156,7 @@ class Joomla_Sniffs_Commenting_FunctionCommentSniff extends PEAR_Sniffs_Commenti
if ($tokens[$returnToken]['code'] === T_RETURN
|| $tokens[$returnToken]['code'] === T_YIELD
|| $tokens[$returnToken]['code'] === T_YIELD_FROM
- )
+ )
{
break;
}
@@ -186,7 +186,7 @@ class Joomla_Sniffs_Commenting_FunctionCommentSniff extends PEAR_Sniffs_Commenti
{
if ($tokens[$returnToken]['code'] === T_CLOSURE
|| $tokens[$returnToken]['code'] === T_ANON_CLASS
- )
+ )
{
$returnToken = $tokens[$returnToken]['scope_closer'];
continue;
@@ -195,7 +195,7 @@ class Joomla_Sniffs_Commenting_FunctionCommentSniff extends PEAR_Sniffs_Commenti
if ($tokens[$returnToken]['code'] === T_RETURN
|| $tokens[$returnToken]['code'] === T_YIELD
|| $tokens[$returnToken]['code'] === T_YIELD_FROM
- )
+ )
{
break;
}
|
Multi-line IF statement not indented correctly
|
joomla_coding-standards
|
train
|
65e59b3140251283603f3a1da8f7ac4481e24507
|
diff --git a/lease/file_leaser.go b/lease/file_leaser.go
index <HASH>..<HASH> 100644
--- a/lease/file_leaser.go
+++ b/lease/file_leaser.go
@@ -38,17 +38,20 @@ type FileLeaser interface {
}
// Create a new file leaser that uses the supplied directory for temporary
-// files (before unlinking them) and attempts to keep usage in bytes below the
-// given limit. If dir is empty, the system default will be used.
+// files (before unlinking them) and attempts to keep usage in number of files
+// and bytes below the given limits. If dir is empty, the system default will be
+// used.
//
-// Usage may exceed the given limit if there are read/write leases whose total
-// size exceeds the limit, since such leases cannot be revoked.
+// Usage may exceed the given limits if there are read/write leases whose total
+// size exceeds the limits, since such leases cannot be revoked.
func NewFileLeaser(
dir string,
+ limitNumFiles int,
limitBytes int64) (fl FileLeaser) {
typed := &fileLeaser{
dir: dir,
- limit: limitBytes,
+ limitNumFiles: limitNumFiles,
+ limitBytes: limitBytes,
readLeasesIndex: make(map[*readLease]*list.Element),
}
@@ -63,8 +66,9 @@ type fileLeaser struct {
// Constant data
/////////////////////////
- dir string
- limit int64
+ dir string
+ limitNumFiles int
+ limitBytes int64
/////////////////////////
// Mutable state
@@ -102,7 +106,7 @@ type fileLeaser struct {
//
// INVARIANT: Equal to the sum over readLeases sizes.
// INVARIANT: 0 <= readOutstanding
- // INVARIANT: readOutstanding <= max(0, limit - readWriteOutstanding)
+ // INVARIANT: readOutstanding <= max(0, limitBytes - readWriteOutstanding)
readOutstanding int64
// Index of read leases by pointer.
@@ -180,12 +184,12 @@ func (fl *fileLeaser) checkInvariants() {
panic(fmt.Sprintf("Unexpected readOutstanding: %v", fl.readOutstanding))
}
- // INVARIANT: readOutstanding <= max(0, limit - readWriteOutstanding)
- if !(fl.readOutstanding <= maxInt64(0, fl.limit-fl.readWriteOutstanding)) {
+ // INVARIANT: readOutstanding <= max(0, limitBytes - readWriteOutstanding)
+ if !(fl.readOutstanding <= maxInt64(0, fl.limitBytes-fl.readWriteOutstanding)) {
panic(fmt.Sprintf(
- "Unexpected readOutstanding: %v. limit: %v, readWriteOutstanding: %v",
+ "Unexpected readOutstanding: %v. limitBytes: %v, readWriteOutstanding: %v",
fl.readOutstanding,
- fl.limit,
+ fl.limitBytes,
fl.readWriteOutstanding))
}
@@ -205,7 +209,7 @@ func (fl *fileLeaser) checkInvariants() {
}
// Add the supplied delta to the leaser's view of outstanding read/write lease
-// bytes, then revoke read leases until we're under limit or we run out of
+// bytes, then revoke read leases until we're under limitBytes or we run out of
// leases to revoke.
//
// Called by readWriteLease while holding its lock.
@@ -213,20 +217,20 @@ func (fl *fileLeaser) checkInvariants() {
// LOCKS_EXCLUDED(fl.mu)
func (fl *fileLeaser) addReadWriteByteDelta(delta int64) {
fl.readWriteOutstanding += delta
- fl.evict(fl.limit)
+ fl.evict(fl.limitBytes)
}
// LOCKS_REQUIRED(fl.mu)
-func (fl *fileLeaser) overLimit(limit int64) bool {
- return fl.readOutstanding+fl.readWriteOutstanding > limit
+func (fl *fileLeaser) overLimit(limitBytes int64) bool {
+ return fl.readOutstanding+fl.readWriteOutstanding > limitBytes
}
-// Revoke read leases until we're within the given limit or we run out of
+// Revoke read leases until we're within the given limitBytes or we run out of
// things to revoke.
//
// LOCKS_REQUIRED(fl.mu)
-func (fl *fileLeaser) evict(limit int64) {
- for fl.overLimit(limit) {
+func (fl *fileLeaser) evict(limitBytes int64) {
+ for fl.overLimit(limitBytes) {
// Do we have anything to revoke?
lru := fl.readLeases.Back()
if lru == nil {
@@ -270,7 +274,7 @@ func (fl *fileLeaser) downgrade(
fl.readLeasesIndex[rlTyped] = e
// Ensure that we're not now over capacity.
- fl.evict(fl.limit)
+ fl.evict(fl.limitBytes)
return
}
|
Updated NewFileLeaser.
|
jacobsa_ratelimit
|
train
|
4f2868acb356be1679a0124121fd927e2cbc5f9d
|
diff --git a/library/Garp/Util/String.php b/library/Garp/Util/String.php
index <HASH>..<HASH> 100755
--- a/library/Garp/Util/String.php
+++ b/library/Garp/Util/String.php
@@ -125,6 +125,7 @@ class Garp_Util_String {
* @return String
*/
static public function excerpt($content, $chars = 140, $respectWords = true) {
+ $content = str_replace(array("<br>", "<br />", "<br >", "<br/>"), "\n",$content);
$content = htmlspecialchars(
str_replace(
array(
diff --git a/tests/library/Garp/Util/StringTest.php b/tests/library/Garp/Util/StringTest.php
index <HASH>..<HASH> 100644
--- a/tests/library/Garp/Util/StringTest.php
+++ b/tests/library/Garp/Util/StringTest.php
@@ -97,6 +97,17 @@ class Garp_Util_StringTest extends Garp_Test_PHPUnit_TestCase {
'Small font Large font Colored font Bold font Italic font and more...');
$this->assertEquals(Garp_Util_String::excerpt("<div class=\"beautify\">x</div>"),"x");
+ $this->assertEquals(Garp_Util_String::excerpt("<p><strong>Uw uitdaging</strong><br>
+ Geen tijd over voor het beheren van uw werkplekken?</p>"), "Uw uitdaging\n
+ Geen tijd over voor het beheren van uw werkplekken?");
+
+ //test different <br> writing styles
+ $this->assertEquals(Garp_Util_String::excerpt("<p><strong>Testing</strong> the <br>break <br />with different formats</p>"), "Testing the \nbreak \nwith different formats");
+ $this->assertEquals(Garp_Util_String::excerpt("<p><strong>Testing</strong> the <br >break <br/>with different formats</p>"), "Testing the \nbreak \nwith different formats");
+
+ //test imput of a space if there is none
+ $this->assertEquals(Garp_Util_String::excerpt("<p><strong>insert</strong> a<br >space<br/>here</p>"), "insert a\nspace\nhere");
+
//this is not working
// $this->assertEquals(Garp_Util_String::excerpt("</div><div>x</div>"),"x");
}
|
Tweaked the excerpt method in String.php and wrote some tests for this
|
grrr-amsterdam_garp3
|
train
|
75f961167570967e81ee52e49c88227e90446931
|
diff --git a/wasp_launcher/core_broker.py b/wasp_launcher/core_broker.py
index <HASH>..<HASH> 100644
--- a/wasp_launcher/core_broker.py
+++ b/wasp_launcher/core_broker.py
@@ -134,3 +134,39 @@ class WResponsiveTask:
WAppsGlobals.broker_calls.add_task(task_uid, scheduler_name)
task_source.add_record(schedule_record)
return WCommandResult(output='Task submitted. Task id: %s' % task_uid, broker_last_task=task_uid)
+
+
+# noinspection PyAbstractClass
+class WResponsiveBrokerCommand(WBrokerCommand):
+
+ __command__ = None
+ __arguments__ = []
+ __argument_relationships = None
+
+ __scheduler_instance__ = None
+ __task_source_name__ = None
+
+ def __init__(self):
+ if self.__command__ is None:
+ raise ValueError('__command__ must be redefined in a subclass')
+
+ WBrokerCommand.__init__(
+ self, self.__command__, *self.__arguments__, relationships=self.__argument_relationships
+ )
+ if self.__task_source_name__ is None:
+ raise ValueError('__task_source_name__ must be redefined in a subclass')
+
+ def _exec(self, command_arguments, **command_env):
+ task = self.create_task(command_arguments, **command_env)
+ rt = WResponsiveTask(task, self.__task_source_name__, scheduler_instance=self.__scheduler_instance__)
+ return rt.submit_task()
+
+ @abstractmethod
+ def create_task(self, command_arguments, **command_env):
+ """
+
+ :param command_arguments:
+ :param command_env:
+ :return: WLauncherScheduleTask
+ """
+ raise NotImplementedError('This method is abstract')
|
wasp_launcher/core_broker.py: WResponsiveBrokerCommand class as a shortcut for WBrokerCommand/WResponsiveTask usage was added
|
a1ezzz_wasp-launcher
|
train
|
88ff336aabe037d1fb51b5104a1f17ba3770879f
|
diff --git a/test/level2/events.js b/test/level2/events.js
index <HASH>..<HASH> 100644
--- a/test/level2/events.js
+++ b/test/level2/events.js
@@ -1,5 +1,6 @@
var sys = require('sys');
var testcase = require('nodeunit').testCase;
+var events = require("../../lib/jsdom/level2/events").dom.level2.events;
var EventMonitor = function() {
self = this;
self.atEvents = [];
@@ -41,8 +42,6 @@ var _tearDown = function(xs) {
})
}
-global.events = require("../../lib/jsdom/level2/events").dom.level2.events;
-
// A document is created using implementation.createDocument and cast to a DocumentEvent interface.
// @author Curt Arnold
// @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent
|
changed global.events to var events
|
jsdom_jsdom
|
train
|
71605ca97f380379c04d4e784a145f73776cf038
|
diff --git a/demo_project/settings.py b/demo_project/settings.py
index <HASH>..<HASH> 100644
--- a/demo_project/settings.py
+++ b/demo_project/settings.py
@@ -78,6 +78,7 @@ INSTALLED_APPS = (
'django.contrib.admin',
'easy_thumbnails',
'userena',
+ 'extra',
)
# Settings required for userena
diff --git a/userena/models.py b/userena/models.py
index <HASH>..<HASH> 100644
--- a/userena/models.py
+++ b/userena/models.py
@@ -7,6 +7,7 @@ from django.conf import settings
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
+from django.core.exceptions import ImproperlyConfigured
from userena import settings as userena_settings
from userena.utils import get_gravatar
@@ -140,7 +141,7 @@ class AccountManager(models.Manager):
account.user.delete()
return deleted_users
-class Account(models.Model):
+class BaseAccount(models.Model):
"""
A user account which stores all the nescessary information to have a full
functional user implementation on your Django website.
@@ -189,6 +190,10 @@ class Account(models.Model):
objects = AccountManager()
+ class Meta:
+ if userena_settings.USERENA_CHILD_MODEL:
+ abstract = True
+
def __unicode__(self):
return '%s' % self.user
@@ -357,4 +362,23 @@ class Account(models.Model):
return userena_settings.USERENA_MUGSHOT_DEFAULT
else: return None
+def get_account_model():
+ """
+ Returns the right account model so your user application can be easily
+ extended without adding extra relationships.
+
+ """
+ from django.db.models import get_model
+ if userena_settings.USERENA_CHILD_MODEL:
+ account_model = get_model(*userena_settings.USERENA_CHILD_MODEL.split('.', 2))
+ if not account_model:
+ raise ImproperlyConfigured('Cannot find the model defined in ``USERINA_CHILD_MODEL``.')
+ return account_model
+
+ return Account
+
+# Return the model that's used for account functionality
+Account = get_account_model()
+
+# Always return an account when asked through a user
User.account = property(lambda u: Account.objects.get_or_create(user=u)[0])
diff --git a/userena/settings.py b/userena/settings.py
index <HASH>..<HASH> 100644
--- a/userena/settings.py
+++ b/userena/settings.py
@@ -58,3 +58,8 @@ USERENA_MUGSHOT_PATH = getattr(settings,
USERENA_USE_HTTPS = getattr(settings,
'USERENA_USE_HTTPS',
False)
+
+# Child model. Use it if more fields are needed.
+USERENA_CHILD_MODEL= getattr(settings,
+ 'USERENA_CHILD_MODEL',
+ None)
|
Added an option to add a child model without adding another relationship
|
django-userena-ce_django-userena-ce
|
train
|
7a6f27fed9e88bcddfee88022ebc19df88656555
|
diff --git a/gns3server/modules/virtualbox/virtualbox_vm.py b/gns3server/modules/virtualbox/virtualbox_vm.py
index <HASH>..<HASH> 100644
--- a/gns3server/modules/virtualbox/virtualbox_vm.py
+++ b/gns3server/modules/virtualbox/virtualbox_vm.py
@@ -799,6 +799,9 @@ class VirtualBoxVM(object):
# add a guest property to let the VM know about the GNS3 name
self._execute("guestproperty", ["set", self._vmname, "NameInGNS3", self._name])
+ # add a guest property to let the VM know about the GNS3 project directory
+ self._execute("guestproperty", ["set", self._vmname, "ProjectDirInGNS3", self._working_dir])
+
if self._enable_remote_console:
# starts the Telnet to pipe thread
pipe_name = self._get_pipe_name()
|
New VirtualBox guest property: ProjectDirInGNS3.
|
GNS3_gns3-server
|
train
|
8b1a62dbcf737ef6dd787259ca3f21f581e59504
|
diff --git a/src/dolo/misc/yamlfile.py b/src/dolo/misc/yamlfile.py
index <HASH>..<HASH> 100644
--- a/src/dolo/misc/yamlfile.py
+++ b/src/dolo/misc/yamlfile.py
@@ -133,7 +133,7 @@ Imports the content of a modfile into the current interpreter scope
model.check_consistency(auto_remove_variables=False)
return model
-def yaml_import(filename,names_dict={},full_output=False,verbose=False):
+def yaml_import(filename,verbose=False):
'''Imports model defined in specified file'''
import os
basename = os.path.basename(filename)
|
removed never used options in yaml_import
|
EconForge_dolo
|
train
|
9d70ff56e7d45ca6d26ee5725cdea6288585358b
|
diff --git a/server/sonar-web/src/main/js/api/ce.js b/server/sonar-web/src/main/js/api/ce.js
index <HASH>..<HASH> 100644
--- a/server/sonar-web/src/main/js/api/ce.js
+++ b/server/sonar-web/src/main/js/api/ce.js
@@ -30,6 +30,15 @@ export function getActivity (data) {
return $.get(url, data);
}
+export function getStatus (componentId) {
+ const url = window.baseUrl + '/api/ce/activity_status';
+ const data = {};
+ if (componentId) {
+ Object.assign(data, { componentId });
+ }
+ return getJSON(url, data);
+}
+
export function getTask (id) {
const url = window.baseUrl + '/api/ce/task';
return getJSON(url, { id }).then(r => r.task);
diff --git a/server/sonar-web/src/main/js/apps/background-tasks/store/actions.js b/server/sonar-web/src/main/js/apps/background-tasks/store/actions.js
index <HASH>..<HASH> 100644
--- a/server/sonar-web/src/main/js/apps/background-tasks/store/actions.js
+++ b/server/sonar-web/src/main/js/apps/background-tasks/store/actions.js
@@ -18,12 +18,10 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import _ from 'underscore';
-import { getTypes, getActivity, cancelAllTasks, cancelTask as cancelTaskAPI } from '../../../api/ce';
+import { getTypes, getActivity, getStatus, cancelAllTasks, cancelTask as cancelTaskAPI } from '../../../api/ce';
import { STATUSES, ALL_TYPES, CURRENTS, DEBOUNCE_DELAY } from '../constants';
-const PAGE_SIZE = 1000;
-
export const INIT = 'INIT';
export const REQUEST_TASKS = 'REQUEST_TASKS';
export const RECEIVE_TASKS = 'RECEIVE_TASKS';
@@ -151,16 +149,16 @@ function fetchTasks (filters) {
dispatch(requestTasks(filters));
return Promise.all([
- getActivity(parameters)
+ getActivity(parameters),
+ getStatus(parameters.componentId)
]).then(responses => {
- const [activity] = responses;
+ const [activity, status] = responses;
const tasks = activity.tasks;
dispatch(receiveTasks(tasks));
- // FIXME request real numbers
- const pendingCount = 0;
- const failingCount = 0;
+ const pendingCount = status.pending;
+ const failingCount = status.failing;
dispatch(receiveStats({ pendingCount, failingCount }));
});
|
SONAR-<I> use api/ce/activity_status to get number of pending and failing tasks
|
SonarSource_sonarqube
|
train
|
76851a4d358150ba3f8710d74fd0b900f93abc4f
|
diff --git a/pg4nosql/PostgresNoSQLResultItem.py b/pg4nosql/PostgresNoSQLResultItem.py
index <HASH>..<HASH> 100644
--- a/pg4nosql/PostgresNoSQLResultItem.py
+++ b/pg4nosql/PostgresNoSQLResultItem.py
@@ -1,4 +1,4 @@
-from pg4nosql import DEFAULT_JSON_COLUMN_NAME
+from pg4nosql import DEFAULT_JSON_COLUMN_NAME, DEFAULT_ROW_IDENTIFIER
class PostgresNoSQLResultItem(object):
@@ -7,6 +7,7 @@ class PostgresNoSQLResultItem(object):
self.__inner_result = inner_result
self.json = self.PostgresNoSQLJSONDocument(self.__inner_result)
self.columns = self.__inner_result.keys()
+ self.id = self.__inner_result.get(DEFAULT_ROW_IDENTIFIER, None)
def __str__(self):
return str(self.__inner_result)
|
implemented id field on result item
|
cansik_pg4nosql
|
train
|
6ec0a0f66a7c51290677289b9752055f5031ff54
|
diff --git a/flask_erppeek/__init__.py b/flask_erppeek/__init__.py
index <HASH>..<HASH> 100644
--- a/flask_erppeek/__init__.py
+++ b/flask_erppeek/__init__.py
@@ -1,8 +1,2 @@
-"""
- __init__.py
- ~~~~~~~~~~~
- :copyright: (c) 2010-2011 Stephane Wirtel <stephane@wirtel.be>
- :license: LGPLv2
-"""
-
-from openerp import *
+from __future__ import absolute_import
+from .openerp import *
|
Improve python3 compatibility
|
gisce_flask-erppeek
|
train
|
be113c78736afc2f1e3cee7ea4f7eb7fc8db968a
|
diff --git a/src/amcrest/http.py b/src/amcrest/http.py
index <HASH>..<HASH> 100644
--- a/src/amcrest/http.py
+++ b/src/amcrest/http.py
@@ -12,8 +12,8 @@
# vim:sw=4:ts=4:et
import logging
import requests
-
from requests.adapters import HTTPAdapter
+import threading
from amcrest.utils import clean_url, pretty
@@ -54,27 +54,16 @@ class Http(System, Network, MotionDetection, Snapshot,
self._protocol = protocol
self._base_url = self.__base_url()
- if timeout_protocol is None:
- self._timeout_protocol = TIMEOUT_HTTP_PROTOCOL
- else:
- self._timeout_protocol = timeout_protocol
+ self._retries_default = (retries_connection or
+ MAX_RETRY_HTTP_CONNECTION)
+ self._timeout_default = timeout_protocol or TIMEOUT_HTTP_PROTOCOL
- self._retries_conn = None
- self._set_command_session(
- retries_connection or MAX_RETRY_HTTP_CONNECTION)
+ self._session = {}
+ self._get_session_lock = threading.Lock()
self._token = self._generate_token()
self._set_name()
- def _set_command_session(self, max_retries):
- if max_retries is not None and self._retries_conn != max_retries:
- self._retries_conn = max_retries
- self._session = requests.Session()
- self._session.mount(
- 'http://', HTTPAdapter(max_retries=max_retries))
- self._session.mount(
- 'https://', HTTPAdapter(max_retries=max_retries))
-
def _generate_token(self):
"""Discover which authentication method to use.
@@ -132,6 +121,18 @@ class Http(System, Network, MotionDetection, Snapshot,
def get_base_url(self):
return self._base_url
+ def _get_session(self, max_retries):
+ with self._get_session_lock:
+ try:
+ return self._session[max_retries]
+ except KeyError:
+ session = requests.Session()
+ adapter = HTTPAdapter(max_retries=max_retries)
+ session.mount('http://', adapter)
+ session.mount('https://', adapter)
+ self._session[max_retries] = session
+ return session
+
def command(self, cmd, retries=None, timeout_cmd=None):
"""
Args:
@@ -139,20 +140,19 @@ class Http(System, Network, MotionDetection, Snapshot,
timeout_cmd - timeout, default 3sec
retries - maximum number of retries each connection should attempt
"""
- if timeout_cmd is not None:
- self._timeout_protocol = timeout_cmd
-
- self._set_command_session(retries)
+ retries = retries or self._retries_default
+ timeout = timeout_cmd or self._timeout_default
+ session = self._get_session(retries)
url = self.__base_url(cmd)
- for loop in range(1, 2 + self._retries_conn):
+ for loop in range(1, 2 + retries):
_LOGGER.debug("Running query attempt %s", loop)
try:
- resp = self._session.get(
+ resp = session.get(
url,
auth=self._token,
stream=True,
- timeout=self._timeout_protocol,
+ timeout=timeout,
)
resp.raise_for_status()
break
@@ -171,8 +171,7 @@ class Http(System, Network, MotionDetection, Snapshot,
timeout=None):
url = self.__base_url(cmd)
- if timeout is not None:
- timeout = self._timeout_protocol
+ timeout = timeout or self._timeout_default
try:
requests.post(
|
Keep session per max_retries
Create a dictionary of sessions, with max_retries as key, so they can be reused once created. Also _retries_conn and _timeout_protocol usage was not thread safe; fix that.
|
tchellomello_python-amcrest
|
train
|
f9073df1d0dba2a2d8af75a26f6bcc29925b5a4a
|
diff --git a/github-linguist.gemspec b/github-linguist.gemspec
index <HASH>..<HASH> 100644
--- a/github-linguist.gemspec
+++ b/github-linguist.gemspec
@@ -16,7 +16,7 @@ Gem::Specification.new do |s|
s.add_dependency 'charlock_holmes', '~> 0.7.6'
s.add_dependency 'escape_utils', '~> 1.2.0'
- s.add_dependency 'mime-types', '>= 1.19'
+ s.add_dependency 'mini_mime', '~> 1.0'
s.add_dependency 'rugged', '>= 0.25.1'
s.add_development_dependency 'minitest', '>= 5.0'
diff --git a/lib/linguist/blob_helper.rb b/lib/linguist/blob_helper.rb
index <HASH>..<HASH> 100644
--- a/lib/linguist/blob_helper.rb
+++ b/lib/linguist/blob_helper.rb
@@ -1,7 +1,7 @@
require 'linguist/generated'
require 'charlock_holmes'
require 'escape_utils'
-require 'mime/types'
+require 'mini_mime'
require 'yaml'
module Linguist
@@ -33,12 +33,7 @@ module Linguist
if defined? @_mime_type
@_mime_type
else
- guesses = ::MIME::Types.type_for(extname.to_s)
-
- # Prefer text mime types over binary
- @_mime_type = guesses.detect { |type| type.ascii? } ||
- # Otherwise use the first guess
- guesses.first
+ @_mime_type = MiniMime.lookup_by_filename(name)
end
end
@@ -51,7 +46,7 @@ module Linguist
#
# Returns a mime type String.
def mime_type
- _mime_type ? _mime_type.to_s : 'text/plain'
+ _mime_type ? _mime_type.content_type : 'text/plain'
end
# Internal: Is the blob binary according to its mime type
@@ -275,7 +270,7 @@ module Linguist
# also--importantly--without having to duplicate many (potentially
# large) strings.
begin
-
+
data.split(encoded_newlines_re, -1)
rescue Encoding::ConverterNotFoundError
# The data is not splittable in the detected encoding. Assume it's
diff --git a/test/test_blob.rb b/test/test_blob.rb
index <HASH>..<HASH> 100644
--- a/test/test_blob.rb
+++ b/test/test_blob.rb
@@ -253,7 +253,7 @@ class TestBlob < Minitest::Test
def test_vendored
assert !fixture_blob_memory("Data/README").vendored?
-
+
# Go fixtures
assert sample_blob("Go/testdata/foo.yml").vendored?
end
|
Update dependencies: use mini mime instead of mime type (#<I>)
* migrate to mini_mime
in an effort to clean up dependencies, moving linguist to mini_mime
removes a second mime library from being required
* update version
* remove version bump
|
github_linguist
|
train
|
976adb69bda8d02ecf1f9c1eec82aea3aae1578d
|
diff --git a/lib/temperature.js b/lib/temperature.js
index <HASH>..<HASH> 100644
--- a/lib/temperature.js
+++ b/lib/temperature.js
@@ -2,10 +2,10 @@
module.exports = require('./quantity')('temperature')
.base('C', {
- names: [ 'C', 'c', 'celsius' ]
+ names: [ 'C', 'c', '°C', 'celsius' ]
})
.add('K', {
- names: [ 'K', 'kelvin', 'kelvins' ],
+ names: [ 'K', '°K', 'kelvin', 'kelvins' ],
prefix: true,
toBase: function(value) {
return value - 273.15;
@@ -15,7 +15,7 @@ module.exports = require('./quantity')('temperature')
}
})
.add('F', {
- names: [ 'F', 'f', 'fahrenheit', 'fahrenheits' ],
+ names: [ 'F', 'f', '°F', 'fahrenheit', 'fahrenheits' ],
toBase: function(value) {
return (value - 32) * (5/9);
},
|
Include temperatures using ° in their unit
|
aholstenson_amounts
|
train
|
84884d343bc5814177a1f8a79cc30e8ad0c614c9
|
diff --git a/telemetry/telemetry/core/timeline/inspector_importer_unittest.py b/telemetry/telemetry/core/timeline/inspector_importer_unittest.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/timeline/inspector_importer_unittest.py
+++ b/telemetry/telemetry/core/timeline/inspector_importer_unittest.py
@@ -4,6 +4,7 @@
import unittest
from telemetry.core.timeline import inspector_importer
+from telemetry.core.timeline import model
_SAMPLE_MESSAGE = {
'children': [
@@ -99,3 +100,13 @@ class InspectorEventParsingTest(unittest.TestCase):
event = (inspector_importer.InspectorTimelineImporter.
RawEventToTimelineEvent(raw_event))
self.assertEquals(None, event)
+
+class InspectorImporterTest(unittest.TestCase):
+ def testImport(self):
+ m = model.TimelineModel([_SAMPLE_MESSAGE], shift_world_to_zero=False)
+ self.assertEquals(1, len(m.processes))
+ self.assertEquals(1, len(m.processes.values()[0].threads))
+ renderer_thread = m.GetAllThreads()[0]
+ self.assertEquals(1, len(renderer_thread.toplevel_slices))
+ self.assertEquals('Program',
+ renderer_thread.toplevel_slices[0].name)
diff --git a/telemetry/telemetry/core/timeline/model.py b/telemetry/telemetry/core/timeline/model.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/timeline/model.py
+++ b/telemetry/telemetry/core/timeline/model.py
@@ -60,6 +60,9 @@ class TimelineModel(object):
for importer in importers:
importer.FinalizeImport()
+ for process in self.processes.itervalues():
+ process.FinalizeImport()
+
if shift_world_to_zero:
self.ShiftWorldToZero()
self.UpdateBounds()
diff --git a/telemetry/telemetry/core/timeline/trace_event_importer.py b/telemetry/telemetry/core/timeline/trace_event_importer.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/timeline/trace_event_importer.py
+++ b/telemetry/telemetry/core/timeline/trace_event_importer.py
@@ -240,9 +240,6 @@ class TraceEventTimelineImporter(importer.TimelineImporter):
self._CreateExplicitObjects()
self._CreateImplicitObjects()
- for process in self._model.processes.itervalues():
- process.FinalizeImport()
-
def _CreateAsyncSlices(self):
if len(self._all_async_events) == 0:
return
|
[telemetry] Add a trace-based loading measurement
As part of this, refactor loading.py into various components to foster code sharing between the three loading measurement flavors.
R=tonyg
Review URL: <URL>
|
catapult-project_catapult
|
train
|
d597292f3c54e322548c48fe6e2649c67d564704
|
diff --git a/test/CapturedExceptions.js b/test/CapturedExceptions.js
index <HASH>..<HASH> 100644
--- a/test/CapturedExceptions.js
+++ b/test/CapturedExceptions.js
@@ -3,19 +3,19 @@ var CapturedExceptions = {};
CapturedExceptions.opera_854 = {
message: "Statement on line 44: Type mismatch (usually a non-object value used where an object is required)\n" +
"Backtrace:\n" +
- " Line 44 of linked script file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/stacktrace.js\n" +
+ " Line 44 of linked script file://localhost/G:/js/stacktrace.js\n" +
" this.undef();\n" +
- " Line 31 of linked script file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/stacktrace.js\n" +
+ " Line 31 of linked script file://localhost/G:/js/stacktrace.js\n" +
" ex = ex || this.createException();\n" +
- " Line 18 of linked script file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/stacktrace.js\n" +
+ " Line 18 of linked script file://localhost/G:/js/stacktrace.js\n" +
" var p = new printStackTrace.implementation(), result = p.run(ex);\n" +
- " Line 4 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 4 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" printTrace(printStackTrace());\n" +
- " Line 7 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" bar(n - 1);\n" +
- " Line 11 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 11 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" bar(2);\n" +
- " Line 15 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 15 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" foo();\n" +
"",
'opera#sourceloc': 44
@@ -24,19 +24,19 @@ CapturedExceptions.opera_854 = {
CapturedExceptions.opera_902 = {
message: "Statement on line 44: Type mismatch (usually a non-object value used where an object is required)\n" +
"Backtrace:\n" +
- " Line 44 of linked script file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/stacktrace.js\n" +
+ " Line 44 of linked script file://localhost/G:/js/stacktrace.js\n" +
" this.undef();\n" +
- " Line 31 of linked script file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/stacktrace.js\n" +
+ " Line 31 of linked script file://localhost/G:/js/stacktrace.js\n" +
" ex = ex || this.createException();\n" +
- " Line 18 of linked script file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/stacktrace.js\n" +
+ " Line 18 of linked script file://localhost/G:/js/stacktrace.js\n" +
" var p = new printStackTrace.implementation(), result = p.run(ex);\n" +
- " Line 4 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 4 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" printTrace(printStackTrace());\n" +
- " Line 7 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" bar(n - 1);\n" +
- " Line 11 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 11 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" bar(2);\n" +
- " Line 15 of inline#1 script in file://localhost/G:/aptana/DevTools/stacktrace/javascript-stacktrace/test/functional/testcase1.html\n" +
+ " Line 15 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" +
" foo();\n" +
"",
'opera#sourceloc': 44
|
Shortened paths in Opera stacktrace
|
stacktracejs_stacktrace.js
|
train
|
d71baac6fc6b7cd1d10cf914f326f74771ef7f41
|
diff --git a/Classes/TYPO3/DocTools/Command/DocumentationCommandController.php b/Classes/TYPO3/DocTools/Command/DocumentationCommandController.php
index <HASH>..<HASH> 100644
--- a/Classes/TYPO3/DocTools/Command/DocumentationCommandController.php
+++ b/Classes/TYPO3/DocTools/Command/DocumentationCommandController.php
@@ -46,9 +46,9 @@ class DocumentationCommandController extends \TYPO3\Flow\Cli\CommandController {
/**
* @Flow\Inject
- * @var \TYPO3\TYPO3CR\Domain\Service\ContentTypeManager
+ * @var \TYPO3\TYPO3CR\Domain\Service\NodeTypeManager
*/
- protected $contentTypeManager;
+ protected $nodeTypeManager;
/**
* @var \TYPO3\Neos\Domain\Model\Site
@@ -206,10 +206,10 @@ class DocumentationCommandController extends \TYPO3\Flow\Cli\CommandController {
* @return void
*/
protected function importBundle($bundle) {
- $contentTypes = array(
- 'page' => $this->contentTypeManager->getContentType('TYPO3.Neos.ContentTypes:Page'),
- 'section' => $this->contentTypeManager->getContentType('TYPO3.Neos.ContentTypes:Section'),
- 'text' => $this->contentTypeManager->getContentType('TYPO3.Neos.ContentTypes:Text')
+ $nodeTypes = array(
+ 'page' => $this->nodeTypeManager->getNodeType('TYPO3.Neos.ContentTypes:Page'),
+ 'section' => $this->nodeTypeManager->getNodeType('TYPO3.Neos.ContentTypes:Section'),
+ 'text' => $this->nodeTypeManager->getNodeType('TYPO3.Neos.ContentTypes:Text')
);
$this->outputLine('Importing bundle "%s"', array($bundle));
@@ -262,7 +262,7 @@ class DocumentationCommandController extends \TYPO3\Flow\Cli\CommandController {
$subPageNode = $pageNode->getNode($nodeName);
if ($subPageNode === NULL) {
$this->outputLine('Creating page node "%s"', array($relativeNodePath));
- $subPageNode = $pageNode->createNode($nodeName, $contentTypes['page']);
+ $subPageNode = $pageNode->createNode($nodeName, $nodeTypes['page']);
if (!$subPageNode->hasProperty('title')) {
$subPageNode->setProperty('title', $nodeName);
}
@@ -272,12 +272,12 @@ class DocumentationCommandController extends \TYPO3\Flow\Cli\CommandController {
$sectionNode = $pageNode->getNode('main');
if ($sectionNode === NULL) {
$this->outputLine('Creating section node "%s"', array($relativeNodePath . '/main'));
- $sectionNode = $pageNode->createNode('main', $contentTypes['section']);
+ $sectionNode = $pageNode->createNode('main', $nodeTypes['section']);
}
$textNode = $sectionNode->getNode('text1');
if ($textNode === NULL) {
$this->outputLine('Creating text node "%s"', array($relativeNodePath . '/main/text1'));
- $textNode = $sectionNode->createNode('text1', $contentTypes['text']);
+ $textNode = $sectionNode->createNode('text1', $nodeTypes['text']);
}
$pageNode->setProperty('title', $data->title);
$this->outputLine('Setting page title of page "%s" to "%s"', array($relativeNodePath, $data->title));
|
[TASK] Adjust to new node type schema
Change-Id: I<I>ee<I>f5dc<I>bc9c<I>c<I>b<I>b<I>cb8f4f
Related: #<I>
|
neos_doctools
|
train
|
21de90b81db38a641c34e3b334018fd494b5ce7a
|
diff --git a/src/parser/variable.js b/src/parser/variable.js
index <HASH>..<HASH> 100644
--- a/src/parser/variable.js
+++ b/src/parser/variable.js
@@ -126,6 +126,9 @@ module.exports = {
}
result = node(result, offset);
break;
+ case this.tok.T_DOUBLE_COLON:
+ result = this.read_static_getter(result, encapsed);
+ break;
case this.tok.T_OBJECT_OPERATOR:
var node = this.node('propertylookup');
var what = null;
diff --git a/test/variableTests.js b/test/variableTests.js
index <HASH>..<HASH> 100644
--- a/test/variableTests.js
+++ b/test/variableTests.js
@@ -48,7 +48,8 @@ describe('Test variables', function() {
'parent::foo();',
'foo::class;',
'$this->foo();',
- 'foo::$bar;'
+ 'foo::$bar;',
+ '$this->foo::bar'
].join('\n'), {
parser: {
// debug: true
@@ -104,6 +105,15 @@ describe('Test variables', function() {
expr.offset.kind.should.be.exactly('variable');
expr.offset.name.should.be.exactly('bar');
});
+ it('should be $this->foo::bar', function() {
+ var expr = ast.children[6];
+ expr.kind.should.be.exactly('staticlookup');
+ expr.what.kind.should.be.exactly('propertylookup');
+ expr.what.what.kind.should.be.exactly('variable');
+ expr.what.what.name.should.be.exactly('this');
+ expr.what.offset.name.should.be.exactly('foo');
+ expr.offset.name.should.be.exactly('bar');
+ });
});
|
Added support for static lookup on property
|
glayzzle_php-parser
|
train
|
ee654c13d094fb16add11aa05702d1324f411afc
|
diff --git a/km3modules/k40.py b/km3modules/k40.py
index <HASH>..<HASH> 100644
--- a/km3modules/k40.py
+++ b/km3modules/k40.py
@@ -49,7 +49,7 @@ class K40BackgroundSubtractor(kp.Module):
def process(self, blob):
dom_ids = list(blob['K40Counts'].keys())
- mean_rates = self.services['MeanPMTRates']
+ mean_rates = self.services['MeanPMTRates']()
corrected_counts = {}
for dom_id in dom_ids:
pmt_rates = mean_rates[dom_id]
@@ -79,6 +79,7 @@ class IntraDOMCalibrator(kp.Module):
det_id = self.get("det_id") or 14
self.input_key = self.get("input_key") or 'K40Counts'
self.detector = kp.hardware.Detector(det_id=det_id)
+ self.fit_background = self.get("fit_background") or True
def process(self, blob):
print("Starting calibration:")
@@ -88,7 +89,8 @@ class IntraDOMCalibrator(kp.Module):
try:
calib = calibrate_dom(dom_id, data,
self.detector,
- livetime=blob['Livetime'])
+ livetime=blob['Livetime'],
+ fit_background=self.fit_background)
except RuntimeError:
log.error(" skipping DOM '{0}'.".format(dom_id))
else:
|
correction of functionality of mean pmt rates
|
tamasgal_km3pipe
|
train
|
9881752cd4cd0d2a27c781600a34df8c0086272d
|
diff --git a/lib/phony/countries/russia_kazakhstan_abkhasia_south_ossetia.rb b/lib/phony/countries/russia_kazakhstan_abkhasia_south_ossetia.rb
index <HASH>..<HASH> 100644
--- a/lib/phony/countries/russia_kazakhstan_abkhasia_south_ossetia.rb
+++ b/lib/phony/countries/russia_kazakhstan_abkhasia_south_ossetia.rb
@@ -104,13 +104,13 @@ ndcs_with_5_subscriber_digits = %w(30130 30131 30132 30133 30134 30135 30136 301
)
ndcs_with_6_subscriber_digits = %w(3012 3022 3412 3435 3439 3452 3456 3462 3463 3466 3473 3494 3496 3513 3519 3532 3537
- 3812 3822 3823 3842 3843 3846 3852 3854 3882 3902 3919 3942 3952 3953 3955 4012 4112 4132 4152 4162 4212 4217 423 4234
+ 3812 3822 3823 3842 3843 3846 3852 3854 3882 3902 3919 3942 3952 3953 3955 4012 4112 4132 4152 4162 4212 4217 4232 4234
4236 4242 4712 4722 4725 4742 4752 4812 4822 4832 4842 4852 4855 4862 4872 4912 4922 4932 4942 8112 8142 8152 8162
8172 8202 8212 8216 8313 8332 8342 8352 8362 8412 8422 8442 8443 8452 8453 8464 8482 8512 8552 8553 8555 8557 8617
- 862 8634 8635 8636 8639 8652 8662 8672 8712 8722 8732 8772 8782 8793
+ 8622 8634 8635 8636 8639 8652 8662 8672 8712 8722 8732 8772 8782 8793
)
-ndcs_with_7_subscriber_digits = %w(342 343 347 351 383 391 473 495 496 498 499 812 818 831 843 844 846 861 862 863
+ndcs_with_7_subscriber_digits = %w(342 343 347 351 383 391 473 495 496 498 499 812 818 831 843 844 846 861 863
901 902 903 904 905 906 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
930 931 932 933 934 936 937 938 950 951 952 953 960 961 962 963 964 965 967 968 980 981 982 983 984 985 987 988
989 997
|
fixed area codes for Big Sochi and Primorsky Krai
|
floere_phony
|
train
|
ecb3b20be657debc38a192bd587ca9f7d10346d8
|
diff --git a/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonMarshaller.java b/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonMarshaller.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonMarshaller.java
+++ b/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonMarshaller.java
@@ -1151,7 +1151,7 @@ public class Bpmn2JsonMarshaller {
Expression conditionExpression = sequenceFlow.getConditionExpression();
if (conditionExpression instanceof FormalExpression) {
properties.put("conditionexpression", ((FormalExpression) conditionExpression).getBody());
- properties.put("conditionexpression_language", ((FormalExpression) conditionExpression).getLanguage());
+ properties.put("conditionexpressionlanguage", ((FormalExpression) conditionExpression).getLanguage());
}
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
diff --git a/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java b/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java
+++ b/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java
@@ -1780,6 +1780,19 @@ public class Bpmn2JsonUnmarshaller {
if (properties.get("conditionexpression") != null && !"".equals(properties.get("conditionexpression"))) {
FormalExpression expr = Bpmn2Factory.eINSTANCE.createFormalExpression();
expr.setBody(properties.get("conditionexpression"));
+ // check if language was specified
+ if (properties.get("conditionexpressionlanguage") != null && !"".equals(properties.get("conditionexpressionlanguage"))) {
+ String languageStr;
+ if(properties.get("conditionexpressionlanguage").equals("drools")) {
+ languageStr = "http://www.jboss.org/drools/rule";
+ } else if(properties.get("conditionexpressionlanguage").equals("mvel")) {
+ languageStr = "http://www.mvel.org/2.0";
+ } else {
+ // default to drools
+ languageStr = "http://www.jboss.org/drools/rule";
+ }
+ expr.setLanguage(languageStr);
+ }
sequenceFlow.setConditionExpression(expr);
}
if (properties.get("monitoring") != null && !"".equals(properties.get("monitoring"))) {
diff --git a/src/main/webapp/stencilsets/bpmn2.0jbpm/stencildata/bpmn2.0jbpm.orig b/src/main/webapp/stencilsets/bpmn2.0jbpm/stencildata/bpmn2.0jbpm.orig
index <HASH>..<HASH> 100644
--- a/src/main/webapp/stencilsets/bpmn2.0jbpm/stencildata/bpmn2.0jbpm.orig
+++ b/src/main/webapp/stencilsets/bpmn2.0jbpm/stencildata/bpmn2.0jbpm.orig
@@ -6134,6 +6134,18 @@
"wrapLines":true
},
{
+ "id":"conditionexpressionlanguage",
+ "type":"String",
+ "title":"Condition Expression Language",
+ "title_de":"Bedingungsausdruck Sprache",
+ "value":"",
+ "description":"",
+ "readonly":false,
+ "optional":true,
+ "length":"",
+ "wrapLines":true
+ },
+ {
"id":"isimmediate",
"type":"Boolean",
"title":"isImmediate",
|
JBPM-<I>: Oryx integration - Sequence Flows do not have a conditional expression language attribute
|
kiegroup_jbpm-designer
|
train
|
2f2447916b76d212de22d6644f96dfac58a3a9b7
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,3 +1,4 @@
+require 'bundler/setup'
require 'rspec/its'
begin
|
Fix warnings about missing simplecov when running without bundle exec.
|
sporkmonger_addressable
|
train
|
3a4bc6edc3f53309267e9a5d8c03c4d9b8d04024
|
diff --git a/Provider/AbstractProvider.php b/Provider/AbstractProvider.php
index <HASH>..<HASH> 100644
--- a/Provider/AbstractProvider.php
+++ b/Provider/AbstractProvider.php
@@ -19,7 +19,7 @@ use Geocoder\Model\Address;
/**
* @author William Durand <william.durand1@gmail.com>
*/
-abstract class AbstractProvider
+abstract class AbstractProvider implements Provider
{
/**
* Returns the results for the 'localhost' special case.
@@ -29,6 +29,7 @@ abstract class AbstractProvider
protected function getLocationForLocalhost(): Location
{
return Address::createFromArray([
+ 'providedBy' => $this->getName(),
'locality' => 'localhost',
'country' => 'localhost',
]);
|
Added 'providedBy' (#<I>)
* Added 'providedBy'
* Bugfix
* Applied changes from StyleCI
|
geocoder-php_php-common
|
train
|
2589e389f02b9c241ac65851a46c30500549fea5
|
diff --git a/salt/cloud/clouds/vmware.py b/salt/cloud/clouds/vmware.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/vmware.py
+++ b/salt/cloud/clouds/vmware.py
@@ -946,7 +946,7 @@ def _format_instance_info_select(vm, selection):
def _format_instance_info(vm):
device_full_info = {}
-
+ device_mac_addresses = []
if "config.hardware.device" in vm:
for device in vm["config.hardware.device"]:
device_full_info[device.deviceInfo.label] = {
@@ -957,9 +957,12 @@ def _format_instance_info(vm):
'unitNumber': device.unitNumber
}
- if hasattr(device.backing, 'network'):
+ if hasattr(device, 'addressType'):
device_full_info[device.deviceInfo.label]['addressType'] = device.addressType
+
+ if hasattr(device, 'macAddress'):
device_full_info[device.deviceInfo.label]['macAddress'] = device.macAddress
+ device_mac_addresses.append(device.macAddress)
if hasattr(device, 'busNumber'):
device_full_info[device.deviceInfo.label]['busNumber'] = device.busNumber
@@ -1004,6 +1007,9 @@ def _format_instance_info(vm):
ip_addresses.extend(net.ipAddress)
mac_addresses.append(net.macAddress)
+ if len(mac_addresses) == 0:
+ mac_addresses = device_mac_addresses
+
cpu = vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A"
ram = "{0} MB".format(vm["config.hardware.memoryMB"]) if "config.hardware.memoryMB" in vm else "N/A"
vm_full_info = {
|
use device mac address if vmtools not active
return device mac address if vmtools is not loaded or does not return any networks.
|
saltstack_salt
|
train
|
48b8607c60978be7f2c4fc5d9e17c863079ee1c5
|
diff --git a/lib/Doctrine/ODM/PHPCR/UnitOfWork.php b/lib/Doctrine/ODM/PHPCR/UnitOfWork.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ODM/PHPCR/UnitOfWork.php
+++ b/lib/Doctrine/ODM/PHPCR/UnitOfWork.php
@@ -452,7 +452,10 @@ class UnitOfWork
$this->documentTranslations[$oid][$locale][$field] = $class->reflFields[$field]->getValue($document);
}
- $this->documentLocales[$oid] = $locale;
+ if (empty($this->documentLocales[$oid])) {
+ $this->documentLocales[$oid] = array('original' => $locale);
+ }
+ $this->documentLocales[$oid]['current'] = $locale;
}
/**
@@ -757,6 +760,12 @@ class UnitOfWork
}
}
+ if (isset($this->documentLocales[$oid])
+ && $this->documentLocales[$oid]['current'] !== $this->documentLocales[$oid]['original']
+ ) {
+ $changed = true;
+ }
+
if ($changed) {
$this->documentChangesets[$oid] = $actualData;
$this->scheduledUpdates[$oid] = $document;
@@ -1645,7 +1654,7 @@ class UnitOfWork
}
$oid = spl_object_hash($document);
- $this->documentLocales[$oid] = $localeUsed;
+ $this->documentLocales[$oid] = array('original' => $locale, 'current' => $locale);
}
protected function doRemoveTranslation($document, $metadata, $locale)
@@ -1690,8 +1699,8 @@ class UnitOfWork
if (!$locale) {
$oid = spl_object_hash($document);
- if (isset($this->documentLocales[$oid])) {
- $locale = $this->documentLocales[$oid];
+ if (isset($this->documentLocales[$oid]['current'])) {
+ $locale = $this->documentLocales[$oid]['current'];
} else {
$locale = $this->dm->getLocaleChooserStrategy()->getLocale();
}
|
tweaked locale tracking to remember the original and current locale
|
doctrine_phpcr-odm
|
train
|
b37da46c9b66222876c3be1e8c45b46ac22c81c4
|
diff --git a/environs/bootstrap.go b/environs/bootstrap.go
index <HASH>..<HASH> 100644
--- a/environs/bootstrap.go
+++ b/environs/bootstrap.go
@@ -63,11 +63,6 @@ type BootstrapParams struct {
// may use to decide which architecture/series to instantiate.
AvailableTools tools.List
- // ContainerBridgeName, if non-empty, overrides the default
- // network bridge device to use for LXC and KVM containers. See
- // also instancecfg.DefaultBridgeName.
- ContainerBridgeName string
-
// ImageMetadata contains simplestreams image metadata for providers
// that rely on it for selecting images. This will be empty for
// providers that do not implements simplestreams.HasRegion.
diff --git a/provider/common/bootstrap.go b/provider/common/bootstrap.go
index <HASH>..<HASH> 100644
--- a/provider/common/bootstrap.go
+++ b/provider/common/bootstrap.go
@@ -23,7 +23,6 @@ import (
"github.com/juju/utils/v2/ssh"
cryptossh "golang.org/x/crypto/ssh"
- "github.com/juju/juju/agent"
"github.com/juju/juju/cloudconfig"
"github.com/juju/juju/cloudconfig/cloudinit"
"github.com/juju/juju/cloudconfig/instancecfg"
@@ -152,19 +151,6 @@ func BootstrapInstance(
instanceConfig.NetBondReconfigureDelay = env.Config().NetBondReconfigureDelay()
instanceConfig.Tags = instancecfg.InstanceTags(envCfg.UUID(), args.ControllerConfig.ControllerUUID(), envCfg, instanceConfig.Jobs)
- maybeSetBridge := func(icfg *instancecfg.InstanceConfig) {
- // If we need to override the default bridge name, do it now. When
- // args.ContainerBridgeName is empty, the default names for LXC
- // (lxcbr0) and KVM (virbr0) will be used.
- if args.ContainerBridgeName != "" {
- logger.Debugf("using %q as network bridge for all container types", args.ContainerBridgeName)
- if icfg.AgentEnvironment == nil {
- icfg.AgentEnvironment = make(map[string]string)
- }
- icfg.AgentEnvironment[agent.LxdBridge] = args.ContainerBridgeName
- }
- }
- maybeSetBridge(instanceConfig)
// We're creating a new instance; inject host keys so that we can then
// make an SSH connection with known keys.
@@ -315,7 +301,6 @@ func BootstrapInstance(
if err := instancecfg.FinishInstanceConfig(icfg, envConfig); err != nil {
return err
}
- maybeSetBridge(icfg)
return FinishBootstrap(ctx, client, env, callCtx, result.Instance, icfg, opts)
}
return result, selectedSeries, finalizer, nil
|
Removes ContainerBridgeName from BootstrapParams. This is never used.
|
juju_juju
|
train
|
3bd5562597c4ec1b89d0feb3605bb584842da42e
|
diff --git a/structr-core/src/main/java/org/structr/core/parser/Functions.java b/structr-core/src/main/java/org/structr/core/parser/Functions.java
index <HASH>..<HASH> 100644
--- a/structr-core/src/main/java/org/structr/core/parser/Functions.java
+++ b/structr-core/src/main/java/org/structr/core/parser/Functions.java
@@ -77,6 +77,7 @@ import org.mozilla.javascript.ScriptableObject;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
+import org.structr.common.AccessMode;
import org.structr.common.GraphObjectComparator;
import org.structr.common.MailHelper;
import org.structr.common.Permission;
@@ -233,6 +234,11 @@ public class Functions {
public static final String ERROR_MESSAGE_GRANT_JS = "Usage: ${{Structr.grant(principal, node, permissions)}}. Example: ${{Structr.grant(Structr.get('me'), Structr.this, 'read, write, delete'))}}";
public static final String ERROR_MESSAGE_REVOKE = "Usage: ${revoke(principal, node, permissions)}. Example: ${revoke(me, this, 'write, delete'))}";
public static final String ERROR_MESSAGE_REVOKE_JS = "Usage: ${{Structr.revoke(principal, node, permissions)}}. Example: ${{Structr.revoke(Structr.('me'), Structr.this, 'write, delete'))}}";
+
+ public static final String ERROR_MESSAGE_IS_ALLOWED = "Usage: ${is_allowed(principal, node, permissions)}. Example: ${is_allowed(me, this, 'write, delete'))}";
+ public static final String ERROR_MESSAGE_IS_ALLOWED_JS = "Usage: ${{Structr.is_allowed(principal, node, permissions)}}. Example: ${{Structr.is_allowed(Structr.('me'), Structr.this, 'write, delete'))}}";
+
+
public static final String ERROR_MESSAGE_UNLOCK_READONLY_PROPERTIES_ONCE = "Usage: ${unlock_readonly_properties_once(node)}. Example ${unlock_readonly_properties_once, this}";
public static final String ERROR_MESSAGE_UNLOCK_READONLY_PROPERTIES_ONCE_JS = "Usage: ${{Structr.unlock_readonly_properties_once(node)}}. Example ${{Structr.unlock_readonly_properties_once, Structr.get('this')}}";
public static final String ERROR_MESSAGE_CALL = "Usage: ${call(key [, payloads...]}. Example ${call('myEvent')}";
@@ -4886,6 +4892,79 @@ public class Functions {
return "Revokes the given permissions on the given entity from a user";
}
});
+ functions.put("is_allowed", new Function<Object, Object>() {
+
+ @Override
+ public String getName() {
+ return "is_allowed()";
+ }
+
+ @Override
+ public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException {
+
+ if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) {
+
+ if (sources[0] instanceof Principal) {
+
+ final Principal principal = (Principal) sources[0];
+
+ if (sources[1] instanceof AbstractNode) {
+
+ final AbstractNode node = (AbstractNode) sources[1];
+
+ if (sources[2] instanceof String) {
+
+ final String[] parts = ((String) sources[2]).split("[,]+");
+ for (final String part : parts) {
+
+ final String trimmedPart = part.trim();
+ if (trimmedPart.length() > 0) {
+
+ final Permission permission = Permissions.valueOf(trimmedPart);
+ if (permission != null) {
+
+ return node.isGranted(permission, SecurityContext.getInstance(principal, AccessMode.Backend));
+
+ } else {
+
+ return "Error: unknown permission " + trimmedPart;
+ }
+ }
+ }
+
+ return "";
+
+ } else {
+
+ return "Error: third argument is not a string.";
+ }
+
+ } else {
+
+ return "Error: second argument is not a node.";
+ }
+
+ } else {
+
+ return "Error: first argument is not of type Principal.";
+ }
+
+ } else {
+
+ return usage(ctx.isJavaScriptContext());
+ }
+ }
+
+ @Override
+ public String usage(boolean inJavaScriptContext) {
+ return (inJavaScriptContext ? ERROR_MESSAGE_GRANT_JS : ERROR_MESSAGE_GRANT);
+ }
+
+ @Override
+ public String shortDescription() {
+ return "Grants the given permissions on the given entity to a user";
+ }
+ });
functions.put("unlock_readonly_properties_once", new Function<Object, Object>() {
@Override
|
Added builtin is_allowed() function to determine the permissions of a principal for a given node.
|
structr_structr
|
train
|
dbd8f0b636d114c6b950df3bd23d4fa4d306c405
|
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -61,7 +61,7 @@ copyright = u'2013-2017, Pablo Acosta-Serafini'
# The short X.Y version.
version = '1.0.8'
# The full version, including alpha/beta/rc tags.
-release = '1.0.8rc2'
+release = '1.0.8'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/pexdoc/version.py b/pexdoc/version.py
index <HASH>..<HASH> 100644
--- a/pexdoc/version.py
+++ b/pexdoc/version.py
@@ -7,7 +7,7 @@
###
# Global variables
###
-VERSION_INFO = (1, 0, 8, 'candidate', 2)
+VERSION_INFO = (1, 0, 8, 'final', 0)
###
|
Bumped version to <I>
|
pmacosta_pexdoc
|
train
|
58023cb0da3be3e078efb147e1decb19ed7964f3
|
diff --git a/atomic_reactor/util.py b/atomic_reactor/util.py
index <HASH>..<HASH> 100644
--- a/atomic_reactor/util.py
+++ b/atomic_reactor/util.py
@@ -276,7 +276,7 @@ def clone_git_repo(git_url, target_dir, commit=None, retry_times=GIT_MAX_RETRIES
subprocess.check_call(cmd, cwd=target_dir)
cmd = ["git", "rev-parse", "HEAD"]
logger.debug("getting SHA-1 of provided ref '%s'", cmd)
- commit_id = subprocess.check_output(cmd, cwd=target_dir)
+ commit_id = subprocess.check_output(cmd, cwd=target_dir, universal_newlines=True)
commit_id = commit_id.strip()
logger.info("commit ID = %s", commit_id)
return commit_id
diff --git a/tests/test_util.py b/tests/test_util.py
index <HASH>..<HASH> 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -153,7 +153,7 @@ def test_clone_git_repo_by_sha1(tmpdir):
tmpdir_path = str(tmpdir.realpath())
commit_id = clone_git_repo(DOCKERFILE_GIT, tmpdir_path, commit=DOCKERFILE_SHA1)
assert commit_id is not None
- assert six.text_type(commit_id, encoding="ascii") == six.text_type(DOCKERFILE_SHA1)
+ assert commit_id == DOCKERFILE_SHA1
assert len(commit_id) == 40 # current git hashes are this long
assert os.path.isdir(os.path.join(tmpdir_path, '.git'))
|
util.py: make sure that the git commit ID is a string, not bytes
subprocess.check_output() by default returns bytes for python3. Using
universal_newlines=True is a trick to get strings for both python2
and python3, since the encoding option is python3 only.
|
projectatomic_atomic-reactor
|
train
|
8d156c948179f6b8c54d854a05b4558c9b7aeaaa
|
diff --git a/lib/measured/measurable.rb b/lib/measured/measurable.rb
index <HASH>..<HASH> 100644
--- a/lib/measured/measurable.rb
+++ b/lib/measured/measurable.rb
@@ -58,7 +58,7 @@ class Measured::Measurable
return false unless other.is_a?(self.class)
other_converted = other.convert_to(unit)
- unit == other_converted.unit && value == other_converted.value
+ value == other_converted.value
end
alias_method :eql?, :==
|
Don't do unit comparison after converting units
|
Shopify_measured
|
train
|
d211940c835c3e88c1cacb8f9f8f265ebdd1fd29
|
diff --git a/class.cws.debug.php b/class.cws.debug.php
index <HASH>..<HASH> 100644
--- a/class.cws.debug.php
+++ b/class.cws.debug.php
@@ -20,7 +20,7 @@
* @author Cr@zy
* @copyright 2013-2015, Cr@zy
* @license GNU LESSER GENERAL PUBLIC LICENSE
- * @version 1.4
+ * @version 1.5
*
*/
@@ -65,11 +65,6 @@ class CwsDebug
public function __construct(CwsDump $cwsDump)
{
- if (!$cwsDump instanceof CwsDump) {
- $this->error('CwsDump is required - https://github.com/crazy-max/CwsDump', self::VERBOSE_QUIET);
- exit();
- }
-
$this->verbose = self::VERBOSE_QUIET;
$this->mode = self::MODE_ECHO;
$this->cwsDump = $cwsDump;
|
No need to check CwsDump instance
|
crazy-max_CwsDebug
|
train
|
8f5fcf591b57c2240c5ddf2734b14db298a15cdf
|
diff --git a/src/main/java/org/jcodec/codecs/png/PNGEncoder.java b/src/main/java/org/jcodec/codecs/png/PNGEncoder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jcodec/codecs/png/PNGEncoder.java
+++ b/src/main/java/org/jcodec/codecs/png/PNGEncoder.java
@@ -60,8 +60,8 @@ public class PNGEncoder extends VideoEncoder {
ByteBuffer _out = out.duplicate();
_out.putLong(PNGSIG);
IHDR ihdr = new IHDR();
- ihdr.width = pic.getWidth();
- ihdr.height = pic.getHeight();
+ ihdr.width = pic.getCroppedWidth();
+ ihdr.height = pic.getCroppedHeight();
ihdr.bitDepth = 8;
ihdr.colorType = PNG_COLOR_MASK_COLOR;
_out.putInt(13);
@@ -72,13 +72,14 @@ public class PNGEncoder extends VideoEncoder {
_out.putInt(crc32(crcFrom, _out));
Deflater deflater = new Deflater();
- byte[] rowData = new byte[pic.getWidth() * 3 + 1];
+ byte[] rowData = new byte[pic.getCroppedWidth() * 3 + 1];
byte[] pix = pic.getPlaneData(0);
byte[] buffer = new byte[1 << 15];
int ptr = 0, len = buffer.length;
// We do one extra iteration here to flush the deflator
- for (int row = 0, bptr = 0; row < pic.getHeight() + 1; row++) {
+ int lineStep = (pic.getWidth() - pic.getCroppedWidth()) * 3;
+ for (int row = 0, bptr = 0; row < pic.getCroppedHeight() + 1; row++) {
int count;
while ((count = deflater.deflate(buffer, ptr, len)) > 0) {
ptr += count;
@@ -95,17 +96,18 @@ public class PNGEncoder extends VideoEncoder {
}
}
- if (row >= pic.getHeight())
+ if (row >= pic.getCroppedHeight())
break;
rowData[0] = 0; // no filter
- for (int i = 1; i <= pic.getWidth() * 3; i += 3, bptr += 3) {
+ for (int i = 1; i <= pic.getCroppedWidth() * 3; i += 3, bptr += 3) {
rowData[i] = (byte) (pix[bptr] + 128);
rowData[i + 1] = (byte) (pix[bptr + 1] + 128);
rowData[i + 2] = (byte) (pix[bptr + 2] + 128);
}
+ bptr += lineStep;
deflater.setInput(rowData);
- if (row >= pic.getHeight() - 1)
+ if (row >= pic.getCroppedHeight() - 1)
deflater.finish();
}
if (ptr > 0) {
@@ -130,6 +132,6 @@ public class PNGEncoder extends VideoEncoder {
@Override
public int estimateBufferSize(Picture frame) {
- return frame.getWidth() * frame.getHeight() * 4;
+ return frame.getCroppedWidth() * frame.getCroppedHeight() * 4;
}
}
|
[pngenc] Support for cropped pictures
|
jcodec_jcodec
|
train
|
bcc79f384fb67c69206d77734c3648673f112336
|
diff --git a/Twig/AsseticNode.php b/Twig/AsseticNode.php
index <HASH>..<HASH> 100644
--- a/Twig/AsseticNode.php
+++ b/Twig/AsseticNode.php
@@ -26,6 +26,8 @@ class AsseticNode extends BaseAsseticNode
$vars = array();
foreach ($asset->getVars() as $var) {
$vars[] = new \Twig_Node_Expression_Constant($var, $this->getLine());
+
+ // Retrieves values of assetic vars from the context, $context['assetic']['vars'][$var].
$vars[] = new \Twig_Node_Expression_GetAttr(
new \Twig_Node_Expression_GetAttr(
new \Twig_Node_Expression_Name('assetic', $this->getLine()),
@@ -34,7 +36,7 @@ class AsseticNode extends BaseAsseticNode
\Twig_TemplateInterface::ARRAY_CALL,
$this->getLine()
),
- new \Twig_Node_Expression_Constant('locale', $this->getLine()),
+ new \Twig_Node_Expression_Constant($var, $this->getLine()),
new \Twig_Node_Expression_Array(array(), $this->getLine()),
\Twig_TemplateInterface::ARRAY_CALL,
$this->getLine()
|
adds comment, and fixes a typo in previous merge
|
symfony_assetic-bundle
|
train
|
dc63eebc0bf8514f0f74cd9fddc3fb634a173ed0
|
diff --git a/src/com/google/javascript/jscomp/GlobalTypeInfo.java b/src/com/google/javascript/jscomp/GlobalTypeInfo.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/GlobalTypeInfo.java
+++ b/src/com/google/javascript/jscomp/GlobalTypeInfo.java
@@ -262,6 +262,7 @@ class GlobalTypeInfo implements CompilerPass {
@Override
public void process(Node externs, Node root) {
+ Preconditions.checkNotNull(warnings, "Cannot rerun GlobalTypeInfo.process");
Preconditions.checkArgument(externs == null || externs.isSyntheticBlock());
Preconditions.checkArgument(root.isSyntheticBlock());
globalScope =
|
Check to make sure that GlobalTypeInfo.process isn't run multiple times.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
6c9fc674e02a797694b63a57fe3302c25a5eb8ea
|
diff --git a/src/Stream/Structures/BufferIterator.php b/src/Stream/Structures/BufferIterator.php
index <HASH>..<HASH> 100644
--- a/src/Stream/Structures/BufferIterator.php
+++ b/src/Stream/Structures/BufferIterator.php
@@ -16,14 +16,9 @@ class BufferIterator implements \SeekableIterator
* @var int
*/
private $current = 0;
-
- /**
- * @var bool
- */
- private $skip = false;
-
+
/**
- * @param Buffer $buffer
+ * @param \Icicle\Stream\Structures\Buffer $buffer
*/
public function __construct(Buffer $buffer)
{
@@ -73,11 +68,7 @@ class BufferIterator implements \SeekableIterator
*/
public function next()
{
- if ($this->skip) {
- $this->skip = false;
- } else {
- ++$this->current;
- }
+ ++$this->current;
}
/**
@@ -85,7 +76,6 @@ class BufferIterator implements \SeekableIterator
*/
public function prev()
{
- $this->skip = false;
--$this->current;
}
@@ -105,9 +95,11 @@ class BufferIterator implements \SeekableIterator
}
/**
- * Inserts the given data into the buffer at the current iterator position.
+ * Inserts the given string into the buffer at the current iterator position.
*
* @param string $data
+ *
+ * @throws \Icicle\Stream\Exception\LogicException If the iterator is invalid.
*/
public function insert($data)
{
@@ -115,13 +107,17 @@ class BufferIterator implements \SeekableIterator
throw new LogicException('The iterator is not valid!');
}
- $this->buffer[$this->current] = $this->buffer[$this->current] . $data;
+ $this->buffer[$this->current] = $data . $this->buffer[$this->current];
}
/**
+ * Replaces the byte at the current iterator position with the given string.
+ *
* @param string $data
*
* @return string
+ *
+ * @throws \Icicle\Stream\Exception\LogicException If the iterator is invalid.
*/
public function replace($data)
{
@@ -137,7 +133,11 @@ class BufferIterator implements \SeekableIterator
}
/**
+ * Removes the byte at the current iterator position and moves the iterator to the previous character.
+ *
* @return string
+ *
+ * @throws \Icicle\Stream\Exception\LogicException If the iterator is invalid.
*/
public function remove()
{
@@ -149,8 +149,8 @@ class BufferIterator implements \SeekableIterator
unset($this->buffer[$this->current]);
- $this->skip = true;
-
+ --$this->current;
+
return $temp;
}
}
diff --git a/tests/Stream/Structures/BufferIteratorTest.php b/tests/Stream/Structures/BufferIteratorTest.php
index <HASH>..<HASH> 100644
--- a/tests/Stream/Structures/BufferIteratorTest.php
+++ b/tests/Stream/Structures/BufferIteratorTest.php
@@ -57,6 +57,8 @@ class BufferIteratorTest extends TestCase
public function testInsert()
{
+ $this->iterator->next();
+
$this->iterator->insert(self::APPEND_STRING);
$this->assertSame(substr(self::INITIAL_STRING, 0, 1) . self::APPEND_STRING . substr(self::INITIAL_STRING, 1), (string) $this->buffer);
@@ -64,7 +66,7 @@ class BufferIteratorTest extends TestCase
/**
* @depends testInsert
- * @expectedException Icicle\Stream\Exception\LogicException
+ * @expectedException \Icicle\Stream\Exception\LogicException
*/
public function testInsertOnInvalidIterator()
{
@@ -82,7 +84,7 @@ class BufferIteratorTest extends TestCase
/**
* @depends testReplace
- * @expectedException Icicle\Stream\Exception\LogicException
+ * @expectedException \Icicle\Stream\Exception\LogicException
*/
public function testReplaceOnInvalidIterator()
{
@@ -106,7 +108,7 @@ class BufferIteratorTest extends TestCase
/**
* @depends testRemove
- * @expectedException Icicle\Stream\Exception\LogicException
+ * @expectedException \Icicle\Stream\Exception\LogicException
*/
public function testRemoveOnInvalidIterator()
{
|
Fixed bug in buffer iterator.
|
icicleio_icicle
|
train
|
df38df5bd91944217dd858b6617975147187f9b3
|
diff --git a/lib/stackops/lambdaRole.js b/lib/stackops/lambdaRole.js
index <HASH>..<HASH> 100644
--- a/lib/stackops/lambdaRole.js
+++ b/lib/stackops/lambdaRole.js
@@ -55,9 +55,15 @@ module.exports = function(currentTemplate, aliasStackTemplates, currentAliasStac
delete currentTemplate.Resources.IamRoleLambdaExecution;
}
- // Import all defined roles from the current template (without overwriting)
- const currentRoles = _.assign({}, _.pickBy(currentTemplate.Resources, (resource, name) => resource.Type === 'AWS::IAM::Role' && /^IamRoleLambdaExecution/.test(name)));
- _.defaults(stageStack.Resources, currentRoles);
+ // Retain the roles of all currently deployed aliases
+ _.forEach(aliasStackTemplates, aliasTemplate => {
+ const alias = _.get(aliasTemplate, 'Outputs.ServerlessAliasName.Value');
+ const aliasRoleName = `IamRoleLambdaExecution${alias}`;
+ const aliasRole = _.get(currentTemplate, `Resources.${aliasRoleName}`);
+ if (alias && aliasRole) {
+ stageStack.Resources[aliasRoleName] = aliasRole;
+ }
+ });
return BbPromise.resolve([ currentTemplate, aliasStackTemplates, currentAliasStackTemplate ]);
};
|
Retain IAM roles only from deployed alias stacks
|
serverless-heaven_serverless-aws-alias
|
train
|
475e4a40cca37d59eff9e6ecaeb202703ef42cb0
|
diff --git a/account/admin.py b/account/admin.py
index <HASH>..<HASH> 100644
--- a/account/admin.py
+++ b/account/admin.py
@@ -14,7 +14,7 @@ class SignupCodeAdmin(admin.ModelAdmin):
class EmailAddressAdmin(admin.ModelAdmin):
list_display = ["user", "email", "verified", "primary"]
- search_fields = ["user", "email"]
+ search_fields = ["email", "user__username"]
list_filter = ["user"]
|
Fix the search on EmailAddress admin.
We cannot query a foreign key directly, but we need to
specify one field. Now we query the username
|
pinax_django-user-accounts
|
train
|
f7f0a24ae26b02352c95b76d0238394a6e63be99
|
diff --git a/internal/hcs/system.go b/internal/hcs/system.go
index <HASH>..<HASH> 100644
--- a/internal/hcs/system.go
+++ b/internal/hcs/system.go
@@ -497,7 +497,7 @@ func (computeSystem *System) PropertiesV2(ctx context.Context, types ...hcsschem
if err == nil && len(fallbackTypes) == 0 {
return properties, nil
} else if err != nil {
- logEntry.WithError(fmt.Errorf("failed to query compute system properties in-proc: %w", err))
+ logEntry = logEntry.WithError(fmt.Errorf("failed to query compute system properties in-proc: %w", err))
fallbackTypes = types
}
|
Properly assign logEntry for fallback queries
I didn't reassign the logEntry that contained the error reason if
querying for stats in the shim failed
|
Microsoft_hcsshim
|
train
|
8a0f2eb8030ab3fabbd2d6444dc139d69045b48c
|
diff --git a/src/Orchestra/Foundation/Services/Event/AdminMenuHandler.php b/src/Orchestra/Foundation/Services/Event/AdminMenuHandler.php
index <HASH>..<HASH> 100644
--- a/src/Orchestra/Foundation/Services/Event/AdminMenuHandler.php
+++ b/src/Orchestra/Foundation/Services/Event/AdminMenuHandler.php
@@ -5,6 +5,39 @@ use Orchestra\Support\Facades\App;
use Orchestra\Support\Facades\Resources;
class AdminMenuHandler {
+
+ /**
+ * ACL instance.
+ *
+ * @var \Orchestra\Auth\Acl\Container
+ */
+ protected $acl;
+
+ /**
+ * Menu instance.
+ *
+ * @var \Orchestra\Widget\Drivers\Menu
+ */
+ protected $menu;
+
+ /**
+ * Translator instance.
+ *
+ * @var \Illuminate\Translation\Translator
+ */
+ protected $translator;
+
+ /**
+ * Construct a new handler.
+ *
+ * @return void
+ */
+ public function __construct()
+ {
+ $this->menu = App::menu();
+ $this->acl = App::acl();
+ $this->translator = App::make('translator');
+ }
/**
* Create a handler for `orchestra.ready: admin` event.
@@ -13,9 +46,9 @@ class AdminMenuHandler {
*/
public function handle()
{
- $acl = App::acl();
- $menu = App::menu();
- $translator = App::make('translator');
+ $acl = $this->acl;
+ $menu = $this->menu;
+ $translator = $this->translator;
// Add menu when logged-user user has authorization to
// `manage users`
@@ -39,6 +72,20 @@ class AdminMenuHandler {
->link(App::handles('orchestra::settings'));
}
+ $this->resources();
+ }
+
+ /**
+ * Resources link.
+ *
+ * @return void
+ */
+ protected function resources()
+ {
+ $acl = $this->acl;
+ $menu = $this->menu;
+ $translator = $this->translator;
+
$resources = Resources::all();
$isLoaded = false;
$boot = function ($menu, $translator)
|
Separate resources link, allow further customization to AdminMenuHandler
|
orchestral_foundation
|
train
|
4323c7706b6b641dcc9ed51f00ff163e5f80966f
|
diff --git a/packages/mui-material/src/Grid/Grid.js b/packages/mui-material/src/Grid/Grid.js
index <HASH>..<HASH> 100644
--- a/packages/mui-material/src/Grid/Grid.js
+++ b/packages/mui-material/src/Grid/Grid.js
@@ -175,6 +175,30 @@ export function generateColumnGap({ theme, ownerState }) {
return styles;
}
+export function resolveSpacingClasses(spacing, container, styles = {}) {
+ // in case of grid item or undefined/null or `spacing` <= 0
+ if (!container || !spacing || spacing <= 0) {
+ return [];
+ }
+ // in case of string/number `spacing`
+ if (
+ (typeof spacing === 'string' && !Number.isNaN(Number(spacing))) ||
+ typeof spacing === 'number'
+ ) {
+ return [styles[`spacing-xs-${String(spacing)}`] || `spacing-xs-${String(spacing)}`];
+ }
+ // in case of object `spacing`
+ const { xs, sm, md, lg, xl } = spacing;
+
+ return [
+ Number(xs) > 0 && (styles[`spacing-xs-${String(xs)}`] || `spacing-xs-${String(xs)}`),
+ Number(sm) > 0 && (styles[`spacing-sm-${String(sm)}`] || `spacing-sm-${String(sm)}`),
+ Number(md) > 0 && (styles[`spacing-md-${String(md)}`] || `spacing-md-${String(md)}`),
+ Number(lg) > 0 && (styles[`spacing-lg-${String(lg)}`] || `spacing-lg-${String(lg)}`),
+ Number(xl) > 0 && (styles[`spacing-xl-${String(xl)}`] || `spacing-xl-${String(xl)}`),
+ ];
+}
+
// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
@@ -193,7 +217,7 @@ const GridRoot = styled('div', {
container && styles.container,
item && styles.item,
zeroMinWidth && styles.zeroMinWidth,
- container && spacing !== 0 && styles[`spacing-xs-${String(spacing)}`],
+ ...resolveSpacingClasses(spacing, container, styles),
direction !== 'row' && styles[`direction-xs-${String(direction)}`],
wrap !== 'wrap' && styles[`wrap-xs-${String(wrap)}`],
xs !== false && styles[`grid-xs-${String(xs)}`],
@@ -245,7 +269,7 @@ const useUtilityClasses = (ownerState) => {
container && 'container',
item && 'item',
zeroMinWidth && 'zeroMinWidth',
- container && spacing !== 0 && `spacing-xs-${String(spacing)}`,
+ ...resolveSpacingClasses(spacing, container),
direction !== 'row' && `direction-xs-${String(direction)}`,
wrap !== 'wrap' && `wrap-xs-${String(wrap)}`,
xs !== false && `grid-xs-${String(xs)}`,
diff --git a/packages/mui-material/src/Grid/Grid.test.js b/packages/mui-material/src/Grid/Grid.test.js
index <HASH>..<HASH> 100644
--- a/packages/mui-material/src/Grid/Grid.test.js
+++ b/packages/mui-material/src/Grid/Grid.test.js
@@ -166,6 +166,44 @@ describe('<Grid />', () => {
});
});
+ it('should not support undefined values', () => {
+ const { container } = render(
+ <Grid container>
+ <Grid item data-testid="child" />
+ </Grid>,
+ );
+ expect(container.firstChild).not.to.have.class('MuiGrid-spacing-xs-undefined');
+ });
+
+ it('should not support zero values', () => {
+ const { container } = render(
+ <Grid container spacing={0}>
+ <Grid item data-testid="child" />
+ </Grid>,
+ );
+ expect(container.firstChild).not.to.have.class('MuiGrid-spacing-xs-0');
+ });
+
+ it('should support object values', () => {
+ const { container } = render(
+ <Grid container spacing={{ sm: 1.5, md: 2 }}>
+ <Grid item data-testid="child" />
+ </Grid>,
+ );
+ expect(container.firstChild).to.have.class('MuiGrid-spacing-sm-1.5');
+ expect(container.firstChild).to.have.class('MuiGrid-spacing-md-2');
+ });
+
+ it('should ignore object values of zero', () => {
+ const { container } = render(
+ <Grid container spacing={{ sm: 0, md: 2 }}>
+ <Grid item data-testid="child" />
+ </Grid>,
+ );
+ expect(container.firstChild).not.to.have.class('MuiGrid-spacing-sm-0');
+ expect(container.firstChild).to.have.class('MuiGrid-spacing-md-2');
+ });
+
it('should generate correct responsive styles', () => {
const theme = createTheme();
expect(
|
[Grid] Fix generated classes for `spacing` prop when the value is object (#<I>)
|
mui-org_material-ui
|
train
|
616948d76587709f3588b9b16a38d9fd32b3ef6e
|
diff --git a/src/cone/ugm/model/group.py b/src/cone/ugm/model/group.py
index <HASH>..<HASH> 100644
--- a/src/cone/ugm/model/group.py
+++ b/src/cone/ugm/model/group.py
@@ -1,23 +1,23 @@
-from plumber import plumber
-from node.locking import locktree
-from node.utils import instance_property
-from pyramid.i18n import TranslationStringFactory
from cone.app.model import AdapterNode
-from cone.app.model import Properties
from cone.app.model import Metadata
-from cone.app.model import NodeInfo
-from cone.app.model import registerNodeInfo
+from cone.app.model import Properties
+from cone.app.model import node_info
from cone.ugm.model.localmanager import LocalManagerGroupACL
+from node.locking import locktree
+from node.utils import instance_property
+from plumber import plumbing
+from pyramid.i18n import TranslationStringFactory
_ = TranslationStringFactory('cone.ugm')
+@node_info(
+ 'group',
+ title=_('group_node', 'Group'),
+ description=_('group_node_description', 'Group'))
+@plumbing(LocalManagerGroupACL)
class Group(AdapterNode):
- __metaclass__ = plumber
- __plumbing__ = LocalManagerGroupACL
-
- node_info_name = 'group'
@instance_property
def properties(self):
@@ -34,11 +34,3 @@ class Group(AdapterNode):
@locktree
def __call__(self):
self.model()
-
-
-info = NodeInfo()
-info.title = _('group_node', 'Group')
-info.description = _('group_node_description', 'Group')
-info.node = Group
-info.addables = []
-registerNodeInfo('group', info)
diff --git a/src/cone/ugm/model/group.rst b/src/cone/ugm/model/group.rst
index <HASH>..<HASH> 100644
--- a/src/cone/ugm/model/group.rst
+++ b/src/cone/ugm/model/group.rst
@@ -1,12 +1,15 @@
cone.ugm.model.group
====================
-::
+Test imports::
+
+ >>> from cone.app import root
+ >>> from cone.ugm.model.group import Group
+
+Group node::
>>> layer.login('manager')
- >>> from cone.ugm.model.group import Group
- >>> from cone.app import root
>>> groups = root['groups']
>>> group = groups['group0']
>>> group
diff --git a/src/cone/ugm/model/groups.py b/src/cone/ugm/model/groups.py
index <HASH>..<HASH> 100644
--- a/src/cone/ugm/model/groups.py
+++ b/src/cone/ugm/model/groups.py
@@ -1,6 +1,5 @@
from cone.app.model import BaseNode
from cone.app.model import Metadata
-from cone.app.model import NodeInfo
from cone.app.model import Properties
from cone.app.model import node_info
from cone.ugm.browser.utils import unquote_slash
diff --git a/src/cone/ugm/model/user.py b/src/cone/ugm/model/user.py
index <HASH>..<HASH> 100644
--- a/src/cone/ugm/model/user.py
+++ b/src/cone/ugm/model/user.py
@@ -1,6 +1,5 @@
from cone.app.model import AdapterNode
from cone.app.model import Metadata
-from cone.app.model import NodeInfo
from cone.app.model import Properties
from cone.app.model import node_info
from cone.ugm.model.localmanager import LocalManagerUserACL
diff --git a/src/cone/ugm/model/users.py b/src/cone/ugm/model/users.py
index <HASH>..<HASH> 100644
--- a/src/cone/ugm/model/users.py
+++ b/src/cone/ugm/model/users.py
@@ -1,6 +1,5 @@
from cone.app.model import BaseNode
from cone.app.model import Metadata
-from cone.app.model import NodeInfo
from cone.app.model import Properties
from cone.app.model import node_info
from cone.ugm.browser.utils import unquote_slash
|
Group model and tests. Remove superfluous imports
|
bluedynamics_cone.ugm
|
train
|
b32747e4cc886ef62c450d190bf51ef080c40cdb
|
diff --git a/platform/android/Rhodes/src/com/rhomobile/rhodes/geolocation/GeoLocationImpl.java b/platform/android/Rhodes/src/com/rhomobile/rhodes/geolocation/GeoLocationImpl.java
index <HASH>..<HASH> 100644
--- a/platform/android/Rhodes/src/com/rhomobile/rhodes/geolocation/GeoLocationImpl.java
+++ b/platform/android/Rhodes/src/com/rhomobile/rhodes/geolocation/GeoLocationImpl.java
@@ -388,8 +388,9 @@ public class GeoLocationImpl {
synchronized float getSpeed() {
return (lastLocation != null && lastLocation.hasSpeed()) ? lastLocation.getSpeed() : 0;
}
-
- synchronized int getSatellities() {
+ //This method is no longer needed as it is the wrong way to collect the satellites.locationManger.getSpsStatus should ONLY be called from onGpsStatusChanged(int)
+ // Hence commenting out the whole method
+ /*synchronized int getSatellities() {
if ((lastLocation == null) || (locationManager == null)) {
return 0;
}
@@ -404,7 +405,7 @@ public class GeoLocationImpl {
}
return Satellites;
}
-
+ */
synchronized double getAltitude() {
return (lastLocation != null && lastLocation.hasAltitude()) ? lastLocation.getAltitude() : 0;
}
|
This is a wrong way of collecting satellites
getGpsStatus should be called from onGpsStatusChanged(int)
|
rhomobile_rhodes
|
train
|
b1620230ecb1c346e9c45263c431e95e8c9fe7d0
|
diff --git a/pyOCD/gdbserver/gdbserver.py b/pyOCD/gdbserver/gdbserver.py
index <HASH>..<HASH> 100644
--- a/pyOCD/gdbserver/gdbserver.py
+++ b/pyOCD/gdbserver/gdbserver.py
@@ -518,20 +518,21 @@ class GDBServer(threading.Thread):
def handleMsg(self, msg):
try:
- assert msg[0:1] == b'$', "invalid first char of message (!= $"
+ assert msg[0:1] == b'$', "invalid first char of message != $"
try:
handler, msgStart = self.COMMANDS[msg[1:2]]
- if msgStart == 0:
- reply = handler()
- else:
- reply = handler(msg[msgStart:])
- detach = 1 if msg[1:2] in self.DETACH_COMMANDS else 0
- return reply, detach
except (KeyError, IndexError):
self.log.error("Unknown RSP packet: %s", msg)
return self.createRSPPacket(b""), 0
+ if msgStart == 0:
+ reply = handler()
+ else:
+ reply = handler(msg[msgStart:])
+ detach = 1 if msg[1:2] in self.DETACH_COMMANDS else 0
+ return reply, detach
+
except Exception as e:
self.log.error("Unhandled exception in handleMsg: %s", e)
traceback.print_exc()
|
Exception handler fix for GDBServer.handleMsg().
- The exception handler for an unrecognized GDB command was also wrapped
around the invocation of the command handler, so if a KeyError or
IndexError exception was raised during command execution it would be
incorrectly treated as an unknown command packet.
|
mbedmicro_pyOCD
|
train
|
3e00e211e81889edfa1da4431ad6f38ed49fbb7d
|
diff --git a/lib/releasetools.js b/lib/releasetools.js
index <HASH>..<HASH> 100644
--- a/lib/releasetools.js
+++ b/lib/releasetools.js
@@ -30,7 +30,7 @@ var ReleaseTools = module.exports = function releaseTools(options) {
},
function(err, stdout, stderr) {
if (err) throw err;
- exec('ls | grep -v docs | xargs rm', this);
+ exec('ls | grep -v docs | xargs git rm -r', this);
},
function(err, stdout, stderr) {
if (err) throw err;
|
Fixed a bug on the create gh-pages branch method
|
rafeca_node-releasetools
|
train
|
a6bad04f09caaf3fd17778f4b6ecc499f908880e
|
diff --git a/pydle/client.py b/pydle/client.py
index <HASH>..<HASH> 100644
--- a/pydle/client.py
+++ b/pydle/client.py
@@ -171,7 +171,7 @@ class BasicClient:
def _create_user(self, nickname):
# Servers are NOT users.
- if '.' in nickname:
+ if not nickname or '.' in nickname:
return
self.users[nickname] = {
diff --git a/pydle/features/account.py b/pydle/features/account.py
index <HASH>..<HASH> 100644
--- a/pydle/features/account.py
+++ b/pydle/features/account.py
@@ -7,15 +7,12 @@ class AccountSupport(rfc1459.RFC1459Support):
## Internal.
def _create_user(self, nickname):
- # Servers aren't users here, either!
- if "." in nickname:
- return
-
super()._create_user(nickname)
- self.users[nickname].update({
- 'account': None,
- 'identified': False
- })
+ if nickname in self.users:
+ self.users[nickname].update({
+ 'account': None,
+ 'identified': False
+ })
def _rename_user(self, user, new):
super()._rename_user(user, new)
diff --git a/pydle/features/rfc1459/client.py b/pydle/features/rfc1459/client.py
index <HASH>..<HASH> 100644
--- a/pydle/features/rfc1459/client.py
+++ b/pydle/features/rfc1459/client.py
@@ -78,10 +78,11 @@ class RFC1459Support(BasicClient):
def _create_user(self, nickname):
super()._create_user(nickname)
- self.users[nickname].update({
- 'away': False,
- 'away_message': None,
- })
+ if nickname in self.users:
+ self.users[nickname].update({
+ 'away': False,
+ 'away_message': None,
+ })
def _rename_user(self, user, new):
super()._rename_user(user, new)
@@ -106,14 +107,17 @@ class RFC1459Support(BasicClient):
ch['modes'][status].remove(nickname)
def _parse_user(self, data):
- nickname, username, host = parsing.parse_user(data)
-
- metadata = {}
- metadata['nickname'] = nickname
- if username:
- metadata['username'] = username
- if host:
- metadata['hostname'] = host
+ if data:
+ nickname, username, host = parsing.parse_user(data)
+
+ metadata = {}
+ metadata['nickname'] = nickname
+ if username:
+ metadata['username'] = username
+ if host:
+ metadata['hostname'] = host
+ else:
+ return None, {}
return nickname, metadata
def _parse_user_modes(self, user, modes, current=None):
|
Be more robust in source parsing and user creation.
This fixes #<I>.
|
Shizmob_pydle
|
train
|
f215934ea1680a4a3e4981a7846e94f95695ad37
|
diff --git a/lib/ebookr/pandoc.js b/lib/ebookr/pandoc.js
index <HASH>..<HASH> 100644
--- a/lib/ebookr/pandoc.js
+++ b/lib/ebookr/pandoc.js
@@ -30,7 +30,7 @@ module.exports.convert = function (src, options) {
delete metadata[key];
}
});
- files.push(options.metadataFile);
+ files.unshift(options.metadataFile);
}
Object.keys(metadata).forEach(function (key) {
if (metadata[key] !== true) {
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "ebookr",
- "version": "0.2.16",
+ "version": "0.2.17",
"repository": {
"type": "git",
"url": "https://github.com/ebookr/ebookr"
diff --git a/test/when-utilizing-pandoc.js b/test/when-utilizing-pandoc.js
index <HASH>..<HASH> 100644
--- a/test/when-utilizing-pandoc.js
+++ b/test/when-utilizing-pandoc.js
@@ -66,7 +66,7 @@ describe('When utilizing pandoc', function () {
it('should support option "metadata"', function () {
ebookr.pandoc('test.md', { metadataFile: 'metadata.yaml' });
- expect(shell.exec).to.have.been.calledWithMatch('pandoc test.md metadata.yaml');
+ expect(shell.exec).to.have.been.calledWithMatch('pandoc metadata.yaml test.md');
});
it('should set metadata for pandoc if accumulated metadata differs from metadata.yaml', function () {
@@ -77,7 +77,7 @@ describe('When utilizing pandoc', function () {
});
ebookr.pandoc('test.md', { metadataFile: 'metadata.yaml' });
expect(fs.readFileSync).to.have.been.calledWith('metadata.yaml', 'utf-8');
- expect(shell.exec).to.have.been.calledWithMatch('pandoc test.md metadata.yaml -M foo=42 -M bar=new');
+ expect(shell.exec).to.have.been.calledWithMatch('pandoc metadata.yaml test.md -M foo=42 -M bar=new');
});
describe('When converting to MOBI', function () {
|
Another try...
Why does the position of metadata.yaml need to change?
|
ebookr_ebookr
|
train
|
af5be7831c15955a0031822e9d2db2317e4335b7
|
diff --git a/code/CommentAdmin.php b/code/CommentAdmin.php
index <HASH>..<HASH> 100644
--- a/code/CommentAdmin.php
+++ b/code/CommentAdmin.php
@@ -285,7 +285,7 @@ JS;
* Return the number of unmoderated comments
*/
function NumUnmoderated() {
- return DB::query("SELECT COUNT(*) FROM \"PageComment\" WHERE \"IsSpam\"=0 AND \"NeedsModeration\"=0")->value();
+ return DB::query("SELECT COUNT(*) FROM \"PageComment\" WHERE \"IsSpam\"=0 AND \"NeedsModeration\"=1")->value();
}
/**
|
BUGFIX: fixed query to get number of unmoderated comments (from r<I>)
git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/cms/trunk@<I> <I>b<I>ca-7a2a-<I>-9d3b-<I>d<I>a<I>a9
|
silverstripe_silverstripe-reports
|
train
|
0bb91106d35ad92e3f20e44b4729488284de2104
|
diff --git a/lib/main.js b/lib/main.js
index <HASH>..<HASH> 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -57,8 +57,11 @@ function convertTimestampToBigEndian(timestamp) {
var buffer = new Buffer(8);
buffer.fill(0);
- buffer.writeUInt32BE(parseInt(timestamp / 0xffffffff, 10), 0); // jshint ignore:line
- buffer.writeUInt32BE(parseInt(timestamp & 0xffffffff, 10), 4); // jshint ignore:line
+ var high = ~~(timestamp / 0xffffffff); // jshint ignore:line
+ var low = timestamp % (0xffffffff + 0x1); // jshint ignore:line
+
+ buffer.writeUInt32BE(parseInt(high, 10), 0);
+ buffer.writeUInt32BE(parseInt(low, 10), 4);
return buffer;
}
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -14,8 +14,11 @@ function convertTimestampToBigEndian(timestamp) {
var buffer = new Buffer(8);
buffer.fill(0);
- buffer.writeUInt32BE(parseInt(timestamp / 0xffffffff, 10), 0); // jshint ignore:line
- buffer.writeUInt32BE(parseInt(timestamp & 0xffffffff, 10), 4); // jshint ignore:line
+ var high = ~~(timestamp / 0xffffffff); // jshint ignore:line
+ var low = timestamp % (0xffffffff + 0x1); // jshint ignore:line
+
+ buffer.writeUInt32BE(parseInt(high, 10), 0);
+ buffer.writeUInt32BE(parseInt(low, 10), 4);
return buffer;
}
@@ -89,6 +92,24 @@ describe('verifying gameCenter identity', function () {
});
});
+ it('should succeed to verify identity when most significant (left-most) bit of timestamp high and low bit block is 1',
+ function (done) {
+ var testToken = {
+ publicKeyUrl: 'https://valid.apple.com/public/public.cer',
+ timestamp: 1462525134342,
+ salt: 'saltST==',
+ playerId: 'G:1111111',
+ bundleId: 'com.valid.app'
+ };
+ testToken.signature = calculateSignature(testToken);
+
+ verifier.verify(testToken, function (error, token) {
+ assert.equal(_.isError(error), false);
+ assert.equal(token.playerId, testToken.playerId);
+ done();
+ });
+ });
+
it('should fail to get publicKey with http: protocol',
function (done) {
var testToken = {
|
Fix bug in convertTimestampToBigEndian method.
To solve 'TypeError: value is out of bounds' issue when
timestamp's low bits start with 1.
|
maeltm_node-gamecenter-identity-verifier
|
train
|
0de8e64734f3d15bcfe246603aa6c01a0235e517
|
diff --git a/prow/plugins/bugzilla/bugzilla.go b/prow/plugins/bugzilla/bugzilla.go
index <HASH>..<HASH> 100644
--- a/prow/plugins/bugzilla/bugzilla.go
+++ b/prow/plugins/bugzilla/bugzilla.go
@@ -325,7 +325,7 @@ Once a valid bug is referenced in the title of this pull request, request a bug
log.Debug("Valid bug found.")
response = fmt.Sprintf(`This pull request references a valid `+bugLink+`.`, bc.Endpoint(), e.bugId)
// if configured, move the bug to the new state
- if options.StatusAfterValidation != nil {
+ if options.StatusAfterValidation != nil && bug.Status != *options.StatusAfterValidation {
if err := bc.UpdateBug(e.bugId, bugzilla.BugUpdate{Status: *options.StatusAfterValidation}); err != nil {
log.WithError(err).Warn("Unexpected error updating Bugzilla bug.")
return comment(fmt.Sprintf(`An error was encountered updating the bug to the %s state on the Bugzilla server at %s for bug %d:
diff --git a/prow/plugins/bugzilla/bugzilla_test.go b/prow/plugins/bugzilla/bugzilla_test.go
index <HASH>..<HASH> 100644
--- a/prow/plugins/bugzilla/bugzilla_test.go
+++ b/prow/plugins/bugzilla/bugzilla_test.go
@@ -547,6 +547,25 @@ Instructions for interacting with me using PR comments are available [here](http
</details>`,
expectedBug: &bugzilla.Bug{ID: 123, Status: "UPDATED"},
},
+ {
+ name: "valid bug with status update removes invalid label, adds valid label, comments and does not update status when it is already correct",
+ bug: &bugzilla.Bug{ID: 123, Status: updated},
+ options: plugins.BugzillaBranchOptions{StatusAfterValidation: &updated}, // no requirements --> always valid
+ labels: []string{"bugzilla/invalid-bug"},
+ expectedLabels: []string{"bugzilla/valid-bug"},
+ expectedComment: `org/repo#1:@user: This pull request references a valid [Bugzilla bug](www.bugzilla/show_bug.cgi?id=123).
+
+<details>
+
+In response to [this](http.com):
+
+>Bug 123: fixed it!
+
+
+Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md). If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes/test-infra](https://github.com/kubernetes/test-infra/issues/new?title=Prow%20issue:) repository.
+</details>`,
+ expectedBug: &bugzilla.Bug{ID: 123, Status: "UPDATED"},
+ },
}
for _, testCase := range testCases {
|
Update Bug state only when necessary
The API call to update a Bugzilla bug state is only necessary when the
state does not already match what we want to move it to. The API call
succeeds either way but making it conditionally helps message better to
the developers.
|
kubernetes_test-infra
|
train
|
949cb8d8e3fc28cf3c2ba78d9920d8ac15b0e160
|
diff --git a/js/panel_controller.js b/js/panel_controller.js
index <HASH>..<HASH> 100644
--- a/js/panel_controller.js
+++ b/js/panel_controller.js
@@ -11,7 +11,7 @@
var conversations = new Whisper.ConversationCollection();
- window.inbox = new Whisper.ConversationCollection([], {
+ window.inbox = new Backbone.Collection([], {
comparator: function(model) {
return -model.get('active_at');
}
|
Use generic Backbone collection for inbox
There's no need to use a custom collection type here since we don't use
any of the ConversationCollection methods. This helps prevent the
introduction of duplicate models for the same chat.
// FREEBIE
|
ForstaLabs_librelay-node
|
train
|
f40d6d23800d599bb481a33aa7ba51aa8f3cba2e
|
diff --git a/app/helpers/admin/resources_helper.rb b/app/helpers/admin/resources_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/admin/resources_helper.rb
+++ b/app/helpers/admin/resources_helper.rb
@@ -1,7 +1,6 @@
module Admin::ResourcesHelper
def show_thumbnail(image)
- image.create_thumbnail unless File.exists? "#{::Rails.root.to_s}/public/files/thumb_#{image.filename}"
-
+ image.create_thumbnail
"<img class='tumb' src='#{this_blog.base_url}/files/thumb_#{image.filename}' alt='#{this_blog.base_url}/files/#{image.filename}' />"
end
diff --git a/app/models/resource.rb b/app/models/resource.rb
index <HASH>..<HASH> 100644
--- a/app/models/resource.rb
+++ b/app/models/resource.rb
@@ -38,12 +38,13 @@ class Resource < ActiveRecord::Base
def create_thumbnail
blog = Blog.default
- return unless self.mime =~ /image/ or File.exists?(fullpath("thumb_#{self.filename}"))
+ return unless self.mime =~ /image/
return unless File.exists?(fullpath("#{self.filename}"))
begin
img_orig = MiniMagick::Image.from_file(fullpath(self.filename))
['medium', 'thumb'].each do |size|
+ next if File.exists?(fullpath("#{size}_#{self.filename}"))
resize = blog.send("image_#{size.to_s}_size").to_s
img_orig = img_orig.resize("#{resize}x#{resize}")
img_orig.write(fullpath("#{size}_#{self.filename}"))
|
Fixes a bug introduced by previous commit.
Since we now generate 2 sizes of thumbnail, we need to move the check on thumb creation from the helper to the model
|
publify_publify
|
train
|
d0e49dbbc1a922c1c85bd957b6ffbde15fc37222
|
diff --git a/tests/unit/ImapTest.php b/tests/unit/ImapTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/ImapTest.php
+++ b/tests/unit/ImapTest.php
@@ -54,7 +54,7 @@ class ImapTest extends Base
if (\is_string($imapPath) && \is_string($login) && \is_string($password)) {
yield 'CI ENV with invalid password' => [
UnexpectedValueException::class,
- 'IMAP error:[AUTHENTICATIONFAILED] Authentication failed.',
+ '/^IMAP error:.*\[AUTHENTICATIONFAILED\].*/',
[
new HiddenString($imapPath, true, true),
new HiddenString($login, true, true),
@@ -63,6 +63,7 @@ class ImapTest extends Base
0,
[],
],
+ true,
];
}
}
|
switch to regex match for differing error formats
|
barbushin_php-imap
|
train
|
f3acaaa80ceca2e4df9098118c4772300048cefd
|
diff --git a/lib/serve/html.js b/lib/serve/html.js
index <HASH>..<HASH> 100644
--- a/lib/serve/html.js
+++ b/lib/serve/html.js
@@ -24,6 +24,8 @@ function init() {
}
function hijack(res) {
+ res.setHeader('Content-Type', 'text/html; charset=utf-8')
+
const _write = res.write
, _end = res.end
, _writeHead = res.writeHead
@@ -46,6 +48,7 @@ function hijack(res) {
}
function index(res) {
+ res.setHeader('Content-Type', 'text/html; charset=utf-8')
if (config.main.endsWith('.js'))
return res.end(addFiles(html(config.name) + scriptTag(config.main.replace(config.serve, ''), true)))
|
Set content-type for html requests
|
porsager_wright
|
train
|
708e71b43071edb129cfc4055a4b7f3845f470a3
|
diff --git a/astroplan/constraints.py b/astroplan/constraints.py
index <HASH>..<HASH> 100644
--- a/astroplan/constraints.py
+++ b/astroplan/constraints.py
@@ -245,6 +245,7 @@ class Constraint(object):
else:
targets = targets[..., np.newaxis]
times, targets = observer._preprocess_inputs(times, targets, grid=False)
+
result = self.compute_constraint(times, observer, targets)
# make sure the output has the same shape as would result from
@@ -257,6 +258,7 @@ class Constraint(object):
output_shape = np.broadcast(a, b).shape
if output_shape != result.shape:
result = broadcast_to(result, output_shape)
+
return result
@abstractmethod
@@ -490,6 +492,7 @@ class SunSeparationConstraint(Constraint):
# 'get_sun' returns ICRS coords.
sun = get_body('sun', times, location=observer.location)
solar_separation = sun.separation(targets)
+
if self.min is None and self.max is not None:
mask = self.max >= solar_separation
elif self.max is None and self.min is not None:
|
use numpy broadcasting in constraints
|
astropy_astroplan
|
train
|
4bf6dc57432014f6c01b099d39c48cacb2038087
|
diff --git a/lib/vagrant/util/platform.rb b/lib/vagrant/util/platform.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant/util/platform.rb
+++ b/lib/vagrant/util/platform.rb
@@ -56,6 +56,32 @@ module Vagrant
return !File.file?(File.join(tmp_dir, "file"))
end
+ # This expands the path and ensures proper casing of each part
+ # of the path.
+ def fs_real_path(path)
+ path = Pathname.new(File.expand_path(path))
+ raise "Path must exist for path expansion" if !path.exist?
+ return path if fs_case_sensitive?
+
+ # Build up all the parts of the path
+ original = []
+ while !path.root?
+ original.unshift(path.basename.to_s)
+ path = path.parent
+ end
+
+ # Traverse each part and join it into the resulting path
+ original.each do |single|
+ Dir.entries(path).each do |entry|
+ if entry.downcase == single.downcase
+ path = path.join(entry)
+ end
+ end
+ end
+
+ path
+ end
+
# Returns a boolean noting whether the terminal supports color.
# output.
def terminal_supports_colors?
|
Method for getting the case-correct path of a path [GH-<I>]
|
hashicorp_vagrant
|
train
|
668732305a518fee80a30bad4d6b1eb2d091f716
|
diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Yaml/Parser.php
+++ b/src/Symfony/Component/Yaml/Parser.php
@@ -1170,7 +1170,9 @@ class Parser
for (; \strlen($this->currentLine) > $cursor; ++$cursor) {
switch ($this->currentLine[$cursor]) {
case '\\':
- if (isset($this->currentLine[++$cursor])) {
+ if ("'" === $quotation) {
+ $value .= '\\';
+ } elseif (isset($this->currentLine[++$cursor])) {
$value .= '\\'.$this->currentLine[$cursor];
}
diff --git a/src/Symfony/Component/Yaml/Tests/ParserTest.php b/src/Symfony/Component/Yaml/Tests/ParserTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Yaml/Tests/ParserTest.php
+++ b/src/Symfony/Component/Yaml/Tests/ParserTest.php
@@ -1618,6 +1618,11 @@ YAML
];
}
+ public function testBackslashInSingleQuotedString()
+ {
+ $this->assertSame(['foo' => 'bar\\'], $this->parser->parse("foo: 'bar\'"));
+ }
+
public function testParseMultiLineString()
{
$this->assertEquals("foo bar\nbaz", $this->parser->parse("foo\nbar\n\nbaz"));
|
fix lexing backslashes in single quoted strings
|
symfony_symfony
|
train
|
51d8ca5327e7434a757117911f25f50a3e51dd03
|
diff --git a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/organizations/ListOrganizationServicesRequest.java b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/organizations/ListOrganizationServicesRequest.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/organizations/ListOrganizationServicesRequest.java
+++ b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/organizations/ListOrganizationServicesRequest.java
@@ -26,6 +26,7 @@ import lombok.ToString;
import org.cloudfoundry.Validatable;
import org.cloudfoundry.ValidationResult;
import org.cloudfoundry.client.v2.InFilterParameter;
+import org.cloudfoundry.client.v2.IsFilterParameter;
import org.cloudfoundry.client.v2.PaginatedRequest;
import java.util.List;
@@ -44,7 +45,7 @@ public final class ListOrganizationServicesRequest extends PaginatedRequest impl
* @param active the active flag
* @return the active flag
*/
- @Getter(onMethod = @__(@InFilterParameter("active")))
+ @Getter(onMethod = @__(@IsFilterParameter("active")))
private final Boolean active;
/**
diff --git a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/serviceplans/ListServicePlansRequest.java b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/serviceplans/ListServicePlansRequest.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/serviceplans/ListServicePlansRequest.java
+++ b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/serviceplans/ListServicePlansRequest.java
@@ -25,6 +25,7 @@ import lombok.ToString;
import org.cloudfoundry.Validatable;
import org.cloudfoundry.ValidationResult;
import org.cloudfoundry.client.v2.InFilterParameter;
+import org.cloudfoundry.client.v2.IsFilterParameter;
import org.cloudfoundry.client.v2.PaginatedRequest;
import java.util.List;
@@ -43,7 +44,7 @@ public final class ListServicePlansRequest extends PaginatedRequest implements V
* @param active the active flag
* @return the active flag
*/
- @Getter(onMethod = @__(@InFilterParameter("active")))
+ @Getter(onMethod = @__(@IsFilterParameter("active")))
private final Boolean active;
/**
diff --git a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServiceServicePlansRequest.java b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServiceServicePlansRequest.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServiceServicePlansRequest.java
+++ b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServiceServicePlansRequest.java
@@ -26,6 +26,7 @@ import lombok.ToString;
import org.cloudfoundry.Validatable;
import org.cloudfoundry.ValidationResult;
import org.cloudfoundry.client.v2.InFilterParameter;
+import org.cloudfoundry.client.v2.IsFilterParameter;
import org.cloudfoundry.client.v2.PaginatedRequest;
import java.util.List;
@@ -44,7 +45,7 @@ public final class ListServiceServicePlansRequest extends PaginatedRequest imple
* @param active the active flag
* @return the active flag
*/
- @Getter(onMethod = @__(@InFilterParameter("active")))
+ @Getter(onMethod = @__(@IsFilterParameter("active")))
private final Boolean active;
/**
diff --git a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServicesRequest.java b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServicesRequest.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServicesRequest.java
+++ b/cloudfoundry-client/src/main/lombok/org/cloudfoundry/client/v2/services/ListServicesRequest.java
@@ -25,6 +25,7 @@ import lombok.ToString;
import org.cloudfoundry.Validatable;
import org.cloudfoundry.ValidationResult;
import org.cloudfoundry.client.v2.InFilterParameter;
+import org.cloudfoundry.client.v2.IsFilterParameter;
import org.cloudfoundry.client.v2.PaginatedRequest;
import java.util.List;
@@ -43,7 +44,7 @@ public final class ListServicesRequest extends PaginatedRequest implements Valid
* @param active the active flag
* @return the active flag
*/
- @Getter(onMethod = @__(@InFilterParameter("active")))
+ @Getter(onMethod = @__(@IsFilterParameter("active")))
private final Boolean active;
/**
|
Polishing
Ensure all List*Request client API operations filtering on Boolean values are
set as IsFilterParameter and not InFilterParameter. This is for consistency.
|
cloudfoundry_cf-java-client
|
train
|
eccffc24a413c5c18ff6976b392242886f09f791
|
diff --git a/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java
+++ b/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java
@@ -60,6 +60,7 @@ public class PeerEntryEvent extends ResponseEvent
private String autoForcerport;
private String comedia;
private String description;
+ private String accountcode;
/**
* Creates a new instance.
@@ -414,4 +415,24 @@ public class PeerEntryEvent extends ResponseEvent
{
this.description = description;
}
+
+ /**
+ * @return the accountcode
+ */
+ public String getAccountcode()
+ {
+ return accountcode;
+ }
+
+ /**
+ * @param the accountcode to set
+ */
+ public void setAccountcode(String description)
+ {
+ this.accountcode = accountcode;
+ }
+
+
+
+
}
|
accountcodr Property for PeerEntry
this is based on <URL>
|
asterisk-java_asterisk-java
|
train
|
7af4559e0d7f9ee3027758ce77b26f7743aaec26
|
diff --git a/grunt/concurrent.js b/grunt/concurrent.js
index <HASH>..<HASH> 100644
--- a/grunt/concurrent.js
+++ b/grunt/concurrent.js
@@ -22,18 +22,6 @@ Object.keys(configuration.browsers).forEach(browserName => {
module.exports = {
- // Linters
- linters: [
- "jshint",
- "eslint"
- ],
-
- // Code quality tools
- quality: [
- "istanbul",
- "plato"
- ],
-
// Tests on sources
source: [
"mocha:source",
|
Removes useless concurrent tasks (#<I>)
|
ArnaudBuchholz_gpf-js
|
train
|
0f31850a35319fb2d6245a8e72fd25554facae9b
|
diff --git a/user/externallib.php b/user/externallib.php
index <HASH>..<HASH> 100644
--- a/user/externallib.php
+++ b/user/externallib.php
@@ -354,7 +354,7 @@ class moodle_user_external extends external_api {
$userarray = (array) $user; //we want to return an array not an object
/// now we transfert all profile_field_xxx into the customfields external_multiple_structure required by description
- $userarray['customfields'] = null;
+ $userarray['customfields'] = array();
$customfields = profile_user_record($user->id);
$customfields = (array) $customfields;
foreach ($customfields as $key => $value) {
|
webservice MDL-<I> fix moodle_user_get_users_by_id() ws function when no custom field are returned
|
moodle_moodle
|
train
|
54f238c7a64b989de772660b4e417cceb31f869d
|
diff --git a/src/python_pachyderm/mixin/pps.py b/src/python_pachyderm/mixin/pps.py
index <HASH>..<HASH> 100644
--- a/src/python_pachyderm/mixin/pps.py
+++ b/src/python_pachyderm/mixin/pps.py
@@ -347,7 +347,7 @@ class PPSMixin:
"""
return self._req(Service.PPS, "ListPipeline", history=history)
- def delete_pipeline(self, pipeline_name, force=None):
+ def delete_pipeline(self, pipeline_name, force=None, keep_repo=None):
"""
Deletes a pipeline.
@@ -355,8 +355,15 @@ class PPSMixin:
* `pipeline_name`: A string representing the pipeline name.
* `force`: Whether to force delete.
+ * `keep_repo`: Whether to keep the repo.
"""
- return self._req(Service.PPS, "DeletePipeline", pipeline=pps_proto.Pipeline(name=pipeline_name), force=force)
+ return self._req(
+ Service.PPS,
+ "DeletePipeline",
+ pipeline=pps_proto.Pipeline(name=pipeline_name),
+ force=force,
+ keep_repo=keep_repo
+ )
def delete_all_pipelines(self, force=None):
"""
|
Add `keep_repo` to `delete_pipeline`
|
pachyderm_python-pachyderm
|
train
|
4d1e457f8a193ac23222de777bdeb6c5d209d030
|
diff --git a/src/main/org/codehaus/groovy/runtime/NullObject.java b/src/main/org/codehaus/groovy/runtime/NullObject.java
index <HASH>..<HASH> 100644
--- a/src/main/org/codehaus/groovy/runtime/NullObject.java
+++ b/src/main/org/codehaus/groovy/runtime/NullObject.java
@@ -77,22 +77,26 @@ public class NullObject extends GroovyObjectSupport {
}
/**
+ * Tries to get a property on null, which will always fail
* @param property - the property to get
* @returns a NPE
**/
public Object getProperty(String property) {
throw new NullPointerException("Cannot get property " + property + "() on null object");
}
-
+
/**
- * @param property - the property to set
+ * Tries to set a property on null, which will always fail
+ * @param property - the proprty to set
+ * @param newValue - the new value of the property
* @returns a NPE
- **/
- public Object setProperty(String property) {
- throw new NullPointerException("Cannot set property " + property + "() on null object");
+ */
+ public void setProperty(String property, Object newValue) {
+ throw new NullPointerException("Cannot set property " + property + "() on null object");
}
/**
+ * Tries to invoke a method on null, which will always fail
* @param name the name of the method to invoke
* @param args - arguments to the method
* @returns a NPE
@@ -103,6 +107,7 @@ public class NullObject extends GroovyObjectSupport {
}
/**
+ * null is only equal to null
* @param to - the reference object with which to compare
* @returns - true if this object is the same as the to argument
**/
@@ -119,16 +124,43 @@ public class NullObject extends GroovyObjectSupport {
return Collections.EMPTY_LIST.iterator();
}
+ /**
+ * Allows to add a String to null.
+ * The result is concatenated String of "null" and the
+ * String in the parameter.
+ * @param s - the String to concatenate
+ * @return the concatenated string
+ */
public Object plus(String s){
return "null"+s;
}
+ /**
+ * The method "is" is used to test for equal references.
+ * This method will return true only if the given parameter
+ * is null
+ * @param other - the object to test
+ * @return true if other is null
+ */
public boolean is(Object other) {
return other==null;
}
+ /**
+ * Type conversion method for null.
+ * @param c - the class to convert to
+ * @return always null
+ */
public Object asType(Class c) {
return null;
}
+
+ public String toString(){
+ throw new NullPointerException("toString() not allowed on null");
+ }
+
+ public int hashCode() {
+ throw new NullPointerException("hashCode() not allowed on null");
+ }
}
|
* additional methods to ensure null is handled properly in cases of toString and others.
git-svn-id: <URL>
|
groovy_groovy-core
|
train
|
da9eb366df14f3369c39bca63c631057bacc0b5f
|
diff --git a/salsa.go b/salsa.go
index <HASH>..<HASH> 100644
--- a/salsa.go
+++ b/salsa.go
@@ -11,26 +11,24 @@ var sigmaWords = []uint32{
}
func (s *SalsaManager) unlockProtectedEntries(gs []Group) {
- for _, g := range gs {
- for i, e := range g.Entries {
- g.Entries[i].
- Password = s.getUnlockedPassword(&e)
-
- for j, h := range e.Histories {
- for k, el := range h.Entries {
- g.Entries[i].
- Histories[j].
- Entries[k].
- Password = s.getUnlockedPassword(&el)
- }
- }
-
- }
- if len(g.Groups) > 0 {
- s.unlockProtectedEntries(g.Groups)
+ for i,_ := range gs { //For each top level group
+ s.unlockProtectedEntrySlice(gs[i].Entries) //Unlock the Entries in the group
+ if len(g.Groups) > 0 { //Recursively unlock any subgroups
+ s.unlockProtectedEntries(gs[i].Groups)
}
}
}
+func (s *SalsaManager) unlockProtectedEntrySlice (e []Entry) {
+ for i, _ := range e {
+ s.unlockProtectedEntry(&e[i])
+ }
+}
+func (s *SalsaManager) unlockProtectedEntry(e *Entry) {
+ e.Password = s.getUnlockedPassword(e)
+ for i,_ := range e.Histories {
+ s.unlockProtectedEntrySlice(e.Histories[i].Entries)
+ }
+}
func (s *SalsaManager) lockProtectedEntries(gs []Group) {
for _, g := range gs {
|
seperated unlock groups into seperate functions for increased modularity and pottential individual use
|
tobischo_gokeepasslib
|
train
|
a287ca93ea746c132df8cbd73b783ae4558d61a6
|
diff --git a/test/Shippo/AddressTest.php b/test/Shippo/AddressTest.php
index <HASH>..<HASH> 100644
--- a/test/Shippo/AddressTest.php
+++ b/test/Shippo/AddressTest.php
@@ -11,7 +11,7 @@ class Shippo_AddressTest extends Shippo_Test
public function testResidentialCreate()
{
$address = Shippo_Address::create(array(
- 'object_purpose' => 'QUOTE',
+ 'object_purpose' => 'PURCHASE',
'name' => 'John Smith',
'company' => 'Initech',
'street1' => 'Greene Rd.',
|
Changing from QUOTE to PURCHASE
|
goshippo_shippo-php-client
|
train
|
4fd26f91b8a139569b0adb38edc8411ae9dd5728
|
diff --git a/.editorconfig b/.editorconfig
index <HASH>..<HASH> 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -7,6 +7,7 @@ end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
+max_line_length = 100
[*.{md,y{,a}ml}]
indent_style = space
diff --git a/.rubocop.yml b/.rubocop.yml
index <HASH>..<HASH> 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -7,6 +7,8 @@ Layout/IndentationStyle:
IndentationWidth: 2
Layout/IndentationWidth:
Width: 1
+Layout/LineLength:
+ Max: 100
Layout/MultilineMethodCallIndentation:
EnforcedStyle: indented
Layout/ParameterAlignment:
@@ -36,6 +38,10 @@ Lint/RaiseException:
Enabled: true
Lint/StructNewOverride:
Enabled: true
+Lint/DeprecatedOpenSSLConstant:
+ Enabled: true
+Lint/MixedRegexpCaptureTypes:
+ Enabled: true
Style/ParenthesesAroundCondition:
AllowInMultilineConditions: true
@@ -49,6 +55,10 @@ Style/ExponentialNotation:
Enabled: true
Style/SlicingWithRange:
Enabled: true
+Style/RedundantRegexpCharacterClass:
+ Enabled: true
+Style/RedundantRegexpEscape:
+ Enabled: true
AllCops:
TargetRubyVersion: 2.5
diff --git a/lib/flame/config.rb b/lib/flame/config.rb
index <HASH>..<HASH> 100644
--- a/lib/flame/config.rb
+++ b/lib/flame/config.rb
@@ -25,9 +25,7 @@ module Flame
## @return [Object] config value
def [](key)
result = super(key)
- if result.class <= Proc && result.parameters.empty?
- result = instance_exec(&result)
- end
+ result = instance_exec(&result) if result.class <= Proc && result.parameters.empty?
result
end
diff --git a/lib/flame/render.rb b/lib/flame/render.rb
index <HASH>..<HASH> 100644
--- a/lib/flame/render.rb
+++ b/lib/flame/render.rb
@@ -38,9 +38,7 @@ module Flame
## Find filename
@filename = find_file(path)
- unless @filename
- raise Flame::Errors::TemplateNotFoundError.new(controller, path)
- end
+ raise Flame::Errors::TemplateNotFoundError.new(controller, path) unless @filename
@layout = nil if File.basename(@filename)[0] == '_'
end
diff --git a/lib/flame/router/routes_refine.rb b/lib/flame/router/routes_refine.rb
index <HASH>..<HASH> 100644
--- a/lib/flame/router/routes_refine.rb
+++ b/lib/flame/router/routes_refine.rb
@@ -95,9 +95,7 @@ module Flame
def rest
self.class.rest_routes.each do |rest_route|
action = rest_route[:action]
- if !@controller.actions.include?(action) || find_reverse_route(action)
- next
- end
+ next if !@controller.actions.include?(action) || find_reverse_route(action)
send(*rest_route.values.map(&:downcase))
end
|
Enable new cops from RuboCop <I> and <I>, fix changed
|
AlexWayfer_flame
|
train
|
e3f6654dd8fadaf4b1ba60ce8d79e11932fc9eeb
|
diff --git a/restless/dj.py b/restless/dj.py
index <HASH>..<HASH> 100644
--- a/restless/dj.py
+++ b/restless/dj.py
@@ -6,6 +6,7 @@ from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
+from .constants import OK, NO_CONTENT
from .exceptions import NotFound
from .resources import Resource
@@ -29,8 +30,13 @@ class DjangoResource(Resource):
def is_debug(self):
return settings.DEBUG
- def build_response(self, data, status=200):
- resp = HttpResponse(data, content_type='application/json')
+ def build_response(self, data, status=OK):
+ if status == NO_CONTENT:
+ # Avoid crashing the client when it tries to parse nonexisting JSON.
+ content_type = 'text/plain'
+ else:
+ content_type = 'application/json'
+ resp = HttpResponse(data, content_type=content_type)
resp.status_code = status
return resp
diff --git a/tests/test_dj.py b/tests/test_dj.py
index <HASH>..<HASH> 100644
--- a/tests/test_dj.py
+++ b/tests/test_dj.py
@@ -60,7 +60,7 @@ class DjTestResource(DjangoResource):
]
def is_authenticated(self):
- if self.request_method() == 'DELETE':
+ if self.request_method() == 'DELETE' and self.endpoint == 'list':
return False
return True
@@ -94,6 +94,12 @@ class DjTestResource(DjangoResource):
'message': 'This is a random & crazy exception.',
})
+ def delete(self, pk):
+ for i, item in enumerate(self.fake_db):
+ if item.id == pk:
+ del self.fake_db[i]
+ return
+
@skip_prepare
def schema(self):
# A WILD SCHEMA VIEW APPEARS!
@@ -356,3 +362,18 @@ class DjangoResourceTestCase(unittest.TestCase):
'id': 6,
'title': 'Moved hosts'
})
+
+ def test_delete(self):
+ self.res.request = FakeHttpRequest('DELETE')
+ self.assertEqual(len(self.res.fake_db), 3)
+
+ resp = self.res.handle('detail', pk=2)
+ self.assertEqual(resp['Content-Type'], 'text/plain')
+ self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.content.decode('utf-8'), '')
+
+ # Check the internal state.
+ self.res.request = FakeHttpRequest('GET')
+ self.assertEqual(len(self.res.fake_db), 2)
+ resp = self.res.handle('detail', pk=2)
+ self.assertEqual(resp.status_code, 404)
|
Setting Content-Type: text/plain for DELETE responses
|
toastdriven_restless
|
train
|
06208419a361ebc08008c60502aeb997c003bee8
|
diff --git a/airflow/contrib/hooks/gc_base_hook.py b/airflow/contrib/hooks/gc_base_hook.py
index <HASH>..<HASH> 100644
--- a/airflow/contrib/hooks/gc_base_hook.py
+++ b/airflow/contrib/hooks/gc_base_hook.py
@@ -3,11 +3,26 @@ import logging
from airflow.hooks.base_hook import BaseHook
from airflow.utils import AirflowException
-from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials, GoogleCredentials
class GoogleCloudBaseHook(BaseHook):
+ """
+ A base hook for Google cloud-related hooks. Google cloud has a shared REST
+ API client that is built in the same way no matter which service you use.
+ This class helps construct and authorize the credentials needed to then
+ call apiclient.discovery.build() to actually discover and build a client
+ for a Google cloud service.
+
+ The class also contains some miscellaneous helper functions.
+ """
+
def __init__(self, scope, conn_id):
+ """
+ :param scope: The scope of the hook.
+ :type scope: string
+ :param conn_id: The connection ID to use when fetching connection info.
+ :type conn_id: string
+ """
self.scope = scope
self.conn_id = conn_id
|
Add docs to Google cloud base hook.
|
apache_airflow
|
train
|
94f07a8381bc1dca09b56e664170a511f2dfd99c
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -62,6 +62,7 @@ setup(name="polysquare-setuptools-lint",
"pylint-common",
"pyroma",
"vulture",
+ "logilab==0.63.0",
"prospector>=0.10.1",
"flake8==2.3.0",
"flake8-blind-except",
|
Explicitly pull in logilab <I> for now
pylint seems to depend on it, although a newer version
is pulled in from pypi
|
polysquare_polysquare-setuptools-lint
|
train
|
9e2c8cf9dc59ddc93b7ae27e1b700669784d5f9c
|
diff --git a/android/src/main/java/com/appsflyer/reactnative/RNAppsFlyerModule.java b/android/src/main/java/com/appsflyer/reactnative/RNAppsFlyerModule.java
index <HASH>..<HASH> 100755
--- a/android/src/main/java/com/appsflyer/reactnative/RNAppsFlyerModule.java
+++ b/android/src/main/java/com/appsflyer/reactnative/RNAppsFlyerModule.java
@@ -278,6 +278,18 @@ public class RNAppsFlyerModule extends ReactContextBaseJavaModule {
callback.invoke(SUCCESS);
}
+ @ReactMethod
+ public void setCollectIMEI(boolean isCollect, Callback callback){
+ AppsFlyerLib.getInstance().setCollectIMEI(isCollect);
+ callback.invoke(SUCCESS);
+ }
+
+ @ReactMethod
+ public void setCollectAndroidID(boolean isCollect, Callback callback){
+ AppsFlyerLib.getInstance().setCollectAndroidID(isCollect);
+ callback.invoke(SUCCESS);
+ }
+
@ReactMethod
public void setUserEmails(ReadableMap _options,
diff --git a/demo/index.android.js b/demo/index.android.js
index <HASH>..<HASH> 100755
--- a/demo/index.android.js
+++ b/demo/index.android.js
@@ -54,6 +54,18 @@ export default class demo extends Component {
isDebug: true
};
+
+ appsFlyer.setCollectIMEI(false,
+ (result) => {
+ console.log("setCollectIMEI: " + false + " succeeded");
+ });
+
+ appsFlyer.setCollectAndroidID(false,
+ (result) => {
+ console.log("setCollectAndroidID: " + false + " succeeded");
+ });
+
+
appsFlyer.initSdk(options,
(result) => {
this.setState( { ...this.state, initSdkResponse: result });
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100755
--- a/index.js
+++ b/index.js
@@ -73,6 +73,13 @@ appsFlyer.setCustomerUserId = (userId, successC) => {
return RNAppsFlyer.setCustomerUserId(userId, successC);
};
+appsFlyer.setCollectIMEI = (isCollect, successC) => {
+ return RNAppsFlyer.setCollectIMEI(isCollect, successC);
+};
+
+appsFlyer.setCollectAndroidID = (isCollect, successC) => {
+ return RNAppsFlyer.setCollectAndroidID(isCollect, successC);
+};
/**
|
added "setCollectAndroidID" and "setCollectIMEI" methods
|
AppsFlyerSDK_react-native-appsflyer
|
train
|
4508d93cc6b092c3dc12d2a36112d29fdc7717f1
|
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -76,7 +76,7 @@ copyright = '%d, Inonit AS' % date.today().year
# The short X.Y version.
version = '1.7'
# The full version, including alpha/beta/rc tags.
-release = '1.7.0'
+release = '1.7.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/docs/index.rst b/docs/index.rst
index <HASH>..<HASH> 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -109,9 +109,15 @@ Thanks guys!
Changelog
=========
+v1.7.1
+------
+*Release date: 2018-01-06*
+
+ - Locked Django versions in order to comply with Haystack requirements.
+
v1.7.0
------
-*Release date: Not released*
+*Release date: 2018-01-06*
- Bumping minimum support for Django to v1.10.
- Bumping minimum support for Django REST Framework to v1.6.0
diff --git a/drf_haystack/__init__.py b/drf_haystack/__init__.py
index <HASH>..<HASH> 100644
--- a/drf_haystack/__init__.py
+++ b/drf_haystack/__init__.py
@@ -3,7 +3,7 @@
from __future__ import unicode_literals
__title__ = "drf-haystack"
-__version__ = "1.7.0"
+__version__ = "1.7.1"
__author__ = "Rolf Haavard Blindheim"
__license__ = "MIT License"
diff --git a/requirements.txt b/requirements.txt
index <HASH>..<HASH> 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,5 @@
coverage
-django>=1.10,<2.1
+django>=1.10,<2.0
django-haystack>=2.5
djangorestframework>=3.6.0
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -33,7 +33,7 @@ setup(
],
include_package_data=True,
install_requires=[
- "Django>=1.10,<2.1",
+ "Django>=1.10,<2.0",
"djangorestframework>=3.6.0",
"django-haystack>=2.5.0",
"python-dateutil"
|
Locked Django requirements in order to comply with Haystack requirements.
|
inonit_drf-haystack
|
train
|
8a10fb3405e7222ffd97f4b990a7fe7f45e04a10
|
diff --git a/spec/controllers/dashboard_controller_spec.rb b/spec/controllers/dashboard_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/dashboard_controller_spec.rb
+++ b/spec/controllers/dashboard_controller_spec.rb
@@ -18,15 +18,7 @@ describe DashboardController, type: :controller do
get :index
expect(response).to be_successful
expect(assigns(:user)).to eq(user)
- end
-
- it "gathers the user's recent activity" do
- get :index
expect(assigns(:activity)).to be_empty
- end
-
- it "gathers the user's notifications" do
- get :index
expect(assigns(:notifications)).to be_truthy
end
|
Consolidate some controller tests to improve test suite performance
|
samvera_hyrax
|
train
|
343f6a2fe800b87fe09e04c7fd5c8baddb93fdfa
|
diff --git a/test_chain.py b/test_chain.py
index <HASH>..<HASH> 100644
--- a/test_chain.py
+++ b/test_chain.py
@@ -598,7 +598,7 @@ class TestChain(object):
assert np.all(np.abs(expected_y - y_sum) < threshold)
def test_grid_dict_input(self):
- x, y = np.linspace(-3, 3, 200), np.linspace(-5, 5, 200)
+ x, y = np.linspace(-3, 3, 250), np.linspace(-5, 5, 250)
xx, yy = np.meshgrid(x, y, indexing='ij')
pdf = (1 / (2 * np.pi)) * np.exp(-0.5 * (xx * xx + yy * yy / 4))
c = ChainConsumer()
|
Unsure why the only thing that fails is one test in python <I>...
|
Samreay_ChainConsumer
|
train
|
cd8eae5013c07a943df1c6255ee0e5f54a439f5a
|
diff --git a/prom/interface/base.py b/prom/interface/base.py
index <HASH>..<HASH> 100644
--- a/prom/interface/base.py
+++ b/prom/interface/base.py
@@ -99,10 +99,6 @@ class Connection(object):
def _transaction_failing(self, name): pass
-# def cursor(self, *args, **kwargs):
-# pout.v("in transaction? {}".format(self.in_transaction()))
-# return super(Connection, self).cursor(*args, **kwargs)
-
class SQLConnection(Connection):
def _transaction_start(self):
@@ -490,7 +486,7 @@ class Interface(object):
except Exception as e:
exc_info = sys.exc_info()
- if self.handle_error(schema, e, **kwargs):
+ if self.handle_error(schema, e, query=query, **kwargs):
ret = callback(schema, query, *args, **kwargs)
else:
self.raise_error(e, exc_info)
@@ -903,24 +899,31 @@ class SQLInterface(Interface):
if not connection: return False
ret = False
- if connection.closed == 0: # connection is open
+ if connection.closed:
+ # we are unsure of the state of everything since this connection has
+ # closed, go ahead and close out this interface and allow this query
+ # to fail, but subsequent queries should succeed
+ self.close()
+ ret = True
+
+ else:
+ # connection is open
if isinstance(e, InterfaceError):
- # unwind to the first error
+ # unwind to the original error
while isinstance(e, InterfaceError):
e = e.e
- ret = self._handle_error(schema, e, **kwargs)
-
+ query = kwargs.get("query", None)
+ schemas = query.schemas if query else []
+ if schemas:
+ ret = True
+ for s in query.schemas:
+ ret = self._handle_error(s, e, **kwargs)
+ if not ret:
+ break
else:
ret = self._handle_error(schema, e, **kwargs)
- else:
- # we are unsure of the state of everything since this connection has
- # closed, go ahead and close out this interface and allow this query
- # to fail, but subsequent queries should succeed
- self.close()
- ret = True
-
return ret
def _handle_error(self, schema, e, **kwargs): raise NotImplemented()
diff --git a/prom/query.py b/prom/query.py
index <HASH>..<HASH> 100644
--- a/prom/query.py
+++ b/prom/query.py
@@ -625,6 +625,28 @@ class Query(object):
return self.orm_class.schema
@property
+ def schemas(self):
+ """Find and return all the schemas that are needed for this query to complete
+ successfully
+
+ Another way to put this is all the schemas this query touches
+
+ :returns: list, a list of Schema instances
+ """
+ schemas = []
+ s = self.schema
+ if s:
+ schemas.append(s)
+
+ for f in self.fields_where:
+ if isinstance(f.value, Query):
+ s = f.value.schema
+ if s:
+ schemas.append(s)
+
+ return schemas
+
+ @property
def iterator_class(self):
if not self.orm_class: return None
return self.orm_class.iterator_class if self.orm_class else Iterator
diff --git a/tests/interface/__init__.py b/tests/interface/__init__.py
index <HASH>..<HASH> 100644
--- a/tests/interface/__init__.py
+++ b/tests/interface/__init__.py
@@ -674,6 +674,14 @@ class BaseTestInterface(BaseTestCase):
ret = i._set_all_fields(s)
self.assertTrue(ret)
+ def test_handle_error_subquery(self):
+ Foo = self.get_orm_class()
+ Bar = self.get_orm_class()
+
+ bar_q = Bar.query.select_foo()
+ foo_ids = list(Foo.query.select_pk().in_foo(bar_q).values())
+ self.assertEqual([], foo_ids) # no error means it worked
+
def test_handle_error_column(self):
i, s = self.get_table()
s.set_field("che", Field(str, True)) # it's required
diff --git a/tests/query_test.py b/tests/query_test.py
index <HASH>..<HASH> 100644
--- a/tests/query_test.py
+++ b/tests/query_test.py
@@ -137,10 +137,17 @@ class BoundsTest(TestCase):
class QueryTest(EnvironTestCase):
-# @classmethod
-# def setUpClass(cls):
-# from unittest import SkipTest
-# raise SkipTest()
+ def test_schemas(self):
+ Foo = self.get_orm_class()
+ Bar = self.get_orm_class()
+
+ bar_q = Bar.query.select_foo()
+ foo_q = Foo.query.select_pk().in_foo(bar_q)
+
+ schemas = foo_q.schemas
+ self.assertEqual(2, len(schemas))
+ self.assertEqual(Foo.schema, schemas[0])
+ self.assertEqual(String(Bar.schema), String(schemas[1]))
def test_render(self):
q = self.get_query()
|
Closes #<I>. The Interface.handle_error will now receive the Query instance if it is there, this allowed the handle_error method to inspect the Query instance to find all the schemas the query would touch
|
Jaymon_prom
|
train
|
33d8bfa99d0669e7aef54567e8f3ee9dae1c215b
|
diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvoker.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvoker.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvoker.java
+++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvoker.java
@@ -16,9 +16,12 @@
package org.springframework.boot.actuate.endpoint.invoker.cache;
+import java.time.Duration;
import java.util.Map;
import java.util.Objects;
+import reactor.core.publisher.Mono;
+
import org.springframework.boot.actuate.endpoint.InvocationContext;
import org.springframework.boot.actuate.endpoint.invoke.OperationInvoker;
import org.springframework.util.Assert;
@@ -67,13 +70,20 @@ public class CachingOperationInvoker implements OperationInvoker {
long accessTime = System.currentTimeMillis();
CachedResponse cached = this.cachedResponse;
if (cached == null || cached.isStale(accessTime, this.timeToLive)) {
- Object response = this.invoker.invoke(context);
+ Object response = handleMonoResponse(this.invoker.invoke(context));
this.cachedResponse = new CachedResponse(response, accessTime);
return response;
}
return cached.getResponse();
}
+ private Object handleMonoResponse(Object response) {
+ if (response instanceof Mono) {
+ return ((Mono) response).cache(Duration.ofMillis(this.timeToLive));
+ }
+ return response;
+ }
+
private boolean hasInput(InvocationContext context) {
if (context.getSecurityContext().getPrincipal() != null) {
return true;
diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java
+++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java
@@ -17,15 +17,20 @@
package org.springframework.boot.actuate.endpoint.invoker.cache;
import java.security.Principal;
+import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import org.junit.Rule;
import org.junit.Test;
+import reactor.core.publisher.Mono;
import org.springframework.boot.actuate.endpoint.InvocationContext;
import org.springframework.boot.actuate.endpoint.SecurityContext;
+import org.springframework.boot.actuate.endpoint.invoke.MissingParametersException;
import org.springframework.boot.actuate.endpoint.invoke.OperationInvoker;
+import org.springframework.boot.test.rule.OutputCapture;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -42,6 +47,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public class CachingOperationInvokerTests {
+ @Rule
+ public OutputCapture outputCapture = new OutputCapture();
+
@Test
public void createInstanceWithTtlSetToZero() {
assertThatIllegalArgumentException()
@@ -62,6 +70,21 @@ public class CachingOperationInvokerTests {
assertCacheIsUsed(parameters);
}
+ @Test
+ public void cacheInTtlWithMonoResponse() {
+ MonoOperationInvoker target = new MonoOperationInvoker();
+ InvocationContext context = new InvocationContext(mock(SecurityContext.class), Collections.emptyMap());
+ CachingOperationInvoker invoker = new CachingOperationInvoker(target, 500L);
+ Object monoResponse = invoker.invoke(context);
+ assertThat(monoResponse).isInstanceOf(Mono.class);
+ Object response = ((Mono) monoResponse).block(Duration.ofSeconds(30));
+ Object cachedMonoResponse = invoker.invoke(context);
+ assertThat(cachedMonoResponse).isInstanceOf(Mono.class);
+ Object cachedResponse = ((Mono) cachedMonoResponse).block(Duration.ofSeconds(30));
+ assertThat(response).isSameAs(cachedResponse);
+ assertThat(this.outputCapture.toString()).containsOnlyOnce("invoked");
+ }
+
private void assertCacheIsUsed(Map<String, Object> parameters) {
OperationInvoker target = mock(OperationInvoker.class);
Object expected = new Object();
@@ -119,4 +142,18 @@ public class CachingOperationInvokerTests {
verify(target, times(2)).invoke(context);
}
+ private static class MonoOperationInvoker implements OperationInvoker {
+
+ @Override
+ public Object invoke(InvocationContext context) throws MissingParametersException {
+ return Mono.fromCallable(this::printInvocation);
+ }
+
+ private Mono<String> printInvocation() {
+ System.out.println("MonoOperationInvoker invoked");
+ return Mono.just("test");
+ }
+
+ }
+
}
|
Apply TTL invocation caching on reactor types
Update `CachingOperationInvoker` so that TTL caching is applied directly
to reactive types. Prior to this commit, a `Mono` would be cached, but
the values that it emitted would not.
See gh-<I>
|
spring-projects_spring-boot
|
train
|
aedaa1c53b1e96e75251d965156f1ce96cf5de1b
|
diff --git a/cli/src/commands/__tests__/install-test.js b/cli/src/commands/__tests__/install-test.js
index <HASH>..<HASH> 100644
--- a/cli/src/commands/__tests__/install-test.js
+++ b/cli/src/commands/__tests__/install-test.js
@@ -1025,6 +1025,48 @@ describe('install (command)', () => {
).toEqual(false);
});
});
+
+ it('treats dependency prefixed with `>=` the same as `^`', () => {
+ return fakeProjectEnv(async FLOWPROJ_DIR => {
+ // Create some dependencies
+ await Promise.all([
+ mkdirp(path.join(FLOWPROJ_DIR, 'src')),
+ writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
+ name: 'test',
+ devDependencies: {
+ 'flow-bin': '^0.43.0',
+ },
+ dependencies: {
+ foo: '>=1.2.3',
+ },
+ }),
+ mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
+ mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
+ ]);
+
+ // Run the install command
+ await run({
+ overwrite: false,
+ verbose: false,
+ skip: false,
+ rootDir: path.join(FLOWPROJ_DIR, 'src'),
+ explicitLibDefs: [],
+ });
+
+ // Installs libdef
+ expect(
+ await fs.exists(
+ path.join(
+ FLOWPROJ_DIR,
+ 'src',
+ 'flow-typed',
+ 'npm',
+ 'foo_v1.x.x.js',
+ ),
+ ),
+ ).toEqual(false);
+ });
+ });
});
describe('workspace tests', () => {
diff --git a/cli/src/lib/npm/npmLibDefs.js b/cli/src/lib/npm/npmLibDefs.js
index <HASH>..<HASH> 100644
--- a/cli/src/lib/npm/npmLibDefs.js
+++ b/cli/src/lib/npm/npmLibDefs.js
@@ -249,7 +249,7 @@ function validateVersionNumPart(part: string, partName: string): number {
return num;
}
-function pkgVersionMatch(pkgSemver: string, libDefSemverRaw: string) {
+function pkgVersionMatch(pkgSemverRaw: string, libDefSemverRaw: string) {
// The package version should be treated as a semver implicitly prefixed by
// `^` or `~`. Depending on whether or not the minor value is defined.
// i.e.: "foo_v2.2.x" is the same range as "~2.2.x"
@@ -267,6 +267,20 @@ function pkgVersionMatch(pkgSemver: string, libDefSemverRaw: string) {
return libDefSemverRaw;
})();
+ const pkgSemver = (() => {
+ // If pkg version is prefixed with `>=` we should be treated as `^`
+ // Normally `>=` would mean anything greater than a particular version so
+ // ">=2.1.0" would match 2.1.0 up to anything such as 3.4.5
+ // But in the case of flow types, an import of a lib should probably match
+ // the lowest version that matches the range to assume backwards compatibility usage
+ const gtEq = '>=';
+ if (pkgSemverRaw.startsWith(gtEq)) {
+ return pkgSemverRaw.replace(gtEq, '^');
+ }
+
+ return pkgSemverRaw;
+ })();
+
if (semver.valid(pkgSemver)) {
// Test the single package version against the LibDef range
return semver.satisfies(pkgSemver, libDefSemver);
|
[cli] Fix installing lib def package dep uses `>=` (#<I>)
* greater than or equal is the same as caret
* add test
|
flow-typed_flow-typed
|
train
|
19c5194eb8bdd777a298b28f87f2ee4ac5313764
|
diff --git a/tests/functions_test.py b/tests/functions_test.py
index <HASH>..<HASH> 100644
--- a/tests/functions_test.py
+++ b/tests/functions_test.py
@@ -12,6 +12,12 @@ class FunctionsTest(TestCase):
def test_try_catch_two_args(self):
self.assertEquals(try_catch(lambda x,y: x+y+1337, 1, 1), 1339)
+ def test_try_catch_named_args_one_arg(self):
+ self.assertEquals(try_catch(lambda x: x+1337, x=1), 1338)
+
+ def test_try_catch_named_args_two_args_one_named(self):
+ self.assertEquals(try_catch(lambda x,y: x+y+1337, 1, y=1), 1339)
+
def test_try_catch_args_list_one_arg(self):
self.assertEquals(try_catch(lambda x: x+1337, *[1]), 1338)
|
Added tests for named arguments in functions_test.py.
|
marccarre_py_sak
|
train
|
71b9f19e6a314da2ea7c128397a1ef708144f740
|
diff --git a/src/babel/build-external-helpers.js b/src/babel/build-external-helpers.js
index <HASH>..<HASH> 100644
--- a/src/babel/build-external-helpers.js
+++ b/src/babel/build-external-helpers.js
@@ -13,21 +13,15 @@ export default function (whitelist) {
buildHelpers(body, namespace, whitelist);
- var globalHelpersDeclar = t.variableDeclaration("var", [
- t.variableDeclarator(
- namespace,
- t.objectExpression({})
- )
- ]);
var container = util.template("umd-commonjs-strict", {
AMD_ARGUMENTS: t.arrayExpression([t.literal("exports")]),
COMMON_ARGUMENTS: t.identifier("exports"),
- BROWSER_ARGUMENTS: t.identifier("root"),
- UMD_ROOT: namespace,
+ BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression({})),
+ UMD_ROOT: t.identifier("this"),
FACTORY_PARAMETERS: t.identifier("global"),
FACTORY_BODY: body
});
- var tree = t.program([globalHelpersDeclar, container]);
+ var tree = t.program([container]);
return generator(tree).code;
};
|
change to normal UMD (fixes bug with leaking variable in AMD mode)
|
babel_babel
|
train
|
a114d9aff0c86b2cd9091604b7a8f89d5bf232d2
|
diff --git a/angr/paths.py b/angr/paths.py
index <HASH>..<HASH> 100644
--- a/angr/paths.py
+++ b/angr/paths.py
@@ -6,19 +6,19 @@ class PathGenerator(object):
def __init__(self, project):
self._project = project
- def blank_path(self, *args, **kwargs):
+ def blank_path(self, state=None, *args, **kwargs):
'''
blank_point - Returns a start path, representing a clean start of symbolic execution.
'''
- s = self._project.state_generator.blank_state(*args, **kwargs)
+ s = self._project.state_generator.blank_state(*args, **kwargs) if state is None else state
return Path(self._project, s)
- def entry_point(self, *args, **kwargs):
+ def entry_point(self, state=None, *args, **kwargs):
'''
entry_point - Returns a path reflecting the processor when execution
reaches the binary's entry point.
'''
- s = self._project.state_generator.entry_point(*args, **kwargs)
+ s = self._project.state_generator.entry_point(*args, **kwargs) if state is None else state
return Path(self._project, s)
from .path import Path
|
feature to provide a state when creating paths
|
angr_angr
|
train
|
da6b34d6b9a904f6e3c9d380fc9fd2cdad6f587e
|
diff --git a/greencard/greencard.py b/greencard/greencard.py
index <HASH>..<HASH> 100644
--- a/greencard/greencard.py
+++ b/greencard/greencard.py
@@ -55,6 +55,6 @@ def main(clargs=None):
try:
test(card)
except AssertionError:
- print("{0} failed {1}".format(card, test.__name__))
+ print("{0} failed {1}".format(card.__repr__(), test.__name__))
failures += 1
sys.exit(failures)
|
Made the failure printing a little prettier
|
Nekroze_greencard
|
train
|
fb9c2f76a395ef0d9e7915882e5b00f626edd38f
|
diff --git a/library/UnitTestCase.php b/library/UnitTestCase.php
index <HASH>..<HASH> 100755
--- a/library/UnitTestCase.php
+++ b/library/UnitTestCase.php
@@ -960,4 +960,23 @@ abstract class UnitTestCase extends BaseTestCase
}
}
}
+
+ /**
+ * OnlineCaller rethrows exception in method _castExceptionAndWriteToLog
+ * this way we mock it from writing to log.
+ *
+ * @param string $exceptionClassName The name of the exception we want to stub, to not log its output.
+ * @param string $saveUnderClassName The name under which we save the stubbed exception in the testing library.
+ *
+ * @return MockObject The mocked exception.
+ */
+ protected function stubExceptionToNotWriteToLog($exceptionClassName = 'oxException', $saveUnderClassName = 'oxException')
+ {
+ $exception = $this->getMock($exceptionClassName, ['debugOut']);
+ $exception->expects($this->any())->method('debugOut');
+
+ oxTestModules::addModuleObject($saveUnderClassName, $exception);
+
+ return $exception;
+ }
}
|
ESDEV-<I> Move test method to abstract base class
|
OXID-eSales_testing_library
|
train
|
4fbdffe340b6cbc524f3245198ab94dfaeae254f
|
diff --git a/pywbem/cim_obj.py b/pywbem/cim_obj.py
index <HASH>..<HASH> 100644
--- a/pywbem/cim_obj.py
+++ b/pywbem/cim_obj.py
@@ -1837,32 +1837,32 @@ class CIMProperty(_CIMComparisonMixin):
type (:term:`unicode string`):
Name of the CIM data type of the property (e.g. ``"uint8"``).
- class_origin (:term:`unicode string`):
- The CIM class origin of the property, or `None`.
+ reference_class (:term:`unicode string`):
+ The name of the referenced class, for reference properties, or `None`.
+
+ embedded_object (:term:`unicode string`):
+ A string value indicating the kind of embedded object represented
+ by the property value, or `None`.
For details, see the corresponding constructor parameter.
array_size (:term:`integer`):
The size of the array property, or `None`.
- propagated (:class:`py:bool`):
- Propagation information for the property, see the corresponding
- constructor parameter, or `None`.
-
is_array (:class:`py:bool`):
A boolean indicating whether the property is an array (`True`) or a
scalar (`False`).
- reference_class (:term:`unicode string`):
- The name of the referenced class, for reference properties, or `None`.
+ class_origin (:term:`unicode string`):
+ The CIM class origin of the property, or `None`.
+ For details, see the corresponding constructor parameter.
+
+ propagated (:class:`py:bool`):
+ Propagation information for the property, see the corresponding
+ constructor parameter, or `None`.
qualifiers (`NocaseDict`_):
Qualifier values for the property declaration, see the corresponding
constructor parameter.
-
- embedded_object (:term:`unicode string`):
- A string value indicating the kind of embedded object represented
- by the property value, or `None`.
- For details, see the corresponding constructor parameter.
"""
# pylint: disable=too-many-statements
@@ -2355,10 +2355,6 @@ class CIMMethod(_CIMComparisonMixin):
return_type (:term:`unicode string`):
Name of the CIM data type of the method return type.
- parameters (`NocaseDict`_):
- Parameter declarations for the method declaration, see the
- corresponding constructor parameter.
-
class_origin (:term:`unicode string`):
The CIM class origin of the method, or `None`.
For details, see the corresponding constructor parameter.
@@ -2367,6 +2363,10 @@ class CIMMethod(_CIMComparisonMixin):
Indicates whether the method has been propagated from a superclass to
this class, or `None`.
+ parameters (`NocaseDict`_):
+ Parameter declarations for the method declaration, see the
+ corresponding constructor parameter.
+
qualifiers (`NocaseDict`_):
Qualifier values for the method declaration, see the corresponding
constructor parameter.
@@ -2792,10 +2792,6 @@ class CIMQualifier(_CIMComparisonMixin):
Indicates whether the qualifier value has been propagated from a
superclass to this class, or `None`.
- overridable (:class:`py:bool`):
- Indicates whether the qualifier value is overridable in subclasses,
- or `None`.
-
tosubclass (:class:`py:bool`):
Indicates whether the qualifier value propagates to subclasses, or
`None`.
@@ -2804,6 +2800,13 @@ class CIMQualifier(_CIMComparisonMixin):
Indicates whether the qualifier value propagates to instances, or
`None`.
+ Note that :term:`DSP0200` has deprecated the presence of qualifier
+ values on CIM instances.
+
+ overridable (:class:`py:bool`):
+ Indicates whether the qualifier value is overridable in subclasses,
+ or `None`.
+
translatable (:class:`py:bool`):
Indicates whether the qualifier is translatable, or `None`.
"""
@@ -2856,6 +2859,9 @@ class CIMQualifier(_CIMComparisonMixin):
to instances.
`None` means that this information is not available.
+ Note that :term:`DSP0200` has deprecated the presence of qualifier
+ values on CIM instances.
+
translatable (:class:`py:bool`):
If not `None`, specifies whether the qualifier is translatable.
`None` means that this information is not available.
@@ -3050,11 +3056,6 @@ class CIMQualifierDeclaration(_CIMComparisonMixin):
Scopes of the qualifier declaration.
For details, see the corresponding constructor parameter.
- overridable (:class:`py:bool`):
- If not `None`, specifies whether the qualifier value is overridable
- in subclasses.
- `None` means that this information is not available.
-
tosubclass (:class:`py:bool`):
If not `None`, specifies whether the qualifier value propagates
to subclasses.
@@ -3065,6 +3066,14 @@ class CIMQualifierDeclaration(_CIMComparisonMixin):
to instances.
`None` means that this information is not available.
+ Note that :term:`DSP0200` has deprecated the presence of qualifier
+ values on CIM instances.
+
+ overridable (:class:`py:bool`):
+ If not `None`, specifies whether the qualifier value is overridable
+ in subclasses.
+ `None` means that this information is not available.
+
translatable (:class:`py:bool`):
If not `None`, specifies whether the qualifier is translatable.
`None` means that this information is not available.
@@ -3131,6 +3140,9 @@ class CIMQualifierDeclaration(_CIMComparisonMixin):
to instances.
`None` means that this information is not available.
+ Note that :term:`DSP0200` has deprecated the presence of qualifier
+ values on CIM instances.
+
translatable (:class:`py:bool`):
If not `None`, specifies whether the qualifier is translatable.
`None` means that this information is not available.
|
Changed order of instance variables in some CIM object classes to be more logical.
Details:
- Changed the order of instance variables in docstrings of CIMProperty,
CIMMethod, CIMParameter, CIMQualifier, and CIMQualifierDeclaration to be more
logical. The order of ctor parameters is unchanged, for compatibility.
|
pywbem_pywbem
|
train
|
3ba4efa929bb9ca46e8c3b6c921b5ffee03e61a2
|
diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java
@@ -15,7 +15,6 @@
*/
package com.orientechnologies.orient.server;
-import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.raw.ODatabaseRaw;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary;
@@ -30,7 +29,7 @@ import java.net.InetSocketAddress;
public class OClientConnection {
public final int id;
- public final ONetworkProtocol protocol;
+ public volatile ONetworkProtocol protocol;
public final long since;
public volatile ODatabaseDocumentTx database;
public volatile ODatabaseRaw rawDatabase;
@@ -38,9 +37,9 @@ public class OClientConnection {
public ONetworkProtocolData data = new ONetworkProtocolData();
- public OClientConnection(final int iId, final ONetworkProtocol iProtocol) throws IOException {
- this.id = iId;
- this.protocol = iProtocol;
+ public OClientConnection(final int id, final ONetworkProtocol protocol) throws IOException {
+ this.id = id;
+ this.protocol = protocol;
this.since = System.currentTimeMillis();
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
index <HASH>..<HASH> 100755
--- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
@@ -118,14 +118,13 @@ public class OClientConnectionManager {
* id of connection
* @return The connection if any, otherwise null
*/
- public OClientConnection getConnection(final int iChannelId) {
+ public OClientConnection getConnection(final int iChannelId, ONetworkProtocol protocol) {
// SEARCH THE CONNECTION BY ID
- return connections.get(iChannelId);
+ OClientConnection connection = connections.get(iChannelId);
+ if (connection != null)
+ connection.protocol = protocol;
- // COMMENTED TO USE SOCKET POOL: THINK TO ANOTHER WAY TO IMPROVE SECURITY
- // if (conn != null && conn.getChannel().socket != socket)
- // throw new IllegalStateException("Requested sessionId " + iChannelId + " by connection " + socket
- // + " while it's tied to connection " + conn.getChannel().socket);
+ return connection;
}
/**
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
index <HASH>..<HASH> 100755
--- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
@@ -151,7 +151,7 @@ public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract {
protected void onBeforeRequest() throws IOException {
waitNodeIsOnline();
- connection = OClientConnectionManager.instance().getConnection(clientTxId);
+ connection = OClientConnectionManager.instance().getConnection(clientTxId, this);
if (clientTxId < 0) {
short protocolId = 0;
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/OpenCloseMTTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/OpenCloseMTTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/OpenCloseMTTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/OpenCloseMTTest.java
@@ -29,8 +29,6 @@ public class OpenCloseMTTest {
public void openCloseMTTest() throws Exception {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false);
- OGlobalConfiguration.SECURITY_MAX_CACHED_USERS.setValue(0);
- OGlobalConfiguration.SECURITY_MAX_CACHED_ROLES.setValue(0);
ODatabaseDocumentTx databaseDocumentTx = new ODatabaseDocumentTx(URL);
databaseDocumentTx.create();
|
Issue which causes unexpected close of database on server because of connection multiplexing on client was fixed.
|
orientechnologies_orientdb
|
train
|
4770590ca5999676e3e1c9f3a13cf7011d6704b1
|
diff --git a/src/test/java/io/vlingo/actors/RepeatableCompletesTest.java b/src/test/java/io/vlingo/actors/RepeatableCompletesTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/io/vlingo/actors/RepeatableCompletesTest.java
+++ b/src/test/java/io/vlingo/actors/RepeatableCompletesTest.java
@@ -19,7 +19,7 @@ public class RepeatableCompletesTest {
final Completes<Integer> completes = new RepeatableCompletes<>(0);
completes
- .after((value) -> value * 2)
+ .andThen((value) -> value * 2)
.andThen((Integer value) -> andThenValue = value)
.repeat();
|
Test new Completes API that supports nested async pipes-filters.
|
vlingo_vlingo-actors
|
train
|
10687ec54082a8e043fed5181b878ab6384305ac
|
diff --git a/lib/generators/preact_generator.rb b/lib/generators/preact_generator.rb
index <HASH>..<HASH> 100644
--- a/lib/generators/preact_generator.rb
+++ b/lib/generators/preact_generator.rb
@@ -15,6 +15,10 @@ Preact.configure do |config|
# disable this if you want to only log manual events
config.autolog = true
+ # specify controller#action items that you want to ignore and not log to Preact.
+ # default is to not log sessions#create beacuse if you're using Devise, we get that already
+ config.autolog_ignored_actions = ["sessions#create"]
+
# disable in Rails non-production environments
# uncomment this if you don't want to log development activities
#config.disabled = !Rails.env.production?
diff --git a/lib/preact.rb b/lib/preact.rb
index <HASH>..<HASH> 100644
--- a/lib/preact.rb
+++ b/lib/preact.rb
@@ -41,8 +41,10 @@ module Preact
# never log things if we're in Rails test environment
configuration.disabled = true if ::Rails.env.test?
- elsif defined? ::Warden
- # not using rails, so try to use warden
+ end
+
+ if defined? ::Warden
+ # if we're using Warden (Devise), load those extensions
require 'preact/warden'
end
diff --git a/lib/preact/version.rb b/lib/preact/version.rb
index <HASH>..<HASH> 100644
--- a/lib/preact/version.rb
+++ b/lib/preact/version.rb
@@ -1,3 +1,3 @@
module Preact
- VERSION = "0.8.1"
+ VERSION = "0.8.2"
end
|
update to use native Warden login/logout tracking and ignore sessions#create so as not to double-log the event
|
preact_preact-ruby
|
train
|
d4ff392be49b23bea20dcc2476a143188424856f
|
diff --git a/lib/vagrant/ui.rb b/lib/vagrant/ui.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant/ui.rb
+++ b/lib/vagrant/ui.rb
@@ -10,7 +10,7 @@ module Vagrant
end
[:warn, :error, :info, :confirm].each do |method|
- define_method(method) do |message|
+ define_method(method) do |message, *opts|
# Log normal console messages
env.logger.info("ui") { message }
end
|
Fix wrong # of argument issue. [closes GH-<I>]
The second parameter actually is supposed to be options.
|
hashicorp_vagrant
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.