hash
stringlengths 40
40
| diff
stringlengths 131
26.7k
| message
stringlengths 7
694
| project
stringlengths 5
67
| split
stringclasses 1
value | diff_languages
stringlengths 2
24
|
---|---|---|---|---|---|
9f47b96a69faba35b653d59b45a5f724a859faf3 | diff --git a/packages/core/src/textures/resources/CanvasResource.js b/packages/core/src/textures/resources/CanvasResource.js
index <HASH>..<HASH> 100644
--- a/packages/core/src/textures/resources/CanvasResource.js
+++ b/packages/core/src/textures/resources/CanvasResource.js
@@ -1,6 +1,10 @@
import BaseImageResource from './BaseImageResource';
/**
+ * @interface OffscreenCanvas
+ */
+
+/**
* Resource type for HTMLCanvasElement.
* @class
* @extends PIXI.resources.BaseImageResource | Compatibility with older typescript OffscreenCanvas type (#<I>) | pixijs_pixi.js | train | js |
f8b4056ed8dad5905b5499fb1dede0640a89390c | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -16,15 +16,9 @@ try:
from Cython.Build import cythonize
except ImportError:
import os
- try:
- pyx_time = os.path.getmtime('cyflann/index.pyx')
- pxd_time = os.path.getmtime('cyflann/flann.pxd')
- c_time = os.path.getmtime('cyflann/index.c'.format(pkg, name))
- if max(pyx_time, pxd_time) >= c_time:
- raise ValueError
- except (OSError, ValueError):
- msg = "{} extension needs to be compiled but cython isn't available"
- raise ImportError(msg.format(name))
+ if not os.path.exists('cyflann/index.c'):
+ msg = "index extension needs to be compiled but cython isn't available"
+ raise ImportError(msg)
else:
cythonize("cyflann/index.pyx", "cyflann/flann.pdx")
ext_modules = [ | meh; don't be clever about mod-times for .c when cython isn't available | dougalsutherland_cyflann | train | py |
ec72568733828a0c1c821d2b29cd37d71e06fd08 | diff --git a/sinatra-contrib/lib/sinatra/reloader.rb b/sinatra-contrib/lib/sinatra/reloader.rb
index <HASH>..<HASH> 100644
--- a/sinatra-contrib/lib/sinatra/reloader.rb
+++ b/sinatra-contrib/lib/sinatra/reloader.rb
@@ -232,6 +232,15 @@ module Sinatra
# Contains the methods defined in Sinatra::Base that are overriden.
module BaseMethods
+ # Protects Sinatra::Base.run! from being called more than once.
+ def run!(*args)
+ if settings.reloader?
+ super unless running?
+ else
+ super
+ end
+ end
+
# Does everything Sinatra::Base#route does, but it also tells the
# +Watcher::List+ for the Sinatra application to watch the defined
# route. | don't run if we are already running, closes #<I> | sinatra_sinatra | train | rb |
c5d0c499bdb878a47e295f3cc507166f1e5e00e7 | diff --git a/pull_into_place/pipeline.py b/pull_into_place/pipeline.py
index <HASH>..<HASH> 100644
--- a/pull_into_place/pipeline.py
+++ b/pull_into_place/pipeline.py
@@ -102,7 +102,7 @@ class Workspace(object):
@property
def rosetta_dir(self):
- return self.find_path('rosetta')
+ return self.find_path('rosetta', self.root_dir)
@property
def rosetta_scripts_path(self):
@@ -273,7 +273,7 @@ Expected to find a file matching '{0}'. Did you forget to compile rosetta?
self.standard_params_dir,
]
- def find_path(self, basename):
+ def find_path(self, basename, install_dir=None):
"""
Look in a few places for a file with the given name. If a custom
version of the file is found in the directory being managed by
@@ -294,7 +294,7 @@ Expected to find a file matching '{0}'. Did you forget to compile rosetta?
# If we didn't find the file, return the path to where we'd like it to
# be installed.
- return os.path.join(self.preferred_install_dir, basename)
+ return os.path.join(install_dir or self.preferred_install_dir, basename)
def check_paths(self):
required_paths = [ | Install the rosetta symlink into the root dir.
This removes the need for creating a basically empty project_params dir
in remote workspaces. | Kortemme-Lab_pull_into_place | train | py |
2e9726a5338c6f7d9c514d23fb60a9454dd32e16 | diff --git a/lib/fabrication/schematic/manager.rb b/lib/fabrication/schematic/manager.rb
index <HASH>..<HASH> 100644
--- a/lib/fabrication/schematic/manager.rb
+++ b/lib/fabrication/schematic/manager.rb
@@ -8,16 +8,13 @@ class Fabrication::Schematic::Manager
def initializing?; @initializing end
- def freeze
- @initializing = false
- end
-
- def clear
- schematics.clear
+ def schematics
+ @schematics ||= {}
end
+ delegate :clear, :empty?, to: :schematics
- def empty?
- schematics.empty?
+ def freeze
+ @initializing = false
end
def register(name, options, &block)
@@ -30,10 +27,6 @@ class Fabrication::Schematic::Manager
schematics[name.to_sym]
end
- def schematics
- @schematics ||= {}
- end
-
def build_stack
@build_stack ||= []
end | Delegate clear and empty? to schematics | paulelliott_fabrication | train | rb |
5c10af46256a96a71df21496c1b8c1e19681c004 | diff --git a/app/controllers/tuttle/ruby_controller.rb b/app/controllers/tuttle/ruby_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/tuttle/ruby_controller.rb
+++ b/app/controllers/tuttle/ruby_controller.rb
@@ -7,7 +7,7 @@ module Tuttle
def index
# TODO: need better filter for sensitive values. this covers DB-style URLs with passwords, passwords, and keys
- @filtered_env = ENV.to_hash.tap { |h| h.each { |k, _v| h[k] = '--FILTERED--' if /.*_(URL|PASSWORD|KEY|KEY_BASE)$/ =~ k } }
+ @filtered_env = ENV.to_hash.tap { |h| h.each { |k, _v| h[k] = '--FILTERED--' if /.*_(URL|PASSWORD|KEY|KEY_BASE|AUTHENTICATION)$/ =~ k } }
end
def tuning | filter *_AUTHENTICATION environment variables | dgynn_tuttle | train | rb |
32f13d972eac3ae48de697dacca1dba28dc423cf | diff --git a/test/unit/list_test.rb b/test/unit/list_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/list_test.rb
+++ b/test/unit/list_test.rb
@@ -158,7 +158,8 @@ EOS
def test_self_default_getter
- assert_equal nil, PublicSuffix::List.class_eval { @default }
+ PublicSuffix::List.default = nil
+ assert_nil PublicSuffix::List.class_eval { @default; }
PublicSuffix::List.default
assert_not_equal nil, PublicSuffix::List.class_eval { @default }
end | As we don't know test_self_default_getter will run, it must be set to nil | weppos_publicsuffix-ruby | train | rb |
caae48701583f8baedb78ba5678457d67a569982 | diff --git a/app/controllers/concerns/paginated.rb b/app/controllers/concerns/paginated.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/concerns/paginated.rb
+++ b/app/controllers/concerns/paginated.rb
@@ -6,7 +6,7 @@ module Paginated
end
def per_page
- @per_page ||= params[:per_page].to_i == 0 ? AppSettings.default_page_size : params[:per].to_i
+ @per_page ||= params[:per_page].to_i == 0 ? AppSettings.default_page_size : params[:per_page].to_i
end
def set_pagination_results(resource, results, total_count = nil) | Fixed per_page assignment booboo | cortex-cms_cortex | train | rb |
1a64226c29ccdb4fb3b9775f7e32bbdea5e32fd5 | diff --git a/Helper/PasswordHelper.php b/Helper/PasswordHelper.php
index <HASH>..<HASH> 100644
--- a/Helper/PasswordHelper.php
+++ b/Helper/PasswordHelper.php
@@ -12,7 +12,7 @@
namespace Orkestra\Bundle\ApplicationBundle\Helper;
use Orkestra\Bundle\ApplicationBundle\Entity\HashedEntity;
-use Orkestra\Bundle\ApplicationBundle\Entity\User;
+use Orkestra\Bundle\ApplicationBundle\Model\UserInterface;
class PasswordHelper
{
@@ -64,7 +64,7 @@ class PasswordHelper
*
* @return HashedEntity
*/
- public function sendPasswordResetEmail(User $user, $subject = 'Password reset request')
+ public function sendPasswordResetEmail(UserInterface $user, $subject = 'Password reset request')
{
$hashedEntity = $this->createHash($user);
$this->emailHelper->createAndSendMessageFromTemplate(
@@ -84,7 +84,7 @@ class PasswordHelper
* @param User $user
* @return HashedEntity
*/
- private function createHash(User $user)
+ private function createHash(UserInterface $user)
{
$hashedEntity = $this->hashedEntityHelper->create($user, new \DateTime('+1 day')); | PasswordHelper now only needs a UserInterface | orkestra_OrkestraApplicationBundle | train | php |
3e0932c6c86f1eb2f48ab71a77b849e5978c2465 | diff --git a/firetv/__init__.py b/firetv/__init__.py
index <HASH>..<HASH> 100644
--- a/firetv/__init__.py
+++ b/firetv/__init__.py
@@ -9,6 +9,7 @@ ADB Debugging must be enabled.
import errno
from socket import error as socket_error
from adb import adb_commands
+from adb.adb_protocol import InvalidChecksumError
# ADB key event codes.
HOME = 3
@@ -205,11 +206,15 @@ class FireTV:
return
result = []
ps = self._adb.StreamingShell('ps')
- for bad_line in ps:
- # The splitting of the StreamingShell doesn't always work
- # this is to ensure that we get only one line
- for line in bad_line.splitlines():
- if search in line:
- result.append(line.strip().rsplit(' ',1)[-1])
- return result
-
+ try:
+ for bad_line in ps:
+ # The splitting of the StreamingShell doesn't always work
+ # this is to ensure that we get only one line
+ for line in bad_line.splitlines():
+ if search in line:
+ result.append(line.strip().rsplit(' ',1)[-1])
+ return result
+ except InvalidChecksumError as e:
+ print e
+ self.connect()
+ raise IOError | Worked around bug with Checksum error dropping connection | happyleavesaoc_python-firetv | train | py |
fd1b74f6360f01fd9800ea8d24284d682a8f38ba | diff --git a/bypy.py b/bypy.py
index <HASH>..<HASH> 100755
--- a/bypy.py
+++ b/bypy.py
@@ -1500,13 +1500,15 @@ class ByPy(object):
return EFileWrite
def __store_json(self, r):
+ j = {}
try:
- r.json()
+ j = r.json()
except Exception:
perr("Failed to decode JSON:\n" \
"Exception:\n{}".format(traceback.format_exc()))
+ perr("Error response:\n{}".format(r.text));
return EInvalidJson
- return self.__store_json_only(r.json())
+ return self.__store_json_only(j)
def __load_local_bduss(self):
try: | Print auth/refresh web response on error | houtianze_bypy | train | py |
77f9cff99b3d2bfc9e81e5439c025be8a9900f21 | diff --git a/lib/api.js b/lib/api.js
index <HASH>..<HASH> 100644
--- a/lib/api.js
+++ b/lib/api.js
@@ -1,7 +1,8 @@
/**
* Helper "class" for accessing MediaWiki API and handling cookie-based session
*/
- var VERSION = '0.3.5';
+module.exports = (function() {
+ var VERSION = '0.3.6';
// @see https://github.com/mikeal/request
var request = require('request');
@@ -104,15 +105,21 @@
port: this.port,
hostname: this.server,
pathname: this.path + '/api.php',
- query: params
+ query: (options.method === 'GET') ? params : {}
});
+ // POST all parameters (avoid "request string too long" errors)
+ if (method === 'POST') {
+ options.form = params;
+ }
+
request(options, function(error, response, body) {
if (error) {
throw 'Request to API failed: ' + error;
}
if (response.statusCode !== 200) {
+ console.log(new Error().stack);
throw 'Request to API failed: HTTP status code was ' + response.statusCode;
}
@@ -246,4 +253,5 @@
}
};
- module.exports = api;
+ return api;
+}()); | api.js:
* fix for huge POST requests (make sure data is POSTed, not encoded in URL)
* wrap module in immediate function
* <I> | macbre_nodemw | train | js |
766d7c1e968477f0be9b517bb1dd31daa99456b5 | diff --git a/src/main/java/org/java_websocket/WebSocket.java b/src/main/java/org/java_websocket/WebSocket.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/java_websocket/WebSocket.java
+++ b/src/main/java/org/java_websocket/WebSocket.java
@@ -137,17 +137,18 @@ public interface WebSocket {
boolean hasBufferedData();
/**
- * Returns the address of the endpoint this socket is connected to, or{@code null} if it is
+ * Returns the address of the endpoint this socket is connected to, or {@code null} if it is
* unconnected.
*
- * @return never returns null
+ * @return the remote socket address or null, if this socket is unconnected
*/
InetSocketAddress getRemoteSocketAddress();
/**
- * Returns the address of the endpoint this socket is bound to.
+ * Returns the address of the endpoint this socket is bound to, or {@code null} if it is not
+ * bound.
*
- * @return never returns null
+ * @return the local socket address or null, if this socket is not bound
*/
InetSocketAddress getLocalSocketAddress(); | Update documentation comments for member methods
Update documentation comments for methods getRemoteSocketAddress and getLocalSocketAddress in WebSocket.java. | TooTallNate_Java-WebSocket | train | java |
06f7b1a80fefe952665aae996e380f8798812287 | diff --git a/montblanc/impl/biro/v5/gpu/RimeSumCoherencies.py b/montblanc/impl/biro/v5/gpu/RimeSumCoherencies.py
index <HASH>..<HASH> 100644
--- a/montblanc/impl/biro/v5/gpu/RimeSumCoherencies.py
+++ b/montblanc/impl/biro/v5/gpu/RimeSumCoherencies.py
@@ -26,8 +26,8 @@ import pycuda.gpuarray as gpuarray
import montblanc.impl.biro.v4.gpu.RimeSumCoherencies
class RimeSumCoherencies(montblanc.impl.biro.v4.gpu.RimeSumCoherencies.RimeSumCoherencies):
- def __init__(self, weight_vector=False):
- super(RimeSumCoherencies, self).__init__(weight_vector=weight_vector)
+ def __init__(self):
+ super(RimeSumCoherencies, self).__init__()
def initialise(self, solver, stream=None):
super(RimeSumCoherencies, self).initialise(solver,stream)
def shutdown(self, solver, stream=None): | Cease passing weight vector flags in v5. | ska-sa_montblanc | train | py |
4fd14159cedc96bb2676ba371d9e0da5c3bb3ab7 | diff --git a/js/sia.js b/js/sia.js
index <HASH>..<HASH> 100644
--- a/js/sia.js
+++ b/js/sia.js
@@ -18,7 +18,6 @@ function SiadWrapper () {
var settings = {
fileName: process.platform === 'win32' ? 'siad.exe' : 'siad',
detached: false,
- agent: 'Sia-Agent',
address: 'localhost:9980',
rpcAddress: ':9981',
hostAddress: ':9982',
@@ -49,7 +48,7 @@ function SiadWrapper () {
call.url = 'http://' + settings.address + call.url
call.json = true
call.headers = {
- 'User-Agent': settings.agent
+ 'User-Agent': 'Sia-Agent'
}
// Return the request sent if the user wants to be creative and get more
@@ -163,7 +162,6 @@ function SiadWrapper () {
// Spawn siad
const Process = require('child_process').spawn
var daemonProcess = new Process(nodePath.join(settings.path, settings.fileName), [
- '--agent=' + settings.agent,
'--api-addr=' + settings.address,
'--rpc-addr=' + settings.rpcAddress,
'--host-addr=' + settings.hostAddress, | User agent option prevented siad from starting
Somehow I thought I already fixed this. | NebulousLabs_Nodejs-Sia | train | js |
2146a4b5937b044e96e5760c88258982495dbc1a | diff --git a/lib/sensu/api/routes/silenced.rb b/lib/sensu/api/routes/silenced.rb
index <HASH>..<HASH> 100644
--- a/lib/sensu/api/routes/silenced.rb
+++ b/lib/sensu/api/routes/silenced.rb
@@ -77,7 +77,7 @@ module Sensu
if data[:expire]
expire = data[:expire]
expire += begin_timestamp - timestamp
- @redis.expire(silenced_key, expire) do
+ @redis.expire(silenced_key, expire) do
created!
end
else | [maitenance] fixed minor indentation issue | sensu_sensu | train | rb |
0dd2fe692190d9cb67b714fda6a5147204b6bce6 | diff --git a/jsx.js b/jsx.js
index <HASH>..<HASH> 100644
--- a/jsx.js
+++ b/jsx.js
@@ -43,12 +43,9 @@
acornJSXWalk(walk.base);
// Allow renaming variables used in JSX.
- infer.searchVisitor.JSXIdentifier = function () {
- // Identifier is defined ad-hoc, so call the latest instance. Using
- // `this` is risky because the callee could be detached. However, at
- // present, Tern only passes this visitor and its descendants to `walk`
- // methods which preserve the context.
- return this.Identifier.apply(this, arguments);
+ infer.searchVisitor.JSXIdentifier = function (node, st, c) {
+ // Identifier is defined ad-hoc, so call the latest instance.
+ c(node, st, 'Identifier');
};
// Allow finding the definition, type and docs of a JSXIdentifier. | Use typical "forwarding" technique. | jacksonrayhamilton_tern-jsx | train | js |
a1a8ca4814dc35766b897f2d825212faf088621a | diff --git a/src/util/Constants.js b/src/util/Constants.js
index <HASH>..<HASH> 100644
--- a/src/util/Constants.js
+++ b/src/util/Constants.js
@@ -723,7 +723,7 @@ exports.VerificationLevels = createEnum(['NONE', 'LOW', 'MEDIUM', 'HIGH', 'VERY_
* * MESSAGE_ALREADY_HAS_THREAD
* * THREAD_LOCKED
* * MAXIMUM_ACTIVE_THREADS
- * * MAXIMUM_ACTIVE_ANNOUCEMENT_THREAD
+ * * MAXIMUM_ACTIVE_ANNOUNCEMENT_THREAD
* @typedef {string} APIError
* @see {@link https://discord.com/developers/docs/topics/opcodes-and-status-codes#json-json-error-codes}
*/ | docs(Constants): fix typo "announcement" (#<I>) | discordjs_discord.js | train | js |
ded67bd62442c72a95df84c474a38c10152c2029 | diff --git a/wayback-core/src/main/java/org/archive/wayback/webapp/AccessPoint.java b/wayback-core/src/main/java/org/archive/wayback/webapp/AccessPoint.java
index <HASH>..<HASH> 100644
--- a/wayback-core/src/main/java/org/archive/wayback/webapp/AccessPoint.java
+++ b/wayback-core/src/main/java/org/archive/wayback/webapp/AccessPoint.java
@@ -503,6 +503,8 @@ implements ShutdownListener {
if (redirScheme == null && isExactSchemeMatch()) {
location = UrlOperations.resolveUrl(closest.getOriginalUrl(), location);
redirScheme = UrlOperations.urlToScheme(location);
+ } else if (location.startsWith("/")) {
+ location = UrlOperations.resolveUrl(closest.getOriginalUrl(), location);
}
if (getSelfRedirectCanonicalizer() != null) { | FIX: self-redirect check accounts for relative urls | iipc_openwayback | train | java |
2862e55085434c849de9d4f979a31a896a914f66 | diff --git a/consumer_test.go b/consumer_test.go
index <HASH>..<HASH> 100644
--- a/consumer_test.go
+++ b/consumer_test.go
@@ -243,7 +243,7 @@ func TestConsumerRebalancingMultiplePartitions(t *testing.T) {
seedBroker.Close()
}
-func ExampleConsumer_usingSelect() {
+func ExampleConsumer_select() {
master, err := NewConsumer([]string{"localhost:9092"}, nil)
if err != nil {
panic(err)
@@ -285,7 +285,7 @@ consumerLoop:
fmt.Println("Got", msgCount, "messages.")
}
-func ExampleConsumer_usingGoroutines() {
+func ExampleConsumer_goroutines() {
master, err := NewConsumer([]string{"localhost:9092"}, nil)
if err != nil {
panic(err)
@@ -298,7 +298,7 @@ func ExampleConsumer_usingGoroutines() {
}
}()
- consumer, err := master.ConsumePartition("my_topic", 0, 0)
+ consumer, err := master.ConsumePartition("my_topic", 0, OffsetOldest)
if err != nil {
panic(err)
} else { | Tweaks to consumer_test.rb | Shopify_sarama | train | go |
87fab1a5c1494b359234cb568a816e64bffe2285 | diff --git a/tests/class-wp-cli-test-case.php b/tests/class-wp-cli-test-case.php
index <HASH>..<HASH> 100644
--- a/tests/class-wp-cli-test-case.php
+++ b/tests/class-wp-cli-test-case.php
@@ -43,12 +43,13 @@ abstract class Wp_Cli_Test_Case extends PHPUnit_Framework_TestCase {
}
class Wordpress_Installer {
+
private $install_dir;
private $runner;
- public function __construct( $install_dir, $runner ) {
+ public function __construct( $install_dir ) {
$this->install_dir = $install_dir;
- $this->runner = $runner;
+ $this->runner = new Command_Runner( $install_dir );
}
public function create_config( $db_settings ) { | don't require passing a runner to Wordpress_Installer | wp-cli_export-command | train | php |
3e40dc1c43b76e0d7543780820f413a9edd030b3 | diff --git a/closure/goog/locale/timezonefingerprint.js b/closure/goog/locale/timezonefingerprint.js
index <HASH>..<HASH> 100644
--- a/closure/goog/locale/timezonefingerprint.js
+++ b/closure/goog/locale/timezonefingerprint.js
@@ -201,7 +201,7 @@ goog.locale.TimeZoneFingerprint = {
680176266: ['RU-Asia/Krasnoyarsk'],
1465210176: ['US-America/Anchorage'],
805312908: ['NI-America/Managua'],
- 492088530: ['AU-Australia/Currie', 'AU-Australia/Hobart'],
+ 492088530: ['AU-Australia/Hobart', 'AU-Australia/Currie'],
901076366: ['BR-America/Campo_Grande', 'BR-America/Cuiaba'],
943019406: ['CL-America/Santiago', 'AQ-Antarctica/Palmer'],
928339288: ['US-America/New_York', 'CA-America/Montreal', | Avoid mystifying certain DownUnder users. Hobart is a far bigger place than Currie. Note that goog.locale.timeZoneDetection.detectTimeZone() looks at the 0'th string in the array.
-------------
Created by MOE: <URL> | google_closure-library | train | js |
bda772578d0dc970360ba9d8302b34839a5f512c | diff --git a/estnltk/taggers/web_taggers/v01/batch_processing_web_tagger.py b/estnltk/taggers/web_taggers/v01/batch_processing_web_tagger.py
index <HASH>..<HASH> 100644
--- a/estnltk/taggers/web_taggers/v01/batch_processing_web_tagger.py
+++ b/estnltk/taggers/web_taggers/v01/batch_processing_web_tagger.py
@@ -44,7 +44,7 @@ class BatchProcessingWebTagger( WebTagger ):
def batch_process(self, text: Text, layers: MutableMapping[str, Layer], parameters=None):
# TODO: because estnltk.layer_operations contains some tangled
# imports, we have to use inner-import-hack (for python 36)
- from estnltk.layer_operations import join_layers
+ from estnltk.layer_operations import join_layers_while_reusing_spans
assert self.batch_layer is not None and \
isinstance(self.batch_layer, str) and \
self.batch_layer in layers
@@ -80,7 +80,7 @@ class BatchProcessingWebTagger( WebTagger ):
resulting_layers.append( new_layer )
logger.debug( 'Batch processing completed.'.format() )
# Join/concatenate results
- new_layer = join_layers( resulting_layers, separators )
+ new_layer = join_layers_while_reusing_spans( resulting_layers, separators )
# Set Text object and return newly created layer
new_layer.text_object = text
return new_layer | Refactored BatchProcessingWebTagger: now join_layers_while_reusing_spans is used for joining | estnltk_estnltk | train | py |
967cc1a76d765378644b6bea8006878a74d38d34 | diff --git a/pyphi/labels.py b/pyphi/labels.py
index <HASH>..<HASH> 100644
--- a/pyphi/labels.py
+++ b/pyphi/labels.py
@@ -12,18 +12,26 @@ def default_labels(indices):
class NodeLabels:
- '''
- TODO: validate labels for duplicates
- TODO: pass in indices if defaults are generated here
+ '''Text labels for nodes in a network.
+
+ Labels can either be instantiated as a tuple of strings:
+
+ >>> NodeLabels(('A', 'IN'), (0, 1)).labels
+ ('A', 'IN')
+
+ Or, if all labels are a single character, as a string:
+
+ >>> NodeLabels('AB', (0, 1)).labels
+ ('A', 'B')
'''
def __init__(self, labels, node_indices):
if labels is None:
labels = default_labels(node_indices)
- self.labels = labels
+ self.labels = tuple(label for label in labels)
self.node_indices = node_indices
- validate.node_labels(labels, node_indices)
+ validate.node_labels(self.labels, node_indices)
# Dicts mapping indices to labels and vice versa
self._l2i = dict(zip(self.labels, self.node_indices)) | Cast string of labels to a tuple | wmayner_pyphi | train | py |
a6340c69aa762500bc0db2ceae9b91bdbab325d9 | diff --git a/lib/axiom/relation/operation/sorted/direction_set.rb b/lib/axiom/relation/operation/sorted/direction_set.rb
index <HASH>..<HASH> 100644
--- a/lib/axiom/relation/operation/sorted/direction_set.rb
+++ b/lib/axiom/relation/operation/sorted/direction_set.rb
@@ -90,7 +90,7 @@ module Axiom
# @api private
def cmp_tuples(left, right)
reduce(0) do |cmp, direction|
- break cmp if cmp.nonzero?
+ return cmp if cmp.nonzero?
direction.call(left, right)
end
end | Refactor comparison to return early when it is nonzero | dkubb_axiom | train | rb |
bd9f3ced15339a3800a3184daed1508014c94738 | diff --git a/km3pipe/io/aanet.py b/km3pipe/io/aanet.py
index <HASH>..<HASH> 100644
--- a/km3pipe/io/aanet.py
+++ b/km3pipe/io/aanet.py
@@ -327,7 +327,7 @@ class AanetPump(Pump):
tab_dict['parameter'].append(parameter)
tab_dict['field_names'].append(' '.join(fields))
tab_dict['field_values'].append(' '.join(values))
- tab_dict['dtype'].append(', '.join(types))
+ tab_dict['dtype'].append(' '.join(types))
return Table(
tab_dict, h5loc='/raw_header', name='RawHeader', h5singleton=True
) | Don't use commas for splitting char in the dtype field | tamasgal_km3pipe | train | py |
080f9bb63e79fd8cdc6e841be04835ad5d66dd8a | diff --git a/Tests/Logger/LoggerFactoryTest.php b/Tests/Logger/LoggerFactoryTest.php
index <HASH>..<HASH> 100644
--- a/Tests/Logger/LoggerFactoryTest.php
+++ b/Tests/Logger/LoggerFactoryTest.php
@@ -48,14 +48,16 @@ class LoggerFactoryTest extends \PHPUnit_Framework_TestCase {
{
$this->initiateContainerWithDebugMode(false);
$this->loggerFactory->addLogger("invalid", new AuditLog());
+ $this->assertAttributeEquals(array(), 'loggers', $this->loggerFactory);
}
public function testLoggerFactoryThrowsNoExceptionOnAddValidLogger()
{
$logger1 = $this->getMock('Xiidea\EasyAuditBundle\Logger\LoggerInterface');
- $loggerFactory = new LoggerFactory();
- $loggerFactory->addLogger("valid", $logger1);
+ $this->loggerFactory->addLogger("valid", $logger1);
+
+ $this->assertAttributeEquals(array('valid'=>$logger1), 'loggers', $this->loggerFactory);
}
public function testExecuteAllLoggers() { | Assert for check if logger is being added or not | xiidea_EasyAuditBundle | train | php |
aecf2a62d5e6a13dbe906d0d8cd3a2ddd554a21c | diff --git a/disposable_email_checker/__init__.py b/disposable_email_checker/__init__.py
index <HASH>..<HASH> 100644
--- a/disposable_email_checker/__init__.py
+++ b/disposable_email_checker/__init__.py
@@ -1 +1 @@
-__version__ = '1.0.0'
+__version__ = '1.1.0' | version bump <I> - Increase number of blacklisted domains | aaronbassett_DisposableEmailChecker | train | py |
ef65851c42b11b498a3829b93378565467542f5d | diff --git a/limpyd/__init__.py b/limpyd/__init__.py
index <HASH>..<HASH> 100644
--- a/limpyd/__init__.py
+++ b/limpyd/__init__.py
@@ -2,7 +2,7 @@
power and the control of the Redis API, in a limpid way, with just as
abstraction as needed."""
-VERSION = (0, 1, 0)
+VERSION = (0, 1, 1)
__author__ = 'Yohan Boniface'
__contact__ = "[email protected]"
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@
import codecs
-from setuptools import setup, find_packages
+from setuptools import setup
import limpyd
@@ -18,7 +18,7 @@ setup(
keywords = "redis",
url = limpyd.__homepage__,
download_url = "https://github.com/yohanboniface/redis-limpyd/tags",
- packages = find_packages(),
+ packages = ['limpyd'],
include_package_data=True,
install_requires=["redis", ],
platforms=["any"], | Include only the "limpyd" package in setup.py (no tests) | limpyd_redis-limpyd | train | py,py |
712bb76528f88e7b217ee053450c00dc66c8b11b | diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -23,7 +23,7 @@ module.exports = function createServePlaceholder (_options) {
}
// In case of no handler guessed
- if (handler === undefined) {
+ if (typeof handler === 'undefined') {
if (options.skipUnknown) {
// Skip this middleware
return next() | refactor: use typeof for undefined check | nuxt_serve-placeholder | train | js |
92ee210549292e559905b7b43cfd437aefa90c48 | diff --git a/lib/fog/rackspace/models/auto_scale/policy.rb b/lib/fog/rackspace/models/auto_scale/policy.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/rackspace/models/auto_scale/policy.rb
+++ b/lib/fog/rackspace/models/auto_scale/policy.rb
@@ -154,6 +154,18 @@ module Fog
true
end
+ # Saves the policy
+ # Creates policy if it is new, otherwise it will update it
+ # @return [Boolean] true if policy has saved
+ def save
+ if persisted?
+ update
+ else
+ create
+ end
+ true
+ end
+
# Destroy the policy
#
# @return [Boolean] returns true if policy has started deleting | [rackspace|auto_scale] added a save method to policy | fog_fog | train | rb |
de3ae768a715f408cc3e361bcf46e6bd98402885 | diff --git a/Example/bouncing/index.js b/Example/bouncing/index.js
index <HASH>..<HASH> 100644
--- a/Example/bouncing/index.js
+++ b/Example/bouncing/index.js
@@ -43,6 +43,7 @@ class Snappable extends Component {
return (
<PanGestureHandler
{...this.props}
+ maxPointers={1}
onGestureEvent={this._onGestureEvent}
onHandlerStateChange={this._onHandlerStateChange}>
<Animated.View style={{ transform: [{ translateX: this._transX }] }}> | Make it easier to twist view in twist & bounce example. | kmagiera_react-native-gesture-handler | train | js |
038a60128da4d0196cf89eee5abfd673834923c3 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -3,6 +3,7 @@
var fs = require('fs');
var url = require('url');
+var pathlib = require('path');
var co = require('co');
var maybe = require('call-me-maybe');
@@ -10,7 +11,7 @@ var fetch = require('node-fetch');
var yaml = require('js-yaml');
var common = require('./common.js');
-var statusCodes = require('./statusCodes.json');
+var statusCodes = require(pathlib.join(__dirname,'statusCodes.json'));
// TODO split out into params, security etc
// TODO handle specification-extensions with plugins? | Make statusCodes.json findable when loaded as module | wework_speccy | train | js |
38ad7a8efa38049d5f219943fc8ab2406c14b0b3 | diff --git a/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java b/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
index <HASH>..<HASH> 100644
--- a/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
+++ b/agrona/src/main/java/org/agrona/DeadlineTimerWheel.java
@@ -244,7 +244,7 @@ public class DeadlineTimerWheel
{
final long[] array = wheel[currentTick & wheelMask];
- for (int length = array.length; pollIndex < length && maxTimersToExpire > timersExpired; pollIndex++)
+ for (int i = 0, length = array.length; i < length && maxTimersToExpire > timersExpired; i++)
{
final long deadline = array[pollIndex];
@@ -262,6 +262,8 @@ public class DeadlineTimerWheel
return timersExpired;
}
}
+
+ pollIndex = (pollIndex + 1) >= length ? 0 : (pollIndex + 1);
}
if (maxTimersToExpire > timersExpired && currentTickTime() <= now) | fix handling of timers that get shceduled to expire in the current tick by always perfoming one loop in the poll. If breaking out due to max expirations, don't advance the tick. | real-logic_agrona | train | java |
2b6baa2d7f48a5c507a3e72ec8eaafa2b84f1d0b | diff --git a/parsedatetime/pdt_locales/base.py b/parsedatetime/pdt_locales/base.py
index <HASH>..<HASH> 100644
--- a/parsedatetime/pdt_locales/base.py
+++ b/parsedatetime/pdt_locales/base.py
@@ -86,8 +86,8 @@ decimal_mark = '.'
# this will be added to re_values later
units = {
- 'seconds': ['second', 'seconds', 'sec', 's'],
- 'minutes': ['minute', 'minutes', 'min', 'm'],
+ 'seconds': ['second', 'seconds', 'sec', 'secs' 's'],
+ 'minutes': ['minute', 'minutes', 'min', 'mins', 'm'],
'hours': ['hour', 'hours', 'hr', 'h'],
'days': ['day', 'days', 'dy', 'd'],
'weeks': ['week', 'weeks', 'wk', 'w'], | Add 'secs' and 'mins' into base units | bear_parsedatetime | train | py |
311b70a7c013805dfaaf878060a3633dc17770c1 | diff --git a/src/Model/AssociationsAwareTrait.php b/src/Model/AssociationsAwareTrait.php
index <HASH>..<HASH> 100644
--- a/src/Model/AssociationsAwareTrait.php
+++ b/src/Model/AssociationsAwareTrait.php
@@ -244,6 +244,12 @@ trait AssociationsAwareTrait
*/
if ($field->getAssocCsvModule() === $module) {
$className = $module;
+ // Set self related association
+ $this->setAssociation(
+ 'hasMany',
+ static::generateAssociationName($field->getName(), $className),
+ ['className' => $className, 'foreignKey' => $field->getName()]
+ );
$associationType = 'belongsTo';
} | Add self related associations (task #<I>) | QoboLtd_cakephp-csv-migrations | train | php |
8125808f2216666b8ca3ae7d1baac43a9bb7edae | diff --git a/blockstack_client/cli.py b/blockstack_client/cli.py
index <HASH>..<HASH> 100644
--- a/blockstack_client/cli.py
+++ b/blockstack_client/cli.py
@@ -214,7 +214,7 @@ def run_cli(argv=None, config_path=CONFIG_PATH):
sys.exit(1)
argv = new_argv
- if cli_password or os.environ.get('BLOCKSTACK_CLIENT_WALLET_PASSWORD') is None:
+ if cli_password and os.environ.get('BLOCKSTACK_CLIENT_WALLET_PASSWORD') is None:
log.debug("Use CLI password")
os.environ["BLOCKSTACK_CLIENT_WALLET_PASSWORD"] = cli_password | don't set to boolean | blockstack_blockstack-core | train | py |
9750caa215bc745066f691c208410669af5ec73d | diff --git a/client/html/src/Client/Html/Catalog/Lists/Standard.php b/client/html/src/Client/Html/Catalog/Lists/Standard.php
index <HASH>..<HASH> 100644
--- a/client/html/src/Client/Html/Catalog/Lists/Standard.php
+++ b/client/html/src/Client/Html/Catalog/Lists/Standard.php
@@ -646,13 +646,15 @@ class Standard
$page = min( max( $view->param( 'l_page', 1 ), 1 ), $pages );
$products = \Aimeos\Controller\Frontend::create( $context, 'product' )
+ // apply sort() before category() to prioritize user sorting over the sorting through category
+ ->sort( $sort )
->category( $catids, 'default', $level )
->supplier( $view->param( 'f_supid', [] ) )
->allOf( $view->param( 'f_attrid', [] ) )
->oneOf( $view->param( 'f_optid', [] ) )
->oneOf( $view->param( 'f_oneid', [] ) )
->text( $view->param( 'f_search' ) )
- ->slice( ( $page - 1 ) * $size, $size )->sort( $sort )
+ ->slice( ( $page - 1 ) * $size, $size )
->uses( $domains )
->search( $total ); | Sort by parameter before category position (#<I>)
Sort by the parameter `f_sort` with higher priority then the position of the item in the category. | aimeos_ai-client-html | train | php |
31839c44808d17c9d13ea78134f8f431a36a8ffe | diff --git a/SoftLayer/CLI/modules/subnet.py b/SoftLayer/CLI/modules/subnet.py
index <HASH>..<HASH> 100644
--- a/SoftLayer/CLI/modules/subnet.py
+++ b/SoftLayer/CLI/modules/subnet.py
@@ -93,11 +93,12 @@ Options:
table.align['cost'] = 'r'
total = 0.0
- for price in result['prices']:
- total += float(price.get('recurringFee', 0.0))
- rate = "%.2f" % float(price['recurringFee'])
+ if 'prices' in result:
+ for price in result['prices']:
+ total += float(price.get('recurringFee', 0.0))
+ rate = "%.2f" % float(price['recurringFee'])
- table.add_row([price['item']['description'], rate])
+ table.add_row([price['item']['description'], rate])
table.add_row(['Total monthly cost', "%.2f" % total])
return table | Make sure the 'prices' key exists in the dictionary before trying to use it | softlayer_softlayer-python | train | py |
cad70a2d06043cf1e3f6ba628ca28d6fccd6be04 | diff --git a/resources/views/app.blade.php b/resources/views/app.blade.php
index <HASH>..<HASH> 100644
--- a/resources/views/app.blade.php
+++ b/resources/views/app.blade.php
@@ -43,7 +43,7 @@
@endforeach
</head>
-<body>
+<body class="page-{{\Str::slug(\Route::currentRouteName())}}">
<div class="container-fluid" data-controller="@yield('controller')" @yield('controller-data')> | Added routeprefixed class to body (#<I>)
* Added routeprefixed class to body
Added a class to body, that will always use a slugified version of the current path as basic.
This allows to style subpages (login, template, ...) differently easily using a custom css file.
* Added slugified route name as body class | orchidsoftware_platform | train | php |
9d6418aa4ba49c531dfd0b8940eba32c605c67f0 | diff --git a/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java b/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java
index <HASH>..<HASH> 100644
--- a/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java
+++ b/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java
@@ -3460,13 +3460,13 @@ public class GrailsDomainBinder implements MetadataContributor {
protected final GrailsDomainBinder binder;
protected final MetadataBuildingContext buildingContext;
- protected static CollectionType SET;
- protected static CollectionType LIST;
- protected static CollectionType BAG;
- protected static CollectionType MAP;
- protected static boolean initialized;
+ protected CollectionType SET;
+ protected CollectionType LIST;
+ protected CollectionType BAG;
+ protected CollectionType MAP;
+ protected boolean initialized;
- protected static final Map<Class<?>, CollectionType> INSTANCES = new HashMap<>();
+ protected final Map<Class<?>, CollectionType> INSTANCES = new HashMap<>();
public abstract Collection create(ToMany property, PersistentClass owner,
String path, InFlightMetadataCollector mappings, String sessionFactoryBeanName) throws MappingException; | fix for #<I> (#<I>) | grails_gorm-hibernate5 | train | java |
9a76f8e52127688404ae2c1c2979718c70b54cfe | diff --git a/tests/unit/Gateway/SeemeGatewayTest.php b/tests/unit/Gateway/SeemeGatewayTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/Gateway/SeemeGatewayTest.php
+++ b/tests/unit/Gateway/SeemeGatewayTest.php
@@ -2,6 +2,7 @@
namespace Indigo\Sms\Test\Gateway;
+use Indigo\Sms\Message;
use Indigo\Sms\Gateway\SeemeGateway;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Stream;
@@ -52,13 +53,7 @@ class SeemeGatewayTest extends AbstractGatewayTest
*/
public function testMessage()
{
- $message = \Mockery::mock('Indigo\\Sms\\Message');
-
- $message->shouldReceive('getData')
- ->andReturn(array(
- 'number' => 123456789,
- 'message' => 'This is a test message',
- ));
+ $message = new Message(123456789, 'This is a test message');
$result = $this->gateway->send($message); | Removes Message mocking for now, error thrown because of serializable | indigophp-archive_sms | train | php |
56cd57872cd5f6f7198b38201428845ae8b554ba | diff --git a/lib/browser/api/browser-window.js b/lib/browser/api/browser-window.js
index <HASH>..<HASH> 100644
--- a/lib/browser/api/browser-window.js
+++ b/lib/browser/api/browser-window.js
@@ -95,17 +95,6 @@ BrowserWindow.prototype._init = function () {
// Notify the creation of the window.
app.emit('browser-window-created', {}, this)
- // Be compatible with old APIs.
- this.webContents.on('devtools-focused', () => {
- this.emit('devtools-focused')
- })
- this.webContents.on('devtools-opened', () => {
- this.emit('devtools-opened')
- })
- this.webContents.on('devtools-closed', () => {
- this.emit('devtools-closed')
- })
-
Object.defineProperty(this, 'devToolsWebContents', {
enumerable: true,
configurable: false, | Remove BrowserWindow events now on WebContents | electron_electron | train | js |
44680ec4f3d71b0064e3a416525d176cf613a92b | diff --git a/src/Illuminate/Routing/Router.php b/src/Illuminate/Routing/Router.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Routing/Router.php
+++ b/src/Illuminate/Routing/Router.php
@@ -305,7 +305,20 @@ class Router implements RegistrarContract, BindingRegistrar
}
/**
- * Route an api resource to a controller.
+ * Register an array of API resource controllers.
+ *
+ * @param array $resources
+ * @return void
+ */
+ public function apiResources(array $resources)
+ {
+ foreach ($resources as $name => $controller) {
+ $this->apiResource($name, $controller);
+ }
+ }
+
+ /**
+ * Route an API resource to a controller.
*
* @param string $name
* @param string $controller | [<I>] Add apiResources function to Router (#<I>)
* Add apiResources function to Router
Mimick the functionality of resources in routes with apiResources
* Update Router.php | laravel_framework | train | php |
8bec318b5d55910a602c5e46c414e2cd3e1431b4 | diff --git a/cmd/kube-scheduler/app/options/configfile.go b/cmd/kube-scheduler/app/options/configfile.go
index <HASH>..<HASH> 100644
--- a/cmd/kube-scheduler/app/options/configfile.go
+++ b/cmd/kube-scheduler/app/options/configfile.go
@@ -53,7 +53,7 @@ func loadConfig(data []byte) (*config.KubeSchedulerConfiguration, error) {
// more details.
cfgObj.TypeMeta.APIVersion = gvk.GroupVersion().String()
if cfgObj.TypeMeta.APIVersion == configv1beta2.SchemeGroupVersion.String() {
- klog.Warning("KubeSchedulerConfiguration v1beta2 is deprecated in v1.25, will be removed in v1.26")
+ klog.InfoS("KubeSchedulerConfiguration v1beta2 is deprecated in v1.25, will be removed in v1.26")
}
return cfgObj, nil
} | Switch klog call to use structured logging | kubernetes_kubernetes | train | go |
9cd062ff99c4ef00d0eeb011ec91e64972ebed47 | diff --git a/client/my-sites/pages/page/index.js b/client/my-sites/pages/page/index.js
index <HASH>..<HASH> 100644
--- a/client/my-sites/pages/page/index.js
+++ b/client/my-sites/pages/page/index.js
@@ -211,7 +211,11 @@ class Page extends Component {
}
return (
- <PopoverMenuItem onClick={ this.editPage } onMouseOver={ preloadEditor }>
+ <PopoverMenuItem
+ onClick={ this.editPage }
+ onMouseOver={ preloadEditor }
+ onFocus={ preloadEditor }
+ >
<Gridicon icon="pencil" size={ 18 } />
{ this.props.translate( 'Edit' ) }
</PopoverMenuItem>
@@ -456,6 +460,7 @@ class Page extends Component {
}
onClick={ this.props.recordPageTitle }
onMouseOver={ preloadEditor }
+ onFocus={ preloadEditor }
data-tip-target={ 'page-' + page.slug }
>
{ depthIndicator }
@@ -463,7 +468,7 @@ class Page extends Component {
{ latestPostsPage && (
<InfoPopover position="right">
{ translate(
- 'The content of your latest posts page is automatically generated and it cannot be edited.'
+ 'The content of your latest posts page is automatically generated and cannot be edited.'
) }
</InfoPopover>
) } | Resolve a<I>y warnings | Automattic_wp-calypso | train | js |
c2d9dc45bd1a75475043b6796fac7c7d4d368b60 | diff --git a/lib/health-data-standards/import/bundle/importer.rb b/lib/health-data-standards/import/bundle/importer.rb
index <HASH>..<HASH> 100644
--- a/lib/health-data-standards/import/bundle/importer.rb
+++ b/lib/health-data-standards/import/bundle/importer.rb
@@ -64,8 +64,11 @@ module HealthDataStandards
return bundle
ensure
- bundle.done_importing = true unless bundle.nil?
- bundle.save
+ # If the bundle is nil or the bundle has never been saved then do not set done_importing or run save.
+ if bundle && bundle.created_at
+ bundle.done_importing = true
+ bundle.save
+ end
end | Do not save the bundle if it did not successfully import
Currently if you import a bundle and it fails because the same version already exists in the database, then the ensure block is still run and the bundle is still saved, leaving 2 records for the same bundle in the database. This adds a check to see if the bundle was ever saved in the first place before running bundle.save again. This issue can be seen now by accessing the cypress bundle import admin page and uploading the same bundle twice. | projectcypress_health-data-standards | train | rb |
b87ae89e8610f76c9902c46644bdca6fd4e83607 | diff --git a/sqlparse/filters/reindent.py b/sqlparse/filters/reindent.py
index <HASH>..<HASH> 100644
--- a/sqlparse/filters/reindent.py
+++ b/sqlparse/filters/reindent.py
@@ -168,7 +168,8 @@ class ReindentFilter(object):
def _process_default(self, tlist, stmts=True):
self._split_statements(tlist) if stmts else None
self._split_kwds(tlist)
- [self._process(sgroup) for sgroup in tlist.get_sublists()]
+ for sgroup in tlist.get_sublists():
+ self._process(sgroup)
def process(self, stmt):
self._curr_stmt = stmt | Make reindent more robust regarding max recursion errors. | andialbrecht_sqlparse | train | py |
e1f2168b7ce5a54f5128d64ceaec08f8355d7d4a | diff --git a/lib/discordrb/voice/voice_bot.rb b/lib/discordrb/voice/voice_bot.rb
index <HASH>..<HASH> 100644
--- a/lib/discordrb/voice/voice_bot.rb
+++ b/lib/discordrb/voice/voice_bot.rb
@@ -99,6 +99,12 @@ module Discordrb::Voice
@encoder.filter_volume = value
end
+ # @see #filter_volume=
+ # @return [Integer] the volume used as a filter for ffmpeg/avconv.
+ def filter_volume
+ @encoder.filter_volume
+ end
+
# Pause playback. This is not instant; it may take up to 20 ms for this change to take effect. (This is usually
# negligible.)
def pause | Add a reader for filter_volume | meew0_discordrb | train | rb |
fbf7d8e92cc34e2012b386a78d0fb0ac89aa7177 | diff --git a/tls.go b/tls.go
index <HASH>..<HASH> 100644
--- a/tls.go
+++ b/tls.go
@@ -10,8 +10,9 @@
package gramework
import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
"crypto/rand"
- "crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
@@ -27,7 +28,7 @@ func selfSignedCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate,
return nil, fmt.Errorf("self-signed certificate for %q not permitted", clientHello.ServerName)
}
- priv, err := rsa.GenerateKey(rand.Reader, 1024)
+ priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
} | Using ECDSA for self-signed certificat | gramework_gramework | train | go |
b0dbd5f595cdd6acfa7e9147189ff3dfbfccbb51 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -41,6 +41,6 @@ module.exports = function createGenerator(pattern, options) {
var genericName = interpolateName(loaderContext, name, loaderOptions);
return genericName
.replace(new RegExp('[^a-zA-Z0-9\\-_\u00A0-\uFFFF]', 'g'), '-')
- .replace(/^([^a-zA-Z_])/, '_$1');
+ .replace(/^((-?[0-9])|--)/, "_$1");
};
}; | Prefix hashes with underscores based on CSS spec
To match with <URL> | css-modules_generic-names | train | js |
d47c0ae4228a59fcf731f626d650bb55c4e34609 | diff --git a/src/attributes.js b/src/attributes.js
index <HASH>..<HASH> 100644
--- a/src/attributes.js
+++ b/src/attributes.js
@@ -153,15 +153,15 @@ jQuery.fn.extend({
},
val: function( value ) {
- var hooks, val,
+ var hooks, ret,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
- if ( hooks && "get" in hooks && (val = hooks.get( elem )) !== undefined ) {
- return val;
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem )) !== undefined ) {
+ return ret;
}
return (elem.value || "").replace(rreturn, "");
@@ -173,15 +173,16 @@ jQuery.fn.extend({
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
- var self = jQuery(this);
+ var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
- val = value;
if ( isFunction ) {
val = value.call( this, i, self.val() );
+ } else {
+ val = value;
}
// Treat null/undefined as ""; convert numbers to string | Performance testing: localize val to each block and only set val to value when not a function | jquery_jquery | train | js |
6f6d65e29ab443056000c332d2cd4b01bfb73231 | diff --git a/__pkginfo__.py b/__pkginfo__.py
index <HASH>..<HASH> 100644
--- a/__pkginfo__.py
+++ b/__pkginfo__.py
@@ -23,10 +23,10 @@ numversion = (1, 2, 1)
version = '.'.join([str(num) for num in numversion])
if sys.version_info < (2, 6):
- install_requires = ['logilab-common >= 0.53.0', 'astroid >= 1.2',
+ install_requires = ['logilab-common >= 0.53.0', 'astroid >= 1.1',
'StringFormat']
else:
- install_requires = ['logilab-common >= 0.53.0', 'astroid >= 1.2']
+ install_requires = ['logilab-common >= 0.53.0', 'astroid >= 1.1']
license = 'GPL'
description = "python code static checker" | go back to dependency on astroid <I> since it breaks tox tests, even when configured to grab astroid from hg :( | PyCQA_pylint | train | py |
f087c68e01c7aed492457beeb2bb40ca30d2c1fa | diff --git a/lib/frameit/editor.rb b/lib/frameit/editor.rb
index <HASH>..<HASH> 100644
--- a/lib/frameit/editor.rb
+++ b/lib/frameit/editor.rb
@@ -20,7 +20,7 @@ module Frameit
def run(path, color = Color::BLACK)
@color = color
- Dir["#{path}/**/*.png"].each do |screenshot|
+ Dir.glob("#{path}/**/*.{png,PNG}").each do |screenshot|
next if screenshot.include?"_framed.png"
begin
template_path = get_template(screenshot)
@@ -38,7 +38,7 @@ module Frameit
c.geometry offset_information[:offset]
end
- output_path = screenshot.gsub('.png', '_framed.png')
+ output_path = screenshot.gsub('.png', '_framed.png').gsub('.PNG', '_framed.png')
result.write output_path
Helper.log.info "Successfully framed screenshot at path '#{output_path}'".green
end | Added support for PNG files (upper case) | fastlane_fastlane | train | rb |
1f7724a1ab5a883f6dbe55e8c82abb7b0acffa0d | diff --git a/lib/audited/auditor.rb b/lib/audited/auditor.rb
index <HASH>..<HASH> 100644
--- a/lib/audited/auditor.rb
+++ b/lib/audited/auditor.rb
@@ -43,7 +43,7 @@ module Audited
class_attribute :audit_associated_with, instance_writer: false
if options[:only]
- except = column_names - options[:only].flatten.map(&:to_s)
+ except = column_names - Array(options[:only]).flatten.map(&:to_s)
else
except = default_ignored_attributes + Audited.ignored_attributes
except |= Array(options[:except]).collect(&:to_s) if options[:except] | Fix bug when only: is a single field. | collectiveidea_audited | train | rb |
8ff0ca106207458ce462f796ab05b1d370cfde27 | diff --git a/tofu/version.py b/tofu/version.py
index <HASH>..<HASH> 100644
--- a/tofu/version.py
+++ b/tofu/version.py
@@ -1,2 +1,2 @@
# Do not edit, pipeline versioning governed by git tags!
-__version__ = '1.4.3b4-44-g38061c12'
\ No newline at end of file
+__version__ = '1.4.3b4-44-g38061c12' | Added new line at end of file | ToFuProject_tofu | train | py |
518fab9bf8bbfd2e3f21471feb69b9c17791a934 | diff --git a/drip/models.py b/drip/models.py
index <HASH>..<HASH> 100644
--- a/drip/models.py
+++ b/drip/models.py
@@ -1,9 +1,14 @@
from datetime import datetime, timedelta
from django.db import models
-from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
+try:
+ from django.contrib.auth import get_user_model
+ User = get_user_model()
+except ImportError:
+ from django.contrib.auth.models import User
+
# just using this to parse, but totally insane package naming...
# https://bitbucket.org/schinckel/django-timedelta-field/
import timedelta as djangotimedelta
@@ -53,7 +58,7 @@ class SentDrip(models.Model):
date = models.DateTimeField(auto_now_add=True)
drip = models.ForeignKey('drip.Drip', related_name='sent_drips')
- user = models.ForeignKey('auth.User', related_name='sent_drips')
+ user = models.ForeignKey(User, related_name='sent_drips')
subject = models.TextField()
body = models.TextField() | support for django <I>'s custom user model | zapier_django-drip | train | py |
e86b995a1f628cb4192fdd6c5f34bf98057b33c9 | diff --git a/src/scripts/directives/fa-input.js b/src/scripts/directives/fa-input.js
index <HASH>..<HASH> 100644
--- a/src/scripts/directives/fa-input.js
+++ b/src/scripts/directives/fa-input.js
@@ -37,7 +37,7 @@
*
**/
angular.module('famous.angular')
-.config(function ($provide) {
+.config(['$provide', function ($provide) {
$provide.decorator('ngClickDirective', function ($delegate, $famousDecorator, $parse, $rootElement, $famous, $timeout) {
var directive = $delegate[0];
@@ -270,7 +270,7 @@ angular.module('famous.angular')
return $delegate;
});
});
-});
+}]);
/**
* @ngdoc directive | =BG= minor: explicit directive name for minifcation
one more yet! | Famous_famous-angular | train | js |
4fde82994326ebce1a328b4f188d2a8a3cfce72e | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -98,7 +98,7 @@ var latencyReport = function() {
max: latencyData.max,
avg: latencyData.total / latencyData.count,
};
- exports.emit('eventloop', { time: Date.now(), latency: latency });
+ module.exports.emit('eventloop', { time: Date.now(), latency: latency });
latencyData.count = 0;
latencyData.min = 1 * 60 * 1000;
latencyData.max = 0;
@@ -124,7 +124,7 @@ if (global.Appmetrics) {
global.Appmetrics.VERSION +
'.\n'
);
- module.exports = global.Appmetrics;
+ exports = module.exports = global.Appmetrics;
} else {
global.Appmetrics = module.exports;
module.exports.VERSION = VERSION; | Make use of module.exports/exports consistent (#<I>) | RuntimeTools_appmetrics | train | js |
28e81db545e0dfbac31091034d101ab3a2a29557 | diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -371,6 +371,7 @@ gulp.task('bundle-framework', function bundleBoot() {
.external('reducer-register')
.external('redux-thunk')
.external('redux')
+ .external('silverstripe-backend')
.external('silverstripe-component')
.external('bootstrap-collapse')
.bundle() | Require silverstripe-backend to avoid double include | silverstripe_silverstripe-framework | train | js |
742ac63eea6b9b80d558d52d9e2ce0367d84819b | diff --git a/lib/bmc-daemon-lib/conf.rb b/lib/bmc-daemon-lib/conf.rb
index <HASH>..<HASH> 100644
--- a/lib/bmc-daemon-lib/conf.rb
+++ b/lib/bmc-daemon-lib/conf.rb
@@ -85,7 +85,7 @@ module BmcDaemonLib
Encoding.default_external = "utf-8"
# Try to access any key to force parsing of the files
- self[:dummy]
+ self[:test35547647654856865436346453754746588586799078079876543245678654324567865432]
rescue Psych::SyntaxError => e
fail ConfigParseError, e.message | conf: avoid key collision in prepare method | bmedici_bmc-daemon-lib | train | rb |
b1a9c663e2e7fc66c5d74d9b41d89bd4e526b782 | diff --git a/src/main/java/water/TypeMap.java b/src/main/java/water/TypeMap.java
index <HASH>..<HASH> 100644
--- a/src/main/java/water/TypeMap.java
+++ b/src/main/java/water/TypeMap.java
@@ -133,7 +133,9 @@ public class TypeMap {
Freezable f = GOLD[id];
if( f == null ) {
try { GOLD[id] = f = (Freezable) Class.forName(CLAZZES[id]).newInstance(); }
- catch( Exception e ) { throw Log.errRTExcept(e); }
+ catch( Exception e ) {
+ throw Log.errRTExcept(e);
+ }
}
return f.newInstance();
} | Rearrange code to make it possible to set a breakpoint on the exception. | h2oai_h2o-2 | train | java |
98881874987c28adc65df7c1c89b6e8be6cc6245 | diff --git a/src/lewis/adapters/stream.py b/src/lewis/adapters/stream.py
index <HASH>..<HASH> 100644
--- a/src/lewis/adapters/stream.py
+++ b/src/lewis/adapters/stream.py
@@ -675,6 +675,8 @@ class StreamInterface(InterfaceBase):
in_terminator = '\r'
out_terminator = '\r'
+ readtimeout = 100
+
commands = None
def __init__(self): | ReadTimeout attribute, analogous but opposite direction of ReadTimeout in protocol files | DMSC-Instrument-Data_lewis | train | py |
bfa9a4375b4f883238a355f74bd9bc2411a3dab0 | diff --git a/less.js b/less.js
index <HASH>..<HASH> 100644
--- a/less.js
+++ b/less.js
@@ -9,7 +9,10 @@ var options = loader.lessOptions || {};
// default optimization value.
options.optimization |= lessEngine.optimization;
-lessEngine.options.async = true;
+if(lessEngine.options) {
+ lessEngine.options.async = true;
+}
+
exports.translate = function(load) {
var address = load.address.replace(/^file\:/,""); | Make sure lessEngine.options exist
Only exists in the browser, it seems. | stealjs_steal-less | train | js |
43bc2602069168a3906d22d244d163f385a8cb9a | diff --git a/specs/spec-reporter.spec.php b/specs/spec-reporter.spec.php
index <HASH>..<HASH> 100644
--- a/specs/spec-reporter.spec.php
+++ b/specs/spec-reporter.spec.php
@@ -8,11 +8,10 @@ use Symfony\Component\Console\Output\BufferedOutput;
describe('SpecReporter', function() {
beforeEach(function() {
- $config = new Configuration();
-
+ $this->configuration = new Configuration();
$this->output = new BufferedOutput();
$this->emitter = new EventEmitter();
- $this->reporter = new SpecReporter($config, $this->output, $this->emitter);
+ $this->reporter = new SpecReporter($this->configuration, $this->output, $this->emitter);
});
context('when test.failed is emitted', function() {
@@ -33,4 +32,14 @@ describe('SpecReporter', function() {
});
});
+ describe('->color()', function() {
+ context('when colors are disabled', function() {
+ it('should return plain text', function() {
+ $this->configuration->disableColors();
+ $text = $this->reporter->color('color', 'hello world');
+ assert($text == "hello world", "disabled colors should contain color sequences");
+ });
+ });
+ });
+
}); | cover SpecReporter::color | peridot-php_peridot | train | php |
4766605b08d527b9b195d0d03f10de67054fd046 | diff --git a/resource/crud.go b/resource/crud.go
index <HASH>..<HASH> 100644
--- a/resource/crud.go
+++ b/resource/crud.go
@@ -58,17 +58,7 @@ func (res *Resource) saveHandler(result interface{}, context *qor.Context) error
if (context.GetDB().NewScope(result).PrimaryKeyZero() &&
res.HasPermission(roles.Create, context)) || // has create permission
res.HasPermission(roles.Update, context) { // has update permission
- results := context.GetDB().Save(result)
-
- if results.RowsAffected == 0 {
- primaryField := context.GetDB().NewScope(result).PrimaryField()
- // if primary field has value and it is not a auto increment field, then create it if nothing updated
- if _, ok := primaryField.TagSettings["AUTO_INCREMENT"]; !primaryField.IsBlank && !ok {
- return context.GetDB().Create(result).Error
- }
- }
-
- return results.Error
+ return context.GetDB().Save(result).Error
}
return roles.ErrPermissionDenied
} | Remove unnecessary create operation if failed to save | qor_qor | train | go |
17259ff8b9943fbbaf7ee3a8f312a73381d7c09e | diff --git a/source/Application/Model/PaymentList.php b/source/Application/Model/PaymentList.php
index <HASH>..<HASH> 100644
--- a/source/Application/Model/PaymentList.php
+++ b/source/Application/Model/PaymentList.php
@@ -62,7 +62,6 @@ class PaymentList extends \OxidEsales\Eshop\Core\Model\ListModel
$tableViewNameGenerator = oxNew(TableViewNameGenerator::class);
$sTable = $tableViewNameGenerator->getViewName('oxpayments');
$sQ = "select {$sTable}.* from ( select distinct {$sTable}.* from {$sTable} ";
- $sQ .= "left join oxobject2group ON oxobject2group.oxobjectid = {$sTable}.oxid ";
$sQ .= "inner join oxobject2payment ON oxobject2payment.oxobjectid = " . $oDb->quote($sShipSetId) . " and oxobject2payment.oxpaymentid = {$sTable}.oxid ";
$sQ .= "where {$sTable}.oxactive='1' ";
$sQ .= " and {$sTable}.oxfromboni <= " . $oDb->quote($sBoni) . " and {$sTable}.oxfromamount <= " . $oDb->quote($dPrice) . " and {$sTable}.oxtoamount >= " . $oDb->quote($dPrice); | perf optimization payment list.
question in slack by aurimas urbonas. would it be faster with this small change without any break? | OXID-eSales_oxideshop_ce | train | php |
ed7bb56c662ea9ab9cf5d3102d1bc84c6ac32935 | diff --git a/tests/TestCase/Integration/JsonApi/SparseFieldsetsIntegrationTest.php b/tests/TestCase/Integration/JsonApi/SparseFieldsetsIntegrationTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/Integration/JsonApi/SparseFieldsetsIntegrationTest.php
+++ b/tests/TestCase/Integration/JsonApi/SparseFieldsetsIntegrationTest.php
@@ -14,13 +14,13 @@ class SparseFieldsetsIntegrationTest extends JsonApiBaseTestCase
public function viewProvider()
{
return [
- // assert "single-field" sparse for index actions
+ // assert "single-field" sparse for index actions
'single-field sparse index' => [
'/countries?fields[countries]=name',
'index-single-field-sparse.json',
],
'single-field sparse for included index data' => [
- '/countries?include=currencies&fields[currencies]=id,name',
+ '/countries?include=currency&fields[currency]=id,name',
'index-single-field-sparse-for-included-data.json',
],
'combined single-field sparse index (both primary and included data)' => [ | Small difference in url to ensure that correct association is still used | FriendsOfCake_crud-json-api | train | php |
9b10319d473f7e74875b62ff35171800ee1234c8 | diff --git a/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java b/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java
index <HASH>..<HASH> 100644
--- a/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java
+++ b/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java
@@ -123,11 +123,11 @@ public class TimerTest {
assertThat(timer.getCount()).isZero();
int dummy = 0;
-
try (Timer.Context context = timer.time()) {
+ assertThat(context).isNotNull();
dummy += 1;
}
-
+ assertThat(dummy).isEqualTo(1);
assertThat(timer.getCount())
.isEqualTo(1); | Add additional checks for the try-with-resources test for a Timer | dropwizard_metrics | train | java |
dea95bad694d30595a21f5d925720e6d8eb8c40e | diff --git a/lib/FieldType/Mapper/RelationListFormMapper.php b/lib/FieldType/Mapper/RelationListFormMapper.php
index <HASH>..<HASH> 100644
--- a/lib/FieldType/Mapper/RelationListFormMapper.php
+++ b/lib/FieldType/Mapper/RelationListFormMapper.php
@@ -48,7 +48,7 @@ class RelationListFormMapper implements FieldTypeFormMapperInterface
$contentTypeHash[$contentType->identifier] = $this->translationHelper->getTranslatedByProperty($contentType, 'names');
}
}
- sort($contentTypeHash);
+ asort($contentTypeHash);
$fieldDefinitionForm
->add('selectionDefaultLocation', 'hidden', [ | Fix EZP-<I>: "Allowed content types" selected item, from ezobjectrelationlist, changes under certain conditions | ezsystems_repository-forms | train | php |
df09b773c50ca3200503f2be25a1c5f69d0666be | diff --git a/src/connection.js b/src/connection.js
index <HASH>..<HASH> 100644
--- a/src/connection.js
+++ b/src/connection.js
@@ -149,6 +149,9 @@ Connection.prototype.send = function(message) {
if (this._options['apisecret']) {
message.apisecret = this._options['apisecret'];
}
+ if (!message['transaction']) {
+ message['transaction'] = Transaction.generateRandomId();
+ }
return this._websocketConnection.send(message);
}; | Always add transaction on connection.send if it's not present | cargomedia_janus-gateway-js | train | js |
47dc91581c9c0da0691a1861ab76b72bfd74313d | diff --git a/MEA_package/ProgramFiles/regression_tests.py b/MEA_package/ProgramFiles/regression_tests.py
index <HASH>..<HASH> 100755
--- a/MEA_package/ProgramFiles/regression_tests.py
+++ b/MEA_package/ProgramFiles/regression_tests.py
@@ -28,9 +28,6 @@ def create_options_parser():
# install it
if os.path.isfile('/usr/local/lib/libsundials_cvode.a'):
return "--sd2=/usr/local/lib/ --sd1=/usr/local/include/"
- # This is where it is stored in jenkins
- elif os.path.isfile('/usr/share/lib/libsundials_cvode.a'):
- return "--sd2=/usr/share/lib/ --sd1=/usr/local/include/"
else:
return None | removed the /usr/share sundials loc as we dont need it | theosysbio_means | train | py |
b9af9bf0185a47ed25d3b1c8de03f872cf42dfb1 | diff --git a/manticore/platforms/linux.py b/manticore/platforms/linux.py
index <HASH>..<HASH> 100644
--- a/manticore/platforms/linux.py
+++ b/manticore/platforms/linux.py
@@ -868,7 +868,7 @@ class Linux(Platform):
for mpath in env['LD_LIBRARY_PATH'].split(":"):
interpreter_path_filename = os.path.join(mpath, os.path.basename(interpreter_filename))
logger.info("looking for interpreter %s", interpreter_path_filename)
- if os.path.exists(interpreter_filename):
+ if os.path.exists(interpreter_path_filename):
interpreter = ELFFile(open(interpreter_path_filename))
break
break | Fixed variable name typo. Issue #<I>. (#<I>) | trailofbits_manticore | train | py |
bac4ccead7048486fea4c92115e6b97a9ade7eee | diff --git a/src/client/websocket/packets/WebSocketPacketManager.js b/src/client/websocket/packets/WebSocketPacketManager.js
index <HASH>..<HASH> 100644
--- a/src/client/websocket/packets/WebSocketPacketManager.js
+++ b/src/client/websocket/packets/WebSocketPacketManager.js
@@ -95,6 +95,11 @@ class WebSocketPacketManager {
this.ws.client.emit('debug', 'Heartbeat acknowledged');
}
+ if (packet.op === Constants.OPCodes.HEARTBEAT) {
+ this.client.ws.send({ op: Constants.OPCodes.HEARTBEAT_ACK });
+ this.ws.client.emit('debug', 'ACKed gateway heartbeat!');
+ }
+
if (this.ws.status === Constants.Status.RECONNECTING) {
this.ws.reconnecting = false;
this.ws.checkIfReady(); | "knock, knock. who's there. discord, lol" (#<I>) | discordjs_discord.js | train | js |
717067833c72ce49fa6b0481760b3a352471ad31 | diff --git a/src/main/java/com/microsoft/aad/adal4j/AuthenticationAuthority.java b/src/main/java/com/microsoft/aad/adal4j/AuthenticationAuthority.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/microsoft/aad/adal4j/AuthenticationAuthority.java
+++ b/src/main/java/com/microsoft/aad/adal4j/AuthenticationAuthority.java
@@ -37,7 +37,7 @@ class AuthenticationAuthority {
private final static String[] TRUSTED_HOST_LIST = { "login.windows.net",
"login.chinacloudapi.cn", "login-us.microsoftonline.com", "login.microsoftonline.de",
- "login.microsoftonline.com" };
+ "login.microsoftonline.com", "login.microsoftonline.us" };
private final static String TENANTLESS_TENANT_NAME = "common";
private final static String AUTHORIZE_ENDPOINT_TEMPLATE = "https://{host}/{tenant}/oauth2/authorize";
private final static String DISCOVERY_ENDPOINT = "common/discovery/instance"; | adding login.microsoftonline.us to Authority trusted hosts list | AzureAD_azure-activedirectory-library-for-java | train | java |
4a4de777488feb49e9da13eb26bf9f46ee2c5e3a | diff --git a/src/Watson/Sitemap/Sitemap.php b/src/Watson/Sitemap/Sitemap.php
index <HASH>..<HASH> 100644
--- a/src/Watson/Sitemap/Sitemap.php
+++ b/src/Watson/Sitemap/Sitemap.php
@@ -136,7 +136,17 @@ class Sitemap
*/
public function xml()
{
- return $this->renderSitemap()->getOriginalContent();
+ return $this->render()->getOriginalContent();
+ }
+
+ /**
+ * Get the formatted sitemap index.
+ *
+ * @return string
+ */
+ public function xmlIndex()
+ {
+ return $this->index()->getOriginalContent();
}
/** | Add method to get original content from index (#<I>) | dwightwatson_sitemap | train | php |
3a4049a9d2d384c1c4738041edc34c530f69ace9 | diff --git a/lib/faker/business.rb b/lib/faker/business.rb
index <HASH>..<HASH> 100644
--- a/lib/faker/business.rb
+++ b/lib/faker/business.rb
@@ -10,7 +10,7 @@ module Faker
end
def credit_card_expiry_date
- ::Date.today + (365 * rand(1..4))
+ ::Date.today + (365 * (rand(4) + 1))
end
def credit_card_type | fixed for compatibility with ruby <I> | stympy_faker | train | rb |
7435be55394d7b1c4cbadae8574976455eae19a9 | diff --git a/library/src/com/johnliu/swipefinish/core/SwipeFinishActivity.java b/library/src/com/johnliu/swipefinish/core/SwipeFinishActivity.java
index <HASH>..<HASH> 100644
--- a/library/src/com/johnliu/swipefinish/core/SwipeFinishActivity.java
+++ b/library/src/com/johnliu/swipefinish/core/SwipeFinishActivity.java
@@ -8,6 +8,13 @@ import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
+/**
+ * SwipeFinishActivity.
+ * <p>
+ * Base activity for swiping to finish activity.
+ *
+ * Created by John on 2014-6-19
+ */
public class SwipeFinishActivity extends FragmentActivity {
SwipeFinishLayout swipeLayout; | Add some comments for SwipeFinshActivity. | liuguangqiang_SwipeBack | train | java |
61a55720a4942efea39333994d8ad0422eae445a | diff --git a/controllers/FrontController.php b/controllers/FrontController.php
index <HASH>..<HASH> 100644
--- a/controllers/FrontController.php
+++ b/controllers/FrontController.php
@@ -221,9 +221,9 @@ class FrontController
$video = $this->download->getJSON($url, $format);
$client = new \GuzzleHttp\Client();
$stream = $client->request('GET', $video->url, array('stream'=>true));
- $response = $response->withHeader('Content-Disposition', 'inline; filename="'.$video->_filename.'"');
+ $response = $response->withHeader('Content-Disposition', 'attachment; filename="'.$video->_filename.'"');
$response = $response->withHeader('Content-Type', $stream->getHeader('Content-Type'));
- $response = $response->withHeader('Content-Length', $stream->getHeader('Content-Length'));
+ //$response = $response->withHeader('Content-Length', $stream->getHeader('Content-Length'));
if ($request->isGet()) {
$response = $response->withBody($stream->getBody());
} | Don't include Content-Length for now | Rudloff_alltube | train | php |
71d6fa1793e4c9e4a81b67c59a6bd2207337f01d | diff --git a/telegram_handler/formatters.py b/telegram_handler/formatters.py
index <HASH>..<HASH> 100644
--- a/telegram_handler/formatters.py
+++ b/telegram_handler/formatters.py
@@ -32,7 +32,7 @@ class StyledFormatter(TelegramFormatter):
def __init__(self, *args, **kwargs):
if 'escape_message' in kwargs:
- self.escape_exception = kwargs.pop('escape_message')
+ self.escape_message = kwargs.pop('escape_message')
if 'escape_exception' in kwargs:
self.escape_exception = kwargs.pop('escape_exception')
super(StyledFormatter, self).__init__(*args, **kwargs) | Setting escape_message field missed | sashgorokhov_python-telegram-handler | train | py |
94f9bec937f233b6b3177525b35022931accb5fd | diff --git a/web/concrete/core/models/file.php b/web/concrete/core/models/file.php
index <HASH>..<HASH> 100644
--- a/web/concrete/core/models/file.php
+++ b/web/concrete/core/models/file.php
@@ -443,11 +443,14 @@ class Concrete5_Model_File extends Object {
if ($fvID == null) {
$fvID = $this->fvID; // approved version
}
-
- if (is_object($this->fv)) {
- return $this->fv;
+ $fv = CacheLocal::getEntry('file_versions', $this->getFileID() . ':' . $fvID);
+ if ($fv === -1) {
+ return false;
}
-
+ if ($fv) {
+ return $fv;
+ }
+
$db = Loader::db();
$row = $db->GetRow("select * from FileVersions where fvID = ? and fID = ?", array($fvID, $this->fID));
$row['fvAuthorName'] = $db->GetOne("select uName from Users where uID = ?", array($row['fvAuthorUID']));
@@ -456,7 +459,7 @@ class Concrete5_Model_File extends Object {
$row['fslID'] = $this->fslID;
$fv->setPropertiesFromArray($row);
- $this->fv = $fv;
+ CacheLocal::set('file_versions', $this->getFileID() . ':' . $fvID, $fv);
return $fv;
} | Fix Version Display in Dashboard
Fix version display in dashboard view.
`$this->fv` was storing on file version and caching that. This caused
the same version as the first one to always be returned.
Change to `CacheLocal::set()` `CacheLocal::getEntry()`
Former-commit-id: 4fd6fa<I>b2e<I>deeb<I>ff3cbb8c<I>cbf<I>fe0f | concrete5_concrete5 | train | php |
5fe9ec692529c9d00e429a968f1624e4efda828c | diff --git a/verisure/session.py b/verisure/session.py
index <HASH>..<HASH> 100644
--- a/verisure/session.py
+++ b/verisure/session.py
@@ -91,6 +91,7 @@ class Session(object):
self._request_cookies = None
# The login with stored cookies failed, try to get a new one
+ last_exception = None
for login_url in ['https://automation01.verisure.com/auth/login',
'https://automation02.verisure.com/auth/login']:
try:
@@ -103,11 +104,13 @@ class Session(object):
pickle.dump(response.cookies, f)
self._request_cookies = {'vid': response.cookies['vid']}
self._get_installations()
+ return
except requests.exceptions.RequestException as ex:
raise LoginError(ex)
except Exception as ex:
- print(ex)
- pass
+ last_exception = ex
+
+ raise LoginError(last_exception)
def _get_installations(self):
""" Get information about installations """ | Raise on login error, after all attempts are exhausted (#<I>) | persandstrom_python-verisure | train | py |
9ab03e40859234839a6ceace4ba1230fe155efbc | diff --git a/lib/nucleon/action/node/provision.rb b/lib/nucleon/action/node/provision.rb
index <HASH>..<HASH> 100644
--- a/lib/nucleon/action/node/provision.rb
+++ b/lib/nucleon/action/node/provision.rb
@@ -69,7 +69,7 @@ class Provision < Nucleon.plugin_class(:nucleon, :cloud_action)
end
end
end
- success('complete', { :provider => node.plugin_provider, :name => node.plugin_name }) if success
+ success('complete', { :provider => node.plugin_provider, :name => node.plugin_name, :time => Time.now.to_s }) if success
myself.status = code.provision_failure unless success
end
end | Adding time output variable to the provision node action provider. | coralnexus_corl | train | rb |
c50276f1d0c2ddd6c83cbb59f36ca3d3e3de5fdb | diff --git a/lib/iso/iban.rb b/lib/iso/iban.rb
index <HASH>..<HASH> 100644
--- a/lib/iso/iban.rb
+++ b/lib/iso/iban.rb
@@ -2,6 +2,7 @@
require 'iso/iban/specification'
require 'iso/iban/version'
+require 'yaml'
module ISO | Require yaml. | apeiros_iso-iban | train | rb |
5621228c38d7bec3e7540ae6ba126f7a6f3a394d | diff --git a/django_jenkins/runner.py b/django_jenkins/runner.py
index <HASH>..<HASH> 100644
--- a/django_jenkins/runner.py
+++ b/django_jenkins/runner.py
@@ -136,10 +136,11 @@ class CITestSuiteRunner(DiscoverRunner):
"""
Continuous integration test runner
"""
- def __init__(self, output_dir, with_reports=True, **kwargs):
+ def __init__(self, output_dir, with_reports=True, debug=False, **kwargs):
super(CITestSuiteRunner, self).__init__(**kwargs)
self.with_reports = with_reports
self.output_dir = output_dir
+ self.debug = debug
def setup_test_environment(self, **kwargs):
super(CITestSuiteRunner, self).setup_test_environment()
@@ -164,7 +165,7 @@ class CITestSuiteRunner(DiscoverRunner):
def run_suite(self, suite, **kwargs):
signals.before_suite_run.send(sender=self)
- result = TextTestRunner(buffer=True,
+ result = TextTestRunner(buffer=not self.debug,
resultclass=EXMLTestResult,
verbosity=self.verbosity).run(suite)
if self.with_reports: | Allow to use pdb under jenkins Close #<I> | kmmbvnr_django-jenkins | train | py |
3bc1ae248e64c758a09a70d6d1188b7651052323 | diff --git a/great_expectations/data_context/datasource/databricks_generator.py b/great_expectations/data_context/datasource/databricks_generator.py
index <HASH>..<HASH> 100644
--- a/great_expectations/data_context/datasource/databricks_generator.py
+++ b/great_expectations/data_context/datasource/databricks_generator.py
@@ -1,4 +1,4 @@
-import datetime
+import time
import logging
from .batch_generator import BatchGenerator
@@ -38,6 +38,6 @@ class DatabricksTableGenerator(BatchGenerator):
return iter(
{
"query": query,
- "timestamp": datetime.datetime.timestamp(datetime.now())
+ "timestamp": time.time()
}
) | Update timestamp generation for databricks_generator | great-expectations_great_expectations | train | py |
6928dbfd6568a9cbea97cfa654e2d9a022ffd4d9 | diff --git a/lib/fog/ibm/models/compute/server.rb b/lib/fog/ibm/models/compute/server.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/ibm/models/compute/server.rb
+++ b/lib/fog/ibm/models/compute/server.rb
@@ -150,7 +150,7 @@ module Fog
# Expires the instance immediately
def expire!
- expire_at(Time.now)
+ expire_at(Time.now + 5)
end
def image | [ibm] Set expire a few seconds in the future since it takes a while to process | fog_fog | train | rb |
941d63e6edd792f85ee2ef2d7b2d926aceda70fb | diff --git a/ssllabs-scan.go b/ssllabs-scan.go
index <HASH>..<HASH> 100644
--- a/ssllabs-scan.go
+++ b/ssllabs-scan.go
@@ -391,19 +391,19 @@ func invokeGetRepeatedly(url string) (*http.Response, []byte, error) {
return resp, body, nil
} else {
- if err.Error() == "EOF" {
+ if strings.Contains(err.Error(), "EOF") {
// Server closed a persistent connection on us, which
// Go doesn't seem to be handling well. So we'll try one
// more time.
if retryCount > 5 {
- log.Fatalf("[ERROR] Too many HTTP requests (5) failed with EOF (ref#1)")
+ log.Fatalf("[ERROR] Too many HTTP requests (5) failed with EOF (ref#3)")
}
if logLevel >= LOG_DEBUG {
- log.Printf("[DEBUG] HTTP request failed with EOF (ref#1)")
+ log.Printf("[DEBUG] HTTP request failed with EOF (ref#3)")
}
} else {
- log.Fatalf("[ERROR] HTTP request failed: %v (ref#1)", err.Error())
+ log.Fatalf("[ERROR] HTTP request failed: %v (ref#3)", err.Error())
}
retryCount++ | Fix retry on HTTP EOF. | ssllabs_ssllabs-scan | train | go |
f2791286b5769572a7f313ec54052ad6440f6c8f | diff --git a/modeshape-jcr/src/main/java/org/modeshape/jcr/JcrSession.java b/modeshape-jcr/src/main/java/org/modeshape/jcr/JcrSession.java
index <HASH>..<HASH> 100644
--- a/modeshape-jcr/src/main/java/org/modeshape/jcr/JcrSession.java
+++ b/modeshape-jcr/src/main/java/org/modeshape/jcr/JcrSession.java
@@ -1256,14 +1256,21 @@ public class JcrSession implements org.modeshape.jcr.api.Session {
assert path == null ? true : path.isAbsolute() : "The path (if provided) must be absolute";
SecurityContext sec = context.getSecurityContext();
+ boolean hasPermission = true;
+
final String repositoryName = this.repository.repositoryName();
if (sec instanceof AuthorizationProvider) {
// Delegate to the security context ...
AuthorizationProvider authorizer = (AuthorizationProvider)sec;
- return authorizer.hasPermission(context, repositoryName, repositoryName, workspaceName, path, actions);
+ hasPermission = authorizer.hasPermission(context, repositoryName, repositoryName, workspaceName, path, actions);
+
+ if (hasPermission) {
+ hasPermission = acm.hasPermission(path, actions);
+ }
+
+ return hasPermission;
}
- boolean hasPermission = true;
if (sec instanceof AdvancedAuthorizationProvider) {
// Delegate to the security context ...
AdvancedAuthorizationProvider authorizer = (AdvancedAuthorizationProvider)sec; | MODE-<I>: Add permission checking using ACM within authorizer block | ModeShape_modeshape | train | java |
14a4303a547dc0c91db4f8427e3f14b66125d8a3 | diff --git a/src/Response/Status.php b/src/Response/Status.php
index <HASH>..<HASH> 100644
--- a/src/Response/Status.php
+++ b/src/Response/Status.php
@@ -65,11 +65,11 @@ class Status implements ResponseInterface
switch ($payload) {
case 'OK':
case 'QUEUED':
- if (!isset(self::$$payload)) {
- self::$$payload = new self($payload);
+ if (isset(self::$$payload)) {
+ return self::$$payload;
}
- return self::$$payload;
+ return self::$$payload = new self($payload);
default:
return new self($payload); | Apply easy micro-optimization. | imcj_predis | train | php |
baf4a63c33dca4cc4a836abda2826abe9a5425c3 | diff --git a/router/routes.go b/router/routes.go
index <HASH>..<HASH> 100644
--- a/router/routes.go
+++ b/router/routes.go
@@ -150,11 +150,12 @@ func (rm *RouteManager) Route(route *Route, logstream chan *Message) {
}
func (rm *RouteManager) RoutingFrom(containerID string) bool {
- routing := false
for _, router := range LogRouters.All() {
- routing = routing || router.RoutingFrom(containerID)
+ if router.RoutingFrom(containerID) {
+ return true
+ }
}
- return routing
+ return false
}
func (rm *RouteManager) Run() error { | Simplify and add early exit to RoutingFrom | gliderlabs_logspout | train | go |
7bdfe2bfe7208c81a16513642c8081917976ebcc | diff --git a/xerox/darwin.py b/xerox/darwin.py
index <HASH>..<HASH> 100644
--- a/xerox/darwin.py
+++ b/xerox/darwin.py
@@ -14,7 +14,7 @@ def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
- except Exception, why:
+ except Exception as why:
raise XcodeNotFound
return
@@ -24,6 +24,6 @@ def paste():
"""Returns system clipboard contents."""
try:
return unicode(commands.getoutput('pbpaste'))
- except Exception, why:
+ except Exception as why:
raise XcodeNotFound
diff --git a/xerox/linux.py b/xerox/linux.py
index <HASH>..<HASH> 100644
--- a/xerox/linux.py
+++ b/xerox/linux.py
@@ -13,13 +13,13 @@ def copy(string):
_cmd = ["xclip", "-selection", "clipboard"]
subprocess.Popen(_cmd, stdin=subprocess.PIPE).communicate(unicode(string))
return
- except Exception, why:
+ except Exception as why:
raise XclipNotFound
def paste():
"""Returns system clipboard contents."""
try:
return unicode(subprocess.Popen(["xclip", "-selection", "clipboard", "-o"], stdout=subprocess.PIPE).communicate()[0])
- except Exception, why:
+ except Exception as why:
raise XclipNotFound | Use `except Exception as why` syntax rather than `except Exception, why` | kennethreitz_xerox | train | py,py |
7ebd3967299606094c7cdc62a6b7c965f0b7376c | diff --git a/src/array.js b/src/array.js
index <HASH>..<HASH> 100644
--- a/src/array.js
+++ b/src/array.js
@@ -69,6 +69,9 @@ class RynoArray extends RynoObject {
// Public: Returns the current length of the array.
get length() { return this.__elements__.length; }
+ // Public: Returns the backing native array.
+ get native() { return this.__elements__; }
+
// Public: Element reference and assignment method. When given one argument, returns the item at
// the specified index. When passed, two arguments, the second argument is set as the item at the
// index indicated by the first. | Adds Array#native property. | centro_transis | train | js |
160ad19ea6bff9fa15346c04087e5b4b864b7065 | diff --git a/test/actions/pulp3/orchestration/file_delete_test.rb b/test/actions/pulp3/orchestration/file_delete_test.rb
index <HASH>..<HASH> 100644
--- a/test/actions/pulp3/orchestration/file_delete_test.rb
+++ b/test/actions/pulp3/orchestration/file_delete_test.rb
@@ -9,7 +9,7 @@ class FileDeleteTest < ActiveSupport::TestCase
@repo.root.update_attributes(:url => 'http://test/test/')
create_repo(@repo, @master)
ForemanTasks.sync_task(
- ::Actions::Katello::Repository::MetadataGenerate, repo,
+ ::Actions::Katello::Repository::MetadataGenerate, @repo,
repository_creation: true)
ForemanTasks.sync_task(
::Actions::Pulp3::Orchestration::Repository::Delete, @repo, @master) | Fixes #<I> - repairs file delete test setup | Katello_katello | train | rb |
6ac34a483604895a787106485dadcf19f84b9bdc | diff --git a/lib/ways.js b/lib/ways.js
index <HASH>..<HASH> 100644
--- a/lib/ways.js
+++ b/lib/ways.js
@@ -35,11 +35,15 @@ module.exports = function(pattern, runner, destroyer, dependency){
exports = module.exports;
+exports.init = function() {
+ dispatch(this.pathname());
+};
+
exports.mode = function (m){
routes = [];
if((mode = m) != null)
flo = flow(routes, mode);
-}
+};
exports.use = function(mid){
middleware = new mid;
@@ -70,4 +74,4 @@ exports.reset = function(){
mode = null
routes = []
middleware = null
-}
\ No newline at end of file
+};
\ No newline at end of file | adding `init` method to keep state clean | arboleya_ways | train | js |
e0bd24f8e5b91acc009c8f0f5d304efa4671ed61 | diff --git a/src/main/java/com/mebigfatguy/fbcontrib/detect/ClassEnvy.java b/src/main/java/com/mebigfatguy/fbcontrib/detect/ClassEnvy.java
index <HASH>..<HASH> 100755
--- a/src/main/java/com/mebigfatguy/fbcontrib/detect/ClassEnvy.java
+++ b/src/main/java/com/mebigfatguy/fbcontrib/detect/ClassEnvy.java
@@ -181,7 +181,7 @@ public class ClassEnvy extends BytecodeScanningDetector {
for (int i = 1; i < envies.length; i++) {
runnerUpEnvyCount += envies[i].getValue().cardinality();
}
- if (runnerUpEnvyCount >= bestEnvyCount) {
+ if ((2 * runnerUpEnvyCount) > bestEnvyCount) {
return;
}
} | make an envy class have to dominate other enviors | mebigfatguy_fb-contrib | train | java |
45bf925ef04b97bfc7bdf7b39f1f5f481a261ec8 | diff --git a/release/golden_notebook_tests/workloads/torch_tune_serve_test.py b/release/golden_notebook_tests/workloads/torch_tune_serve_test.py
index <HASH>..<HASH> 100644
--- a/release/golden_notebook_tests/workloads/torch_tune_serve_test.py
+++ b/release/golden_notebook_tests/workloads/torch_tune_serve_test.py
@@ -126,9 +126,7 @@ def get_remote_model(remote_model_checkpoint_path):
def get_model(model_checkpoint_path):
- checkpoint_dict = Trainer.load_checkpoint_from_path(
- model_checkpoint_path + "/checkpoint"
- )
+ checkpoint_dict = Trainer.load_checkpoint_from_path(model_checkpoint_path)
model_state = checkpoint_dict["model_state_dict"]
model = ResNet18(None) | [train/serve] Fix torch tune serve test (#<I>)
#<I> broke the smoke test as it was not run on CI - this PR hotfixes this | ray-project_ray | train | py |
bcf61f1e98b3433ff683f862bb3706d02c153300 | diff --git a/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTTranslatedCSNodeV1Wrapper.java b/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTTranslatedCSNodeV1Wrapper.java
index <HASH>..<HASH> 100644
--- a/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTTranslatedCSNodeV1Wrapper.java
+++ b/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTTranslatedCSNodeV1Wrapper.java
@@ -53,7 +53,7 @@ public class RESTTranslatedCSNodeV1Wrapper extends RESTBaseWrapper<TranslatedCSN
@Override
public void setNodeRevision(Integer revision) {
- getEntity().setNodeRevision(revision);
+ getEntity().explicitSetNodeRevision(revision);
}
@Override | Fixed a bug where the Translated CSNode Revision attribute wasn't being set to be saved. | pressgang-ccms_PressGangCCMSDatasourceProviders | train | java |
54c7ae9d1f6c0cdc318d80d284d8c654435d7d51 | diff --git a/web/opensubmit/admin/submission.py b/web/opensubmit/admin/submission.py
index <HASH>..<HASH> 100644
--- a/web/opensubmit/admin/submission.py
+++ b/web/opensubmit/admin/submission.py
@@ -233,11 +233,8 @@ class SubmissionAdmin(ModelAdmin):
'''
if db_field.name == "grading":
submurl = kwargs['request'].path
- try:
- submid = int(submurl.split('/')[-2])
- kwargs["queryset"] = Submission.objects.get(pk=submid).assignment.gradingScheme.gradings
- except:
- pass
+ submid = [int(s) for s in submurl.split('/') if s.isdigit()][0] # Will break with two numbers in the relative URL. This is ok.
+ kwargs["queryset"] = Submission.objects.get(pk=submid).assignment.gradingScheme.gradings
return super(SubmissionAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def save_model(self, request, obj, form, change): | Show only assignment grading options, fixes regression of #<I> | troeger_opensubmit | train | py |
06988f6e0638e088137fe2b55368bdfe41f97184 | diff --git a/emit/router.py b/emit/router.py
index <HASH>..<HASH> 100644
--- a/emit/router.py
+++ b/emit/router.py
@@ -278,9 +278,12 @@ class Router(object):
pass
for origin in resolved:
- self.routes.setdefault(origin, set())
- self.routes[origin].add(destination)
- self.logger.info('added route "%s" -> "%s"', origin, destination)
+ destinations = self.routes.setdefault(origin, set())
+
+ if destination not in destinations:
+ self.logger.info('added route "%s" -> "%s"', origin, destination)
+
+ destinations.add(destination)
def route(self, origin, message):
'''\ | fix too much logging in regenerate_routes | BrianHicks_emit | train | py |
Subsets and Splits