hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
d1c63e833a3c26527e99583e1ddb9a56baef65d7
|
diff --git a/resources/lang/en/admin.php b/resources/lang/en/admin.php
index <HASH>..<HASH> 100644
--- a/resources/lang/en/admin.php
+++ b/resources/lang/en/admin.php
@@ -100,4 +100,12 @@ return [
'new_folder' => 'New folder',
'time' => 'Time',
'size' => 'Size',
+
+ 'listbox' => [
+ 'text_total' => 'Showing all {0}',
+ 'text_empty' => 'Empty list',
+ 'filtered' => '{0} / {1}',
+ 'filter_clear' => 'Show all',
+ 'filter_placeholder' => 'Filter',
+ ]
];
diff --git a/resources/lang/zh-CN/admin.php b/resources/lang/zh-CN/admin.php
index <HASH>..<HASH> 100644
--- a/resources/lang/zh-CN/admin.php
+++ b/resources/lang/zh-CN/admin.php
@@ -100,4 +100,12 @@ return [
'new_folder' => '新建文件夹',
'time' => '时间',
'size' => '大小',
+
+ 'listbox' => [
+ 'text_total' => '总共 {0} 项',
+ 'text_empty' => '空列表',
+ 'filtered' => '{0} / {1}',
+ 'filter_clear' => '显示全部',
+ 'filter_placeholder' => '过滤',
+ ]
];
diff --git a/src/Form/Field/Listbox.php b/src/Form/Field/Listbox.php
index <HASH>..<HASH> 100644
--- a/src/Form/Field/Listbox.php
+++ b/src/Form/Field/Listbox.php
@@ -29,11 +29,11 @@ class Listbox extends MultipleSelect
public function render()
{
$settings = array_merge($this->settings, [
- 'infoTextEmpty' => '空列表',
- 'infoText' => '总共 {0} 项',
- 'infoTextFiltered' => '{0} / {1}',
- 'filterTextClear' => '显示全部',
- 'filterPlaceHolder' => '过滤',
+ 'infoText' => trans('admin.listbox.text_total'),
+ 'infoTextEmpty' => trans('admin.listbox.text_empty'),
+ 'infoTextFiltered' => trans('admin.listbox.filtered'),
+ 'filterTextClear' => trans('admin.listbox.filter_clear'),
+ 'filterPlaceHolder' => trans('admin.listbox.filter_placeholder'),
]);
$settings = json_encode($settings);
|
fix hard code chinese in listbox
|
ShaoZeMing_laravel-merchant
|
train
|
25ea67a9f75cc6190e99301e5d66d6e702a751a4
|
diff --git a/test/vagrant/config_test.rb b/test/vagrant/config_test.rb
index <HASH>..<HASH> 100644
--- a/test/vagrant/config_test.rb
+++ b/test/vagrant/config_test.rb
@@ -13,7 +13,7 @@ class ConfigTest < Test::Unit::TestCase
@klass.run { |config| foo.call }
value = @klass.last_proc.first
assert value.is_a?(Proc)
- value.call
+ value.call(nil)
assert @klass.last_proc.nil?
end
|
Get rid of Ruby <I> warning in tests
|
hashicorp_vagrant
|
train
|
e87d9dfb904e29e265dc0e3462a20ee1295f3403
|
diff --git a/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/SchemaTypeSpecBuilder.kt b/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/SchemaTypeSpecBuilder.kt
index <HASH>..<HASH> 100644
--- a/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/SchemaTypeSpecBuilder.kt
+++ b/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/SchemaTypeSpecBuilder.kt
@@ -222,7 +222,7 @@ class SchemaTypeSpecBuilder(
fun responseMarshallerSpec(fieldSpecs: List<FieldSpec>): MethodSpec {
val code = fieldSpecs
.map { fieldSpec ->
- if (fieldSpec.type.isOptional()) {
+ if (fieldSpec.type.isNullable()) {
CodeBlock.builder()
.addStatement("final \$T \$L = \$L", fieldSpec.type.unwrapOptionalType().withoutAnnotations(),
"\$${fieldSpec.name}", fieldSpec.type.unwrapOptionalValue(fieldSpec.name))
diff --git a/apollo-compiler/src/test/graphql/com/example/fragments_with_type_condition_nullable/TestQuery.java b/apollo-compiler/src/test/graphql/com/example/fragments_with_type_condition_nullable/TestQuery.java
index <HASH>..<HASH> 100644
--- a/apollo-compiler/src/test/graphql/com/example/fragments_with_type_condition_nullable/TestQuery.java
+++ b/apollo-compiler/src/test/graphql/com/example/fragments_with_type_condition_nullable/TestQuery.java
@@ -377,8 +377,14 @@ public final class TestQuery implements Query<TestQuery.Data, TestQuery.Data, Op
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
- writer.writeFragment(humanDetails.marshaller());
- writer.writeFragment(droidDetails.marshaller());
+ final HumanDetails $humanDetails = humanDetails;
+ if ($humanDetails != null) {
+ writer.writeFragment($humanDetails.marshaller());
+ }
+ final DroidDetails $droidDetails = droidDetails;
+ if ($droidDetails != null) {
+ writer.writeFragment($droidDetails.marshaller());
+ }
}
};
}
@@ -575,8 +581,14 @@ public final class TestQuery implements Query<TestQuery.Data, TestQuery.Data, Op
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
- writer.writeFragment(humanDetails.marshaller());
- writer.writeFragment(droidDetails.marshaller());
+ final HumanDetails $humanDetails = humanDetails;
+ if ($humanDetails != null) {
+ writer.writeFragment($humanDetails.marshaller());
+ }
+ final DroidDetails $droidDetails = droidDetails;
+ if ($droidDetails != null) {
+ writer.writeFragment($droidDetails.marshaller());
+ }
}
};
}
diff --git a/apollo-compiler/src/test/graphql/com/example/union_fragment/TestQuery.java b/apollo-compiler/src/test/graphql/com/example/union_fragment/TestQuery.java
index <HASH>..<HASH> 100644
--- a/apollo-compiler/src/test/graphql/com/example/union_fragment/TestQuery.java
+++ b/apollo-compiler/src/test/graphql/com/example/union_fragment/TestQuery.java
@@ -363,8 +363,14 @@ public final class TestQuery implements Query<TestQuery.Data, TestQuery.Data, Op
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
- writer.writeFragment(character.marshaller());
- writer.writeFragment(starship.marshaller());
+ final Character $character = character;
+ if ($character != null) {
+ writer.writeFragment($character.marshaller());
+ }
+ final Starship $starship = starship;
+ if ($starship != null) {
+ writer.writeFragment($starship.marshaller());
+ }
}
};
}
|
fix marshaller is nullable (#<I>)
|
apollographql_apollo-android
|
train
|
ef647dd830f74de5eeb849c7a11f1aa11223a978
|
diff --git a/lib/jsdom/level1/core.js b/lib/jsdom/level1/core.js
index <HASH>..<HASH> 100644
--- a/lib/jsdom/level1/core.js
+++ b/lib/jsdom/level1/core.js
@@ -1198,7 +1198,7 @@ core.Document = function Document(options) {
};
-var tagRegEx = /[^\w:\d_-]+/i;
+var tagRegEx = /[^\w:\d_\.-]+/i;
var entRegEx = /[^\w\d_\-&;]+/;
var invalidAttrRegEx = /[^\w:\d_\.-]+/;
|
createDocument fix from the previous commit exposed a failing test case caused by tagRegEx not matching the 'Name' production from the XML grammar. For now just change the regex to also match dot '.' since that is the minimum change to pass the test.
|
jsdom_jsdom
|
train
|
8270280df7f76ff27a99524ce3ad37beddbfeb2a
|
diff --git a/m9dicts/api.py b/m9dicts/api.py
index <HASH>..<HASH> 100644
--- a/m9dicts/api.py
+++ b/m9dicts/api.py
@@ -191,9 +191,6 @@ def make(obj=None, ordered=False, merge=m9dicts.globals.MS_DICTS,
if merge not in m9dicts.globals.MERGE_STRATEGIES:
raise ValueError("Wrong merge strategy: %r" % merge)
- if getattr(options, "namedtuple", False):
- ordered = True # To keep the order of items.
-
cls = m9dicts.dicts.get_mdict_class(merge=merge, ordered=ordered)
if obj is None:
return cls()
|
fix: m9dicts.api.make does not receive 'namedtuple' keyword option
|
ssato_python-anyconfig
|
train
|
2ef9d19a519c02e61943e66abf1784dc719e2548
|
diff --git a/course/format/lams/format.php b/course/format/lams/format.php
index <HASH>..<HASH> 100644
--- a/course/format/lams/format.php
+++ b/course/format/lams/format.php
@@ -71,7 +71,7 @@ if (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $editing) {
}
/// Start main column
-echo '<td id="middle-column">';
+echo '<td id="middle-column"><a name="startofcontent"></a>';
print_heading_block(get_string('lamsoutline','lams'), 'outline');
diff --git a/course/format/scorm/format.php b/course/format/scorm/format.php
index <HASH>..<HASH> 100644
--- a/course/format/scorm/format.php
+++ b/course/format/scorm/format.php
@@ -30,7 +30,7 @@
echo '</td>';
}
- echo '<td id="middle-column">';
+ echo '<td id="middle-column"><a name="startofcontent"></a>';
$moduleformat = $module.'_course_format_display';
if (function_exists($moduleformat)) {
$moduleformat($USER,$course);
diff --git a/course/format/social/format.php b/course/format/social/format.php
index <HASH>..<HASH> 100644
--- a/course/format/social/format.php
+++ b/course/format/social/format.php
@@ -28,7 +28,7 @@
echo '</td>';
}
- echo '<td id="middle-column">';
+ echo '<td id="middle-column"><a name="startofcontent"></a>';
if ($forum = forum_get_course_forum($course->id, 'social')) {
if (forum_is_forcesubscribed($forum->id)) {
$subtext = '<div class="link">'.get_string('everyoneissubscribed', 'forum').'</div>';
diff --git a/course/format/topics/format.php b/course/format/topics/format.php
index <HASH>..<HASH> 100644
--- a/course/format/topics/format.php
+++ b/course/format/topics/format.php
@@ -76,7 +76,7 @@
}
/// Start main column
- echo '<td id="middle-column">';
+ echo '<td id="middle-column"><a name="startofcontent"></a>';
print_heading_block(get_string('topicoutline'), 'outline');
@@ -270,4 +270,4 @@
echo '</tr></table>';
-?>
\ No newline at end of file
+?>
diff --git a/course/format/weeks/format.php b/course/format/weeks/format.php
index <HASH>..<HASH> 100644
--- a/course/format/weeks/format.php
+++ b/course/format/weeks/format.php
@@ -62,7 +62,7 @@
}
/// Start main column
- echo '<td id="middle-column">';
+ echo '<td id="middle-column"><a name="startofcontent"></a>';
print_heading_block(get_string('weeklyoutline'), 'outline');
@@ -267,4 +267,4 @@
echo '</tr></table>';
-?>
\ No newline at end of file
+?>
diff --git a/course/format/weekscss/format.php b/course/format/weekscss/format.php
index <HASH>..<HASH> 100644
--- a/course/format/weekscss/format.php
+++ b/course/format/weekscss/format.php
@@ -91,7 +91,7 @@
}
/// Start main column
- echo '<div id="middle-column">';
+ echo '<div id="middle-column"><a name="startofcontent"></a>';
print_heading_block(get_string('weeklyoutline'), 'outline');
@@ -277,4 +277,4 @@
echo '</div>';
echo '<div class="clearer"></div>';
-?>
\ No newline at end of file
+?>
diff --git a/lang/en_utf8/moodle.php b/lang/en_utf8/moodle.php
index <HASH>..<HASH> 100644
--- a/lang/en_utf8/moodle.php
+++ b/lang/en_utf8/moodle.php
@@ -1246,6 +1246,7 @@ $string['sizegb'] = 'GB';
$string['sizekb'] = 'KB';
$string['sizemb'] = 'MB';
$string['skipped'] = 'Skipped';
+$string['skiptomaincontent'] = 'Skip forward to main content';
$string['skypeid'] = 'Skype ID';
$string['socialheadline'] = 'Social forum - latest topics';
$string['someallowguest'] = 'Some courses may allow guest access';
diff --git a/lib/pagelib.php b/lib/pagelib.php
index <HASH>..<HASH> 100644
--- a/lib/pagelib.php
+++ b/lib/pagelib.php
@@ -407,6 +407,8 @@ class page_course extends page_base {
print_header($title, $this->courserecord->fullname, $crumbtext,
'', $meta, true, $buttons, user_login_string($this->courserecord, $USER), false, $bodytags);
+
+ echo '<div class="accesshide"><a href="#startofcontent">'.get_string('skiptomaincontent').'</a></div>';
}
// SELF-REPORTING SECTION
|
Added skip links to all course formats to main content MDL-<I>
|
moodle_moodle
|
train
|
6b2da18bf6ef7e9d8d8d7b6d6ef8b9e2fb47155f
|
diff --git a/simplefix/message.py b/simplefix/message.py
index <HASH>..<HASH> 100644
--- a/simplefix/message.py
+++ b/simplefix/message.py
@@ -58,6 +58,10 @@ class FixMessage(object):
self.pairs = []
return
+ def count(self):
+ """Return the number of pairs in this message."""
+ return len(self.pairs)
+
def append_pair(self, tag, value):
"""Append a tag=value pair to this message.
@@ -217,4 +221,20 @@ class FixMessage(object):
return True
+ def __getitem__(self, item_index):
+ """Enable messages to be iterated over, and treated as a sequence.
+
+ :param item_index: Numeric index in range 0 to length - 1
+
+ Supports both 'for tag, value in message' usage, and
+ 'message[n]' access."""
+
+ if item_index >= len(self.pairs):
+ raise IndexError
+
+ tag, value = self.pairs[item_index]
+ return (int(tag), value)
+
+
+
########################################################################
diff --git a/test/test_message.py b/test/test_message.py
index <HASH>..<HASH> 100644
--- a/test/test_message.py
+++ b/test/test_message.py
@@ -192,6 +192,23 @@ class MessageTests(unittest.TestCase):
self.assertFalse(a == b)
return
+ def test_sequence_access(self):
+ msg = FixMessage()
+ msg.append_pair(8, "FIX.4.2")
+ msg.append_pair(35, "A")
+ msg.append_pair(108, 30)
+ msg.append_pair(141, "N")
+ msg.append_pair(383, 16384)
+
+ self.assertEqual(35, msg[1][0])
+ self.assertEqual(141, msg[3][0])
+
+ l = []
+ for tag, _ in msg:
+ l.append(int(tag))
+
+ self.assertEqual([8, 35, 108, 141, 383], l)
+ return
if __name__ == "__main__":
unittest.main()
|
Add support for iteration over message's fields (#4).
|
da4089_simplefix
|
train
|
5bb0810d6b82de3a0ccc7d4cd82b160c39f6ef79
|
diff --git a/python_modules/airline-demo/setup.py b/python_modules/airline-demo/setup.py
index <HASH>..<HASH> 100644
--- a/python_modules/airline-demo/setup.py
+++ b/python_modules/airline-demo/setup.py
@@ -28,7 +28,7 @@ setup(
],
packages=find_packages(exclude=['test']),
install_requires=[
- 'boto3==1.9.47',
+ 'boto3==1.9.*',
'dagster',
'dagstermill',
'descartes==1.1.0',
diff --git a/python_modules/automation/setup.py b/python_modules/automation/setup.py
index <HASH>..<HASH> 100644
--- a/python_modules/automation/setup.py
+++ b/python_modules/automation/setup.py
@@ -25,7 +25,7 @@ setup(
],
packages=find_packages(exclude=['test']),
install_requires=[
- 'boto3==1.9.47',
+ 'boto3==1.9.*',
'click>=6.7',
'faker>=1.0.4',
'pytablereader',
diff --git a/python_modules/dagma/setup.py b/python_modules/dagma/setup.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagma/setup.py
+++ b/python_modules/dagma/setup.py
@@ -52,7 +52,7 @@ def _do_setup(name='dagma'):
],
packages=find_packages(exclude=['dagma_tests']),
install_requires=[
- 'boto3==1.9.67',
+ 'boto3==1.9.*',
'cloudpickle==0.3.1',
(
'dagster @ git+https://github.com/dagster-io/dagster.git'
diff --git a/python_modules/dagster-airflow/setup.py b/python_modules/dagster-airflow/setup.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagster-airflow/setup.py
+++ b/python_modules/dagster-airflow/setup.py
@@ -50,7 +50,7 @@ def _do_setup(name='dagster-airflow'):
# docker api
'docker==3.7.0',
# aws
- 'boto3==1.9.103',
+ 'boto3==1.9.*',
],
entry_points={"console_scripts": ['dagster-airflow = dagster_airflow.cli:main']},
)
|
Relax boto3 constraints to be compatible (#<I>)
|
dagster-io_dagster
|
train
|
bfbeb185752b1b93e4892d716b0405f4b55c6871
|
diff --git a/yalla.js b/yalla.js
index <HASH>..<HASH> 100644
--- a/yalla.js
+++ b/yalla.js
@@ -1085,7 +1085,7 @@ var yalla = (function () {
output = renderer(attributes);
}
yalla.idom.patch(dom, yalla.toDom, output);
- }
+ };
yalla.start = function (startFile, el, baseLib) {
yalla.baselib = baseLib || yalla.baseLib;
@@ -1148,7 +1148,7 @@ var yalla = (function () {
};
Store.prototype.getState = function () {
return this.state;
- }
+ };
return new Store();
};
|
Yalla version <I> stable version
|
yallajs_yalla
|
train
|
1886ca81945492b3d95620000cce09a09da943ca
|
diff --git a/lib/chamber/file_set.rb b/lib/chamber/file_set.rb
index <HASH>..<HASH> 100644
--- a/lib/chamber/file_set.rb
+++ b/lib/chamber/file_set.rb
@@ -113,8 +113,7 @@ class FileSet
def initialize(options = {})
self.namespaces = options[:namespaces] || {}
self.paths = options.fetch(:files)
- self.clean_settings = Settings.new :namespaces => namespaces,
- :decryption_key => options[:decryption_key]
+ self.clean_settings = Settings.new options
end
###
|
Pass all options to clean_settings so that we don't need to update every time we add new settings
|
thekompanee_chamber
|
train
|
e4e77147cde49f50c4ea2599774d24a44b8b99df
|
diff --git a/src/main/groovy/netflix/nebula/dependency/recommender/provider/RecommendationProviderContainer.java b/src/main/groovy/netflix/nebula/dependency/recommender/provider/RecommendationProviderContainer.java
index <HASH>..<HASH> 100644
--- a/src/main/groovy/netflix/nebula/dependency/recommender/provider/RecommendationProviderContainer.java
+++ b/src/main/groovy/netflix/nebula/dependency/recommender/provider/RecommendationProviderContainer.java
@@ -22,9 +22,9 @@ import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Namer;
import org.gradle.api.Project;
-import org.gradle.api.internal.ClosureBackedAction;
import org.gradle.api.internal.ConfigureByMapAction;
import org.gradle.api.internal.DefaultNamedDomainObjectList;
+import org.gradle.util.ConfigureUtil;
import java.util.Arrays;
import java.util.HashMap;
@@ -91,7 +91,7 @@ public class RecommendationProviderContainer extends DefaultNamedDomainObjectLis
ensureCoreBomSupportNotEnabled("propertiesFile");
String message = "nebula.dependency-recommender uses a properties file";
reasons.add(message);
- return addProvider(new PropertyFileRecommendationProvider(project), new ClosureBackedAction<PropertyFileRecommendationProvider>(closure));
+ return addProvider(new PropertyFileRecommendationProvider(project), ConfigureUtil.<PropertyFileRecommendationProvider>configureUsing(closure));
}
public MavenBomRecommendationProvider mavenBom(Map<String, ?> args) {
@@ -124,7 +124,7 @@ public class RecommendationProviderContainer extends DefaultNamedDomainObjectLis
ensureCoreBomSupportNotEnabled("ivyXml");
String message = "nebula.dependency-recommender uses a ivyXml";
reasons.add(message);
- return addProvider(new IvyRecommendationProvider(project), new ClosureBackedAction<IvyRecommendationProvider>(closure));
+ return addProvider(new IvyRecommendationProvider(project), ConfigureUtil.<IvyRecommendationProvider>configureUsing(closure));
}
public DependencyLockProvider dependencyLock(Map<String, ?> args) {
@@ -139,7 +139,7 @@ public class RecommendationProviderContainer extends DefaultNamedDomainObjectLis
ensureCoreBomSupportNotEnabled("dependencyLock");
String message = "nebula.dependency-recommender uses a dependency lock for recommendations";
reasons.add(message);
- return addProvider(new DependencyLockProvider(project), new ClosureBackedAction<DependencyLockProvider>(closure));
+ return addProvider(new DependencyLockProvider(project), ConfigureUtil.<DependencyLockProvider>configureUsing(closure));
}
public MapRecommendationProvider map(Map<String, ?> args) {
@@ -154,7 +154,7 @@ public class RecommendationProviderContainer extends DefaultNamedDomainObjectLis
ensureCoreBomSupportNotEnabled("map");
String message = "nebula.dependency-recommender uses a provided map for recommendations";
reasons.add(message);
- return addProvider(new MapRecommendationProvider(), new ClosureBackedAction<MapRecommendationProvider>(closure));
+ return addProvider(new MapRecommendationProvider(), ConfigureUtil.<MapRecommendationProvider>configureUsing(closure));
}
public CustomRecommendationProvider addProvider(Closure closure) {
|
Gradle <I> Compatibility
ClosureBackedAction was moved to a new package in gradle/gradle@b<I>a<I>f<I>d<I>d<I>bc<I>bdbe2c0af3,
which will first be released in Gradle <I>. Switching to ConfigureUtil, since there is a
note in the Javadoc recommending using org.gradle.util.ConfigureUtil anyway.
|
nebula-plugins_nebula-dependency-recommender-plugin
|
train
|
6860c0f1a1af5675bf5e1cadb4515f77d5aa40a6
|
diff --git a/slither/slither.py b/slither/slither.py
index <HASH>..<HASH> 100644
--- a/slither/slither.py
+++ b/slither/slither.py
@@ -2,15 +2,20 @@ import sys
import logging
import subprocess
+import os.path
from solcParsing.slitherSolc import SlitherSolc
from utils.colors import red
logger = logging.getLogger("Slither")
+logging.basicConfig()
class Slither(SlitherSolc):
def __init__(self, filename, solc='solc', disable_solc_warnings=False ,solc_arguments=''):
+ if not os.path.isfile(filename):
+ logger.error('{} does not exist (are you in the correct directory?)'.format(filename))
+ exit(-1)
is_ast_file = False
if filename.endswith('json'):
is_ast_file = True
|
Add check for solidity file existence
Call logger.basicConfig by default
|
crytic_slither
|
train
|
2252149c37e2786bfdea8abe8c79eb749ab82c37
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -140,6 +140,27 @@ osmtogeojson = function( data, options ) {
pseudoWay.__is_bounds_placeholder = true;
ways.push(pseudoWay);
}
+ function fullGeometryWay(way, nds) {
+ function addFullGeometryNode(lat,lon,id) {
+ // todo? add shortcut such that has_interesting_tags doesn't have to be called
+ // later on; because we already know that these nodes are by not interesting
+ var geometryNode = {
+ type:"node",
+ id: id,
+ lat: lat,
+ lon: lon
+ }
+ nodes.push(geometryNode);
+ }
+ _.each( nds, function( nd, i ) {
+ addFullGeometryNode(
+ nd.getAttribute('lat'),
+ nd.getAttribute('lon'),
+ way.nodes[i]
+ );
+ });
+ //way.__has_full_geometry = true;
+ }
// nodes
_.each( xml.getElementsByTagName('node'), function( node, i ) {
var tags = {};
@@ -187,7 +208,9 @@ osmtogeojson = function( data, options ) {
wayObject.tags = tags;
if (centroid = way.getElementsByTagName('center')[0])
centerGeometry(wayObject,centroid);
- if (bounds = way.getElementsByTagName('bounds')[0])
+ if (wnodes.length > 0 && way.getElementsByTagName('nd')[0].getAttribute('lat'))
+ fullGeometryWay(wayObject, way.getElementsByTagName('nd'));
+ else if (bounds = way.getElementsByTagName('bounds')[0])
boundsGeometry(wayObject,bounds);
ways.push(wayObject);
});
diff --git a/test/osm.test.js b/test/osm.test.js
index <HASH>..<HASH> 100644
--- a/test/osm.test.js
+++ b/test/osm.test.js
@@ -2800,4 +2800,89 @@ describe("overpass geometry types", function () {
expect(geojson.features[0].properties.geometry).to.eql("bounds");
});
+ // full geometry
+ it("full (xml)", function () {
+ var xml, geojson;
+
+ // a way
+ xml = "<osm><way id='1'>"
+ + "<bounds minlat='0' minlon='0' maxlat='1' maxlon='1'/>"
+ + "<nd ref='1' lat='0' lon='0' />"
+ + "<nd ref='2' lat='0' lon='1' />"
+ + "<nd ref='3' lat='1' lon='1' />"
+ + "<nd ref='1' lat='0' lon='0' />"
+ + "<tag k='area' v='yes' />"
+ + "</way></osm>";
+ xml = (new DOMParser()).parseFromString(xml, 'text/xml');
+
+ geojson = osmtogeojson.toGeojson(xml);
+
+ expect(geojson.features.length).to.eql(1);
+ expect(geojson.features[0].id).to.eql("way/1");
+ expect(geojson.features[0].geometry.type).to.eql("Polygon");
+ expect(geojson.features[0].geometry.coordinates[0].length).to.eql(4);
+ //expect(geojson.features[0].properties.geometry).to.eql("full");
+
+ // a relation
+ return;// todo
+ xml = "<osm><relation id='1'><bounds minlat='1.234' minlon='4.321' maxlat='2.234' maxlon='5.321'/></relation></osm>";
+ xml = (new DOMParser()).parseFromString(xml, 'text/xml');
+
+ geojson = osmtogeojson.toGeojson(xml);
+
+ expect(geojson.features.length).to.eql(1);
+ expect(geojson.features[0].id).to.eql("relation/1");
+ expect(geojson.features[0].geometry.type).to.eql("Polygon");
+ expect(geojson.features[0].properties.geometry).to.eql("bounds");
+ });
+ it("bounds (json)", function () {
+ var json, geojson;
+
+ // a way
+ return;// todo
+ json = {
+ elements: [
+ {
+ type: "way",
+ id: 1,
+ bounds: {
+ minlat: 1.234,
+ minlon: 4.321,
+ maxlat: 2.234,
+ maxlon: 5.321
+ }
+ }
+ ]
+ };
+ geojson = osmtogeojson.toGeojson(json);
+
+ expect(geojson.features.length).to.eql(1);
+ expect(geojson.features[0].id).to.eql("way/1");
+ expect(geojson.features[0].geometry.type).to.eql("Polygon");
+ expect(geojson.features[0].properties.geometry).to.eql("bounds");
+
+ // a relation
+ return;// todo
+ json = {
+ elements: [
+ {
+ type: "relation",
+ id: 1,
+ bounds: {
+ minlat: 1.234,
+ minlon: 4.321,
+ maxlat: 2.234,
+ maxlon: 5.321
+ }
+ }
+ ]
+ };
+ geojson = osmtogeojson.toGeojson(json);
+
+ expect(geojson.features.length).to.eql(1);
+ expect(geojson.features[0].id).to.eql("relation/1");
+ expect(geojson.features[0].geometry.type).to.eql("Polygon");
+ expect(geojson.features[0].properties.geometry).to.eql("bounds");
+ });
+
});
\ No newline at end of file
|
implemented full geometry for ways in xmldom mode
|
tyrasd_osmtogeojson
|
train
|
8e3ff396321e719151fedaf2bb7750fb2d3ae73f
|
diff --git a/includes/class-freemius.php b/includes/class-freemius.php
index <HASH>..<HASH> 100755
--- a/includes/class-freemius.php
+++ b/includes/class-freemius.php
@@ -19092,6 +19092,8 @@
$success_cache_expiration = 0,
$failure_cache_expiration = 0
) {
+ $should_cache = ($success_cache_expiration + $failure_cache_expiration > 0);
+
$cache_key = $should_cache ? md5( fs_strip_url_protocol($url) . json_encode( $request ) ) : false;
$response = ( false !== $cache_key ) ?
@@ -20131,17 +20133,18 @@
'timeout' => WP_FS__DEBUG_SDK ? 60 : 30,
);
- $url = WP_FS__ADDRESS . '/action/service/user_plugin/';
-
$result = array();
- $total_plugin_ids = count( $plugin_ids );
+ $url = WP_FS__ADDRESS . '/action/service/user_plugin/';
+ $total_plugin_ids = count( $plugin_ids );
+
$plugin_ids_count_per_request = 10;
for ( $i = 1; $i <= $total_plugin_ids; $i += $plugin_ids_count_per_request ) {
- $plugin_ids_set = array_slice( $plugin_ids, $i - 1, $plugin_ids_count_per_request );
+ $plugin_ids_set = array_slice( $plugin_ids, $i - 1, $plugin_ids_count_per_request );
+
$request['body']['plugin_ids'] = $plugin_ids_set;
- $response = $this->safe_remote_post(
+ $response = self::safe_remote_post(
$url,
$request,
WP_FS__TIME_24_HOURS_IN_SEC,
|
[api] [safe-remote-post] [misc] Updates after refactor.
|
Freemius_wordpress-sdk
|
train
|
fe1d01684c96d55224c67e67c31c3fd8faa05c24
|
diff --git a/retrofit/src/main/java/retrofit/client/OkClient.java b/retrofit/src/main/java/retrofit/client/OkClient.java
index <HASH>..<HASH> 100644
--- a/retrofit/src/main/java/retrofit/client/OkClient.java
+++ b/retrofit/src/main/java/retrofit/client/OkClient.java
@@ -61,7 +61,9 @@ public class OkClient implements Client {
List<Header> headers = request.getHeaders();
for (int i = 0, size = headers.size(); i < size; i++) {
Header header = headers.get(i);
- builder.addHeader(header.getName(), header.getValue());
+ String value = header.getValue();
+ if (value == null) value = "";
+ builder.addHeader(header.getName(), value);
}
return builder.build();
diff --git a/retrofit/src/test/java/retrofit/client/OkClientTest.java b/retrofit/src/test/java/retrofit/client/OkClientTest.java
index <HASH>..<HASH> 100644
--- a/retrofit/src/test/java/retrofit/client/OkClientTest.java
+++ b/retrofit/src/test/java/retrofit/client/OkClientTest.java
@@ -53,13 +53,15 @@ public final class OkClientTest {
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("kit", "kat"));
headers.add(new Header("foo", "bar"));
+ headers.add(new Header("ping", null));
Request request = new Request("GET", HOST + "/this/", headers, null);
com.squareup.okhttp.Request okRequest = OkClient.createRequest(request);
Headers okHeaders = okRequest.headers();
- assertThat(okHeaders.size()).isEqualTo(2);
+ assertThat(okHeaders.size()).isEqualTo(3);
assertThat(okHeaders.get("kit")).isEqualTo("kat");
assertThat(okHeaders.get("foo")).isEqualTo("bar");
+ assertThat(okHeaders.get("ping")).isEqualTo("");
}
@Test public void response() throws IOException {
|
Ensure we don't crash on null header values.
|
square_retrofit
|
train
|
be5e3a232692851b029ae25e83f32910ae733634
|
diff --git a/spyder/plugins/ipythonconsole/plugin.py b/spyder/plugins/ipythonconsole/plugin.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/ipythonconsole/plugin.py
+++ b/spyder/plugins/ipythonconsole/plugin.py
@@ -197,10 +197,13 @@ class IPythonConsole(SpyderPluginWidget):
self.interrupt_action = None
self.add_actions_to_main_menus = True
- if parent.no_web_widgets:
- self.info_widget_enable = False
- else:
- self.info_widget_enable = True
+ self.info_widget_enable = True
+
+ try:
+ if parent.no_web_widgets:
+ self.info_widget_enable = False
+ except AttributeError:
+ pass
# Attrs for testing
self.testing = testing
|
Enable web widgets in ipythonconsole if parent window isn't MainWindow and doesn't have no_web_widgets attr.
|
spyder-ide_spyder
|
train
|
15dbd21972bd019e8a1e9926b7dfa6e3c38e40ec
|
diff --git a/public/js/jibe.js b/public/js/jibe.js
index <HASH>..<HASH> 100644
--- a/public/js/jibe.js
+++ b/public/js/jibe.js
@@ -309,7 +309,7 @@ var Jibe = (function (BCSocket, CodeMirror, Replay, Showdown, Timestamps, TextFo
codemirror : replay_editor,
delay : 100,
room : room,
- timestamps : setTimestamps (replay_editor, 'mpgeraty')
+ timestamps : setTimestamps (replay_editor, client)
});
$('#toggle-slider').click (function () {
|
Removing my hardcoded username in favor of the client variable...
|
VisionistInc_jibe
|
train
|
cfee9fae91975c64d9b6fc5dfdff294e9260c09f
|
diff --git a/python-package/xgboost/core.py b/python-package/xgboost/core.py
index <HASH>..<HASH> 100644
--- a/python-package/xgboost/core.py
+++ b/python-package/xgboost/core.py
@@ -498,8 +498,8 @@ class DMatrix(object):
feature_types : list, optional
Set types for features.
nthread : integer, optional
- Number of threads to use for loading data from numpy array. If -1,
- uses maximum threads available on the system.
+ Number of threads to use for loading data when parallelization is
+ applicable. If -1, uses maximum threads available on the system.
"""
# force into void_p, mac need to pass things in as void_p
@@ -518,7 +518,8 @@ class DMatrix(object):
data, feature_names, feature_types = _convert_dataframes(
data, feature_names, feature_types
)
- missing = np.nan if missing is None else missing
+ missing = missing if missing is not None else np.nan
+ nthread = nthread if nthread is not None else 1
if isinstance(data, (STRING_TYPES, os_PathLike)):
handle = ctypes.c_void_p()
@@ -609,15 +610,13 @@ class DMatrix(object):
# explicitly tell np.array to try and avoid copying)
data = np.array(mat.reshape(mat.size), copy=False, dtype=np.float32)
handle = ctypes.c_void_p()
- missing = missing if missing is not None else np.nan
- nthread = nthread if nthread is not None else 1
_check_call(_LIB.XGDMatrixCreateFromMat_omp(
data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
c_bst_ulong(mat.shape[0]),
c_bst_ulong(mat.shape[1]),
ctypes.c_float(missing),
ctypes.byref(handle),
- c_bst_ulong(nthread)))
+ ctypes.c_int(nthread)))
self.handle = handle
def _init_from_dt(self, data, nthread):
@@ -648,19 +647,18 @@ class DMatrix(object):
c_bst_ulong(data.shape[0]),
c_bst_ulong(data.shape[1]),
ctypes.byref(handle),
- nthread))
+ ctypes.c_int(nthread)))
self.handle = handle
def _init_from_array_interface_columns(self, df, missing, nthread):
"""Initialize DMatrix from columnar memory format."""
interfaces_str = _cudf_array_interfaces(df)
handle = ctypes.c_void_p()
- missing = missing if missing is not None else np.nan
- nthread = nthread if nthread is not None else 1
_check_call(
_LIB.XGDMatrixCreateFromArrayInterfaceColumns(
interfaces_str,
- ctypes.c_float(missing), ctypes.c_int(nthread),
+ ctypes.c_float(missing),
+ ctypes.c_int(nthread),
ctypes.byref(handle)))
self.handle = handle
@@ -672,12 +670,11 @@ class DMatrix(object):
interface_str = bytes(json.dumps(interface, indent=2), 'utf-8')
handle = ctypes.c_void_p()
- missing = missing if missing is not None else np.nan
- nthread = nthread if nthread is not None else 1
_check_call(
_LIB.XGDMatrixCreateFromArrayInterface(
interface_str,
- ctypes.c_float(missing), ctypes.c_int(nthread),
+ ctypes.c_float(missing),
+ ctypes.c_int(nthread),
ctypes.byref(handle)))
self.handle = handle
|
Don't use uint for threads. (#<I>)
|
dmlc_xgboost
|
train
|
197f659da0de51b98f20db89c81fe2f659c15b5d
|
diff --git a/slim/Request.php b/slim/Request.php
index <HASH>..<HASH> 100644
--- a/slim/Request.php
+++ b/slim/Request.php
@@ -112,7 +112,7 @@ class Request {
}
$this->headers = $this->getHttpHeaders();
$this->cookies = $_COOKIE;
- $this->isAjax = isset($request->headers['X_REQUESTED_WITH']) && $request->headers['X_REQUESTED_WITH'] == 'XMLHttpRequest';
+ $this->isAjax = isset($this->headers['X_REQUESTED_WITH']) && $this->headers['X_REQUESTED_WITH'] == 'XMLHttpRequest';
$this->checkForHttpMethodOverride();
}
diff --git a/tests/RequestTest.php b/tests/RequestTest.php
index <HASH>..<HASH> 100644
--- a/tests/RequestTest.php
+++ b/tests/RequestTest.php
@@ -99,6 +99,33 @@ class RequestTest extends PHPUnit_Framework_TestCase {
$this->assertEquals($r->root, '/');
}
+ /**
+ * Test isAjax is set to true, when HTTP_X_REQUESTED_WITH is set to
+ * 'XMLHttpRequest'.
+ *
+ * Pre-conditions:
+ * Case A: HTTP_X_REQUESTED_WITH is set to XMLHttpRequest.
+ * Case B: HTTP_X_REQUESTED_WITH is not set to XMLHttpRequest.
+ * Case C: HTTP_X_REQUESTED_WITH is not set.
+ *
+ * Post-conditions:
+ * Case A: Request::isAjax should be true.
+ * Case B: Request::isAjax should be false.
+ * Case C: Request::isAjax should be false.
+ */
+ public function testIsAjaxSet(){
+ $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
+ $r = new Request();
+ $this->assertTrue($r->isAjax);
+
+ $_SERVER['HTTP_X_REQUESTED_WITH'] = 'foo';
+ $r = new Request();
+ $this->assertFalse($r->isAjax);
+
+ unset($_SERVER['HTTP_X_REQUESTED_WITH']);
+ $r = new Request();
+ $this->assertFalse($r->isAjax);
+ }
}
?>
|
Fixed Request::isAjax value and added tests for Request::isAjax.
|
slimphp_Slim
|
train
|
c75075b267c0890a40a349f2848e2c3a17583448
|
diff --git a/src/Parser/utils.js b/src/Parser/utils.js
index <HASH>..<HASH> 100644
--- a/src/Parser/utils.js
+++ b/src/Parser/utils.js
@@ -24,7 +24,7 @@ function htmlspecialchars_compat(str)
'>' : '>',
'&' : '&',
'"' : '"'
- }
+ };
return str.replace(/[<>&"]/g, function(c) { return t[c]; });
}
@@ -38,6 +38,6 @@ function htmlspecialchars_noquotes(str)
'<' : '<',
'>' : '>',
'&' : '&'
- }
+ };
return str.replace(/[<>&]/g, function(c) { return t[c]; });
}
\ No newline at end of file
|
Added missing semi-colons in utils.js
|
s9e_TextFormatter
|
train
|
15b5ba499b2550f20ccefc19bb9d6ce682dd5338
|
diff --git a/src/Iverberk/Larasearch/Proxy.php b/src/Iverberk/Larasearch/Proxy.php
index <HASH>..<HASH> 100644
--- a/src/Iverberk/Larasearch/Proxy.php
+++ b/src/Iverberk/Larasearch/Proxy.php
@@ -78,6 +78,18 @@ class Proxy {
}
/**
+ * @param array $query
+ * @param array $options
+ * @return \Iverberk\Larasearch\Response
+ */
+ public function query($query, $options = [])
+ {
+ $options = array_merge(['query' => $query], $options);
+
+ return App::make('iverberk.larasearch.query', ['proxy' => $this, 'term' => null, 'options' => $options])->execute();
+ }
+
+ /**
* @param bool $relations
* @param int $batchSize
* @param array $mapping
diff --git a/tests/Iverberk/Larasearch/ProxyTest.php b/tests/Iverberk/Larasearch/ProxyTest.php
index <HASH>..<HASH> 100644
--- a/tests/Iverberk/Larasearch/ProxyTest.php
+++ b/tests/Iverberk/Larasearch/ProxyTest.php
@@ -161,6 +161,47 @@ class ProxyTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals('result', $result);
}
+ /**
+ * @test
+ */
+ public function it_can_query()
+ {
+ /**
+ *
+ * Set
+ *
+ */
+ $queryMock = m::mock('Iverberk\Larasearch\Query');
+
+ $query['index'] = 'my_index';
+ $query['type'] = 'my_type';
+ $query['body']['query']['match']['testField'] = 'abc';
+
+ /**
+ *
+ * Expectation
+ *
+ */
+ $queryMock->shouldReceive('execute')->andReturn('result');
+
+ App::shouldReceive('make')
+ ->with('iverberk.larasearch.query', [
+ 'proxy' => $this->proxy,
+ 'term' => null,
+ 'options' => array_merge(['query' => $query], ['option'])])
+ ->once()
+ ->andReturn($queryMock);
+
+ /**
+ *
+ * Assertion
+ *
+ */
+ $result = $this->proxy->query($query, ['option']);
+
+ $this->assertEquals('result', $result);
+ }
+
/**
* @test
*/
|
Create a nicer interface for sending a plain query to the Elasticsearch client
|
iverberk_larasearch
|
train
|
5248b94d745981371d454fc804ad945c10088da2
|
diff --git a/airflow/hooks/hive_hooks.py b/airflow/hooks/hive_hooks.py
index <HASH>..<HASH> 100644
--- a/airflow/hooks/hive_hooks.py
+++ b/airflow/hooks/hive_hooks.py
@@ -810,6 +810,7 @@ class HiveServer2Hook(BaseHook):
lowered_statement = statement.lower().strip()
if (lowered_statement.startswith('select') or
lowered_statement.startswith('with') or
+ lowered_statement.startswith('show') or
(lowered_statement.startswith('set') and
'=' not in lowered_statement)):
description = [c for c in cur.description]
|
add show statements to hql filtering.
|
apache_airflow
|
train
|
bbd3ee580fcd2d5d46c63340944245d2e9b2183f
|
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalHelper.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalHelper.java
index <HASH>..<HASH> 100644
--- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalHelper.java
+++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/util/TraversalHelper.java
@@ -427,7 +427,9 @@ public final class TraversalHelper {
return true;
}
- if (step instanceof TraversalParent) anyStepRecursively(predicate, ((TraversalParent) step));
+ if (step instanceof TraversalParent && anyStepRecursively(predicate, ((TraversalParent) step))) {
+ return true;
+ }
}
return false;
}
diff --git a/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/util/TraversalHelperTest.java b/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/util/TraversalHelperTest.java
index <HASH>..<HASH> 100644
--- a/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/util/TraversalHelperTest.java
+++ b/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/util/TraversalHelperTest.java
@@ -29,6 +29,7 @@ import org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.LambdaFilterStep;
+import org.apache.tinkerpop.gremlin.process.traversal.step.filter.PathFilterStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.TraversalFilterStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTraversalStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.FlatMapStep;
@@ -395,4 +396,10 @@ public class TraversalHelperTest {
assertTrue(labels.contains("e"));
assertTrue(labels.contains("f"));
}
+
+ @Test
+ public void shouldFindStepsRecursively() {
+ final Traversal<?,?> traversal = __.V().repeat(__.out().simplePath());
+ assertTrue(TraversalHelper.anyStepRecursively(s -> s instanceof PathFilterStep, traversal.asAdmin()));
+ }
}
|
CTR: Fixed a bug in `TraversalHelper.anyStepRecursively()`. Also added a test to ensure proper functionality.
|
apache_tinkerpop
|
train
|
e1ee56e0ac3454c29d09f9671b2ccf36f962198f
|
diff --git a/db/seeds.rb b/db/seeds.rb
index <HASH>..<HASH> 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -5,7 +5,7 @@ super_admin = Fae::Role.create(name: 'super admin', position: 0)
Fae::User.create(
first_name: 'FINE',
last_name: 'admin',
- email: 'super.admin@finedesigngroup.com',
+ email: 'admin@finedesigngroup.com',
password: 'doingfine',
role: super_admin,
active: true
|
changed default login from super.admin to admin
|
wearefine_fae
|
train
|
a1378c9525b78ba640297cc61bfb193afca85451
|
diff --git a/src/Sylius/Behat/Context/Setup/CatalogPromotionContext.php b/src/Sylius/Behat/Context/Setup/CatalogPromotionContext.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Behat/Context/Setup/CatalogPromotionContext.php
+++ b/src/Sylius/Behat/Context/Setup/CatalogPromotionContext.php
@@ -83,9 +83,9 @@ final class CatalogPromotionContext implements Context
$catalogPromotionRule->setType(CatalogPromotionRule::TYPE_CONTAINS_VARIANTS);
$catalogPromotionRule->setConfiguration([$variant->getCode()]);
- $catalogPromotionRule->setCatalogPromotion($catalogPromotion);
- $this->entityManager->persist($catalogPromotionRule);
+ $catalogPromotion->addRule($catalogPromotionRule);
+
$this->entityManager->flush();
}
diff --git a/src/Sylius/Bundle/CoreBundle/Provider/CatalogPromotionProductsProvider.php b/src/Sylius/Bundle/CoreBundle/Provider/CatalogPromotionProductsProvider.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/CoreBundle/Provider/CatalogPromotionProductsProvider.php
+++ b/src/Sylius/Bundle/CoreBundle/Provider/CatalogPromotionProductsProvider.php
@@ -29,7 +29,7 @@ final class CatalogPromotionProductsProvider implements CatalogPromotionProducts
$this->productVariantRepository = $productVariantRepository;
}
- public function provideEligibleProducts(CatalogPromotionInterface $catalogPromotion)
+ public function provideEligibleProducts(CatalogPromotionInterface $catalogPromotion): array
{
$products = [];
diff --git a/src/Sylius/Component/Core/Provider/CatalogPromotionProductsProviderInterface.php b/src/Sylius/Component/Core/Provider/CatalogPromotionProductsProviderInterface.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Component/Core/Provider/CatalogPromotionProductsProviderInterface.php
+++ b/src/Sylius/Component/Core/Provider/CatalogPromotionProductsProviderInterface.php
@@ -8,5 +8,5 @@ use Sylius\Component\Core\Model\CatalogPromotionInterface;
interface CatalogPromotionProductsProviderInterface
{
- public function provideEligibleProducts(CatalogPromotionInterface $catalogPromotion);
+ public function provideEligibleProducts(CatalogPromotionInterface $catalogPromotion): array;
}
|
Fix adding CP rule to CP in Behat
|
Sylius_Sylius
|
train
|
72395d14b8a251315d2a84533e0eb6b0ed249c7e
|
diff --git a/snap7/util.py b/snap7/util.py
index <HASH>..<HASH> 100644
--- a/snap7/util.py
+++ b/snap7/util.py
@@ -134,11 +134,8 @@ def set_int(_bytearray, byte_index, _int):
"""
# make sure were dealing with an int
_int = int(_int)
- # int needs two be two bytes.
- byte0 = _int >> 8
- byte1 = _int - (byte0 << 8)
- _bytearray[byte_index] = byte0
- _bytearray[byte_index + 1] = byte1
+ _bytes = struct.unpack('2B', struct.pack('>h', _int))
+ _bytearray[byte_index:2] = _bytes
def get_int(_bytearray, byte_index):
@@ -147,9 +144,9 @@ def get_int(_bytearray, byte_index):
int are represented in two bytes
"""
- byte1 = _bytearray[byte_index + 1]
- byte0 = _bytearray[byte_index]
- return byte1 + (byte0 << 8)
+ data = _bytearray[byte_index:2]
+ value = struct.unpack('>h', struct.pack('2B', *data))[0]
+ return value
def set_real(_bytearray, byte_index, real):
diff --git a/test/test_util.py b/test/test_util.py
index <HASH>..<HASH> 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -68,6 +68,25 @@ class TestS7util(unittest.TestCase):
row['ID'] = 259
self.assertEqual(row['ID'], 259)
+ def test_get_int_values(self):
+ test_array = bytearray(_bytearray)
+ row = util.DB_Row(test_array, test_spec, layout_offset=4)
+ for value in (
+ -32768,
+ -16385,
+ -256,
+ -128,
+ -127,
+ 0,
+ 127,
+ 128,
+ 255,
+ 256,
+ 16384,
+ 32767):
+ row['ID'] = value
+ self.assertEqual(row['ID'], value)
+
def test_get_bool(self):
test_array = bytearray(_bytearray)
row = util.DB_Row(test_array, test_spec, layout_offset=4)
|
util.get_int() broken on Linux / Python <I> #<I> (#<I>)
rewrite get_int and set_int to use struct.pack and struct.unpack, matching
get/set_dword
Add test that fails on previous implementation
|
gijzelaerr_python-snap7
|
train
|
e752a48a3012e43e4471cce0412cd9beadd3be57
|
diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion.go
index <HASH>..<HASH> 100644
--- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion.go
+++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion.go
@@ -37,5 +37,7 @@ func ConvertToGVK(obj runtime.Object, gvk schema.GroupVersionKind, o admission.O
if err != nil {
return nil, err
}
+ // Explicitly set the GVK
+ out.GetObjectKind().SetGroupVersionKind(gvk)
return out, nil
}
diff --git a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion_test.go b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion_test.go
index <HASH>..<HASH> 100644
--- a/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion_test.go
+++ b/staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/generic/conversion_test.go
@@ -62,6 +62,10 @@ func TestConvertToGVK(t *testing.T) {
},
gvk: examplev1.SchemeGroupVersion.WithKind("Pod"),
expectedObj: &examplev1.Pod{
+ TypeMeta: metav1.TypeMeta{
+ APIVersion: "example.apiserver.k8s.io/v1",
+ Kind: "Pod",
+ },
ObjectMeta: metav1.ObjectMeta{
Name: "pod1",
Labels: map[string]string{
@@ -87,6 +91,10 @@ func TestConvertToGVK(t *testing.T) {
},
gvk: example2v1.SchemeGroupVersion.WithKind("ReplicaSet"),
expectedObj: &example2v1.ReplicaSet{
+ TypeMeta: metav1.TypeMeta{
+ APIVersion: "example2.apiserver.k8s.io/v1",
+ Kind: "ReplicaSet",
+ },
ObjectMeta: metav1.ObjectMeta{
Name: "rs1",
Labels: map[string]string{
|
Explicitly set GVK when sending objects to webhooks
|
kubernetes_kubernetes
|
train
|
4b26b5837ced0c2f76495b05b87e63e05f81c2af
|
diff --git a/qless/__init__.py b/qless/__init__.py
index <HASH>..<HASH> 100755
--- a/qless/__init__.py
+++ b/qless/__init__.py
@@ -1,15 +1,17 @@
-#! /usr/bin/env python
+'''Main qless business'''
import time
import redis
import pkgutil
import logging
+import decorator
import simplejson as json
# Internal imports
from .exceptions import QlessException
+# Our logger
logger = logging.getLogger('qless')
formatter = logging.Formatter(
'%(asctime)s | PID %(process)d | [%(levelname)s] %(message)s')
@@ -23,16 +25,14 @@ logger.setLevel(logging.FATAL)
def retry(*excepts):
'''A decorator to specify a bunch of exceptions that should be caught
and the job retried. It turns out this comes up with relative frequency'''
- def decorator(func):
+ @decorator.decorator
+ def new_func(func, job):
'''No docstring'''
- def _func(job):
- '''No doctstring'''
- try:
- func(job)
- except tuple(excepts):
- job.retry()
- return _func
- return decorator
+ try:
+ func(job)
+ except tuple(excepts):
+ job.retry()
+ return new_func
class Jobs(object):
diff --git a/requirements.txt b/requirements.txt
index <HASH>..<HASH> 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -5,3 +5,4 @@ redis==2.7.5
psutil==0.7.1
gevent==0.13.8
setproctitle==1.1.5
+decorator==3.4.0
diff --git a/test/test_client.py b/test/test_client.py
index <HASH>..<HASH> 100644
--- a/test/test_client.py
+++ b/test/test_client.py
@@ -168,3 +168,8 @@ class TestRetry(TestQless):
self.client.jobs['jid'].untag('valueerror')
self.client.queues['foo'].pop().process()
self.assertEqual(self.client.jobs['jid'].state, 'failed')
+
+ def test_docstring(self):
+ '''Retry decorator should preserve docstring'''
+ self.assertEqual(Foo.process.__doc__,
+ 'This is supposed to raise an Exception')
|
Switched to using the decorator module to preserve docstring, signature, etc.
|
seomoz_qless-py
|
train
|
fa293d87ba55e60937559c9647bcef24827cba77
|
diff --git a/command/install.py b/command/install.py
index <HASH>..<HASH> 100644
--- a/command/install.py
+++ b/command/install.py
@@ -365,9 +365,9 @@ class install (Command):
# Run all sub-commands: currently this just means install all
# Python modules using 'install_lib'.
- for (func, cmd) in self.sub_commands:
+ for (func, cmd_name) in self.sub_commands:
if func is None or func():
- self.run_peer (cmd)
+ self.run_peer (cmd_name)
if self.path_file:
self.create_path_file ()
@@ -387,13 +387,25 @@ class install (Command):
# This command doesn't have any outputs of its own, so just
# get the outputs of all its sub-commands.
outputs = []
- for (func, cmd) in self.sub_commands:
+ for (func, cmd_name) in self.sub_commands:
if func is None or func():
- outputs.extend (self.run_peer (cmd))
+ cmd = self.find_peer (cmd_name)
+ outputs.extend (cmd.get_outputs())
return outputs
+ def get_inputs (self):
+ # XXX gee, this looks familiar ;-(
+ inputs = []
+ for (func, cmd_name) in self.sub_commands:
+ if func is None or func():
+ cmd = self.find_peer (cmd_name)
+ inputs.extend (cmd.get_inputs())
+
+ return inputs
+
+
def create_path_file (self):
filename = os.path.join (self.install_libbase,
self.path_file + ".pth")
|
Fixed 'get_outputs()' so it actually works.
Added 'get_inputs()' (which is strikingly similar to 'get_outputs()' - sigh).
Cosmetic tweaks.
|
pypa_setuptools
|
train
|
7b19d0d90b6eff4f7f33357c443c9c4ab12d339a
|
diff --git a/doc/conf.py b/doc/conf.py
index <HASH>..<HASH> 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -20,6 +20,7 @@ import os
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
+import pkg_resources
# -- General configuration ------------------------------------------------
@@ -60,10 +61,9 @@ author = 'Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcie
# built documents.
#
# The short X.Y version.
-# FIXME: pull from setup.py
-version = '0.15'
+version = next(pkg_resources.find_distributions('..')).version
# The full version, including alpha/beta/rc tags.
-release = '0.15'
+release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
|
pull doc version from setup.py, fix #<I>
|
tjcsl_cslbot
|
train
|
7b46768aa7947438fe8f872690097a4f3acdb034
|
diff --git a/django_extensions/management/shells.py b/django_extensions/management/shells.py
index <HASH>..<HASH> 100644
--- a/django_extensions/management/shells.py
+++ b/django_extensions/management/shells.py
@@ -58,6 +58,13 @@ def import_objects(options, style):
# models from installed apps. (this is fixed by now, but leaving it here
# for people using 0.96 or older trunk (pre [5919]) versions.
from django.db.models.loading import get_models, get_apps
+ mongoengine = False
+ try:
+ from mongoengine.base import _document_registry
+ mongoengine = True
+ except:
+ pass
+
loaded_models = get_models() # NOQA
from django.conf import settings
@@ -75,6 +82,17 @@ def import_objects(options, style):
for k, v in imports.items():
imported_objects[k] = v
+ load_models = {}
+ if mongoengine:
+ for name, mod in _document_registry.items():
+ name = name.split('.')[-1]
+ app_name = mod.__module__.split('.')[-2]
+ if app_name in dont_load or ("%s.%s" % (app_name, name)) in dont_load:
+ continue
+
+ load_models.setdefault(mod.__module__, [])
+ load_models[mod.__module__].append(name)
+
for app_mod in get_apps():
app_models = get_models(app_mod)
if not app_models:
@@ -85,12 +103,21 @@ def import_objects(options, style):
continue
app_aliases = model_aliases.get(app_name, {})
+ for mod in app_models:
+ if "%s.%s" % (app_name, mod.__name__) in dont_load:
+ continue
+
+ load_models.setdefault(mod.__module__, [])
+ load_models[mod.__module__].append(mod.__name__)
+
+ for app_mod, models in load_models.items():
+ app_name = app_mod.split('.')[-2]
+ app_aliases = model_aliases.get(app_name, {})
model_labels = []
- for model in app_models:
+ for model_name in models:
try:
- imported_object = getattr(__import__(app_mod.__name__, {}, {}, model.__name__), model.__name__)
- model_name = model.__name__
+ imported_object = getattr(__import__(app_mod, {}, {}, model_name), model_name)
if "%s.%s" % (app_name, model_name) in dont_load:
continue
@@ -106,10 +133,11 @@ def import_objects(options, style):
if options.get("traceback"):
traceback.print_exc()
if not quiet_load:
- print(style.ERROR("Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_mod.__name__, str(e))))
+ print(style.ERROR("Failed to import '%s' from '%s' reason: %s" % (model_name, app_mod, str(e))))
continue
+
if not quiet_load:
- print(style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.__name__.split('.')[-2], ", ".join(model_labels))))
+ print(style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.split('.')[-2], ", ".join(model_labels))))
# Perform post-imports after any other imports
imports = import_items(getattr(settings, 'SHELL_PLUS_POST_IMPORTS', {}))
|
added support for mongoengine with the updated code
|
django-extensions_django-extensions
|
train
|
93cc0c9744c9dc1498139fe9e574d59a79fe6891
|
diff --git a/get_git_test.go b/get_git_test.go
index <HASH>..<HASH> 100644
--- a/get_git_test.go
+++ b/get_git_test.go
@@ -263,6 +263,16 @@ func TestGitGetter_submodule(t *testing.T) {
g := new(GitGetter)
dst := tempDir(t)
+ relpath := func(basepath, targpath string) string {
+ relpath, err := filepath.Rel(basepath, targpath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.Replace(relpath, `\`, `/`, -1)
+ // on windows git still prefers relatives paths
+ // containing `/` for submodules
+ }
+
// Set up the grandchild
gc := testGitRepo(t, "grandchild")
gc.commitFile("grandchild.txt", "grandchild")
@@ -270,13 +280,13 @@ func TestGitGetter_submodule(t *testing.T) {
// Set up the child
c := testGitRepo(t, "child")
c.commitFile("child.txt", "child")
- c.git("submodule", "add", gc.dir)
+ c.git("submodule", "add", "-f", relpath(c.dir, gc.dir))
c.git("commit", "-m", "Add grandchild submodule")
// Set up the parent
p := testGitRepo(t, "parent")
p.commitFile("parent.txt", "parent")
- p.git("submodule", "add", c.dir)
+ p.git("submodule", "add", "-f", relpath(p.dir, c.dir))
p.git("commit", "-m", "Add child submodule")
// Clone the root repository
|
TestGitGetter_submodule: use relative paths for submodules as git does not like drive names
|
hashicorp_go-getter
|
train
|
451bf05827e602b122c3a00d722190557927a673
|
diff --git a/src/commands/exec.js b/src/commands/exec.js
index <HASH>..<HASH> 100644
--- a/src/commands/exec.js
+++ b/src/commands/exec.js
@@ -16,6 +16,10 @@ const {
function getManifestDefaults() {
const manifest = require(resolveExtensionPath("dist/manifest.json"));
+ if (!manifest.options) {
+ return {};
+ }
+
return manifest.options.reduce((defaultOptions, option) => {
defaultOptions[option.id] = option.default;
|
Handle no-options case in exec command
|
zeplin_zem
|
train
|
e5c436dfc39f38007c1cf8ee5e42a2e33e71740c
|
diff --git a/tests/test_base_utils.py b/tests/test_base_utils.py
index <HASH>..<HASH> 100644
--- a/tests/test_base_utils.py
+++ b/tests/test_base_utils.py
@@ -47,7 +47,7 @@ def test_attrs_with_repr():
def __repr__(self):
return 'foo'
- assert hash(WithRepr(1)) == hash(WithRepr(1))
+ # assert hash(WithRepr(1)) == hash(WithRepr(1))
assert repr(WithRepr(2)) == 'foo'
|
Comment out failing check. See GH-<I>.
|
TeamHG-Memex_eli5
|
train
|
8873e39fa11a346d320f7183ffdb79a78f09bf04
|
diff --git a/backtrader/indicators/lineutils.py b/backtrader/indicators/lineutils.py
index <HASH>..<HASH> 100644
--- a/backtrader/indicators/lineutils.py
+++ b/backtrader/indicators/lineutils.py
@@ -54,7 +54,7 @@ class _LineBasePeriod(_LineBase):
class Highest(_LineBasePeriod):
def next(self):
- self.lines[0] = max(self.dataline.get(size=self.p.period, ago=self.p.ago))
+ self.lines[0] = max(self.dline.get(size=self.p.period, ago=self.p.ago))
def once(self, start, end):
darray = self.dline.array
@@ -73,7 +73,7 @@ class Max(Highest):
class Lowest(_LineBasePeriod):
def next(self):
- self.lines[0] = min(self.dataline.get(size=self.p.period, ago=self.p.ago))
+ self.lines[0] = min(self.dline.get(size=self.p.period, ago=self.p.ago))
def once(self, start, end):
darray = self.dline.array
|
Highest/Lowest leftovers corrected in next from previous incarnation
|
backtrader_backtrader
|
train
|
70699712abbfd70e16dbbea62cbea59c43b056a7
|
diff --git a/reactor-core/src/main/java/reactor/core/publisher/FluxDoOnEach.java b/reactor-core/src/main/java/reactor/core/publisher/FluxDoOnEach.java
index <HASH>..<HASH> 100644
--- a/reactor-core/src/main/java/reactor/core/publisher/FluxDoOnEach.java
+++ b/reactor-core/src/main/java/reactor/core/publisher/FluxDoOnEach.java
@@ -129,6 +129,7 @@ final class FluxDoOnEach<T> extends FluxOperator<T, T> {
onSignal.accept(Signal.complete(cachedContext));
}
catch (Throwable e) {
+ state = STATE_MONO_START;
onError(Operators.onOperatorError(s, e, cachedContext));
return;
}
@@ -171,15 +172,14 @@ final class FluxDoOnEach<T> extends FluxOperator<T, T> {
if (state == STATE_DONE) {
return;
}
- boolean applyHandler = state < STATE_SKIP_HANDLER;
+ short oldState = state;
state = STATE_DONE;
- if (applyHandler) {
+ if (oldState < STATE_SKIP_HANDLER) {
try {
onSignal.accept(Signal.complete(cachedContext));
}
catch (Throwable e) {
- //we won't try to apply the handler (even with different signal type)
- state = STATE_SKIP_HANDLER;
+ state = oldState;
onError(Operators.onOperatorError(s, e, cachedContext));
return;
}
diff --git a/reactor-core/src/test/java/reactor/core/publisher/FluxDoOnEachTest.java b/reactor-core/src/test/java/reactor/core/publisher/FluxDoOnEachTest.java
index <HASH>..<HASH> 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/FluxDoOnEachTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/FluxDoOnEachTest.java
@@ -238,21 +238,28 @@ public class FluxDoOnEachTest {
@Test
public void completeCallbackError() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
- LongAdder state = new LongAdder();
+ AtomicBoolean completeHandled = new AtomicBoolean();
+ AtomicBoolean errorHandled = new AtomicBoolean();
Throwable err = new Exception("test");
Flux.just(1)
.doOnEach(s -> {
if (s.isOnComplete()) {
- state.increment();
+ completeHandled.set(true);
throw Exceptions.propagate(err);
}
+ if (s.isOnError()) {
+ errorHandled.set(true);
+ }
})
.subscribe(ts);
ts.assertErrorMessage("test");
- Assert.assertEquals(1, state.intValue());
+ assertThat(completeHandled).as("complete() handler triggered")
+ .isTrue();
+ assertThat(errorHandled).as("complete() failure passed to error handler triggered")
+ .isTrue();
}
@Test
diff --git a/reactor-core/src/test/java/reactor/core/publisher/MonoDoOnEachTest.java b/reactor-core/src/test/java/reactor/core/publisher/MonoDoOnEachTest.java
index <HASH>..<HASH> 100644
--- a/reactor-core/src/test/java/reactor/core/publisher/MonoDoOnEachTest.java
+++ b/reactor-core/src/test/java/reactor/core/publisher/MonoDoOnEachTest.java
@@ -408,4 +408,45 @@ public class MonoDoOnEachTest {
assertThat(completeHandlerCount).hasValue(1);
}
-}
\ No newline at end of file
+
+ @Test
+ public void errorInCompleteHandlingTriggersErrorHandling() {
+ AtomicInteger errorHandlerCount = new AtomicInteger();
+
+ StepVerifier.create(
+ Mono.just("foo")
+ .hide()
+ .doOnEach(sig -> {
+ if (sig.isOnComplete()) {
+ throw new IllegalStateException("boom");
+ }
+ if (sig.isOnError()) {
+ errorHandlerCount.incrementAndGet();
+ }
+ })
+ )
+ .verifyErrorMessage("boom");
+
+ assertThat(errorHandlerCount).as("error handler invoked on top on complete").hasValue(1);
+ }
+
+ @Test
+ public void errorInCompleteHandlingTriggersErrorHandlingFused() {
+ AtomicInteger errorHandlerCount = new AtomicInteger();
+
+ StepVerifier.create(
+ Mono.just("foo")
+ .doOnEach(sig -> {
+ if (sig.isOnComplete()) {
+ throw new IllegalStateException("boom");
+ }
+ if (sig.isOnError()) {
+ errorHandlerCount.incrementAndGet();
+ }
+ })
+ )
+ .verifyErrorMessage("boom");
+
+ assertThat(errorHandlerCount).as("error handler invoked on top on complete").hasValue(1);
+ }
+}
|
fix #<I> regression: call doOnEach handler with error if complete fails
|
reactor_reactor-core
|
train
|
f734877c49b6acd23a827f2eb4d83f21f3c0db42
|
diff --git a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/FeatureScopeTracker.java b/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/FeatureScopeTracker.java
index <HASH>..<HASH> 100644
--- a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/FeatureScopeTracker.java
+++ b/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/internal/FeatureScopeTracker.java
@@ -28,7 +28,7 @@ public class FeatureScopeTracker implements IFeatureScopeTracker {
private final Map<EObject, EnumMap<IExpressionScope.Anchor, ExpressionScope>> featureScopeSessions;
- protected FeatureScopeTracker() {
+ public FeatureScopeTracker() {
featureScopeSessions = Maps.newHashMapWithExpectedSize(256);
}
|
made constructor of FeatureScopeTracker public so it can be instantiated more easily by subclasses of OptimizingFeatureScopeTrackerProvider #<I>
|
eclipse_xtext-extras
|
train
|
718db7b8537510503e35b5bd029c777ee0dcae95
|
diff --git a/api/service/service_instance.go b/api/service/service_instance.go
index <HASH>..<HASH> 100644
--- a/api/service/service_instance.go
+++ b/api/service/service_instance.go
@@ -41,3 +41,18 @@ func (si *ServiceInstance) AllApps() []app.App {
db.Session.Apps().Find(q).All(&apps)
return apps
}
+
+func (si *ServiceInstance) RemoveApp(appName string) {
+ var i int
+ var name string
+ for i, name = range si.Apps {
+ if name == appName {
+ break
+ }
+ }
+ last := len(si.Apps)-1
+ if i != last {
+ si.Apps[i] = si.Apps[last]
+ }
+ si.Apps = si.Apps[:last]
+}
diff --git a/api/service/service_instance_test.go b/api/service/service_instance_test.go
index <HASH>..<HASH> 100644
--- a/api/service/service_instance_test.go
+++ b/api/service/service_instance_test.go
@@ -94,3 +94,14 @@ func (s *S) TestRetrieveAssociatedApp(c *C) {
c.Assert(a.Name, Equals, rApp.Name)
c.Assert(a.Framework, Equals, rApp.Framework)
}
+
+func (s *S) TestRemoveApp(c *C) {
+ instance := ServiceInstance{
+ Name: "myinstance",
+ Apps: []string{"app1", "app2", "app3"},
+ }
+ instance.RemoveApp("app2")
+ c.Assert(instance.Apps, DeepEquals, []string{"app1", "app3"})
+ instance.RemoveApp("app4")
+ c.Assert(instance.Apps, DeepEquals, []string{"app1"})
+}
|
api/service: added RemoveApp method to ServiceInstance
|
tsuru_tsuru
|
train
|
f9231c2b1e5cf729a92d7094a9fdcfd7aafc7cdc
|
diff --git a/src/clientApplication.js b/src/clientApplication.js
index <HASH>..<HASH> 100644
--- a/src/clientApplication.js
+++ b/src/clientApplication.js
@@ -1,5 +1,5 @@
var $ = require('jquery');
-var Utils = require('./utils.js');
+var _ = require('./utils.js');
var Model = require('./model.js');
var ViewModel = require('./viewModel.js');
var Query = require('./query.js');
@@ -40,10 +40,10 @@ var ClientApplication = function() {
// Process all database operations that happened while offline
var flushPendingOperations = function() {
var ops = localStore.pendingOperations();
- Utils.each(ops.save, function(data, key) {
+ _.each(ops.save, function(data, key) {
//XXX Load and update model
});
- Utils.each(ops.delete, function(data, key) {
+ _.each(ops.delete, function(data, key) {
//XXX Load and delete model
});
};
@@ -57,6 +57,9 @@ var ClientApplication = function() {
}
});
+ var attachHandlers = [];
+ var attached = false;
+
return {
// Allow subscribing to database updates
pubSub: require('./clientSubscriber.js')(),
@@ -78,8 +81,8 @@ var ClientApplication = function() {
},
// Proxy view model constructor
- ViewModel: function(name, reference, constructor) {
- return this.use(ViewModel(name, reference, constructor));
+ ViewModel: function(name, reference, constructor, postCb) {
+ return this.use(ViewModel(name, reference, constructor, postCb));
},
// Proxy query constructor
@@ -102,11 +105,23 @@ var ClientApplication = function() {
install(function() {
// Make links use history api instead of default action
router.hijackLocalLinks();
+ // Run attach handlers
+ _.each(attachHandlers, function(handler) {
+ handler();
+ });
cbb && cbb();
});
}
});
});
+ },
+
+ onAttach: function(cb) {
+ if(attached) {
+ cb();
+ } else {
+ attachHandlers.push(cb);
+ }
}
};
};
diff --git a/src/model.js b/src/model.js
index <HASH>..<HASH> 100644
--- a/src/model.js
+++ b/src/model.js
@@ -139,7 +139,7 @@ var Instance = function() {
}
var finish = function() {
self.data.local = [];
- cb && cb();
+ cb && typeof(cb) == 'function' && cb();
self.emit('save');
};
}
diff --git a/src/serverApplication.js b/src/serverApplication.js
index <HASH>..<HASH> 100644
--- a/src/serverApplication.js
+++ b/src/serverApplication.js
@@ -212,8 +212,8 @@ var ServerApplication = function(options) {
},
// Proxy view model constructor
- ViewModel: function(name, reference, constructor) {
- return this.use(ViewModel(name, reference, constructor));
+ ViewModel: function(name, reference, constructor, postCb) {
+ return this.use(ViewModel(name, reference, constructor, postCb));
},
// Proxy query constructor
diff --git a/src/viewModel.js b/src/viewModel.js
index <HASH>..<HASH> 100644
--- a/src/viewModel.js
+++ b/src/viewModel.js
@@ -6,7 +6,7 @@ var Model = require('./model.js');
// template scopes with dynamic data
// The constructor function may return a promise if it needs
// to do aynchronous work to set up model instances
-var ViewModel = function(name, reference, constructor) {
+var ViewModel = function(name, reference, constructor, postCb) {
var model = Model('_view', reference);
return {
klass: 'ViewModel',
@@ -14,16 +14,25 @@ var ViewModel = function(name, reference, constructor) {
// Return a fully resolved and constructed view model instance
create: function(args, elem, cb) {
+ var self = this;
var inst = model.create();
inst.el = elem;
inst.resolve(function() {
+ var post = function() {
+ cb(inst);
+ if(postCb) {
+ self.app.onAttach(function() {
+ postCb.apply(inst);
+ });
+ }
+ };
var promise = constructor && constructor.apply(inst, args);
if(promise) {
promise.then(function() {
- cb(inst);
+ post();
});
} else {
- cb(inst);
+ post();
}
});
}
|
Allow passing post-attach handler to view models
|
syntheticore_declaire
|
train
|
5be54c643d8c29394f8836c94d69d055472bf925
|
diff --git a/pymatgen/electronic_structure/tests/test_plotter.py b/pymatgen/electronic_structure/tests/test_plotter.py
index <HASH>..<HASH> 100644
--- a/pymatgen/electronic_structure/tests/test_plotter.py
+++ b/pymatgen/electronic_structure/tests/test_plotter.py
@@ -190,8 +190,13 @@ class BoltztrapPlotterTest(unittest.TestCase):
os.path.join(test_dir, "boltztrap/transp/"))
plotter = BoltztrapPlotter(bz)
plotter.plot_seebeck_eff_mass_mu()
- plotter.plot_seebeck_temp()
- plotter.plot_seebeck_dop()
+
+ # TODO: These two tests fail. Whoever is responsible for the
+ # BoltztrapPlotter needs to fix these. The fact that there are not tests
+ # for the plotter is atrocious. I will reject all future additions to
+ # the plotter until these are fixed.
+ # plotter.plot_seebeck_temp()
+ # plotter.plot_seebeck_dop()
plotter.plot_complexity_factor_mu()
plotter.plot_conductivity_dop()
|
Comment out tests with an angry message at the person who coded the
BzTPlotter.
|
materialsproject_pymatgen
|
train
|
9e29ba045b93fb3a91fd567439ad2ca556c9b842
|
diff --git a/lib/dm-core/query.rb b/lib/dm-core/query.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/query.rb
+++ b/lib/dm-core/query.rb
@@ -541,29 +541,33 @@ module DataMapper
# the subject to match
#
# @param [Object] bind_value
- # the value to match with
+ # the value to match on
+ #
+ # @param [Symbol] operator
+ # the operator to match with
+ #
#
# @api private
def append_condition(subject, bind_value, operator = :eql)
property = case subject
- when Property
- subject
- when Query::Path
- validate_query_path_links(subject)
- operator = subject.operator
- subject.property
- when Operator
- return append_condition(subject.target, bind_value, subject.operator)
when Symbol
@properties[subject]
+ when Operator
+ return append_condition(subject.target, bind_value, subject.operator)
+ when Property
+ subject
when String
- if subject =~ /\w\.\w/
- query_path = @model
- subject.split('.').each { |part| query_path = query_path.send(part) }
+ if subject.include?('.')
+ query_path = model
+ subject.split('.').each { |m| query_path = query_path.send(m) }
return append_condition(query_path, bind_value, operator)
else
@properties[subject]
end
+ when Query::Path
+ validate_query_path_links(subject)
+ operator = subject.operator
+ subject.property
else
raise ArgumentError, "Condition type #{subject.inspect} not supported", caller(2)
end
|
Rearranged case statement so more common statements are checked first
|
datamapper_dm-core
|
train
|
89aa5f30ef2df09633c23bca2a343c50fbc918af
|
diff --git a/lib/http-client.js b/lib/http-client.js
index <HASH>..<HASH> 100644
--- a/lib/http-client.js
+++ b/lib/http-client.js
@@ -14,10 +14,14 @@ exports.init = function(l, o) {
console.log("Service already running. Attaching CLI to master service");
- rl.question("Command? (or help)\r\n", onCommand);
+ if (!options || options.silentMode !== true) {
+ rl.question("Command? (or help)\r\n", onCommand);
+ }
};
-function onCommand(question) {
+exports.execute = onCommand;
+
+function onCommand(question, cb) {
var split = question.split(" ");
if (split[0] === "exit") {
console.log("Exiting CLI ONLY.");
@@ -28,20 +32,20 @@ function onCommand(question) {
cmd: question,
accessKey: options.accessKey
});
- var url = "http://" + options.host + ":" + options.port + "/cli"
+ var url = "http://" + (options.host || "localhost") + ":" + (options.port || 11987) + "/cli"
+ "?" + qs
;
console.log("Running remote command: " + url);
request.post(url, function (err, res, body) {
if (err) {
- onCallback(err);
+ onCallback(err, null, cb);
} else {
- onCallback(null, body);
+ onCallback(null, body, cb);
}
});
}
-function onCallback(err, result) {
+function onCallback(err, result, cb) {
if (err) {
console.log("Error: ", err);
} else if (result) {
@@ -53,5 +57,9 @@ function onCallback(err, result) {
console.log("");//newline
- rl.question("Command? (or help)\r\n", onCommand);
+ if (!options || options.silentMode !== true) {
+ rl.question("Command? (or help)\r\n", onCommand);
+ }
+
+ cb && cb(err, result);
}
|
added silentMode option, and added cb hooks
|
godaddy_node-cluster-service
|
train
|
a34dc422e25fbfd8704e652ff787e87a385f2f6d
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -16,6 +16,12 @@
import distutils.core
import sys
+# Importing setuptools adds some features like "setup.py develop", but
+# it's optional so swallow the error if it's not there.
+try:
+ import setuptools
+except ImportError:
+ pass
# Build the epoll extension for Linux systems with Python < 2.6
extensions = []
|
Import setuptools if it's available.
|
tornadoweb_tornado
|
train
|
36564abc7e02759d076111f45ecf8a507a1158a1
|
diff --git a/src/com/googlecode/jmxtrans/model/output/StatsDWriter.java b/src/com/googlecode/jmxtrans/model/output/StatsDWriter.java
index <HASH>..<HASH> 100644
--- a/src/com/googlecode/jmxtrans/model/output/StatsDWriter.java
+++ b/src/com/googlecode/jmxtrans/model/output/StatsDWriter.java
@@ -2,8 +2,8 @@ package com.googlecode.jmxtrans.model.output;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -19,9 +19,9 @@ import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.model.Server;
import com.googlecode.jmxtrans.util.BaseOutputWriter;
+import com.googlecode.jmxtrans.util.DatagramSocketFactory;
import com.googlecode.jmxtrans.util.JmxUtils;
import com.googlecode.jmxtrans.util.LifecycleException;
-import com.googlecode.jmxtrans.util.SocketFactory;
import com.googlecode.jmxtrans.util.ValidationException;
/**
@@ -37,12 +37,17 @@ public class StatsDWriter extends BaseOutputWriter {
private String host;
private Integer port;
+ /** bucketType defaults to c == counter */
+ private String bucketType = "c";
private String rootPrefix = "servers";
- private InetAddress ipAddress;
+ private SocketAddress address;
+
+ private static final String BUCKET_TYPE = "bucketType";
private KeyedObjectPool pool;
private ManagedObject mbean;
+
/**
* Uses JmxUtils.getDefaultPoolMap()
*/
@@ -52,7 +57,7 @@ public class StatsDWriter extends BaseOutputWriter {
@Override
public void start() throws LifecycleException {
try {
- this.pool = JmxUtils.getObjectPool(new SocketFactory());
+ this.pool = JmxUtils.getObjectPool(new DatagramSocketFactory());
this.mbean = new ManagedGenericKeyedObjectPool((GenericKeyedObjectPool) pool, Server.SOCKET_FACTORY_POOL);
JmxUtils.registerJMX(this.mbean);
} catch (Exception e) {
@@ -95,18 +100,17 @@ public class StatsDWriter extends BaseOutputWriter {
rootPrefix = rootPrefixTmp;
}
- try {
- ipAddress = InetAddress.getByName(host);
- } catch (UnknownHostException uhe) {
- log.debug("Exception: " + uhe.getMessage());
- }
+ this.address = new InetSocketAddress(host, port);
+
+ if (this.getSettings().containsKey(BUCKET_TYPE))
+ bucketType = (String) this.getSettings().get(BUCKET_TYPE);
}
public void doWrite(Query query) throws Exception {
List<String> typeNames = this.getTypeNames();
- DatagramSocket socket = new DatagramSocket();
+ DatagramSocket socket = (DatagramSocket) pool.borrowObject(this.address);
try {
for (Result result : query.getResults()) {
if (isDebugEnabled()) {
@@ -124,25 +128,24 @@ public class StatsDWriter extends BaseOutputWriter {
sb.append(":");
sb.append(values.getValue().toString());
sb.append("|");
- sb.append("c\n");
+ sb.append(bucketType);
+ sb.append("\n");
String line = sb.toString();
- byte[] sendData = sb.toString().trim().getBytes();
+ byte[] sendData = line.getBytes();
if (isDebugEnabled()) {
log.debug("StatsD Message: " + line.trim());
}
- DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);
+ DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length);
socket.send(sendPacket);
}
}
}
}
} finally {
- if (socket != null && ! socket.isClosed()) {
- socket.close();
- }
+ pool.returnObject(address, socket);
}
}
}
diff --git a/src/com/googlecode/jmxtrans/util/DatagramSocketFactory.java b/src/com/googlecode/jmxtrans/util/DatagramSocketFactory.java
index <HASH>..<HASH> 100644
--- a/src/com/googlecode/jmxtrans/util/DatagramSocketFactory.java
+++ b/src/com/googlecode/jmxtrans/util/DatagramSocketFactory.java
@@ -1,6 +1,7 @@
package com.googlecode.jmxtrans.util;
import java.net.DatagramSocket;
+import java.net.SocketAddress;
import org.apache.commons.pool.BaseKeyedPoolableObjectFactory;
import org.slf4j.Logger;
@@ -23,7 +24,7 @@ public class DatagramSocketFactory extends BaseKeyedPoolableObjectFactory {
*/
@Override
public Object makeObject(Object key) throws Exception {
- return new DatagramSocket();
+ return new DatagramSocket((SocketAddress)key);
}
/**
@@ -41,6 +42,6 @@ public class DatagramSocketFactory extends BaseKeyedPoolableObjectFactory {
@Override
public boolean validateObject(Object key, Object obj) {
DatagramSocket socket = (DatagramSocket) obj;
- return !socket.isClosed();
+ return socket.isBound() && !socket.isClosed() && socket.isConnected();
}
}
|
bit of cleanup on the statsdwriter
|
jmxtrans_jmxtrans
|
train
|
ed5be57bbad462b8232b95c6e37f71ef3b96c303
|
diff --git a/openquake/commonlib/commands/info.py b/openquake/commonlib/commands/info.py
index <HASH>..<HASH> 100644
--- a/openquake/commonlib/commands/info.py
+++ b/openquake/commonlib/commands/info.py
@@ -50,6 +50,8 @@ def info(name, filtersources=False):
oqparam, sitecol, prefilter=filtersources, in_memory=filtersources)
assoc = csm.get_rlzs_assoc()
print assoc.csm_info
+ print('See https://github.com/gem/oq-risklib/blob/master/docs/'
+ 'effective-realizations.rst for an explanation')
print assoc
if filtersources:
# display information about the size of the hazard curve matrices
|
Added a reference to the documentation
|
gem_oq-engine
|
train
|
a26a6998a6ad5006deeccac631c68dc9a8d51837
|
diff --git a/riak/bucket.py b/riak/bucket.py
index <HASH>..<HASH> 100644
--- a/riak/bucket.py
+++ b/riak/bucket.py
@@ -179,7 +179,7 @@ class RiakBucket(object):
def get(self, key, r=None, pr=None):
"""
- Retrieve a JSON-encoded object from Riak.
+ Retrieve an object from Riak.
:param key: Name of the key.
:type key: string
@@ -194,7 +194,7 @@ class RiakBucket(object):
def get_binary(self, key, r=None, pr=None):
"""
- Retrieve a binary/string object from Riak.
+ Retrieve a binary/string object from Riak. DEPRECATED
:param key: Name of the key.
:type key: string
|
Fix a few doc string problems in bucket.py.
|
basho_riak-python-client
|
train
|
37d56c8746c77e2d9c5db71cc2675419f0ba56e3
|
diff --git a/packages/__examples__/renderExample.js b/packages/__examples__/renderExample.js
index <HASH>..<HASH> 100644
--- a/packages/__examples__/renderExample.js
+++ b/packages/__examples__/renderExample.js
@@ -48,7 +48,15 @@ export function renderExample({
>
<Component {...componentProps} />
<Tooltip
- renderTip={<pre>{JSON.stringify(componentProps, null, 2)}</pre>}
+ renderTip={
+ <pre>
+ {JSON.stringify(
+ { ...componentProps, browser: navigator.userAgent },
+ null,
+ 2
+ )}
+ </pre>
+ }
placement="bottom"
on={['click']}
>
@@ -58,6 +66,7 @@ export function renderExample({
screenReaderLabel="props"
/>
</Tooltip>
+ <p>{navigator.userAgent}</p>
</View>
)
}
|
docs: test: browser version log for chromatic
Temporary logging of browser version for Chromatic debugging
|
instructure_instructure-ui
|
train
|
c4f641778a2b2e57ef437c21cf6eca7014ed72e6
|
diff --git a/snippets/event-subprocess-example/src/main/java/org/camunda/bpm/example/eventsubprocess/event_subprocess_example/SendCancelMessage.java b/snippets/event-subprocess-example/src/main/java/org/camunda/bpm/example/eventsubprocess/event_subprocess_example/SendCancelMessage.java
index <HASH>..<HASH> 100644
--- a/snippets/event-subprocess-example/src/main/java/org/camunda/bpm/example/eventsubprocess/event_subprocess_example/SendCancelMessage.java
+++ b/snippets/event-subprocess-example/src/main/java/org/camunda/bpm/example/eventsubprocess/event_subprocess_example/SendCancelMessage.java
@@ -23,7 +23,7 @@ public class SendCancelMessage implements JavaDelegate {
vars.put("reason", reason);
vars.put("messageFrom", messageFrom);
- if(orderedItem == null){
+ if(orderedItem == null || orderedItem == ""){
execution.getProcessEngineServices().getRuntimeService().correlateMessage(messageType, orderBusKey, vars);
|
Changed event sub-process example. Order Item not required
|
camunda-consulting_code
|
train
|
ddd2ee304f2a8868a5198385fa73efc9356080d5
|
diff --git a/lib/populator/model_additions.rb b/lib/populator/model_additions.rb
index <HASH>..<HASH> 100644
--- a/lib/populator/model_additions.rb
+++ b/lib/populator/model_additions.rb
@@ -1,13 +1,14 @@
module Populator
module ModelAdditions
def populate(size)
- sql = (1..size).map do
- record = Record.new(self)
+ last_id = connection.select_value("SELECT id FROM #{quoted_table_name} ORDER BY id DESC", "#{name} Last ID").to_i
+ sql = (1..size).map do |i|
+ record = Record.new(self, last_id+i)
yield(record) if block_given?
- "INSERT INTO #{quoted_table_name} " +
- "(#{quoted_column_names.join(', ')}) " +
- "VALUES(#{record.attribute_values.map { |v| sanitize(v) }.join(', ')})"
+ quoted_attributes = record.attribute_values.map { |v| sanitize(v) }
+
+ "INSERT INTO #{quoted_table_name} (#{quoted_column_names.join(', ')}) VALUES(#{quoted_attributes.join(', ')})"
end.join(';')
connection.raw_connection.execute_batch(sql)
end
diff --git a/lib/populator/record.rb b/lib/populator/record.rb
index <HASH>..<HASH> 100644
--- a/lib/populator/record.rb
+++ b/lib/populator/record.rb
@@ -2,8 +2,8 @@ module Populator
class Record
attr_accessor :attributes
- def initialize(model_class)
- @attributes = {}
+ def initialize(model_class, id)
+ @attributes = { :id => id }
@columns = model_class.column_names
@columns.each do |column|
self.instance_eval <<-EOS
diff --git a/spec/populator/record_spec.rb b/spec/populator/record_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/populator/record_spec.rb
+++ b/spec/populator/record_spec.rb
@@ -2,7 +2,7 @@ require File.dirname(__FILE__) + '/../spec_helper.rb'
describe Populator::Record do
it "should have a writer and reader methods for each column" do
- record = Populator::Record.new(Product)
+ record = Populator::Record.new(Product, 1)
Product.column_names.each do |column|
record.send("#{column}=", "foo")
record.send(column).should == "foo"
@@ -10,9 +10,13 @@ describe Populator::Record do
end
it "should return attribute values in same order as columns" do
- record = Populator::Record.new(Product)
+ record = Populator::Record.new(Product, nil)
record.name = "foo"
expected = Product.column_names.map { |c| "foo" if c == 'name' }
record.attribute_values.should == expected
end
+
+ it "should assign second parameter to id" do
+ Populator::Record.new(Product, 2).id.should == 2
+ end
end
diff --git a/spec/populator_spec.rb b/spec/populator_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/populator_spec.rb
+++ b/spec/populator_spec.rb
@@ -27,6 +27,24 @@ describe Populator do
it "should only use one query when inserting records" do
$queries_executed = []
Product.populate(10)
- $queries_executed.should have(1).record
+ $queries_executed.grep(/^insert/i).should have(1).record
+ end
+
+ it "should start id at 1 and increment when table is empty" do
+ Product.delete_all
+ expected_id = 1
+ Product.populate(5) do |product|
+ product.id.should == expected_id
+ expected_id += 1
+ end
+ end
+
+ it "should start id at last id and increment" do
+ product = Product.create
+ expected_id = product.id+1
+ Product.populate(5) do |product|
+ product.id.should == expected_id
+ expected_id += 1
+ end
end
end
|
keep track of next id number and assign it to record
|
ryanb_populator
|
train
|
a8680f3b807b6876a8a45d4ddd8b8be9c93b024f
|
diff --git a/drawingTests/allShapes/script.js b/drawingTests/allShapes/script.js
index <HASH>..<HASH> 100644
--- a/drawingTests/allShapes/script.js
+++ b/drawingTests/allShapes/script.js
@@ -24,7 +24,7 @@
container.add(new P.Rectangle(new P.Position(50, 0), 50, 40, {
rotation: 0.125,
- rotationAnchor: new P.Position(25, 20),
+ rotationCenter: new P.Position(25, 20),
}));
shapes.push(container);
diff --git a/modules/component/component.js b/modules/component/component.js
index <HASH>..<HASH> 100644
--- a/modules/component/component.js
+++ b/modules/component/component.js
@@ -86,7 +86,7 @@ export default class Component extends Container {
const origin = this.getOrigin();
const relative = Position.from(positionDefinition).clone().subtract(this.position);
- const rotated = relative.clone().rotate(-this.options.rotation, this.options.rotationAnchor).subtract(origin);
+ const rotated = relative.clone().rotate(-this.options.rotation, this.options.rotationCenter).subtract(origin);
const path = new window.Path2D();
this.trace(path);
diff --git a/modules/container/container.js b/modules/container/container.js
index <HASH>..<HASH> 100644
--- a/modules/container/container.js
+++ b/modules/container/container.js
@@ -32,7 +32,7 @@ export default class Container extends EventEmitter {
...this.constructor.defaultOptions,
...options,
};
- this.options.rotationAnchor = Position.from(this.options.rotationAnchor);
+ this.options.rotationCenter = Position.from(this.options.rotationCenter);
/**
* @type {Array<Container>}
*/
@@ -162,7 +162,7 @@ export default class Container extends EventEmitter {
const position = new Position();
this.climbAncestry((ancestor) => {
- position.rotate(ancestor.options.rotation, ancestor.options.rotationAnchor).add(ancestor.position);
+ position.rotate(ancestor.options.rotation, ancestor.options.rotationCenter).add(ancestor.position);
});
return position;
@@ -194,7 +194,7 @@ export default class Container extends EventEmitter {
const relativePosition = position.clone()
.subtract(this.position)
- .rotate(-this.options.rotation, this.options.rotationAnchor);
+ .rotate(-this.options.rotation, this.options.rotationCenter);
let lastHovered = null;
let lookup = this.children.length - 1;
@@ -242,7 +242,7 @@ export default class Container extends EventEmitter {
}
if (this.options.rotation) {
- const anchor = Position.from(this.options.rotationAnchor);
+ const anchor = Position.from(this.options.rotationCenter);
ctx.translate(anchor.x, anchor.y);
ctx.rotate(this.options.rotation * radianCircle);
ctx.translate(-anchor.x, -anchor.y);
@@ -414,7 +414,7 @@ export default class Container extends EventEmitter {
* @prop {Boolean} [shown=true] - Is shown
* @prop {Number} [opacity=null] - Opacity level from 0 to 1 (null mean inherited from parent)
* @prop {Number} [rotation=0] - Rotation ratio from 0 to 1 (clockwise)
- * @prop {PositionDefinition} [rotationAnchor=new Position()] - Center of rotation relative to this position
+ * @prop {PositionDefinition} [rotationCenter=new Position()] - Center of rotation relative to this position
* @prop {Number} [zIndex=1] - Depth ordering
* @prop {Component} [clip=null] -
*/
@@ -426,7 +426,7 @@ export default class Container extends EventEmitter {
shown: true,
opacity: null,
rotation: 0,
- rotationAnchor: new Position(),
+ rotationCenter: new Position(),
zIndex: 1,
clip: null,
};
diff --git a/modules/container/container.test.js b/modules/container/container.test.js
index <HASH>..<HASH> 100644
--- a/modules/container/container.test.js
+++ b/modules/container/container.test.js
@@ -266,13 +266,13 @@ test("toJSON", (t) => {
const specific = new Container([0, 0], {
opacity: 0.5,
- rotationAnchor: [10, 20],
+ rotationCenter: [10, 20],
});
addHeir(specific);
const reJson = specific.toJSON();
t.deepEqual(reJson.options, {
opacity: 0.5,
- rotationAnchor: specific.options.rotationAnchor,
+ rotationCenter: specific.options.rotationCenter,
});
t.is(reJson.children.length, 1);
});
@@ -301,8 +301,8 @@ test("defaultOptions", (t) => {
t.is(options.shown, true);
t.is(options.opacity, null);
t.is(options.rotation, 0);
- t.is(options.rotationAnchor.x, 0);
- t.is(options.rotationAnchor.y, 0);
+ t.is(options.rotationCenter.x, 0);
+ t.is(options.rotationCenter.y, 0);
t.is(options.zIndex, 1);
t.is(options.clip, null);
});
|
:recycle: Refactoring code.
Rename option rotationAnchor to rotationCenter
fix #<I>
|
pencil-js_pencil.js
|
train
|
9a5e716fd4029ea11ab8638c0cb6c72a6fa4ab5b
|
diff --git a/system_maintenance/tests/functional/tests.py b/system_maintenance/tests/functional/tests.py
index <HASH>..<HASH> 100644
--- a/system_maintenance/tests/functional/tests.py
+++ b/system_maintenance/tests/functional/tests.py
@@ -2,8 +2,10 @@ from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
+from selenium.webdriver.support.color import Color
-from system_maintenance.tests.utilities import populate_test_db
+from system_maintenance.tests.utilities import (
+ login_sysadmin_user, populate_test_db)
class FunctionalTest(StaticLiveServerTestCase):
@@ -164,3 +166,22 @@ class FunctionalTest(StaticLiveServerTestCase):
self.password_inputbox.size['width'] / 2
self.assertAlmostEqual(center_username, window_width / 2, delta=5)
self.assertAlmostEqual(center_password, window_width / 2, delta=5)
+
+
+ # Sign in as sysadmin and go to Maintenance Records
+ self.browser.get(self.system_maintenance_url('records'))
+ self.find_authentication_elements()
+ self.username_inputbox.send_keys('sysadmin')
+ self.password_inputbox.send_keys('sysadmin' + Keys.ENTER)
+
+ # See, based on the color-coded backgrounds, that the status of the
+ # first record is 'Failed', the second is 'Complete', and the third is
+ # 'In Progress'
+ list_group_items = self.browser.find_elements_by_class_name(
+ 'list-group-item')
+ background_colors = ['#f2dede', '#ffffff', '#fcf8e3']
+
+ self.assertEqual(len(list_group_items), 3)
+ for item, color in zip(list_group_items, background_colors):
+ self.assertEqual(Color.from_string(
+ item.value_of_css_property('background-color')).hex, color)
|
Test that the color coding for 'Complete', 'In Progress', and 'Failed' statuses are correct
|
mfcovington_django-system-maintenance
|
train
|
7104d9ad2600b16a5cffc9c2e66e80b294363bc9
|
diff --git a/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java b/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java
+++ b/src/main/java/net/finmath/montecarlo/interestrate/products/BermudanSwaptionFromSwapSchedules.java
@@ -62,6 +62,7 @@ public class BermudanSwaptionFromSwapSchedules extends AbstractLIBORMonteCarloPr
private final Schedule[] floatSchedules;
private final RegressionBasisFunctionsProvider regressionBasisFunctionProvider;
private final MonteCarloConditionalExpectationRegressionFactory conditionalExpectationRegressionFactory;
+ private final boolean isUseAnalyticSwapValuationAtExercise = true;
/**
* Create a Bermudan swaption from an array of underlying swap schedules (fix leg and float leg), swap rates and notionals.
@@ -290,27 +291,39 @@ public class BermudanSwaptionFromSwapSchedules extends AbstractLIBORMonteCarloPr
* @throws CalculationException Thrown if underlying model failed to calculate stochastic process.
*/
private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException {
- RandomVariable value = model.getRandomVariableForConstant(0.0);
- for(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {
+ if(isUseAnalyticSwapValuationAtExercise) {
+ double valuationTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(0).getFixing());
+ RandomVariable numeraireAtValuationTime = model.getNumeraire(valuationTime);
+ RandomVariable monteCarloProbabilitiesAtValuationTime = model.getMonteCarloWeights(valuationTime);
+ RandomVariable value = SwaptionFromSwapSchedules.getValueOfLegAnalytic(valuationTime, model, legSchedule, paysFloat, swaprate, notional);
+ value = value.div(model.getNumeraire(valuationTime)).mult(monteCarloProbabilitiesAtValuationTime);
+ return value;
+ }
+ else {
- double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());
- double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());
- double periodLength = legSchedule.getPeriodLength(periodIndex);
+ RandomVariable value = model.getRandomVariableForConstant(0.0);
- RandomVariable numeraireAtPayment = model.getNumeraire(paymentTime);
- RandomVariable monteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);
- if(swaprate != 0.0) {
- RandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);
- value = value.add(periodCashFlowFix);
- }
- if(paysFloat) {
- RandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);
- RandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);
- value = value.add(periodCashFlowFloat);
+ for(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {
+
+ double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());
+ double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());
+ double periodLength = legSchedule.getPeriodLength(periodIndex);
+
+ RandomVariable numeraireAtPayment = model.getNumeraire(paymentTime);
+ RandomVariable monteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);
+ if(swaprate != 0.0) {
+ RandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);
+ value = value.add(periodCashFlowFix);
+ }
+ if(paysFloat) {
+ RandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);
+ RandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);
+ value = value.add(periodCashFlowFloat);
+ }
}
+ return value;
}
- return value;
}
/**
|
Bermudan uses analytic value of swap when valuing underlying.
|
finmath_finmath-lib
|
train
|
a90e18e9c5bcc052c45d93295123dc2d5c3a11c3
|
diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py
index <HASH>..<HASH> 100644
--- a/qiskit/providers/models/backendconfiguration.py
+++ b/qiskit/providers/models/backendconfiguration.py
@@ -204,8 +204,9 @@ class QasmBackendConfiguration:
def __init__(self, backend_name, backend_version, n_qubits,
basis_gates, gates, local, simulator,
conditional, open_pulse, memory,
- max_shots, coupling_map, dynamic_reprate_enabled=False,
- rep_delay_range=None, default_rep_delay=None, max_experiments=None,
+ max_shots, coupling_map, supported_instructions=None,
+ dynamic_reprate_enabled=False, rep_delay_range=None,
+ default_rep_delay=None, max_experiments=None,
sample_name=None, n_registers=None, register_map=None,
configurable=None, credits_required=None, online_date=None,
display_name=None, description=None, tags=None, **kwargs):
@@ -227,6 +228,7 @@ class QasmBackendConfiguration:
memory (bool): True if the backend supports memory
max_shots (int): The maximum number of shots allowed on the backend
coupling_map (list): The coupling map for the device
+ supported_instructions (List[str]): Instructions supported by the backend.
dynamic_reprate_enabled (bool): whether delay between programs can be set dynamically
(ie via ``rep_delay``). Defaults to False.
rep_delay_range (List[float]): 2d list defining supported range of repetition
@@ -266,6 +268,8 @@ class QasmBackendConfiguration:
self.memory = memory
self.max_shots = max_shots
self.coupling_map = coupling_map
+ if supported_instructions:
+ self.supported_instructions = supported_instructions
self.dynamic_reprate_enabled = dynamic_reprate_enabled
if rep_delay_range:
@@ -362,6 +366,9 @@ class QasmBackendConfiguration:
'dynamic_reprate_enabled': self.dynamic_reprate_enabled
}
+ if hasattr(self, 'supported_instructions'):
+ out_dict['supported_instructions'] = self.supported_instructions
+
if hasattr(self, 'rep_delay_range'):
out_dict['rep_delay_range'] = [_rd * 1e6 for _rd in self.rep_delay_range]
if hasattr(self, 'default_rep_delay'):
diff --git a/qiskit/schemas/backend_configuration_schema.json b/qiskit/schemas/backend_configuration_schema.json
index <HASH>..<HASH> 100644
--- a/qiskit/schemas/backend_configuration_schema.json
+++ b/qiskit/schemas/backend_configuration_schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://www.qiskit.org/schemas/backend_config_schema.json",
"description": "Qiskit device backend configuration",
- "version": "1.2.0",
+ "version": "1.3.0",
"definitions": {
"hamiltonian": {
"type": "object",
@@ -156,6 +156,12 @@
"type": "boolean",
"description": "Whether delay between programs can be set dynamically using 'rep_delay').",
"default": false
+ },
+ "supported_instructions": {
+ "type": "array",
+ "minItems": 0,
+ "description": "Instructions supported by the backend.",
+ "items": {"type": "string"}
}
}
},
diff --git a/test/python/providers/test_backendconfiguration.py b/test/python/providers/test_backendconfiguration.py
index <HASH>..<HASH> 100644
--- a/test/python/providers/test_backendconfiguration.py
+++ b/test/python/providers/test_backendconfiguration.py
@@ -107,6 +107,15 @@ class TestBackendConfiguration(QiskitTestCase):
# Check that an error is raised if key not found in self._channel_qubit_map
self.config.get_qubit_channels(10)
+ def test_supported_instructions(self):
+ """Test that supported instructions get entered into config dict properly."""
+ # verify the supported instructions is not in the config dict when the flag is not set
+ self.assertNotIn("supported_instructions", self.config.to_dict())
+ # verify that supported instructions get added to config dict when set
+ supp_instrs = ["u1", "u2", "play", "acquire"]
+ setattr(self.config, "supported_instructions", supp_instrs)
+ self.assertEqual(supp_instrs, self.config.to_dict()["supported_instructions"])
+
def test_get_rep_times(self):
"""Test whether rep time property is the right size"""
_rep_times_us = [100, 250, 500, 1000]
|
Add supported instruction support (#<I>)
* Add supported instr
* Add test and fix case w/ no supp instr in init
* Update schema
* Fix up schema
|
Qiskit_qiskit-terra
|
train
|
e63914a3133c75e9e54ee3c664eb6c1c66ad605e
|
diff --git a/examples/analyze_mef.py b/examples/analyze_mef.py
index <HASH>..<HASH> 100644
--- a/examples/analyze_mef.py
+++ b/examples/analyze_mef.py
@@ -159,20 +159,26 @@ if __name__ == "__main__":
gate_fraction=0.85,
sigma=5.,
full_output=True)
- min_beads_sample_gated, __, min_gate_contour = FlowCal.gate.density2d(
+ beads_sample_gated = density_gate_output.gated_data
+ gate_contour = density_gate_output.contour
+
+ min_density_gate_output = FlowCal.gate.density2d(
data=min_beads_sample_gated,
channels=['FSC','SSC'],
gate_fraction=0.85,
sigma=5.,
full_output=True)
- max_beads_sample_gated, __, max_gate_contour = FlowCal.gate.density2d(
+ min_beads_sample_gated = min_density_gate_output.gated_data
+ min_gate_contour = min_density_gate_output.contour
+
+ max_density_gate_output = FlowCal.gate.density2d(
data=max_beads_sample_gated,
channels=['FSC','SSC'],
gate_fraction=0.85,
sigma=5.,
full_output=True)
- beads_sample_gated = density_gate_output.gated_data
- gate_contour = density_gate_output.contour
+ max_beads_sample_gated = max_density_gate_output.gated_data
+ max_gate_contour = max_density_gate_output.contour
# Plot forward/side scatter 2D density plot and 1D fluorescence histograms
print("Plotting density plot and histogram...")
@@ -389,16 +395,21 @@ if __name__ == "__main__":
max_sample_gated = FlowCal.gate.high_low(max_sample_gated,
channels=['FSC','SSC','FL1'])
- min_sample_gated, __, min_gate_contour = FlowCal.gate.density2d(
+ min_density_gate_output = FlowCal.gate.density2d(
data=min_sample_gated,
channels=['FSC','SSC'],
gate_fraction=0.85,
full_output=True)
- max_sample_gated, __, max_gate_contour = FlowCal.gate.density2d(
+ min_sample_gated = min_density_gate_output.gated_data
+ min_gate_contour = min_density_gate_output.contour
+
+ max_density_gate_output = FlowCal.gate.density2d(
data=max_sample_gated,
channels=['FSC','SSC'],
gate_fraction=0.85,
full_output=True)
+ max_sample_gated = max_density_gate_output.gated_data
+ max_gate_contour = max_density_gate_output.contour
# Plot and save
min_plot_filename = '{}/density_hist_min.png'.format(samples_plot_dir)
|
Fix unpacking of density gate outputs.
|
taborlab_FlowCal
|
train
|
1b4d987ec1f58fe8c5d06fb1f75e17ce53a9f46a
|
diff --git a/lib/socket.js b/lib/socket.js
index <HASH>..<HASH> 100644
--- a/lib/socket.js
+++ b/lib/socket.js
@@ -30,9 +30,9 @@ function Socket (opts) {
}
opts = opts || {};
- this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' == global.location.protocol);
- this.host = opts.host || opts.hostname || 'localhost';
- this.port = opts.port || (this.secure ? 443 : 80);
+ this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' == location.protocol);
+ this.host = opts.host || opts.hostname || (global.location ? location.host : 'localhost');
+ this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80));
this.query = opts.query || {};
this.query.uid = rnd();
this.upgrade = false !== opts.upgrade;
|
socket: introduced `host` and `port` `location` defaults
|
socketio_engine.io-client
|
train
|
7bc13e1b566a9ac2a717a2b6f9cc188855277fdf
|
diff --git a/lib/visitor/sourcemapper.js b/lib/visitor/sourcemapper.js
index <HASH>..<HASH> 100644
--- a/lib/visitor/sourcemapper.js
+++ b/lib/visitor/sourcemapper.js
@@ -38,8 +38,15 @@ var SourceMapper = module.exports = function SourceMapper(root, options){
this.basePath = sourcemap.basePath || '.';
this.inline = sourcemap.inline;
this.comment = sourcemap.comment;
+ var filename;
+ if (extname(this.dest) === '.css') {
+ filename = basename(this.dest);
+ } else {
+ filename = basename(this.filename, extname(this.filename)) + '.css';
+ }
+
this.map = new SourceMapGenerator({
- file: basename(this.filename, extname(this.filename)) + '.css',
+ file: filename,
sourceRoot: sourcemap.sourceRoot || null
});
Compiler.call(this, root, options);
|
Fix incorrect filenames included in source maps
This was an edge case introduced when compiling single files with specific output. The current logic was building the filename in the source maps base on input name.
|
stylus_stylus
|
train
|
2c3cf1bcfa95e86776f8e88bfe8a3488fa9c3185
|
diff --git a/pydoop/mapreduce/pipes.py b/pydoop/mapreduce/pipes.py
index <HASH>..<HASH> 100644
--- a/pydoop/mapreduce/pipes.py
+++ b/pydoop/mapreduce/pipes.py
@@ -28,6 +28,7 @@ from pydoop.mapreduce.streams import get_key_value_stream, get_key_values_stream
from string_utils import create_digest
from pydoop.mapreduce.api import Counter
from environment_keys import *
+from pydoop.mapreduce.serialize import private_encode
from pydoop import hadoop_version_info
from pydoop.mapreduce.api import Factory as FactoryInterface
@@ -125,6 +126,7 @@ class CombineRunner(RecordWriter):
class TaskContext(MapContext, ReduceContext):
def __init__(self, up_link):
+ self._private_encoding = False
self.up_link = up_link
self.writer = None
self.partitioner = None
@@ -142,6 +144,9 @@ class TaskContext(MapContext, ReduceContext):
self._last_progress = 0
self._registered_counters = []
+ def enable_private_encoding(self):
+ self._private_encoding = True
+
def close(self):
if self.writer:
self.writer.close()
@@ -163,12 +168,16 @@ class TaskContext(MapContext, ReduceContext):
self.progress()
if self.writer:
self.writer.emit(key, value)
- elif self.partitioner:
- part = self.partitioner.partition(key, self.n_reduces)
- self.up_link.send('partitionedOutput', part, key, value)
else:
- logger.debug("** Sending: %r,%r" % (key, value))
- self.up_link.send('output', key, value)
+ if self._private_encoding:
+ key = private_encode(key)
+ value = private_encode(value)
+ if self.partitioner:
+ part = self.partitioner.partition(key, self.n_reduces)
+ self.up_link.send('partitionedOutput', part, key, value)
+ else:
+ logger.debug("** Sending: %r,%r" % (key, value))
+ self.up_link.send('output', key, value)
def set_job_conf(self, vals):
self._job_conf = JobConf(vals)
@@ -325,6 +334,9 @@ class StreamRunner(object):
self.logger.debug('start run_map')
factory, ctx = self.factory, self.ctx
+ if n_reduces > 0:
+ ctx.enable_private_encoding()
+
ctx._input_split = input_split
logger.debug("InputSPlit setted %r" % input_split)
if piped_input:
diff --git a/pydoop/mapreduce/streams.py b/pydoop/mapreduce/streams.py
index <HASH>..<HASH> 100644
--- a/pydoop/mapreduce/streams.py
+++ b/pydoop/mapreduce/streams.py
@@ -18,6 +18,7 @@
from abc import ABCMeta, abstractmethod
+from serialize import private_decode
class ProtocolError(Exception):
pass
@@ -100,7 +101,8 @@ class KeyValuesStream(object):
raise StopIteration
elif cmd == 'reduceKey':
values_stream = self.get_value_stream(self.stream)
- return args[0], values_stream
+ key = private_decode(args[0])
+ return key, values_stream
elif cmd == 'reduceValue':
continue
else:
@@ -114,7 +116,7 @@ class KeyValuesStream(object):
stream.push_back((cmd, args))
raise StopIteration
elif cmd == 'reduceValue':
- yield args[0]
+ yield private_decode(args[0])
else:
stream.push_back((cmd, args))
raise StopIteration
|
Added support for private enconding/decoding of key and values in pipes
|
crs4_pydoop
|
train
|
5ebb6970c3c16cde4e319e594f3dc3aea0fc02e5
|
diff --git a/cyth/cyth_script.py b/cyth/cyth_script.py
index <HASH>..<HASH> 100755
--- a/cyth/cyth_script.py
+++ b/cyth/cyth_script.py
@@ -38,9 +38,13 @@ class CythVisitor(BASE_CLASS):
self.benchmark_codes = []
self.py_modname = py_modname
self.imported_modules = {}
+ self.imported_functions = {}
+# self.all_funcalls = []
+ #self.imports_with_usemaps = {}
+ self.import_lines = ["cimport cython", "import cython"]
def get_result(self):
- return ''.join(self.result)
+ return '\n'.join(self.import_lines) + '\n' + ''.join(self.result)
def process_args(self, args, vararg, kwarg, defaults=None):
processed_argslist = map(self.visit, args)
@@ -175,6 +179,11 @@ class CythVisitor(BASE_CLASS):
return None
def visit_Module(self, node):
+# cr = CallRecorder()
+# cr.visit(node)
+# self.all_funcalls = cr.calls
+ def get_alias_name(al):
+ return al.asname if al.asname is not None else al.name
for subnode in node.body:
if is_docstring(subnode):
#print('Encountered global docstring: %s' % repr(subnode.value.s))
@@ -186,14 +195,40 @@ class CythVisitor(BASE_CLASS):
self.write(cyth_def)
elif isinstance(subnode, ast.FunctionDef):
self.visit(subnode)
- elif isinstance(subnode, (ast.Import, ast.ImportFrom)):
+ elif isinstance(subnode, ast.Import):
for alias in subnode.names:
- self.imported_modules[alias.name] = alias.asname
+ self.imported_modules[get_alias_name(alias)] = [alias, False]
+ elif isinstance(subnode, ast.ImportFrom):
+ for alias in subnode.names:
+ self.imported_functions[get_alias_name(alias)] = [subnode.module, alias, False]
else:
#print('Skipping a global %r' % subnode.__class__)
pass
+ self.import_lines.extend(self.generate_imports(self.imported_modules, self.imported_functions))
#return BASE_CLASS.visit_Module(self, node)
+ def generate_imports(self, modules, functions):
+ imports = []
+ for (alias, used_flag) in modules.itervalues():
+ if used_flag:
+ imports.append(ast_to_sourcecode(ast.Import(names=[alias])))
+ for (modulename, alias, used_flag) in functions.itervalues():
+ if used_flag and not (modulename == '__future__'):
+ imports.append(ast_to_sourcecode(ast.ImportFrom(module=modulename, names=[alias], level=0)))
+ return imports
+
+ def visit_Call(self, node):
+ print(ast.dump(node))
+ if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
+ print('visit_Call, branch 1')
+ if self.imported_modules.has_key(node.func.value.id):
+ self.imported_modules[node.func.value.id][1] = True
+ if isinstance(node.func, ast.Name):
+ print('visit_Call, branch 2')
+ if self.imported_functions.has_key(node.func.id):
+ self.imported_functions[node.func.id][2] = True
+ return BASE_CLASS.visit_Call(self, node)
+
def visit_FunctionDef(self, node):
#super(CythVisitor, self).visit_FunctionDef(node)
new_body = []
@@ -237,17 +272,20 @@ class CythVisitor(BASE_CLASS):
self.newline(extra=1)
self.write(cyth_def)
- def visit_ImportFrom(self, node):
- if node.module:
- self.statement(node, 'from ', node.level * '.',
- node.module, ' import ')
- else:
- self.statement(node, 'from ', node.level * '. import ')
- self.comma_list(node.names)
-
- def visit_Import(self, node):
- self.statement(node, 'import ')
- self.comma_list(node.names)
+# def visit_ImportFrom(self, node):
+# if node.module:
+# self.statement(node, 'from ', node.level * '.',
+# node.module, ' import ')
+# else:
+# self.statement(node, 'from ', node.level * '. import ')
+# self.comma_list(node.names)
+#
+# def visit_Import(self, node):
+# #def get_alias_name(al):
+# # return al.asname if al.asname is not None else al.name
+# self.statement(node, 'import ')
+# #if all_funcalls.
+# self.comma_list(node.names)
def comma_list(self, items, trailing=False):
for idx, item in enumerate(items):
@@ -300,6 +338,12 @@ import astor
</CYTH>
"""
+#class CallRecorder(ast.NodeVisitor):
+# def __init__(self):
+# calls = []
+# def visit_Call(self, node):
+# self.calls.append(node)
+
def ast_to_sourcecode(node):
generator = astor.codegen.SourceGenerator(' ' * 4)
|
Added automatic analysis of imports to cyth.
|
Erotemic_utool
|
train
|
0cca49e82e46ba4376b2137a32284d56366e892b
|
diff --git a/src/Lock/MySqlLock.php b/src/Lock/MySqlLock.php
index <HASH>..<HASH> 100644
--- a/src/Lock/MySqlLock.php
+++ b/src/Lock/MySqlLock.php
@@ -53,14 +53,14 @@ class MySqlLock extends LockAbstract {
}
protected function getLock($name) {
- return !$this->isLocked($name) && current($this->pdo->query(
+ return !$this->isLocked($name) && $this->pdo->query(
sprintf(
'SELECT GET_LOCK("%s", %d)',
$name,
0
),
- \PDO::FETCH_NUM
- ));
+ \PDO::FETCH_COLUMN, 0
+ )->fetch();
}
/**
@@ -70,13 +70,13 @@ class MySqlLock extends LockAbstract {
* @return bool
*/
public function releaseLock($name) {
- return (bool)current($this->pdo->query(
+ return (bool)$this->pdo->query(
sprintf(
'SELECT RELEASE_LOCK("%s")',
$name
),
- \PDO::FETCH_NUM
- ));
+ \PDO::FETCH_COLUMN, 0
+ )->fetch();
}
/**
@@ -86,12 +86,12 @@ class MySqlLock extends LockAbstract {
* @return bool
*/
public function isLocked($name) {
- return !current($this->pdo->query(
+ return !$this->pdo->query(
sprintf(
'SELECT IS_FREE_LOCK("%s")',
$name
),
- \PDO::FETCH_NUM
- ));
+ \PDO::FETCH_COLUMN, 0
+ )->fetch();
}
}
diff --git a/tests/MockPDO.php b/tests/MockPDO.php
index <HASH>..<HASH> 100644
--- a/tests/MockPDO.php
+++ b/tests/MockPDO.php
@@ -20,12 +20,16 @@ class MockPDO extends \PDO {
*/
protected static $data = array();
+ protected $_mock_pdostatment;
+
/**
* @var string[]
*/
protected $current = array();
- public function __construct () {}
+ public function __construct () {
+ $this->_mock_pdostatment = new MockPDOStatment();
+ }
public function query($statement) {
if (preg_match('/RELEASE_LOCK\("(.*)"\)/', $statement, $m)) {
@@ -49,25 +53,39 @@ class MockPDO extends \PDO {
if (current($this->_mock_is_free_lock($key)) || isset($this->current[$key])) {
self::$data[$key] = true;
$this->current[$key] = true;
- return array("1");
+ return $this->_mock_pdostatment->_mock_set_fetch("1");
}
// We use sleep because GET_LOCK(str,timeout) accept timeout in seconds
sleep($timeout);
- return array("0");
+ return $this->_mock_pdostatment->_mock_set_fetch("0");
}
protected function _mock_is_free_lock($key) {
if (isset(self::$data[$key])) {
- return array("0");
+ return $this->_mock_pdostatment->_mock_set_fetch("0");
}
- return array("1");
+ return $this->_mock_pdostatment->_mock_set_fetch("1");
}
protected function _mock_release_lock($key) {
unset(self::$data[$key]);
unset($this->current[$key]);
- return array("1");
+ return $this->_mock_pdostatment->_mock_set_fetch("1");
}
}
+
+class MockPDOStatment extends \PDOStatement {
+ protected $_mock_fetch;
+
+
+ public function _mock_set_fetch($result) {
+ $this->_mock_fetch = $result;
+ return $this;
+ }
+
+ public function fetch() {
+ return $this->_mock_fetch;
+ }
+}
\ No newline at end of file
|
bugfix in MySql implementation (need to write some tests for this)
|
arvenil_ninja-mutex
|
train
|
d1fa9f9db83e287f9a48b9138104fdd6ab459f7d
|
diff --git a/cmd/bad-key-revoker/main.go b/cmd/bad-key-revoker/main.go
index <HASH>..<HASH> 100644
--- a/cmd/bad-key-revoker/main.go
+++ b/cmd/bad-key-revoker/main.go
@@ -65,6 +65,11 @@ type uncheckedBlockedKey struct {
RevokedBy int64
}
+func (ubk uncheckedBlockedKey) String() string {
+ return fmt.Sprintf("[revokedBy: %d, keyHash: %x]",
+ ubk.RevokedBy, ubk.KeyHash)
+}
+
func (bkr *badKeyRevoker) selectUncheckedKey() (uncheckedBlockedKey, error) {
var row uncheckedBlockedKey
err := bkr.dbMap.SelectOne(
@@ -258,13 +263,17 @@ func (bkr *badKeyRevoker) invoke() (bool, error) {
}
return false, err
}
+ bkr.logger.AuditInfo(fmt.Sprintf("found unchecked block key to work on: %s", unchecked))
// select all unrevoked, unexpired serials associated with the blocked key hash
unrevokedCerts, err := bkr.findUnrevoked(unchecked)
if err != nil {
+ bkr.logger.AuditInfo(fmt.Sprintf("finding unrevoked certificates related to %s: %s",
+ unchecked, err))
return false, err
}
if len(unrevokedCerts) == 0 {
+ bkr.logger.AuditInfo(fmt.Sprintf("found no certificates that need revoking related to %s, marking row as checked", unchecked))
// mark row as checked
err = bkr.markRowChecked(unchecked)
if err != nil {
@@ -306,6 +315,10 @@ func (bkr *badKeyRevoker) invoke() (bool, error) {
}
}
+ revokerEmails := idToEmails[unchecked.RevokedBy]
+ bkr.logger.AuditInfo(fmt.Sprintf("revoking certs. revoked emails=%v, emailsToCerts=%v",
+ revokerEmails, emailsToCerts))
+
// revoke each certificate and send emails to their owners
err = bkr.revokeCerts(idToEmails[unchecked.RevokedBy], emailsToCerts)
if err != nil {
@@ -438,10 +451,12 @@ func main() {
noWork, err := bkr.invoke()
if err != nil {
keysProcessed.WithLabelValues("error").Inc()
- logger.Errf("failed to process blockedKeys row: %s", err)
+ logger.AuditErrf("failed to process blockedKeys row: %s", err)
continue
}
if noWork {
+ logger.Info(fmt.Sprintf(
+ "No work to do. Sleeping for %s", config.BadKeyRevoker.Interval.Duration))
time.Sleep(config.BadKeyRevoker.Interval.Duration)
} else {
keysProcessed.WithLabelValues("success").Inc()
diff --git a/cmd/bad-key-revoker/main_test.go b/cmd/bad-key-revoker/main_test.go
index <HASH>..<HASH> 100644
--- a/cmd/bad-key-revoker/main_test.go
+++ b/cmd/bad-key-revoker/main_test.go
@@ -14,6 +14,7 @@ import (
"github.com/letsencrypt/boulder/core"
corepb "github.com/letsencrypt/boulder/core/proto"
"github.com/letsencrypt/boulder/db"
+ blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/mocks"
rapb "github.com/letsencrypt/boulder/ra/proto"
"github.com/letsencrypt/boulder/sa"
@@ -57,7 +58,10 @@ func TestSelectUncheckedRows(t *testing.T) {
test.AssertNotError(t, err, "failed setting up db client")
defer test.ResetSATestDatabase(t)()
- bkr := &badKeyRevoker{dbMap: dbMap}
+ bkr := &badKeyRevoker{
+ dbMap: dbMap,
+ logger: blog.NewMock(),
+ }
hashA, hashB, hashC := randHash(t), randHash(t), randHash(t)
insertBlockedRow(t, dbMap, hashA, 1, true)
@@ -248,7 +252,16 @@ func TestInvoke(t *testing.T) {
mm := &mocks.Mailer{}
mr := &mockRevoker{}
- bkr := &badKeyRevoker{dbMap: dbMap, maxRevocations: 10, serialBatchSize: 1, raClient: mr, mailer: mm, emailSubject: "testing", emailTemplate: testTemplate}
+ bkr := &badKeyRevoker{
+ dbMap: dbMap,
+ maxRevocations: 10,
+ serialBatchSize: 1,
+ raClient: mr,
+ mailer: mm,
+ emailSubject: "testing",
+ emailTemplate: testTemplate,
+ logger: blog.NewMock(),
+ }
// populate DB with all the test data
regIDA := insertRegistration(t, dbMap, "example.com")
@@ -307,7 +320,15 @@ func TestInvokeRevokerHasNoExtantCerts(t *testing.T) {
mm := &mocks.Mailer{}
mr := &mockRevoker{}
- bkr := &badKeyRevoker{dbMap: dbMap, maxRevocations: 10, serialBatchSize: 1, raClient: mr, mailer: mm, emailSubject: "testing", emailTemplate: testTemplate}
+ bkr := &badKeyRevoker{dbMap: dbMap,
+ maxRevocations: 10,
+ serialBatchSize: 1,
+ raClient: mr,
+ mailer: mm,
+ emailSubject: "testing",
+ emailTemplate: testTemplate,
+ logger: blog.NewMock(),
+ }
// populate DB with all the test data
regIDA := insertRegistration(t, dbMap, "a@example.com")
|
Add more logging to bad-key-revoker. (#<I>)
|
letsencrypt_boulder
|
train
|
a607873ad26d46a85ca136a506c4f211a827be8e
|
diff --git a/retrieval/targetmanager.go b/retrieval/targetmanager.go
index <HASH>..<HASH> 100644
--- a/retrieval/targetmanager.go
+++ b/retrieval/targetmanager.go
@@ -86,7 +86,7 @@ func (tm *TargetManager) Stop() {
// Wait for all scrape inserts to complete.
tm.wg.Wait()
- tm.logger.Debugln("Target manager stopped")
+ tm.logger.Infoln("Target manager stopped.")
}
func (tm *TargetManager) reload() {
|
Log the stopping of TargetManager in Info
Fixes #<I>
|
prometheus_prometheus
|
train
|
07f149182fed3f39ec7f38a4aafbd9cfae5e16a0
|
diff --git a/cleverhans/devtools/list_files.py b/cleverhans/devtools/list_files.py
index <HASH>..<HASH> 100644
--- a/cleverhans/devtools/list_files.py
+++ b/cleverhans/devtools/list_files.py
@@ -27,11 +27,11 @@ def list_files(suffix=""):
A list of all files in CleverHans whose filepath ends with `suffix`
"""
- cleverhans_path, = cleverhans.__path__
+ cleverhans_path = os.path.abspath(cleverhans.__path__[0])
+ repo_path = os.path.abspath(os.path.join(cleverhans_path, os.pardir))
file_list = _list_files(cleverhans_path, suffix)
- repo_path = os.path.abspath(os.path.join(cleverhans_path, os.pardir))
tutorials_path = os.path.join(repo_path, "cleverhans_tutorials")
tutorials_files = _list_files(tutorials_path, suffix)
tutorials_files = [os.path.join(os.pardir, path) for path in
diff --git a/cleverhans/devtools/version.py b/cleverhans/devtools/version.py
index <HASH>..<HASH> 100644
--- a/cleverhans/devtools/version.py
+++ b/cleverhans/devtools/version.py
@@ -16,7 +16,7 @@ def dev_version():
m = hashlib.md5()
py_files = sorted(list_files(suffix=".py"))
for filename in py_files:
- with open(filename, 'r') as f:
- content = f.read()
+ with open(filename, 'rb') as f:
+ content = f.read()
m.update(content)
return m.hexdigest()
|
make this work in python3
|
tensorflow_cleverhans
|
train
|
bdf0f5365d7b386284dcda27b72fc0df116a5d2b
|
diff --git a/lib/magic_lamp.rb b/lib/magic_lamp.rb
index <HASH>..<HASH> 100644
--- a/lib/magic_lamp.rb
+++ b/lib/magic_lamp.rb
@@ -38,9 +38,8 @@ module MagicLamp
def register_fixture(options = {}, &block)
controller_class = options.fetch(:controller, ::ApplicationController)
fixture_name = options[:name]
- if block.nil?
- raise ArgumentError, "MagicLamp#register_fixture requires a block"
- end
+
+ raise_missing_block_error(block, __method__)
if fixture_name.nil? && configuration.infer_names
fixture_name = default_fixture_name(controller_class, block)
@@ -59,9 +58,7 @@ module MagicLamp
alias_method :wish, :register_fixture
def configure(&block)
- if block.nil?
- raise ArgumentError, "MagicLamp#configure requires a block"
- end
+ raise_missing_block_error(block, __method__)
block.call(configuration)
end
@@ -96,6 +93,12 @@ module MagicLamp
private
+ def raise_missing_block_error(block, method_name)
+ if block.nil?
+ raise ArgumentError, "MagicLamp##{method_name} requires a block"
+ end
+ end
+
def config_files
Dir[path.join(STARS, "magic#{LAMP}_config.rb")]
end
|
refactored missing block error stuff into private method
|
crismali_magic_lamp
|
train
|
24142e04d19d12b982643ddcda06a637cd3fa015
|
diff --git a/examples/acme/main.go b/examples/acme/main.go
index <HASH>..<HASH> 100644
--- a/examples/acme/main.go
+++ b/examples/acme/main.go
@@ -58,7 +58,7 @@ func main() {
panic(err)
}
- writer, err := speed.NewPCPWriter("acme", speed.ProcessFlag)
+ writer, err := speed.NewPCPClient("acme", speed.ProcessFlag)
if err != nil {
panic(err)
}
diff --git a/examples/http_counter/server.go b/examples/http_counter/server.go
index <HASH>..<HASH> 100644
--- a/examples/http_counter/server.go
+++ b/examples/http_counter/server.go
@@ -27,7 +27,7 @@ func main() {
panic(err)
}
- writer, err := speed.NewPCPWriter("example", speed.ProcessFlag)
+ writer, err := speed.NewPCPClient("example", speed.ProcessFlag)
if err != nil {
panic(err)
}
diff --git a/examples/instance_string/main.go b/examples/instance_string/main.go
index <HASH>..<HASH> 100644
--- a/examples/instance_string/main.go
+++ b/examples/instance_string/main.go
@@ -12,7 +12,7 @@ var timelimit = flag.Int("time", 60, "number of seconds to run for")
func main() {
flag.Parse()
- w, err := speed.NewPCPWriter("strings", speed.ProcessFlag)
+ w, err := speed.NewPCPClient("strings", speed.ProcessFlag)
if err != nil {
panic(err)
}
diff --git a/examples/simple/main.go b/examples/simple/main.go
index <HASH>..<HASH> 100644
--- a/examples/simple/main.go
+++ b/examples/simple/main.go
@@ -21,7 +21,7 @@ func main() {
panic(err)
}
- writer, err := speed.NewPCPWriter("simple", speed.ProcessFlag)
+ writer, err := speed.NewPCPClient("simple", speed.ProcessFlag)
if err != nil {
panic(err)
}
diff --git a/examples/simple_string_metric/main.go b/examples/simple_string_metric/main.go
index <HASH>..<HASH> 100644
--- a/examples/simple_string_metric/main.go
+++ b/examples/simple_string_metric/main.go
@@ -12,7 +12,7 @@ var timelimit = flag.Int("time", 60, "number of seconds to run for")
func main() {
flag.Parse()
- w, err := speed.NewPCPWriter("stringtest", speed.ProcessFlag)
+ w, err := speed.NewPCPClient("stringtest", speed.ProcessFlag)
if err != nil {
panic(err)
}
diff --git a/examples/singleton_counter/main.go b/examples/singleton_counter/main.go
index <HASH>..<HASH> 100644
--- a/examples/singleton_counter/main.go
+++ b/examples/singleton_counter/main.go
@@ -28,7 +28,7 @@ func main() {
panic(err)
}
- writer, err := speed.NewPCPWriter("singletoncounter", speed.ProcessFlag)
+ writer, err := speed.NewPCPClient("singletoncounter", speed.ProcessFlag)
if err != nil {
panic(err)
}
diff --git a/examples/singleton_string/main.go b/examples/singleton_string/main.go
index <HASH>..<HASH> 100644
--- a/examples/singleton_string/main.go
+++ b/examples/singleton_string/main.go
@@ -13,7 +13,7 @@ var timelimit = flag.Int("time", 60, "number of seconds to run for")
func main() {
flag.Parse()
- w, err := speed.NewPCPWriter("strings", speed.ProcessFlag)
+ w, err := speed.NewPCPClient("strings", speed.ProcessFlag)
if err != nil {
panic(err)
}
|
examples: rename writer to client
|
performancecopilot_speed
|
train
|
f7dcbe7667f5a69b185c880d9d3a5a1258bab5ca
|
diff --git a/components/services/src/main/java/org/openengsb/core/services/internal/ConnectorManagerImpl.java b/components/services/src/main/java/org/openengsb/core/services/internal/ConnectorManagerImpl.java
index <HASH>..<HASH> 100644
--- a/components/services/src/main/java/org/openengsb/core/services/internal/ConnectorManagerImpl.java
+++ b/components/services/src/main/java/org/openengsb/core/services/internal/ConnectorManagerImpl.java
@@ -44,6 +44,7 @@ import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import java.util.ArrayList;
+import org.openengsb.core.common.xlink.XLinkUtils;
public class ConnectorManagerImpl implements ConnectorManager {
@@ -51,14 +52,16 @@ public class ConnectorManagerImpl implements ConnectorManager {
private ConnectorRegistrationManager registrationManager;
private ConfigPersistenceService configPersistence;
- private List<XLinkToolRegistration> xlinkRegistrations;
+ private Map<XLinkRegistrationKey,XLinkToolRegistration> xlinkRegistrations;
+ private String xLinkBaseUrl = "http://localhost/openXLink";
+ private int xLinkExpiresIn = 3;
public void init() {
new Thread() {
@Override
public void run() {
try {
- xlinkRegistrations = new ArrayList<XLinkToolRegistration>();
+ xlinkRegistrations = new HashMap<XLinkRegistrationKey,XLinkToolRegistration>();
Collection<ConnectorConfiguration> configs;
try {
Map<String, String> emptyMap = Collections.emptyMap();
@@ -242,26 +245,81 @@ public class ConnectorManagerImpl implements ConnectorManager {
@Override
public void disconnectFromXLink(ConnectorId id) {
+ //api change: add hostId to disconnect
throw new UnsupportedOperationException("Not supported yet.");
}
private boolean isRegistered(ConnectorId id, String hostId){
- for(XLinkToolRegistration registration : xlinkRegistrations){
- if(registration.getHostId().equals(hostId) && registration.getConnectorId().equals(id))return true;
- }
- return false;
+ XLinkRegistrationKey key = new XLinkRegistrationKey(id, hostId);
+ return xlinkRegistrations.containsKey(key);
}
@Override
public List<XLinkToolRegistration> getXLinkRegistration(String hostId) {
List<XLinkToolRegistration> registrationsOfHostId = new ArrayList<XLinkToolRegistration>();
- for(XLinkToolRegistration registration : xlinkRegistrations){
- if(registration.getHostId().equals(hostId))registrationsOfHostId.add(registration);
+ for(XLinkRegistrationKey key : xlinkRegistrations.keySet()){
+ if(key.getHostId().equals(hostId))registrationsOfHostId.add(xlinkRegistrations.get(key));
}
return registrationsOfHostId;
}
+
public XLinkTemplate connectToXLink(ConnectorId id, String hostId, String toolName, Map<XLinkModelInformation, List<XLinkToolView>> modelsToViews) {
- throw new UnsupportedOperationException("Not supported yet.");
+ //XLinkTemplate template = XLinkUtils.prepareXLinkTemplate(xLinkBaseUrl, id.toFullID(), modelsToViews, xLinkExpiresIn, null);
+ return null;
+ }
+
+ private class XLinkRegistrationKey{
+ private ConnectorId connectorId;
+ private String hostId;
+
+ public XLinkRegistrationKey(ConnectorId connectorId, String hostId) {
+ this.connectorId = connectorId;
+ this.hostId = hostId;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final XLinkRegistrationKey other = (XLinkRegistrationKey) obj;
+ if (this.connectorId != other.connectorId && (this.connectorId == null || !this.connectorId.equals(other.connectorId))) {
+ return false;
+ }
+ if ((this.hostId == null) ? (other.hostId != null) : !this.hostId.equals(other.hostId)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 5;
+ hash = 89 * hash + (this.connectorId != null ? this.connectorId.hashCode() : 0);
+ hash = 89 * hash + (this.hostId != null ? this.hostId.hashCode() : 0);
+ return hash;
+ }
+
+ public ConnectorId getConnectorId() {
+ return connectorId;
+ }
+
+ public void setConnectorId(ConnectorId connectorId) {
+ this.connectorId = connectorId;
+ }
+
+ public String getHostId() {
+ return hostId;
+ }
+
+ public void setHostId(String hostId) {
+ this.hostId = hostId;
+ }
+
+
}
}
|
[OPENENGSB-<I>] changes in registration
|
openengsb_openengsb
|
train
|
c788c00099e06d8c18519fec38e0f5a60e3bfd98
|
diff --git a/lib/guard/watcher.rb b/lib/guard/watcher.rb
index <HASH>..<HASH> 100644
--- a/lib/guard/watcher.rb
+++ b/lib/guard/watcher.rb
@@ -46,7 +46,7 @@ module Guard
if @pattern.is_a?(Regexp)
file.match(@pattern)
else
- file == @pattern
+ file == @pattern ? [file] : nil
end
end
diff --git a/spec/guard/watcher_spec.rb b/spec/guard/watcher_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/guard/watcher_spec.rb
+++ b/spec/guard/watcher_spec.rb
@@ -41,10 +41,20 @@ describe Guard::Watcher do
before(:all) { @guard = Guard::Guard.new }
describe "a watcher's with no action" do
- before(:all) { @guard.watchers = [Guard::Watcher.new(/.*_spec\.rb/)] }
+ context "regex pattern" do
+ before(:all) { @guard.watchers = [Guard::Watcher.new(/.*_spec\.rb/)] }
+
+ it "should return paths as they came" do
+ Guard::Watcher.match_files(@guard, ['guard_rocks_spec.rb']).should == ['guard_rocks_spec.rb']
+ end
+ end
- it "should return paths as they came" do
- Guard::Watcher.match_files(@guard, ['guard_rocks_spec.rb']).should == ['guard_rocks_spec.rb']
+ context "string pattern" do
+ before(:all) { @guard.watchers = [Guard::Watcher.new('guard_rocks_spec.rb')] }
+
+ it "should return paths as they came" do
+ Guard::Watcher.match_files(@guard, ['guard_rocks_spec.rb']).should == ['guard_rocks_spec.rb']
+ end
end
end
@@ -56,7 +66,7 @@ describe Guard::Watcher do
Guard::Watcher.new('hash.rb', lambda { Hash[:foo, 'bar'] }),
Guard::Watcher.new('array.rb', lambda { ['foo', 'bar'] }),
Guard::Watcher.new('blank.rb', lambda { '' }),
- Guard::Watcher.new('uptime.rb', lambda { `uptime > /dev/null` })
+ Guard::Watcher.new(/^uptime\.rb/, lambda { `uptime > /dev/null` })
]
end
@@ -85,7 +95,7 @@ describe Guard::Watcher do
@guard.watchers = [
Guard::Watcher.new(%r{lib/(.*)\.rb}, lambda { |m| "spec/#{m[1]}_spec.rb" }),
Guard::Watcher.new(/addition(.*)\.rb/, lambda { |m| 1 + 1 }),
- Guard::Watcher.new('hash.rb', lambda { Hash[:foo, 'bar'] }),
+ Guard::Watcher.new('hash.rb', lambda { Hash[:foo, 'bar'] }),
Guard::Watcher.new(/array(.*)\.rb/, lambda { |m| ['foo', 'bar'] }),
Guard::Watcher.new(/blank(.*)\.rb/, lambda { |m| '' }),
Guard::Watcher.new(/uptime(.*)\.rb/, lambda { |m| `uptime > /dev/null` })
|
Fix bug that occurred when pattern was a string and no action was associated.
|
guard_guard
|
train
|
964ec16c09811e45fcc0fcf73077343e7af788f7
|
diff --git a/haffmpeg/core.py b/haffmpeg/core.py
index <HASH>..<HASH> 100644
--- a/haffmpeg/core.py
+++ b/haffmpeg/core.py
@@ -21,9 +21,10 @@ class HAFFmpeg(object):
"""Base initialize."""
self._ffmpeg = ffmpeg_bin
self._argv = [ffmpeg_bin]
- self._proc = None
self._chunk_size = chunk_size
self._iter_input = iter_input
+ self._bin_mode = None
+ self._proc = None
# pylint: disable=too-many-arguments
def open(self, cmd, output="-", extra_cmd=None, text=False,
@@ -52,27 +53,35 @@ class HAFFmpeg(object):
self._argv,
stderr=stderr,
stdout=stdout,
+ stdin=subprocess.PIPE,
universal_newlines=text
)
+ # save bin/text mode of process
+ self._bin_mode = False if text else True
+
def close(self, timeout=5):
"""Stop a ffmpeg instance."""
if self._proc is None or self._proc.poll() is not None:
_LOGGER.error("FFmpeg isn't running!")
return
- # send stop to ffmpeg
- self._proc.kill()
+ # set stop command for ffmpeg
+ stop = b'q' if self._bin_mode else 'q'
try:
- self._proc.wait(timeout=timeout)
+ # send stop to ffmpeg
+ self._proc.communicate(input=stop, timeout=timeout)
_LOGGER.debug("Close FFmpeg process.")
except subprocess.TimeoutExpired:
_LOGGER.warning("Timeout while waiting of FFmpeg.")
+ self._proc.kill()
+ self._proc.wait()
# clean ffmpeg cmd
self._argv = [self._ffmpeg]
self._proc = None
+ self._bin_mode = None
@property
def process(self):
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ from setuptools import setup
with open('README.rst') as f:
long_description = f.read()
-VERSION = "0.3"
+VERSION = "0.4"
setup(
name='ha-ffmpeg',
|
improve ffmpeg close process
|
pvizeli_ha-ffmpeg
|
train
|
7067c46604a03ced09dff8a31f437356c4b444ea
|
diff --git a/src/Core.php b/src/Core.php
index <HASH>..<HASH> 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -515,39 +515,43 @@ class Core implements iCore
// Read file into object
$composerObject = json_decode(file_get_contents($path), true);
- //elapsed('Loading from composer.json');
- // If composer has requirements configured
- if (isset($composerObject['require'])) {
- // Iterate requirements
- foreach ($composerObject['require'] as $requirement => $version) {
- // Ignore core module and work only with samsonos/* modules before they are not PSR- optimized
- if(($requirement != 'samsonos/php_core') && (strpos($requirement, 'samsonos/') !== false)) {
-
- //elapsed('Loading module '.$requirement);
-
- // TODO: Make possible to use local modules when developing SamsonCMS - get relative path to main folder
- // TODO: Make possible to automatically search for local modules firstly and only then default
- // TODO: Make possible to automatically define depth of web-application to build proper paths to local modules
- // TODO: Force debug message if module cannot be autoloaded by PSR-* standard
-
- // Use default path
- $path = __SAMSON_VENDOR_PATH.$requirement;
-
- // If path with underscores does not exists
+ // Gather all possible requires
+ $require = array_merge(
+ array(),
+ isset($composerObject['require']) ? array_merge($require, $composerObject['require']) : array(),
+ isset($composerObject['require']) ? array_merge($require, $composerObject['require-dev']) : array()
+ );
+
+ // Iterate requirements
+ foreach ($require as $requirement => $version) {
+ // Ignore core module and work only with samsonos/* modules before they are not PSR- optimized
+ if(($requirement != 'samsonos/php_core') && (strpos($requirement, 'samsonos/') !== false)) {
+
+ //elapsed('Loading module '.$requirement);
+
+ // TODO: Make possible to use local modules when developing SamsonCMS - get relative path to main folder
+ // TODO: Make possible to automatically search for local modules firstly and only then default
+ // TODO: Make possible to automatically define depth of web-application to build proper paths to local modules
+ // TODO: Force debug message if module cannot be autoloaded by PSR-* standard
+
+ // Use default path
+ $path = __SAMSON_VENDOR_PATH.$requirement;
+
+ // If path with underscores does not exists
+ if (!file_exists($path)) {
+ // Try path without underscore
+ $path = str_replace('_', '/', $path);
if (!file_exists($path)) {
- // Try path without underscore
- $path = str_replace('_', '/', $path);
- if (!file_exists($path)) {
- return e('Cannot load module(from ##): "##" - Path not found', E_SAMSON_FATAL_ERROR, array($path, $requirement));
- }
+ return e('Cannot load module(from ##): "##" - Path not found', E_SAMSON_FATAL_ERROR, array($path, $requirement));
}
-
- // Load module
- $this->load($path);
}
+
+ // Load module
+ $this->load($path);
}
}
+
// Load generic local module with all web-application resources
if ($this->resources($this->system_path, $ls2)) {
|
Added support to composer parser to load from require-dev section
|
samsonos_php_core
|
train
|
fea375130281d0551e38280a3a8166b951c9a84f
|
diff --git a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java
+++ b/languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanSpellerRule.java
@@ -122,6 +122,8 @@ public class GermanSpellerRule extends CompoundAwareHunspellRule {
String w = word.replaceFirst("\\.$", "");
if ("unzwar".equals(w)) {
return Collections.singletonList("und zwar");
+ } else if ("desweiteren".equals(w)) {
+ return Collections.singletonList("des Weiteren");
} else if ("wieviel".equals(w)) {
return Collections.singletonList("wie viel");
} else if ("wieviele".equals(w)) {
|
[de] improve a spelling suggestion
|
languagetool-org_languagetool
|
train
|
8c72898e2ebae7a647f231e2aa33b8ff11ee604e
|
diff --git a/bin.js b/bin.js
index <HASH>..<HASH> 100755
--- a/bin.js
+++ b/bin.js
@@ -135,6 +135,14 @@ if (process.mainModule && process.mainModule.filename === __filename) {
process.exit();
}
+ if (couch == undefined) {
+ try {
+ couch = JSON.parse(fs.readFileSync('.couchapp.json')).couch;
+ } catch (e) {
+ // Discard exception: absent or malformed config file
+ }
+ }
+
if (isUsingDirectoryConfig()) {
if (command == 'boiler') {
for (i in apps) {
|
Optionally read CouchDB url from .couchapp.json (because I don't want passwords on my command line).
|
mikeal_node.couchapp.js
|
train
|
9e448c5fef7fb6ec82f12359cbc509de9f5f74ef
|
diff --git a/src/TQ/Git/Repository/Repository.php b/src/TQ/Git/Repository/Repository.php
index <HASH>..<HASH> 100644
--- a/src/TQ/Git/Repository/Repository.php
+++ b/src/TQ/Git/Repository/Repository.php
@@ -63,7 +63,7 @@ class Repository extends AbstractRepository
*/
protected $git;
- /**
+ /**
* Opens a Git repository on the file system, optionally creates and initializes a new repository
*
* @param string $repositoryPath The full path to the repository
@@ -73,15 +73,16 @@ class Repository extends AbstractRepository
* should create the directory and init the repository instead
* @param array|null $initArguments Arguments to be passed to git-init if initializing a
* repository
- * @param string|null $repositoryRoot The full path of the repository root path to avoid bubbling
- * up the repository path looking for the .git directory.
+ * @param boolean $findRepositoryRoot False to use the repository path as the root directory.
+ *
* @return Repository
* @throws \RuntimeException If the path cannot be created
* @throws \InvalidArgumentException If the path is not valid or if it's not a valid Git repository
*/
- public static function open($repositoryPath, $git = null, $createIfNotExists = false, $initArguments = null, $repositoryRoot = null)
+ public static function open($repositoryPath, $git = null, $createIfNotExists = false, $initArguments = null, $findRepositoryRoot = true)
{
$git = Binary::ensure($git);
+ $repositoryRoot = null;
if (!is_string($repositoryPath)) {
throw new \InvalidArgumentException(sprintf(
@@ -89,7 +90,7 @@ class Repository extends AbstractRepository
));
}
- if ($repositoryRoot === null) {
+ if ($findRepositoryRoot) {
$repositoryRoot = self::findRepositoryRoot($repositoryPath);
}
|
Repository Open Argument Flag Added for Finding Repository Root
|
teqneers_PHP-Stream-Wrapper-for-Git
|
train
|
4dd4efcf981ef17ce3b648778fd1358ed08c7f46
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -52,3 +52,4 @@ docs/_build/
# PyBuilder
target/
+.DS_Store
diff --git a/bin/moneywagon b/bin/moneywagon
index <HASH>..<HASH> 100644
--- a/bin/moneywagon
+++ b/bin/moneywagon
@@ -358,7 +358,7 @@ elif argz.subparser_name == 'wallet-balance':
if not x.startswith("#")
]
- if argz.async:
+ if argz.async_:
modes['async'] = True
fiat = argz.fiat.upper()
diff --git a/moneywagon/__init__.py b/moneywagon/__init__.py
index <HASH>..<HASH> 100644
--- a/moneywagon/__init__.py
+++ b/moneywagon/__init__.py
@@ -442,6 +442,12 @@ def change_version_byte(address, new_version=None, new_crypto=None):
Convert the passed in address (or any base58 encoded string), and change the
version byte to `new_version`.
"""
+ if not new_version and new_crypto:
+ try:
+ new_version = crypto_data[new_crypto]['address_version_byte']
+ except KeyError:
+ raise CurrencyNotSupported("Can't yet make %s addresses.")
+
payload = b58decode_check(address)[1:]
return b58encode_check(chr(new_version) + payload)
diff --git a/moneywagon/mcaf.py b/moneywagon/mcaf.py
index <HASH>..<HASH> 100644
--- a/moneywagon/mcaf.py
+++ b/moneywagon/mcaf.py
@@ -131,10 +131,12 @@ def decode_mcaf(address, mode="P"):
currencies = decode(token[1:])
ret = {}
for currency in currencies:
- new_version = crypto_data[currency].get('address_version_byte', None)
- ret[currency] = change_version_byte(
- payload, new_version
- ) if new_version else None
+ try:
+ ret[currency] = change_version_byte(
+ payload, to_crypto=currency
+ )
+ except CurrencyNotSupported as exc:
+ ret[currency] = str(exc)
return ret
@@ -150,6 +152,7 @@ if __name__ == "__main__":
case = sorted(case)
encoded = encode(case)
result = sorted(decode(encoded))
+
print("Case %s" % i, end=' ')
if result == case:
print("Passed", result, str(encoded))
diff --git a/moneywagon/network_replay.py b/moneywagon/network_replay.py
index <HASH>..<HASH> 100644
--- a/moneywagon/network_replay.py
+++ b/moneywagon/network_replay.py
@@ -1,7 +1,7 @@
from __future__ import print_function
import random
-from crypto_data import crypto_data
+from .crypto_data import crypto_data
from moneywagon import get_block, push_tx, get_single_transaction, watch_mempool
from .core import to_rawtx
from moneywagon.services import BitpayInsight, ChainSo, LocalBitcoinsChain, BlockDozer
|
some python 3 fixes
|
priestc_moneywagon
|
train
|
c82c0cd8c6ff7675830e9cfd4ed39e3049e3bd20
|
diff --git a/src/txkube/_exception.py b/src/txkube/_exception.py
index <HASH>..<HASH> 100644
--- a/src/txkube/_exception.py
+++ b/src/txkube/_exception.py
@@ -7,9 +7,15 @@ from twisted.web.client import readBody
class KubernetesError(Exception):
- def __init__(self, code, response):
+ """
+ Kubernetes has returned an error for some attempted operation.
+
+ :ivar int code: The HTTP response code.
+ :ivar Status status: The *v1.Status* returned in the response.
+ """
+ def __init__(self, code, status):
self.code = code
- self.response = response
+ self.status = status
@classmethod
@@ -36,8 +42,8 @@ class KubernetesError(Exception):
def __repr__(self):
- return "<KubernetesError: code = {}; response = {}>".format(
- self.code, self.response,
+ return "<KubernetesError: code = {}; status = {}>".format(
+ self.code, self.status,
)
__str__ = __repr__
diff --git a/src/txkube/testing/integration.py b/src/txkube/testing/integration.py
index <HASH>..<HASH> 100644
--- a/src/txkube/testing/integration.py
+++ b/src/txkube/testing/integration.py
@@ -165,7 +165,7 @@ def kubernetes_client_tests(get_kubernetes):
reason.value,
MatchesStructure(
code=Equals(CONFLICT),
- response=Equals(Status(
+ status=Equals(Status(
kind=u"Status",
apiVersion=u"v1",
metadata={},
|
It changed to the v1.Status _in_ the response.
Also missing API docs for KubernetesError.
|
LeastAuthority_txkube
|
train
|
3a4b051f10badabe3731f3f5d8a574f0b1b31802
|
diff --git a/engine/test_engine.py b/engine/test_engine.py
index <HASH>..<HASH> 100644
--- a/engine/test_engine.py
+++ b/engine/test_engine.py
@@ -638,11 +638,11 @@ class Test_Engine(unittest.TestCase):
# Ignore NaN's
if numpy.isnan(depth):
continue
-
+
structural_damage = iattributes[i]['STRUCT_DAM']
contents_damage = iattributes[i]['CONTENTS_D']
for imp in [structural_damage, contents_damage]:
- msg = ('Percent damage was outside range [0,1] at depth %f: %f'
+ msg = ('Percent damage was outside range [0,1] at depth %f: %f'
% (depth, imp))
assert 0 <= imp <= 1, msg
diff --git a/gui/is_impact_calculator_thread.py b/gui/is_impact_calculator_thread.py
index <HASH>..<HASH> 100644
--- a/gui/is_impact_calculator_thread.py
+++ b/gui/is_impact_calculator_thread.py
@@ -50,7 +50,8 @@ class ISImpactCalculatorThread(threading.Thread, QObject):
Prints 'hello' to the console
- .. seealso:: http://techbase.kde.org/Development/Tutorials/Python_introduction_to_signals_and_slots
+ .. seealso::
+ http://techbase.kde.org/Development/Tutorials/Python_introduction_to_signals_and_slots
for an alternative (maybe nicer?) approach.
"""
diff --git a/gui/is_map.py b/gui/is_map.py
index <HASH>..<HASH> 100644
--- a/gui/is_map.py
+++ b/gui/is_map.py
@@ -29,7 +29,7 @@ from qgis.core import (QgsComposition,
QgsPoint,
QgsRectangle)
from qgis.gui import QgsComposerView
-from is_exceptions import (LegendLayerException,
+from is_exceptions import (LegendLayerException,
KeywordNotFoundException)
from PyQt4 import QtCore, QtGui, QtWebKit, QtXml
from is_keyword_io import ISKeywordIO
diff --git a/gui/is_options_dialog_base.py b/gui/is_options_dialog_base.py
index <HASH>..<HASH> 100644
--- a/gui/is_options_dialog_base.py
+++ b/gui/is_options_dialog_base.py
@@ -2,7 +2,7 @@
# Form implementation generated from reading ui file 'is_options_dialog_base.ui'
#
-# Created: Mon Apr 23 21:51:32 2012
+# Created: Mon Apr 23 22:33:47 2012
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
diff --git a/gui/is_safe_interface.py b/gui/is_safe_interface.py
index <HASH>..<HASH> 100644
--- a/gui/is_safe_interface.py
+++ b/gui/is_safe_interface.py
@@ -296,12 +296,17 @@ def writeKeywordsToFile(theFilename, theKeywords):
Args:
* thePath - str representing path to layer that must be written.
+ If the file does not end in .keywords, its extension will be
+ stripped off and the basename + .keywords will be used as the file.
* theKeywords - a dictionary of keywords to be written
Returns:
A safe readSafeLayer object is returned.
Raises:
None
"""
+ myBasename, myExtension = os.path.splitext(theFilename)
+ if 'keywords' not in myExtension:
+ theFilename = myBasename + '.keywords'
safe_write_keywords(theKeywords, theFilename)
diff --git a/gui/is_utilities.py b/gui/is_utilities.py
index <HASH>..<HASH> 100644
--- a/gui/is_utilities.py
+++ b/gui/is_utilities.py
@@ -343,6 +343,7 @@ def htmlFooter():
myFile.close()
return myFooter
+
def qgisVersion():
"""Get the version of QGIS
Args:
@@ -358,4 +359,4 @@ def qgisVersion():
except:
myVersion = unicode(QGis.qgisVersion)[0]
myVersion = int(myVersion)
- return myVersion
\ No newline at end of file
+ return myVersion
diff --git a/gui/test_is_keyword_io.py b/gui/test_is_keyword_io.py
index <HASH>..<HASH> 100644
--- a/gui/test_is_keyword_io.py
+++ b/gui/test_is_keyword_io.py
@@ -41,7 +41,7 @@ class ISKeywordIOTest(unittest.TestCase):
self.expectedSqliteKeywords = {'category': 'exposure',
'datatype': 'OSM',
'subcategory': 'building'}
- self.expectedVectorKeywords = {'category': 'exposure',
+ self.expectedVectorKeywords = {'category': 'exposure',
'datatype': 'itb',
'subcategory': 'building'}
self.expectedRasterKeywords = {'category': 'hazard',
@@ -124,8 +124,8 @@ class ISKeywordIOTest(unittest.TestCase):
assert myKeywords == myExpectedKeywords, myMessage
def test_readVectorFileKeywords(self):
- """Can we read vector file keywords with the generic readKeywords method
- """
+ """Can we read vector file keywords with the generic readKeywords
+ method """
myKeywords = self.keywordIO.readKeywords(self.fileVectorLayer)
myExpectedKeywords = self.expectedVectorKeywords
mySource = self.fileVectorLayer.source()
|
Fixed bug when writing file based keywords - ensure keywords extension is set on destination file
|
inasafe_inasafe
|
train
|
f9cd0666ee38d763574d9b8c56e78de1f2995fe0
|
diff --git a/numexpr/utils.py b/numexpr/utils.py
index <HASH>..<HASH> 100644
--- a/numexpr/utils.py
+++ b/numexpr/utils.py
@@ -93,8 +93,7 @@ def get_vml_num_threads():
"""
if use_vml:
return _get_vml_num_threads()
- return 0
-
+ return None
def set_num_threads(nthreads):
"""
|
Revert `get_vml_num_threads` to return `None` when not installed
|
pydata_numexpr
|
train
|
f17c950605c47d2552a0782d46703a5609d48ef7
|
diff --git a/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/Http2ClientChannel.java b/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/Http2ClientChannel.java
index <HASH>..<HASH> 100644
--- a/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/Http2ClientChannel.java
+++ b/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/Http2ClientChannel.java
@@ -267,6 +267,7 @@ public class Http2ClientChannel {
public void onStreamClosed(Http2Stream stream) {
// Channel is no longer exhausted, so we can return it back to the pool
+ http2ClientChannel.removeInFlightMessage(stream.id());
activeStreams.decrementAndGet();
http2ClientChannel.getDataEventListeners().
forEach(dataEventListener -> dataEventListener.onStreamClose(stream.id()));
diff --git a/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/TimeoutHandler.java b/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/TimeoutHandler.java
index <HASH>..<HASH> 100644
--- a/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/TimeoutHandler.java
+++ b/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/sender/http2/TimeoutHandler.java
@@ -170,6 +170,7 @@ public class TimeoutHandler implements Http2DataEventListener {
Constants.IDLE_TIMEOUT_TRIGGERED_BEFORE_WRITING_OUTBOUND_RESPONSE,
HttpResponseStatus.GATEWAY_TIMEOUT.code()));
}
+ http2ClientChannel.removeInFlightMessage(streamId);
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
timerTasks.put(streamId, schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS));
|
Fix possible OOM situation with burst of request timeouts
|
wso2_transport-http
|
train
|
9ec28cd9abb7ac5980c9c2d4a99c25dfcfb54bc7
|
diff --git a/jpyutil.py b/jpyutil.py
index <HASH>..<HASH> 100644
--- a/jpyutil.py
+++ b/jpyutil.py
@@ -31,6 +31,12 @@ import ctypes.util
import logging
+__author__ = "Norman Fomferra, Brockmann Consult GmbH"
+__copyright__ = "Copyright 2015-2017 Brockmann Consult GmbH"
+__license__ = "Apache 2.0"
+__version__ = "0.9.0dev"
+
+
# Uncomment for debugging
# logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,6 +1,6 @@
# !/usr/bin/env python3
-# Copyright 2015 Brockmann Consult GmbH
+# Copyright 2014-2017 Brockmann Consult GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,10 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-__author__ = "Norman Fomferra, Brockmann Consult GmbH"
-__copyright__ = "Copyright 2015-2017 Brockmann Consult GmbH"
-__license__ = "Apache 2.0"
-__version__ = "0.9.0dev"
import sys
import os
@@ -40,6 +36,11 @@ src_test_py_dir = os.path.join(base_dir, 'src', 'test', 'python')
import jpyutil
+__author__ = jpyutil.__author__
+__copyright__ = jpyutil.__copyright__
+__license__ = jpyutil.__license__
+__version__ = jpyutil.__version__
+
print('Using ' + jpyutil.__file__)
do_maven = False
|
getting version from jpyutil
|
bcdev_jpy
|
train
|
a0ed12248c263a829dac8d3207b584d06c50edab
|
diff --git a/lib/hipchat_searcher/result.rb b/lib/hipchat_searcher/result.rb
index <HASH>..<HASH> 100644
--- a/lib/hipchat_searcher/result.rb
+++ b/lib/hipchat_searcher/result.rb
@@ -4,17 +4,19 @@ class HipchatSearcher
class Result
class InvalidResponse < StandardError; end
+ attr_accessor :room
+
def initialize(response)
@response = response
valid!
end
def room_list
- @response['items'].map { |item| item['name'] }
+ @response['items'].map {|i| i['name'] }
end
- def message_list
- JSON.parse(@response)['items'].map{|i| i['message']}
+ def messages
+ @messages = JSON.parse(@response)['items'].map {|i| i['message']}
end
def valid!
diff --git a/spec/lib/hipchat_searcher/result_spec.rb b/spec/lib/hipchat_searcher/result_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/hipchat_searcher/result_spec.rb
+++ b/spec/lib/hipchat_searcher/result_spec.rb
@@ -74,15 +74,15 @@ describe HipchatSearcher::Result do
end
end
- describe '#message_list' do
- subject { result(response).message_list }
+ describe '#messages' do
+ subject { result(response).messages }
let(:response) { File.read(path) }
let(:path) { File.join('spec', 'data', 'message_list.json') }
it { should be_instance_of Array }
- it 'should be return messages' do
+ it 'should return messages' do
should == ["yareyare daze", "rerorero", "a... arinomama ima okotta koto wo hanasu ze"]
end
end
|
* #message_list → #messages
* Define accessor :room
|
mgi166_hipchat_searcher
|
train
|
ba0e2e0b367a7b81f0c3a018a73fd8cc97592c06
|
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultScheduler.java
@@ -182,7 +182,8 @@ public class DefaultScheduler extends SchedulerBase implements SchedulerOperatio
}
}
- private void handleTaskFailure(final ExecutionVertexID executionVertexId, final Throwable error) {
+ private void handleTaskFailure(final ExecutionVertexID executionVertexId, @Nullable final Throwable error) {
+ setGlobalFailureCause(error);
final FailureHandlingResult failureHandlingResult = executionFailureHandler.getFailureHandlingResult(executionVertexId, error);
maybeRestartTasks(failureHandlingResult);
}
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
+++ b/flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/SchedulerBase.java
@@ -94,6 +94,8 @@ import org.apache.flink.util.function.FunctionUtils;
import org.slf4j.Logger;
+import javax.annotation.Nullable;
+
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;
@@ -348,8 +350,10 @@ public abstract class SchedulerBase implements SchedulerNG {
.transitionState(ExecutionState.SCHEDULED));
}
- protected void setGlobalFailureCause(final Throwable cause) {
- getExecutionGraph().initFailureCause(cause);
+ protected void setGlobalFailureCause(@Nullable final Throwable cause) {
+ if (cause != null) {
+ getExecutionGraph().initFailureCause(cause);
+ }
}
protected ComponentMainThreadExecutor getMainThreadExecutor() {
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultSchedulerTest.java
@@ -34,6 +34,7 @@ import org.apache.flink.runtime.concurrent.ManuallyTriggeredScheduledExecutor;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.executiongraph.AccessExecutionJobVertex;
import org.apache.flink.runtime.executiongraph.ArchivedExecutionVertex;
+import org.apache.flink.runtime.executiongraph.ErrorInfo;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.failover.flip1.RestartPipelinedRegionFailoverStrategy;
import org.apache.flink.runtime.executiongraph.failover.flip1.TestRestartBackoffTimeStrategy;
@@ -91,10 +92,12 @@ import static org.apache.flink.util.ExceptionUtils.findThrowable;
import static org.apache.flink.util.ExceptionUtils.findThrowableWithMessage;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
+import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
@@ -607,6 +610,23 @@ public class DefaultSchedulerTest extends TestLogger {
assertTrue(executionVertexVersioner.isModified(executionVertexVersion));
}
+ @Test
+ public void failureInfoIsSetAfterTaskFailure() {
+ final JobGraph jobGraph = singleNonParallelJobVertexJobGraph();
+ final JobID jobId = jobGraph.getJobID();
+ final DefaultScheduler scheduler = createSchedulerAndStartScheduling(jobGraph);
+
+ final ArchivedExecutionVertex onlyExecutionVertex = Iterables.getOnlyElement(scheduler.requestJob().getAllExecutionVertices());
+ final ExecutionAttemptID attemptId = onlyExecutionVertex.getCurrentExecutionAttempt().getAttemptId();
+
+ final String exceptionMessage = "expected exception";
+ scheduler.updateTaskExecutionState(new TaskExecutionState(jobId, attemptId, ExecutionState.FAILED, new RuntimeException(exceptionMessage)));
+
+ final ErrorInfo failureInfo = scheduler.requestJob().getFailureInfo();
+ assertThat(failureInfo, is(notNullValue()));
+ assertThat(failureInfo.getExceptionAsString(), containsString(exceptionMessage));
+ }
+
private static JobVertex createVertexWithAllInputConstraints(String name, int parallelism) {
final JobVertex v = new JobVertex(name);
v.setParallelism(parallelism);
|
[FLINK-<I>][runtime] Fix that the root exception is not shown in Web UI
|
apache_flink
|
train
|
65c58c1ecb8e3d08d928381fa6a84e6e4f71ab8a
|
diff --git a/cdpybio/general.py b/cdpybio/general.py
index <HASH>..<HASH> 100644
--- a/cdpybio/general.py
+++ b/cdpybio/general.py
@@ -2,6 +2,24 @@ import re
R_REGEX = re.compile('(.*):(.*)-(.*)')
R_REGEX_STRAND = re.compile('(.*):(.*)-(.*):(.*)')
+def transform_standard_normal(df):
+ """Transform a series or the rows of a dataframe to the values of a standard
+ normal based on rank."""
+ import pandas as pd
+ import scipy.stats as stats
+ if type(df) == pd.core.frame.DataFrame:
+ gc_ranks = df.rank(axis=1)
+ gc_ranks = gc_ranks / (gc_ranks.shape[1] + 1)
+ std_norm = stats.norm.ppf(gc_ranks)
+ std_norm = pd.DataFrame(std_norm, index=gc_ranks.index,
+ columns=gc_ranks.columns)
+ elif type(df) == pd.core.series.Series:
+ gc_ranks = df.rank()
+ gc_ranks = gc_ranks / (gc_ranks.shape[0] + 1)
+ std_norm = stats.norm.ppf(gc_ranks)
+ std_norm = pd.Series(std_norm, index=df.index)
+ return std_norm
+
def read_gzipped_text_url(url):
"""Read a gzipped text file from a URL and return
contents as a string."""
|
Added std norm transformation
|
cdeboever3_cdpybio
|
train
|
e3f9abce5483021ac6cb52ff90d5c524d0b473a2
|
diff --git a/saltpylint/strings.py b/saltpylint/strings.py
index <HASH>..<HASH> 100644
--- a/saltpylint/strings.py
+++ b/saltpylint/strings.py
@@ -156,12 +156,13 @@ class StringCurlyBracesFormatIndexChecker(BaseChecker):
if BAD_FORMATTING_SLOT.findall(inferred.value):
if self.config.un_indexed_curly_braces_always_error or \
sys.version_info[:2] < (2, 7):
- msgid = 'E1320'
- else:
- msgid = 'W1320'
- self.add_message(
- msgid, node=inferred, args=inferred.value
- )
+ self.add_message(
+ 'E1320', node=inferred, args=inferred.value
+ )
+ elif six.PY2:
+ self.add_message(
+ 'W1320', node=inferred, args=inferred.value
+ )
try:
# Walk back up until no parents are found and look for a
|
Don't show warning under Py3
|
saltstack_salt-pylint
|
train
|
f2e095f0e0cfc63b57ac589f04895acdf4de9971
|
diff --git a/lib/filters.php b/lib/filters.php
index <HASH>..<HASH> 100644
--- a/lib/filters.php
+++ b/lib/filters.php
@@ -122,19 +122,6 @@ MangoFilters::$set['wp_filter'] = function($data, string $filter) {
return apply_filters($filter, $data);
};
-MangoFilters::$set['number'] = function($number, $decimal = 2) {
- if(fmod($number, 1) == 0) {
- $decimal = 0;
- }
- $sep = '.';
- $formatted = number_format($number, $decimal, $sep, ",");
- if($decimal) {
- $formatted = Strings::replace($formatted, '~\.?0$~');
- }
-
- return $formatted;
-};
-
function nbsp($str) {
$str = trim($str);
return Nette\Utils\Strings::replace($str, '~[ ]~', "\xc2\xa0");
|
remove number filter which already exists in latte
|
manGoweb_MangoPressTemplating
|
train
|
c986f92dc5d8ef9c8e95e242633052c3e1fff979
|
diff --git a/paramiko/sftp_file.py b/paramiko/sftp_file.py
index <HASH>..<HASH> 100644
--- a/paramiko/sftp_file.py
+++ b/paramiko/sftp_file.py
@@ -124,8 +124,8 @@ class SFTPFile (BufferedFile):
if whence == self.SEEK_SET:
self._realpos = self._pos = offset
elif whence == self.SEEK_CUR:
- self._realpos += offset
self._pos += offset
+ self._realpos = self._pos
else:
self._realpos = self._pos = self._get_size() + offset
self._rbuffer = ''
|
[project @ Arch-1:<EMAIL><I>-master-shake%paramiko--dev--1--patch-<I>]
i think seek_cur had a bug here
|
paramiko_paramiko
|
train
|
3c5d31d1b91d9e9db9ffbddfa6c2259a048b3a3e
|
diff --git a/unyt/array.py b/unyt/array.py
index <HASH>..<HASH> 100644
--- a/unyt/array.py
+++ b/unyt/array.py
@@ -2345,7 +2345,7 @@ def allclose_units(actual, desired, rtol=1e-7, atol=0, **kwargs):
try:
at = at.in_units(act.units)
- except UnitOperationError:
+ except (UnitOperationError, UnitConversionError):
return False
# units have been validated, so we strip units before calling numpy
diff --git a/unyt/tests/test_unyt_testing.py b/unyt/tests/test_unyt_testing.py
index <HASH>..<HASH> 100644
--- a/unyt/tests/test_unyt_testing.py
+++ b/unyt/tests/test_unyt_testing.py
@@ -15,7 +15,6 @@ import pytest
from unyt.array import unyt_array, unyt_quantity
from unyt.testing import assert_allclose_units
-from unyt.exceptions import UnitConversionError
def test_equality():
@@ -45,9 +44,8 @@ def test_runtime_error():
assert_allclose_units(a1, a2, rtol=unyt_quantity(1e-7, "cm"))
-def test_operation_error():
+def test_atol_conversion_error():
a1 = unyt_array([1.0, 2.0, 3.0], "cm")
a2 = unyt_array([1.0, 2.0, 3.0], "cm")
- with pytest.raises(UnitConversionError):
+ with pytest.raises(AssertionError):
assert_allclose_units(a1, a2, atol=unyt_quantity(0.0, "kg"))
-
|
Increase test cov of allclose_units to <I>%
|
yt-project_unyt
|
train
|
f2eb6152a1356e34117feca11cb3a5d36f0a9ba8
|
diff --git a/fixtext.py b/fixtext.py
index <HASH>..<HASH> 100644
--- a/fixtext.py
+++ b/fixtext.py
@@ -14,7 +14,8 @@ else:
def fixtext(text, normalization='NFKC'):
"""
- Given any basestring as input, make its representation consistent:
+ Given any basestring as input, make its representation consistent and
+ possibly less broken:
- Ensure that it is a Unicode string, converting from UTF-8 if
necessary.
@@ -40,13 +41,33 @@ def fixtext(text, normalization='NFKC'):
You may change the `normalization` argument to apply a different kind of
Unicode normalization, such as NFC or NFKD, or set it to None to skip this
step.
+
+ >>> print(fixtext('ünicode'))
+ ünicode
+
+ >>> print(fixtext('Broken text… it’s flubberific!'))
+ Broken text... it's flubberific!
+
+ >>> print(fixtext('HTML entities <3'))
+ HTML entities <3
+
+ >>> print(fixtext('<em>HTML entities <3</em>'))
+ <em>HTML entities <3</em>
+
+ >>> print(fixtext('\001\033[36;44mI’m blue, da ba dee da ba '
+ ... 'doo…\033[0m'))
+ I'm blue, da ba dee da ba doo...
+
+ >>> len(fixtext(''))
+ 0
+
"""
if isinstance(text, bytes):
text = text.decode('utf-8')
text = remove_terminal_escapes(text)
- text = fix_bad_encoding(text)
if '<' not in text or '>' not in text:
text = unescape_html(text)
+ text = fix_bad_encoding(text)
text = text.translate(CONTROL_CHARS)
if normalization is not None:
text = unicodedata.normalize(normalization, text)
|
change order of operations, add doctests to top level
|
LuminosoInsight_python-ftfy
|
train
|
367cd92ad8a9b039b882fc44e4acf7a2f70247a6
|
diff --git a/lib/network_interface.js b/lib/network_interface.js
index <HASH>..<HASH> 100644
--- a/lib/network_interface.js
+++ b/lib/network_interface.js
@@ -59,7 +59,6 @@ exports.loopbackInterface = function loopbackInterface() {
}
}
-
exports.loopbackName = function loopbackName() {
var interfaces = os.networkInterfaces();
for (var name in interfaces) {
|
[formatting] just removed an empty line
|
agnat_node_mdns
|
train
|
c9038c821d52fad86cd80c2c2f8923033a8520b6
|
diff --git a/auth.class.php b/auth.class.php
index <HASH>..<HASH> 100755
--- a/auth.class.php
+++ b/auth.class.php
@@ -174,7 +174,7 @@ class Auth
if(strlen($key) !== 20) {
$this->addAttempt();
- $return['message'] = $this->lang["key_invalid"];
+ $return['message'] = $this->lang["activationkey_invalid"];
return $return;
}
@@ -235,7 +235,7 @@ class Auth
$return['message'] = $this->lang["email_incorrect"];
return $return;
}
-
+
$addRequest = $this->addRequest($query->fetch(PDO::FETCH_ASSOC)['id'], $email, "reset");
if ($addRequest['error'] == 1) {
$this->addAttempt();
@@ -668,7 +668,7 @@ class Auth
if($type == "activation") {
$mail->Subject = sprintf($this->lang['email_activation_subject'], $this->config->site_name);
$mail->Body = sprintf($this->lang['email_activation_body'], $this->config->site_url, $this->config->site_activation_page, $key);
- $mail->AltBody = sprintf($this->lang['email_activation_altbody'], $this->config->site_url, $this->config->site_activation_page, $key);
+ $mail->AltBody = sprintf($this->lang['email_activation_altbody'], $this->config->site_url, $this->config->site_activation_page, $key);
} else {
$mail->Subject = sprintf($this->lang['email_reset_subject'], $this->config->site_name);
$mail->Body = sprintf($this->lang['email_reset_body'], $this->config->site_url, $this->config->site_password_reset_page, $key);
@@ -812,7 +812,7 @@ class Auth
}
if(strlen($key) != 20) {
- $return['message'] = $this->lang["key_invalid"];
+ $return['message'] = $this->lang["resetkey_invalid"];
return $return;
}
|
Fixed undefined index error "key_invalid" (Issue #<I> by @human-inhabitant)
|
PHPAuth_PHPAuth
|
train
|
12521b23e826d47e49485ffd641512d1c257c704
|
diff --git a/go/chat/giphy/search.go b/go/chat/giphy/search.go
index <HASH>..<HASH> 100644
--- a/go/chat/giphy/search.go
+++ b/go/chat/giphy/search.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
+ "errors"
"fmt"
"io"
"io/ioutil"
@@ -24,6 +25,22 @@ const MediaHost = "media.giphy.com"
const Host = "giphy.com"
const giphyProxy = "https://giphy-proxy.core.keybaseapi.com"
+func getPreferredPreview(mctx libkb.MetaContext, img gifImage) (string, bool, error) {
+ if len(img.MP4) == 0 && len(img.URL) == 0 {
+ return "", false, errors.New("no preview")
+ }
+ if len(img.MP4) == 0 {
+ return img.URL, false, nil
+ }
+ if len(img.URL) == 0 {
+ return img.MP4, true, nil
+ }
+ if mctx.G().GetEnv().GetAppType() == libkb.MobileAppType {
+ return img.URL, false, nil
+ }
+ return img.MP4, true, nil
+}
+
func formatResponse(mctx libkb.MetaContext, response giphyResponse, srv types.AttachmentURLSrv) (res []chat1.GiphySearchResult) {
for _, obj := range response.Data {
for typ, img := range obj.Images {
@@ -35,7 +52,8 @@ func formatResponse(mctx libkb.MetaContext, response giphyResponse, srv types.At
if typ != "fixed_height" {
continue
}
- if len(img.MP4) == 0 {
+ previewURL, isVideo, err := getPreferredPreview(mctx, img)
+ if err != nil {
continue
}
height, err := strconv.Atoi(img.Height)
@@ -48,10 +66,10 @@ func formatResponse(mctx libkb.MetaContext, response giphyResponse, srv types.At
}
res = append(res, chat1.GiphySearchResult{
TargetUrl: obj.URL,
- PreviewUrl: srv.GetGiphyURL(mctx.Ctx(), img.MP4),
+ PreviewUrl: srv.GetGiphyURL(mctx.Ctx(), previewURL),
PreviewHeight: height,
PreviewWidth: width,
- PreviewIsVideo: true,
+ PreviewIsVideo: isVideo,
})
}
}
diff --git a/go/chat/giphy/types.go b/go/chat/giphy/types.go
index <HASH>..<HASH> 100644
--- a/go/chat/giphy/types.go
+++ b/go/chat/giphy/types.go
@@ -1,6 +1,7 @@
package giphy
type gifImage struct {
+ URL string
MP4 string
Width string
Height string
|
use gifs for search on mobile
|
keybase_client
|
train
|
ab44967bbb72228cb5c92a0159d584e796192087
|
diff --git a/packages/cozy-client/src/CozyClient.spec.js b/packages/cozy-client/src/CozyClient.spec.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/CozyClient.spec.js
+++ b/packages/cozy-client/src/CozyClient.spec.js
@@ -993,6 +993,16 @@ describe('CozyClient', () => {
)
})
+ it('should dispatch a INIT_QUERY action if no skip and no bookmark', async () => {
+ getQueryFromState.mockReturnValueOnce({
+ fetchStatus: 'loaded'
+ })
+ await client.query(query, { as: 'allTodos' })
+ expect(client.store.dispatch.mock.calls[0][0]).toEqual(
+ initQuery('allTodos', { doctype: 'io.cozy.todos' })
+ )
+ })
+
it('should dispatch a RECEIVE_QUERY_RESULT action if query has skip', async () => {
requestHandler.mockReturnValueOnce(Promise.resolve(fakeResponse))
getQueryFromState.mockReturnValueOnce({
|
test: Add test if no skip and no bookmark
|
cozy_cozy-client
|
train
|
afc3944a4a2b04afe214143eb6aa07feadc5734a
|
diff --git a/lib/liquid/context.rb b/lib/liquid/context.rb
index <HASH>..<HASH> 100644
--- a/lib/liquid/context.rb
+++ b/lib/liquid/context.rb
@@ -168,6 +168,7 @@ module Liquid
# Fetches an object starting at the local scope and then moving up the hierachy
def find_variable(key)
scope = @scopes.find { |s| s.has_key?(key) }
+ variable = nil
if scope.nil?
@environments.each do |e|
|
Fix assignment with no effect outside of iterator
|
Shopify_liquid
|
train
|
982873cf3d2eb026fb64404b86065fa98baa1a40
|
diff --git a/src/parser/parser_test.go b/src/parser/parser_test.go
index <HASH>..<HASH> 100644
--- a/src/parser/parser_test.go
+++ b/src/parser/parser_test.go
@@ -178,6 +178,14 @@ func (self *QueryParserSuite) TestParseDeleteQuery(c *C) {
c.Assert(q.GetEndTime(), Equals, endTime)
}
+func (self *QueryParserSuite) TestInvalidWhereClause(c *C) {
+ _, err := ParseQuery("delete from foo where 1;")
+ c.Assert(err, NotNil)
+
+ _, err = ParseQuery("select * from foo where is_uppercase(name);")
+ c.Assert(err, IsNil)
+}
+
func (self *QueryParserSuite) TestParseWithUnderscore(c *C) {
queryString := "select _value, time, sequence_number from foo"
query, err := ParseSelectQuery(queryString)
diff --git a/src/parser/query_api.go b/src/parser/query_api.go
index <HASH>..<HASH> 100644
--- a/src/parser/query_api.go
+++ b/src/parser/query_api.go
@@ -375,6 +375,15 @@ func getTime(condition *WhereCondition, isParsingStartTime bool) (*WhereConditio
}
if expr, ok := condition.GetBoolExpression(); ok {
+ switch expr.Type {
+ case ValueDuration, ValueFloat, ValueInt, ValueString, ValueWildcard:
+ return nil, ZERO_TIME, fmt.Errorf("Invalid where expression: %v", expr)
+ }
+
+ if expr.Type == ValueFunctionCall {
+ return condition, ZERO_TIME, nil
+ }
+
leftValue := expr.Elems[0]
isTimeOnLeft := leftValue.Type != ValueExpression && leftValue.Type != ValueFunctionCall
rightValue := expr.Elems[1]
|
Don't panic on invalid where conditions, e.g. where 1
|
influxdata_influxdb
|
train
|
0a5f095388edff36f34d0ff9a79aba5b11657090
|
diff --git a/test/active_resource_response_test.rb b/test/active_resource_response_test.rb
index <HASH>..<HASH> 100644
--- a/test/active_resource_response_test.rb
+++ b/test/active_resource_response_test.rb
@@ -27,6 +27,7 @@ class ActiveResourceResponseTest < Test::Unit::TestCase
mock.get "/regions.json", {}, [@region].to_json, 200, {"X-total"=>'1'}
mock.get "/regions/1.json", {}, @region.to_json, 200, {"X-total"=>'1'}
mock.get "/regions/population.json", {}, {:count => 45000000}.to_json, 200, {"X-total"=>'1'}
+ mock.get "/regions/cities.json", {}, [@city].to_json, 200, {"X-total"=>'1'}
mock.get "/countries/1.json", {}, @country.to_json, 200, {"X-total"=>'1', 'Set-Cookie'=>['path=/; expires=Tue, 20-Jan-2015 15:03:14 GMT, foo=bar, bar=foo']}
mock.get "/countries/1/population.json", {}, {:count => 45000000}.to_json, 200, {"X-total"=>'1'}
mock.post "/countries.json" , {}, @country.to_json, 422, {"X-total"=>'1'}
@@ -85,8 +86,9 @@ class ActiveResourceResponseTest < Test::Unit::TestCase
assert cities.respond_to?(:http_response)
assert_equal cities.http_response['X-total'].to_i, 1
-
-
+ cities = Region.get("cities")
+ assert cities.respond_to?(:http_response)
+ assert_equal cities.http_response['X-total'].to_i, 1
end
|
test for class custom get method was added
|
Fivell_activeresource-response
|
train
|
44b66a352345f1bca47645a2fc7da31109eb2fd2
|
diff --git a/lib/class-wp-json-posts.php b/lib/class-wp-json-posts.php
index <HASH>..<HASH> 100644
--- a/lib/class-wp-json-posts.php
+++ b/lib/class-wp-json-posts.php
@@ -575,7 +575,7 @@ class WP_JSON_Posts {
* @access protected
*
* @param array $post The unprepared post data
- * @param string $context The context for the prepared post. (view|view-revision|edit)
+ * @param string $context The context for the prepared post. (view|view-revision|edit|embed)
* @return array The prepared post data
*/
protected function prepare_post( $post, $context = 'view' ) {
@@ -649,7 +649,7 @@ class WP_JSON_Posts {
// This gives post + post-extended + meta for the main post,
// post + meta for the parent and just meta for the grandparent
$parent = get_post( $post['post_parent'], ARRAY_A );
- $post_fields['parent'] = $this->prepare_post( $parent, 'parent' );
+ $post_fields['parent'] = $this->prepare_post( $parent, 'embed' );
}
// Merge requested $post_fields fields into $_post
|
Change post parent preparation context to embed
This matches the context used in Users.
|
WP-API_WP-API
|
train
|
83f096c784c4f7070e607919cbb8d4303be39312
|
diff --git a/server/webapp/WEB-INF/rails.new/spec/presenters/api_v4/plugin/plugin_info_representer_spec.rb b/server/webapp/WEB-INF/rails.new/spec/presenters/api_v4/plugin/plugin_info_representer_spec.rb
index <HASH>..<HASH> 100644
--- a/server/webapp/WEB-INF/rails.new/spec/presenters/api_v4/plugin/plugin_info_representer_spec.rb
+++ b/server/webapp/WEB-INF/rails.new/spec/presenters/api_v4/plugin/plugin_info_representer_spec.rb
@@ -308,7 +308,7 @@ describe ApiV4::Plugin::PluginInfoRepresenter do
plugin_view = com.thoughtworks.go.plugin.domain.common.PluginView.new('plugin_view_template')
plugin_metadata = com.thoughtworks.go.plugin.domain.common.Metadata.new(true, false)
plugin_settings = com.thoughtworks.go.plugin.domain.common.PluggableInstanceSettings.new([com.thoughtworks.go.plugin.domain.common.PluginConfiguration.new('username', plugin_metadata)], plugin_view)
- capabilities = com.thoughtworks.go.plugin.domain.analytics.Capabilities.new(true)
+ capabilities = com.thoughtworks.go.plugin.domain.analytics.Capabilities.new(true, true)
plugin_info = com.thoughtworks.go.plugin.domain.analytics.AnalyticsPluginInfo.new(descriptor, image, capabilities, plugin_settings)
actual_json = ApiV4::Plugin::PluginInfoRepresenter.new(plugin_info).to_hash(url_builder: UrlBuilder.new)
|
fix plugin_info_representer_spec
|
gocd_gocd
|
train
|
b33933f2e227e1a03eb8bb2567d9d1264147576f
|
diff --git a/recordlinkage/base.py b/recordlinkage/base.py
index <HASH>..<HASH> 100644
--- a/recordlinkage/base.py
+++ b/recordlinkage/base.py
@@ -648,7 +648,7 @@ class BaseCompare(object):
return features
- def union(self, objs, index=None):
+ def union(self, objs, index=None, column_i=0):
"""Make a union of the features.
The term 'union' is based on the terminology of scikit-learn.
@@ -662,32 +662,48 @@ class BaseCompare(object):
# result is tuple of results
if isinstance(feat, tuple):
if label is None:
- label = [None for _ in len(feat)]
+ label = [None] * len(feat)
- partial_result = self.union(zip(feat, label))
+ partial_result = self.union(zip(feat, label), column_i=column_i)
feat_conc.append(partial_result)
+ column_i = column_i + partial_result.shape[1]
# result is pandas.Series.
elif isinstance(feat, pandas.Series):
feat.reset_index(drop=True, inplace=True)
+ if label is None:
+ label = column_i
feat.rename(label, inplace=True)
feat_conc.append(feat)
+ column_i = column_i + 1
# result is pandas.DataFrame
elif isinstance(feat, pandas.DataFrame):
feat.reset_index(drop=True, inplace=True)
+ if label is None:
+ label = np.arange(column_i, column_i + feat.shape[1])
feat.columns = label
feat_conc.append(feat)
+ column_i = column_i + feat.shape[1]
# result is numpy 1d array
elif is_numpy_like(feat) and len(feat.shape) == 1:
+ if label is None:
+ label = column_i
f = pandas.Series(feat, name=label, copy=False)
+
feat_conc.append(f)
+ column_i = column_i + 1
# result is numpy 2d array
elif is_numpy_like(feat) and len(feat.shape) == 2:
- f = pandas.DataFrame(feat, columns=label, copy=False)
- feat_conc.append(f)
+ if label is None:
+ label = np.arange(column_i, column_i + feat.shape[1])
+ feat_df = pandas.DataFrame(feat, columns=label, copy=False)
+ if label is None:
+ feat_df.columns = [None for _ in range(feat_df.shape[1])]
+ feat_conc.append(feat_df)
+ column_i = column_i + feat.shape[1]
# other results are not (yet) supported
else:
@@ -699,10 +715,6 @@ class BaseCompare(object):
if index is not None:
result.set_index(index, inplace=True)
- # replace missing columns names by numbers
- result.columns = [col if pandas.notnull(col) else j
- for j, col in enumerate(result.columns.tolist())]
-
return result
def compute(self, pairs, x, x_link=None):
diff --git a/tests/test_compare.py b/tests/test_compare.py
index <HASH>..<HASH> 100644
--- a/tests/test_compare.py
+++ b/tests/test_compare.py
@@ -169,6 +169,28 @@ class TestCompareApi(TestData):
assert "my_feature_label" in result.columns.tolist()
+ def test_multilabel_none_linking(self):
+ def ones_np_multi(s1, s2):
+ return np.ones(len(s1)), np.ones((len(s1), 3))
+
+ def ones_pd_multi(s1, s2):
+ return (Series(np.ones(len(s1))), DataFrame(np.ones((len(s1), 3))))
+
+ comp = recordlinkage.Compare()
+ comp.string('given_name', 'given_name', method='jaro')
+ comp.compare_vectorized(
+ ones_np_multi,
+ 'given_name',
+ 'given_name')
+ comp.compare_vectorized(
+ ones_pd_multi,
+ 'given_name',
+ 'given_name')
+ result = comp.compute(self.index_AB, self.A, self.B)
+
+ assert [0, 1, 2, 3, 4, 5, 6, 7, 8] == \
+ result.columns.tolist()
+
def test_multilabel_linking(self):
def ones_np_multi(s1, s2):
return np.ones(len(s1)), np.ones((len(s1), 3))
@@ -217,6 +239,28 @@ class TestCompareApi(TestData):
assert [0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] == \
result.columns.tolist()
+ def test_multilabel_none_dedup(self):
+ def ones_np_multi(s1, s2):
+ return np.ones(len(s1)), np.ones((len(s1), 3))
+
+ def ones_pd_multi(s1, s2):
+ return (Series(np.ones(len(s1))), DataFrame(np.ones((len(s1), 3))))
+
+ comp = recordlinkage.Compare()
+ comp.string('given_name', 'given_name', method='jaro')
+ comp.compare_vectorized(
+ ones_np_multi,
+ 'given_name',
+ 'given_name')
+ comp.compare_vectorized(
+ ones_pd_multi,
+ 'given_name',
+ 'given_name')
+ result = comp.compute(self.index_AB, self.A)
+
+ assert [0, 1, 2, 3, 4, 5, 6, 7, 8] == \
+ result.columns.tolist()
+
def test_multilabel_error_dedup(self):
def ones(s1, s2):
return np.ones((len(s1), 2))
|
Fix bug with None labels on multicolumn output
Add tests
|
J535D165_recordlinkage
|
train
|
c7214ffba57dee66e5c38024788a65f591bf0b6a
|
diff --git a/ndbench-dynamodb-plugins/src/main/java/com/netflix/ndbench/plugin/dynamodb/operations/dynamodb/dataplane/DynamoDBWriteTransaction.java b/ndbench-dynamodb-plugins/src/main/java/com/netflix/ndbench/plugin/dynamodb/operations/dynamodb/dataplane/DynamoDBWriteTransaction.java
index <HASH>..<HASH> 100644
--- a/ndbench-dynamodb-plugins/src/main/java/com/netflix/ndbench/plugin/dynamodb/operations/dynamodb/dataplane/DynamoDBWriteTransaction.java
+++ b/ndbench-dynamodb-plugins/src/main/java/com/netflix/ndbench/plugin/dynamodb/operations/dynamodb/dataplane/DynamoDBWriteTransaction.java
@@ -18,6 +18,7 @@ package com.netflix.ndbench.plugin.dynamodb.operations.dynamodb.dataplane;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
+import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -25,6 +26,7 @@ import org.slf4j.LoggerFactory;
import com.amazonaws.services.cloudwatch.model.ResourceNotFoundException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
+import com.amazonaws.services.dynamodbv2.model.CancellationReason;
import com.amazonaws.services.dynamodbv2.model.ConsumedCapacity;
import com.amazonaws.services.dynamodbv2.model.InternalServerErrorException;
import com.amazonaws.services.dynamodbv2.model.Put;
@@ -97,17 +99,31 @@ public class DynamoDBWriteTransaction extends AbstractDynamoDBDataPlaneOperation
}
catch (ResourceNotFoundException rnf)
{
- logger.error("One of the table involved in the transaction is not found" + rnf.getMessage());
+ logger.error("One of the table involved in the transaction is not found" + rnf);
+ throw rnf;
}
catch (InternalServerErrorException ise)
{
- logger.error("Internal Server Error" + ise.getMessage());
+ logger.error("Internal Server Error" + ise);
+ throw ise;
}
catch (TransactionCanceledException tce)
{
- logger.warn("Transaction Canceled " + tce.getMessage());
+ StringBuilder sb = new StringBuilder();
+ sb.append(String.format("Transaction cancelled. %s", tce));
+
+ // get cancellation reasons
+ List<CancellationReason> cancellationReasonList = tce.getCancellationReasons();
+ if (cancellationReasonList != null)
+ {
+ for (CancellationReason cancellationReason : cancellationReasonList)
+ {
+ sb.append(String.format("Cancellation reason: %s", cancellationReason.getMessage()));
+ }
+ }
+ logger.warn(sb.toString());
+ throw tce;
}
- return ResultFailed;
}
@Override
|
Bubbling up exceptions so they count towards write failures as appropriate, and extracting transaction failure reasons and logging
|
Netflix_ndbench
|
train
|
8a96d142bfeec839aadea72bd994f667ea77ec1f
|
diff --git a/reformulation-core/src/main/java/org/semanticweb/ontop/pivotalrepr/impl/JgraphtQueryTreeComponent.java b/reformulation-core/src/main/java/org/semanticweb/ontop/pivotalrepr/impl/JgraphtQueryTreeComponent.java
index <HASH>..<HASH> 100644
--- a/reformulation-core/src/main/java/org/semanticweb/ontop/pivotalrepr/impl/JgraphtQueryTreeComponent.java
+++ b/reformulation-core/src/main/java/org/semanticweb/ontop/pivotalrepr/impl/JgraphtQueryTreeComponent.java
@@ -21,6 +21,13 @@ import java.util.*;
*/
public class JgraphtQueryTreeComponent implements QueryTreeComponent {
+ private static final Optional<ArgumentPosition> NO_POSITION = Optional.absent();
+ private static final Optional<ArgumentPosition> LEFT_POSITION = Optional.of(ArgumentPosition.LEFT);
+ private static final Optional<ArgumentPosition> RIGHT_POSITION = Optional.of(ArgumentPosition.RIGHT);
+
+ /**
+ * TODO: explain
+ */
public static class LabeledEdge extends DefaultEdge implements Comparable<LabeledEdge> {
private final Optional<ArgumentPosition> optionalPosition;
@@ -167,7 +174,8 @@ public class JgraphtQueryTreeComponent implements QueryTreeComponent {
for (QueryNode childNode : subQuery.getCurrentSubNodesOf(parentNode)) {
queryDAG.addVertex(childNode);
try {
- queryDAG.addDagEdge(childNode, parentNode);
+ Optional<ArgumentPosition> optionalPosition = subQuery.getOptionalPosition(parentNode, childNode);
+ queryDAG.addDagEdge(childNode, parentNode, new LabeledEdge(optionalPosition));
} catch (DirectedAcyclicGraph.CycleFoundException e) {
throw new RuntimeException("BUG (internal error)" + e.getLocalizedMessage());
}
@@ -178,6 +186,12 @@ public class JgraphtQueryTreeComponent implements QueryTreeComponent {
@Override
public void setChildrenNodes(QueryNode parentNode, List<QueryNode> allChildrenNodes) throws IllegalTreeException {
+ boolean isAsymmetric = (parentNode instanceof BinaryAsymmetricOperatorNode);
+
+ if (isAsymmetric && allChildrenNodes.size() != 2) {
+ throw new IllegalTreeException("A BinaryAsymmetricOperatorNode requires two children, " +
+ "not " + allChildrenNodes);
+ }
Set<QueryNode> proposedSubNodesToConsider = new HashSet<>(allChildrenNodes);
@@ -200,17 +214,31 @@ public class JgraphtQueryTreeComponent implements QueryTreeComponent {
/**
* New sub-nodes: added to the DAG
*/
+ int i = 0;
for (QueryNode newSubNode : proposedSubNodesToConsider) {
if (!queryDAG.containsVertex(newSubNode)) {
queryDAG.addVertex(newSubNode);
}
+ LabeledEdge edge;
+ if (isAsymmetric) {
+ if (i == 0) {
+ edge = new LabeledEdge(LEFT_POSITION);
+ }
+ else {
+ edge = new LabeledEdge(RIGHT_POSITION);
+ }
+ }
+ else {
+ edge = new LabeledEdge(NO_POSITION);
+ }
try {
- queryDAG.addDagEdge(parentNode, newSubNode);
+ queryDAG.addDagEdge(parentNode, newSubNode, edge);
} catch (DirectedAcyclicGraph.CycleFoundException ex) {
// Inconsistent proposal (should not introduce a cycle in the DAG) --> throw an exception.
// TODO: return a non- RuntimeException.
throw new IllegalTreeException(ex.getMessage());
}
+ i++;
}
}
|
Bugfix: optional positions were not copied when adding a sub-tree.
|
ontop_ontop
|
train
|
b3e70ee6f2fdf59802f5b2b62847411afcee4385
|
diff --git a/bridge.js b/bridge.js
index <HASH>..<HASH> 100644
--- a/bridge.js
+++ b/bridge.js
@@ -138,6 +138,8 @@ var callbacks = [
'onAlert', 'onCallback', 'onClosing', 'onConfirm', 'onConsoleMessage', 'onError', 'onFilePicker',
'onInitialized', 'onLoadFinished', 'onLoadStarted', 'onNavigationRequested',
'onPrompt', 'onResourceRequested', 'onResourceReceived', 'onResourceTimeout', 'onResourceError', 'onUrlChanged',
+ // SlimerJS only
+ 'onAuthPrompt'
];
function setup_callbacks (id, page) {
|
Added `onAuthPrompt` handler (implemented in SlimerJS only)
|
baudehlo_node-phantom-simple
|
train
|
76a6bbd142beaf5db56166b02979641a3d3d8520
|
diff --git a/service/src/main/java/org/ops4j/pax/web/service/internal/model/ServletModel.java b/service/src/main/java/org/ops4j/pax/web/service/internal/model/ServletModel.java
index <HASH>..<HASH> 100644
--- a/service/src/main/java/org/ops4j/pax/web/service/internal/model/ServletModel.java
+++ b/service/src/main/java/org/ops4j/pax/web/service/internal/model/ServletModel.java
@@ -166,7 +166,7 @@ public class ServletModel
private static String aliasAsUrlPattern( final String alias )
{
String urlPattern = alias;
- if( urlPattern != null && !urlPattern.contains( "*" ) )
+ if( urlPattern != null && !urlPattern.equals( "/" ) && !urlPattern.contains( "*" ) )
{
if( urlPattern.endsWith( "/" ) )
{
|
/ registered servlet should become the Default Servlet.
|
ops4j_org.ops4j.pax.web
|
train
|
435b4b1644841df8dbc7434ae88f835ef4fd70dd
|
diff --git a/lib/Alchemy/Phrasea/Controller/Permalink.php b/lib/Alchemy/Phrasea/Controller/Permalink.php
index <HASH>..<HASH> 100644
--- a/lib/Alchemy/Phrasea/Controller/Permalink.php
+++ b/lib/Alchemy/Phrasea/Controller/Permalink.php
@@ -78,7 +78,7 @@ class Permalink extends AbstractDelivery
}
$response = $that->deliverContent($app['request'], $record, $subdef, $watermark, $stamp, $app);
- $linkToCaption = $app->path("permalinks_caption", array('sbas_id' => $sbas_id, 'record_id' => $record_id, 'token' => $token));
+ $linkToCaption = $app->url("permalinks_caption", array('sbas_id' => $sbas_id, 'record_id' => $record_id, 'token' => $token));
$response->headers->set('Link', $linkToCaption);
return $response;
@@ -100,7 +100,7 @@ class Permalink extends AbstractDelivery
$response = $that->deliverContent($app['request'], $record, $subdef, $watermark, $stamp, $app);
- $linkToCaption = $app->path("permalinks_caption", array('sbas_id' => $sbas_id, 'record_id' => $record_id, 'token' => $token));
+ $linkToCaption = $app->url("permalinks_caption", array('sbas_id' => $sbas_id, 'record_id' => $record_id, 'token' => $token));
$response->headers->set('Link', $linkToCaption);
return $response;
diff --git a/tests/Alchemy/Tests/Phrasea/Application/OverviewTest.php b/tests/Alchemy/Tests/Phrasea/Application/OverviewTest.php
index <HASH>..<HASH> 100644
--- a/tests/Alchemy/Tests/Phrasea/Application/OverviewTest.php
+++ b/tests/Alchemy/Tests/Phrasea/Application/OverviewTest.php
@@ -185,7 +185,7 @@ class ApplicationOverviewTest extends \PhraseanetWebTestCaseAuthenticatedAbstrac
$this->assertEquals($value, $response->headers->get($name));
}
- $this->assertEquals($response->headers->get("Link"), "/permalink/v1/1/". self::$DI['record_1']->get_record_id()."/caption/?token=".$token);
+ $this->assertEquals(rtrim(self::$DI['app']['phraseanet.configuration']['main']['servername'], '/') . "/permalink/v1/1/". self::$DI['record_1']->get_record_id()."/caption/?token=".$token, $response->headers->get("Link"));
$this->assertEquals(200, $response->getStatusCode());
}
@@ -217,7 +217,7 @@ class ApplicationOverviewTest extends \PhraseanetWebTestCaseAuthenticatedAbstrac
$this->assertEquals($value, $response->headers->get($name));
}
- $this->assertEquals($response->headers->get("Link"), "/permalink/v1/1/". self::$DI['record_1']->get_record_id()."/caption/?token=".$token);
+ $this->assertEquals(rtrim(self::$DI['app']['phraseanet.configuration']['main']['servername'], '/') . "/permalink/v1/1/". self::$DI['record_1']->get_record_id()."/caption/?token=".$token, $response->headers->get("Link"));
$this->assertEquals(200, $response->getStatusCode());
}
diff --git a/tests/classes/PhraseanetPHPUnitAbstract.php b/tests/classes/PhraseanetPHPUnitAbstract.php
index <HASH>..<HASH> 100644
--- a/tests/classes/PhraseanetPHPUnitAbstract.php
+++ b/tests/classes/PhraseanetPHPUnitAbstract.php
@@ -8,6 +8,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
+use Symfony\Component\Routing\RequestContext;
abstract class PhraseanetPHPUnitAbstract extends WebTestCase
{
@@ -118,6 +119,13 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
return new CsrfTestProvider();
});
+ $app['url_generator'] = $app->share($app->extend('url_generator', function($generator, $app) {
+ $host = parse_url($app['phraseanet.configuration']['main']['servername'], PHP_URL_HOST);
+ $generator->setContext(new RequestContext('', 'GET', $host));
+
+ return $generator;
+ }));
+
$app['debug'] = true;
$app['EM'] = $app->share($app->extend('EM', function($em) {
|
Link header should provide fully qualified URIs
|
alchemy-fr_Phraseanet
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.