hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
20783369f696a1903aa47164ff5ccab7349334f5
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@ composer require alexantr/yii2-elfinder
### Configure actions
For using elFinder you must create and configure controller. Full example with actions for elFinder's connector,
-`InputFile` widget, CKEditor `filebrowser*` and TinyMCE `file_picker_callback`:
+`InputFile` widget, CKEditor `filebrowser*` params and TinyMCE `file_picker_callback` param:
```php
<?php
@@ -165,7 +165,7 @@ For using elFinder with TinyMCE 4 widget (like [this one](https://github.com/2am
specify param `file_picker_callback`:
```php
-<?= alexantr\ckeditor\CKEditor::widget([
+<?= dosamigos\tinymce\TinyMce::widget([
'name' => 'attributeName',
'clientOptions' => [
// ...
@@ -174,6 +174,12 @@ specify param `file_picker_callback`:
]) ?>
```
+With second param in `getFilePickerCallback()` you can set additional `tinymce.WindowManager.open` settings:
+
+```php
+TinyMCE::getFilePickerCallback(['elfinder/tinymce'], ['width' => 1200, 'height' => 600])
+```
+
### Standalone file manager
Create action in any controller:
diff --git a/src/TinyMCE.php b/src/TinyMCE.php
index <HASH>..<HASH> 100644
--- a/src/TinyMCE.php
+++ b/src/TinyMCE.php
@@ -2,6 +2,7 @@
namespace alexantr\elfinder;
+use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
@@ -10,21 +11,24 @@ class TinyMCE
/**
* Callback for TinyMCE 4 file_picker_callback
* @param array|string $url Url to TinyMCEAction
- * @param int $width Pupup width
- * @param int $height Popup height
+ * @param array $popupSettings TinyMCE popup settings
* @return JsExpression
*/
- public static function getFilePickerCallback($url, $width = 900, $height = 500)
+ public static function getFilePickerCallback($url, $popupSettings = [])
{
- $url = Url::to($url);
+ $default = [
+ 'title' => 'elFinder 2.1',
+ 'width' => 900,
+ 'height' => 500,
+ ];
+
+ $settings = array_merge($default, $popupSettings);
+ $settings['file'] = Url::to($url);
+ $encodedSettings = Json::encode($settings);
+
$callback = <<<JSEXP
function (callback, value, meta) {
- tinymce.activeEditor.windowManager.open({
- file: "$url",
- title: "elFinder 2.1",
- width: $width,
- height: $height
- }, {
+ tinymce.activeEditor.windowManager.open($encodedSettings, {
oninsert: function (file, fm) {
var url = file.url, reg = /\/[^/]+?\/\.\.\//;
while(url.match(reg)) {
diff --git a/tests/TinyMCETest.php b/tests/TinyMCETest.php
index <HASH>..<HASH> 100644
--- a/tests/TinyMCETest.php
+++ b/tests/TinyMCETest.php
@@ -8,15 +8,10 @@ class TinyMCETest extends TestCase
{
public function testTinyMCEFilePickerCallback()
{
- $out = TinyMCE::getFilePickerCallback(['/elfinder/tinymce'], 1000, 600);
+ $out = TinyMCE::getFilePickerCallback(['/elfinder/tinymce'], ['width' => 1000, 'height' => 600]);
$expected = 'function (callback, value, meta) {
- tinymce.activeEditor.windowManager.open({
- file: "/index.php?r=elfinder%2Ftinymce",
- title: "elFinder 2.1",
- width: 1000,
- height: 600
- }, {
+ tinymce.activeEditor.windowManager.open({"title":"elFinder 2.1","width":1000,"height":600,"file":"/index.php?r=elfinder%2Ftinymce"}, {
oninsert: function (file, fm) {
var url = file.url, reg = /\/[^/]+?\/\.\.\//;
while(url.match(reg)) {
|
Can set full setting array for TinyMCE popup instead width and height only
|
alexantr_yii2-elfinder
|
train
|
81846b4bddc40bd5f61e38ea509f2cd7d72d8d79
|
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/detect/FieldItemSummary.java b/findbugs/src/java/edu/umd/cs/findbugs/detect/FieldItemSummary.java
index <HASH>..<HASH> 100644
--- a/findbugs/src/java/edu/umd/cs/findbugs/detect/FieldItemSummary.java
+++ b/findbugs/src/java/edu/umd/cs/findbugs/detect/FieldItemSummary.java
@@ -23,6 +23,7 @@ import java.util.HashSet;
import java.util.Set;
import org.apache.bcel.classfile.Code;
+import org.apache.bcel.classfile.JavaClass;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.NonReportingDetector;
@@ -46,6 +47,11 @@ public class FieldItemSummary extends OpcodeStackDetector implements NonReportin
Set<XField> touched = new HashSet<XField>();
+
+ @Override
+ public boolean shouldVisit(JavaClass obj) {
+ return !getXClass().hasStubs();
+ }
boolean sawInitializeSuper;
@Override
public void sawOpcode(int seen) {
|
don't summarize classes that have method stubs
git-svn-id: <URL>
|
spotbugs_spotbugs
|
train
|
5620e3bee50e0eb040baf161a300400ba90395b3
|
diff --git a/src/libs/Cron.php b/src/libs/Cron.php
index <HASH>..<HASH> 100644
--- a/src/libs/Cron.php
+++ b/src/libs/Cron.php
@@ -73,7 +73,10 @@ class Cron
ob_start();
- $controllerObj = new $controller( $app );
+ $controllerObj = new $controller;
+
+ if (method_exists($controllerObj, 'injectApp'))
+ $controllerObj->injectApp($this->app);
if( !method_exists( $controllerObj, 'cron' ) )
echo "$controller\-\>cron($command) does not exist\n";
|
use new way to inject app into controllers
|
infusephp_cron
|
train
|
de13ad570d7e882a182500daecd2f06b1eba8bdb
|
diff --git a/Manager/PublishingManager.php b/Manager/PublishingManager.php
index <HASH>..<HASH> 100644
--- a/Manager/PublishingManager.php
+++ b/Manager/PublishingManager.php
@@ -302,31 +302,14 @@ class PublishingManager
if (!empty($nodes)) {
$pathRights = $this->path->getResourceNode()->getRights();
- $user = $this->security->getToken()->getUser();
- // This piece of code is copied from ActivityManager
- $nodesInitialized = array ();
foreach ($nodes as $node) {
- $isNodeCreator = $node->getCreator() === $user;
- $ws = $node->getWorkspace();
- $roleWsManager = $this->om->getRepository('ClarolineCoreBundle:Role')->findManagerRole($ws);
- $isWsManager = $user->hasRole($roleWsManager);
-
- if ($isNodeCreator || $isWsManager) {
- $nodesInitialized[] = $node;
- }
- }
-
- $rolesInitialized = array ();
- foreach ($pathRights as $right) {
- $role = $right->getRole();
-
- if (!strpos('_' . $role->getName(), 'ROLE_WS_MANAGER') && $right->getMask() & 1) {
- $rolesInitialized[] = $role;
+ foreach ($pathRights as $right) {
+ if ($right->getMask() & 1) {
+ $this->rightsManager->editPerms($right->getMask(), $right->getRole(), $node, true);
+ }
}
}
-
- $this->rightsManager->initializePermissions($nodesInitialized, $rolesInitialized);
}
return $this;
|
[PathBundle] clean manage rights function (still override resources rights with path rights)
|
claroline_Distribution
|
train
|
2137ea026acaa0929aa2b05e1d35c5e2654ada42
|
diff --git a/lib/browser.php b/lib/browser.php
index <HASH>..<HASH> 100644
--- a/lib/browser.php
+++ b/lib/browser.php
@@ -257,7 +257,7 @@ $browser = array(
"icon" => "chrome",
"title" => "Chrome",
"rule" => array(
- "chrome([ /])?([0-9.]{1,10})?" => "\\2"
+ "chrome([ /])?([0-9.]{1,12})?" => "\\2"
),
"uri" => "http://www.google.com/chrome/"
),
@@ -1466,6 +1466,7 @@ $browser = array(
"Minefield/([0-9.+]{1,10})" => "\\1", // Firefox 3.0 beta
"Shiretoko/([0-9a-z.+]{1,10})" => "\\1", // Firefox 3.1 alpha
"Namoroka/([0-9a-z.+]{1,10})" => "\\1", // Firefox 3.6 beta
+ "MozillaDeveloperPreview/([0-9a-z.+]{1,10})" => "\\1", // Firefox 3.7 alpha
"Firefox" => ""
),
"uri" => "http://www.mozilla.org/projects/firefox/",
|
more than <I> characters for chrome versions
|
znarf_bouncer
|
train
|
8f51c998e84feeac6cb760a9f12baf6948cd5922
|
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -1,7 +1,6 @@
import builtins
import datetime as dt
from io import StringIO
-from itertools import product
from string import ascii_lowercase
import numpy as np
@@ -1296,36 +1295,32 @@ def test_count_uses_size_on_exception():
# --------------------------------
-def test_size(df):
- grouped = df.groupby(["A", "B"])
+@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]])
+def test_size(df, by):
+ grouped = df.groupby(by=by)
result = grouped.size()
for key, group in grouped:
assert result[key] == len(group)
- grouped = df.groupby("A")
- result = grouped.size()
- for key, group in grouped:
- assert result[key] == len(group)
- grouped = df.groupby("B")
- result = grouped.size()
- for key, group in grouped:
- assert result[key] == len(group)
+@pytest.mark.parametrize("by", ["A", "B", ["A", "B"]])
+@pytest.mark.parametrize("sort", [True, False])
+def test_size_sort(df, sort, by):
+ df = DataFrame(np.random.choice(20, (1000, 3)), columns=list("ABC"))
+ left = df.groupby(by=by, sort=sort).size()
+ right = df.groupby(by=by, sort=sort)["C"].apply(lambda a: a.shape[0])
+ tm.assert_series_equal(left, right, check_names=False)
- df = DataFrame(np.random.choice(20, (1000, 3)), columns=list("abc"))
- for sort, key in product((False, True), ("a", "b", ["a", "b"])):
- left = df.groupby(key, sort=sort).size()
- right = df.groupby(key, sort=sort)["c"].apply(lambda a: a.shape[0])
- tm.assert_series_equal(left, right, check_names=False)
- # GH11699
+def test_size_series_dataframe():
+ # https://github.com/pandas-dev/pandas/issues/11699
df = DataFrame(columns=["A", "B"])
out = Series(dtype="int64", index=Index([], name="A"))
tm.assert_series_equal(df.groupby("A").size(), out)
def test_size_groupby_all_null():
- # GH23050
+ # https://github.com/pandas-dev/pandas/issues/23050
# Assert no 'Value Error : Length of passed values is 2, index implies 0'
df = DataFrame({"A": [None, None]}) # all-null groups
result = df.groupby("A").size()
@@ -1335,6 +1330,8 @@ def test_size_groupby_all_null():
# quantile
# --------------------------------
+
+
@pytest.mark.parametrize(
"interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
)
|
TST: Removed import of itertools (#<I>)
|
pandas-dev_pandas
|
train
|
afd3d828987edfae0e3bfc20831ab2e17ca86c9e
|
diff --git a/codecov/__init__.py b/codecov/__init__.py
index <HASH>..<HASH> 100644
--- a/codecov/__init__.py
+++ b/codecov/__init__.py
@@ -83,6 +83,7 @@ is_report = re.compile('.*('
r'(\.lst)|'
r'(clover\.xml)|'
r'(cobertura\.xml)|'
+ r'(coverage-final\.json)|'
r'(gcov\.info)|'
r'(jacoco[^/]*\.xml)|'
r'(lcov\.info)|'
|
add coverage-final.json detection
|
codecov_codecov-python
|
train
|
1f38e29a22c4c2d2338386f0ce711bffc7dfabb0
|
diff --git a/connection.class.php b/connection.class.php
index <HASH>..<HASH> 100644
--- a/connection.class.php
+++ b/connection.class.php
@@ -554,8 +554,8 @@ class CPS_LoadBalancer
$this->_lastSuccess = false;
$this->_exclusionTime = 30;
$tmp = sys_get_temp_dir();
- if (substr($tmp, strlen($tmp) - 1) !== "/") {
- $tmp .= "/";
+ if (substr($tmp, strlen($tmp) - 1) !== DIRECTORY_SEPARATOR) {
+ $tmp .= DIRECTORY_SEPARATOR;
};
$this->_statusFilePrefix = $tmp . "cps-api-node-status-";
$this->_sendWhenAllFailed = true;
|
#Connection class :: updated to DIRECTORY_SEPARATOR
|
clusterpoint_php-client-api
|
train
|
cb0561de74570e9038eb9679fbc4377e44167961
|
diff --git a/colr/__init__.py b/colr/__init__.py
index <HASH>..<HASH> 100644
--- a/colr/__init__.py
+++ b/colr/__init__.py
@@ -41,6 +41,8 @@ from .colr import ( # noqa
strip_codes
)
+from .colr_docopt import docopt
+
from .trans import (
ColorCode,
fix_hex,
@@ -65,6 +67,7 @@ __all__ = [
'codeformat',
'disable',
'disabled',
+ 'docopt',
'enable',
'extbackformat',
'extforeformat',
diff --git a/colr/__main__.py b/colr/__main__.py
index <HASH>..<HASH> 100644
--- a/colr/__main__.py
+++ b/colr/__main__.py
@@ -33,7 +33,7 @@ from .colr import (
from .trans import ColorCode
try:
- from docopt import docopt
+ from .colr_docopt import docopt
except ImportError as eximp:
print('\n'.join((
'Import error: {}',
@@ -123,7 +123,7 @@ def main(argd):
try:
print('\n'.join(translate(argd['CODE'] or read_stdin().split())))
except ValueError as ex:
- print('Translation error: {}'.format(ex), file=sys.stderr)
+ print_err('Translation error: {}'.format(ex))
return 1
return 0
elif argd['--listcodes']:
@@ -170,7 +170,7 @@ def get_colr(txt, argd):
style=style
)
except ValueError as ex:
- print('Error: {}'.format(ex), file=sys.stderr)
+ print_err('Error: {}'.format(ex))
return None
elif argd['--rainbow']:
clr = C(txt).rainbow(
@@ -225,6 +225,13 @@ def list_known_codes(s, unique=True):
return 0 if total > 0 else 1
+def print_err(*args, **kwargs):
+ """ A wrapper for print() that uses stderr by default. """
+ if kwargs.get('file', None) is None:
+ kwargs['file'] = sys.stderr
+ print(C(kwargs.get('sep', ' ').join(args), fore='red'), **kwargs)
+
+
def read_stdin():
""" Read text from stdin, and print a helpful message for ttys. """
if sys.stdin.isatty() and sys.stdout.isatty():
@@ -320,15 +327,13 @@ if __name__ == '__main__':
try:
mainret = main(docopt(USAGESTR, version=VERSIONSTR))
except (EOFError, KeyboardInterrupt):
- print('\nUser cancelled.\n', file=sys.stderr)
+ print_err('\nUser cancelled.\n')
mainret = 2
except BrokenPipeError:
- print(
- '\nBroken pipe, input/output was interrupted.\n',
- file=sys.stderr)
+ print_err('\nBroken pipe, input/output was interrupted.\n')
mainret = 3
- except InvalidNumber as exnum:
- print('\n{}'.format(exnum), file=sys.stderr)
+ except (ValueError, InvalidNumber) as exnum:
+ print_err('\n{}'.format(exnum))
mainret = 4
sys.exit(mainret)
diff --git a/colr/colr.py b/colr/colr.py
index <HASH>..<HASH> 100644
--- a/colr/colr.py
+++ b/colr/colr.py
@@ -56,7 +56,7 @@ CodeFormatFunc = Callable[[CodeFormatArg], str]
ColorType = Union[str, int]
-__version__ = '0.4.4'
+__version__ = '0.5.0'
__all__ = [
'_disabled',
@@ -375,7 +375,12 @@ class Colr(object):
style: Optional[str]=None) -> None:
""" Initialize a Colr object with text and color options. """
# Can be initialized with colored text, not required though.
- self.data = self.color(text or '', fore=fore, back=back, style=style)
+ self.data = self.color(
+ text,
+ fore=fore,
+ back=back,
+ style=style
+ )
def __add__(self, other: 'Colr') -> 'Colr':
""" Allow the old string concat methods through addition. """
@@ -912,11 +917,12 @@ class Colr(object):
Raises ValueError for invalid color names.
The 'reset_all' code is appended if text is given.
"""
+ text = str(text) if text is not None else ''
if _disabled:
- return str(text or '')
+ return text
return ''.join((
self.color_code(fore=fore, back=back, style=style),
- str(text or ''),
+ text,
closing_code if text else ''
))
@@ -948,7 +954,7 @@ class Colr(object):
""" A wrapper for str() that matches self.color().
For overriding when _auto_disable is used.
"""
- return str(text or '')
+ return str(text) if text is not None else ''
def format(self, *args, **kwargs):
""" Like str.format, except it returns a Colr. """
|
Add colorized docopt, fix text=0, bad color msg.
A colorized docopt is now available in `colr.colr_docopt`.
Should be importable with `from colr import docopt`.
Previous bug was fixed, where text=0 was falsey empty
text was used (instead of `str(0)`). This also caused
the closing code to be omitted.
The command line tool printed an ugly message when invalid
color names/values were given. This has been shortened
and an error exit status is returned.
|
welbornprod_colr
|
train
|
82d47dc596125506ac9fdcc6ede0b5a91348dd15
|
diff --git a/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/aggregator/swingui/BenchmarkAggregatorFrame.java b/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/aggregator/swingui/BenchmarkAggregatorFrame.java
index <HASH>..<HASH> 100644
--- a/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/aggregator/swingui/BenchmarkAggregatorFrame.java
+++ b/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/aggregator/swingui/BenchmarkAggregatorFrame.java
@@ -32,6 +32,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.AbstractAction;
+import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
@@ -108,10 +109,6 @@ public class BenchmarkAggregatorFrame extends JFrame {
setLocationRelativeTo(null);
}
- // ************************************************************************
- // TODO All code below is POC code: replace this code with production quality code
- // ************************************************************************
-
private JComponent createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
if (plannerBenchmarkResultList.isEmpty()) {
@@ -240,29 +237,29 @@ public class BenchmarkAggregatorFrame extends JFrame {
@Override
protected void done() {
try {
- File reportFile = get();
- CustomDialog dialog = new CustomDialog(parentFrame, reportFile);
+ File htmlOverviewFile = get();
+ CustomDialog dialog = new CustomDialog(parentFrame, htmlOverviewFile);
dialog.pack();
- dialog.setLocationRelativeTo(null);
+ dialog.setLocationRelativeTo(BenchmarkAggregatorFrame.this);
dialog.setVisible(true);
- } catch (InterruptedException ex) {
- throw new IllegalStateException(ex);
- } catch (ExecutionException ex) {
- throw new IllegalStateException(ex);
+ } catch (InterruptedException e) {
+ throw new IllegalStateException(e);
+ } catch (ExecutionException e) {
+ throw new IllegalStateException(e);
} finally {
parentFrame.setEnabled(true);
frameStatusBar.setText(null);
}
}
+
}
private class CustomDialog extends JDialog {
public CustomDialog(final JFrame parentFrame, final File reportFile) {
- super(parentFrame, "Reprot generation finished");
+ super(parentFrame, "Report generation finished");
JPanel contentPanel = new JPanel(new GridLayout(2, 2, 10, 10));
- contentPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
- contentPanel.setBackground(Color.WHITE);
+ contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JButton openBrowserButton = new JButton("Show in browser");
openBrowserButton.addActionListener(new AbstractAction() {
@@ -284,7 +281,6 @@ public class BenchmarkAggregatorFrame extends JFrame {
final JCheckBox exitCheckbox = new JCheckBox("Exit application”");
exitCheckbox.setSelected(true);
- exitCheckbox.setBackground(Color.WHITE);
contentPanel.add(exitCheckbox);
JButton closeButton = new JButton("Ok");
@@ -300,28 +296,28 @@ public class BenchmarkAggregatorFrame extends JFrame {
});
contentPanel.add(closeButton);
getContentPane().add(contentPanel);
- setPreferredSize(new Dimension(400, 150));
}
private void openReportFile(File file, Desktop.Action action) {
Desktop desktop = Desktop.getDesktop();
try {
switch (action) {
- case OPEN: {
+ case OPEN:
if (desktop.isSupported(Desktop.Action.OPEN)) {
desktop.open(file);
}
break;
- }
- case BROWSE: {
+ case BROWSE:
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(file.toURI());
}
- }
+ break;
}
- } catch (IOException ex) {
- throw new IllegalStateException(ex);
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
}
}
+
}
+
}
|
peer review aggregator gui: clearer variable name (htmlOverviewFile), no messing with the LaF background color, code style
|
kiegroup_optaplanner
|
train
|
c8fb2322341cbd90cab8948cee29e15b1582090e
|
diff --git a/src/PhantomInstaller/Installer.php b/src/PhantomInstaller/Installer.php
index <HASH>..<HASH> 100644
--- a/src/PhantomInstaller/Installer.php
+++ b/src/PhantomInstaller/Installer.php
@@ -275,7 +275,7 @@ class Installer
if ($os !== 'unknown') {
copy($targetDir . $sourceName, $targetName);
- chmod($targetName, self::PHANTOMJS_CHMODE);
+ chmod($targetName, static::PHANTOMJS_CHMODE);
}
self::dropClassWithPathToInstalledBinary($targetName);
|
use static to access chmod constant
to allow override via extending class
|
jakoch_phantomjs-installer
|
train
|
118308ae21ec5d85b644bcf426d8da9a7d4762d7
|
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index <HASH>..<HASH> 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -79,7 +79,7 @@ jobs:
- run: coverage xml
- - uses: codecov/codecov-action@v1.4.1
+ - uses: codecov/codecov-action@v1.5.2
with:
file: ./coverage.xml
env_vars: PYTHON,OS
diff --git a/arq/connections.py b/arq/connections.py
index <HASH>..<HASH> 100644
--- a/arq/connections.py
+++ b/arq/connections.py
@@ -265,10 +265,17 @@ async def create_pool(
async def log_redis_info(redis: Redis, log_func: Callable[[str], Any]) -> None:
with await redis as r:
- info, key_count = await asyncio.gather(r.info(), r.dbsize())
+ info_server, info_memory, info_clients, key_count = await asyncio.gather(
+ r.info(section='Server'), r.info(section='Memory'), r.info(section='Clients'), r.dbsize(),
+ )
+
+ redis_version = info_server.get('server', {}).get('redis_version', '?')
+ mem_usage = info_memory.get('memory', {}).get('used_memory_human', '?')
+ clients_connected = info_clients.get('clients', {}).get('connected_clients', '?')
+
log_func(
- f'redis_version={info["server"]["redis_version"]} '
- f'mem_usage={info["memory"]["used_memory_human"]} '
- f'clients_connected={info["clients"]["connected_clients"]} '
+ f'redis_version={redis_version} '
+ f'mem_usage={mem_usage} '
+ f'clients_connected={clients_connected} '
f'db_keys={key_count}'
)
diff --git a/arq/version.py b/arq/version.py
index <HASH>..<HASH> 100644
--- a/arq/version.py
+++ b/arq/version.py
@@ -1,3 +1,3 @@
__all__ = ('VERSION',)
-VERSION = '0.20'
+VERSION = '0.21'
|
log_redis_info (#<I>)
* log_redis_info, fix #<I>
* uprev
* linting and fix CI
|
samuelcolvin_arq
|
train
|
969df7fb6cd59001ab086fa453c64289ba53f0c8
|
diff --git a/lib/search_engine.py b/lib/search_engine.py
index <HASH>..<HASH> 100644
--- a/lib/search_engine.py
+++ b/lib/search_engine.py
@@ -87,7 +87,7 @@ from invenio.intbitset import intbitset as HitSet
from invenio.dbquery import DatabaseError, deserialize_via_marshal
from invenio.access_control_engine import acc_authorize_action
from invenio.errorlib import register_exception
-from invenio.textutils import encode_for_xml
+from invenio.textutils import encode_for_xml, wash_for_utf8
import invenio.template
webstyle_templates = invenio.template.load('webstyle')
@@ -1475,6 +1475,8 @@ def wash_pattern(p):
p = re_pattern_today.sub(time.strftime("%Y-%m-%d", time.localtime()), p)
# remove unnecessary whitespace:
p = string.strip(p)
+ # remove potentially wrong UTF-8 characters:
+ p = wash_for_utf8(p)
return p
def wash_field(f):
|
WebSearch: wash user query of bad UTF-8 chars
* Fix the problem when incorrect UTF-8 query parameters are passed to
the search engine. (closes #<I>)
|
inveniosoftware_invenio-records
|
train
|
fb392807ee7897868f36f2db9c49c7b67b3efb96
|
diff --git a/package-testing/spec/package/update_module_spec.rb b/package-testing/spec/package/update_module_spec.rb
index <HASH>..<HASH> 100644
--- a/package-testing/spec/package/update_module_spec.rb
+++ b/package-testing/spec/package/update_module_spec.rb
@@ -34,7 +34,9 @@ describe 'Updating an existing module' do
end
end
+ sync_yaml['Gemfile']['required'][':system_tests'] ||= []
sync_yaml['Gemfile']['required'][':system_tests'] << { 'gem' => 'nokogiri', 'version' => '1.8.5' }
+
create_remote_file(get_working_node, File.join(module_dir, '.sync.yml'), sync_yaml.to_yaml)
end
|
(FIXUP) Avoid attempting to append nokogiri pin to nil in package tests
|
puppetlabs_pdk
|
train
|
97ebcfff985821b2c7a54e5e70bdd7ae654cd08b
|
diff --git a/closure/goog/soy/renderer.js b/closure/goog/soy/renderer.js
index <HASH>..<HASH> 100644
--- a/closure/goog/soy/renderer.js
+++ b/closure/goog/soy/renderer.js
@@ -207,7 +207,7 @@ goog.soy.Renderer.prototype.renderText = function(template, opt_templateData) {
* defaults to goog.soy.data.SanitizedContentKind.HTML).
* @return {RETURN_TYPE} The SanitizedContent object. This return type is
* generic based on the return type of the template, such as
- * soy.SanitizedHtml.
+ * soydata.SanitizedHtml.
* @template ARG_TYPES, RETURN_TYPE
*/
goog.soy.Renderer.prototype.renderStrict = function(
|
Fix a typo in a comment.
-------------
Created by MOE: <URL>
|
google_closure-library
|
train
|
8c6cca053d2b5a4d4bd1449d834dc738bffd7fe1
|
diff --git a/README.rdoc b/README.rdoc
index <HASH>..<HASH> 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -40,6 +40,21 @@ You can configure easy_captcha in "config/initializers/easy_captcha.rb", if you
# config.image_height = 40
# config.image_width = 140
+ # eSpeak (default disabled)
+ # config.espeak do |espeak|
+ # Amplitude, 0 to 200
+ # espeak.amplitude = 80..120
+
+ # Word gap. Pause between words
+ # espeak.gap = 80
+
+ # Pitch adjustment, 0 to 99
+ # espeak.pitch = 30..70
+
+ # Use voice file of this name from espeak-data/voices
+ # espeak.voice = nil
+ # end
+
# configure generator
# config.generator :default do |generator|
@@ -90,17 +105,18 @@ You can configure easy_captcha in "config/initializers/easy_captcha.rb", if you
<p><%= captcha_tag %></p>
<p><%= text_field_tag :captcha %></p>
<p><%= submit_tag 'Validate' %></p>
- <% end %>
+ <% end %>
== Example app
You find an example app under: http://github.com/phatworx/easy_captcha_example
== History
- * 0.1 init
- * 0.2 cache support for high frequented sites
- * 0.3 use generators, optimizations, update licence to same of all my plugins
- * 0.4 generator support
- * 0.5 (transparent) background support
+* 0.1 init
+* 0.2 cache support for high frequented sites
+* 0.3 use generators, optimizations, update licence to same of all my plugins
+* 0.4 generator support
+* 0.5 (transparent) background support
+* 0.6 espeak support for barrier-free support
== Maintainers
diff --git a/lib/easy_captcha.rb b/lib/easy_captcha.rb
index <HASH>..<HASH> 100644
--- a/lib/easy_captcha.rb
+++ b/lib/easy_captcha.rb
@@ -71,8 +71,24 @@ module EasyCaptcha
end
end
+ def espeak=(state)
+ if state === true
+ @espeak = Espeak.new
+ else
+ @espeak = false
+ end
+ end
+
def espeak(&block)
- @espeak = Espeak.new &block
+ if block_given?
+ @espeak = Espeak.new &block
+ else
+ @espeak ||= false
+ end
+ end
+
+ def espeak?
+ not @espeak === false
end
# depracated
diff --git a/lib/easy_captcha/controller.rb b/lib/easy_captcha/controller.rb
index <HASH>..<HASH> 100644
--- a/lib/easy_captcha/controller.rb
+++ b/lib/easy_captcha/controller.rb
@@ -3,7 +3,7 @@ module EasyCaptcha
class Controller < ActionController::Base
# captcha action send the generated image to browser
def captcha
- if params[:format] == "wav"
+ if params[:format] == "wav" and EasyCaptcha.espeak?
send_data generate_speech_captcha, :disposition => 'inline', :type => 'audio/wav'
else
send_data generate_captcha, :disposition => 'inline', :type => 'image/png'
diff --git a/lib/easy_captcha/controller_helpers.rb b/lib/easy_captcha/controller_helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/easy_captcha/controller_helpers.rb
+++ b/lib/easy_captcha/controller_helpers.rb
@@ -36,7 +36,7 @@ module EasyCaptcha
File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image }
# write speech file if u create a new captcha image
- EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code))
+ EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak?
# return image
image
@@ -47,6 +47,7 @@ module EasyCaptcha
# generate speech by captcha from session
def generate_speech_captcha
+ raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak?
if EasyCaptcha.cache
File.read(speech_captcha_cache_path(current_captcha_code))
else
|
fix some bugs in espeak
|
phatworx_easy_captcha
|
train
|
596e83d015037d216912771b5c75acc5e91c5c8a
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -768,17 +768,17 @@ constructor.
var Rollbar = require('rollbar');
var rollbar = new Rollbar({
accessToken: 'POST_SERVER_ITEM_ACCESS_TOKEN',
- handleUncaughtExceptions: true,
- handleUnhandledRejections: true
+ captureUncaught: true,
+ captureUnhandledRejections: true
});
// log a generic message and send to rollbar
rollbar.log('Hello world!');
```
-Setting the ```handleUncaughtExceptions``` option to true will register Rollbar as a handler for
+Setting the ```captureUncaught``` option to true will register Rollbar as a handler for
any uncaught exceptions in your Node process.
-Similarly, setting the ```handleUnhandledRejections``` option to true will register Rollbar as a
+Similarly, setting the ```captureUnhandledRejections``` option to true will register Rollbar as a
handler for any unhandled Promise rejections in your Node process.
<!-- RemoveNextIfProject -->
@@ -1066,8 +1066,8 @@ New:
```js
var rollbar = new Rollbar({
accessToken: "POST_SERVER_ITEM_ACCESS_TOKEN",
- handleUncaughtExceptions: true,
- handleUnhandledRejections: true
+ captureUncaught: true,
+ captureUnhandledRejections: true
});
```
@@ -1085,7 +1085,7 @@ const Rollbar = require('rollbar');
const rollbar = Rollbar.init({
accessToken: "POST_SERVER_ITEM_ACCESS_TOKEN",
- handleUncaughtExceptions: true
+ captureUncaught: true
});
```
diff --git a/src/browser/rollbar.js b/src/browser/rollbar.js
index <HASH>..<HASH> 100644
--- a/src/browser/rollbar.js
+++ b/src/browser/rollbar.js
@@ -18,11 +18,11 @@ function Rollbar(options, client) {
this.client = client || new Client(this.options, api, logger, 'browser');
addTransformsToNotifier(this.client.notifier);
addPredicatesToQueue(this.client.queue);
- if (this.options.captureUncaught) {
+ if (this.options.captureUncaught || this.options.handleUncaughtExceptions) {
globals.captureUncaughtExceptions(window, this);
globals.wrapGlobals(window, this);
}
- if (this.options.captureUnhandledRejections) {
+ if (this.options.captureUnhandledRejections || this.options.handleUnhandledRejections) {
globals.captureUnhandledRejections(window, this);
}
}
diff --git a/src/server/rollbar.js b/src/server/rollbar.js
index <HASH>..<HASH> 100644
--- a/src/server/rollbar.js
+++ b/src/server/rollbar.js
@@ -32,10 +32,10 @@ function Rollbar(options, client) {
addTransformsToNotifier(this.client.notifier);
addPredicatesToQueue(this.client.queue);
- if (this.options.handleUncaughtExceptions) {
+ if (this.options.captureUncaught || this.options.handleUncaughtExceptions) {
this.handleUncaughtExceptions();
}
- if (this.options.handleUnhandledRejections) {
+ if (this.options.captureUnhandledRejections || this.options.handleUnhandledRejections) {
this.handleUnhandledRejections();
}
}
|
the configuration options for capturing unhandled exceptions and rejections should be the same on the browser and server
|
rollbar_rollbar.js
|
train
|
5d73b474292b22ebdcdd2ac21884e1429289e535
|
diff --git a/lib/weixin_authorize/client.rb b/lib/weixin_authorize/client.rb
index <HASH>..<HASH> 100644
--- a/lib/weixin_authorize/client.rb
+++ b/lib/weixin_authorize/client.rb
@@ -37,12 +37,22 @@ module WeixinAuthorize
# authenticate access_token
def authenticate
if is_weixin_redis_blank?
- http_get_access_token
+ set_access_token_for_client
else
authenticate_with_redis
end
end
+ # 检查appid和app_secret是否有效。
+ def is_valid?
+ valid_result = http_get_access_token
+ if valid_result.keys.include?("access_token")
+ set_access_token_for_client(valid_result)
+ return true
+ end
+ false
+ end
+
def token_expired?
if is_weixin_redis_blank?
# 如果当前token过期时间小于现在的时间,则重新获取一次
@@ -55,15 +65,20 @@ module WeixinAuthorize
private
def authenticate_with_redis
- http_get_access_token
+ set_access_token_for_client
weixin_redis.hmset(redis_key, :access_token, access_token, :expired_at, expired_at)
weixin_redis.expireat(redis_key, expired_at.to_i-10) # 提前10秒超时
end
+ def set_access_token_for_client(access_token_infos=nil)
+ token_infos = access_token_infos || http_get_access_token
+ self.access_token = token_infos["access_token"]
+ self.expired_at = Time.now.to_i + token_infos["expires_in"]
+ end
+
def http_get_access_token
- hash_infos = http_get_without_token("/token", authenticate_options)
- self.access_token = hash_infos["access_token"]
- self.expired_at = Time.now.to_i + hash_infos["expires_in"]
+ hash_infos = http_get_without_token("/token", authenticate_options)
+ hash_infos
end
def authenticate_options
|
added is_valid? method to valid app_id and app_secret
|
lanrion_weixin_authorize
|
train
|
8ace503f4e59582213812a7631183b253e8c8ca6
|
diff --git a/sos/plugins/docker.py b/sos/plugins/docker.py
index <HASH>..<HASH> 100644
--- a/sos/plugins/docker.py
+++ b/sos/plugins/docker.py
@@ -17,6 +17,7 @@ from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin
class Docker(Plugin):
+
"""Docker containers
"""
@@ -24,6 +25,9 @@ class Docker(Plugin):
profiles = ('virt',)
docker_bin = "docker"
+ option_list = [("all", "capture all container logs even the "
+ "terminated ones", 'fast', False)]
+
def setup(self):
self.add_copy_specs([
"/var/lib/docker/repositories-*"
@@ -35,8 +39,11 @@ class Docker(Plugin):
"{0} images".format(self.docker_bin)
])
- result = self.get_command_output("{0} ps".format(
- self.docker_bin))
+ ps_cmd = "{0} ps".format(self.docker_bin)
+ if self.get_option('all'):
+ ps_cmd = "{0} -a".format(ps_cmd)
+
+ result = self.get_command_output(ps_cmd)
if result['status'] == 0:
result['output'] = result['output'].split("\n")
for line in result['output'][1:]:
|
[docker] optional log capturing for all containers
This options provides the user the ability to pull
logs from all containers including the terminated/stopped.
Fixes #<I>
Fixes #<I>
|
sosreport_sos
|
train
|
e5b7f61f090bfc951590dd5dad3f6bb1ce3888ba
|
diff --git a/integration-cli/docker_api_containers_test.go b/integration-cli/docker_api_containers_test.go
index <HASH>..<HASH> 100644
--- a/integration-cli/docker_api_containers_test.go
+++ b/integration-cli/docker_api_containers_test.go
@@ -94,7 +94,7 @@ type containerPs struct {
func (s *DockerSuite) TestContainerPsOmitFields(c *check.C) {
name := "pstest"
port := 80
- runCmd := exec.Command(dockerBinary, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", "sleep", "5")
+ runCmd := exec.Command(dockerBinary, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", "top")
_, err := runCommand(runCmd)
c.Assert(err, check.IsNil)
|
Replace "sleep" by "top" in test implementation
Eliminate any chance of race condition by replacing a call to sleep by a
call to top, and rely on test cleanup logic to have it exit cleanly.
|
containers_storage
|
train
|
9c9301bbb1988824c10dbc0f41716eaef6bd8245
|
diff --git a/scipy_data_fitting/fit.py b/scipy_data_fitting/fit.py
index <HASH>..<HASH> 100644
--- a/scipy_data_fitting/fit.py
+++ b/scipy_data_fitting/fit.py
@@ -401,4 +401,4 @@ class Fit:
else:
symbols.append(variable)
- return symbols
+ return tuple(symbols)
diff --git a/test/test_fit.py b/test/test_fit.py
index <HASH>..<HASH> 100644
--- a/test/test_fit.py
+++ b/test/test_fit.py
@@ -100,4 +100,4 @@ class TestFit():
{'symbol': 'a'},
{'symbol': 'b'},
]
- eq_(fit.all_variables, [fit.model.symbol(s) for s in symbols])
+ eq_(fit.all_variables, tuple( fit.model.symbol(s) for s in symbols ))
|
Fit.all_variables should return tuple.
|
razor-x_scipy-data_fitting
|
train
|
37399ccb738080ade029aa0df4972c2fa25d8fe7
|
diff --git a/dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/internal/SpringBootRuntimeContainer.java b/dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/internal/SpringBootRuntimeContainer.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/internal/SpringBootRuntimeContainer.java
+++ b/dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/internal/SpringBootRuntimeContainer.java
@@ -68,7 +68,7 @@ public class SpringBootRuntimeContainer implements ModuleRuntimeContainer {
@Override
public J2EEName getJ2EEName() {
- return null;
+ return ((ExtendedApplicationInfo) moduleInfo.getApplicationInfo()).getMetaData().getJ2EEName();
}
}
|
Issue #<I>-A NullPointerException occurs when starting a spring boot application if cdi-<I> feature is enabled
Fixed the issue by returning the J2EEName in SpringBootRuntimeContainer
|
OpenLiberty_open-liberty
|
train
|
49c1fa6f261d6058e4a37ca93aea50175b3b5b74
|
diff --git a/lib/archivers/zip/zip-archive-output-stream.js b/lib/archivers/zip/zip-archive-output-stream.js
index <HASH>..<HASH> 100644
--- a/lib/archivers/zip/zip-archive-output-stream.js
+++ b/lib/archivers/zip/zip-archive-output-stream.js
@@ -8,7 +8,7 @@
var inherits = require('util').inherits;
var crc32 = require('buffer-crc32');
var {CRC32Stream} = require('crc32-stream');
-var DeflateCRC32Stream = CRC32Stream.DeflateCRC32Stream;
+var {DeflateCRC32Stream} = require('crc32-stream');
var ArchiveOutputStream = require('../archive-output-stream');
var ZipArchiveEntry = require('./zip-archive-entry');
|
Update zip-archive-output-stream.js
|
archiverjs_node-compress-commons
|
train
|
3a9c8121896787ce33f9d3b91cb76b68b7cf6b02
|
diff --git a/src/sap.ui.core/src/jquery.sap.script.js b/src/sap.ui.core/src/jquery.sap.script.js
index <HASH>..<HASH> 100644
--- a/src/sap.ui.core/src/jquery.sap.script.js
+++ b/src/sap.ui.core/src/jquery.sap.script.js
@@ -421,26 +421,6 @@ sap.ui.define(['jquery.sap.global'],
}());
/**
- * This function generates a hash-code from a string
- * @param {string} sString The string to generate the hash-code from
- * @return {integer} The generated hash-code
- * @since 1.39
- * @public
- */
- jQuery.sap.hashCode = function(sString) {
- var iHash, iLength, iCharCode, i;
- iHash = 0;
- iLength = sString.length;
-
- for (i = 0; i < iLength; i++) {
- iCharCode = sString.charCodeAt(i);
- iHash = (iHash << 5) - iHash + iCharCode;
- iHash = iHash & iHash;
- }
- return iHash;
- };
-
- /**
* Calculate delta of old list and new list
* This implements the algorithm described in "A Technique for Isolating Differences Between Files"
* (Commun. ACM, April 1978, Volume 21, Number 4, Pages 264-268)
|
[INTERNAL] jquery.sap.script: remove redundant method implementation
Note that this (intentionally) reverts the visibility of the method to
private.
Change-Id: I<I>f<I>b<I>fa<I>fe<I>d<I>f<I>f
|
SAP_openui5
|
train
|
7839e44ff7665fa501d9b6092d8ed659309f1f1b
|
diff --git a/eZ/Publish/Core/FieldType/Tests/PageTest.php b/eZ/Publish/Core/FieldType/Tests/PageTest.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/FieldType/Tests/PageTest.php
+++ b/eZ/Publish/Core/FieldType/Tests/PageTest.php
@@ -124,10 +124,6 @@ class PageTest extends StandardizedFieldTypeTest
new \stdClass(),
'eZ\\Publish\\Core\\Base\\Exceptions\\InvalidArgumentException'
),
- array(
- null,
- 'eZ\\Publish\\Core\\Base\\Exceptions\\InvalidArgumentException'
- ),
);
}
@@ -164,6 +160,10 @@ class PageTest extends StandardizedFieldTypeTest
{
return array(
array(
+ null,
+ new PageValue()
+ ),
+ array(
new PageValue(),
new PageValue()
),
|
Fixed: all provided field types accept null as empty value
|
ezsystems_ezpublish-kernel
|
train
|
25e428029000a93b19951a76d19efff6688ea2c0
|
diff --git a/src/Html5FileUploadViewBridge.js b/src/Html5FileUploadViewBridge.js
index <HASH>..<HASH> 100644
--- a/src/Html5FileUploadViewBridge.js
+++ b/src/Html5FileUploadViewBridge.js
@@ -69,6 +69,9 @@ window.rhubarb.vb.create("Html5FileUploadViewBridge", function(parent){
this.uploadNextFile();
},
+ onUploadStarted: function (file) {
+
+ },
onUploadFailed: function (response) {
// There isn't any appropriate default behaviour for this so we don't provide any.
// AS it's an HTML 5 upload the user could have scrolled this control out of view
@@ -272,6 +275,7 @@ window.rhubarb.vb.create("Html5FileUploadViewBridge", function(parent){
"remaining": false
};
+ this.onUploadStarted(file);
this.raiseClientEvent("UploadStarted", file);
this.request = this.sendFileAsServerEvent(
diff --git a/src/SingleHtml5FileUploadWithPersistenceViewBridge.js b/src/SingleHtml5FileUploadWithPersistenceViewBridge.js
index <HASH>..<HASH> 100644
--- a/src/SingleHtml5FileUploadWithPersistenceViewBridge.js
+++ b/src/SingleHtml5FileUploadWithPersistenceViewBridge.js
@@ -15,17 +15,28 @@ window.rhubarb.vb.create("SingleHtml5FileUploadWithPersistenceViewBridge", funct
this.label.style.display = 'none';
this.button.style.display = 'none';
}
+
+ if (this.uploading){
+ this.originalFileInput.style.display = 'none';
+ }
},
extractFileName: function(filePath) {
var parts = filePath.split(/\//);
return parts[parts.length-1];
},
+ onUploadStarted: function(file){
+ this.uploading = true;
+ this.updateDom();
+ },
onUploadFailed: function (response) {
this.viewNode.classList.add("has-failed");
+ this.uploading = false;
+ this.updateDom();
},
onUploadComplete: function(fileProgressDom, serverResponse){
this.model.value = serverResponse;
+ this.uploading = false;
this.updateDom();
},
onReady: function(){
|
Tweaks to round off single html 5 upload
|
RhubarbPHP_Module.Leaf.Html5Upload
|
train
|
bbe0bd9899636a49d1b5d5e7aa6d8a9685e9878e
|
diff --git a/group/assign.php b/group/assign.php
index <HASH>..<HASH> 100644
--- a/group/assign.php
+++ b/group/assign.php
@@ -1,13 +1,35 @@
-<?php // $Id$
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
/**
* Add/remove group from grouping.
+ *
+ * @copyright 1999 Martin Dougiamas http://dougiamas.com
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package groups
*/
+
require_once('../config.php');
require_once('lib.php');
$groupingid = required_param('id', PARAM_INT);
+$PAGE->set_url(new moodle_url($CFG->wwwroot.'/group/assign.php', array('id'=>$groupingid)));
+
if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingid))) {
print_error('invalidgroupid');
}
diff --git a/group/delete.php b/group/delete.php
index <HASH>..<HASH> 100644
--- a/group/delete.php
+++ b/group/delete.php
@@ -16,6 +16,8 @@ $courseid = required_param('courseid', PARAM_INT);
$groupids = required_param('groups', PARAM_SEQUENCE);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
+$PAGE->set_url(new moodle_url($CFG->wwwroot.'/group/delete.php', array('courseid'=>$courseid,'groups'=>$groupids)));
+
// Make sure course is OK and user has access to manage groups
if (!$course = $DB->get_record('course', array('id' => $courseid))) {
print_error('invalidcourseid');
diff --git a/group/grouping.php b/group/grouping.php
index <HASH>..<HASH> 100644
--- a/group/grouping.php
+++ b/group/grouping.php
@@ -18,16 +18,19 @@ $id = optional_param('id', 0, PARAM_INT);
$delete = optional_param('delete', 0, PARAM_BOOL);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
+$url = new moodle_url($CFG->wwwroot.'/group/grouping.php');
if ($id) {
+ $url->param('id', $id);
if (!$grouping = $DB->get_record('groupings', array('id'=>$id))) {
print_error('invalidgroupid');
}
$grouping->description = clean_text($grouping->description);
if (empty($courseid)) {
$courseid = $grouping->courseid;
-
} else if ($courseid != $grouping->courseid) {
print_error('invalidcourseid');
+ } else {
+ $url->param('courseid', $courseid);
}
if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
@@ -35,6 +38,7 @@ if ($id) {
}
} else {
+ $url->param('courseid', $courseid);
if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
print_error('invalidcourseid');
}
@@ -42,6 +46,8 @@ if ($id) {
$grouping->courseid = $course->id;
}
+$PAGE->set_url($url);
+
require_login($course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('moodle/course:managegroups', $context);
diff --git a/group/groupings.php b/group/groupings.php
index <HASH>..<HASH> 100644
--- a/group/groupings.php
+++ b/group/groupings.php
@@ -1,11 +1,35 @@
-<?php // $Id$
- // Allows a creator to edit groupings
+<?php
+
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Allows a creator to edit groupings
+ *
+ * @copyright 1999 Martin Dougiamas http://dougiamas.com
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package groups
+ */
require_once '../config.php';
require_once $CFG->dirroot.'/group/lib.php';
$courseid = required_param('id', PARAM_INT);
+$PAGE->set_url(new moodle_url($CFG->wwwroot.'/group/groupings.php', array('id'=>$courseid)));
+
if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
print_error('nocourseid');
}
|
group MDL-<I> Added set_url calls
|
moodle_moodle
|
train
|
b83986a07119400bbe673ca286838f56f01c7e59
|
diff --git a/state/application.go b/state/application.go
index <HASH>..<HASH> 100644
--- a/state/application.go
+++ b/state/application.go
@@ -122,8 +122,8 @@ func applicationCharmConfigKey(appName string, curl *charm.URL) string {
}
// charmConfigKeyGeneration returns the charm-version-specific settings
-// collection key and possibly a fallback, for the application based on the
-// input generation. I
+// collection key and possibly a fallback for the application, based on the
+// input generation.
// If the next generation is requested, the fallback is the standard key.
// If the current generation is requested, there is no fallback.
// TODO (manadart 2019-02-21) This will eventually strangle out usage of the
@@ -2036,7 +2036,7 @@ func applicationRelations(st *State, name string) (relations []*Relation, err er
}
func charmSettingsWithDefaults(st *State, curl *charm.URL, requestKey, fallbackKey string) (charm.Settings, error) {
- settings, err := readSettingsWithFallback(st.db(), settingsC, requestKey, fallbackKey)
+ settings, err := readSettingsOrCreateFromFallback(st.db(), settingsC, requestKey, fallbackKey)
if err != nil {
return nil, err
}
@@ -2084,7 +2084,7 @@ func (a *Application) UpdateCharmConfig(gen model.GenerationVersion, changes cha
// name, so the actual impact of a race is non-threatening.
k1, k2 := a.charmConfigKeyGeneration(gen)
- node, err := readSettingsWithFallback(a.st.db(), settingsC, k1, k2)
+ node, err := readSettingsOrCreateFromFallback(a.st.db(), settingsC, k1, k2)
if err != nil {
return errors.Annotatef(err, "charm config for application %q", a.doc.Name)
}
diff --git a/state/settings.go b/state/settings.go
index <HASH>..<HASH> 100644
--- a/state/settings.go
+++ b/state/settings.go
@@ -315,10 +315,10 @@ func (st *State) ReadSettings(collection, key string) (*Settings, error) {
return readSettings(st.db(), collection, key)
}
-// readSettingsWithFallback attempts to retrieve settings first for the
+// readSettingsOrCreateFromFallback attempts to retrieve settings first for the
// requested key, then if not found, a non-empty fallback key.
// If the fallback is used, the settings are created for the requested key.
-func readSettingsWithFallback(db Database, collection, requestKey, fallbackKey string) (*Settings, error) {
+func readSettingsOrCreateFromFallback(db Database, collection, requestKey, fallbackKey string) (*Settings, error) {
s, err := readSettings(db, collection, requestKey)
if err == nil {
return s, nil
diff --git a/state/settings_test.go b/state/settings_test.go
index <HASH>..<HASH> 100644
--- a/state/settings_test.go
+++ b/state/settings_test.go
@@ -550,11 +550,11 @@ func (s *SettingsSuite) TestReadSettingsWithFallback(c *gc.C) {
nextGenKey := model.NextGenerationKey(s.key)
// Without a fallback, we get a not found error.
- _, err = readSettingsWithFallback(s.state.db(), s.collection, nextGenKey, "")
+ _, err = readSettingsOrCreateFromFallback(s.state.db(), s.collection, nextGenKey, "")
c.Assert(errors.IsNotFound(err), jc.IsTrue)
// Next generation settings do not exist; fallback should create them.
- s2, err := readSettingsWithFallback(s.state.db(), s.collection, nextGenKey, s.key)
+ s2, err := readSettingsOrCreateFromFallback(s.state.db(), s.collection, nextGenKey, s.key)
c.Assert(err, jc.ErrorIsNil)
c.Check(s2.key, gc.DeepEquals, nextGenKey)
c.Check(s2.Map(), gc.DeepEquals, s1.Map())
|
Renames readSettingsWithFallback to better indicate behaviour, plus minor comment typo fix.
|
juju_juju
|
train
|
7c06a79ebc60b7118a7908ed14b1acb8282a2b46
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -27,7 +27,7 @@ setup(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Education',
- 'Intended Audience :: Science/Research'
+ 'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Mathematics',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
|
Fixed a missing comma.
|
gvanderheide_discreteMarkovChain
|
train
|
755807afb82ea2b756f2c14ea10541dc623f05a6
|
diff --git a/examples/android-example/src/main/java/io/joynr/example/JoynrAndroidExampleApplication.java b/examples/android-example/src/main/java/io/joynr/example/JoynrAndroidExampleApplication.java
index <HASH>..<HASH> 100644
--- a/examples/android-example/src/main/java/io/joynr/example/JoynrAndroidExampleApplication.java
+++ b/examples/android-example/src/main/java/io/joynr/example/JoynrAndroidExampleApplication.java
@@ -20,6 +20,9 @@ package io.joynr.example;
*/
import io.joynr.joynrandroidruntime.JoynrAndroidRuntime;
+import io.joynr.messaging.MessagingPropertyKeys;
+
+import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,14 +32,22 @@ import android.app.Application;
public class JoynrAndroidExampleApplication extends Application {
private static final Logger logger = LoggerFactory.getLogger(JoynrAndroidExampleApplication.class);
- private JoynrAndroidExampleLauncher joynrAndroidExampleLauncher = new JoynrAndroidExampleLauncher();
+ private final JoynrAndroidExampleLauncher joynrAndroidExampleLauncher = new JoynrAndroidExampleLauncher();
private JoynrAndroidRuntime runtime;
@Override
public void onCreate() {
super.onCreate();
- runtime = new JoynrAndroidRuntime(getApplicationContext());
+ // Replace with your bounceproxy's host name
+ String backendHost = "YOURHOSTHERE:8080"; //TODO make this configurable
+ Properties joynrConfig = new Properties();
+ joynrConfig.setProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL, "http://" + backendHost + "/bounceproxy/");
+ joynrConfig.setProperty(MessagingPropertyKeys.CHANNELURLDIRECTORYURL, "http://" + backendHost
+ + "/discovery/channels/discoverydirectory_channelid/");
+ joynrConfig.setProperty(MessagingPropertyKeys.CAPABILITIESDIRECTORYURL, "http://" + backendHost
+ + "/discovery/channels/discoverydirectory_channelid/");
+ runtime = new JoynrAndroidRuntime(getApplicationContext(), joynrConfig);
logger.info("onCreate JoynAndroidExampleApplication");
joynrAndroidExampleLauncher.setJoynAndroidRuntime(runtime);
|
android example not configured correctly
since the default settings are now localhost:<I>, it is
necessary to explicitly configure the bounceproxy and
directories on android. Testing using localhost obviously
does not work.
A new ticket JOYn-<I> will make this configurable in the UI
Change-Id: Ia<I>e<I>d<I>a9b<I>bbbf<I>f6d<I>a<I>
|
bmwcarit_joynr
|
train
|
ec5a967937a8dd4fb5287591e8dedcdedfa2b32d
|
diff --git a/models/user.go b/models/user.go
index <HASH>..<HASH> 100644
--- a/models/user.go
+++ b/models/user.go
@@ -469,6 +469,12 @@ func (u *User) ShortName(length int) string {
return base.EllipsisString(u.Name, length)
}
+// IsMailable checks if a user is elegible
+// to receive emails.
+func (u *User) IsMailable() bool {
+ return u.IsActive
+}
+
// IsUserExist checks if given user name exist,
// the user name should be noncased unique.
// If uid is presented, then check will rule out that one,
@@ -929,7 +935,9 @@ func GetUserEmailsByNames(names []string) []string {
if err != nil {
continue
}
- mails = append(mails, u.Email)
+ if u.IsMailable() {
+ mails = append(mails, u.Email)
+ }
}
return mails
}
|
Issue #<I> (#<I>)
|
gogs_gogs
|
train
|
1e5a723f306ba0c6c34fe75d06e8a41d697523c3
|
diff --git a/protoc-gen-swagger/genswagger/template.go b/protoc-gen-swagger/genswagger/template.go
index <HASH>..<HASH> 100644
--- a/protoc-gen-swagger/genswagger/template.go
+++ b/protoc-gen-swagger/genswagger/template.go
@@ -510,7 +510,7 @@ func updateSwaggerDataFromComments(swaggerObject interface{}, comment string) er
summary := strings.TrimSpace(paragraphs[0])
description := strings.TrimSpace(strings.Join(paragraphs[1:], "\n\n"))
- if !usingTitle || summary[len(summary)-1] != '.' {
+ if !usingTitle || summary == "" || summary[len(summary)-1] != '.' {
if len(summary) > 0 {
summaryValue.Set(reflect.ValueOf(summary))
}
|
Fixes index out of range panic when empty.
|
grpc-ecosystem_grpc-gateway
|
train
|
43ca7646d4c744797a9e4d4f3d9d2333ad6942a2
|
diff --git a/test/object-model.spec.js b/test/object-model.spec.js
index <HASH>..<HASH> 100644
--- a/test/object-model.spec.js
+++ b/test/object-model.spec.js
@@ -2,24 +2,33 @@
QUnit.module("Object Models");
-const consoleMock = {
- methods: ["debug","log","warn","error"],
- apply: function(){
- consoleMock.methods.forEach(function(method){
- consoleMock["_default"+method] = console[method];
- consoleMock[method+"LastArgs"] = [];
- console[method] = function(){
- consoleMock[method+"LastArgs"] = arguments;
- }
- })
- },
- revert: function(){
- consoleMock.methods.forEach(function(method){
- console[method] = consoleMock["_default"+method];
- consoleMock[method+"LastArgs"] = [];
- });
+const consoleMock = (function(console) {
+ const methods = ["debug", "log", "warn", "error"];
+ const originals = {};
+ const mocks = {}
+ const lastArgs = {};
+
+ methods.forEach(method => {
+ originals[method] = console[method]
+ mocks[method] = function(){ lastArgs[method] = arguments }
+ })
+
+ return {
+ apply: function () {
+ methods.forEach(method => {
+ lastArgs[method] = [];
+ console[method] = mocks[method]
+ })
+ },
+ revert: function () {
+ methods.forEach(method => {
+ lastArgs[method] = [];
+ console[method] = originals[method]
+ })
+ },
+ lastArgs
}
-};
+})(console);
QUnit.test("Object model constructor && proto", function (assert) {
@@ -972,7 +981,7 @@ QUnit.test("Automatic model casting", function (assert) {
consoleMock.apply();
c.foo.bar; //get ambiguous key
assert.ok(/Ambiguous model for[\s\S]*?name: "dunno"[\s\S]*?other1: \[Boolean\][\s\S]*?other2: \[Number]/
- .test(consoleMock["warnLastArgs"][0]),
+ .test(consoleMock.lastArgs.warn[0]),
"should warn about ambiguous model for object sub prop"
);
assert.ok(c.foo.bar.name === "dunno", "should preserve values even when ambiguous model cast");
@@ -981,7 +990,7 @@ QUnit.test("Automatic model casting", function (assert) {
consoleMock.apply();
c = new Container({ foo: { bar: Type2({ name: "dunno" }) }});
- assert.ok(consoleMock["warnLastArgs"].length === 0, "should not warn when explicit model cast in ambiguous context");
+ assert.ok(consoleMock.lastArgs.warn.length === 0, "should not warn when explicit model cast in ambiguous context");
assert.ok(c.foo.bar.name === "dunno", "should preserve values when explicit model cast in ambiguous context");
assert.ok(c.foo.bar instanceof Type2, "should preserve model when explicit cast in ambiguous context");
consoleMock.revert();
@@ -1081,4 +1090,5 @@ QUnit.test("ObjectModel class constructors", function (assert) {
assert.equal(Object.keys(User.definition).join(","), "firstName,lastName,fullName,role")
assert.equal(Object.keys(user).join(","), "firstName,lastName,fullName,role")
assert.throws(function(){ user.role = null; }, /TypeError/, "extended class model check definition")
+
})
\ No newline at end of file
|
refactored console mocking
|
sylvainpolletvillard_ObjectModel
|
train
|
6449d28e513f066e66aa2e798aca568b0f9f9f4c
|
diff --git a/packages/migrate/src/index.js b/packages/migrate/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/migrate/src/index.js
+++ b/packages/migrate/src/index.js
@@ -54,40 +54,37 @@ export default async function(options) {
fileNames: {}
};
- await Promise.all(
- files.map(async file => {
- const basename = path.basename(file);
- if (basename.endsWith(".marko")) {
- const prettyPrintOptions = {
- syntax: options.syntax,
- maxLen: options.maxLen,
- noSemi: options.noSemi,
- singleQuote: options.singleQuote,
- filename: file
- };
- const migrateHelper = new MigrateHelper(options.prompt);
- const add = migrateOptions =>
- addMigration(migrateHelper, migrateOptions);
- const source = await fs.readFile(file, "utf-8");
- const ast = markoCompiler.parse(source, file, {
- onContext(ctx) {
- prettyPrintOptions.context = ctx;
- ctx.addMigration = add;
- addDefaultMigrations(ctx, results);
- },
- migrate: true,
- raw: true
- });
-
- await runAutoMigrations(migrateHelper);
-
- results.fileContents[file] = markoPrettyprint.prettyPrintAST(
- ast,
- prettyPrintOptions
- );
- }
- })
- );
+ for (const file of files) {
+ const basename = path.basename(file);
+ if (basename.endsWith(".marko")) {
+ const prettyPrintOptions = {
+ syntax: options.syntax,
+ maxLen: options.maxLen,
+ noSemi: options.noSemi,
+ singleQuote: options.singleQuote,
+ filename: file
+ };
+ const migrateHelper = new MigrateHelper(options.prompt);
+ const add = migrateOptions => addMigration(migrateHelper, migrateOptions);
+ const source = await fs.readFile(file, "utf-8");
+ const ast = markoCompiler.parse(source, file, {
+ onContext(ctx) {
+ prettyPrintOptions.context = ctx;
+ ctx.addMigration = add;
+ addDefaultMigrations(ctx, results);
+ },
+ migrate: true,
+ raw: true
+ });
+
+ await runAutoMigrations(migrateHelper);
+
+ results.fileContents[file] = markoPrettyprint.prettyPrintAST(
+ ast,
+ prettyPrintOptions
+ );
+ }
+ }
return results;
}
|
fix(migrate): run migrations serially (#<I>)
|
marko-js_cli
|
train
|
85e5a77de130f4b064d3c70671f1fd7f3fc046e2
|
diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/RemoteStreamEnvironment.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/RemoteStreamEnvironment.java
index <HASH>..<HASH> 100644
--- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/RemoteStreamEnvironment.java
+++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/RemoteStreamEnvironment.java
@@ -22,6 +22,7 @@ import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.InvalidProgramException;
import org.apache.flink.api.common.JobExecutionResult;
+import org.apache.flink.api.common.PlanExecutor;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.client.ClientUtils;
import org.apache.flink.client.program.ClusterClient;
@@ -225,7 +226,6 @@ public class RemoteStreamEnvironment extends StreamExecutionEnvironment {
) throws ProgramInvocationException {
StreamGraph streamGraph = streamExecutionEnvironment.getStreamGraph(jobName);
return executeRemotely(streamGraph,
- streamExecutionEnvironment.getClass().getClassLoader(),
streamExecutionEnvironment.getConfig(),
jarFiles,
host,
@@ -242,7 +242,6 @@ public class RemoteStreamEnvironment extends StreamExecutionEnvironment {
* @throws ProgramInvocationException
*/
private static JobExecutionResult executeRemotely(StreamGraph streamGraph,
- ClassLoader envClassLoader,
ExecutionConfig executionConfig,
List<URL> jarFiles,
String host,
@@ -255,8 +254,6 @@ public class RemoteStreamEnvironment extends StreamExecutionEnvironment {
LOG.info("Running remotely at {}:{}", host, port);
}
- ClassLoader userCodeClassLoader = ClientUtils.buildUserCodeClassLoader(jarFiles, globalClasspaths, envClassLoader);
-
Configuration configuration = new Configuration();
configuration.addAll(clientConfiguration);
@@ -274,13 +271,18 @@ public class RemoteStreamEnvironment extends StreamExecutionEnvironment {
streamGraph.getJobGraph().getJobID(), e);
}
- if (savepointRestoreSettings == null) {
- savepointRestoreSettings = SavepointRestoreSettings.none();
+ if (savepointRestoreSettings != null) {
+ streamGraph.setSavepointRestoreSettings(savepointRestoreSettings);
}
try {
- return client.run(streamGraph, jarFiles, globalClasspaths, userCodeClassLoader, savepointRestoreSettings)
- .getJobExecutionResult();
+ final PlanExecutor executor = PlanExecutor.createRemoteExecutor(
+ host,
+ port,
+ clientConfiguration,
+ jarFiles,
+ globalClasspaths);
+ return executor.executePlan(streamGraph).getJobExecutionResult();
}
catch (ProgramInvocationException e) {
throw e;
@@ -318,7 +320,6 @@ public class RemoteStreamEnvironment extends StreamExecutionEnvironment {
@Deprecated
protected JobExecutionResult executeRemotely(StreamGraph streamGraph, List<URL> jarFiles) throws ProgramInvocationException {
return executeRemotely(streamGraph,
- this.getClass().getClassLoader(),
getConfig(),
jarFiles,
host,
|
[FLINK-<I>] Use RemoteExecutor in RemoteStreamEnvironment
|
apache_flink
|
train
|
84ab91a365ae4d0c82677a42f0d8758d22b3ba0d
|
diff --git a/src/bbn/api/kendo/grid.php b/src/bbn/api/kendo/grid.php
index <HASH>..<HASH> 100644
--- a/src/bbn/api/kendo/grid.php
+++ b/src/bbn/api/kendo/grid.php
@@ -206,7 +206,7 @@ class grid // extends object
height:"auto",
width:720,
"max-height":bbn.env.height-100
- }).restyle().data("kendoWindow").title("'.bbn\str::escape_dquotes($cfg['description']).'").center();
+ }).data("kendoWindow").title("'.bbn\str::escape_dquotes($cfg['description']).'").center();
}'));
diff --git a/src/bbn/api/kendo/tree.php b/src/bbn/api/kendo/tree.php
index <HASH>..<HASH> 100644
--- a/src/bbn/api/kendo/tree.php
+++ b/src/bbn/api/kendo/tree.php
@@ -113,7 +113,7 @@ class tree // extends object
height:"auto",
width:720,
"max-height":bbn.env.height-100
- }).restyle().data("kendoWindow").title("Formulaire de saisie").center();
+ }).data("kendoWindow").title("Formulaire de saisie").center();
}'));
diff --git a/src/bbn/appui/options.php b/src/bbn/appui/options.php
index <HASH>..<HASH> 100644
--- a/src/bbn/appui/options.php
+++ b/src/bbn/appui/options.php
@@ -405,8 +405,8 @@ class options extends bbn\models\cls\db
return false;
}
// They must all have the same form at start with an id_parent as last argument
- if ( !bbn\str::is_integer(last($args)) ){
- array_push($args, $this->default);
+ if ( !bbn\str::is_integer(end($args)) ){
+ $args[] = $this->default;
}
// So the target has always the same name
$local_cache_name = implode('-', $args);
|
Important bug on options, removed restyle()
|
nabab_bbn
|
train
|
3988306bd2cc7743d24e24d753730ba04462f018
|
diff --git a/pandas_gbq/load.py b/pandas_gbq/load.py
index <HASH>..<HASH> 100644
--- a/pandas_gbq/load.py
+++ b/pandas_gbq/load.py
@@ -119,6 +119,7 @@ def load_parquet(
):
job_config = bigquery.LoadJobConfig()
job_config.write_disposition = "WRITE_APPEND"
+ job_config.create_disposition = "CREATE_NEVER"
job_config.source_format = "PARQUET"
if schema is not None:
@@ -148,6 +149,7 @@ def load_csv(
):
job_config = bigquery.LoadJobConfig()
job_config.write_disposition = "WRITE_APPEND"
+ job_config.create_disposition = "CREATE_NEVER"
job_config.source_format = "CSV"
job_config.allow_quoted_newlines = True
|
fix: allow `to_gbq` to run without `bigquery.tables.create` permission. (#<I>)
|
pydata_pandas-gbq
|
train
|
cd8f7e72cfcb4e30762928d8cfc0e69583b17a4b
|
diff --git a/penn/calendar3year.py b/penn/calendar3year.py
index <HASH>..<HASH> 100644
--- a/penn/calendar3year.py
+++ b/penn/calendar3year.py
@@ -31,11 +31,11 @@ class Calendar(object):
if line == "BEGIN:VEVENT":
d = {}
elif line.startswith("DTSTART"):
- raw_date = line.split(":")[1]
+ raw_date = line.split(":")[1][0:8]
start_date = datetime.datetime.strptime(raw_date, '%Y%m%d').date()
d['start'] = start_date.strftime('%Y-%m-%d')
elif line.startswith("DTEND"):
- raw_date = line.split(":")[1]
+ raw_date = line.split(":")[1][0:8]
end_date = datetime.datetime.strptime(raw_date, '%Y%m%d').date()
d['end'] = end_date.strftime('%Y-%m-%d')
elif line.startswith("SUMMARY"):
|
Fixed calendar crash when rawdate includes timezone by stripping timezone
|
pennlabs_penn-sdk-python
|
train
|
3cfec37d39bcc140b7c131b317c177e83b0c5b05
|
diff --git a/src/org/opencms/main/OpenCmsCore.java b/src/org/opencms/main/OpenCmsCore.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/main/OpenCmsCore.java
+++ b/src/org/opencms/main/OpenCmsCore.java
@@ -1577,6 +1577,8 @@ public final class OpenCmsCore {
synchronized (lock) {
rpcService.service(req, res);
}
+ // update the session info
+ m_sessionManager.updateSessionInfo(cms, req);
} finally {
// be sure to clear the cms context
rpcService.setCms(null);
|
Fixing issue where GWT RPC calls would not update the session info.
|
alkacon_opencms-core
|
train
|
302d91b9d430bd77d252efd8f5de371c993558d1
|
diff --git a/src/components/context-menu/QContextMenu.js b/src/components/context-menu/QContextMenu.js
index <HASH>..<HASH> 100644
--- a/src/components/context-menu/QContextMenu.js
+++ b/src/components/context-menu/QContextMenu.js
@@ -8,7 +8,6 @@ export default {
disable: Boolean
},
data () {
- console.log('is mobile:', this.$q.platform.is.mobile)
return {
mobile: this.$q.platform.is.mobile
}
diff --git a/src/components/tab/QRouteTab.js b/src/components/tab/QRouteTab.js
index <HASH>..<HASH> 100644
--- a/src/components/tab/QRouteTab.js
+++ b/src/components/tab/QRouteTab.js
@@ -35,7 +35,7 @@ export default {
})
}
},
- created () {
+ mounted () {
this.checkIfSelected()
},
render (h) {
|
feat: SSR work on Tabs
|
quasarframework_quasar
|
train
|
64fcc4b37cd218ad99bc97b96c30f47626d85f75
|
diff --git a/src/Post/PostFile.php b/src/Post/PostFile.php
index <HASH>..<HASH> 100644
--- a/src/Post/PostFile.php
+++ b/src/Post/PostFile.php
@@ -112,9 +112,9 @@ class PostFile implements PostFileInterface
// Set a default content-disposition header if one was no provided
if (!$this->hasHeader('Content-Disposition')) {
$this->headers['Content-Disposition'] = sprintf(
- 'form-data; filename="%s"; name="%s"',
- basename($this->filename),
- $this->name
+ 'form-data; name="%s"; filename="%s"',
+ $this->name,
+ basename($this->filename)
);
}
diff --git a/tests/Post/MultipartBodyTest.php b/tests/Post/MultipartBodyTest.php
index <HASH>..<HASH> 100644
--- a/tests/Post/MultipartBodyTest.php
+++ b/tests/Post/MultipartBodyTest.php
@@ -23,7 +23,7 @@ class MultipartBodyTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('abcdef', $b->getBoundary());
$c = (string) $b;
$this->assertContains("--abcdef\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n", $c);
- $this->assertContains("--abcdef\r\nContent-Disposition: form-data; filename=\"foo.txt\"; name=\"foo\"\r\n"
+ $this->assertContains("--abcdef\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"foo.txt\"\r\n"
. "Content-Type: text/plain\r\n\r\nabc\r\n--abcdef--", $c);
}
diff --git a/tests/Post/PostFileTest.php b/tests/Post/PostFileTest.php
index <HASH>..<HASH> 100644
--- a/tests/Post/PostFileTest.php
+++ b/tests/Post/PostFileTest.php
@@ -18,7 +18,7 @@ class PostFileTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('foo', $p->getName());
$this->assertEquals('/path/to/test.php', $p->getFilename());
$this->assertEquals(
- 'form-data; filename="test.php"; name="foo"',
+ 'form-data; name="foo"; filename="test.php"',
$p->getHeaders()['Content-Disposition']
);
}
|
Changing content-disposition order to match curl. Closes #<I>
|
guzzle_guzzle
|
train
|
016f2fbee775825719b8e762cf7b4fa40852d211
|
diff --git a/middleware.go b/middleware.go
index <HASH>..<HASH> 100644
--- a/middleware.go
+++ b/middleware.go
@@ -4,22 +4,19 @@ import (
"net/http"
)
-// NextMiddlewareFunc is the function signature for the next parameter in ServerHTTPMiddleware
-type NextMiddlewareFunc func(http.ResponseWriter, *http.Request)
-
//The MiddlewareFunc type is an adapter to allow the use of ordinary functions as HTTP middlewares.
//
// If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
-type MiddlewareFunc func(http.ResponseWriter, *http.Request, NextMiddlewareFunc)
+type MiddlewareFunc func(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request))
// ServeHTTPMiddleware calls f(w, r, n).
-func (m MiddlewareFunc) ServeHTTPMiddleware(rw http.ResponseWriter, req *http.Request, n NextMiddlewareFunc) {
+func (m MiddlewareFunc) ServeHTTPMiddleware(rw http.ResponseWriter, req *http.Request, n func(http.ResponseWriter, *http.Request)) {
m(rw, req, n)
}
// Middleware handles HTTP requests and optionally passes them along to the next handler in the chain.
type Middleware interface {
- ServeHTTPMiddleware(http.ResponseWriter, *http.Request, NextMiddlewareFunc)
+ ServeHTTPMiddleware(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request))
}
// getNextMiddleware returns the first middleware of a recursive closure.
|
Removed function type
Middleware no longer has to be powermux aware. The more generic
function signature is accepted without having to cast.
|
AndrewBurian_powermux
|
train
|
f66e929d89648568ce61cab53b38e7744f8683bd
|
diff --git a/lib/getFilterInfosAndTargetContentTypeFromQueryString.js b/lib/getFilterInfosAndTargetContentTypeFromQueryString.js
index <HASH>..<HASH> 100644
--- a/lib/getFilterInfosAndTargetContentTypeFromQueryString.js
+++ b/lib/getFilterInfosAndTargetContentTypeFromQueryString.js
@@ -199,6 +199,31 @@ module.exports = function getFilterInfosAndTargetContentTypeFromQueryString(quer
} else {
leftOverQueryStringFragments.push(keyValuePair);
}
+ } else if (operationName === 'metadata' && sharp) {
+ flushOperations();
+ targetContentType = 'application/json; charset=utf-8';
+ filterInfos.push({
+ metadata: true,
+ outputContentType: targetContentType,
+ create: function () {
+ var sharpInstance = sharp();
+ var duplexStream = new Stream.Duplex({ objectMode: true });
+ duplexStream._write = function (chunk, encoding, cb) {
+ sharpInstance.write(chunk, encoding);
+ cb();
+ };
+ duplexStream._read = function (size) {
+ sharpInstance.metadata().then(function (metadata) {
+ duplexStream.push(metadata);
+ duplexStream.push(null);
+ });
+ };
+ duplexStream.on('finish', function () {
+ sharpInstance.end();
+ });
+ return duplexStream;
+ }
+ });
} else if (isOperationByEngineNameAndName[operationName]) {
usedQueryStringFragments.push(keyValuePair);
flushOperations();
diff --git a/lib/processImage.js b/lib/processImage.js
index <HASH>..<HASH> 100644
--- a/lib/processImage.js
+++ b/lib/processImage.js
@@ -1,3 +1,4 @@
+/*global JSON*/
var Path = require('path'),
getFilterInfosAndTargetContentTypeFromQueryString = require('./getFilterInfosAndTargetContentTypeFromQueryString'),
mime = require('mime');
@@ -114,7 +115,12 @@ module.exports = function (options) {
filters[filters.length - 1].on('data', function (chunk) {
seenData = true;
if (!hasEnded) {
- res.write(chunk);
+ if (typeof chunk === 'object' && !Buffer.isBuffer(chunk)) {
+ // objectMode, probably a metadata retrieval operation
+ res.write(JSON.stringify(chunk));
+ } else {
+ res.write(chunk);
+ }
}
}).on('end', function () {
if (!hasEnded) {
diff --git a/test/processImage.js b/test/processImage.js
index <HASH>..<HASH> 100644
--- a/test/processImage.js
+++ b/test/processImage.js
@@ -250,4 +250,32 @@ describe('express-processimage', function () {
errorPassedToNext: /jpegtran -grayscale:/
});
});
+
+ describe.skipIf(!sharp, 'when sharp is available', function () {
+ it('should allow retrieving the image metadata as JSON', function () {
+ return expect('GET /turtle.jpg?metadata', 'to yield response', {
+ body: {
+ width: 481,
+ height: 424,
+ space: 'srgb',
+ channels: 3,
+ hasProfile: false,
+ hasAlpha: false
+ }
+ });
+ });
+
+ it('should allow retrieving the image metadata for the result of an operation', function () {
+ return expect('GET /turtle.jpg?png&greyscale&resize=10&metadata', 'to yield response', {
+ body: {
+ width: 10,
+ height: 9,
+ space: 'srgb',
+ channels: 3,
+ hasProfile: false,
+ hasAlpha: false
+ }
+ });
+ });
+ });
});
|
Added support for &metadata when the sharp library is available.
|
papandreou_express-processimage
|
train
|
073a12c8285353866dfd74de5d88c543bd3ae20d
|
diff --git a/acorn/src/bin/acorn.js b/acorn/src/bin/acorn.js
index <HASH>..<HASH> 100644
--- a/acorn/src/bin/acorn.js
+++ b/acorn/src/bin/acorn.js
@@ -46,7 +46,7 @@ function run(code) {
} while (token.type !== acorn.tokTypes.eof)
}
} catch (e) {
- console.error(e.message)
+ console.error(infile ? e.message.replace(/\(\d+:\d+\)$/, m => m.slice(0, 1) + infile + " " + m.slice(1)) : e.message)
process.exit(1)
}
if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2))
|
Include input file name in error messages output by bin/acorn
Issue #<I>
|
acornjs_acorn
|
train
|
d7675aeda84196d97826eda4b562d828b0fe3105
|
diff --git a/tests/ArionumTest.php b/tests/ArionumTest.php
index <HASH>..<HASH> 100644
--- a/tests/ArionumTest.php
+++ b/tests/ArionumTest.php
@@ -105,6 +105,17 @@ class ArionumTest extends TestCase
{
$data = $this->arionum->getTransaction(self::TEST_TRANSACTION_ID);
$this->assertInstanceOf(\stdClass::class, $data);
- $this->assertNotEmpty($data);
+ $this->assertObjectHasAttribute('version', $data);
+ }
+
+ /**
+ * @covers ::getPublicKey
+ * @throws ApiException
+ */
+ public function testGetPublicKey()
+ {
+ $data = $this->arionum->getPublicKey(self::TEST_ADDRESS);
+ $this->assertInternalType('string', $data);
+ $this->assertTrue(($data === self::TEST_PUBLIC_KEY || $data === ''));
}
}
|
Add test for the getPublicKey method
|
pxgamer_arionum-php
|
train
|
213a7711ecdc75eb484cf0ff4aa3166608453e3f
|
diff --git a/lib/merb-core/dispatch/session/cookie.rb b/lib/merb-core/dispatch/session/cookie.rb
index <HASH>..<HASH> 100644
--- a/lib/merb-core/dispatch/session/cookie.rb
+++ b/lib/merb-core/dispatch/session/cookie.rb
@@ -156,6 +156,7 @@ module Merb
data, digest = Merb::Request.unescape(cookie).split('--')
return {} if data.blank?
unless digest == generate_digest(data)
+ delete
raise TamperedWithCookie, "Maybe the site's session_secret_key has changed?"
end
Marshal.load(Base64.decode64(data))
|
Syncronized code with rails branch. Delete call is required, because user cookie must be cleaned when TamperedWithCookie is raised.
|
wycats_merb
|
train
|
447a70a7b4c01f7806fc5f421d3dceaf7562162f
|
diff --git a/internal/service/networkmanager/tags_gen.go b/internal/service/networkmanager/tags_gen.go
index <HASH>..<HASH> 100644
--- a/internal/service/networkmanager/tags_gen.go
+++ b/internal/service/networkmanager/tags_gen.go
@@ -2,6 +2,7 @@
package networkmanager
import (
+ "context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
@@ -14,11 +15,15 @@ import (
// The identifier is typically the Amazon Resource Name (ARN), although
// it may also be a different identifier depending on the service.
func ListTags(conn networkmanageriface.NetworkManagerAPI, identifier string) (tftags.KeyValueTags, error) {
+ return ListTagsWithContext(context.Background(), conn, identifier)
+}
+
+func ListTagsWithContext(ctx context.Context, conn networkmanageriface.NetworkManagerAPI, identifier string) (tftags.KeyValueTags, error) {
input := &networkmanager.ListTagsForResourceInput{
ResourceArn: aws.String(identifier),
}
- output, err := conn.ListTagsForResource(input)
+ output, err := conn.ListTagsForResourceWithContext(ctx, input)
if err != nil {
return tftags.New(nil), err
@@ -59,7 +64,10 @@ func KeyValueTags(tags []*networkmanager.Tag) tftags.KeyValueTags {
// UpdateTags updates networkmanager service tags.
// The identifier is typically the Amazon Resource Name (ARN), although
// it may also be a different identifier depending on the service.
-func UpdateTags(conn networkmanageriface.NetworkManagerAPI, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
+func UpdateTags(conn networkmanageriface.NetworkManagerAPI, identifier string, oldTags interface{}, newTags interface{}) error {
+ return UpdateTagsWithContext(context.Background(), conn, identifier, oldTags, newTags)
+}
+func UpdateTagsWithContext(ctx context.Context, conn networkmanageriface.NetworkManagerAPI, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error {
oldTags := tftags.New(oldTagsMap)
newTags := tftags.New(newTagsMap)
@@ -69,7 +77,7 @@ func UpdateTags(conn networkmanageriface.NetworkManagerAPI, identifier string, o
TagKeys: aws.StringSlice(removedTags.IgnoreAWS().Keys()),
}
- _, err := conn.UntagResource(input)
+ _, err := conn.UntagResourceWithContext(ctx, input)
if err != nil {
return fmt.Errorf("error untagging resource (%s): %w", identifier, err)
@@ -82,7 +90,7 @@ func UpdateTags(conn networkmanageriface.NetworkManagerAPI, identifier string, o
Tags: Tags(updatedTags.IgnoreAWS()),
}
- _, err := conn.TagResource(input)
+ _, err := conn.TagResourceWithContext(ctx, input)
if err != nil {
return fmt.Errorf("error tagging resource (%s): %w", identifier, err)
|
gen/tags: Generate 'WithContext' variants of AWS SDK for Go v1 tagging functions for networkmanager.
|
terraform-providers_terraform-provider-aws
|
train
|
7fbdde642df11507cedd1387499cb50afa2f28f8
|
diff --git a/tests/app/build_ui.py b/tests/app/build_ui.py
index <HASH>..<HASH> 100644
--- a/tests/app/build_ui.py
+++ b/tests/app/build_ui.py
@@ -17,9 +17,7 @@ def build_filter_props(buttons):
Args:
buttons (list): list of pyxley.Filter components.
"""
- ui = UILayout(
- "PyxleyChart",
- "component_id")
+ ui = UILayout("PyxleyChart")
for b in buttons:
ui.add_filter(b)
|
modified uilayout for filters call in tests/app/buildui.py
|
stitchfix_pyxley
|
train
|
26d77228f54df298c0d09a8f97687b1d49de9c82
|
diff --git a/bundles/BlockManagerBundle/Controller/API/V1/LayoutController.php b/bundles/BlockManagerBundle/Controller/API/V1/LayoutController.php
index <HASH>..<HASH> 100644
--- a/bundles/BlockManagerBundle/Controller/API/V1/LayoutController.php
+++ b/bundles/BlockManagerBundle/Controller/API/V1/LayoutController.php
@@ -68,20 +68,26 @@ class LayoutController extends Controller
/**
* Loads either the draft status or published status of specified layout.
*
+ * If a query param "published" with value of "true" is provided, published
+ * state will be loaded directly, without first loading the draft.
+ *
* @param int $layoutId
+ * @param \Symfony\Component\HttpFoundation\Request $request
*
* @return \Netgen\BlockManager\Serializer\Values\View
*/
- public function load($layoutId)
+ public function load($layoutId, Request $request)
{
$layout = null;
- try {
- $layout = $this->layoutService->loadLayoutDraft(
- $layoutId
- );
- } catch (NotFoundException $e) {
- // Do nothing
+ if ($request->query->get('published') !== 'true') {
+ try {
+ $layout = $this->layoutService->loadLayoutDraft(
+ $layoutId
+ );
+ } catch (NotFoundException $e) {
+ // Do nothing
+ }
}
if (!$layout instanceof Layout) {
|
Make it possible to load published layout directly
|
netgen-layouts_layouts-core
|
train
|
70055af1f2876c24e66f3f58d7ca435cd828698f
|
diff --git a/awesomplete.js b/awesomplete.js
index <HASH>..<HASH> 100644
--- a/awesomplete.js
+++ b/awesomplete.js
@@ -383,7 +383,7 @@ if (typeof self !== "undefined") {
}
// Expose Awesomplete as a CJS module
-if (typeof exports === "object") {
+if (typeof module === "object" && module.exports) {
module.exports = _;
}
|
Fix issue when an element with ID of `exports` is defined in the browser.
Elements with IDs automatically have their IDs exposed. This causes errors
where `module` is not defined, and yet `module.exports = _` is run. This also
aligns the export with UMD.
|
LeaVerou_awesomplete
|
train
|
2ca75d52e33f136c4fed4d776ea2c42cd244834f
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -171,7 +171,7 @@ CompileModules.prototype.compileAndCacheModules = function (modulePaths, srcDir,
path.join(cacheDir, path.basename(outputPath)) : cacheDir;
// Outputs the compiled modules to the cache.
- mkdirp(target);
+ mkdirp.sync(target);
container.write(target);
var outputHash = [],
|
Synchronously create the cacheDir
ENOTDIR, error were thrown.
|
mmun_broccoli-es6-module-transpiler
|
train
|
6a22861f4c52a420b3bb9adc21e1199b81cee985
|
diff --git a/lib/msgr.rb b/lib/msgr.rb
index <HASH>..<HASH> 100644
--- a/lib/msgr.rb
+++ b/lib/msgr.rb
@@ -4,6 +4,7 @@ require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/hash/reverse_merge'
require 'msgr/logging'
require 'msgr/binding'
@@ -22,22 +23,20 @@ require 'msgr/railtie' if defined? Rails
module Msgr
class << self
+ attr_accessor :client
+ delegate :publish, to: :client
+
def logger
- @logger ||= Logger.new($stdout).tap do |logger|
- logger.level = Logger::Severity::INFO
+ if @logger.nil?
+ @logger = Logger.new $stdout
+ @logger.level = Logger::Severity::INFO
end
+
+ @logger
end
def logger=(logger)
@logger = logger
end
-
- def start
- # stub
- end
-
- def publish
- # stub
- end
end
end
|
Improve logger setting. Set to false to disable logging.
|
jgraichen_msgr
|
train
|
bbbe72827b5456e7c6d382a2cba311050db756c5
|
diff --git a/molo/core/tests/test_commands.py b/molo/core/tests/test_commands.py
index <HASH>..<HASH> 100644
--- a/molo/core/tests/test_commands.py
+++ b/molo/core/tests/test_commands.py
@@ -1,22 +1,24 @@
+import json
+
from django.test import TestCase
from molo.core.tests.base import MoloTestCaseMixin
+from molo.core.models import ArticlePageRecommendedSections
from molo.core.management.commands.move_page_links_to_recomended_articles import convert_articles # noqa
-body = [
- {
- "type": "paragraph",
- "value": "paragraph 1"
- },
- {
+
+def fake_page_stream_block(id_):
+ return {
"type": "page",
- "value": 48
- },
- {
+ "value": id_
+ }
+
+
+def fake_pragraph_stream_block():
+ return {
"type": "paragraph",
- "value": "paragraph 1"
- },
-]
+ "value": "paragraph content"
+ }
class TestCommands(MoloTestCaseMixin, TestCase):
@@ -29,5 +31,91 @@ class TestCommands(MoloTestCaseMixin, TestCase):
def setUp(self):
self.mk_main()
+ self.linked_article = self.mk_article(self.section_index)
+ self.main_article = self.mk_article(self.section_index)
+ self.body = [fake_page_stream_block(self.linked_article.id)]
+ setattr(self.main_article, 'body', json.dumps(self.body))
+ self.main_article.save()
+
+ def assert_recommended_article_equal(self, ra1, ra2):
+ '''
+ This function check the page and recommended articles
+
+ It is necessary because RA Objects are destroyed and re-created
+ during
+ '''
+ self.assertEqual(ra1.page.specific, ra2.page.specific)
+ self.assertEqual(ra1.recommended_article.specific,
+ ra2.recommended_article.specific)
+
def test_convert_articles(self):
+
+ self.assertEqual(self.main_article.body.stream_data, self.body)
+ self.assertEqual(
+ ArticlePageRecommendedSections.objects.count(), 0
+ )
+
convert_articles()
+
+ self.main_article.refresh_from_db()
+ self.assertEqual(self.main_article.body.stream_data, [])
+ self.assertEqual(
+ ArticlePageRecommendedSections.objects.count(), 1)
+ rec_art = ArticlePageRecommendedSections.objects.first()
+
+ self.assertEqual(rec_art.page, self.main_article)
+ self.assertEqual(rec_art.recommended_article.specific,
+ self.linked_article)
+
+ def test_convert_article_body_____(self):
+ '''
+ Test the existing recommended articles are preserved
+ '''
+ linked_article_1 = self.mk_article(self.section_index,
+ title="linked_article_1")
+ linked_article_2 = self.mk_article(self.section_index,
+ title="linked_article_2")
+
+ rec_art1 = ArticlePageRecommendedSections.objects.create(
+ page=self.main_article,
+ recommended_article=linked_article_1)
+ rec_art2 = ArticlePageRecommendedSections.objects.create(
+ page=self.main_article,
+ recommended_article=linked_article_2)
+ self.assertEqual(ArticlePageRecommendedSections.objects.count(), 2)
+
+ convert_articles()
+
+ self.main_article.refresh_from_db()
+ self.assertEqual(self.main_article.body.stream_data, [])
+ self.assertEqual(
+ ArticlePageRecommendedSections.objects.count(), 3
+ )
+
+ rec_arts = list(self.main_article.recommended_articles.all())
+
+ # check that ordering follows the pattern of linked articles
+ # first, existing recommended articles afterwards
+ self.assertEqual(rec_arts[0].page.specific, self.main_article)
+ self.assertEqual(rec_arts[0].recommended_article.specific,
+ self.linked_article)
+ self.assert_recommended_article_equal(rec_arts[1], rec_art1)
+ self.assert_recommended_article_equal(rec_arts[2], rec_art2)
+
+ def test_convert_article_body_no_duplicates(self):
+ # create Rec Art object with the same linked page as
+ # the embedded page link
+ rec_art1 = ArticlePageRecommendedSections.objects.create(
+ page=self.main_article,
+ recommended_article=self.linked_article)
+
+ self.assertEqual(
+ ArticlePageRecommendedSections.objects.count(), 1)
+
+ convert_articles()
+
+ self.assertEqual(
+ ArticlePageRecommendedSections.objects.count(), 1)
+
+ [rec_art] = self.main_article.recommended_articles.all()
+ self.assert_recommended_article_equal(rec_art, rec_art1)
|
Test expected behaviour for converting embedded page links to RAs
RA = Recommended Articles
|
praekeltfoundation_molo
|
train
|
6689b069f7a571f64c47bd7443d1053559476181
|
diff --git a/pyOCD/rtos/rtx5.py b/pyOCD/rtos/rtx5.py
index <HASH>..<HASH> 100644
--- a/pyOCD/rtos/rtx5.py
+++ b/pyOCD/rtos/rtx5.py
@@ -259,6 +259,8 @@ class RTX5ThreadProvider(ThreadProvider):
return False
log.debug('init(), found osRtxInfo')
self._threads = {}
+ self._target.root_target.subscribe(Target.EVENT_POST_FLASH_PROGRAM, self.event_handler)
+ self._target.subscribe(Target.EVENT_POST_RESET, self.event_handler)
return True
def get_threads(self):
@@ -313,6 +315,12 @@ class RTX5ThreadProvider(ThreadProvider):
self._threads[thread] = RTXTargetThread(self._target_context, self, thread)
thread = self._target_context.read32(thread+DELAYNEXT_OFFSET)
+ # Create fake handler mode thread.
+ if self.get_ipsr() > 0:
+ log.debug("creating handler mode thread")
+ t = HandlerModeThread(self._target_context, self)
+ self._threads[t.unique_id] = t
+
log.debug('found %d threads' % len(self._threads))
def get_thread(self, threadId):
|
Add HandlerModeThread and subsribe to flast&reset events
|
mbedmicro_pyOCD
|
train
|
428af79284280246e1a0294e4af7b9b5fc11b075
|
diff --git a/cf/terminal/ui.go b/cf/terminal/ui.go
index <HASH>..<HASH> 100644
--- a/cf/terminal/ui.go
+++ b/cf/terminal/ui.go
@@ -3,6 +3,7 @@ package terminal
import (
"fmt"
"io"
+ "os"
"strings"
"github.com/vito/go-interact/interact"
@@ -315,6 +316,10 @@ func (ui *terminalUI) NotifyUpdateIfNeeded(config coreconfig.Reader) {
func (ui *terminalUI) AskForPassword(prompt string) string {
interactivePrompt := interact.NewInteraction(prompt)
+ if _, ok := ui.stdin.(*os.File); !ok { //only set them for tests
+ interactivePrompt.Input = ui.stdin
+ interactivePrompt.Output = ui.stdout
+ }
var response interact.Password
interactivePrompt.Resolve(interact.Required(&response)) // Explicitly ignoring error because blank is the default value on error
return string(response)
|
ok, only set them in tests
[Finishes #<I>]
|
cloudfoundry_cli
|
train
|
23911bbd7fa6f46500ec9bcefee69f0822917a58
|
diff --git a/src/org/joml/Matrix4d.java b/src/org/joml/Matrix4d.java
index <HASH>..<HASH> 100644
--- a/src/org/joml/Matrix4d.java
+++ b/src/org/joml/Matrix4d.java
@@ -6878,10 +6878,7 @@ public class Matrix4d implements Externalizable {
dirY = centerY - eyeY;
dirZ = centerZ - eyeZ;
// Normalize direction
- double invDirLength = 1.0 / Math.sqrt(
- (eyeX - centerX) * (eyeX - centerX)
- + (eyeY - centerY) * (eyeY - centerY)
- + (eyeZ - centerZ) * (eyeZ - centerZ));
+ double invDirLength = 1.0 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
dirX *= invDirLength;
dirY *= invDirLength;
dirZ *= invDirLength;
diff --git a/src/org/joml/Matrix4f.java b/src/org/joml/Matrix4f.java
index <HASH>..<HASH> 100644
--- a/src/org/joml/Matrix4f.java
+++ b/src/org/joml/Matrix4f.java
@@ -5205,10 +5205,7 @@ public class Matrix4f implements Externalizable {
dirY = centerY - eyeY;
dirZ = centerZ - eyeZ;
// Normalize direction
- float invDirLength = 1.0f / (float) Math.sqrt(
- (eyeX - centerX) * (eyeX - centerX)
- + (eyeY - centerY) * (eyeY - centerY)
- + (eyeZ - centerZ) * (eyeZ - centerZ));
+ float invDirLength = 1.0f / (float) Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
dirX *= invDirLength;
dirY *= invDirLength;
dirZ *= invDirLength;
|
Improve Matrix4.lookAt() as suggested in #<I>
|
JOML-CI_JOML
|
train
|
858c0117851de801222a3c80538e9edc5a766f28
|
diff --git a/lib/ohai/mixin/string.rb b/lib/ohai/mixin/string.rb
index <HASH>..<HASH> 100644
--- a/lib/ohai/mixin/string.rb
+++ b/lib/ohai/mixin/string.rb
@@ -17,6 +17,11 @@
#
class String
+ # Add string function to handle WMI property conversion to json hash keys
+ # Makes an underscored, lowercase form from the expression in the string.
+ # underscore will also change ’::’ to ’/’ to convert namespaces to paths.
+ # This should implement the same functionality as underscore method in
+ # ActiveSupport::CoreExtensions::String::Inflections
def wmi_underscore
self.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase
|
Added comments to wmi_underscore method
|
chef_ohai
|
train
|
8b3fd99df24f5ac72856fab7bf4af85718873f0b
|
diff --git a/d1_mn_generic/src/setup.py b/d1_mn_generic/src/setup.py
index <HASH>..<HASH> 100755
--- a/d1_mn_generic/src/setup.py
+++ b/d1_mn_generic/src/setup.py
@@ -66,8 +66,8 @@ setup(
# Dependencies that are available through PYPI / easy_install.
install_requires=[
- 'dataone.common == 1.1.0',
- 'dataone.libclient == 1.1.0',
+ 'dataone.common >= 1.1.0',
+ 'dataone.libclient >= 1.2.0',
'dataone.certificate_extensions == 1.1.0',
'dataone.cli >= 1.0.0',
'django == 1.4.1',
|
Updated dependencies to use libclient <I> and to pick the latest version of common and libclient, instead of a fixed version. At first, I was thinking that using fixed versions would be safer. But I always have the latest versions of common and libclient in my development environment, so those are the ones that the latest version of GMN is tested with.
|
DataONEorg_d1_python
|
train
|
eb37f4a2859414c988c4012eac427c64518cbd00
|
diff --git a/test/runtime/samples/dynamic-element-animation-2/_config.js b/test/runtime/samples/dynamic-element-animation-2/_config.js
index <HASH>..<HASH> 100644
--- a/test/runtime/samples/dynamic-element-animation-2/_config.js
+++ b/test/runtime/samples/dynamic-element-animation-2/_config.js
@@ -59,7 +59,7 @@ export default {
originalParagraphGetBoundingClientRect;
},
- async test({ assert, component, target, raf }) {
+ async test({ assert, component, raf }) {
// switch tag and things at the same time
await component.update('p', [
{ id: 5, name: 'e' },
diff --git a/test/runtime/samples/if-block-else-update/_config.js b/test/runtime/samples/if-block-else-update/_config.js
index <HASH>..<HASH> 100644
--- a/test/runtime/samples/if-block-else-update/_config.js
+++ b/test/runtime/samples/if-block-else-update/_config.js
@@ -1,7 +1,7 @@
export default {
- async test({ assert, component, target, window }) {
+ async test({ assert, target, window }) {
const [btn1, btn2] = target.querySelectorAll('button');
-
+
const clickEvent = new window.MouseEvent('click');
await btn2.dispatchEvent(clickEvent);
@@ -23,7 +23,7 @@ export default {
<hr>
foo!
`);
-
+
await btn2.dispatchEvent(clickEvent);
assert.htmlEqual(target.innerHTML, `
<button>Toggle foo</button>
@@ -33,7 +33,7 @@ export default {
<hr>
foo!
`);
-
+
await btn1.dispatchEvent(clickEvent);
assert.htmlEqual(target.innerHTML, `
<button>Toggle foo</button>
diff --git a/test/runtime/samples/inline-style/_config.js b/test/runtime/samples/inline-style/_config.js
index <HASH>..<HASH> 100644
--- a/test/runtime/samples/inline-style/_config.js
+++ b/test/runtime/samples/inline-style/_config.js
@@ -3,7 +3,7 @@ export default {
<div style="color: red;"></div>
`,
- test({ assert, component, target, window }) {
+ test({ assert, target, window }) {
const div = target.querySelector('div');
const styles = window.getComputedStyle(div);
diff --git a/test/runtime/samples/key-block-component-slot/_config.js b/test/runtime/samples/key-block-component-slot/_config.js
index <HASH>..<HASH> 100644
--- a/test/runtime/samples/key-block-component-slot/_config.js
+++ b/test/runtime/samples/key-block-component-slot/_config.js
@@ -5,7 +5,7 @@ export default {
props: {
logs
},
- async test({ assert, component, target, raf }) {
+ async test({ assert, target }) {
assert.deepEqual(logs, ['mount']);
const button = target.querySelector('button');
|
[chore] fix lint (#<I>)
|
sveltejs_svelte
|
train
|
f0b1426a9d0bda74b1586d1664eddcac366af150
|
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/detect/Naming.java b/findbugs/src/java/edu/umd/cs/findbugs/detect/Naming.java
index <HASH>..<HASH> 100644
--- a/findbugs/src/java/edu/umd/cs/findbugs/detect/Naming.java
+++ b/findbugs/src/java/edu/umd/cs/findbugs/detect/Naming.java
@@ -75,6 +75,8 @@ public class Naming extends PreorderVisitor implements Detector {
}
private boolean checkSuper(XMethod m, HashSet<XMethod> others) {
+ if (m.isStatic()) return false;
+ if (m.getName().equals("<init>") || m.getName().equals("<clinit>")) return false;
for (XMethod m2 : others) {
try {
if (confusingMethodNames(m, m2)
@@ -118,6 +120,8 @@ public class Naming extends PreorderVisitor implements Detector {
}
private boolean checkNonSuper(XMethod m, HashSet<XMethod> others) {
+ if (m.isStatic()) return false;
+ if (m.getName().startsWith("<init>") || m.getName().startsWith("<clinit>")) return false;
for (XMethod m2 : others) {
if (confusingMethodNames(m,m2)) {
bugReporter.reportBug(new BugInstance(this, "NM_CONFUSING", LOW_PRIORITY)
|
don't report signature package confusion on static methods or constructors
git-svn-id: <URL>
|
spotbugs_spotbugs
|
train
|
94bdf595301b970281ae6b93cb4676d9aad12e98
|
diff --git a/server/src/main/java/org/jboss/as/server/ServerEnvironment.java b/server/src/main/java/org/jboss/as/server/ServerEnvironment.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/org/jboss/as/server/ServerEnvironment.java
+++ b/server/src/main/java/org/jboss/as/server/ServerEnvironment.java
@@ -227,9 +227,9 @@ public class ServerEnvironment extends ProcessEnvironment implements Serializabl
protected static final String DOMAIN_BASE_DIR = "jboss.domain.base.dir";
protected static final String DOMAIN_CONFIG_DIR = "jboss.domain.config.dir";
- private static final Set<String> ILLEGAL_PROPERTIES = new HashSet<String>(Arrays.asList(JAVA_EXT_DIRS, HOME_DIR,
- "modules.path", SERVER_BASE_DIR, SERVER_CONFIG_DIR, SERVER_DATA_DIR, SERVER_DEPLOY_DIR, SERVER_LOG_DIR,
- BOOTSTRAP_MAX_THREADS, CONTROLLER_TEMP_DIR));
+ private static final Set<String> ILLEGAL_PROPERTIES = new HashSet<String>(Arrays.asList(DOMAIN_BASE_DIR,
+ DOMAIN_CONFIG_DIR, JAVA_EXT_DIRS, HOME_DIR, "modules.path", SERVER_BASE_DIR, SERVER_CONFIG_DIR,
+ SERVER_DATA_DIR, SERVER_DEPLOY_DIR, SERVER_LOG_DIR, BOOTSTRAP_MAX_THREADS, CONTROLLER_TEMP_DIR));
private static final Set<String> BOOT_PROPERTIES = new HashSet<String>(Arrays.asList(BUNDLES_DIR, SERVER_TEMP_DIR,
NODE_NAME, SERVER_NAME, HOST_NAME, QUALIFIED_HOST_NAME));
@@ -354,14 +354,12 @@ public class ServerEnvironment extends ProcessEnvironment implements Serializabl
tmp = getFileFromProperty(DOMAIN_BASE_DIR, props);
if (tmp != null) {
this.domainBaseDir = tmp;
- SecurityActions.setSystemProperty(DOMAIN_BASE_DIR, this.domainBaseDir.getAbsolutePath());
} else {
this.domainBaseDir = null;
}
tmp = getFileFromProperty(DOMAIN_CONFIG_DIR, props);
if (tmp != null) {
this.domainConfigurationDir = tmp;
- SecurityActions.setSystemProperty(DOMAIN_CONFIG_DIR, this.domainConfigurationDir.getAbsolutePath());
} else {
this.domainConfigurationDir = null;
}
@@ -416,6 +414,15 @@ public class ServerEnvironment extends ProcessEnvironment implements Serializabl
SecurityActions.setSystemProperty(SERVER_LOG_DIR, serverLogDir.getAbsolutePath());
SecurityActions.setSystemProperty(SERVER_TEMP_DIR, serverTempDir.getAbsolutePath());
+ if(launchType.getProcessType() == ProcessType.DOMAIN_SERVER) {
+ if(domainBaseDir != null) {
+ SecurityActions.setSystemProperty(DOMAIN_BASE_DIR, domainBaseDir.getAbsolutePath());
+ }
+ if(domainConfigurationDir != null) {
+ SecurityActions.setSystemProperty(DOMAIN_CONFIG_DIR, domainConfigurationDir.getAbsolutePath());
+ }
+ }
+
// Register the vfs module as URLStreamHandlerFactory
try {
ModuleLoader bootLoader = Module.getBootModuleLoader();
|
setup sys properties in install()
was: a<I>f4bbc2cfcbaedc4a<I>dedca6fb<I>a<I>
|
wildfly_wildfly-core
|
train
|
5e0a020cb1d17c0996d39a417ae0fcb4dad70850
|
diff --git a/tests/functional/test_awsclient.py b/tests/functional/test_awsclient.py
index <HASH>..<HASH> 100644
--- a/tests/functional/test_awsclient.py
+++ b/tests/functional/test_awsclient.py
@@ -89,9 +89,9 @@ def test_can_iterate_logs(stubbed_session):
logGroupName='loggroup', interleaved=True).returns({
"events": [{
"logStreamName": "logStreamName",
- "timestamp": 0,
+ "timestamp": 1501278366000,
"message": "message",
- "ingestionTime": 0,
+ "ingestionTime": 1501278366000,
"eventId": "eventId"
}],
})
@@ -100,7 +100,7 @@ def test_can_iterate_logs(stubbed_session):
awsclient = TypedAWSClient(stubbed_session)
logs = list(awsclient.iter_log_events('loggroup'))
- timestamp = datetime.datetime.fromtimestamp(0)
+ timestamp = datetime.datetime.fromtimestamp(1501278366)
assert logs == [
{'logStreamName': 'logStreamName',
# We should have converted the ints to timestamps.
|
Use proper timetsamp for win py3 compat
You can't create a timestamp of time 0 on windows in py3.
|
aws_chalice
|
train
|
17d33e846eab224d5638575263202489c57d11d8
|
diff --git a/nabu/data/security/CNabuUser.php b/nabu/data/security/CNabuUser.php
index <HASH>..<HASH> 100644
--- a/nabu/data/security/CNabuUser.php
+++ b/nabu/data/security/CNabuUser.php
@@ -71,7 +71,7 @@ class CNabuUser extends CNabuUserBase
public function setPassword($password)
{
- $this->setValue('nb_user_password', CNabuUser::encodePassword($password));
+ $this->setValue('nb_user_passwd', CNabuUser::encodePassword($password));
}
/**
|
Solve issue when use setPassword to change password in database
|
nabu-3_core
|
train
|
003c0ceabdddafbc30685bfb9de22e24bafd5b27
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java
@@ -241,6 +241,19 @@ public abstract class ODatabaseDocumentAbstract extends OListenerManger<ODatabas
public ODatabaseDocument delete(final ORecord iRecord, final OPERATION_MODE iMode) {
checkIfActive();
+ ODirtyManager dirtyManager = ORecordInternal.getDirtyManager(iRecord);
+ if (iRecord instanceof OElement && dirtyManager != null && dirtyManager.getReferences() != null && !dirtyManager.getReferences()
+ .isEmpty()) {
+ if (((OElement) iRecord).isEdge() || ((OElement) iRecord).isVertex() && !getTransaction().isActive()) {
+ begin();
+ try {
+ currentTx.deleteRecord(iRecord, iMode);
+ return this;
+ } finally {
+ commit();
+ }
+ }
+ }
currentTx.deleteRecord(iRecord, iMode);
return this;
}
@@ -2385,6 +2398,19 @@ public abstract class ODatabaseDocumentAbstract extends OListenerManger<ODatabas
public <RET extends ORecord> RET save(ORecord iRecord, String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate,
final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback) {
checkOpenness();
+
+ ODirtyManager dirtyManager = ORecordInternal.getDirtyManager(iRecord);
+ if (iRecord instanceof OElement && dirtyManager != null && dirtyManager.getReferences() != null && !dirtyManager.getReferences()
+ .isEmpty()) {
+ if (((OElement) iRecord).isVertex() || ((OElement) iRecord).isEdge() && !getTransaction().isActive()) {
+ return saveGraph(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback);
+ }
+ }
+ return saveInternal(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback);
+ }
+
+ private <RET extends ORecord> RET saveInternal(ORecord iRecord, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate,
+ ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback) {
if (iRecord instanceof OVertexDelegate) {
iRecord = iRecord.getRecord();
}
@@ -2425,6 +2451,17 @@ public abstract class ODatabaseDocumentAbstract extends OListenerManger<ODatabas
return (RET) doc;
}
+ private <RET extends ORecord> RET saveGraph(ORecord iRecord, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate,
+ ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback) {
+ begin();
+ try {
+ return saveInternal(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback);
+ } finally {
+ commit();
+ }
+
+ }
+
/**
* Deletes a document. Behavior depends by the current running transaction if any. If no transaction is running then the record is
* deleted immediately. If an Optimistic transaction is running then the record will be deleted at commit time. The current
|
Add automatic begin/commit when manipulating edges
|
orientechnologies_orientdb
|
train
|
e951f31b2ccf00b579971ac4128b4ca2a98e714a
|
diff --git a/packages/perspective-bench/bench/versions.js b/packages/perspective-bench/bench/versions.js
index <HASH>..<HASH> 100644
--- a/packages/perspective-bench/bench/versions.js
+++ b/packages/perspective-bench/bench/versions.js
@@ -34,7 +34,7 @@ const JPMC_VERSIONS = [
const FINOS_VERSIONS = ["0.3.1", "0.3.0", "0.3.0-rc.3", "0.3.0-rc.2", "0.3.0-rc.1"];
-const UMD_VERSIONS = ["0.4.8", "0.4.7", "0.4.6", "0.4.5", "0.4.4", "0.4.2", "0.4.1", "0.4.0", "0.3.9", "0.3.8", "0.3.7", "0.3.6"];
+const UMD_VERSIONS = ["0.5.2", "0.5.1", "0.5.0", "0.4.8", "0.4.7", "0.4.6", "0.4.5", "0.4.4", "0.4.2", "0.4.1", "0.4.0", "0.3.9", "0.3.8", "0.3.7", "0.3.6"];
async function run() {
await PerspectiveBench.run("master", "bench/perspective.benchmark.js", `http://${process.env.PSP_DOCKER_PUPPETEER ? `localhost` : `host.docker.internal`}:8080/perspective.js`, {
|
add <I>.x to benchmark
|
finos_perspective
|
train
|
9859dc11138047e75a956fe6edba5e408fcd17cd
|
diff --git a/src/edeposit/amqp/ftp/proftpd_monitor.py b/src/edeposit/amqp/ftp/proftpd_monitor.py
index <HASH>..<HASH> 100755
--- a/src/edeposit/amqp/ftp/proftpd_monitor.py
+++ b/src/edeposit/amqp/ftp/proftpd_monitor.py
@@ -5,24 +5,22 @@
#
#= Imports ====================================================================
import sys
+import os.path
-
-#= Variables ==================================================================
-
+import sh
+#= Variables ==================================================================
#= Functions & objects ========================================================
-def read_stdin():
- while True:
+def _read_stdin():
+ line = sys.stdin.readline()
+ while line:
+ yield line
line = sys.stdin.readline()
- if line:
- yield line
- else:
- break
-def parse_line(line):
+def _parse_line(line):
line, timestamp = line.rsplit(",", 1)
line, command = line.rsplit(",", 1)
path, username = line.rsplit(",", 1)
@@ -34,10 +32,33 @@ def parse_line(line):
"path": path,
}
-#= Main program ===============================================================
-if __name__ == '__main__':
- for line in read_stdin():
- if "," not in line or "[" in line:
+
+def process_request(parsed):
+ print parsed
+
+
+def process_file(file_iterator):
+ for line in file_iterator:
+ if "," not in line or "[" in line: # TODO: remove [ check
continue
- print parse_line(line)
+ parsed = _parse_line(line)
+
+ if not (parsed["command"] in ["STOR", "APPE", "STOU"]):
+ continue
+
+ if not os.path.exists(parsed["path"]):
+ continue
+
+ process_request(parsed)
+
+
+#= Main program ===============================================================
+if __name__ == '__main__':
+ try:
+ if len(sys.argv) > 1:
+ process_file(sh.tail("-f", sys.argv[1], _iter=True))
+ else:
+ process_file(_read_stdin())
+ except KeyboardInterrupt:
+ sys.exit(0)
|
Added parsing of stdin/file given by commandline arguments.
|
edeposit_edeposit.amqp.ftp
|
train
|
6d12ef7968a484eb95802411c277260c3b867c5b
|
diff --git a/src/js/pannellum.js b/src/js/pannellum.js
index <HASH>..<HASH> 100644
--- a/src/js/pannellum.js
+++ b/src/js/pannellum.js
@@ -1685,10 +1685,10 @@ function renderInitCallback() {
preview = undefined;
}
loaded = true;
-
- animateInit();
fireEvent('load');
+
+ animateInit();
}
/**
|
Temporarily revert "Move `load` event to fire after rendering instead of before (#<I>)."
This reverts commit df4c<I>dd<I>b<I>fb3fa<I>cdab4dd<I>f<I>d<I> temporarily to
push a new point release.
|
mpetroff_pannellum
|
train
|
a7755eca251ac961229780ec83edafa5542bbdc7
|
diff --git a/nodeconductor/structure/log.py b/nodeconductor/structure/log.py
index <HASH>..<HASH> 100644
--- a/nodeconductor/structure/log.py
+++ b/nodeconductor/structure/log.py
@@ -139,6 +139,7 @@ class ServiceSettingsEventLogger(EventLogger):
error_message = six.text_type
class Meta:
+ nullable_fields = ['error_message']
event_types = ('service_settings_sync_failed',
'service_settings_recovered')
|
Fix ServiceSettings event logger
- NC-<I>
|
opennode_waldur-core
|
train
|
93529de8fc8b4f497b74363dd9e655cd636b0376
|
diff --git a/satpy/readers/__init__.py b/satpy/readers/__init__.py
index <HASH>..<HASH> 100644
--- a/satpy/readers/__init__.py
+++ b/satpy/readers/__init__.py
@@ -540,27 +540,10 @@ def load_readers(filenames=None, reader=None, reader_kwargs=None):
"""
reader_instances = {}
- if not filenames and not reader:
- # used for an empty Scene
- return {}
- if reader and filenames is not None and not filenames:
- # user made a mistake in their glob pattern
- raise ValueError("'filenames' was provided but is empty.")
- if not filenames:
- LOG.warning("'filenames' required to create readers and load data")
+ if _early_exit(filenames, reader):
return {}
- if reader is None and isinstance(filenames, dict):
- # filenames is a dictionary of reader_name -> filenames
- reader = list(filenames.keys())
- remaining_filenames = set(f for fl in filenames.values() for f in fl)
- elif reader and isinstance(filenames, dict):
- # filenames is a dictionary of reader_name -> filenames
- # but they only want one of the readers
- filenames = filenames[reader]
- remaining_filenames = set(filenames or [])
- else:
- remaining_filenames = set(filenames or [])
+ reader, filenames, remaining_filenames = _get_reader_and_filenames(reader, filenames)
(reader_kwargs, reader_kwargs_without_filter) = _get_reader_kwargs(reader, reader_kwargs)
for idx, reader_configs in enumerate(configs_for_reader(reader)):
@@ -591,15 +574,51 @@ def load_readers(filenames=None, reader=None, reader_kwargs=None):
if not remaining_filenames:
break
+ _check_remaining_files(remaining_filenames)
+ _check_reader_instances(reader_instances)
+ return reader_instances
+
+
+def _early_exit(filenames, reader):
+ if not filenames and not reader:
+ # used for an empty Scene
+ return True
+ if reader and filenames is not None and not filenames:
+ # user made a mistake in their glob pattern
+ raise ValueError("'filenames' was provided but is empty.")
+ if not filenames:
+ LOG.warning("'filenames' required to create readers and load data")
+ return True
+ return False
+
+
+def _get_reader_and_filenames(reader, filenames):
+ if reader is None and isinstance(filenames, dict):
+ # filenames is a dictionary of reader_name -> filenames
+ reader = list(filenames.keys())
+ remaining_filenames = set(f for fl in filenames.values() for f in fl)
+ elif reader and isinstance(filenames, dict):
+ # filenames is a dictionary of reader_name -> filenames
+ # but they only want one of the readers
+ filenames = filenames[reader]
+ remaining_filenames = set(filenames or [])
+ else:
+ remaining_filenames = set(filenames or [])
+ return reader, filenames, remaining_filenames
+
+
+def _check_remaining_files(remaining_filenames):
if remaining_filenames:
LOG.warning("Don't know how to open the following files: {}".format(str(remaining_filenames)))
+
+
+def _check_reader_instances(reader_instances):
if not reader_instances:
raise ValueError("No supported files found")
if not any(list(r.available_dataset_ids) for r in reader_instances.values()):
raise ValueError("No dataset could be loaded. Either missing "
"requirements (such as Epilog, Prolog) or none of the "
"provided files match the filter parameters.")
- return reader_instances
def _get_reader_kwargs(reader, reader_kwargs):
|
Refactor 'load_readers'
|
pytroll_satpy
|
train
|
aeaf7655a71c3306b1e42bcd257e2074a00923b2
|
diff --git a/sslyze/__main__.py b/sslyze/__main__.py
index <HASH>..<HASH> 100644
--- a/sslyze/__main__.py
+++ b/sslyze/__main__.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
+from __future__ import print_function
import os
import sys
@@ -7,7 +8,6 @@ import sys
if not hasattr(sys,"frozen"):
sys.path.insert(1, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
-from __future__ import print_function
from sslyze.cli.output_hub import OutputHub
from sslyze.cli import FailedServerScan, CompletedServerScan
from sslyze import __version__
diff --git a/sslyze/plugins/certificate_info_plugin.py b/sslyze/plugins/certificate_info_plugin.py
index <HASH>..<HASH> 100755
--- a/sslyze/plugins/certificate_info_plugin.py
+++ b/sslyze/plugins/certificate_info_plugin.py
@@ -142,6 +142,9 @@ class Certificate(object):
def __ne__(self, other):
return not self.__eq__(other)
+ def __hash__(self):
+ return hash(self.as_pem)
+
class CertificateInfoPlugin(plugin_base.PluginBase):
diff --git a/sslyze/plugins/heartbleed_plugin.py b/sslyze/plugins/heartbleed_plugin.py
index <HASH>..<HASH> 100644
--- a/sslyze/plugins/heartbleed_plugin.py
+++ b/sslyze/plugins/heartbleed_plugin.py
@@ -2,9 +2,7 @@
"""Plugin to test the server for CVE-2014-0160.
"""
-
-
-import new
+import types
from xml.etree.ElementTree import Element
from nassl import TLSV1, TLSV1_1, TLSV1_2, SSLV3
@@ -31,7 +29,7 @@ class HeartbleedPlugin(plugin_base.PluginBase):
# Awful hack #1: replace nassl.sslClient.do_handshake() with a heartbleed
# checking SSL handshake so that all the SSLyze options
# (startTLS, proxy, etc.) still work
- ssl_connection.do_handshake = new.instancemethod(do_handshake_with_heartbleed, ssl_connection, None)
+ ssl_connection.do_handshake = types.MethodType(do_handshake_with_heartbleed, ssl_connection)
heartbleed = None
try: # Perform the SSL handshake
|
Fixes for Python 3 compatibility
|
nabla-c0d3_sslyze
|
train
|
515c79c2644b4c6a2face4a92a02cbb03a796986
|
diff --git a/tests/Gush/Tests/Command/IssueShowCommandTest.php b/tests/Gush/Tests/Command/IssueShowCommandTest.php
index <HASH>..<HASH> 100644
--- a/tests/Gush/Tests/Command/IssueShowCommandTest.php
+++ b/tests/Gush/Tests/Command/IssueShowCommandTest.php
@@ -21,7 +21,7 @@ class IssueShowCommandTest extends BaseTestCase
{
public function testCommand()
{
- $this->httpClient->whenGet('repos/cordoval/gush/issues/60', [])->thenReturn(
+ $this->httpClient->whenGet('repos/cordoval/gush/issues/60')->thenReturn(
[
'number' => 60,
'state' => "open",
diff --git a/tests/Gush/Tests/Command/PullRequestMergeCommandTest.php b/tests/Gush/Tests/Command/PullRequestMergeCommandTest.php
index <HASH>..<HASH> 100644
--- a/tests/Gush/Tests/Command/PullRequestMergeCommandTest.php
+++ b/tests/Gush/Tests/Command/PullRequestMergeCommandTest.php
@@ -32,26 +32,38 @@ class PullRequestMergeCommandTest extends BaseTestCase
protected function expectShowPullRequest()
{
- $this->httpClient->whenGet(
- 'repos/cordoval/gush/pulls/40/merge',
- json_encode(['commit_message' => 'Merged using Gush'])
- )->thenReturn(
- [
- 'merged' => true,
- 'message' => 'Pull Request successfully merged.',
- ]
- );
+ $this->httpClient->whenGet('repos/cordoval/gush/pulls/40')
+ ->thenReturn(
+ [
+ 'number' => 60,
+ 'state' => "open",
+ 'user' => ['login' => 'weaverryan'],
+ 'assignee' => ['login' => 'cordoval'],
+ 'pull_request' => [],
+ 'milestone' => ['title' => "Conquer the world"],
+ 'labels' => [['name' => 'actionable'], ['name' => 'easy pick']],
+ 'title' => 'Write a behat test to launch strategy',
+ 'body' => 'Help me conquer the world. Teach them to use gush.',
+ 'base' => ['label' => 'master']
+ ]
+ )
+ ;
}
protected function expectPullRequestCommits()
{
- $this->httpClient->whenPut(
- 'repos/cordoval/gush/pulls/40/merge',
- json_encode(['commit_message' => 'Merged using Gush'])
- )->thenReturn(
+ $this->httpClient->whenGet('repos/cordoval/gush/pulls/40/commits')->thenReturn(
[
- 'merged' => true,
- 'message' => 'Pull Request successfully merged.',
+ [
+ 'sha' => '32fe234332fe234332fe234332fe234332fe2343',
+ 'commit' => ['message' => 'added merge pull request feature'],
+ 'author' => ['login' => 'cordoval']
+ ],
+ [
+ 'sha' => 'ab34567812345678123456781234567812345678',
+ 'commit' => ['message' => 'added final touches'],
+ 'author' => ['login' => 'cordoval']
+ ],
]
);
}
|
plug stubs on api calls
|
gushphp_gush
|
train
|
fec1e8ed4962badc0c10e1b56d8e5fafec60cc9b
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -34,7 +34,7 @@ from setuptools import setup, find_packages
setup(
name='thingamon',
- version='0.2.0',
+ version='0.2.1-dev',
description='AWS MQTT IoT Thing monitor',
long_description=__doc__,
url='https://github.com/mgk/thingamon/blob/master/README.md',
@@ -42,6 +42,10 @@ setup(
author_email='michael@keirnan.com',
packages=find_packages(exclude=["tests*"]),
include_package_data=True,
+ install_requires=[
+ 'paho-mqtt',
+ 'certifi '
+ ],
tests_require=['pytest'],
zip_safe=False,
platforms='any',
|
fix #2 - dependencies not installed
|
mgk_thingamon
|
train
|
dced3afed5d3d4c5ee1d66dff131a993e65892db
|
diff --git a/tests/Handlers/FatalHandlerTest.php b/tests/Handlers/FatalHandlerTest.php
index <HASH>..<HASH> 100644
--- a/tests/Handlers/FatalHandlerTest.php
+++ b/tests/Handlers/FatalHandlerTest.php
@@ -29,7 +29,8 @@ class FatalHandlerTest extends BaseRollbarTest
$errors = $result->errors();
- $stdOut = $errors[0]->thrownException()->getTrace()[0]['args'][2];
+ $trace = $errors[0]->thrownException()->getTrace();
+ $stdOut = $trace['args'][2];
/**
* Assert that the standard output contains the log message generated
@@ -67,7 +68,7 @@ class FatalHandlerTest extends BaseRollbarTest
* testRegisterAndHandle test. This way we can verify that the fatal handler
* triggers the log() method of the provider logger.
*/
- public function testHandleInternalPHP5()
+ public function handleInternalPHP5()
{
$logger = new StdOutLogger(self::$simpleConfig);
|
github-<I>: fix typo and some <I> issue
|
rollbar_rollbar-php
|
train
|
8620d99118bf91295068e84e87d5ef976af71f46
|
diff --git a/test/viewbridge.js b/test/viewbridge.js
index <HASH>..<HASH> 100644
--- a/test/viewbridge.js
+++ b/test/viewbridge.js
@@ -19,7 +19,6 @@ var baseTest = function(done) {
assert.equal(info.stats.templates[0], 'viewbridge.index');
jsdom.env('<div id=foo></div>', [info.file], function(err, window) {
var doc = window.document;
- assert.ok(!!window.jade || !!window.Hogan);
assert.ok(!!window.viewbridge);
assert.ok(!!window.viewbridge.index);
assert.equal(typeof window.viewbridge.index, 'function');
@@ -102,6 +101,19 @@ describe('viewbridge()', function() {
viewbridge(options, baseTest(done));
});
+ it('should load the Jade runtime in browser', function(done) {
+ var options = {
+ dir: jadedir
+ , output: path.join(deploydir, 'tmpljade.js')
+ };
+ viewbridge(options, function(err, info) {
+ jsdom.env(html, [info.file], function(err, window) {
+ assert.ok(!!window.jade, 'window.jade should be defined');
+ done();
+ });
+ });
+ });
+
it('should work with Hogan templates', function(done) {
var options = {
dir: hogandir
@@ -110,6 +122,20 @@ describe('viewbridge()', function() {
};
viewbridge(options, baseTest(done));
});
+
+ it('should load Hogan lib in browser', function(done) {
+ var options = {
+ dir: hogandir
+ , engine: 'hogan'
+ , output: path.join(deploydir, 'tmplhogan.js')
+ };
+ viewbridge(options, function(err, info) {
+ jsdom.env(html, [info.file], function(err, window) {
+ assert.ok(!!window.Hogan, 'window.Hogan should be defined');
+ done();
+ });
+ });
+ });
});
|
Template engine specific code pulled out into their own file/object
|
corymartin_viewbridge
|
train
|
5fbaa6c89712578d5319fd7493c49c1e5066eb9d
|
diff --git a/pointer/smudge.go b/pointer/smudge.go
index <HASH>..<HASH> 100644
--- a/pointer/smudge.go
+++ b/pointer/smudge.go
@@ -39,7 +39,7 @@ func downloadFile(writer io.Writer, oid, mediafile string) error {
return errors.New("open: " + err.Error())
}
- copyErr := copyFile(reader, writer, mediaWriter)
+ _, copyErr := io.Copy(mediaWriter, reader)
closeErr := mediaWriter.Close()
if copyErr != nil {
@@ -50,7 +50,13 @@ func downloadFile(writer io.Writer, oid, mediafile string) error {
return errors.New("close: " + closeErr.Error())
}
- return nil
+ file, err := os.Open(mediaWriter.Path)
+ if err != nil {
+ return err
+ }
+
+ _, err = io.Copy(writer, file)
+ return err
}
func readLocalFile(writer io.Writer, mediafile string) error {
@@ -60,13 +66,7 @@ func readLocalFile(writer io.Writer, mediafile string) error {
}
defer reader.Close()
- return copyFile(reader, writer)
-}
-
-func copyFile(reader io.ReadCloser, writers ...io.Writer) error {
- multiWriter := io.MultiWriter(writers...)
-
- _, err := io.Copy(multiWriter, reader)
+ _, err = io.Copy(writer, reader)
return err
}
|
write to a temp file first before streaming to stdout
|
git-lfs_git-lfs
|
train
|
9b157ab0d152213d828225c7b2ec379ff3f00b19
|
diff --git a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestInvoice.java b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestInvoice.java
index <HASH>..<HASH> 100644
--- a/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestInvoice.java
+++ b/profiles/killbill/src/test/java/org/killbill/billing/jaxrs/TestInvoice.java
@@ -26,7 +26,6 @@ import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
-import org.killbill.billing.api.FlakyRetryAnalyzer;
import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.client.KillBillClientException;
@@ -531,8 +530,7 @@ public class TestInvoice extends TestJaxrsBase {
assertEquals(killBillClient.getInvoicesForAccount(accountJson.getAccountId(), requestOptions).size(), 3);
}
- // Flaky, see https://github.com/killbill/killbill/issues/801
- @Test(groups = "slow", description = "Can create multiple external charges with same invoice and external keys", retryAnalyzer = FlakyRetryAnalyzer.class)
+ @Test(groups = "slow", description = "Can create multiple external charges with same invoice and external keys")
public void testExternalChargesWithSameInvoiceAndExternalKeys() throws Exception {
final Account accountJson = createAccountWithPMBundleAndSubscriptionAndWaitForFirstInvoice();
diff --git a/util/src/main/java/org/killbill/billing/util/export/dao/DatabaseExportDao.java b/util/src/main/java/org/killbill/billing/util/export/dao/DatabaseExportDao.java
index <HASH>..<HASH> 100644
--- a/util/src/main/java/org/killbill/billing/util/export/dao/DatabaseExportDao.java
+++ b/util/src/main/java/org/killbill/billing/util/export/dao/DatabaseExportDao.java
@@ -16,6 +16,7 @@
package org.killbill.billing.util.export.dao;
+import java.io.IOException;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.List;
@@ -34,10 +35,14 @@ import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.IDBI;
import org.skife.jdbi.v2.ResultIterator;
import org.skife.jdbi.v2.tweak.HandleCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Singleton
public class DatabaseExportDao {
+ private static final Logger logger = LoggerFactory.getLogger(DatabaseExportDao.class);
+
private final DatabaseSchemaDao databaseSchemaDao;
private final IDBI dbi;
@@ -172,7 +177,12 @@ public class DatabaseExportDao {
}
}
- out.write(row);
+ try {
+ out.write(row);
+ } catch (final IOException e) {
+ logger.warn("Unable to write row: {}", row, e);
+ throw e;
+ }
}
} finally {
iterator.close();
|
util, server: tests iteration
* Unmark TestInvoice test as flaky
* Add log line to debug sporadic H2 failures
|
killbill_killbill
|
train
|
f17e64e4f1bca045d0225882538fff8a9b95103c
|
diff --git a/src/main/java/net/openhft/chronicle/network/ConnectionStrategy.java b/src/main/java/net/openhft/chronicle/network/ConnectionStrategy.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/openhft/chronicle/network/ConnectionStrategy.java
+++ b/src/main/java/net/openhft/chronicle/network/ConnectionStrategy.java
@@ -111,4 +111,11 @@ public interface ConnectionStrategy extends Marshallable {
}
+ /**
+ * allows control of a backoff strategy
+ * @return how long in milliseconds to pause before attempting a reconnect
+ */
+ default long pauseMillisBeforeReconnect() {
+ return 500;
+ }
}
diff --git a/src/main/java/net/openhft/chronicle/network/connection/TcpChannelHub.java b/src/main/java/net/openhft/chronicle/network/connection/TcpChannelHub.java
index <HASH>..<HASH> 100755
--- a/src/main/java/net/openhft/chronicle/network/connection/TcpChannelHub.java
+++ b/src/main/java/net/openhft/chronicle/network/connection/TcpChannelHub.java
@@ -1277,7 +1277,10 @@ public class TcpChannelHub implements Closeable {
else
Jvm.warn().on(getClass(), "reconnecting due to unexpected exception", e);
closeSocket();
- Jvm.pause(500);
+
+ long pauseMs = connectionStrategy == null ? 500 : connectionStrategy.pauseMillisBeforeReconnect();
+ Jvm.pause(pauseMs);
+
}
} finally {
start = Long.MAX_VALUE;
|
added the following to allow clients to control the reconnect -
long pauseMs = connectionStrategy == null ? <I> : connectionStrategy.pauseMillisBeforeReconnect();
Jvm.pause(pauseMs);
|
OpenHFT_Chronicle-Network
|
train
|
efaefa3652cfc6581fe675be2a3c9e078469e652
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -512,6 +512,11 @@ IRC.prototype._getClient = function (job, create) {
create = (typeof create === 'boolean') ? create : true;
+ if (self.client) {
+ debug('using existing client instance. ' + self.client.id);
+ return Promise.resolve(self.client);
+ }
+
//
// get credentials
self.session.store.get(job.actor.id, function (err, creds) {
@@ -526,12 +531,15 @@ IRC.prototype._getClient = function (job, create) {
if ((!client) && (create)) {
//
// create a client
- return self._createClient(job.actor.id, creds).then(pending.resolve).catch(function (err) {console.log('err',err); pending.reject(err);});
+ return self._createClient(job.actor.id, creds).then(function (client) {
+ self.client = client;
+ pending.resolve(client);
+ }).catch(function (err) {console.log('err',err); pending.reject(err);});
} else if (client) {
//
// client already exists
- self.session.debug('returning existing client ' + client.id);
+ self.session.debug('using client from connection manager. ' + client.id);
// make sure we have listeners for this session
//
@@ -541,6 +549,7 @@ IRC.prototype._getClient = function (job, create) {
// if (!client.listeners.message[self.sessionId]) {
// client.listeners = mergeListeners(client, self._registerListeners(client));
// }
+ self.client = client;
pending.resolve(client);
} else {
//
@@ -571,7 +580,7 @@ IRC.prototype._createClient = function (key, creds) {
var self = this,
pending = Promise.defer();
- self.session.debug('creating new client connection: ' + creds.object.server, creds);
+ self.session.debug('creating new client ');
self.session.connection.create({
id: creds.actor.id,
@@ -610,6 +619,7 @@ IRC.prototype._createClient = function (key, creds) {
},
listeners: {
'*': function (object) {
+ self.session.debug('HANDLER * called: ', object);
if (typeof object.names === 'object') {
// user list
self.session.debug('received user list: ' + object.channel);
|
assign client to local object once fetched
|
sockethub_sockethub-platform-irc
|
train
|
c745275718212779b02e293334cc9c053f05e615
|
diff --git a/browse-everything.gemspec b/browse-everything.gemspec
index <HASH>..<HASH> 100644
--- a/browse-everything.gemspec
+++ b/browse-everything.gemspec
@@ -27,8 +27,9 @@ Gem::Specification.new do |spec|
spec.add_dependency "bootstrap-sass"
spec.add_dependency "font-awesome-rails"
spec.add_dependency "google-api-client"
- spec.add_development_dependency "rspec", "~> 2.0"
+ spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "rspec-rails"
+ spec.add_development_dependency "rspec-its"
spec.add_development_dependency "simplecov"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "pry"
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -14,8 +14,10 @@ VCR.configure do |c|
c.configure_rspec_metadata!
end
-RSpec.configure do |c|
- c.treat_symbols_as_metadata_keys_with_true_values = true
+RSpec.configure do |config|
+ config.expect_with :rspec do |c|
+ c.syntax = [:should, :expect]
+ end
end
module BrowserConfigHelper
diff --git a/spec/unit/browser_spec.rb b/spec/unit/browser_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/browser_spec.rb
+++ b/spec/unit/browser_spec.rb
@@ -26,7 +26,7 @@ describe BrowseEverything::Browser do
}
describe "file config" do
- before(:each) { File.stub(:read).and_return(file_config) }
+ before(:each) { allow(File).to receive(:read).and_return(file_config) }
subject { BrowseEverything::Browser.new(url_options) }
it "should have 2 providers" do
@@ -69,7 +69,7 @@ describe BrowseEverything::Browser do
}
it "should complain but continue" do
- Rails.logger.should_receive(:warn).with('Unknown provider: foo')
+ allow(Rails.logger).to receive(:warn).with('Unknown provider: foo')
expect(subject.providers.keys).to eq([:file_system,:drop_box])
end
end
diff --git a/spec/unit/file_entry_spec.rb b/spec/unit/file_entry_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/file_entry_spec.rb
+++ b/spec/unit/file_entry_spec.rb
@@ -38,7 +38,7 @@ describe BrowseEverything::FileEntry do
end
it "#container?" do
- expect(subject.container?).to be_false
+ expect(subject.container?).to be false
end
-end
\ No newline at end of file
+end
|
Eliminate most rspec deprecations
|
samvera_browse-everything
|
train
|
57f3e7446203275346d742cd72da561ced1acadd
|
diff --git a/goinvestigate.go b/goinvestigate.go
index <HASH>..<HASH> 100644
--- a/goinvestigate.go
+++ b/goinvestigate.go
@@ -28,6 +28,7 @@ import (
"errors"
"fmt"
"io"
+ "io/ioutil"
"log"
"net/http"
"net/url"
@@ -346,6 +347,15 @@ func (inv *Investigate) PostParse(subUri string, body io.Reader, v interface{})
return err
}
+type JSONDecodeError struct {
+ Err error
+ Body []byte
+}
+
+func (e JSONDecodeError) Error() string {
+ return fmt.Sprintf("error: %s\nbody: %s", e.Err.Error(), e.Body)
+}
+
// Parse an HTTP JSON response into a map
func parseBody(respBody io.ReadCloser, v interface{}) (err error) {
defer respBody.Close()
@@ -370,6 +380,15 @@ func parseBody(respBody io.ReadCloser, v interface{}) (err error) {
default:
err = errors.New("type of v is unsupported")
}
+ //return err
+ if err != nil {
+ body, readErr := ioutil.ReadAll(respBody)
+ if readErr != nil {
+ log.Printf("error reading body: %v", readErr)
+ return err
+ }
+ return JSONDecodeError{Err: err, Body: body}
+ }
return err
}
|
Change JSON parsing error to be more helpful
|
dead10ck_goinvestigate
|
train
|
00206270a4d00b6730c599d71013f4fcc4fc0abc
|
diff --git a/azurerm/resource_arm_batch_pool.go b/azurerm/resource_arm_batch_pool.go
index <HASH>..<HASH> 100644
--- a/azurerm/resource_arm_batch_pool.go
+++ b/azurerm/resource_arm_batch_pool.go
@@ -59,6 +59,7 @@ func resourceArmBatchPool() *schema.Resource {
Type: schema.TypeInt,
Optional: true,
Default: 1,
+ ForceNew: true,
ValidateFunc: validation.IntAtLeast(1),
},
"fixed_scale": {
|
Mark maxTasksPerNode as forcenew
The maxTasksPerNode cannot be changed once a Batch pool has been created
so marking as ForceNew to require re-creating the pool
|
terraform-providers_terraform-provider-azurerm
|
train
|
6be318bb0b13cf61b402fc69783db9ac2cdd2a38
|
diff --git a/java/src/main/java/net/razorvine/pickle/Pickler.java b/java/src/main/java/net/razorvine/pickle/Pickler.java
index <HASH>..<HASH> 100644
--- a/java/src/main/java/net/razorvine/pickle/Pickler.java
+++ b/java/src/main/java/net/razorvine/pickle/Pickler.java
@@ -33,8 +33,14 @@ import net.razorvine.pyro.Config;
*/
public class Pickler {
+ /**
+ * The highest Python pickle protocol supported by this Pickler.
+ */
public static int HIGHEST_PROTOCOL = 2;
+ /**
+ * A memoized object.
+ */
protected static class Memo {
public Object obj;
public int index;
@@ -45,12 +51,40 @@ public class Pickler {
}
}
+ /**
+ * Limit on the recursion depth to avoid stack overflows.
+ */
protected static int MAX_RECURSE_DEPTH = 1000;
+
+ /**
+ * Current recursion level.
+ */
protected int recurse = 0; // recursion level
+
+ /**
+ * Output where the pickle data is written to.
+ */
protected OutputStream out;
+
+ /**
+ * The Python pickle protocol version of the pickles created by this library.
+ */
protected int PROTOCOL = 2;
+
+ /**
+ * Registry of picklers for custom classes, to be able to not just pickle simple built in datatypes.
+ * You can add to this via {@link Pickler.registerCustomPickler}
+ */
protected static Map<Class<?>, IObjectPickler> customPicklers=new HashMap<Class<?>, IObjectPickler>();
+
+ /**
+ * Use memoization or not. This saves pickle size, but can only create pickles of objects that are hashable.
+ */
protected boolean useMemo=true;
+
+ /**
+ * The memoization cache.
+ */
protected HashMap<Integer, Memo> memo; // maps object's identity hash to (object, memo index)
/**
@@ -332,6 +366,12 @@ public class Pickler {
return false;
}
+ /**
+ * Get the custom pickler fot the given class, to be able to pickle not just built in collection types.
+ * A custom pickler is matched on the interface or abstract base class that the object implements or inherits from.
+ * @param t the class of the object to be pickled
+ * @return null (if no custom pickler found) or a pickler registered for this class (via {@link Pickler.registerCustomPickler})
+ */
protected IObjectPickler getCustomPickler(Class<?> t) {
IObjectPickler pickler = customPicklers.get(t);
if(pickler!=null) {
diff --git a/java/src/main/java/net/razorvine/pickle/Unpickler.java b/java/src/main/java/net/razorvine/pickle/Unpickler.java
index <HASH>..<HASH> 100644
--- a/java/src/main/java/net/razorvine/pickle/Unpickler.java
+++ b/java/src/main/java/net/razorvine/pickle/Unpickler.java
@@ -35,13 +35,34 @@ import net.razorvine.pickle.objects.SetConstructor;
*/
public class Unpickler {
+ /**
+ * Used as return value for {@link Unpickler.dispatch} in the general case (because the object graph is built on the stack)
+ */
protected static final Object NO_RETURN_VALUE = new Object();
+ /**
+ * The highest Python Pickle protocol version supported by this library.
+ */
protected final int HIGHEST_PROTOCOL = 4;
+ /**
+ * Internal cache of memoized objects.
+ */
protected Map<Integer, Object> memo;
+
+ /**
+ * The stack that is used for building the resulting object graph.
+ */
protected UnpickleStack stack;
+
+ /**
+ * The stream where the pickle data is read from.
+ */
protected InputStream input;
+
+ /**
+ * Registry of object constructors that are used to create the appropriate Java objects for the given Python module.typename references.
+ */
protected static Map<String, IObjectConstructor> objectConstructors;
static {
@@ -763,7 +784,12 @@ public class Unpickler {
stack.add(object);
}
-
+ /**
+ * Hook for the persistent id feature where an id is replaced externally by the appropriate object.
+ * @param pid the persistent id from the pickle
+ * @return the actual object that belongs to that id. The default implementation throws a PickleException,
+ * telling you that you should implement this function yourself in a subclass of the Unpickler.
+ */
protected Object persistentLoad(String pid)
{
throw new PickleException("A load persistent id instruction was encountered, but no persistentLoad function was specified. (implement it in custom Unpickler subclass)");
|
more javadocs added for various methods and exposed properties
|
irmen_Pyrolite
|
train
|
efd5c11e06cc396ee73e1d66798d77779fb854ca
|
diff --git a/src/ProfileConfig.php b/src/ProfileConfig.php
index <HASH>..<HASH> 100644
--- a/src/ProfileConfig.php
+++ b/src/ProfileConfig.php
@@ -44,9 +44,7 @@ class ProfileConfig extends Config
'reject6' => false,
'vpnProtoPorts' => [
'udp/1194',
- 'udp/1195',
'tcp/1194',
- 'tcp/1195',
],
'hideProfile' => false,
];
|
default to one udp and one tcp port
|
eduvpn_vpn-lib-common
|
train
|
3020a65ae10cb4e5f9572dcdbb2a53aeed8ada17
|
diff --git a/estnltk/layer/base_span.py b/estnltk/layer/base_span.py
index <HASH>..<HASH> 100644
--- a/estnltk/layer/base_span.py
+++ b/estnltk/layer/base_span.py
@@ -1,4 +1,4 @@
-from typing import Sequence
+from typing import Iterable
class BaseSpan:
@@ -61,7 +61,7 @@ class ElementaryBaseSpan(BaseSpan):
class EnvelopingBaseSpan(BaseSpan):
__slots__ = ['_spans']
- def __init__(self, spans: Sequence[BaseSpan]):
+ def __init__(self, spans: Iterable[BaseSpan]):
spans = tuple(spans)
if len(spans) == 0:
|
replace Sequence with Iterable in EnvelopingBaseSpan
|
estnltk_estnltk
|
train
|
d2cf93c817f3d24816112704ff53ae80b062876f
|
diff --git a/src/blocksToNodes.js b/src/blocksToNodes.js
index <HASH>..<HASH> 100644
--- a/src/blocksToNodes.js
+++ b/src/blocksToNodes.js
@@ -92,7 +92,7 @@ function blocksToNodes(h, properties) {
const nodes = blocks.map(serializeNode)
if (nodes.length > 1) {
const containerProps = props.className ? {className: props.className} : {}
- return h('div', containerProps, nodes)
+ return h(serializers.container, containerProps, nodes)
}
return nodes[0] || serializers.empty
diff --git a/src/serializers.js b/src/serializers.js
index <HASH>..<HASH> 100644
--- a/src/serializers.js
+++ b/src/serializers.js
@@ -28,7 +28,7 @@ module.exports = h => {
console.warn(
`Unknown mark type "${markType}", please specify a serializer for it in the \`serializers.marks\` prop`
)
- return h('span', null, children)
+ return h(props.serializers.markFallback, null, children)
}
return h(serializer, props.node, children)
@@ -88,7 +88,7 @@ module.exports = h => {
}
if (typeof span === 'string') {
- return span
+ return serializers.text ? h(serializers.text, {key: `text-${index}`}, span) : span
}
let children
@@ -135,6 +135,15 @@ module.exports = h => {
span: SpanSerializer,
hardBreak: HardBreakSerializer,
+ // Container element
+ container: 'div',
+
+ // When we can't resolve the mark properly, use this renderer as the container
+ markFallback: 'span',
+
+ // Allow overriding text renderer, but leave undefined to just use plain strings by default
+ text: undefined,
+
// Empty nodes (React uses null, hyperscript with empty strings)
empty: ''
}
|
Remove HTMLisms into overridable serializers
|
sanity-io_block-content-to-hyperscript
|
train
|
61a1831523ab86588a31b4fd9dea72695a374e9b
|
diff --git a/kernel/content/attribute_edit.php b/kernel/content/attribute_edit.php
index <HASH>..<HASH> 100644
--- a/kernel/content/attribute_edit.php
+++ b/kernel/content/attribute_edit.php
@@ -316,6 +316,10 @@ if ( $storingAllowed && $hasObjectInput)
$object->storeInput( $contentObjectAttributes,
$attributeInputMap );
$db->commit();
+ ezpEvent::getInstance()->notify(
+ 'content/cache/version',
+ array( $object->attribute( 'id' ), $version->attribute( 'version' ) )
+ );
}
$validation['processed'] = true;
|
Fix EZP-<I>: Preview cache not being updated
> <URL>, preview won't reflect the changes.
A previously cached content is displayed instead.
Only applies if the frontend siteaccess is *not* using `legacy_mode`.
This patch introduces a new `content/cache/version` event.
|
ezsystems_ezpublish-legacy
|
train
|
b4cc7258d5ffe875e225e6a46c71e6de886593e4
|
diff --git a/maas/client/flesh/vlans.py b/maas/client/flesh/vlans.py
index <HASH>..<HASH> 100644
--- a/maas/client/flesh/vlans.py
+++ b/maas/client/flesh/vlans.py
@@ -58,7 +58,7 @@ class cmd_vlan(OriginPagedTableCommand):
super(cmd_vlan, self).__init__(parser)
parser.add_argument("fabric", nargs=1, help=(
"Name of the fabric."))
- parser.add_argument("vid", nargs=1, type=int, help=(
+ parser.add_argument("vid", nargs=1, help=(
"VID of the VLAN."))
@asynchronous
@@ -84,7 +84,16 @@ class cmd_vlan(OriginPagedTableCommand):
"Unable to find fabric %s." % options.fabric[0])
else:
raise
- vlan = self.get_vlan(fabric.vlans, options.vid[0])
+ vlan_id = options.vid[0]
+ if vlan_id != 'untagged':
+ try:
+ vlan_id = int(vlan_id)
+ except ValueError:
+ vlan = None
+ else:
+ vlan = self.get_vlan(fabric.vlans, options.vid[0])
+ else:
+ vlan = fabric.vlans.get_default()
if vlan is None:
raise CommandError(
"Unable to find VLAN %s on fabric %s." % (
|
Support untagged VLAN name on vlan command.
|
maas_python-libmaas
|
train
|
0013641fdda4e3d4a1c35090793c9fc58f49d1b7
|
diff --git a/services/maintenance/maintenance.service.js b/services/maintenance/maintenance.service.js
index <HASH>..<HASH> 100644
--- a/services/maintenance/maintenance.service.js
+++ b/services/maintenance/maintenance.service.js
@@ -1,8 +1,8 @@
'use strict'
-const { BaseService } = require('..')
+const { NonMemoryCachingBaseService } = require('..')
-module.exports = class Maintenance extends BaseService {
+module.exports = class Maintenance extends NonMemoryCachingBaseService {
static get route() {
return {
base: 'maintenance',
@@ -51,11 +51,12 @@ module.exports = class Maintenance extends BaseService {
static get category() {
return 'other'
}
+
static get examples() {
return [
{
title: 'Maintenance',
- pattern: ':maintained/:year',
+ pattern: ':maintained(yes|no)/:year',
namedParams: {
maintained: 'yes',
year: '2019',
|
Tweak [maintenance] badge in UI; remove caching (#<I>)
|
badges_shields
|
train
|
8917ba82cfc67548c955491c16050fa57a9a7fd4
|
diff --git a/ripozo_sqlalchemy/alcehmymanager.py b/ripozo_sqlalchemy/alcehmymanager.py
index <HASH>..<HASH> 100644
--- a/ripozo_sqlalchemy/alcehmymanager.py
+++ b/ripozo_sqlalchemy/alcehmymanager.py
@@ -3,8 +3,11 @@ from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
+from datetime import datetime
from ripozo.exceptions import NotFoundException
from ripozo.managers.base import BaseManager
+from ripozo.viewsets.fields.base import BaseField
+from ripozo.viewsets.fields.common import StringField, IntegerField, FloatField, DateTimeField, BooleanField
from ripozo.utilities import serialize_fields
import logging
@@ -17,8 +20,22 @@ class AlchemyManager(BaseManager):
session = None # the database object needs to be given to the class
pagination_pk_query_arg = 'page'
- def get_field_type(self, name):
- return self.model.metadata.tables[self.model.__tablename__].columns._data[name].type.python_type
+ @classmethod
+ def get_field_type(cls, name):
+ # TODO need to look at the columns for defaults and such
+ t = cls.model.metadata.tables[cls.model.__tablename__].columns._data[name].type.python_type
+ if t in six.string_types:
+ return StringField(t)
+ elif t is int:
+ return IntegerField(t)
+ elif t is float:
+ return FloatField(t)
+ elif t is datetime:
+ return DateTimeField(t)
+ elif t is bool:
+ return BooleanField(t)
+ else:
+ return BaseField(t)
def create(self, values, *args, **kwargs):
logger.info('Creating model')
|
Update get_field_type to use common Field types
|
vertical-knowledge_ripozo-sqlalchemy
|
train
|
747bc60de47be90f0eb753c563ae2a62ab450313
|
diff --git a/lib/ember-app.js b/lib/ember-app.js
index <HASH>..<HASH> 100644
--- a/lib/ember-app.js
+++ b/lib/ember-app.js
@@ -2,6 +2,7 @@
const fs = require('fs');
const path = require('path');
+const RSVP = require('rsvp');
const najax = require('najax');
const SimpleDOM = require('simple-dom');
@@ -218,6 +219,7 @@ class EmberApp {
})
.then(() => instance.visit(path, bootOptions))
.then(() => waitForApp(instance))
+ .then(() => createShoebox(doc, fastbootInfo))
.catch(error => result.error = error)
.then(() => result._finalize())
.finally(() => instance.destroy());
@@ -287,6 +289,34 @@ function waitForApp(instance) {
}
/*
+ * Writes the shoebox into the DOM for the browser rendered app to consume.
+ * Uses a script tag with custom type so that the browser will treat as plain
+ * text, and not expend effort trying to parse contents of the script tag.
+ * Each key is written separately so that the browser rendered app can
+ * parse the specific item at the time it is needed instead of everything
+ * all at once.
+ */
+function createShoebox(doc, fastbootInfo) {
+ let shoebox = fastbootInfo.shoebox;
+ if (!shoebox) { return RSVP.resolve(); }
+
+ for (let key in shoebox) {
+ if (!shoebox.hasOwnProperty(key)) { continue; }
+
+ let value = shoebox[key];
+ let scriptText = doc.createTextNode(JSON.stringify(value));
+ let scriptEl = doc.createElement('script');
+
+ scriptEl.setAttribute('type', 'fastboot/shoebox');
+ scriptEl.setAttribute('data-key', key);
+ scriptEl.appendChild(scriptText);
+ doc.body.appendChild(scriptEl);
+ }
+
+ return RSVP.resolve();
+}
+
+/*
* Builds a new FastBootInfo instance with the request and response and injects
* it into the application instance.
*/
|
Adding the "Shoebox" -- a means to serialize application state into DOM
|
ember-fastboot_ember-cli-fastboot
|
train
|
1c85b8aa050e085ec94f2a2d8d0920f4e9ea69f6
|
diff --git a/core/FrontController.php b/core/FrontController.php
index <HASH>..<HASH> 100644
--- a/core/FrontController.php
+++ b/core/FrontController.php
@@ -438,6 +438,10 @@ class FrontController extends Singleton
if(Piwik::getModule() == 'CoreAdminHome' && Piwik::getAction() == 'optOut') {
return;
}
+ // Disable Https for VisitorGenerator
+ if(Piwik::getModule() == 'VisitorGenerator') {
+ return;
+ }
if(Common::isPhpCliMode()) {
return;
}
|
Ignore SSL redirection for VisitorGenerator to work around issue when SSL is not working on localhost
|
matomo-org_matomo
|
train
|
d997f66f4e38674b55f8f381f7cb6ca0de11d2f9
|
diff --git a/demo.js b/demo.js
index <HASH>..<HASH> 100644
--- a/demo.js
+++ b/demo.js
@@ -45,8 +45,9 @@ fields
var testData = [
{
- 'name': 'dog',
- 'fk': 1
+ 'name*': 'dog',
+ 'fk': 1,
+ 'pet': 'Fido'
},
{
'name': 'cat',
@@ -54,15 +55,16 @@ var testData = [
'fk:b': 'B'
},
{
- 'name': 'dog',
+ 'name*': 'dog',
'fk:a': 'X',
- 'fk:b': 'Y'
+ 'fk:b': 'Y',
+ 'pet': 'Mittens'
},
];
var test = new Treeize();
test
- .setOptions({ log: true, data: { uniformRows: false, prune: true } })
+ .setOptions({ log: true, data: { uniformRows: false, prune: true, objectOverwrite: true } })
.grow(testData)
;
diff --git a/lib/treeize.js b/lib/treeize.js
index <HASH>..<HASH> 100644
--- a/lib/treeize.js
+++ b/lib/treeize.js
@@ -203,6 +203,7 @@ Treeize.prototype.grow = function(data, options) {
_.each(node.blueprint, function(attribute) {
var key = (node.path ? (node.path + ':') : '') + attribute.name;
blueprint[attribute.name] = row[attribute.key];
+ this.log('creating attribute "' + attribute.name + '" within blueprint', row[attribute.key]);
}, this);
// create full node signature for insertion/updating
@@ -212,6 +213,7 @@ Treeize.prototype.grow = function(data, options) {
// insert extended blueprint attributes when not empty (or not pruning)
if (!opt.data.prune || (value !== null && value !== undefined)) {
+ this.log('creating attribute "' + attribute.name + '" within extended blueprint', row[attribute.key]);
blueprintExtended[attribute.name] = row[attribute.key];
}
}, this);
@@ -234,6 +236,7 @@ Treeize.prototype.grow = function(data, options) {
// NOT ROOT CASE
if (node.isCollection) {
// handle collection nodes
+ this.log('inserting into collection node');
if (!trail[node.name]) {
// node attribute doesnt exist, create array with fresh blueprint
trail[node.name] = [blueprintExtended];
@@ -250,13 +253,17 @@ Treeize.prototype.grow = function(data, options) {
}
} else {
// handle non-collection nodes
- if (!trail[node.name]) {
+ this.log('inserting into non-collection node');
+ //if (!trail[node.name]) { // TODO: CONSIDER: add typeof check to this for possible overwriting
+ if (!trail[node.name] || (opt.data.objectOverwrite && (typeof trail[node.name] !== typeof blueprintExtended))) {
// node attribute doesnt exist, create object
+ this.log('create object');
trail[node.name] = blueprintExtended;
trails[node.path] = blueprintExtended;
} else {
// node attribute exists, set path for next pass
// TODO: extend trail??
+ this.log('object at node "' + node.name + '" exists, skipping insertion and adding trail');
trails[node.path] = trail[node.path];
}
}
@@ -309,6 +316,7 @@ Treeize.prototype.resetOptions = function() {
uniformRows: true,
prune: true,
detectCollections: true,
+ objectOverwrite: false,
},
log: false,
};
|
Added objectOverwrite optiont to address #<I>. Allows object replacement over static value
|
kwhitley_treeize
|
train
|
273296217776dc802c8377713a91555608751223
|
diff --git a/runtime/context_test.go b/runtime/context_test.go
index <HASH>..<HASH> 100644
--- a/runtime/context_test.go
+++ b/runtime/context_test.go
@@ -22,7 +22,7 @@ func TestAnnotateContext(t *testing.T) {
request.Header.Add("Some-Irrelevant-Header", "some value")
annotated := runtime.AnnotateContext(ctx, request)
ctx = metadata.NewContext(ctx, metadata.Pairs("RemoteAddr", "127.0.0.1"))
- if annotated != ctx {
+ if !reflect.DeepEqual(annotated, ctx) {
t.Errorf("AnnotateContext(ctx, request) = %v; want %v", annotated, ctx)
}
|
update tests - try DeepEqual comparison for metadata background with context
|
grpc-ecosystem_grpc-gateway
|
train
|
ccc1661cd7dda20d61262f348762718a0ade7d81
|
diff --git a/tests/test_archives.py b/tests/test_archives.py
index <HASH>..<HASH> 100644
--- a/tests/test_archives.py
+++ b/tests/test_archives.py
@@ -516,6 +516,7 @@ class TestArchives (ArchiveTest):
self.archive_create('t.flac', srcfile="t.wav")
@needs_program('shar')
+ @needs_program('unshar')
def test_shar (self):
self.program = 'shar'
self.archive_create('t.shar', singlefile=True)
|
Need unshar to test shar archives.
|
wummel_patool
|
train
|
651827b38ea314397338d91f3446cf76ea2c160e
|
diff --git a/xmlnuke-php5/src/Xmlnuke/Library/OAuthClient/v20/BaseOAuth20.class.php b/xmlnuke-php5/src/Xmlnuke/Library/OAuthClient/v20/BaseOAuth20.class.php
index <HASH>..<HASH> 100644
--- a/xmlnuke-php5/src/Xmlnuke/Library/OAuthClient/v20/BaseOAuth20.class.php
+++ b/xmlnuke-php5/src/Xmlnuke/Library/OAuthClient/v20/BaseOAuth20.class.php
@@ -19,6 +19,8 @@
namespace OAuthClient\v20;
+use Xmlnuke\Util\WebRequest;
+
/**
* Base OAuth class
*/
|
Updated OAuth library to PHP <I> namespaces;
|
byjg_xmlnuke
|
train
|
8bbc84c97f34416e5458a934967c93db50a02b86
|
diff --git a/compliance/run-autobahn-tests.py b/compliance/run-autobahn-tests.py
index <HASH>..<HASH> 100644
--- a/compliance/run-autobahn-tests.py
+++ b/compliance/run-autobahn-tests.py
@@ -10,7 +10,7 @@ import socket
import subprocess
import sys
import time
-from typing import Any, Dict, List, Tuple
+from typing import Dict, List, Tuple
PORT = 8642
@@ -62,7 +62,7 @@ CASES = {
}
-def say(*args: Any) -> None: # type: ignore
+def say(*args: object) -> None:
print("run-autobahn-tests.py:", *args)
diff --git a/setup.cfg b/setup.cfg
index <HASH>..<HASH> 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -41,6 +41,7 @@ disallow_untyped_decorators = True
disallow_untyped_defs = True
implicit_reexport = False
no_implicit_optional = True
+show_error_codes = True
strict_equality = True
strict_optional = True
warn_redundant_casts = True
diff --git a/src/wsproto/events.py b/src/wsproto/events.py
index <HASH>..<HASH> 100644
--- a/src/wsproto/events.py
+++ b/src/wsproto/events.py
@@ -54,7 +54,7 @@ class Request(Event):
host: str
target: str
- extensions: Union[Sequence[Extension], Sequence[str]] = field( # type: ignore
+ extensions: Union[Sequence[Extension], Sequence[str]] = field( # type: ignore[assignment]
default_factory=list
)
extra_headers: Headers = field(default_factory=list)
diff --git a/src/wsproto/handshake.py b/src/wsproto/handshake.py
index <HASH>..<HASH> 100644
--- a/src/wsproto/handshake.py
+++ b/src/wsproto/handshake.py
@@ -344,15 +344,18 @@ class H11Handshake:
)
if request.extensions:
- offers = {e.name: e.offer() for e in request.extensions} # type: ignore
+ offers: Dict[str, Union[str, bool]] = {}
+ for e in request.extensions:
+ assert isinstance(e, Extension)
+ offers[e.name] = e.offer()
extensions = []
for name, params in offers.items():
- name = name.encode("ascii")
+ bname = name.encode("ascii")
if isinstance(params, bool):
if params:
- extensions.append(name)
+ extensions.append(bname)
else:
- extensions.append(b"%s; %s" % (name, params.encode("ascii")))
+ extensions.append(b"%s; %s" % (bname, params.encode("ascii")))
if extensions:
headers.append((b"Sec-WebSocket-Extensions", b", ".join(extensions)))
diff --git a/test/test_connection.py b/test/test_connection.py
index <HASH>..<HASH> 100644
--- a/test/test_connection.py
+++ b/test/test_connection.py
@@ -65,7 +65,7 @@ def test_closure(client_sends: bool, code: CloseReason, reason: str) -> None:
assert event.code is code
assert event.reason == reason
- assert remote.state is ConnectionState.CLOSED # type: ignore
+ assert remote.state is ConnectionState.CLOSED # type: ignore[comparison-overlap]
assert local.state is ConnectionState.CLOSED
diff --git a/test/test_extensions.py b/test/test_extensions.py
index <HASH>..<HASH> 100644
--- a/test/test_extensions.py
+++ b/test/test_extensions.py
@@ -22,23 +22,23 @@ class TestExtension:
def test_frame_inbound_header(self) -> None:
ext = wpext.Extension()
- result = ext.frame_inbound_header(None, None, None, None) # type: ignore
+ result = ext.frame_inbound_header(None, None, None, None) # type: ignore[arg-type]
assert result == fp.RsvBits(False, False, False)
def test_frame_inbound_payload_data(self) -> None:
ext = wpext.Extension()
data = b""
- assert ext.frame_inbound_payload_data(None, data) == data # type: ignore
+ assert ext.frame_inbound_payload_data(None, data) == data # type: ignore[arg-type]
def test_frame_inbound_complete(self) -> None:
ext = wpext.Extension()
- assert ext.frame_inbound_complete(None, None) is None # type: ignore
+ assert ext.frame_inbound_complete(None, None) is None # type: ignore[arg-type]
def test_frame_outbound(self) -> None:
ext = wpext.Extension()
rsv = fp.RsvBits(True, True, True)
data = b""
- assert ext.frame_outbound(None, None, rsv, data, None) == ( # type: ignore
+ assert ext.frame_outbound(None, None, rsv, data, None) == ( # type: ignore[arg-type]
rsv,
data,
)
|
Set mypy show_error_codes and change type-ignore to specific error codes
This makes it easier to see what is being ignored, and doesn't ignore
any unrelated error that might come up in the line.
|
python-hyper_wsproto
|
train
|
fcbbe03d27d02db8f833604f784ca56bbc7e436e
|
diff --git a/lib/boolean.js b/lib/boolean.js
index <HASH>..<HASH> 100644
--- a/lib/boolean.js
+++ b/lib/boolean.js
@@ -47,14 +47,14 @@ BooleanType.set('DOMCheckboxBox', Db.fixed(function () {
}));
BooleanType.set('toDOMInputBox', function (document, options) {
var box;
- if (options && (options.control === 'checkbox')) {
+ if (options && (options.type === 'checkbox')) {
box = new this.DOMCheckboxBox(document, this);
} else {
box = new this.DOMInputBox(document, this);
}
if (options) {
Object.keys(Object(options)).forEach(function (name) {
- if (name === 'control') return;
+ if (name === 'type') return;
box.setAttribute(name, options[name]);
});
}
diff --git a/lib/dom-input-box.js b/lib/dom-input-box.js
index <HASH>..<HASH> 100644
--- a/lib/dom-input-box.js
+++ b/lib/dom-input-box.js
@@ -47,7 +47,7 @@ Db.Base.set('toDOMInputBox', function (document, options) {
var box = new this.DOMInputBox(document, this);
if (options) {
Object.keys(Object(options)).forEach(function (name) {
- if (name === 'control') return;
+ if (name === 'type') return;
box.setAttribute(name, options[name]);
});
}
@@ -70,7 +70,7 @@ Relation.prototype.set('toDOMInputBox', function (document/*, options*/) {
box = this.ns.toDOMInputBox(document, options);
box.set(this._objectValue_);
box.setAttribute('name', this._id_);
- if (this.required && (!options || (options.control !== 'checkbox'))) {
+ if (this.required && (!options || (options.type !== 'checkbox'))) {
box.setAttribute('required', true);
}
this.on('update', function () { box.set(this._objectValue_); });
|
Customize control type with 'type' option
In align with what options are used for (set attributes)
|
medikoo_dbjs-dom
|
train
|
c60cf2aa908d31eb203bfee0483dc0e8b2c82826
|
diff --git a/spec/Gaufrette/FileSpec.php b/spec/Gaufrette/FileSpec.php
index <HASH>..<HASH> 100644
--- a/spec/Gaufrette/FileSpec.php
+++ b/spec/Gaufrette/FileSpec.php
@@ -125,9 +125,9 @@ class FileSpec extends ObjectBehavior
/**
* @param \Gaufrette\Filesystem $filesystem
*/
- function it_calculates_size_from_content($filesystem)
+ function it_calculates_size_from_filesystem($filesystem)
{
- $filesystem->read('filename')->shouldBeCalled()->willReturn('some content');
+ $filesystem->size('filename')->shouldBeCalled()->willReturn(12);
$this->getSize()->shouldReturn(12);
}
@@ -148,7 +148,7 @@ class FileSpec extends ObjectBehavior
*/
function it_gets_zero_size_when_file_not_found($filesystem)
{
- $filesystem->read('filename')->willThrow(new \Gaufrette\Exception\FileNotFound('filename'));
+ $filesystem->size('filename')->willThrow(new \Gaufrette\Exception\FileNotFound('filename'));
$this->getSize()->shouldReturn(0);
}
|
Fixed spec tests for new size calulation
|
KnpLabs_Gaufrette
|
train
|
61e5ac086d8b3704a77329d8e0f3e2945eabcff1
|
diff --git a/karma.conf.js b/karma.conf.js
index <HASH>..<HASH> 100644
--- a/karma.conf.js
+++ b/karma.conf.js
@@ -14,10 +14,9 @@ module.exports = function(config) {
// list of files / patterns to load in the browser
files: [
- "http://code.jquery.com/jquery-1.10.1.min.js",
- "http://code.angularjs.org/1.2.11/angular.min.js",
- "http://code.angularjs.org/1.2.11/angular-mocks.js",
- "http://underscorejs.org/underscore-min.js",
+ 'http://code.angularjs.org/1.2.11/angular.min.js',
+ 'http://code.angularjs.org/1.2.11/angular-mocks.js',
+ 'http://underscorejs.org/underscore-min.js',
'coffee/atTable.coffee',
'coffee/*.coffee',
'test/test_helper.coffee',
@@ -32,9 +31,9 @@ module.exports = function(config) {
],
preprocessors: {
- "coffee/*.coffee": ["coffee"],
- "test/*.coffee": ["coffee"],
- "test/templates/**/*.html": ["ng-html2js"]
+ 'coffee/*.coffee': ['coffee'],
+ 'test/*.coffee': ['coffee'],
+ 'test/templates/**/*.html': ['ng-html2js']
},
// test results reporter to use
|
removed jquery reference from karma config
|
samu_angular-table
|
train
|
f7110ae998a4fb470ed993f74787d396c2f8e616
|
diff --git a/zxbpp.py b/zxbpp.py
index <HASH>..<HASH> 100755
--- a/zxbpp.py
+++ b/zxbpp.py
@@ -16,6 +16,7 @@ import os
import re
import zxbpplex
+import zxbasmpplex
import ply.yacc as yacc
from zxbpplex import tokens
@@ -28,9 +29,13 @@ OPTIONS.add_option_if_not_defined('Sinclair', bool, False)
OUTPUT = ''
INCLUDED = {} # Already included files (with lines)
-LEXER = zxbpplex.Lexer()
SPACES = re.compile(r'[ \t]+')
+# Set to BASIC or ASM depending on the Lexer context
+# e.g. for .ASM files should be set to zxbppasmlex.Lexer()
+# Use setMode('ASM' or 'BASIC') to change this FLAG
+LEXER = zxbpplex.Lexer()
+
# CURRENT working directory for this cpp
precedence = (
@@ -68,6 +73,20 @@ IFDEFS = [] # Push (Line, state here)
+def setMode(mode):
+ global LEXER
+
+ mode = mode.upper()
+ if mode not in ('ASM', 'BASIC'):
+ raise PreprocError('Invalid mode "%s"' % mode)
+
+ if mode == 'ASM':
+ LEXER = zxbasmpplex.Lexer()
+ else:
+ LEXER = zxbpplex.Lexer()
+
+
+
def search_filename(fname, lineno):
''' Search a filename into the list of the include path
'''
@@ -572,7 +591,8 @@ def main(argv):
global OUTPUT, ID_TABLE, ENABLED
ENABLED = True
- ID_TABLE = DefinesTable()
+ #print ID_TABLE.defined('__CHECK_ARRAY_BOUNDARY__')
+ #ID_TABLE = DefinesTable()
if argv:
CURRENT_FILE.append(argv[0])
|
Unified preprocesor for both asm and basic.
Just call setMode() to set the lexer mode
|
boriel_zxbasic
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.