commit
stringlengths 40
40
| old_file
stringlengths 6
152
| new_file
stringlengths 6
152
| old_contents
stringlengths 1.5k
3.26k
| new_contents
stringlengths 22
2.94k
| subject
stringlengths 18
317
| message
stringlengths 20
1.49k
| lang
stringclasses 10
values | license
stringclasses 13
values | repos
stringlengths 7
33.9k
| config
stringclasses 10
values | content
stringlengths 1.79k
5.86k
|
---|---|---|---|---|---|---|---|---|---|---|---|
a67ccbd9031dde4168428521b1cdaa752300739a | app/models/EloquentBuilder.php | app/models/EloquentBuilder.php | <?php
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
/**
* Eager load pivot relations.
*
* @param array $models
* @return void
*/
protected function loadPivotRelations($models)
{
$query = head($models)->pivot->newQuery()->with('unit');
$pivots = array_pluck($models, 'pivot');
$pivots = head($pivots)->newCollection($pivots);
$pivots->load($this->getPivotRelations());
}
/**
* Get the pivot relations to be eager loaded.
*
* @return array
*/
protected function getPivotRelations()
{
$relations = array_filter(array_keys($this->eagerLoad), function ($relation) {
return $relation != 'pivot';
});
return array_map(function ($relation) {
return substr($relation, strlen('pivot.'));
}, $relations);
}
/**
* Override. Eager load relations of pivot models.
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function loadRelation(array $models, $name, Closure $constraints)
{
// In this part, if the relation name is 'pivot',
// therefore there are relations in a pivot to be eager loaded.
if ($name === 'pivot') {
$this->loadPivotRelations($models);
return $models;
}
return parent::loadRelation($models, $name, $constraints);
}
}
| <?php
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
/**
* Eager load pivot relations.
*
* @param array $models
* @return void
*/
protected function loadPivotRelations($models)
{
$query = head($models)->pivot->newQuery()->with('unit');
$pivots = array_pluck($models, 'pivot');
$pivots = head($pivots)->newCollection($pivots);
$pivots->load($this->getPivotRelations());
}
/**
* Get the pivot relations to be eager loaded.
*
* @return array
*/
protected function getPivotRelations()
{
$relations = array_filter(array_keys($this->eagerLoad), function ($relation) {
return $relation != 'pivot' && str_contains($relation, 'pivot');
});
return array_map(function ($relation) {
return substr($relation, strlen('pivot.'));
}, $relations);
}
/**
* Override. Eager load relations of pivot models.
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function loadRelation(array $models, $name, Closure $constraints)
{
// In this part, if the relation name is 'pivot',
// therefore there are relations in a pivot to be eager loaded.
if ($name === 'pivot') {
$this->loadPivotRelations($models);
return $models;
}
return parent::loadRelation($models, $name, $constraints);
}
}
| Fix condition, make sure not to include non-pivot relations | Fix condition, make sure not to include non-pivot relations
| PHP | mit | ajcastro/iprocure,ajcastro/iprocure | php | ## Code Before:
<?php
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
/**
* Eager load pivot relations.
*
* @param array $models
* @return void
*/
protected function loadPivotRelations($models)
{
$query = head($models)->pivot->newQuery()->with('unit');
$pivots = array_pluck($models, 'pivot');
$pivots = head($pivots)->newCollection($pivots);
$pivots->load($this->getPivotRelations());
}
/**
* Get the pivot relations to be eager loaded.
*
* @return array
*/
protected function getPivotRelations()
{
$relations = array_filter(array_keys($this->eagerLoad), function ($relation) {
return $relation != 'pivot';
});
return array_map(function ($relation) {
return substr($relation, strlen('pivot.'));
}, $relations);
}
/**
* Override. Eager load relations of pivot models.
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function loadRelation(array $models, $name, Closure $constraints)
{
// In this part, if the relation name is 'pivot',
// therefore there are relations in a pivot to be eager loaded.
if ($name === 'pivot') {
$this->loadPivotRelations($models);
return $models;
}
return parent::loadRelation($models, $name, $constraints);
}
}
## Instruction:
Fix condition, make sure not to include non-pivot relations
## Code After:
<?php
class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder
{
/**
* Eager load pivot relations.
*
* @param array $models
* @return void
*/
protected function loadPivotRelations($models)
{
$query = head($models)->pivot->newQuery()->with('unit');
$pivots = array_pluck($models, 'pivot');
$pivots = head($pivots)->newCollection($pivots);
$pivots->load($this->getPivotRelations());
}
/**
* Get the pivot relations to be eager loaded.
*
* @return array
*/
protected function getPivotRelations()
{
$relations = array_filter(array_keys($this->eagerLoad), function ($relation) {
return $relation != 'pivot' && str_contains($relation, 'pivot');
});
return array_map(function ($relation) {
return substr($relation, strlen('pivot.'));
}, $relations);
}
/**
* Override. Eager load relations of pivot models.
* Eagerly load the relationship on a set of models.
*
* @param array $models
* @param string $name
* @param \Closure $constraints
* @return array
*/
protected function loadRelation(array $models, $name, Closure $constraints)
{
// In this part, if the relation name is 'pivot',
// therefore there are relations in a pivot to be eager loaded.
if ($name === 'pivot') {
$this->loadPivotRelations($models);
return $models;
}
return parent::loadRelation($models, $name, $constraints);
}
}
|
2f42b4af34396bef942330a0ca7545e1c30627c1 | src/Repositories/RepositoryFactory.php | src/Repositories/RepositoryFactory.php | <?php
namespace GearHub\LaravelEnhancementSuite\Repositories;
use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract;
class RepositoryFactory implements RepositoryFactoryContract
{
/**
* Mapping keys to repositories. Takes precidence over the dynamic resolution.
*
* @var array
*/
protected $overrides = [];
/**
* Create new instance of RepositoryFactory.
*
* @param array $overrides
*
* @return void
*/
public function __construct(array $overrides = [])
{
$this->overrides = $overrides;
}
/**
* Get repository for the corresponding model.
* If $key is null return instance of the factory.
*
* @param string|null $key
*
* @return mixed
*/
public function get($key = null)
{
if (!empty($key)) {
$class = null;
if (array_has($this->overrides, $key)) {
$class = array_get($this->overrides, $key);
} else {
$class = $this->build($key);
}
return resolve($class);
}
return $this;
}
/**
* Build the path of the Repository class.
*
* @param string $key
*
* @return string
*/
protected function build($key)
{
return app()->getNamespace() . $this->laravel['config']['les.repository_namespace'] . '\\' . studly_case(str_singular($key)) . 'Repository';
}
}
| <?php
namespace GearHub\LaravelEnhancementSuite\Repositories;
use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract;
class RepositoryFactory implements RepositoryFactoryContract
{
/**
* Mapping keys to repositories. Takes precidence over the dynamic resolution.
*
* @var array
*/
protected $overrides = [];
/**
* Create new instance of RepositoryFactory.
*
* @param array $overrides
*
* @return void
*/
public function __construct(array $overrides = [])
{
$this->overrides = $overrides;
}
/**
* Get repository for the corresponding model.
* If $key is null return instance of the factory.
*
* @param string|null $key
*
* @return mixed
*/
public function get($key = null)
{
if (!empty($key)) {
$class = null;
if (array_has($this->overrides, $key)) {
$class = array_get($this->overrides, $key);
} else {
$class = $this->build($key);
}
return resolve($class);
}
return $this;
}
/**
* Build the path of the Repository class.
*
* @param string $key
*
* @return string
*/
protected function build($key)
{
return app()->getNamespace() . config('les.repository_namespace') . '\\' . studly_case(str_singular($key)) . 'Repository';
}
}
| Call to config helper function instead of an instance of the container | Call to config helper function instead of an instance of the container
| PHP | mit | gearhub/laravel-enhancement-suite | php | ## Code Before:
<?php
namespace GearHub\LaravelEnhancementSuite\Repositories;
use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract;
class RepositoryFactory implements RepositoryFactoryContract
{
/**
* Mapping keys to repositories. Takes precidence over the dynamic resolution.
*
* @var array
*/
protected $overrides = [];
/**
* Create new instance of RepositoryFactory.
*
* @param array $overrides
*
* @return void
*/
public function __construct(array $overrides = [])
{
$this->overrides = $overrides;
}
/**
* Get repository for the corresponding model.
* If $key is null return instance of the factory.
*
* @param string|null $key
*
* @return mixed
*/
public function get($key = null)
{
if (!empty($key)) {
$class = null;
if (array_has($this->overrides, $key)) {
$class = array_get($this->overrides, $key);
} else {
$class = $this->build($key);
}
return resolve($class);
}
return $this;
}
/**
* Build the path of the Repository class.
*
* @param string $key
*
* @return string
*/
protected function build($key)
{
return app()->getNamespace() . $this->laravel['config']['les.repository_namespace'] . '\\' . studly_case(str_singular($key)) . 'Repository';
}
}
## Instruction:
Call to config helper function instead of an instance of the container
## Code After:
<?php
namespace GearHub\LaravelEnhancementSuite\Repositories;
use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract;
class RepositoryFactory implements RepositoryFactoryContract
{
/**
* Mapping keys to repositories. Takes precidence over the dynamic resolution.
*
* @var array
*/
protected $overrides = [];
/**
* Create new instance of RepositoryFactory.
*
* @param array $overrides
*
* @return void
*/
public function __construct(array $overrides = [])
{
$this->overrides = $overrides;
}
/**
* Get repository for the corresponding model.
* If $key is null return instance of the factory.
*
* @param string|null $key
*
* @return mixed
*/
public function get($key = null)
{
if (!empty($key)) {
$class = null;
if (array_has($this->overrides, $key)) {
$class = array_get($this->overrides, $key);
} else {
$class = $this->build($key);
}
return resolve($class);
}
return $this;
}
/**
* Build the path of the Repository class.
*
* @param string $key
*
* @return string
*/
protected function build($key)
{
return app()->getNamespace() . config('les.repository_namespace') . '\\' . studly_case(str_singular($key)) . 'Repository';
}
}
|
3bfcd86532a3c068e804e3f569de38f6412d8e90 | core/src/main/java/bisq/core/btc/model/InputsAndChangeOutput.java | core/src/main/java/bisq/core/btc/model/InputsAndChangeOutput.java | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.ArrayList;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final ArrayList<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
| /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.List;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final List<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
| Use List instead of ArrayList as type | Use List instead of ArrayList as type
| Java | agpl-3.0 | bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange,bitsquare/bitsquare | java | ## Code Before:
/*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.ArrayList;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final ArrayList<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
## Instruction:
Use List instead of ArrayList as type
## Code After:
/*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq 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 Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.model;
import java.util.List;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
public class InputsAndChangeOutput {
public final List<RawTransactionInput> rawTransactionInputs;
// Is set to 0L in case we don't have an output
public final long changeOutputValue;
@Nullable
public final String changeOutputAddress;
public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) {
checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()");
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;
}
}
|
f3033ed163de4fa8c56f034cae861e7f6556ac4c | lib/dry/types/enum.rb | lib/dry/types/enum.rb | require 'dry/types/decorator'
module Dry
module Types
class Enum
include Type
include Dry::Equalizer(:type, :options, :mapping)
include Decorator
# @return [Array]
attr_reader :values
# @return [Hash]
attr_reader :mapping
# @param [Type] type
# @param [Hash] options
# @option options [Array] :values
def initialize(type, options)
super
@mapping = options.fetch(:mapping).freeze
@values = @mapping.keys.freeze.each(&:freeze)
end
# @param [Object] input
# @return [Object]
def call(input = Undefined)
value =
if input.equal?(Undefined)
type.call
elsif values.include?(input)
input
elsif mapping.key?(input)
mapping[input]
elsif mapping.values.include?(input)
mapping.key(input)
else
input
end
type[value]
end
alias_method :[], :call
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
# Check whether a value is in the enum
# @param [Object] value
# @return [Boolean]
alias_method :include?, :valid?
# @api public
#
# @see Definition#to_ast
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta),
mapping,
meta ? self.meta : EMPTY_HASH]]
end
end
end
end
| require 'dry/types/decorator'
module Dry
module Types
class Enum
include Type
include Dry::Equalizer(:type, :options, :mapping)
include Decorator
# @return [Array]
attr_reader :values
# @return [Hash]
attr_reader :mapping
# @return [Hash]
attr_reader :inverted_mapping
# @param [Type] type
# @param [Hash] options
# @option options [Array] :values
def initialize(type, options)
super
@mapping = options.fetch(:mapping).freeze
@values = @mapping.keys.freeze
@inverted_mapping = @mapping.invert.freeze
freeze
end
# @param [Object] input
# @return [Object]
def call(input = Undefined)
value =
if input.equal?(Undefined)
type.call
elsif mapping.key?(input)
input
else
inverted_mapping.fetch(input, input)
end
type[value]
end
alias_method :[], :call
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
# Check whether a value is in the enum
# @param [Object] value
# @return [Boolean]
alias_method :include?, :valid?
# @api public
#
# @see Definition#to_ast
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta),
mapping,
meta ? self.meta : EMPTY_HASH]]
end
end
end
end
| Replace array search with hash lookup | Replace array search with hash lookup
| Ruby | mit | dryrb/dry-data,dryrb/dry-types,dryrb/dry-data,dryrb/dry-types | ruby | ## Code Before:
require 'dry/types/decorator'
module Dry
module Types
class Enum
include Type
include Dry::Equalizer(:type, :options, :mapping)
include Decorator
# @return [Array]
attr_reader :values
# @return [Hash]
attr_reader :mapping
# @param [Type] type
# @param [Hash] options
# @option options [Array] :values
def initialize(type, options)
super
@mapping = options.fetch(:mapping).freeze
@values = @mapping.keys.freeze.each(&:freeze)
end
# @param [Object] input
# @return [Object]
def call(input = Undefined)
value =
if input.equal?(Undefined)
type.call
elsif values.include?(input)
input
elsif mapping.key?(input)
mapping[input]
elsif mapping.values.include?(input)
mapping.key(input)
else
input
end
type[value]
end
alias_method :[], :call
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
# Check whether a value is in the enum
# @param [Object] value
# @return [Boolean]
alias_method :include?, :valid?
# @api public
#
# @see Definition#to_ast
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta),
mapping,
meta ? self.meta : EMPTY_HASH]]
end
end
end
end
## Instruction:
Replace array search with hash lookup
## Code After:
require 'dry/types/decorator'
module Dry
module Types
class Enum
include Type
include Dry::Equalizer(:type, :options, :mapping)
include Decorator
# @return [Array]
attr_reader :values
# @return [Hash]
attr_reader :mapping
# @return [Hash]
attr_reader :inverted_mapping
# @param [Type] type
# @param [Hash] options
# @option options [Array] :values
def initialize(type, options)
super
@mapping = options.fetch(:mapping).freeze
@values = @mapping.keys.freeze
@inverted_mapping = @mapping.invert.freeze
freeze
end
# @param [Object] input
# @return [Object]
def call(input = Undefined)
value =
if input.equal?(Undefined)
type.call
elsif mapping.key?(input)
input
else
inverted_mapping.fetch(input, input)
end
type[value]
end
alias_method :[], :call
def default(*)
raise '.enum(*values).default(value) is not supported. Call '\
'.default(value).enum(*values) instead'
end
# Check whether a value is in the enum
# @param [Object] value
# @return [Boolean]
alias_method :include?, :valid?
# @api public
#
# @see Definition#to_ast
def to_ast(meta: true)
[:enum, [type.to_ast(meta: meta),
mapping,
meta ? self.meta : EMPTY_HASH]]
end
end
end
end
|
1979204ddddcb1b0d07f649ebc6614a4ec0d5fe4 | lib/carto/db/migration_helper.rb | lib/carto/db/migration_helper.rb | module Carto
module Db
module MigrationHelper
LOCK_TIMEOUT_MS = 1000
MAX_RETRIES = 3
WAIT_BETWEEN_RETRIES_S = 2
def migration(up_block, down_block)
Sequel.migration do
# Forces this migration to run under a transaction (controlled by Sequel)
transaction
up do
lock_safe_migration(&up_block)
end
down do
lock_safe_migration(&down_block)
end
end
end
private
def lock_safe_migration(&block)
run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}"
# As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one
# Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html)
# to start a "sub-transaction" that we can rollback without affecting Sequel
run 'SAVEPOINT before_migration'
(1..MAX_RETRIES).each do
begin
instance_eval &block
return
rescue Sequel::DatabaseError => e
if e.message.include?('lock timeout')
# In case of timeout, we retry by reexecuting the code since the SAVEPOINT
run 'ROLLBACK TO SAVEPOINT before_migration'
sleep WAIT_BETWEEN_RETRIES_S
else
raise e
end
end
end
# Raising an exception forces Sequel to rollback the entire transaction
raise 'Retries exceeded during database migration'
ensure
run "SET lock_timeout TO DEFAULT"
end
end
end
end
| module Carto
module Db
module MigrationHelper
LOCK_TIMEOUT_MS = 1000
MAX_RETRIES = 3
WAIT_BETWEEN_RETRIES_S = 2
def migration(up_block, down_block)
Sequel.migration do
# Forces this migration to run under a transaction (controlled by Sequel)
transaction
up do
lock_safe_migration(&up_block)
end
down do
lock_safe_migration(&down_block)
end
end
end
private
def lock_safe_migration(&block)
run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}"
# As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one
# Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html)
# to start a "sub-transaction" that we can rollback without affecting Sequel
run 'SAVEPOINT before_migration'
(1..MAX_RETRIES).each do
begin
instance_eval &block
return
rescue Sequel::DatabaseError => e
if e.message.include?('lock timeout')
# In case of timeout, we retry by reexecuting the code since the SAVEPOINT
run 'ROLLBACK TO SAVEPOINT before_migration'
sleep WAIT_BETWEEN_RETRIES_S
else
puts e.message
raise e
end
end
end
# Raising an exception forces Sequel to rollback the entire transaction
raise 'Retries exceeded during database migration'
ensure
run "SET lock_timeout TO DEFAULT"
end
end
end
end
| Add extra error information to migration helper | Add extra error information to migration helper
| Ruby | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb | ruby | ## Code Before:
module Carto
module Db
module MigrationHelper
LOCK_TIMEOUT_MS = 1000
MAX_RETRIES = 3
WAIT_BETWEEN_RETRIES_S = 2
def migration(up_block, down_block)
Sequel.migration do
# Forces this migration to run under a transaction (controlled by Sequel)
transaction
up do
lock_safe_migration(&up_block)
end
down do
lock_safe_migration(&down_block)
end
end
end
private
def lock_safe_migration(&block)
run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}"
# As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one
# Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html)
# to start a "sub-transaction" that we can rollback without affecting Sequel
run 'SAVEPOINT before_migration'
(1..MAX_RETRIES).each do
begin
instance_eval &block
return
rescue Sequel::DatabaseError => e
if e.message.include?('lock timeout')
# In case of timeout, we retry by reexecuting the code since the SAVEPOINT
run 'ROLLBACK TO SAVEPOINT before_migration'
sleep WAIT_BETWEEN_RETRIES_S
else
raise e
end
end
end
# Raising an exception forces Sequel to rollback the entire transaction
raise 'Retries exceeded during database migration'
ensure
run "SET lock_timeout TO DEFAULT"
end
end
end
end
## Instruction:
Add extra error information to migration helper
## Code After:
module Carto
module Db
module MigrationHelper
LOCK_TIMEOUT_MS = 1000
MAX_RETRIES = 3
WAIT_BETWEEN_RETRIES_S = 2
def migration(up_block, down_block)
Sequel.migration do
# Forces this migration to run under a transaction (controlled by Sequel)
transaction
up do
lock_safe_migration(&up_block)
end
down do
lock_safe_migration(&down_block)
end
end
end
private
def lock_safe_migration(&block)
run "SET lock_timeout TO #{LOCK_TIMEOUT_MS}"
# As the external transaction is controlled by Sequel, we cannot ROLLBACK and BEGIN a new one
# Instead, we use SAVEPOINTs (https://www.postgresql.org/docs/current/static/sql-savepoint.html)
# to start a "sub-transaction" that we can rollback without affecting Sequel
run 'SAVEPOINT before_migration'
(1..MAX_RETRIES).each do
begin
instance_eval &block
return
rescue Sequel::DatabaseError => e
if e.message.include?('lock timeout')
# In case of timeout, we retry by reexecuting the code since the SAVEPOINT
run 'ROLLBACK TO SAVEPOINT before_migration'
sleep WAIT_BETWEEN_RETRIES_S
else
puts e.message
raise e
end
end
end
# Raising an exception forces Sequel to rollback the entire transaction
raise 'Retries exceeded during database migration'
ensure
run "SET lock_timeout TO DEFAULT"
end
end
end
end
|
72691fbefd2d04a57a66dd3b1cd88b2a1b9478d2 | src/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js | src/FOM/CoreBundle/Resources/public/js/widgets/dropdown.js | $(function() {
$('.dropdown').each(function() {
var element = $(this);
var dropdownList = element.find(".dropdownList");
if(dropdownList.children().length === 0) {
element.find("option").each(function(i, e) {
$(e).addClass("opt-" + i);
dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>'));
});
}
var select = element.find("select").val();
element.find(".dropdownValue").text(element.find('option[value="' + select + '"]').text())
}).on('click', function() {
var me = $(this);
var list = me.find(".dropdownList");
var opts = me.find(".hiddenDropdown");
if(list.css("display") == "block") {
list.hide();
} else {
$(".dropdownList").hide();
list.show();
list.find("li").one("click", function(event) {
event.stopPropagation();
list.hide().find("li").off("click");
var me2 = $(this);
var opt = me2.attr("class").replace("item", "opt");
me.find(".dropdownValue").text(me2.text());
opts.find("[selected=selected]").removeAttr("selected");
var val = opts.find("." + opt).attr("selected", "selected").val();
opts.val(val).trigger('change');
})
}
$(document).one("click", function() {
list.hide().find("li").off("mouseout").off("click");
});
return false;
})
});
| $(function() {
$('.dropdown').each(function() {
var me = $(this);
var dropdownList = me.find(".dropdownList");
if(dropdownList.children().length === 0) {
me.find("option").each(function(i, e) {
$(e).addClass("opt-" + i);
dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>'));
});
}
var select = me.find("select").val();
me.find(".dropdownValue").text(me.find('option[value="' + select + '"]').text())
});
$(document).on("click", ".dropdown", function() {
var me = $(this);
var list = me.find(".dropdownList");
var opts = me.find(".hiddenDropdown");
if(list.css("display") == "block") {
list.hide();
} else {
$(".dropdownList").hide();
list.show();
list.find("li").one("click", function(event) {
event.stopPropagation();
list.hide().find("li").off("click");
var me2 = $(this);
var opt = me2.attr("class").replace("item", "opt");
me.find(".dropdownValue").text(me2.text());
opts.find("[selected=selected]").removeAttr("selected");
var val = opts.find("." + opt).attr("selected", "selected").val();
opts.val(val).trigger('change');
})
}
$(document).one("click", function() {
list.hide().find("li").off("mouseout").off("click");
});
return false;
});
});
| Fix select element global listener | Fix select element global listener
| JavaScript | mit | mapbender/fom,mapbender/fom,mapbender/fom | javascript | ## Code Before:
$(function() {
$('.dropdown').each(function() {
var element = $(this);
var dropdownList = element.find(".dropdownList");
if(dropdownList.children().length === 0) {
element.find("option").each(function(i, e) {
$(e).addClass("opt-" + i);
dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>'));
});
}
var select = element.find("select").val();
element.find(".dropdownValue").text(element.find('option[value="' + select + '"]').text())
}).on('click', function() {
var me = $(this);
var list = me.find(".dropdownList");
var opts = me.find(".hiddenDropdown");
if(list.css("display") == "block") {
list.hide();
} else {
$(".dropdownList").hide();
list.show();
list.find("li").one("click", function(event) {
event.stopPropagation();
list.hide().find("li").off("click");
var me2 = $(this);
var opt = me2.attr("class").replace("item", "opt");
me.find(".dropdownValue").text(me2.text());
opts.find("[selected=selected]").removeAttr("selected");
var val = opts.find("." + opt).attr("selected", "selected").val();
opts.val(val).trigger('change');
})
}
$(document).one("click", function() {
list.hide().find("li").off("mouseout").off("click");
});
return false;
})
});
## Instruction:
Fix select element global listener
## Code After:
$(function() {
$('.dropdown').each(function() {
var me = $(this);
var dropdownList = me.find(".dropdownList");
if(dropdownList.children().length === 0) {
me.find("option").each(function(i, e) {
$(e).addClass("opt-" + i);
dropdownList.append($('<li class="item-' + i + '">' + $(e).text() + '</li>'));
});
}
var select = me.find("select").val();
me.find(".dropdownValue").text(me.find('option[value="' + select + '"]').text())
});
$(document).on("click", ".dropdown", function() {
var me = $(this);
var list = me.find(".dropdownList");
var opts = me.find(".hiddenDropdown");
if(list.css("display") == "block") {
list.hide();
} else {
$(".dropdownList").hide();
list.show();
list.find("li").one("click", function(event) {
event.stopPropagation();
list.hide().find("li").off("click");
var me2 = $(this);
var opt = me2.attr("class").replace("item", "opt");
me.find(".dropdownValue").text(me2.text());
opts.find("[selected=selected]").removeAttr("selected");
var val = opts.find("." + opt).attr("selected", "selected").val();
opts.val(val).trigger('change');
})
}
$(document).one("click", function() {
list.hide().find("li").off("mouseout").off("click");
});
return false;
});
});
|
0c35ee2a8a71bf776001ebebc186b236ab34e7d3 | library/src/main/java/com/novoda/downloadmanager/NotificationDispatcher.java | library/src/main/java/com/novoda/downloadmanager/NotificationDispatcher.java | package com.novoda.downloadmanager;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED;
class NotificationDispatcher {
private final Object waitForDownloadService;
private final NotificationCreator<DownloadBatchStatus> notificationCreator;
private DownloadService downloadService;
NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) {
this.waitForDownloadService = waitForDownloadService;
this.notificationCreator = notificationCreator;
}
void updateNotification(DownloadBatchStatus downloadBatchStatus) {
WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService)
.thenPerform(executeUpdateNotification(downloadBatchStatus));
}
private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
return () -> {
NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);
if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
downloadService.stackNotification(notificationInformation);
} else {
downloadService.updateNotification(notificationInformation);
}
return null;
};
}
void setDownloadService(DownloadService downloadService) {
this.downloadService = downloadService;
}
}
| package com.novoda.downloadmanager;
import android.support.annotation.WorkerThread;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED;
class NotificationDispatcher {
private final Object waitForDownloadService;
private final NotificationCreator<DownloadBatchStatus> notificationCreator;
private DownloadService downloadService;
NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) {
this.waitForDownloadService = waitForDownloadService;
this.notificationCreator = notificationCreator;
}
@WorkerThread
void updateNotification(DownloadBatchStatus downloadBatchStatus) {
WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService)
.thenPerform(executeUpdateNotification(downloadBatchStatus));
}
private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
return () -> {
NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);
if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
downloadService.stackNotification(notificationInformation);
} else {
downloadService.updateNotification(notificationInformation);
}
return null;
};
}
void setDownloadService(DownloadService downloadService) {
this.downloadService = downloadService;
}
}
| Add worker thread annotation to update notification. | Add worker thread annotation to update notification.
| Java | apache-2.0 | novoda/download-manager | java | ## Code Before:
package com.novoda.downloadmanager;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED;
class NotificationDispatcher {
private final Object waitForDownloadService;
private final NotificationCreator<DownloadBatchStatus> notificationCreator;
private DownloadService downloadService;
NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) {
this.waitForDownloadService = waitForDownloadService;
this.notificationCreator = notificationCreator;
}
void updateNotification(DownloadBatchStatus downloadBatchStatus) {
WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService)
.thenPerform(executeUpdateNotification(downloadBatchStatus));
}
private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
return () -> {
NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);
if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
downloadService.stackNotification(notificationInformation);
} else {
downloadService.updateNotification(notificationInformation);
}
return null;
};
}
void setDownloadService(DownloadService downloadService) {
this.downloadService = downloadService;
}
}
## Instruction:
Add worker thread annotation to update notification.
## Code After:
package com.novoda.downloadmanager;
import android.support.annotation.WorkerThread;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED;
class NotificationDispatcher {
private final Object waitForDownloadService;
private final NotificationCreator<DownloadBatchStatus> notificationCreator;
private DownloadService downloadService;
NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) {
this.waitForDownloadService = waitForDownloadService;
this.notificationCreator = notificationCreator;
}
@WorkerThread
void updateNotification(DownloadBatchStatus downloadBatchStatus) {
WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService)
.thenPerform(executeUpdateNotification(downloadBatchStatus));
}
private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
return () -> {
NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);
if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
downloadService.stackNotification(notificationInformation);
} else {
downloadService.updateNotification(notificationInformation);
}
return null;
};
}
void setDownloadService(DownloadService downloadService) {
this.downloadService = downloadService;
}
}
|
d691798551ae3e894d683c5ea142ac1f6b64393b | lib/query_string_search/comparator.rb | lib/query_string_search/comparator.rb | module QueryStringSearch
module Comparator
def self.using(operator)
create_comparison
comparison.operator = operator
self
end
def self.does(subject)
create_comparison
comparison.subject = subject
self
end
def self.equal?(other)
comparison.operator = "="
compare_with?(other)
end
def self.contain?(other)
comparison.operator = "∈"
compare_with?(other)
end
def self.compare_with?(other)
comparison.other = other
resolve
end
private
def self.create_comparison
@comparison ||= Comparison.new
end
def self.comparison
@comparison
end
def self.resolve
ret = @comparison.compare
@comparison = nil
ret
end
end
end
module QueryStringSearch
module Comparator
class Comparison
attr_accessor :subject, :operator, :other
def compare
if operator == "="
equal?
elsif operator == "∈"
contain?
elsif ["<",">","<=",">="]
inequal?
end
end
def inequal?
eval("#{other} #{operator} #{subject}")
end
def equal?
normalize(subject) == normalize(other)
end
def contain?
normalize(subject).include?(normalize(other))
end
def normalize(unnormalized)
if unnormalized.respond_to?(:each)
unnormalized.map(&:to_s).map(&:upcase)
else
unnormalized.to_s.upcase
end
end
end
end
end
| module QueryStringSearch
module Comparator
def self.using(operator)
create_comparison
comparison.operator = operator
self
end
def self.does(subject)
create_comparison
comparison.subject = subject
self
end
def self.equal?(other)
comparison.operator = "="
compare_with?(other)
end
def self.contain?(other)
comparison.operator = "∈"
compare_with?(other)
end
def self.compare_with?(other)
comparison.other = other
resolve
end
private
def self.create_comparison
@comparison ||= Comparison.new
end
def self.comparison
@comparison
end
def self.resolve
ret = @comparison.compare
@comparison = nil
ret
end
end
end
module QueryStringSearch
module Comparator
class Comparison
attr_accessor :subject, :operator, :other
def compare
if ["=".to_sym].include?(operator)
equal?
elsif [:∈].include?(operator)
contain?
elsif [:<, :>, :<=, :>=].include?(operator)
inequal?
else
false
end
end
def operator=(x)
@operator = x.to_sym
end
def inequal?
other.to_i.public_send(operator, subject.to_i)
end
def equal?
normalize(other).public_send(:==, normalize(subject))
end
def contain?
normalize(subject).public_send(:&, [normalize(other)]).any?
end
def normalize(unnormalized)
if unnormalized.respond_to?(:each)
unnormalized.map(&:to_s).map(&:upcase)
else
unnormalized.to_s.upcase
end
end
end
end
end
| Move from strings & eval to symbols and public_send | Move from strings & eval to symbols and public_send
Seems like an obvious change. This works, but it's obviously not in a
final state yet.
| Ruby | mit | umn-asr/query_string_search | ruby | ## Code Before:
module QueryStringSearch
module Comparator
def self.using(operator)
create_comparison
comparison.operator = operator
self
end
def self.does(subject)
create_comparison
comparison.subject = subject
self
end
def self.equal?(other)
comparison.operator = "="
compare_with?(other)
end
def self.contain?(other)
comparison.operator = "∈"
compare_with?(other)
end
def self.compare_with?(other)
comparison.other = other
resolve
end
private
def self.create_comparison
@comparison ||= Comparison.new
end
def self.comparison
@comparison
end
def self.resolve
ret = @comparison.compare
@comparison = nil
ret
end
end
end
module QueryStringSearch
module Comparator
class Comparison
attr_accessor :subject, :operator, :other
def compare
if operator == "="
equal?
elsif operator == "∈"
contain?
elsif ["<",">","<=",">="]
inequal?
end
end
def inequal?
eval("#{other} #{operator} #{subject}")
end
def equal?
normalize(subject) == normalize(other)
end
def contain?
normalize(subject).include?(normalize(other))
end
def normalize(unnormalized)
if unnormalized.respond_to?(:each)
unnormalized.map(&:to_s).map(&:upcase)
else
unnormalized.to_s.upcase
end
end
end
end
end
## Instruction:
Move from strings & eval to symbols and public_send
Seems like an obvious change. This works, but it's obviously not in a
final state yet.
## Code After:
module QueryStringSearch
module Comparator
def self.using(operator)
create_comparison
comparison.operator = operator
self
end
def self.does(subject)
create_comparison
comparison.subject = subject
self
end
def self.equal?(other)
comparison.operator = "="
compare_with?(other)
end
def self.contain?(other)
comparison.operator = "∈"
compare_with?(other)
end
def self.compare_with?(other)
comparison.other = other
resolve
end
private
def self.create_comparison
@comparison ||= Comparison.new
end
def self.comparison
@comparison
end
def self.resolve
ret = @comparison.compare
@comparison = nil
ret
end
end
end
module QueryStringSearch
module Comparator
class Comparison
attr_accessor :subject, :operator, :other
def compare
if ["=".to_sym].include?(operator)
equal?
elsif [:∈].include?(operator)
contain?
elsif [:<, :>, :<=, :>=].include?(operator)
inequal?
else
false
end
end
def operator=(x)
@operator = x.to_sym
end
def inequal?
other.to_i.public_send(operator, subject.to_i)
end
def equal?
normalize(other).public_send(:==, normalize(subject))
end
def contain?
normalize(subject).public_send(:&, [normalize(other)]).any?
end
def normalize(unnormalized)
if unnormalized.respond_to?(:each)
unnormalized.map(&:to_s).map(&:upcase)
else
unnormalized.to_s.upcase
end
end
end
end
end
|
b00876c7c5563839179364762053dfff7f74c124 | test/Permissions/Editor/Create/NotAvailable/FieldEditPermissionTest.php | test/Permissions/Editor/Create/NotAvailable/FieldEditPermissionTest.php | <?php namespace ProcessWire\GraphQL\Test\Permissions;
use ProcessWire\GraphQL\Test\GraphqlTestCase;
use ProcessWire\GraphQL\Utils;
use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists;
class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase {
/**
* + For editor.
* + The template is legal.
* + The configured parent template is legal.
* + All required fields are legal.
* + Editor has all required permissions for templates.
* - Editor does not have edit permission on required field. (title)
*/
public static function getSettings()
{
$editorRole = Utils::roles()->get("editor");
return [
'login' => 'editor',
'legalTemplates' => ['skyscraper', 'city'],
'legalFields' => ['title', 'images'],
'access' => [
'templates' => [
[
'name' => 'skyscraper',
'roles' => [$editorRole->id],
'editRoles' => [$editorRole->id],
'createRoles' => [$editorRole->id],
],
[
'name' => 'city',
'roles' => [$editorRole->id],
'addRoles' => [$editorRole->id],
]
],
'fields' => [
[
'name' => 'images',
'editRoles' => [$editorRole->id],
]
]
]
];
}
public function testPermission() {
assertTypePathNotExists(
['Mutation', 'createSkyscraper'],
'createSkyscraper mutation field should not be available if one of the required fields is not legal.'
);
}
} | <?php namespace ProcessWire\GraphQL\Test\Permissions;
use ProcessWire\GraphQL\Test\GraphqlTestCase;
use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists;
class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase {
/**
* + For editor.
* + The template is legal.
* + The configured parent template is legal.
* + All required fields are legal.
* + Editor has all required permissions for templates.
* - Editor does not have edit permission on required field. (title)
*/
public static function getSettings()
{
return [
'login' => 'editor',
'legalTemplates' => ['skyscraper', 'city'],
'legalFields' => ['title', 'images'],
'access' => [
'templates' => [
[
'name' => 'skyscraper',
'roles' => ['editor'],
'editRoles' => ['editor'],
'createRoles' => ['editor'],
],
[
'name' => 'city',
'roles' => ['editor'],
'addRoles' => ['editor'],
]
],
'fields' => [
[
'name' => 'images',
'editRoles' => ['editor'],
],
[
'name' => 'title',
// 'editRoles' => ['editor'], // <-- has no edit permission to the required "title" field.
],
]
]
];
}
public function testPermission() {
assertTypePathNotExists(
['Mutation', 'createSkyscraper'],
'createSkyscraper mutation field should not be available if user has no edit permission on the required field.'
);
}
} | Update test case create is not available because of field edit permission. | Update test case create is not available because of field edit permission.
| PHP | mit | dadish/ProcessGraphQL,dadish/ProcessGraphQL | php | ## Code Before:
<?php namespace ProcessWire\GraphQL\Test\Permissions;
use ProcessWire\GraphQL\Test\GraphqlTestCase;
use ProcessWire\GraphQL\Utils;
use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists;
class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase {
/**
* + For editor.
* + The template is legal.
* + The configured parent template is legal.
* + All required fields are legal.
* + Editor has all required permissions for templates.
* - Editor does not have edit permission on required field. (title)
*/
public static function getSettings()
{
$editorRole = Utils::roles()->get("editor");
return [
'login' => 'editor',
'legalTemplates' => ['skyscraper', 'city'],
'legalFields' => ['title', 'images'],
'access' => [
'templates' => [
[
'name' => 'skyscraper',
'roles' => [$editorRole->id],
'editRoles' => [$editorRole->id],
'createRoles' => [$editorRole->id],
],
[
'name' => 'city',
'roles' => [$editorRole->id],
'addRoles' => [$editorRole->id],
]
],
'fields' => [
[
'name' => 'images',
'editRoles' => [$editorRole->id],
]
]
]
];
}
public function testPermission() {
assertTypePathNotExists(
['Mutation', 'createSkyscraper'],
'createSkyscraper mutation field should not be available if one of the required fields is not legal.'
);
}
}
## Instruction:
Update test case create is not available because of field edit permission.
## Code After:
<?php namespace ProcessWire\GraphQL\Test\Permissions;
use ProcessWire\GraphQL\Test\GraphqlTestCase;
use function ProcessWire\GraphQL\Test\Assert\assertTypePathNotExists;
class EditorCreateNotAvailableFieldEditPermissionTest extends GraphqlTestCase {
/**
* + For editor.
* + The template is legal.
* + The configured parent template is legal.
* + All required fields are legal.
* + Editor has all required permissions for templates.
* - Editor does not have edit permission on required field. (title)
*/
public static function getSettings()
{
return [
'login' => 'editor',
'legalTemplates' => ['skyscraper', 'city'],
'legalFields' => ['title', 'images'],
'access' => [
'templates' => [
[
'name' => 'skyscraper',
'roles' => ['editor'],
'editRoles' => ['editor'],
'createRoles' => ['editor'],
],
[
'name' => 'city',
'roles' => ['editor'],
'addRoles' => ['editor'],
]
],
'fields' => [
[
'name' => 'images',
'editRoles' => ['editor'],
],
[
'name' => 'title',
// 'editRoles' => ['editor'], // <-- has no edit permission to the required "title" field.
],
]
]
];
}
public function testPermission() {
assertTypePathNotExists(
['Mutation', 'createSkyscraper'],
'createSkyscraper mutation field should not be available if user has no edit permission on the required field.'
);
}
} |
d5d303b3bad1c3451457acf6dc98d673f2e98f2f | java/example/default/index.html | java/example/default/index.html | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Hello MapReduce</title>
</head>
<body>
<h1>Hello MapReduce!</h1>
<table>
<tr>
<td>This is an example Map Reduce that demos parallel computation. <br />
For the purposes of illustration this MapReduce looks for collisions in
Java's Random number generator. (There are not any.) <br /> Here a
collision is defined as multiple seed values that when next is called
produce the same output value. <br /> The input source is a range of
numbers to test, and any collisions are logged and written out to a file
in Google Cloud Storage. (Which in this case will be empty.) <br />
<a href="/randomcollisions">Random collisions example.</a>
</td>
</tr>
<tr>
<td>There is also a second more complex example that chains three
MapReduces together:<br /> The first MapReduce creates some datastore
entities <br /> The second MapReduce does some analysis on them <br />
and the third MapReduce deletes them. <br /> On the whole it does not
do anything useful, but it shows how to chain mapreduce jobs together,
and how to interact with the datastore from mapreduce jobs. <br />
It also gives an example of validating a request using a token. <br />
<a href="/entitycount">Entity counting example.</a>
</td>
</tr>
</table>
</body>
</html>
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Hello MapReduce</title>
</head>
<body>
<h1>MapReduce Sample Programs</h1>
<table>
<tr>
<td><Big>Random collisions example</Big><br />
This example demonstrates parallel computation. It looks for collisions
in Java's random number generator, <br />
where a collision is defined as multiple seed values
that produce the same output value when <code>next()</code> is called. <br />
The input source is a range of numbers to test. Collisions are logged and
written out to a file in Google Cloud Storage. <br />
(No collisions occur so the file will be empty.) <br />
<a href="/randomcollisions">Run the example.</a> <br /></td>
</tr>
<tr>
<td><br /><Big>Entity counting example</Big><br />
The example shows how to “chain" MapReduce jobs together,
running them sequentially, one after the other. <br />
It runs three MapReduce jobs: <br />
The first job creates some datastore entities,
the second job analyzes them, and the third job deletes them. <br />
The example also shows how to access the datastore from a
MapReduce job, and how to validate a request using a token. <br />
<a href="/entitycount">Run the example.</a>
</td>
</tr>
</table>
</body>
</html>
| Add some formatting to landing page. | Java: Add some formatting to landing page.
Revision created by MOE tool push_codebase.
MOE_MIGRATION=6869
| HTML | apache-2.0 | soundofjw/appengine-mapreduce,vendasta/appengine-mapreduce,lordzuko/appengine-mapreduce,vendasta/appengine-mapreduce,rbruyere/appengine-mapreduce,VirusTotal/appengine-mapreduce,soundofjw/appengine-mapreduce,VirusTotal/appengine-mapreduce,lordzuko/appengine-mapreduce,Candreas/mapreduce,ankit318/appengine-mapreduce,rbruyere/appengine-mapreduce,ankit318/appengine-mapreduce,mikelambert/appengine-mapreduce,Candreas/mapreduce,Candreas/mapreduce,talele08/appengine-mapreduce,aozarov/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,mikelambert/appengine-mapreduce,bmenasha/appengine-mapreduce,aozarov/appengine-mapreduce,chargrizzle/appengine-mapreduce,VirusTotal/appengine-mapreduce,westerhofffl/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,chargrizzle/appengine-mapreduce,ankit318/appengine-mapreduce,bmenasha/appengine-mapreduce,potatolondon/potato-mapreduce,soundofjw/appengine-mapreduce,rbruyere/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,bmenasha/appengine-mapreduce,aozarov/appengine-mapreduce,ankit318/appengine-mapreduce,westerhofffl/appengine-mapreduce,soundofjw/appengine-mapreduce,westerhofffl/appengine-mapreduce,aozarov/appengine-mapreduce,talele08/appengine-mapreduce,VirusTotal/appengine-mapreduce,talele08/appengine-mapreduce,vendasta/appengine-mapreduce,vendasta/appengine-mapreduce,aozarov/appengine-mapreduce,mikelambert/appengine-mapreduce,talele08/appengine-mapreduce,Candreas/mapreduce,GoogleCloudPlatform/appengine-mapreduce,bmenasha/appengine-mapreduce,westerhofffl/appengine-mapreduce,rbruyere/appengine-mapreduce,bmenasha/appengine-mapreduce,Candreas/mapreduce,chargrizzle/appengine-mapreduce,ankit318/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,talele08/appengine-mapreduce,mikelambert/appengine-mapreduce,VirusTotal/appengine-mapreduce,lordzuko/appengine-mapreduce,mikelambert/appengine-mapreduce,potatolondon/potato-mapreduce,westerhofffl/appengine-mapreduce,chargrizzle/appengine-mapreduce,soundofjw/appengine-mapreduce,lordzuko/appengine-mapreduce,potatolondon/potato-mapreduce,vendasta/appengine-mapreduce,chargrizzle/appengine-mapreduce,rbruyere/appengine-mapreduce,lordzuko/appengine-mapreduce | html | ## Code Before:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Hello MapReduce</title>
</head>
<body>
<h1>Hello MapReduce!</h1>
<table>
<tr>
<td>This is an example Map Reduce that demos parallel computation. <br />
For the purposes of illustration this MapReduce looks for collisions in
Java's Random number generator. (There are not any.) <br /> Here a
collision is defined as multiple seed values that when next is called
produce the same output value. <br /> The input source is a range of
numbers to test, and any collisions are logged and written out to a file
in Google Cloud Storage. (Which in this case will be empty.) <br />
<a href="/randomcollisions">Random collisions example.</a>
</td>
</tr>
<tr>
<td>There is also a second more complex example that chains three
MapReduces together:<br /> The first MapReduce creates some datastore
entities <br /> The second MapReduce does some analysis on them <br />
and the third MapReduce deletes them. <br /> On the whole it does not
do anything useful, but it shows how to chain mapreduce jobs together,
and how to interact with the datastore from mapreduce jobs. <br />
It also gives an example of validating a request using a token. <br />
<a href="/entitycount">Entity counting example.</a>
</td>
</tr>
</table>
</body>
</html>
## Instruction:
Java: Add some formatting to landing page.
Revision created by MOE tool push_codebase.
MOE_MIGRATION=6869
## Code After:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Hello MapReduce</title>
</head>
<body>
<h1>MapReduce Sample Programs</h1>
<table>
<tr>
<td><Big>Random collisions example</Big><br />
This example demonstrates parallel computation. It looks for collisions
in Java's random number generator, <br />
where a collision is defined as multiple seed values
that produce the same output value when <code>next()</code> is called. <br />
The input source is a range of numbers to test. Collisions are logged and
written out to a file in Google Cloud Storage. <br />
(No collisions occur so the file will be empty.) <br />
<a href="/randomcollisions">Run the example.</a> <br /></td>
</tr>
<tr>
<td><br /><Big>Entity counting example</Big><br />
The example shows how to “chain" MapReduce jobs together,
running them sequentially, one after the other. <br />
It runs three MapReduce jobs: <br />
The first job creates some datastore entities,
the second job analyzes them, and the third job deletes them. <br />
The example also shows how to access the datastore from a
MapReduce job, and how to validate a request using a token. <br />
<a href="/entitycount">Run the example.</a>
</td>
</tr>
</table>
</body>
</html>
|
734903c777fb237509c21a988f79318ec14e997d | st2api/st2api/controllers/sensors.py | st2api/st2api/controllers/sensors.py | import six
from pecan import abort
from pecan.rest import RestController
from mongoengine import ValidationError
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.base import jsexpose
from st2common.models.api.reactor import SensorTypeAPI
http_client = six.moves.http_client
LOG = logging.getLogger(__name__)
class SensorTypeController(RestController):
@jsexpose(str)
def get_one(self, id):
"""
Get sensortype by id.
Handle:
GET /sensortype/1
"""
LOG.info('GET /sensortype/ with id=%s', id)
try:
sensor_type_db = SensorType.get_by_id(id)
except (ValueError, ValidationError):
LOG.exception('Database lookup for id="%s" resulted in exception.', id)
abort(http_client.NOT_FOUND)
return
sensor_type_api = SensorTypeAPI.from_model(sensor_type_db)
LOG.debug('GET /sensortype/ with id=%s, client_result=%s', id, sensor_type_api)
return sensor_type_api
@jsexpose(str)
def get_all(self, **kw):
"""
List all sensor types.
Handles requests:
GET /sensortypes/
"""
LOG.info('GET all /sensortypes/ with filters=%s', kw)
sensor_type_dbs = SensorType.get_all(**kw)
sensor_type_apis = [SensorTypeAPI.from_model(sensor_type_db) for sensor_type_db
in sensor_type_dbs]
return sensor_type_apis
| import six
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.api.reactor import SensorTypeAPI
from st2api.controllers.resource import ResourceController
http_client = six.moves.http_client
LOG = logging.getLogger(__name__)
class SensorTypeController(ResourceController):
model = SensorTypeAPI
access = SensorType
supported_filters = {
'name': 'name',
'pack': 'content_pack'
}
options = {
'sort': ['content_pack', 'name']
}
| Use ResourceController instead of duplicating logic. | Use ResourceController instead of duplicating logic.
| Python | apache-2.0 | pinterb/st2,armab/st2,peak6/st2,pixelrebel/st2,Plexxi/st2,armab/st2,Plexxi/st2,punalpatel/st2,grengojbo/st2,jtopjian/st2,jtopjian/st2,StackStorm/st2,alfasin/st2,dennybaa/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,pinterb/st2,grengojbo/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,pixelrebel/st2,alfasin/st2,emedvedev/st2,pixelrebel/st2,Itxaka/st2,Itxaka/st2,jtopjian/st2,nzlosh/st2,tonybaloney/st2,emedvedev/st2,punalpatel/st2,peak6/st2,tonybaloney/st2,tonybaloney/st2,Plexxi/st2,dennybaa/st2,emedvedev/st2,peak6/st2,StackStorm/st2,nzlosh/st2,pinterb/st2,armab/st2,nzlosh/st2,Itxaka/st2,grengojbo/st2,punalpatel/st2,Plexxi/st2,dennybaa/st2,lakshmi-kannan/st2,alfasin/st2 | python | ## Code Before:
import six
from pecan import abort
from pecan.rest import RestController
from mongoengine import ValidationError
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.base import jsexpose
from st2common.models.api.reactor import SensorTypeAPI
http_client = six.moves.http_client
LOG = logging.getLogger(__name__)
class SensorTypeController(RestController):
@jsexpose(str)
def get_one(self, id):
"""
Get sensortype by id.
Handle:
GET /sensortype/1
"""
LOG.info('GET /sensortype/ with id=%s', id)
try:
sensor_type_db = SensorType.get_by_id(id)
except (ValueError, ValidationError):
LOG.exception('Database lookup for id="%s" resulted in exception.', id)
abort(http_client.NOT_FOUND)
return
sensor_type_api = SensorTypeAPI.from_model(sensor_type_db)
LOG.debug('GET /sensortype/ with id=%s, client_result=%s', id, sensor_type_api)
return sensor_type_api
@jsexpose(str)
def get_all(self, **kw):
"""
List all sensor types.
Handles requests:
GET /sensortypes/
"""
LOG.info('GET all /sensortypes/ with filters=%s', kw)
sensor_type_dbs = SensorType.get_all(**kw)
sensor_type_apis = [SensorTypeAPI.from_model(sensor_type_db) for sensor_type_db
in sensor_type_dbs]
return sensor_type_apis
## Instruction:
Use ResourceController instead of duplicating logic.
## Code After:
import six
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.api.reactor import SensorTypeAPI
from st2api.controllers.resource import ResourceController
http_client = six.moves.http_client
LOG = logging.getLogger(__name__)
class SensorTypeController(ResourceController):
model = SensorTypeAPI
access = SensorType
supported_filters = {
'name': 'name',
'pack': 'content_pack'
}
options = {
'sort': ['content_pack', 'name']
}
|
d7025f92a240284d130ce455b6975ede42d0228e | chalice/cli/filewatch/eventbased.py | chalice/cli/filewatch/eventbased.py | import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileSystemEvent # noqa
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class WatchdogWorkerProcess(WorkerProcess):
"""Worker that runs the chalice dev server."""
def _start_file_watcher(self, project_dir):
# type: (str) -> None
restart_callback = WatchdogRestarter(self._restart_event)
watcher = WatchdogFileWatcher()
watcher.watch_for_file_changes(
project_dir, restart_callback)
class WatchdogFileWatcher(FileWatcher):
def watch_for_file_changes(self, root_dir, callback):
# type: (str, Callable[[], None]) -> None
observer = watchdog.observers.Observer()
observer.schedule(callback, root_dir, recursive=True)
observer.start()
class WatchdogRestarter(FileSystemEventHandler):
def __init__(self, restart_event):
# type: (threading.Event) -> None
# The reason we're using threading
self.restart_event = restart_event
def on_any_event(self, event):
# type: (FileSystemEvent) -> None
# If we modify a file we'll get a FileModifiedEvent
# as well as a DirectoryModifiedEvent.
# We only care about reloading is a file is modified.
if event.is_directory:
return
self()
def __call__(self):
# type: () -> None
self.restart_event.set()
| import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers # pylint: disable=import-error
from watchdog import events # pylint: disable=import-error
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class WatchdogWorkerProcess(WorkerProcess):
"""Worker that runs the chalice dev server."""
def _start_file_watcher(self, project_dir):
# type: (str) -> None
restart_callback = WatchdogRestarter(self._restart_event)
watcher = WatchdogFileWatcher()
watcher.watch_for_file_changes(
project_dir, restart_callback)
class WatchdogFileWatcher(FileWatcher):
def watch_for_file_changes(self, root_dir, callback):
# type: (str, Callable[[], None]) -> None
observer = watchdog.observers.Observer()
observer.schedule(callback, root_dir, recursive=True)
observer.start()
class WatchdogRestarter(events.FileSystemEventHandler):
def __init__(self, restart_event):
# type: (threading.Event) -> None
# The reason we're using threading
self.restart_event = restart_event
def on_any_event(self, event):
# type: (events.FileSystemEvent) -> None
# If we modify a file we'll get a FileModifiedEvent
# as well as a DirectoryModifiedEvent.
# We only care about reloading is a file is modified.
if event.is_directory:
return
self()
def __call__(self):
# type: () -> None
self.restart_event.set()
| Make prcheck pass without needing cond deps | Make prcheck pass without needing cond deps
| Python | apache-2.0 | awslabs/chalice | python | ## Code Before:
import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileSystemEvent # noqa
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class WatchdogWorkerProcess(WorkerProcess):
"""Worker that runs the chalice dev server."""
def _start_file_watcher(self, project_dir):
# type: (str) -> None
restart_callback = WatchdogRestarter(self._restart_event)
watcher = WatchdogFileWatcher()
watcher.watch_for_file_changes(
project_dir, restart_callback)
class WatchdogFileWatcher(FileWatcher):
def watch_for_file_changes(self, root_dir, callback):
# type: (str, Callable[[], None]) -> None
observer = watchdog.observers.Observer()
observer.schedule(callback, root_dir, recursive=True)
observer.start()
class WatchdogRestarter(FileSystemEventHandler):
def __init__(self, restart_event):
# type: (threading.Event) -> None
# The reason we're using threading
self.restart_event = restart_event
def on_any_event(self, event):
# type: (FileSystemEvent) -> None
# If we modify a file we'll get a FileModifiedEvent
# as well as a DirectoryModifiedEvent.
# We only care about reloading is a file is modified.
if event.is_directory:
return
self()
def __call__(self):
# type: () -> None
self.restart_event.set()
## Instruction:
Make prcheck pass without needing cond deps
## Code After:
import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers # pylint: disable=import-error
from watchdog import events # pylint: disable=import-error
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class WatchdogWorkerProcess(WorkerProcess):
"""Worker that runs the chalice dev server."""
def _start_file_watcher(self, project_dir):
# type: (str) -> None
restart_callback = WatchdogRestarter(self._restart_event)
watcher = WatchdogFileWatcher()
watcher.watch_for_file_changes(
project_dir, restart_callback)
class WatchdogFileWatcher(FileWatcher):
def watch_for_file_changes(self, root_dir, callback):
# type: (str, Callable[[], None]) -> None
observer = watchdog.observers.Observer()
observer.schedule(callback, root_dir, recursive=True)
observer.start()
class WatchdogRestarter(events.FileSystemEventHandler):
def __init__(self, restart_event):
# type: (threading.Event) -> None
# The reason we're using threading
self.restart_event = restart_event
def on_any_event(self, event):
# type: (events.FileSystemEvent) -> None
# If we modify a file we'll get a FileModifiedEvent
# as well as a DirectoryModifiedEvent.
# We only care about reloading is a file is modified.
if event.is_directory:
return
self()
def __call__(self):
# type: () -> None
self.restart_event.set()
|
5a92b2d340c78f0a58f059543b38efc8cb0e84f6 | PocketForecast/AppDelegate.swift | PocketForecast/AppDelegate.swift | ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cityDao: CityDao?
var rootViewController: RootViewController?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
ICLoader.setImageName("cloud_icon.png")
ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont.applicationFontOfSize(size: 20),
NSForegroundColorAttributeName : UIColor.white
]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.rootViewController
self.window?.makeKeyAndVisible()
let selectedCity : String! = cityDao!.loadSelectedCity()
if (selectedCity == nil) {
rootViewController?.showCitiesListController()
}
return true
}
}
| ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cityDao: CityDao?
var rootViewController: RootViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
ICLoader.setImageName("cloud_icon.png")
ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont.applicationFontOfSize(size: 20),
NSForegroundColorAttributeName : UIColor.white
]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.rootViewController
self.window?.makeKeyAndVisible()
let selectedCity : String! = cityDao!.loadSelectedCity()
if (selectedCity == nil) {
rootViewController?.showCitiesListController()
}
return true
}
}
| Update application didiFinishLaunching method with Swift 3 syntax | Update application didiFinishLaunching method with Swift 3 syntax
| Swift | apache-2.0 | appsquickly/Typhoon-Swift-Example,appsquickly/Typhoon-Swift-Example | swift | ## Code Before:
////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cityDao: CityDao?
var rootViewController: RootViewController?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
ICLoader.setImageName("cloud_icon.png")
ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont.applicationFontOfSize(size: 20),
NSForegroundColorAttributeName : UIColor.white
]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.rootViewController
self.window?.makeKeyAndVisible()
let selectedCity : String! = cityDao!.loadSelectedCity()
if (selectedCity == nil) {
rootViewController?.showCitiesListController()
}
return true
}
}
## Instruction:
Update application didiFinishLaunching method with Swift 3 syntax
## Code After:
////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Jasper Blues & Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var cityDao: CityDao?
var rootViewController: RootViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
ICLoader.setImageName("cloud_icon.png")
ICLoader.setLabelFontName(UIFont.applicationFontOfSize(size: 10).fontName)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UINavigationBar.appearance().titleTextAttributes = [
NSFontAttributeName : UIFont.applicationFontOfSize(size: 20),
NSForegroundColorAttributeName : UIColor.white
]
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.rootViewController
self.window?.makeKeyAndVisible()
let selectedCity : String! = cityDao!.loadSelectedCity()
if (selectedCity == nil) {
rootViewController?.showCitiesListController()
}
return true
}
}
|
8e275a22aa419297eee0acc5ef65fc0cce4aa3cb | clients/web/test/spec/swaggerSpec.js | clients/web/test/spec/swaggerSpec.js | function jasmineTests() {
var jasmineEnv = jasmine.getEnv();
var consoleReporter = new jasmine.ConsoleReporter();
window.jasmine_phantom_reporter = consoleReporter;
jasmineEnv.addReporter(consoleReporter);
function waitAndExecute() {
if (!jasmineEnv.currentRunner().suites_.length) {
window.setTimeout(waitAndExecute, 10);
return;
}
jasmineEnv.execute();
}
waitAndExecute();
describe('Test the swagger pages', function () {
it('Test swagger', function () {
waitsFor(function () {
return $('li#resource_system.resource').length > 0;
}, 'swagger docs to appear');
runs(function () {
$('li#resource_system.resource .heading h2 a').click();
});
waitsFor(function () {
return $('#system_getVersion:visible').length > 0;
}, 'end points to be visible');
runs(function () {
$('#system_getVersion h3 a').click();
});
waitsFor(function () {
return $('#system_getVersion .sandbox_header input.submit[name="commit"]:visible').length > 0;
}, 'version try out button to be visible');
runs(function () {
$('#system_getVersion .sandbox_header input.submit[name="commit"]').click();
});
waitsFor(function () {
return $('#system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0;
}, 'version information was returned');
});
});
}
$(function () {
$.getScript('/static/built/testing-no-cover.min.js', jasmineTests);
});
| function jasmineTests() {
var jasmineEnv = jasmine.getEnv();
var consoleReporter = new jasmine.ConsoleReporter();
window.jasmine_phantom_reporter = consoleReporter;
jasmineEnv.addReporter(consoleReporter);
function waitAndExecute() {
if (!jasmineEnv.currentRunner().suites_.length) {
window.setTimeout(waitAndExecute, 10);
return;
}
jasmineEnv.execute();
}
waitAndExecute();
describe('Test the swagger pages', function () {
it('Test swagger', function () {
waitsFor(function () {
return $('li#resource_system.resource').length > 0;
}, 'swagger docs to appear');
runs(function () {
$('li#resource_system.resource .heading h2 a').click();
});
waitsFor(function () {
return $('#system_system_getVersion:visible').length > 0;
}, 'end points to be visible');
runs(function () {
$('#system_system_getVersion h3 a').click();
});
waitsFor(function () {
return $('#system_system_getVersion .sandbox_header input.submit:visible').length > 0;
}, 'version try out button to be visible');
runs(function () {
$('#system_system_getVersion .sandbox_header input.submit').click();
});
waitsFor(function () {
return $('#system_system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0;
}, 'version information was returned');
});
});
}
$(function () {
$.getScript('/static/built/testing-no-cover.min.js', jasmineTests);
});
| Update web client swagger test for swagger-ui 2.1.4 | Update web client swagger test for swagger-ui 2.1.4
| JavaScript | apache-2.0 | adsorensen/girder,kotfic/girder,data-exp-lab/girder,jbeezley/girder,Kitware/girder,jbeezley/girder,adsorensen/girder,RafaelPalomar/girder,kotfic/girder,girder/girder,sutartmelson/girder,Xarthisius/girder,sutartmelson/girder,sutartmelson/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,data-exp-lab/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/girder,Xarthisius/girder,adsorensen/girder,kotfic/girder,data-exp-lab/girder,adsorensen/girder,RafaelPalomar/girder,RafaelPalomar/girder,girder/girder,sutartmelson/girder,jbeezley/girder,adsorensen/girder,manthey/girder,Xarthisius/girder,kotfic/girder,Kitware/girder,girder/girder,Kitware/girder,Kitware/girder,sutartmelson/girder,Xarthisius/girder,girder/girder,manthey/girder,jbeezley/girder,kotfic/girder,Xarthisius/girder | javascript | ## Code Before:
function jasmineTests() {
var jasmineEnv = jasmine.getEnv();
var consoleReporter = new jasmine.ConsoleReporter();
window.jasmine_phantom_reporter = consoleReporter;
jasmineEnv.addReporter(consoleReporter);
function waitAndExecute() {
if (!jasmineEnv.currentRunner().suites_.length) {
window.setTimeout(waitAndExecute, 10);
return;
}
jasmineEnv.execute();
}
waitAndExecute();
describe('Test the swagger pages', function () {
it('Test swagger', function () {
waitsFor(function () {
return $('li#resource_system.resource').length > 0;
}, 'swagger docs to appear');
runs(function () {
$('li#resource_system.resource .heading h2 a').click();
});
waitsFor(function () {
return $('#system_getVersion:visible').length > 0;
}, 'end points to be visible');
runs(function () {
$('#system_getVersion h3 a').click();
});
waitsFor(function () {
return $('#system_getVersion .sandbox_header input.submit[name="commit"]:visible').length > 0;
}, 'version try out button to be visible');
runs(function () {
$('#system_getVersion .sandbox_header input.submit[name="commit"]').click();
});
waitsFor(function () {
return $('#system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0;
}, 'version information was returned');
});
});
}
$(function () {
$.getScript('/static/built/testing-no-cover.min.js', jasmineTests);
});
## Instruction:
Update web client swagger test for swagger-ui 2.1.4
## Code After:
function jasmineTests() {
var jasmineEnv = jasmine.getEnv();
var consoleReporter = new jasmine.ConsoleReporter();
window.jasmine_phantom_reporter = consoleReporter;
jasmineEnv.addReporter(consoleReporter);
function waitAndExecute() {
if (!jasmineEnv.currentRunner().suites_.length) {
window.setTimeout(waitAndExecute, 10);
return;
}
jasmineEnv.execute();
}
waitAndExecute();
describe('Test the swagger pages', function () {
it('Test swagger', function () {
waitsFor(function () {
return $('li#resource_system.resource').length > 0;
}, 'swagger docs to appear');
runs(function () {
$('li#resource_system.resource .heading h2 a').click();
});
waitsFor(function () {
return $('#system_system_getVersion:visible').length > 0;
}, 'end points to be visible');
runs(function () {
$('#system_system_getVersion h3 a').click();
});
waitsFor(function () {
return $('#system_system_getVersion .sandbox_header input.submit:visible').length > 0;
}, 'version try out button to be visible');
runs(function () {
$('#system_system_getVersion .sandbox_header input.submit').click();
});
waitsFor(function () {
return $('#system_system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0;
}, 'version information was returned');
});
});
}
$(function () {
$.getScript('/static/built/testing-no-cover.min.js', jasmineTests);
});
|
6bdc335ebb8ed009cbc926e681ee6be8f475f323 | reviewboard/reviews/features.py | reviewboard/reviews/features.py | """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created directly on a review request
without accompanying file attachment or diff. These can be used to raise
issues with the review request itself, such as its summary or description,
or general implementation issues.
"""
feature_id = 'reviews.general_comments'
name = _('General Comments')
level = FeatureLevel.STABLE
summary = _('Allow comments on review requests without an associated file '
'attachment or diff.')
class StatusUpdatesFeature(Feature):
"""A feature for status updates.
A status update is a way for third-party tools to provide feedback on a
review request. In the past, this was done just as a normal review. Status
updates allow those tools (via some integration like Review Bot) to mark
their state (such as pending, success, failure, or error) and then
associate that with a review.
"""
feature_id = 'reviews.status_updates'
name = _('Status Updates')
summary = _('A way for external tools to do checks on a review request '
'and report the results of those checks.')
general_comments_feature = GeneralCommentsFeature()
status_updates_feature = StatusUpdatesFeature()
| """Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created directly on a review request
without accompanying file attachment or diff. These can be used to raise
issues with the review request itself, such as its summary or description,
or general implementation issues.
"""
feature_id = 'reviews.general_comments'
name = _('General Comments')
level = FeatureLevel.STABLE
summary = _('Allow comments on review requests without an associated file '
'attachment or diff.')
class StatusUpdatesFeature(Feature):
"""A feature for status updates.
A status update is a way for third-party tools to provide feedback on a
review request. In the past, this was done just as a normal review. Status
updates allow those tools (via some integration like Review Bot) to mark
their state (such as pending, success, failure, or error) and then
associate that with a review.
"""
feature_id = 'reviews.status_updates'
name = _('Status Updates')
level = FeatureLevel.STABLE
summary = _('A way for external tools to do checks on a review request '
'and report the results of those checks.')
general_comments_feature = GeneralCommentsFeature()
status_updates_feature = StatusUpdatesFeature()
| Mark status updates as stable. | Mark status updates as stable.
This allows people to actually use the feature without turning it on in their
`settings_local.py`.
Reviewed at https://reviews.reviewboard.org/r/8569/
| Python | mit | sgallagher/reviewboard,brennie/reviewboard,chipx86/reviewboard,chipx86/reviewboard,chipx86/reviewboard,davidt/reviewboard,reviewboard/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,brennie/reviewboard,sgallagher/reviewboard,davidt/reviewboard,sgallagher/reviewboard,davidt/reviewboard,brennie/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,brennie/reviewboard,reviewboard/reviewboard | python | ## Code Before:
"""Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created directly on a review request
without accompanying file attachment or diff. These can be used to raise
issues with the review request itself, such as its summary or description,
or general implementation issues.
"""
feature_id = 'reviews.general_comments'
name = _('General Comments')
level = FeatureLevel.STABLE
summary = _('Allow comments on review requests without an associated file '
'attachment or diff.')
class StatusUpdatesFeature(Feature):
"""A feature for status updates.
A status update is a way for third-party tools to provide feedback on a
review request. In the past, this was done just as a normal review. Status
updates allow those tools (via some integration like Review Bot) to mark
their state (such as pending, success, failure, or error) and then
associate that with a review.
"""
feature_id = 'reviews.status_updates'
name = _('Status Updates')
summary = _('A way for external tools to do checks on a review request '
'and report the results of those checks.')
general_comments_feature = GeneralCommentsFeature()
status_updates_feature = StatusUpdatesFeature()
## Instruction:
Mark status updates as stable.
This allows people to actually use the feature without turning it on in their
`settings_local.py`.
Reviewed at https://reviews.reviewboard.org/r/8569/
## Code After:
"""Feature definitions for reviews."""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from djblets.features import Feature, FeatureLevel
class GeneralCommentsFeature(Feature):
"""A feature for general comments.
General comments allow comments to be created directly on a review request
without accompanying file attachment or diff. These can be used to raise
issues with the review request itself, such as its summary or description,
or general implementation issues.
"""
feature_id = 'reviews.general_comments'
name = _('General Comments')
level = FeatureLevel.STABLE
summary = _('Allow comments on review requests without an associated file '
'attachment or diff.')
class StatusUpdatesFeature(Feature):
"""A feature for status updates.
A status update is a way for third-party tools to provide feedback on a
review request. In the past, this was done just as a normal review. Status
updates allow those tools (via some integration like Review Bot) to mark
their state (such as pending, success, failure, or error) and then
associate that with a review.
"""
feature_id = 'reviews.status_updates'
name = _('Status Updates')
level = FeatureLevel.STABLE
summary = _('A way for external tools to do checks on a review request '
'and report the results of those checks.')
general_comments_feature = GeneralCommentsFeature()
status_updates_feature = StatusUpdatesFeature()
|
7da7354668187167ccc6143ee0f469158c858ed3 | lib/economic/proxies/actions/creditor_contact_proxy/find_by_name.rb | lib/economic/proxies/actions/creditor_contact_proxy/find_by_name.rb | module Economic
module Proxies
module Actions
module CreditorContactProxy
class FindByName
attr_reader :name
def initialize(caller, name)
@caller = caller
@name = name
end
def call
# Get a list of CreditorContactHandles from e-conomic
response = request('FindByName', {
'name' => name
})
# Make sure we always have an array of handles even if the result only contains one
handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?)
# Create partial CreditorContact entities
contacts = handles.collect do |handle|
creditor_contact = build
creditor_contact.partial = true
creditor_contact.persisted = true
creditor_contact.handle = handle
creditor_contact.id = handle[:id]
creditor_contact.number = handle[:number]
creditor_contact
end
if owner.is_a?(Creditor)
# Scope to the owner
contacts.select do |creditor_contact|
creditor_contact.get_data
creditor_contact.creditor.handle == owner.handle
end
else
contacts
end
end
private
def build(*options)
@caller.build(options)
end
def owner
@caller.owner
end
def request(action, data)
@caller.request(action, data)
end
end
end
end
end
end
| module Economic
module Proxies
module Actions
module CreditorContactProxy
class FindByName
attr_reader :name
def initialize(caller, name)
@caller = caller
@name = name
end
def call
# Get a list of CreditorContactHandles from e-conomic
handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?)
contacts = build_partial_contact_entities(handles)
scope_to_owner(contacts)
end
private
def build(*options)
@caller.build(options)
end
def build_partial_contact_entities(handles)
handles.collect do |handle|
creditor_contact = build
creditor_contact.partial = true
creditor_contact.persisted = true
creditor_contact.handle = handle
creditor_contact.id = handle[:id]
creditor_contact.number = handle[:number]
creditor_contact
end
end
def owner
@caller.owner
end
def request(action, data)
@caller.request(action, data)
end
def response
request('FindByName', {'name' => name})
end
def scope_to_owner(contacts)
if owner.is_a?(Creditor)
# Scope to the owner
contacts.select do |creditor_contact|
creditor_contact.get_data
creditor_contact.creditor.handle == owner.handle
end
else
contacts
end
end
end
end
end
end
end
| Clean up FindByName a bit | Clean up FindByName a bit
| Ruby | mit | anderslime/rconomic,kongens-net/rconomic,substancelab/rconomic,lokalebasen/rconomic | ruby | ## Code Before:
module Economic
module Proxies
module Actions
module CreditorContactProxy
class FindByName
attr_reader :name
def initialize(caller, name)
@caller = caller
@name = name
end
def call
# Get a list of CreditorContactHandles from e-conomic
response = request('FindByName', {
'name' => name
})
# Make sure we always have an array of handles even if the result only contains one
handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?)
# Create partial CreditorContact entities
contacts = handles.collect do |handle|
creditor_contact = build
creditor_contact.partial = true
creditor_contact.persisted = true
creditor_contact.handle = handle
creditor_contact.id = handle[:id]
creditor_contact.number = handle[:number]
creditor_contact
end
if owner.is_a?(Creditor)
# Scope to the owner
contacts.select do |creditor_contact|
creditor_contact.get_data
creditor_contact.creditor.handle == owner.handle
end
else
contacts
end
end
private
def build(*options)
@caller.build(options)
end
def owner
@caller.owner
end
def request(action, data)
@caller.request(action, data)
end
end
end
end
end
end
## Instruction:
Clean up FindByName a bit
## Code After:
module Economic
module Proxies
module Actions
module CreditorContactProxy
class FindByName
attr_reader :name
def initialize(caller, name)
@caller = caller
@name = name
end
def call
# Get a list of CreditorContactHandles from e-conomic
handles = [response[:creditor_contact_handle]].flatten.reject(&:blank?)
contacts = build_partial_contact_entities(handles)
scope_to_owner(contacts)
end
private
def build(*options)
@caller.build(options)
end
def build_partial_contact_entities(handles)
handles.collect do |handle|
creditor_contact = build
creditor_contact.partial = true
creditor_contact.persisted = true
creditor_contact.handle = handle
creditor_contact.id = handle[:id]
creditor_contact.number = handle[:number]
creditor_contact
end
end
def owner
@caller.owner
end
def request(action, data)
@caller.request(action, data)
end
def response
request('FindByName', {'name' => name})
end
def scope_to_owner(contacts)
if owner.is_a?(Creditor)
# Scope to the owner
contacts.select do |creditor_contact|
creditor_contact.get_data
creditor_contact.creditor.handle == owner.handle
end
else
contacts
end
end
end
end
end
end
end
|
0f08bdd49437340fd087c753be383f33e70f810a | public/views/content/directives/contentEditRouteModal.tpl.html | public/views/content/directives/contentEditRouteModal.tpl.html | <div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">×</button>
<h4 class="modal-title" translate="{{title}}"></h4>
</div>
<div class="modal-body">
<form name="contentRouteForm" novalidate>
<div class="row">
<div class="col-lg-9">
<!-- Title Form input -->
<div class="form-group">
<label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label>
<input id="title" name="title" type="text" class="form-control" required
ng-model="vm.contentRoute">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-success"
ng-click="vm.editRouteModal.closeModal()">
{{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }}
</button>
<button type="button"
class="btn btn-primary"
ng-click="vm.editRouteModal.saveContentRoute()">
<i class="glyphicon glyphicon-ok-circle"></i>
{{ 'SAVE' | translate }}
</button>
</div>
</div>
</div>
</div>
| <div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">×</button>
<h4 class="modal-title" translate="{{title}}"></h4>
</div>
<div class="modal-body">
<form name="contentRouteForm" novalidate>
<div class="row">
<div class="col-lg-9">
<!-- Title Form input -->
<div class="form-group">
<label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label>
<input id="title" name="title" type="text" class="form-control" required
ng-model="vm.contentRoute">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-success"
ng-click="vm.editRouteModal.closeModal()">
{{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }}
</button>
<button type="button"
class="btn btn-primary"
ng-disabled="contentRouteForm.$invalid"
ng-click="vm.editRouteModal.saveContentRoute()">
<i class="glyphicon glyphicon-ok-circle"></i>
{{ 'SAVE' | translate }}
</button>
</div>
</div>
</div>
</div>
| Edit route modal disable button if form is not valid | Edit route modal disable button if form is not valid
| HTML | mit | GrupaZero/admin,GrupaZero/admin,GrupaZero/admin | html | ## Code Before:
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">×</button>
<h4 class="modal-title" translate="{{title}}"></h4>
</div>
<div class="modal-body">
<form name="contentRouteForm" novalidate>
<div class="row">
<div class="col-lg-9">
<!-- Title Form input -->
<div class="form-group">
<label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label>
<input id="title" name="title" type="text" class="form-control" required
ng-model="vm.contentRoute">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-success"
ng-click="vm.editRouteModal.closeModal()">
{{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }}
</button>
<button type="button"
class="btn btn-primary"
ng-click="vm.editRouteModal.saveContentRoute()">
<i class="glyphicon glyphicon-ok-circle"></i>
{{ 'SAVE' | translate }}
</button>
</div>
</div>
</div>
</div>
## Instruction:
Edit route modal disable button if form is not valid
## Code After:
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="vm.editRouteModal.closeModal()">×</button>
<h4 class="modal-title" translate="{{title}}"></h4>
</div>
<div class="modal-body">
<form name="contentRouteForm" novalidate>
<div class="row">
<div class="col-lg-9">
<!-- Title Form input -->
<div class="form-group">
<label for="title">{{ 'PERMALINK' | translate }} <strong class="text-danger">*</strong></label>
<input id="title" name="title" type="text" class="form-control" required
ng-model="vm.contentRoute">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-success"
ng-click="vm.editRouteModal.closeModal()">
{{ (vm.hideSubmitButton) ? 'OK' : 'CANCEL' | translate }}
</button>
<button type="button"
class="btn btn-primary"
ng-disabled="contentRouteForm.$invalid"
ng-click="vm.editRouteModal.saveContentRoute()">
<i class="glyphicon glyphicon-ok-circle"></i>
{{ 'SAVE' | translate }}
</button>
</div>
</div>
</div>
</div>
|
44728ce3574b7459e2c9304383fe2c1dc2dc0b8b | Source/Model/Connecting/Socket/Tcp/Method/MConnectingSocketTcpMethodTypeFactory.swift | Source/Model/Connecting/Socket/Tcp/Method/MConnectingSocketTcpMethodTypeFactory.swift | import Foundation
extension MConnectingSocketTcpMethodType
{
private static func factoryMethod(
type:MConnectingSocketTcpMethodType) -> MConnectingSocketTcpMethodProtocol.Type
{
switch type
{
case MConnectingSocketTcpMethodType.showpin:
return MConnectingSocketTcpMethodShowpin.self
case MConnectingSocketTcpMethodType.register:
return MConnectingSocketTcpMethodRegister.self
case MConnectingSocketTcpMethodType.registerResult:
return MConnectingSocketTcpMethodRegisterResult.self
case MConnectingSocketTcpMethodType.registerCancel:
return MConnectingSocketTcpMethodRegisterCancel.self
case MConnectingSocketTcpMethodType.connect:
return MConnectingSocketTcpMethodConnect.self
case MConnectingSocketTcpMethodType.standby:
return MConnectingSocketTcpMethodStandby.self
}
}
//MARK: internal
static func factoryMethod(
name:String,
received:String) -> MConnectingSocketTcpMethodProtocol?
{
guard
let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType(
rawValue:name)
else
{
return nil
}
let methodType:MConnectingSocketTcpMethodProtocol.Type = factoryMethod(
type:type)
let method:MConnectingSocketTcpMethodProtocol = methodType.init(
received:received)
return method
}
}
| import Foundation
extension MConnectingSocketTcpMethodType
{
private static let kMethodMap:[
MConnectingSocketTcpMethodType:
MConnectingSocketTcpMethodProtocol.Type] = [
MConnectingSocketTcpMethodType.showpin:
MConnectingSocketTcpMethodShowpin.self,
MConnectingSocketTcpMethodType.register:
MConnectingSocketTcpMethodRegister.self,
MConnectingSocketTcpMethodType.registerResult:
MConnectingSocketTcpMethodRegisterResult.self,
MConnectingSocketTcpMethodType.registerCancel:
MConnectingSocketTcpMethodRegisterCancel.self,
MConnectingSocketTcpMethodType.connect:
MConnectingSocketTcpMethodConnect.self,
MConnectingSocketTcpMethodType.standby:
MConnectingSocketTcpMethodStandby.self]
//MARK: internal
static func factoryMethod(
name:String,
received:String) -> MConnectingSocketTcpMethodProtocol?
{
guard
let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType(
rawValue:name),
let methodType:MConnectingSocketTcpMethodProtocol.Type = kMethodMap[
type]
else
{
return nil
}
let method:MConnectingSocketTcpMethodProtocol = methodType.init(
received:received)
return method
}
}
| Replace switch with method map | Replace switch with method map
| Swift | mit | devpunk/velvet_room,devpunk/velvet_room | swift | ## Code Before:
import Foundation
extension MConnectingSocketTcpMethodType
{
private static func factoryMethod(
type:MConnectingSocketTcpMethodType) -> MConnectingSocketTcpMethodProtocol.Type
{
switch type
{
case MConnectingSocketTcpMethodType.showpin:
return MConnectingSocketTcpMethodShowpin.self
case MConnectingSocketTcpMethodType.register:
return MConnectingSocketTcpMethodRegister.self
case MConnectingSocketTcpMethodType.registerResult:
return MConnectingSocketTcpMethodRegisterResult.self
case MConnectingSocketTcpMethodType.registerCancel:
return MConnectingSocketTcpMethodRegisterCancel.self
case MConnectingSocketTcpMethodType.connect:
return MConnectingSocketTcpMethodConnect.self
case MConnectingSocketTcpMethodType.standby:
return MConnectingSocketTcpMethodStandby.self
}
}
//MARK: internal
static func factoryMethod(
name:String,
received:String) -> MConnectingSocketTcpMethodProtocol?
{
guard
let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType(
rawValue:name)
else
{
return nil
}
let methodType:MConnectingSocketTcpMethodProtocol.Type = factoryMethod(
type:type)
let method:MConnectingSocketTcpMethodProtocol = methodType.init(
received:received)
return method
}
}
## Instruction:
Replace switch with method map
## Code After:
import Foundation
extension MConnectingSocketTcpMethodType
{
private static let kMethodMap:[
MConnectingSocketTcpMethodType:
MConnectingSocketTcpMethodProtocol.Type] = [
MConnectingSocketTcpMethodType.showpin:
MConnectingSocketTcpMethodShowpin.self,
MConnectingSocketTcpMethodType.register:
MConnectingSocketTcpMethodRegister.self,
MConnectingSocketTcpMethodType.registerResult:
MConnectingSocketTcpMethodRegisterResult.self,
MConnectingSocketTcpMethodType.registerCancel:
MConnectingSocketTcpMethodRegisterCancel.self,
MConnectingSocketTcpMethodType.connect:
MConnectingSocketTcpMethodConnect.self,
MConnectingSocketTcpMethodType.standby:
MConnectingSocketTcpMethodStandby.self]
//MARK: internal
static func factoryMethod(
name:String,
received:String) -> MConnectingSocketTcpMethodProtocol?
{
guard
let type:MConnectingSocketTcpMethodType = MConnectingSocketTcpMethodType(
rawValue:name),
let methodType:MConnectingSocketTcpMethodProtocol.Type = kMethodMap[
type]
else
{
return nil
}
let method:MConnectingSocketTcpMethodProtocol = methodType.init(
received:received)
return method
}
}
|
aded5c6d0c859d34cd5af3cf4d15f28a924b6072 | resources/frontend/app/pods/tournament/team/route.js | resources/frontend/app/pods/tournament/team/route.js | import Ember from 'ember';
const {
Route,
RSVP
} = Ember;
export default Route.extend({
deactivate() {
this.store.peekAll('team-member').forEach((team) => {
if (team.get('isNew')) {
this.store.deleteRecord(team);
}
});
},
actions: {
assignMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.save().then(() => {
this.currentModel.get('teamMembers').addObject(member);
flashMessages.success(member.get('name')+' has been assigned to the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to assign member to the team');
});
},
removeMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.destroyRecord().then(() => {
flashMessages.success(member.get('name')+' has been removed from the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to remove member from the team');
});
}
},
model: function (params) {
const store = this.store;
const teamId = params.id;
const tournament = this.modelFor('tournament');
return RSVP.hash({
team: store.find('team', teamId),
matches: store.query('match', {tournamentId: tournament.get('id'), teamId}),
teamMembers: store.query('team-member', {teamId})
}).then((hash) => {
hash.team.set('teamMembers', hash.teamMembers);
return hash;
});
}
});
| import Ember from 'ember';
const {
Route,
RSVP
} = Ember;
export default Route.extend({
deactivate() {
this.store.peekAll('team-member').forEach((team) => {
if (team.get('isNew')) {
this.store.deleteRecord(team);
}
});
},
actions: {
assignMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.save().then(() => {
flashMessages.success(member.get('name')+' has been assigned to the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to assign member to the team');
});
},
removeMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.destroyRecord().then(() => {
flashMessages.success(member.get('name')+' has been removed from the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to remove member from the team');
});
}
},
model: function (params) {
const store = this.store;
const teamId = params.id;
const tournament = this.modelFor('tournament');
return RSVP.hash({
team: store.find('team', teamId),
matches: store.query('match', {tournamentId: tournament.get('id'), teamId}),
teamMembers: store.query('team-member', {teamId})
}).then((hash) => {
hash.team.set('teamMembers', hash.teamMembers);
return hash;
});
}
});
| Fix assign member to the team | Fix assign member to the team
| JavaScript | mit | nixsolutions/ggf,nixsolutions/ggf,nixsolutions/ggf,nixsolutions/ggf | javascript | ## Code Before:
import Ember from 'ember';
const {
Route,
RSVP
} = Ember;
export default Route.extend({
deactivate() {
this.store.peekAll('team-member').forEach((team) => {
if (team.get('isNew')) {
this.store.deleteRecord(team);
}
});
},
actions: {
assignMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.save().then(() => {
this.currentModel.get('teamMembers').addObject(member);
flashMessages.success(member.get('name')+' has been assigned to the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to assign member to the team');
});
},
removeMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.destroyRecord().then(() => {
flashMessages.success(member.get('name')+' has been removed from the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to remove member from the team');
});
}
},
model: function (params) {
const store = this.store;
const teamId = params.id;
const tournament = this.modelFor('tournament');
return RSVP.hash({
team: store.find('team', teamId),
matches: store.query('match', {tournamentId: tournament.get('id'), teamId}),
teamMembers: store.query('team-member', {teamId})
}).then((hash) => {
hash.team.set('teamMembers', hash.teamMembers);
return hash;
});
}
});
## Instruction:
Fix assign member to the team
## Code After:
import Ember from 'ember';
const {
Route,
RSVP
} = Ember;
export default Route.extend({
deactivate() {
this.store.peekAll('team-member').forEach((team) => {
if (team.get('isNew')) {
this.store.deleteRecord(team);
}
});
},
actions: {
assignMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.save().then(() => {
flashMessages.success(member.get('name')+' has been assigned to the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to assign member to the team');
});
},
removeMember(member) {
const flashMessages = Ember.get(this, 'flashMessages');
return member.destroyRecord().then(() => {
flashMessages.success(member.get('name')+' has been removed from the team');
}).catch(() => {
member.rollback();
flashMessages.danger('Unable to remove member from the team');
});
}
},
model: function (params) {
const store = this.store;
const teamId = params.id;
const tournament = this.modelFor('tournament');
return RSVP.hash({
team: store.find('team', teamId),
matches: store.query('match', {tournamentId: tournament.get('id'), teamId}),
teamMembers: store.query('team-member', {teamId})
}).then((hash) => {
hash.team.set('teamMembers', hash.teamMembers);
return hash;
});
}
});
|
66fed655a9b41f6e270acec19fe66f787049063b | src/atom10/feed.php | src/atom10/feed.php | <?php
namespace ComplexPie\Atom10;
class Feed
{
private static $aliases = array(
'description' => 'subtitle',
'tagline' => 'subtitle',
'copyright' => 'rights',
);
private static $elements = array(
'title' => array(
'element' => 'atom:title',
'type' => 'atomTextConstruct',
'single' => true
),
'subtitle' => array(
'element' => 'atom:subtitle',
'type' => 'atomTextConstruct',
'single' => true
),
'rights' => array(
'element' => 'atom:rights',
'type' => 'atomTextConstruct',
'single' => true
),
);
public function __invoke($dom, $name)
{
if (isset(self::$elements[$name]))
{
return $this->elements_table($dom, $name);
}
elseif (isset(self::$aliases[$name]))
{
return $this->__invoke($dom, self::$aliases[$name]);
}
}
private function elements_table($dom, $name)
{
$element = self::$elements[$name];
if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single']))
{
switch ($element['type'])
{
case 'atomTextConstruct':
return Content::from_text_construct($return);
default:
throw new \Exception('Um, this shouldn\'t happen');
}
}
}
}
| <?php
namespace ComplexPie\Atom10;
class Feed
{
private static $aliases = array(
'description' => 'subtitle',
'tagline' => 'subtitle',
'copyright' => 'rights',
);
private static $elements = array(
'title' => array(
'element' => 'atom:title',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
'subtitle' => array(
'element' => 'atom:subtitle',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
'rights' => array(
'element' => 'atom:rights',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
);
public function __invoke($dom, $name)
{
if (isset(self::$elements[$name]))
{
return $this->elements_table($dom, $name);
}
elseif (isset(self::$aliases[$name]))
{
return $this->__invoke($dom, self::$aliases[$name]);
}
}
private function elements_table($dom, $name)
{
$element = self::$elements[$name];
if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single']))
{
return call_user_func($element['contentConstructor'], $return);
}
}
}
| Make this a bit cleaner. | Make this a bit cleaner.
| PHP | bsd-3-clause | gsnedders/complexpie | php | ## Code Before:
<?php
namespace ComplexPie\Atom10;
class Feed
{
private static $aliases = array(
'description' => 'subtitle',
'tagline' => 'subtitle',
'copyright' => 'rights',
);
private static $elements = array(
'title' => array(
'element' => 'atom:title',
'type' => 'atomTextConstruct',
'single' => true
),
'subtitle' => array(
'element' => 'atom:subtitle',
'type' => 'atomTextConstruct',
'single' => true
),
'rights' => array(
'element' => 'atom:rights',
'type' => 'atomTextConstruct',
'single' => true
),
);
public function __invoke($dom, $name)
{
if (isset(self::$elements[$name]))
{
return $this->elements_table($dom, $name);
}
elseif (isset(self::$aliases[$name]))
{
return $this->__invoke($dom, self::$aliases[$name]);
}
}
private function elements_table($dom, $name)
{
$element = self::$elements[$name];
if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single']))
{
switch ($element['type'])
{
case 'atomTextConstruct':
return Content::from_text_construct($return);
default:
throw new \Exception('Um, this shouldn\'t happen');
}
}
}
}
## Instruction:
Make this a bit cleaner.
## Code After:
<?php
namespace ComplexPie\Atom10;
class Feed
{
private static $aliases = array(
'description' => 'subtitle',
'tagline' => 'subtitle',
'copyright' => 'rights',
);
private static $elements = array(
'title' => array(
'element' => 'atom:title',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
'subtitle' => array(
'element' => 'atom:subtitle',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
'rights' => array(
'element' => 'atom:rights',
'contentConstructor' => 'ComplexPie\\Atom10\\Content::from_text_construct',
'single' => true
),
);
public function __invoke($dom, $name)
{
if (isset(self::$elements[$name]))
{
return $this->elements_table($dom, $name);
}
elseif (isset(self::$aliases[$name]))
{
return $this->__invoke($dom, self::$aliases[$name]);
}
}
private function elements_table($dom, $name)
{
$element = self::$elements[$name];
if ($return = \ComplexPie\Misc::get_descendant($dom, $element['element'], array('atom' => XMLNS), $element['single']))
{
return call_user_func($element['contentConstructor'], $return);
}
}
}
|
9a733935a16bf898dcb785316e3a1fc98ac91226 | package/src/frontend/media/createMediaPlayer.js | package/src/frontend/media/createMediaPlayer.js | import {browser} from '../browser';
import {VideoPlayer} from '../VideoPlayer';
export const createMediaPlayer = function (options) {
options.tagName = options.tagName || 'video';
let isAudio = options.tagName == 'audio';
let playsInline = options.playsInline;
let mediaElementTemplate = document.createElement(options.tagName);
mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId);
mediaElementTemplate.setAttribute('crossorigin', 'anonymous');
const player = new VideoPlayer(mediaElementTemplate, {
controlBar: false,
loadingSpinner: false,
bigPlayButton: false,
errorDisplay: false,
textTrackSettings: false,
poster: options.poster,
loop: options.loop,
controls: options.controls,
html5: {
nativeCaptions: !isAudio && browser.has('iphone platform')
},
bufferUnderrunWaiting: true,
useSlimPlayerControlsDuringPhonePlayback: !playsInline && !isAudio,
fullscreenDuringPhonePlayback: !playsInline && !isAudio,
fallbackToMutedAutoplay: !isAudio,
volumeFading: true, //should be turned on later
hooks: undefined,
mediaEvents: true,
context: options.mediaContext
});
if (playsInline) {
player.playsinline(true);
}
player.textTrackSettings = {
getValues() {
return {};
}
};
player.playOrPlayOnLoad = function () {
if (this.readyState() > 0) {
player.play();
} else {
player.on('loadedmetadata', player.play);
}
};
player.addClass('video-js');
player.addClass('player');
return player;
};
| import {browser} from '../browser';
import {VideoPlayer} from '../VideoPlayer';
export const createMediaPlayer = function (options) {
options.tagName = options.tagName || 'video';
let isAudio = options.tagName == 'audio';
let playsInline = options.playsInline;
let mediaElementTemplate = document.createElement(options.tagName);
mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId);
mediaElementTemplate.setAttribute('crossorigin', 'anonymous');
const player = new VideoPlayer(mediaElementTemplate, {
controlBar: false,
loadingSpinner: false,
bigPlayButton: false,
errorDisplay: false,
textTrackSettings: false,
poster: options.poster,
loop: options.loop,
controls: options.controls,
html5: {
nativeCaptions: !isAudio && browser.has('iphone platform')
},
bufferUnderrunWaiting: true,
fallbackToMutedAutoplay: !isAudio,
volumeFading: true, //should be turned on later
hooks: undefined,
mediaEvents: true,
context: options.mediaContext
});
if (playsInline) {
player.playsinline(true);
}
player.textTrackSettings = {
getValues() {
return {};
}
};
player.playOrPlayOnLoad = function () {
if (this.readyState() > 0) {
player.play();
} else {
player.on('loadedmetadata', player.play);
}
};
player.addClass('video-js');
player.addClass('player');
return player;
};
| Remove paged specific options from scrolled media player | Remove paged specific options from scrolled media player
* `fullscreenDuringPhonePlayback` is unused legacy.
* `useSlimPlayerControlsDuringPhonePlayback` refers to paged widget
types.
| JavaScript | mit | tf/pageflow,codevise/pageflow,codevise/pageflow,codevise/pageflow,tf/pageflow,tf/pageflow,codevise/pageflow,tf/pageflow | javascript | ## Code Before:
import {browser} from '../browser';
import {VideoPlayer} from '../VideoPlayer';
export const createMediaPlayer = function (options) {
options.tagName = options.tagName || 'video';
let isAudio = options.tagName == 'audio';
let playsInline = options.playsInline;
let mediaElementTemplate = document.createElement(options.tagName);
mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId);
mediaElementTemplate.setAttribute('crossorigin', 'anonymous');
const player = new VideoPlayer(mediaElementTemplate, {
controlBar: false,
loadingSpinner: false,
bigPlayButton: false,
errorDisplay: false,
textTrackSettings: false,
poster: options.poster,
loop: options.loop,
controls: options.controls,
html5: {
nativeCaptions: !isAudio && browser.has('iphone platform')
},
bufferUnderrunWaiting: true,
useSlimPlayerControlsDuringPhonePlayback: !playsInline && !isAudio,
fullscreenDuringPhonePlayback: !playsInline && !isAudio,
fallbackToMutedAutoplay: !isAudio,
volumeFading: true, //should be turned on later
hooks: undefined,
mediaEvents: true,
context: options.mediaContext
});
if (playsInline) {
player.playsinline(true);
}
player.textTrackSettings = {
getValues() {
return {};
}
};
player.playOrPlayOnLoad = function () {
if (this.readyState() > 0) {
player.play();
} else {
player.on('loadedmetadata', player.play);
}
};
player.addClass('video-js');
player.addClass('player');
return player;
};
## Instruction:
Remove paged specific options from scrolled media player
* `fullscreenDuringPhonePlayback` is unused legacy.
* `useSlimPlayerControlsDuringPhonePlayback` refers to paged widget
types.
## Code After:
import {browser} from '../browser';
import {VideoPlayer} from '../VideoPlayer';
export const createMediaPlayer = function (options) {
options.tagName = options.tagName || 'video';
let isAudio = options.tagName == 'audio';
let playsInline = options.playsInline;
let mediaElementTemplate = document.createElement(options.tagName);
mediaElementTemplate.setAttribute('id', 'pageflow_media_element_'+options.playerId);
mediaElementTemplate.setAttribute('crossorigin', 'anonymous');
const player = new VideoPlayer(mediaElementTemplate, {
controlBar: false,
loadingSpinner: false,
bigPlayButton: false,
errorDisplay: false,
textTrackSettings: false,
poster: options.poster,
loop: options.loop,
controls: options.controls,
html5: {
nativeCaptions: !isAudio && browser.has('iphone platform')
},
bufferUnderrunWaiting: true,
fallbackToMutedAutoplay: !isAudio,
volumeFading: true, //should be turned on later
hooks: undefined,
mediaEvents: true,
context: options.mediaContext
});
if (playsInline) {
player.playsinline(true);
}
player.textTrackSettings = {
getValues() {
return {};
}
};
player.playOrPlayOnLoad = function () {
if (this.readyState() > 0) {
player.play();
} else {
player.on('loadedmetadata', player.play);
}
};
player.addClass('video-js');
player.addClass('player');
return player;
};
|
4233dd881c2166a89712d6265c412d205ae6e544 | src/renderware/gzip_renderware.js | src/renderware/gzip_renderware.js | module.exports = (function() {
"use strict";
const Nodal = require('nodal');
const zlib = require('zlib');
class GzipMiddleware extends Nodal.Middleware {
exec(controller, data, callback) {
let contentType = controller.getHeader('Content-Type', '').split(';')[0];
let acceptEncoding = controller._request.headers['accept-encoding'] || '';
let canCompress = !!{
'text/plain': 1,
'text/html': 1,
'text/xml': 1,
'text/json': 1,
'text/javascript': 1,
'application/json': 1,
'application/xml': 1,
'application/javascript': 1,
'application/octet-stream': 1
}[contentType];
if (canCompress) {
if (acceptEncoding.match(/\bgzip\b/)) {
zlib.gzip(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'gzip');
callback(null, result);
return;
}
callback(null, data);
});
return true;
} else if(acceptEncoding.match(/\bdeflate\b/)) {
zlib.deflate(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'deflate');
callback(null, result);
return;
}
callback(null, data);
});
return true;
}
}
callback(null, data);
return false;
}
}
return GzipMiddleware;
})();
| module.exports = (function() {
"use strict";
const Nodal = require('nodal');
const zlib = require('zlib');
class GzipRenderware extends Nodal.Renderware {
exec(controller, data, callback) {
let contentType = controller.getHeader('Content-Type', '').split(';')[0];
let acceptEncoding = controller._request.headers['accept-encoding'] || '';
let canCompress = !!{
'text/plain': 1,
'text/html': 1,
'text/xml': 1,
'text/json': 1,
'text/javascript': 1,
'application/json': 1,
'application/xml': 1,
'application/javascript': 1,
'application/octet-stream': 1
}[contentType];
if (canCompress) {
if (acceptEncoding.match(/\bgzip\b/)) {
zlib.gzip(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'gzip');
callback(null, result);
return;
}
callback(null, data);
});
return true;
} else if(acceptEncoding.match(/\bdeflate\b/)) {
zlib.deflate(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'deflate');
callback(null, result);
return;
}
callback(null, data);
});
return true;
}
}
callback(null, data);
return false;
}
}
return GzipRenderware;
})();
| Add renderware to generated apps | Add renderware to generated apps
| JavaScript | mit | abossard/nodal,nsipplswezey/nodal,IrregularShed/nodal,IrregularShed/nodal,nsipplswezey/nodal,rlugojr/nodal,nsipplswezey/nodal,abossard/nodal,keithwhor/nodal | javascript | ## Code Before:
module.exports = (function() {
"use strict";
const Nodal = require('nodal');
const zlib = require('zlib');
class GzipMiddleware extends Nodal.Middleware {
exec(controller, data, callback) {
let contentType = controller.getHeader('Content-Type', '').split(';')[0];
let acceptEncoding = controller._request.headers['accept-encoding'] || '';
let canCompress = !!{
'text/plain': 1,
'text/html': 1,
'text/xml': 1,
'text/json': 1,
'text/javascript': 1,
'application/json': 1,
'application/xml': 1,
'application/javascript': 1,
'application/octet-stream': 1
}[contentType];
if (canCompress) {
if (acceptEncoding.match(/\bgzip\b/)) {
zlib.gzip(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'gzip');
callback(null, result);
return;
}
callback(null, data);
});
return true;
} else if(acceptEncoding.match(/\bdeflate\b/)) {
zlib.deflate(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'deflate');
callback(null, result);
return;
}
callback(null, data);
});
return true;
}
}
callback(null, data);
return false;
}
}
return GzipMiddleware;
})();
## Instruction:
Add renderware to generated apps
## Code After:
module.exports = (function() {
"use strict";
const Nodal = require('nodal');
const zlib = require('zlib');
class GzipRenderware extends Nodal.Renderware {
exec(controller, data, callback) {
let contentType = controller.getHeader('Content-Type', '').split(';')[0];
let acceptEncoding = controller._request.headers['accept-encoding'] || '';
let canCompress = !!{
'text/plain': 1,
'text/html': 1,
'text/xml': 1,
'text/json': 1,
'text/javascript': 1,
'application/json': 1,
'application/xml': 1,
'application/javascript': 1,
'application/octet-stream': 1
}[contentType];
if (canCompress) {
if (acceptEncoding.match(/\bgzip\b/)) {
zlib.gzip(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'gzip');
callback(null, result);
return;
}
callback(null, data);
});
return true;
} else if(acceptEncoding.match(/\bdeflate\b/)) {
zlib.deflate(data, function(err, result) {
if (!err) {
controller.setHeader('Content-Encoding', 'deflate');
callback(null, result);
return;
}
callback(null, data);
});
return true;
}
}
callback(null, data);
return false;
}
}
return GzipRenderware;
})();
|
5b29dd7ebb53226552d83551cc1e5acb37331d9b | lib/vagrant/ansible_auto/cap/guest/posix/gateway_addresses.rb | lib/vagrant/ansible_auto/cap/guest/posix/gateway_addresses.rb | require 'set'
module VagrantPlugins
module AnsibleAuto
module Cap
module Guest
module POSIX
class GatewayAddresses
class << self
def gateway_addresses(machine)
with_default_gateway_addresses(machine).to_a.compact
end
private
def with_default_gateway_addresses(machine)
return enum_for(__method__, machine) unless block_given?
seen_addresses = Set.new
yield_unseen_address = lambda do |a|
yield a unless seen_addresses.include? a
seen_addresses << a
end
machine.communicate.execute('ip route show', error_check: false) do |type, data|
if type == :stdout
data.lines.each do |line|
if line.start_with?('default')
yield_unseen_address.call(line.split[2])
end
end
end
end
machine.communicate.execute('route -n', error_check: false) do |type, data|
if type == :stdout
data.lines.each do |line|
if line.start_with?('0.0.0.0')
yield_unseen_address.call(line.split[1])
end
end
end
end
machine.communicate.execute('netstat -rn', error_check: false) do |type, data|
if type == :stdout
data.lines.each do |line|
if line.start_with?('0.0.0.0')
yield_unseen_address.call(line.split[1])
end
end
end
end
end
end
end
end
end
end
end
end
| require 'set'
module VagrantPlugins
module AnsibleAuto
module Cap
module Guest
module POSIX
class GatewayAddresses
class << self
def gateway_addresses(machine)
with_default_gateway_addresses(machine).to_a.compact
end
private
def with_default_gateway_addresses(machine)
return enum_for(__method__, machine) unless block_given?
machine.communicate.execute('ip route show', error_check: false) do |type, data|
if type == :stdout
data.each_line { |l| yield l.split[2] if l.start_with? 'default' }
end
end
machine.communicate.execute('route -n', error_check: false) do |type, data|
if type == :stdout
data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' }
end
end
machine.communicate.execute('netstat -rn', error_check: false) do |type, data|
if type == :stdout
data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' }
end
end
end
end
end
end
end
end
end
end
| Simplify iteration over candidate gateway IP addresses | Simplify iteration over candidate gateway IP addresses
| Ruby | mit | BaxterStockman/vagrant-ansible_auto | ruby | ## Code Before:
require 'set'
module VagrantPlugins
module AnsibleAuto
module Cap
module Guest
module POSIX
class GatewayAddresses
class << self
def gateway_addresses(machine)
with_default_gateway_addresses(machine).to_a.compact
end
private
def with_default_gateway_addresses(machine)
return enum_for(__method__, machine) unless block_given?
seen_addresses = Set.new
yield_unseen_address = lambda do |a|
yield a unless seen_addresses.include? a
seen_addresses << a
end
machine.communicate.execute('ip route show', error_check: false) do |type, data|
if type == :stdout
data.lines.each do |line|
if line.start_with?('default')
yield_unseen_address.call(line.split[2])
end
end
end
end
machine.communicate.execute('route -n', error_check: false) do |type, data|
if type == :stdout
data.lines.each do |line|
if line.start_with?('0.0.0.0')
yield_unseen_address.call(line.split[1])
end
end
end
end
machine.communicate.execute('netstat -rn', error_check: false) do |type, data|
if type == :stdout
data.lines.each do |line|
if line.start_with?('0.0.0.0')
yield_unseen_address.call(line.split[1])
end
end
end
end
end
end
end
end
end
end
end
end
## Instruction:
Simplify iteration over candidate gateway IP addresses
## Code After:
require 'set'
module VagrantPlugins
module AnsibleAuto
module Cap
module Guest
module POSIX
class GatewayAddresses
class << self
def gateway_addresses(machine)
with_default_gateway_addresses(machine).to_a.compact
end
private
def with_default_gateway_addresses(machine)
return enum_for(__method__, machine) unless block_given?
machine.communicate.execute('ip route show', error_check: false) do |type, data|
if type == :stdout
data.each_line { |l| yield l.split[2] if l.start_with? 'default' }
end
end
machine.communicate.execute('route -n', error_check: false) do |type, data|
if type == :stdout
data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' }
end
end
machine.communicate.execute('netstat -rn', error_check: false) do |type, data|
if type == :stdout
data.each_line { |l| yield l.split[1] if l.start_with? '0.0.0.0' }
end
end
end
end
end
end
end
end
end
end
|
e4c288af36bf36188e5c1c25513877718883adb6 | tests/integration/components/license-picker/component-test.js | tests/integration/components/license-picker/component-test.js | import Ember from 'ember';
import FakeServer, { stubRequest } from 'ember-cli-fake-server';
import config from 'ember-get-config';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('license-picker', 'Integration | Component | license picker', {
integration: true
});
function render(ctx, args) {
let noop = () => {};
this.set('noop', noop);
let licenses = [{
name: 'Without',
text: 'This is a license without input fields',
requiredFields: []
}, {
name: 'No license',
text: '{{yearRequired}} {{copyrightHolders}}',
required_fields: ['yearRequired', 'copyrightHolders']
}]
ctx.set('licenses', licenses);
return ctx.render(Ember.HTMLBars.compile(`{{license-picker
${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''}
allowDismiss=false
licenses=licenses
pressSubmit=(action noop)
${args || ''}
}}`));
}
test('it renders', function(assert) {
render(this);
assert.ok(true);
});
test('default values cause autosave to trigger', function(assert) {
let called = false;
const autosaveFunc = () => {
called = true;
}
this.set('autosaveFunc', autosaveFunc);
let currentValues = {};
this.set('currentValues', currentValues);
render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues');
assert.ok(called);
});
test('passing currentValues does not trigger autosave', function(assert) {
let called = false;
const autosaveFunc = () => {
called = true;
}
this.set('autosaveFunc', autosaveFunc);
let currentValues = {
year: '2017',
copyrightHolders: 'Henrique',
nodeLicense: {
id: 'a license'
}
};
this.set('currentValues', currentValues);
render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues');
assert.ok(!called);
});
| import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('license-picker', 'Integration | Component | license picker', {
integration: true
});
function render(ctx, args) {
ctx.set('currentValues', {});
ctx.set('noop', () => {});
ctx.set('licenses', [{
name: 'Without',
text: 'This is a license without input fields',
requiredFields: []
}, {
name: 'No license',
text: '{{yearRequired}} {{copyrightHolders}}',
required_fields: ['yearRequired', 'copyrightHolders']
}]);
return ctx.render(Ember.HTMLBars.compile(`{{license-picker
${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''}
allowDismiss=false
licenses=licenses
currentValues=currentValues
pressSubmit=(action noop)
${args || ''}
}}`));
}
test('it renders', function(assert) {
render(this);
assert.ok(true);
});
| Fix linting, remove tests dependent on observables | Fix linting, remove tests dependent on observables
| JavaScript | apache-2.0 | binoculars/ember-osf,CenterForOpenScience/ember-osf,binoculars/ember-osf,jamescdavis/ember-osf,baylee-d/ember-osf,crcresearch/ember-osf,jamescdavis/ember-osf,chrisseto/ember-osf,CenterForOpenScience/ember-osf,baylee-d/ember-osf,chrisseto/ember-osf,crcresearch/ember-osf | javascript | ## Code Before:
import Ember from 'ember';
import FakeServer, { stubRequest } from 'ember-cli-fake-server';
import config from 'ember-get-config';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('license-picker', 'Integration | Component | license picker', {
integration: true
});
function render(ctx, args) {
let noop = () => {};
this.set('noop', noop);
let licenses = [{
name: 'Without',
text: 'This is a license without input fields',
requiredFields: []
}, {
name: 'No license',
text: '{{yearRequired}} {{copyrightHolders}}',
required_fields: ['yearRequired', 'copyrightHolders']
}]
ctx.set('licenses', licenses);
return ctx.render(Ember.HTMLBars.compile(`{{license-picker
${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''}
allowDismiss=false
licenses=licenses
pressSubmit=(action noop)
${args || ''}
}}`));
}
test('it renders', function(assert) {
render(this);
assert.ok(true);
});
test('default values cause autosave to trigger', function(assert) {
let called = false;
const autosaveFunc = () => {
called = true;
}
this.set('autosaveFunc', autosaveFunc);
let currentValues = {};
this.set('currentValues', currentValues);
render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues');
assert.ok(called);
});
test('passing currentValues does not trigger autosave', function(assert) {
let called = false;
const autosaveFunc = () => {
called = true;
}
this.set('autosaveFunc', autosaveFunc);
let currentValues = {
year: '2017',
copyrightHolders: 'Henrique',
nodeLicense: {
id: 'a license'
}
};
this.set('currentValues', currentValues);
render(this, 'editLicense=autosaveFunc autosave=true currentValues=currentValues');
assert.ok(!called);
});
## Instruction:
Fix linting, remove tests dependent on observables
## Code After:
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('license-picker', 'Integration | Component | license picker', {
integration: true
});
function render(ctx, args) {
ctx.set('currentValues', {});
ctx.set('noop', () => {});
ctx.set('licenses', [{
name: 'Without',
text: 'This is a license without input fields',
requiredFields: []
}, {
name: 'No license',
text: '{{yearRequired}} {{copyrightHolders}}',
required_fields: ['yearRequired', 'copyrightHolders']
}]);
return ctx.render(Ember.HTMLBars.compile(`{{license-picker
${args && args.indexOf('editLicense') === -1 ? 'editLicense=(action noop)' : ''}
allowDismiss=false
licenses=licenses
currentValues=currentValues
pressSubmit=(action noop)
${args || ''}
}}`));
}
test('it renders', function(assert) {
render(this);
assert.ok(true);
});
|
450a1f64a21afce008392e321fff2d268bb9fc41 | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ALGPATH = "clusterpy/core/toolboxes/cluster/componentsAlg/"
ALGPKG = "clusterpy.core.toolboxes.cluster.componentsAlg."
CLUSPATH = "clusterpy/core/toolboxes/cluster/"
CLUSPKG = "clusterpy.core.toolboxes.cluster."
setup(
name='clusterPy',
version='0.9.9',
description='Library of spatially constrained clustering algorithms',
long_description="""
clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""",
author='RiSE Group',
author_email='software@rise-group.org',
url='http://www.rise-group.org/section/Software/clusterPy/',
packages=['clusterpy','clusterpy.core','clusterpy.core.data',
'clusterpy.core.geometry','clusterpy.core.toolboxes',
'clusterpy.core.toolboxes.cluster',
'clusterpy.core.toolboxes.cluster.componentsAlg'],
ext_modules = [Extension(CLUSPKG+"arisel", [CLUSPATH+"arisel.pyx"],
extra_link_args=['-fopenmp'],
extra_compile_args=['-fopenmp']
),
Extension(ALGPKG+"distanceFunctions", [ALGPATH+"distanceFunctions.pyx"]),
Extension(ALGPKG+"dist2Regions", [ALGPATH+"dist2Regions.pyx"]),
Extension(ALGPKG+"selectionTypeFunctions", [ALGPATH+"selectionTypeFunctions.pyx"]),
Extension(ALGPKG+"init", [ALGPATH+"init.pyx"]),
Extension(ALGPKG+"objFunctions", [ALGPATH+"objFunctions.pyx"])
],
cmdclass = {'build_ext': build_ext}
)
| from distutils.core import setup
from distutils.extension import Extension
setup(
name='clusterPy',
version='0.9.9',
description='Library of spatially constrained clustering algorithms',
long_description="""
clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""",
author='RiSE Group',
author_email='software@rise-group.org',
url='http://www.rise-group.org/section/Software/clusterPy/',
packages=['clusterpy','clusterpy.core','clusterpy.core.data',
'clusterpy.core.geometry','clusterpy.core.toolboxes',
'clusterpy.core.toolboxes.cluster',
'clusterpy.core.toolboxes.cluster.componentsAlg'],
)
| Remove cython Extension builder and build_ext from Setup | Remove cython Extension builder and build_ext from Setup
| Python | bsd-3-clause | clusterpy/clusterpy,clusterpy/clusterpy | python | ## Code Before:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ALGPATH = "clusterpy/core/toolboxes/cluster/componentsAlg/"
ALGPKG = "clusterpy.core.toolboxes.cluster.componentsAlg."
CLUSPATH = "clusterpy/core/toolboxes/cluster/"
CLUSPKG = "clusterpy.core.toolboxes.cluster."
setup(
name='clusterPy',
version='0.9.9',
description='Library of spatially constrained clustering algorithms',
long_description="""
clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""",
author='RiSE Group',
author_email='software@rise-group.org',
url='http://www.rise-group.org/section/Software/clusterPy/',
packages=['clusterpy','clusterpy.core','clusterpy.core.data',
'clusterpy.core.geometry','clusterpy.core.toolboxes',
'clusterpy.core.toolboxes.cluster',
'clusterpy.core.toolboxes.cluster.componentsAlg'],
ext_modules = [Extension(CLUSPKG+"arisel", [CLUSPATH+"arisel.pyx"],
extra_link_args=['-fopenmp'],
extra_compile_args=['-fopenmp']
),
Extension(ALGPKG+"distanceFunctions", [ALGPATH+"distanceFunctions.pyx"]),
Extension(ALGPKG+"dist2Regions", [ALGPATH+"dist2Regions.pyx"]),
Extension(ALGPKG+"selectionTypeFunctions", [ALGPATH+"selectionTypeFunctions.pyx"]),
Extension(ALGPKG+"init", [ALGPATH+"init.pyx"]),
Extension(ALGPKG+"objFunctions", [ALGPATH+"objFunctions.pyx"])
],
cmdclass = {'build_ext': build_ext}
)
## Instruction:
Remove cython Extension builder and build_ext from Setup
## Code After:
from distutils.core import setup
from distutils.extension import Extension
setup(
name='clusterPy',
version='0.9.9',
description='Library of spatially constrained clustering algorithms',
long_description="""
clusterPy is a Python library with algorithms for spatially constrained clustering. clusterPy offers you some of the most cited algorithms for spatial aggregation.""",
author='RiSE Group',
author_email='software@rise-group.org',
url='http://www.rise-group.org/section/Software/clusterPy/',
packages=['clusterpy','clusterpy.core','clusterpy.core.data',
'clusterpy.core.geometry','clusterpy.core.toolboxes',
'clusterpy.core.toolboxes.cluster',
'clusterpy.core.toolboxes.cluster.componentsAlg'],
)
|
ddec6067054cc4408ac174e3ea4ffeca2a962201 | regulations/views/notice_home.py | regulations/views/notice_home.py |
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.views.preamble import (
notice_data, CommentState)
logger = logging.getLogger(__name__)
class NoticeHomeView(View):
"""
Basic view that provides a list of regulations and notices to the context.
"""
template_name = None # We should probably have a default notice template.
def get(self, request, *args, **kwargs):
notices = ApiReader().notices().get("results", [])
context = {}
notices_meta = []
for notice in notices:
try:
if notice.get("document_number"):
_, meta, _ = notice_data(notice["document_number"])
notices_meta.append(meta)
except Http404:
pass
notices_meta = sorted(notices_meta, key=itemgetter("publication_date"),
reverse=True)
context["notices"] = notices_meta
# Django templates won't show contents of CommentState as an Enum, so:
context["comment_state"] = {state.name: state.value for state in
CommentState}
assert self.template_name
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context)
|
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.views.preamble import (
notice_data, CommentState)
logger = logging.getLogger(__name__)
class NoticeHomeView(View):
"""
Basic view that provides a list of regulations and notices to the context.
"""
template_name = None # We should probably have a default notice template.
def get(self, request, *args, **kwargs):
notices = ApiReader().notices().get("results", [])
context = {}
notices_meta = []
for notice in notices:
try:
if notice.get("document_number"):
_, meta, _ = notice_data(notice["document_number"])
notices_meta.append(meta)
except Http404:
pass
notices_meta = sorted(notices_meta, key=itemgetter("publication_date"),
reverse=True)
context["notices"] = notices_meta
# Django templates won't show contents of CommentState as an Enum, so:
context["comment_state"] = {state.name: state.value for state in
CommentState}
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context)
| Remove unnecessary assert from view for Notice home. | Remove unnecessary assert from view for Notice home.
| Python | cc0-1.0 | 18F/regulations-site,18F/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,18F/regulations-site | python | ## Code Before:
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.views.preamble import (
notice_data, CommentState)
logger = logging.getLogger(__name__)
class NoticeHomeView(View):
"""
Basic view that provides a list of regulations and notices to the context.
"""
template_name = None # We should probably have a default notice template.
def get(self, request, *args, **kwargs):
notices = ApiReader().notices().get("results", [])
context = {}
notices_meta = []
for notice in notices:
try:
if notice.get("document_number"):
_, meta, _ = notice_data(notice["document_number"])
notices_meta.append(meta)
except Http404:
pass
notices_meta = sorted(notices_meta, key=itemgetter("publication_date"),
reverse=True)
context["notices"] = notices_meta
# Django templates won't show contents of CommentState as an Enum, so:
context["comment_state"] = {state.name: state.value for state in
CommentState}
assert self.template_name
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context)
## Instruction:
Remove unnecessary assert from view for Notice home.
## Code After:
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.views.preamble import (
notice_data, CommentState)
logger = logging.getLogger(__name__)
class NoticeHomeView(View):
"""
Basic view that provides a list of regulations and notices to the context.
"""
template_name = None # We should probably have a default notice template.
def get(self, request, *args, **kwargs):
notices = ApiReader().notices().get("results", [])
context = {}
notices_meta = []
for notice in notices:
try:
if notice.get("document_number"):
_, meta, _ = notice_data(notice["document_number"])
notices_meta.append(meta)
except Http404:
pass
notices_meta = sorted(notices_meta, key=itemgetter("publication_date"),
reverse=True)
context["notices"] = notices_meta
# Django templates won't show contents of CommentState as an Enum, so:
context["comment_state"] = {state.name: state.value for state in
CommentState}
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context)
|
fa62ad541d147e740bedd97f470390aafe882e8f | app/js/arethusa.core/directives/foreign_keys.js | app/js/arethusa.core/directives/foreign_keys.js | 'use strict';
angular.module('arethusa.core').directive('foreignKeys',[
'keyCapture',
'languageSettings',
function (keyCapture, languageSettings) {
return {
restrict: 'A',
scope: {
ngChange: '&',
ngModel: '@',
foreignKeys: '='
},
link: function (scope, element, attrs) {
var parent = scope.$parent;
function extractLanguage() {
return (languageSettings.getFor('treebank') || {}).lang;
}
function lang() {
return scope.foreignKeys || extractLanguage();
}
// This will not detect changes right now
function placeHolderText() {
var language = languageSettings.langNames[lang()];
return language ? language + ' input enabled!' : '';
}
element.attr('placeholder', placeHolderText);
element.on('keydown', function (event) {
var input = event.target.value;
if (lang) {
var fK = keyCapture.getForeignKey(event, lang);
if (fK === false) {
return false;
}
if (fK === undefined) {
return true;
} else {
event.target.value = input + fK;
scope.$apply(function() {
parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK });
scope.ngChange();
});
return false;
}
} else {
return true;
}
});
}
};
}
]);
| 'use strict';
angular.module('arethusa.core').directive('foreignKeys',[
'keyCapture',
'languageSettings',
function (keyCapture, languageSettings) {
return {
restrict: 'A',
scope: {
ngChange: '&',
ngModel: '@',
foreignKeys: '='
},
link: function (scope, element, attrs) {
var parent = scope.$parent;
function extractLanguage() {
return (languageSettings.getFor('treebank') || {}).lang;
}
function lang() {
return scope.foreignKeys || extractLanguage();
}
// This will not detect changes right now
function placeHolderText() {
var language = languageSettings.langNames[lang()];
return language ? language + ' input enabled!' : '';
}
element.attr('placeholder', placeHolderText);
element.on('keydown', function (event) {
var input = event.target.value;
var l = lang();
if (l) {
var fK = keyCapture.getForeignKey(event, l);
if (fK === false) {
return false;
}
if (fK === undefined) {
return true;
} else {
event.target.value = input + fK;
scope.$apply(function() {
parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK });
scope.ngChange();
});
return false;
}
} else {
return true;
}
});
}
};
}
]);
| Fix minor mistake in foreignKeys | Fix minor mistake in foreignKeys
| JavaScript | mit | latin-language-toolkit/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa | javascript | ## Code Before:
'use strict';
angular.module('arethusa.core').directive('foreignKeys',[
'keyCapture',
'languageSettings',
function (keyCapture, languageSettings) {
return {
restrict: 'A',
scope: {
ngChange: '&',
ngModel: '@',
foreignKeys: '='
},
link: function (scope, element, attrs) {
var parent = scope.$parent;
function extractLanguage() {
return (languageSettings.getFor('treebank') || {}).lang;
}
function lang() {
return scope.foreignKeys || extractLanguage();
}
// This will not detect changes right now
function placeHolderText() {
var language = languageSettings.langNames[lang()];
return language ? language + ' input enabled!' : '';
}
element.attr('placeholder', placeHolderText);
element.on('keydown', function (event) {
var input = event.target.value;
if (lang) {
var fK = keyCapture.getForeignKey(event, lang);
if (fK === false) {
return false;
}
if (fK === undefined) {
return true;
} else {
event.target.value = input + fK;
scope.$apply(function() {
parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK });
scope.ngChange();
});
return false;
}
} else {
return true;
}
});
}
};
}
]);
## Instruction:
Fix minor mistake in foreignKeys
## Code After:
'use strict';
angular.module('arethusa.core').directive('foreignKeys',[
'keyCapture',
'languageSettings',
function (keyCapture, languageSettings) {
return {
restrict: 'A',
scope: {
ngChange: '&',
ngModel: '@',
foreignKeys: '='
},
link: function (scope, element, attrs) {
var parent = scope.$parent;
function extractLanguage() {
return (languageSettings.getFor('treebank') || {}).lang;
}
function lang() {
return scope.foreignKeys || extractLanguage();
}
// This will not detect changes right now
function placeHolderText() {
var language = languageSettings.langNames[lang()];
return language ? language + ' input enabled!' : '';
}
element.attr('placeholder', placeHolderText);
element.on('keydown', function (event) {
var input = event.target.value;
var l = lang();
if (l) {
var fK = keyCapture.getForeignKey(event, l);
if (fK === false) {
return false;
}
if (fK === undefined) {
return true;
} else {
event.target.value = input + fK;
scope.$apply(function() {
parent.$eval(scope.ngModel + ' = i + k', { i: input, k: fK });
scope.ngChange();
});
return false;
}
} else {
return true;
}
});
}
};
}
]);
|
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 33