commit stringlengths 40 40 | old_file stringlengths 4 184 | new_file stringlengths 4 184 | old_contents stringlengths 1 3.6k | new_contents stringlengths 5 3.38k | subject stringlengths 15 778 | message stringlengths 16 6.74k | lang stringclasses 201 values | license stringclasses 13 values | repos stringlengths 6 116k | config stringclasses 201 values | content stringlengths 137 7.24k | diff stringlengths 26 5.55k | diff_length int64 1 123 | relative_diff_length float64 0.01 89 | n_lines_added int64 0 108 | n_lines_deleted int64 0 106 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e870bbe15a24839e87265ae115d3bbdf41785c0c | spec/support/rails.rb | spec/support/rails.rb | ENV['RAILS_ENV'] = 'test'
require "sprockets/railtie"
module RetinaRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
if Rails::VERSION::STRING >= "4.0.0"
config.secret_token = 'existing secret token'
config.secret_key_base = 'new secret key base'
end
end
end
RetinaRailsTest::Application.initialize! | ENV['RAILS_ENV'] = 'test'
require "sprockets/railtie"
module RetinaRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
if Rails::VERSION::STRING >= "4.0.0"
config.eager_load = false
config.secret_token = 'existing secret token'
config.secret_key_base = 'new secret key base'
end
end
end
RetinaRailsTest::Application.initialize!
| Fix Rails deprecation warning about missing config | Fix Rails deprecation warning about missing config
| Ruby | mit | jhnvz/retina_rails | ruby | ## Code Before:
ENV['RAILS_ENV'] = 'test'
require "sprockets/railtie"
module RetinaRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
if Rails::VERSION::STRING >= "4.0.0"
config.secret_token = 'existing secret token'
config.secret_key_base = 'new secret key base'
end
end
end
RetinaRailsTest::Application.initialize!
## Instruction:
Fix Rails deprecation warning about missing config
## Code After:
ENV['RAILS_ENV'] = 'test'
require "sprockets/railtie"
module RetinaRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
if Rails::VERSION::STRING >= "4.0.0"
config.eager_load = false
config.secret_token = 'existing secret token'
config.secret_key_base = 'new secret key base'
end
end
end
RetinaRailsTest::Application.initialize!
| ENV['RAILS_ENV'] = 'test'
require "sprockets/railtie"
module RetinaRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
if Rails::VERSION::STRING >= "4.0.0"
+ config.eager_load = false
config.secret_token = 'existing secret token'
config.secret_key_base = 'new secret key base'
end
end
end
+
RetinaRailsTest::Application.initialize! | 2 | 0.125 | 2 | 0 |
1c12dc4bd38933ed4e0e4001d05f57176ddc8144 | patches/fix-regex-static-link.patch | patches/fix-regex-static-link.patch | diff --git a/meson.build b/meson.build
index 5570a8a1f39..3dc876413d0 100644
--- a/meson.build
+++ b/meson.build
@@ -1613,9 +1613,12 @@ endif
dep_m = cc.find_library('m', required : false)
if host_machine.system() == 'windows'
- dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ dep_regex = declare_dependency(dependencies : [dependency('regex', required : false)], link_args : ['-liconv'])
if not dep_regex.found()
- dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
+ dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ if not dep_regex.found()
+ dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
+ endif
endif
else
dep_regex = null_dep
| diff --git a/meson.build b/meson.build
index cdff0312e56..46efce97533 100644
--- a/meson.build
+++ b/meson.build
@@ -1566,7 +1566,12 @@ endif
dep_m = cc.find_library('m', required : false)
if host_machine.system() == 'windows'
- dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ dep_part_regex = dependency('regex', required : false)
+ if dep_part_regex.found()
+ dep_regex = declare_dependency(dependencies : [dep_part_regex], link_args : ['-liconv'])
+ else
+ dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ endif
if not dep_regex.found()
dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
endif
| Fix regex linking patch breaking MSVC build | Fix regex linking patch breaking MSVC build
| Diff | mit | pal1000/mesa-dist-win,pal1000/mesa-dist-win | diff | ## Code Before:
diff --git a/meson.build b/meson.build
index 5570a8a1f39..3dc876413d0 100644
--- a/meson.build
+++ b/meson.build
@@ -1613,9 +1613,12 @@ endif
dep_m = cc.find_library('m', required : false)
if host_machine.system() == 'windows'
- dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ dep_regex = declare_dependency(dependencies : [dependency('regex', required : false)], link_args : ['-liconv'])
if not dep_regex.found()
- dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
+ dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ if not dep_regex.found()
+ dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
+ endif
endif
else
dep_regex = null_dep
## Instruction:
Fix regex linking patch breaking MSVC build
## Code After:
diff --git a/meson.build b/meson.build
index cdff0312e56..46efce97533 100644
--- a/meson.build
+++ b/meson.build
@@ -1566,7 +1566,12 @@ endif
dep_m = cc.find_library('m', required : false)
if host_machine.system() == 'windows'
- dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ dep_part_regex = dependency('regex', required : false)
+ if dep_part_regex.found()
+ dep_regex = declare_dependency(dependencies : [dep_part_regex], link_args : ['-liconv'])
+ else
+ dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ endif
if not dep_regex.found()
dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
endif
| diff --git a/meson.build b/meson.build
- index 5570a8a1f39..3dc876413d0 100644
+ index cdff0312e56..46efce97533 100644
--- a/meson.build
+++ b/meson.build
- @@ -1613,9 +1613,12 @@ endif
? ^^ ^ ^^
+ @@ -1566,7 +1566,12 @@ endif
? + ^ ^ + ^
dep_m = cc.find_library('m', required : false)
if host_machine.system() == 'windows'
- dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ + dep_part_regex = dependency('regex', required : false)
+ + if dep_part_regex.found()
- + dep_regex = declare_dependency(dependencies : [dependency('regex', required : false)], link_args : ['-liconv'])
? ^^^^^^^^^ --------------------
+ + dep_regex = declare_dependency(dependencies : [dep_part_regex], link_args : ['-liconv'])
? ++ ^^^^^^
+ + else
+ + dep_regex = meson.get_compiler('c').find_library('regex', required : false)
+ + endif
if not dep_regex.found()
- - dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
- + dep_regex = meson.get_compiler('c').find_library('regex', required : false)
- + if not dep_regex.found()
- + dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
? --
+ dep_regex = declare_dependency(compile_args : ['-DNO_REGEX'])
- + endif
endif
- else
- dep_regex = null_dep | 19 | 1 | 9 | 10 |
3c52c0ce23cc4e0862d19a044bfb0661ed3677d5 | manifest.json | manifest.json | {
"name": "Linksplosion",
"version": "0.3",
"manifest_version": 2,
"description": "Open all links in selected text.",
"homepage_url": "https://github.com/ggreer/linksplosion",
"icons": {
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {"scripts": ["background.js"]},
"permissions": [
"contextMenus",
"tabs",
"<all_urls>"
]
}
| {
"name": "Linksplosion",
"version": "0.4",
"manifest_version": 2,
"description": "Open all links in selected text.",
"homepage_url": "https://github.com/ggreer/linksplosion",
"icons": {
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {"scripts": ["background.js"]},
"permissions": [
"contextMenus",
"<all_urls>"
]
}
| Remove tabs permission. It's not needed. | Remove tabs permission. It's not needed.
| JSON | apache-2.0 | ggreer/linksplosion | json | ## Code Before:
{
"name": "Linksplosion",
"version": "0.3",
"manifest_version": 2,
"description": "Open all links in selected text.",
"homepage_url": "https://github.com/ggreer/linksplosion",
"icons": {
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {"scripts": ["background.js"]},
"permissions": [
"contextMenus",
"tabs",
"<all_urls>"
]
}
## Instruction:
Remove tabs permission. It's not needed.
## Code After:
{
"name": "Linksplosion",
"version": "0.4",
"manifest_version": 2,
"description": "Open all links in selected text.",
"homepage_url": "https://github.com/ggreer/linksplosion",
"icons": {
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {"scripts": ["background.js"]},
"permissions": [
"contextMenus",
"<all_urls>"
]
}
| {
"name": "Linksplosion",
- "version": "0.3",
? ^
+ "version": "0.4",
? ^
"manifest_version": 2,
"description": "Open all links in selected text.",
"homepage_url": "https://github.com/ggreer/linksplosion",
"icons": {
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"background": {"scripts": ["background.js"]},
"permissions": [
"contextMenus",
- "tabs",
"<all_urls>"
]
} | 3 | 0.176471 | 1 | 2 |
83241dd5d303debb37bef1aa08331e0f68c9bfa2 | README.md | README.md | A collection of bash scripts that I have written for one-off applications. Feel to use any of them however you want, but I must warn you that they probably aren't the best examples to learn from. I generally try to stay somewhat portable and POSIX compliant but I also don't follow a lot of best practices.
# Running the scripts
I test these on GNU bash(Version 4.2.25(1)-release x86_64-pc-linux-gnu) and a Debian Stable machine(3.16.0-4-amd64 right now). I don't guarantee these will work on any UNIX platform and there may be edge cases that I didn't account for.
# Documentation
I try to comment on any unusual or non-obvious parts of my code, but you can also find more explanations on my website: https://www.graysonskent.com or just email me about it.
# License
Do whatever you want with them, just don't blame me.
| A collection of bash scripts that I have written for one-off applications. Feel to use any of them however you want. I generally try to stay somewhat portable and POSIX compliant.
# Running the scripts
I test these on GNU bash(Version 4.2.25(1)-release x86_64-pc-linux-gnu) and a Debian Stable machine(3.16.0-4-amd64 right now). I don't guarantee these will work on any UNIX platform and there may be edge cases that I didn't account for.
# Documentation
I try to comment on any unusual or non-obvious parts of my code, but you can also find more explanations on my website: www.grayson.sh or just email me about it.
# License
Do whatever you want with them, just don't blame me.
| Update readme.md for new website | Update readme.md for new website | Markdown | mit | graysonkent/misc-scripts,graysonkent/misc-bash-scripts | markdown | ## Code Before:
A collection of bash scripts that I have written for one-off applications. Feel to use any of them however you want, but I must warn you that they probably aren't the best examples to learn from. I generally try to stay somewhat portable and POSIX compliant but I also don't follow a lot of best practices.
# Running the scripts
I test these on GNU bash(Version 4.2.25(1)-release x86_64-pc-linux-gnu) and a Debian Stable machine(3.16.0-4-amd64 right now). I don't guarantee these will work on any UNIX platform and there may be edge cases that I didn't account for.
# Documentation
I try to comment on any unusual or non-obvious parts of my code, but you can also find more explanations on my website: https://www.graysonskent.com or just email me about it.
# License
Do whatever you want with them, just don't blame me.
## Instruction:
Update readme.md for new website
## Code After:
A collection of bash scripts that I have written for one-off applications. Feel to use any of them however you want. I generally try to stay somewhat portable and POSIX compliant.
# Running the scripts
I test these on GNU bash(Version 4.2.25(1)-release x86_64-pc-linux-gnu) and a Debian Stable machine(3.16.0-4-amd64 right now). I don't guarantee these will work on any UNIX platform and there may be edge cases that I didn't account for.
# Documentation
I try to comment on any unusual or non-obvious parts of my code, but you can also find more explanations on my website: www.grayson.sh or just email me about it.
# License
Do whatever you want with them, just don't blame me.
| - A collection of bash scripts that I have written for one-off applications. Feel to use any of them however you want, but I must warn you that they probably aren't the best examples to learn from. I generally try to stay somewhat portable and POSIX compliant but I also don't follow a lot of best practices.
+ A collection of bash scripts that I have written for one-off applications. Feel to use any of them however you want. I generally try to stay somewhat portable and POSIX compliant.
# Running the scripts
I test these on GNU bash(Version 4.2.25(1)-release x86_64-pc-linux-gnu) and a Debian Stable machine(3.16.0-4-amd64 right now). I don't guarantee these will work on any UNIX platform and there may be edge cases that I didn't account for.
# Documentation
- I try to comment on any unusual or non-obvious parts of my code, but you can also find more explanations on my website: https://www.graysonskent.com or just email me about it.
? -------- ^^^^^^^^
+ I try to comment on any unusual or non-obvious parts of my code, but you can also find more explanations on my website: www.grayson.sh or just email me about it.
? + ^
# License
Do whatever you want with them, just don't blame me. | 4 | 0.4 | 2 | 2 |
f2111bf34092e5c497b37835f585b5ae266abee6 | lib/gir_ffi-gnome_keyring/found.rb | lib/gir_ffi-gnome_keyring/found.rb | require 'gir_ffi-gnome_keyring/attribute_list'
module GnomeKeyring
load_class :Found
class Found
def attributes
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
GnomeKeyring::AttributeList.wrap(struct[:attributes])
end
def attributes=(value)
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
struct[:attributes] = GnomeKeyring::AttributeList.from(value)
end
end
end
| require 'gir_ffi-gnome_keyring/attribute_list'
module GnomeKeyring
load_class :Found
class Found
remove_method :attributes
remove_method :attributes=
def attributes
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
GnomeKeyring::AttributeList.wrap(struct[:attributes])
end
def attributes=(value)
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
struct[:attributes] = GnomeKeyring::AttributeList.from(value)
end
end
end
| Remove old methods before redefining | Remove old methods before redefining
| Ruby | lgpl-2.1 | mvz/gir_ffi-gnome_keyring | ruby | ## Code Before:
require 'gir_ffi-gnome_keyring/attribute_list'
module GnomeKeyring
load_class :Found
class Found
def attributes
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
GnomeKeyring::AttributeList.wrap(struct[:attributes])
end
def attributes=(value)
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
struct[:attributes] = GnomeKeyring::AttributeList.from(value)
end
end
end
## Instruction:
Remove old methods before redefining
## Code After:
require 'gir_ffi-gnome_keyring/attribute_list'
module GnomeKeyring
load_class :Found
class Found
remove_method :attributes
remove_method :attributes=
def attributes
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
GnomeKeyring::AttributeList.wrap(struct[:attributes])
end
def attributes=(value)
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
struct[:attributes] = GnomeKeyring::AttributeList.from(value)
end
end
end
| require 'gir_ffi-gnome_keyring/attribute_list'
module GnomeKeyring
load_class :Found
class Found
+ remove_method :attributes
+ remove_method :attributes=
+
def attributes
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
GnomeKeyring::AttributeList.wrap(struct[:attributes])
end
def attributes=(value)
struct = GnomeKeyring::Found::Struct.new(@struct.to_ptr)
struct[:attributes] = GnomeKeyring::AttributeList.from(value)
end
end
end | 3 | 0.176471 | 3 | 0 |
8a8c5c43a7ea9dc3f5178d7b24e50238e955ad2a | spec/unit/events_chain/next_transition_spec.rb | spec/unit/events_chain/next_transition_spec.rb |
require 'spec_helper'
RSpec.describe FiniteMachine::Event, '#next_transition' do
let(:object) { described_class }
subject(:event) { object.new(machine, name: :test) }
describe "matches transition by name" do
let(:machine) { double(:machine) }
it "finds matching transition" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: true)
event << transition_a
event << transition_b
expect(event.next_transition).to eq(transition_b)
end
end
describe "fails to find" do
let(:machine) { double(:machine) }
it "choses first available transition" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: false)
event << transition_a
event << transition_b
expect(event.next_transition).to eq(transition_a)
end
end
end
|
require 'spec_helper'
RSpec.describe FiniteMachine::EventsChain, '.next_transition' do
let(:machine) { spy(:machine) }
it "finds matching transition by name" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: true)
event = FiniteMachine::Event.new(:go, machine)
event << transition_a
event << transition_b
events_chain = described_class.new(machine)
events_chain.add(:go, event)
expect(events_chain.next_transition(:go)).to eq(transition_b)
end
it "choses first available transition" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: false)
event = FiniteMachine::Event.new(:go, machine)
event << transition_a
event << transition_b
events_chain = described_class.new(machine)
events_chain.add(:go, event)
expect(events_chain.next_transition(:go)).to eq(transition_a)
end
end
| Change tests to reflect changes. | Change tests to reflect changes.
| Ruby | mit | peter-murach/finite_machine | ruby | ## Code Before:
require 'spec_helper'
RSpec.describe FiniteMachine::Event, '#next_transition' do
let(:object) { described_class }
subject(:event) { object.new(machine, name: :test) }
describe "matches transition by name" do
let(:machine) { double(:machine) }
it "finds matching transition" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: true)
event << transition_a
event << transition_b
expect(event.next_transition).to eq(transition_b)
end
end
describe "fails to find" do
let(:machine) { double(:machine) }
it "choses first available transition" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: false)
event << transition_a
event << transition_b
expect(event.next_transition).to eq(transition_a)
end
end
end
## Instruction:
Change tests to reflect changes.
## Code After:
require 'spec_helper'
RSpec.describe FiniteMachine::EventsChain, '.next_transition' do
let(:machine) { spy(:machine) }
it "finds matching transition by name" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: true)
event = FiniteMachine::Event.new(:go, machine)
event << transition_a
event << transition_b
events_chain = described_class.new(machine)
events_chain.add(:go, event)
expect(events_chain.next_transition(:go)).to eq(transition_b)
end
it "choses first available transition" do
transition_a = double(:transition_a, current?: false)
transition_b = double(:transition_b, current?: false)
event = FiniteMachine::Event.new(:go, machine)
event << transition_a
event << transition_b
events_chain = described_class.new(machine)
events_chain.add(:go, event)
expect(events_chain.next_transition(:go)).to eq(transition_a)
end
end
|
require 'spec_helper'
- RSpec.describe FiniteMachine::Event, '#next_transition' do
? ^
+ RSpec.describe FiniteMachine::EventsChain, '.next_transition' do
? ++++++ ^
- let(:object) { described_class }
+ let(:machine) { spy(:machine) }
- subject(:event) { object.new(machine, name: :test) }
+ it "finds matching transition by name" do
+ transition_a = double(:transition_a, current?: false)
+ transition_b = double(:transition_b, current?: true)
+ event = FiniteMachine::Event.new(:go, machine)
+ event << transition_a
+ event << transition_b
- describe "matches transition by name" do
- let(:machine) { double(:machine) }
+ events_chain = described_class.new(machine)
+ events_chain.add(:go, event)
- it "finds matching transition" do
- transition_a = double(:transition_a, current?: false)
- transition_b = double(:transition_b, current?: true)
- event << transition_a
- event << transition_b
-
- expect(event.next_transition).to eq(transition_b)
? --
+ expect(events_chain.next_transition(:go)).to eq(transition_b)
? +++++++ +++++
- end
end
- describe "fails to find" do
- let(:machine) { double(:machine) }
+ it "choses first available transition" do
+ transition_a = double(:transition_a, current?: false)
+ transition_b = double(:transition_b, current?: false)
+ event = FiniteMachine::Event.new(:go, machine)
+ event << transition_a
+ event << transition_b
+ events_chain = described_class.new(machine)
+ events_chain.add(:go, event)
- it "choses first available transition" do
- transition_a = double(:transition_a, current?: false)
- transition_b = double(:transition_b, current?: false)
- event << transition_a
- event << transition_b
- expect(event.next_transition).to eq(transition_a)
? --
+ expect(events_chain.next_transition(:go)).to eq(transition_a)
? +++++++ +++++
- end
end
end | 42 | 1.235294 | 20 | 22 |
07a6d3c5a9b5006fec34bab289c421a097961be4 | kernel/device/pit.c | kernel/device/pit.c |
static void timer_interrupt_handler(struct interrupt_cpu_state *unused(r)) {
log(Log_Error, "tick");
scheduler_yield();
}
void timer_init(void) {
interrupt_register_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
void timer_set_phase(uint8_t hertz) {
uint8_t divisor = Timer_Magic_Number / hertz;
write_port(Timer_Command_Reg, RW_Oneshot_Square);
write_port(Timer_Chan_0, divisor & 0xff);
write_port(Timer_Chan_0, divisor >> 8);
pic_enable(Timer_IRQ_Number);
}
void timer_fini(void) {
interrupt_unregister_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
|
static void timer_interrupt_handler(struct interrupt_cpu_state *unused(r)) {
scheduler_yield();
}
void timer_init(void) {
interrupt_register_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
void timer_set_phase(uint8_t hertz) {
uint8_t divisor = Timer_Magic_Number / hertz;
write_port(Timer_Command_Reg, RW_Oneshot_Square);
write_port(Timer_Chan_0, divisor & 0xff);
write_port(Timer_Chan_0, divisor >> 8);
pic_enable(Timer_IRQ_Number);
}
void timer_fini(void) {
interrupt_unregister_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
| Remove annoying debug log message | Remove annoying debug log message
| C | mit | iankronquist/kernel-of-truth,iankronquist/kernel-of-truth,iankronquist/kernel-of-truth,iankronquist/kernel-of-truth,iankronquist/kernel-of-truth | c | ## Code Before:
static void timer_interrupt_handler(struct interrupt_cpu_state *unused(r)) {
log(Log_Error, "tick");
scheduler_yield();
}
void timer_init(void) {
interrupt_register_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
void timer_set_phase(uint8_t hertz) {
uint8_t divisor = Timer_Magic_Number / hertz;
write_port(Timer_Command_Reg, RW_Oneshot_Square);
write_port(Timer_Chan_0, divisor & 0xff);
write_port(Timer_Chan_0, divisor >> 8);
pic_enable(Timer_IRQ_Number);
}
void timer_fini(void) {
interrupt_unregister_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
## Instruction:
Remove annoying debug log message
## Code After:
static void timer_interrupt_handler(struct interrupt_cpu_state *unused(r)) {
scheduler_yield();
}
void timer_init(void) {
interrupt_register_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
void timer_set_phase(uint8_t hertz) {
uint8_t divisor = Timer_Magic_Number / hertz;
write_port(Timer_Command_Reg, RW_Oneshot_Square);
write_port(Timer_Chan_0, divisor & 0xff);
write_port(Timer_Chan_0, divisor >> 8);
pic_enable(Timer_IRQ_Number);
}
void timer_fini(void) {
interrupt_unregister_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
|
static void timer_interrupt_handler(struct interrupt_cpu_state *unused(r)) {
- log(Log_Error, "tick");
scheduler_yield();
}
void timer_init(void) {
interrupt_register_handler(Timer_IRQ_Number, timer_interrupt_handler);
}
void timer_set_phase(uint8_t hertz) {
uint8_t divisor = Timer_Magic_Number / hertz;
write_port(Timer_Command_Reg, RW_Oneshot_Square);
write_port(Timer_Chan_0, divisor & 0xff);
write_port(Timer_Chan_0, divisor >> 8);
pic_enable(Timer_IRQ_Number);
}
void timer_fini(void) {
interrupt_unregister_handler(Timer_IRQ_Number, timer_interrupt_handler);
} | 1 | 0.047619 | 0 | 1 |
af17ecc4b6a40d4a36f1492fcb374f33d97151dc | tests/library/CM/InputStream/AbstractTest.php | tests/library/CM/InputStream/AbstractTest.php | <?php
class CM_InputStream_AbstractTest extends CMTest_TestCase {
public function testRead() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('_read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('_read')->will($this->onConsecutiveCalls('foo', 'foo', 'bar'));
$input->expects($this->at(0))->method('_read')->with('Hint ');
$input->expects($this->at(1))->method('_read')->with(null);
$input->expects($this->at(2))->method('_read')->with(null);
/** @var $input CM_InputStream_Abstract */
$this->assertSame('foo', $input->read('Hint'));
$this->assertSame('foo', $input->read());
$this->assertSame('bar', $input->read(null, 'bar'));
}
public function testConfirm() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));
/** @var $input CM_InputStream_Abstract */
$this->assertTrue($input->confirm('Hint', 'default'));
$this->assertFalse($input->confirm('Hint', 'default'));
}
}
| <?php
class CM_InputStream_AbstractTest extends CMTest_TestCase {
public function testRead() {
$input = $this->mockClass('CM_InputStream_Abstract')->newInstance();
$readMethod = $input->mockMethod('_read')
->at(0, function ($hint) {
$this->assertSame('Hint ', $hint);
return 'foo';
})
->at(1, function ($hint) {
$this->assertNull($hint);
return '';
});
/** @var $input CM_InputStream_Abstract */
$this->assertSame('foo', $input->read('Hint'));
$this->assertSame('bar', $input->read(null, 'bar'));
$this->assertSame(2, $readMethod->getCallCount());
}
public function testConfirm() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));
/** @var $input CM_InputStream_Abstract */
$this->assertTrue($input->confirm('Hint', 'default'));
$this->assertFalse($input->confirm('Hint', 'default'));
}
}
| Adjust tests to use mocka | Adjust tests to use mocka
| PHP | mit | alexispeter/CM,alexispeter/CM,mariansollmann/CM,fvovan/CM,fauvel/CM,cargomedia/CM,vogdb/cm,alexispeter/CM,mariansollmann/CM,mariansollmann/CM,zazabe/cm,vogdb/cm,njam/CM,njam/CM,zazabe/cm,tomaszdurka/CM,vogdb/cm,tomaszdurka/CM,cargomedia/CM,njam/CM,fauvel/CM,fvovan/CM,mariansollmann/CM,fvovan/CM,tomaszdurka/CM,tomaszdurka/CM,fauvel/CM,tomaszdurka/CM,cargomedia/CM,fvovan/CM,fauvel/CM,alexispeter/CM,zazabe/cm,fauvel/CM,vogdb/cm,cargomedia/CM,njam/CM,njam/CM,vogdb/cm,zazabe/cm | php | ## Code Before:
<?php
class CM_InputStream_AbstractTest extends CMTest_TestCase {
public function testRead() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('_read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('_read')->will($this->onConsecutiveCalls('foo', 'foo', 'bar'));
$input->expects($this->at(0))->method('_read')->with('Hint ');
$input->expects($this->at(1))->method('_read')->with(null);
$input->expects($this->at(2))->method('_read')->with(null);
/** @var $input CM_InputStream_Abstract */
$this->assertSame('foo', $input->read('Hint'));
$this->assertSame('foo', $input->read());
$this->assertSame('bar', $input->read(null, 'bar'));
}
public function testConfirm() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));
/** @var $input CM_InputStream_Abstract */
$this->assertTrue($input->confirm('Hint', 'default'));
$this->assertFalse($input->confirm('Hint', 'default'));
}
}
## Instruction:
Adjust tests to use mocka
## Code After:
<?php
class CM_InputStream_AbstractTest extends CMTest_TestCase {
public function testRead() {
$input = $this->mockClass('CM_InputStream_Abstract')->newInstance();
$readMethod = $input->mockMethod('_read')
->at(0, function ($hint) {
$this->assertSame('Hint ', $hint);
return 'foo';
})
->at(1, function ($hint) {
$this->assertNull($hint);
return '';
});
/** @var $input CM_InputStream_Abstract */
$this->assertSame('foo', $input->read('Hint'));
$this->assertSame('bar', $input->read(null, 'bar'));
$this->assertSame(2, $readMethod->getCallCount());
}
public function testConfirm() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));
/** @var $input CM_InputStream_Abstract */
$this->assertTrue($input->confirm('Hint', 'default'));
$this->assertFalse($input->confirm('Hint', 'default'));
}
}
| <?php
class CM_InputStream_AbstractTest extends CMTest_TestCase {
public function testRead() {
- $input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('_read'))->getMockForAbstractClass();
- $input->expects($this->exactly(3))->method('_read')->will($this->onConsecutiveCalls('foo', 'foo', 'bar'));
- $input->expects($this->at(0))->method('_read')->with('Hint ');
- $input->expects($this->at(1))->method('_read')->with(null);
- $input->expects($this->at(2))->method('_read')->with(null);
-
+ $input = $this->mockClass('CM_InputStream_Abstract')->newInstance();
+ $readMethod = $input->mockMethod('_read')
+ ->at(0, function ($hint) {
+ $this->assertSame('Hint ', $hint);
+ return 'foo';
+ })
+ ->at(1, function ($hint) {
+ $this->assertNull($hint);
+ return '';
+ });
/** @var $input CM_InputStream_Abstract */
$this->assertSame('foo', $input->read('Hint'));
- $this->assertSame('foo', $input->read());
$this->assertSame('bar', $input->read(null, 'bar'));
+ $this->assertSame(2, $readMethod->getCallCount());
}
public function testConfirm() {
$input = $this->getMockBuilder('CM_InputStream_Abstract')->setMethods(array('read'))->getMockForAbstractClass();
$input->expects($this->exactly(3))->method('read')->with('Hint (y/n)', 'default')->will($this->onConsecutiveCalls('invalid value', 'y', 'n'));
/** @var $input CM_InputStream_Abstract */
$this->assertTrue($input->confirm('Hint', 'default'));
$this->assertFalse($input->confirm('Hint', 'default'));
}
} | 18 | 0.692308 | 11 | 7 |
6bef0dc50470bc71c15e0fb7c86f03e69c416e67 | scrapi/harvesters/datacite.py | scrapi/harvesters/datacite.py | '''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIHarvester):
short_name = 'datacite'
long_name = 'DataCite MDS'
url = 'http://oai.datacite.org/oai'
base_url = 'http://oai.datacite.org/oai'
property_list = ['date', 'identifier', 'setSpec', 'description']
timezone_granularity = True
@property
def schema(self):
return updated_schema(self._schema, {
"description": ("//dc:description/node()", get_second_description),
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_dois),
"objectUris": ('//dc:identifier/node()', oai_extract_dois)
}
})
def get_second_description(descriptions):
if descriptions:
if len(descriptions) > 1:
return descriptions[1]
else:
return descriptions[0]
return ''
| '''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIHarvester):
short_name = 'datacite'
long_name = 'DataCite MDS'
url = 'http://oai.datacite.org/oai'
base_url = 'http://oai.datacite.org/oai'
property_list = ['date', 'identifier', 'setSpec', 'description']
timezone_granularity = True
@property
def schema(self):
return updated_schema(self._schema, {
"description": ("//dc:description/node()", get_second_description),
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_dois),
"objectUris": ('//dc:identifier/node()', oai_extract_dois)
}
})
def get_second_description(descriptions):
''' In the DataCite OAI PMH api, there are often 2 descriptions: A type and
a longer kind of abstract. If there are two options, pick the second one which
is almost always the longer abstract
'''
if descriptions:
if len(descriptions) > 1:
return descriptions[1]
else:
return descriptions[0]
return ''
| Add docstring explaiing why to take the second description | Add docstring explaiing why to take the second description
| Python | apache-2.0 | CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,ostwald/scrapi,erinspace/scrapi,mehanig/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,alexgarciac/scrapi,felliott/scrapi,mehanig/scrapi,jeffreyliu3230/scrapi | python | ## Code Before:
'''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIHarvester):
short_name = 'datacite'
long_name = 'DataCite MDS'
url = 'http://oai.datacite.org/oai'
base_url = 'http://oai.datacite.org/oai'
property_list = ['date', 'identifier', 'setSpec', 'description']
timezone_granularity = True
@property
def schema(self):
return updated_schema(self._schema, {
"description": ("//dc:description/node()", get_second_description),
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_dois),
"objectUris": ('//dc:identifier/node()', oai_extract_dois)
}
})
def get_second_description(descriptions):
if descriptions:
if len(descriptions) > 1:
return descriptions[1]
else:
return descriptions[0]
return ''
## Instruction:
Add docstring explaiing why to take the second description
## Code After:
'''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIHarvester):
short_name = 'datacite'
long_name = 'DataCite MDS'
url = 'http://oai.datacite.org/oai'
base_url = 'http://oai.datacite.org/oai'
property_list = ['date', 'identifier', 'setSpec', 'description']
timezone_granularity = True
@property
def schema(self):
return updated_schema(self._schema, {
"description": ("//dc:description/node()", get_second_description),
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_dois),
"objectUris": ('//dc:identifier/node()', oai_extract_dois)
}
})
def get_second_description(descriptions):
''' In the DataCite OAI PMH api, there are often 2 descriptions: A type and
a longer kind of abstract. If there are two options, pick the second one which
is almost always the longer abstract
'''
if descriptions:
if len(descriptions) > 1:
return descriptions[1]
else:
return descriptions[0]
return ''
| '''
Harvester for the DataCite MDS for the SHARE project
Example API call: http://oai.datacite.org/oai?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
from scrapi.base.helpers import updated_schema, oai_extract_dois
class DataciteHarvester(OAIHarvester):
short_name = 'datacite'
long_name = 'DataCite MDS'
url = 'http://oai.datacite.org/oai'
base_url = 'http://oai.datacite.org/oai'
property_list = ['date', 'identifier', 'setSpec', 'description']
timezone_granularity = True
@property
def schema(self):
return updated_schema(self._schema, {
"description": ("//dc:description/node()", get_second_description),
"uris": {
"canonicalUri": ('//dc:identifier/node()', oai_extract_dois),
"objectUris": ('//dc:identifier/node()', oai_extract_dois)
}
})
def get_second_description(descriptions):
+ ''' In the DataCite OAI PMH api, there are often 2 descriptions: A type and
+ a longer kind of abstract. If there are two options, pick the second one which
+ is almost always the longer abstract
+ '''
if descriptions:
if len(descriptions) > 1:
return descriptions[1]
else:
return descriptions[0]
return '' | 4 | 0.105263 | 4 | 0 |
60ae97e2060cb01ac159acc6c0c7abdf866019b0 | clean_lxd.py | clean_lxd.py | from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_output([
'lxc', 'list', '--format', 'json'], env=env))
now = datetime.now()
for container in containers:
name = container['name']
if not name.startswith('juju-'):
continue
# This produces local time. lxc does not respect TZ=UTC.
created_at = datetime.strptime(
container['created_at'][:-6], '%Y-%m-%dT%H:%M:%S')
age = now - created_at
if age <= timedelta(hours=hours):
continue
yield name, age
def main():
parser = ArgumentParser('Delete old juju containers')
parser.add_argument('--dry-run', action='store_true',
help='Do not actually delete.')
parser.add_argument('--hours', type=int, default=1,
help='Number of hours a juju container may exist.')
args = parser.parse_args()
for container, age in list_old_juju_containers(args.hours):
print('deleting {} ({} old)'.format(container, age))
if args.dry_run:
continue
subprocess.check_call(('lxc', 'delete', '--verbose', '--force',
container))
if __name__ == '__main__':
sys.exit(main())
| from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
from dateutil import (
parser as date_parser,
tz,
)
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_output([
'lxc', 'list', '--format', 'json'], env=env))
now = datetime.now(tz.gettz('UTC'))
for container in containers:
name = container['name']
if not name.startswith('juju-'):
continue
created_at = date_parser.parse(container['created_at'])
age = now - created_at
if age <= timedelta(hours=hours):
continue
yield name, age
def main():
parser = ArgumentParser('Delete old juju containers')
parser.add_argument('--dry-run', action='store_true',
help='Do not actually delete.')
parser.add_argument('--hours', type=int, default=1,
help='Number of hours a juju container may exist.')
args = parser.parse_args()
for container, age in list_old_juju_containers(args.hours):
print('deleting {} ({} old)'.format(container, age))
if args.dry_run:
continue
subprocess.check_call(('lxc', 'delete', '--verbose', '--force',
container))
if __name__ == '__main__':
sys.exit(main())
| Use dateutil to calculate age of container. | Use dateutil to calculate age of container. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | python | ## Code Before:
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_output([
'lxc', 'list', '--format', 'json'], env=env))
now = datetime.now()
for container in containers:
name = container['name']
if not name.startswith('juju-'):
continue
# This produces local time. lxc does not respect TZ=UTC.
created_at = datetime.strptime(
container['created_at'][:-6], '%Y-%m-%dT%H:%M:%S')
age = now - created_at
if age <= timedelta(hours=hours):
continue
yield name, age
def main():
parser = ArgumentParser('Delete old juju containers')
parser.add_argument('--dry-run', action='store_true',
help='Do not actually delete.')
parser.add_argument('--hours', type=int, default=1,
help='Number of hours a juju container may exist.')
args = parser.parse_args()
for container, age in list_old_juju_containers(args.hours):
print('deleting {} ({} old)'.format(container, age))
if args.dry_run:
continue
subprocess.check_call(('lxc', 'delete', '--verbose', '--force',
container))
if __name__ == '__main__':
sys.exit(main())
## Instruction:
Use dateutil to calculate age of container.
## Code After:
from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
from dateutil import (
parser as date_parser,
tz,
)
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_output([
'lxc', 'list', '--format', 'json'], env=env))
now = datetime.now(tz.gettz('UTC'))
for container in containers:
name = container['name']
if not name.startswith('juju-'):
continue
created_at = date_parser.parse(container['created_at'])
age = now - created_at
if age <= timedelta(hours=hours):
continue
yield name, age
def main():
parser = ArgumentParser('Delete old juju containers')
parser.add_argument('--dry-run', action='store_true',
help='Do not actually delete.')
parser.add_argument('--hours', type=int, default=1,
help='Number of hours a juju container may exist.')
args = parser.parse_args()
for container, age in list_old_juju_containers(args.hours):
print('deleting {} ({} old)'.format(container, age))
if args.dry_run:
continue
subprocess.check_call(('lxc', 'delete', '--verbose', '--force',
container))
if __name__ == '__main__':
sys.exit(main())
| from __future__ import print_function
from argparse import ArgumentParser
from datetime import (
datetime,
timedelta,
)
import json
import os
import subprocess
import sys
+ from dateutil import (
+ parser as date_parser,
+ tz,
+ )
+
def list_old_juju_containers(hours):
env = dict(os.environ)
containers = json.loads(subprocess.check_output([
'lxc', 'list', '--format', 'json'], env=env))
- now = datetime.now()
+ now = datetime.now(tz.gettz('UTC'))
? ++++++++++++++ +
for container in containers:
name = container['name']
if not name.startswith('juju-'):
continue
+ created_at = date_parser.parse(container['created_at'])
- # This produces local time. lxc does not respect TZ=UTC.
- created_at = datetime.strptime(
- container['created_at'][:-6], '%Y-%m-%dT%H:%M:%S')
age = now - created_at
if age <= timedelta(hours=hours):
continue
yield name, age
def main():
parser = ArgumentParser('Delete old juju containers')
parser.add_argument('--dry-run', action='store_true',
help='Do not actually delete.')
parser.add_argument('--hours', type=int, default=1,
help='Number of hours a juju container may exist.')
args = parser.parse_args()
for container, age in list_old_juju_containers(args.hours):
print('deleting {} ({} old)'.format(container, age))
if args.dry_run:
continue
subprocess.check_call(('lxc', 'delete', '--verbose', '--force',
container))
if __name__ == '__main__':
sys.exit(main()) | 11 | 0.229167 | 7 | 4 |
fa18b9e9839faaef65c3366e88bc04cd99090a49 | test/test_harvestman.rb | test/test_harvestman.rb | require 'minitest/autorun'
require 'harvestman'
class TestHarvestman < MiniTest::Test
def test_namespace
assert Harvestman.is_a?(Module)
end
def test_single_page
result = {}
Harvestman.crawl "test/fixtures/index.html" do
result[:title] = css("title").inner_text
end
assert_equal result[:title], "Home Page"
end
def test_multiple_pages
results = []
Harvestman.crawl "test/fixtures/page*.html", (1..3), :plain do
r = {
:title => css("head title").inner_text,
:header => css("header div.title h1").inner_text,
:footer => css("footer span a").inner_text,
:list => []
}
css "div.main ul" do
r[:list] << css("li").inner_text
end
results << r
end
results.each_with_index do |r, i|
assert_equal(r[:title], "ex#{i+1}")
assert_equal(r[:header], "#{r[:title]}_header_h1")
assert_equal(r[:footer], "#{r[:title]}_footer_span_a")
#assert_equal(r[:list].count, 3)
end
end
end
| require 'minitest/autorun'
require 'harvestman'
class TestHarvestman < MiniTest::Test
def test_namespace
assert Harvestman.is_a?(Module)
end
def test_single_page
result = {}
Harvestman.crawl "test/fixtures/index.html" do
# grab the title
result[:title] = css("title").inner_text
# grab the text inside the a element that points to the second page
el = css("a[href*=page2]").first
result[:second_page_text] = el.inner_text
end
assert_equal result[:title], "Home Page"
assert_equal result[:second_page_text], "Second page"
end
def test_multiple_pages
results = []
Harvestman.crawl "test/fixtures/page*.html", (1..3), :plain do
r = {
:title => css("head title").inner_text,
:header => css("header div.title h1").inner_text,
:footer => css("footer span a").inner_text,
:list => []
}
css "div.main ul" do
r[:list] << css("li").inner_text
end
results << r
end
results.each_with_index do |r, i|
assert_equal(r[:title], "ex#{i+1}")
assert_equal(r[:header], "#{r[:title]}_header_h1")
assert_equal(r[:footer], "#{r[:title]}_footer_span_a")
#assert_equal(r[:list].count, 3)
end
end
end
| Add assertion to single page test | Add assertion to single page test
| Ruby | mit | mion/harvestman | ruby | ## Code Before:
require 'minitest/autorun'
require 'harvestman'
class TestHarvestman < MiniTest::Test
def test_namespace
assert Harvestman.is_a?(Module)
end
def test_single_page
result = {}
Harvestman.crawl "test/fixtures/index.html" do
result[:title] = css("title").inner_text
end
assert_equal result[:title], "Home Page"
end
def test_multiple_pages
results = []
Harvestman.crawl "test/fixtures/page*.html", (1..3), :plain do
r = {
:title => css("head title").inner_text,
:header => css("header div.title h1").inner_text,
:footer => css("footer span a").inner_text,
:list => []
}
css "div.main ul" do
r[:list] << css("li").inner_text
end
results << r
end
results.each_with_index do |r, i|
assert_equal(r[:title], "ex#{i+1}")
assert_equal(r[:header], "#{r[:title]}_header_h1")
assert_equal(r[:footer], "#{r[:title]}_footer_span_a")
#assert_equal(r[:list].count, 3)
end
end
end
## Instruction:
Add assertion to single page test
## Code After:
require 'minitest/autorun'
require 'harvestman'
class TestHarvestman < MiniTest::Test
def test_namespace
assert Harvestman.is_a?(Module)
end
def test_single_page
result = {}
Harvestman.crawl "test/fixtures/index.html" do
# grab the title
result[:title] = css("title").inner_text
# grab the text inside the a element that points to the second page
el = css("a[href*=page2]").first
result[:second_page_text] = el.inner_text
end
assert_equal result[:title], "Home Page"
assert_equal result[:second_page_text], "Second page"
end
def test_multiple_pages
results = []
Harvestman.crawl "test/fixtures/page*.html", (1..3), :plain do
r = {
:title => css("head title").inner_text,
:header => css("header div.title h1").inner_text,
:footer => css("footer span a").inner_text,
:list => []
}
css "div.main ul" do
r[:list] << css("li").inner_text
end
results << r
end
results.each_with_index do |r, i|
assert_equal(r[:title], "ex#{i+1}")
assert_equal(r[:header], "#{r[:title]}_header_h1")
assert_equal(r[:footer], "#{r[:title]}_footer_span_a")
#assert_equal(r[:list].count, 3)
end
end
end
| require 'minitest/autorun'
require 'harvestman'
class TestHarvestman < MiniTest::Test
def test_namespace
assert Harvestman.is_a?(Module)
end
def test_single_page
result = {}
Harvestman.crawl "test/fixtures/index.html" do
+ # grab the title
result[:title] = css("title").inner_text
+
+ # grab the text inside the a element that points to the second page
+ el = css("a[href*=page2]").first
+ result[:second_page_text] = el.inner_text
end
assert_equal result[:title], "Home Page"
+ assert_equal result[:second_page_text], "Second page"
end
def test_multiple_pages
results = []
Harvestman.crawl "test/fixtures/page*.html", (1..3), :plain do
r = {
:title => css("head title").inner_text,
:header => css("header div.title h1").inner_text,
:footer => css("footer span a").inner_text,
:list => []
}
css "div.main ul" do
r[:list] << css("li").inner_text
end
results << r
end
results.each_with_index do |r, i|
assert_equal(r[:title], "ex#{i+1}")
assert_equal(r[:header], "#{r[:title]}_header_h1")
assert_equal(r[:footer], "#{r[:title]}_footer_span_a")
#assert_equal(r[:list].count, 3)
end
end
end | 6 | 0.142857 | 6 | 0 |
75389529b95dbfe29a20d30e32197fb7e7e0f847 | .travis.yml | .travis.yml | language: python
python:
- "2.7"
dist: trusty
sudo: false
addons:
apt:
packages:
- libboost-all-dev
- libcairomm-1.0-dev
install:
- pip install --upgrade pip setuptools coverage sphinx coveralls
- pip install --upgrade matplotlib pycairo
# Temporary workaround for https://travis-ci.org/jacquev6/DrawTurksHead/builds/523061857#L1358
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then pip install urllib3==1.24.2; fi
script:
- coverage run --include=DrawTurksHead*,build/lib/DrawTurksHead* setup.py test
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then python setup.py build_sphinx --builder=doctest; fi
after_success:
- coveralls
deploy:
provider: pypi
user: jacquev6
password:
secure: IxZkM+jLb2kdI836H4h5dAXFu33D7J1FUuJw/Os752XqH0wBK5Xkk/LFz383Nw6auz6ppwjgmnvKdogH+KZwZ/9E5UaNb3cA0veJJDxwdl1c3iZP8z5i0Bk+KsnqJgaUnNuEIWO46Y9LB6VzazhOwE3Ftc+5kzrnEXUU7285iE8=
skip_upload_docs: true
on:
tags: true
repo: jacquev6/DrawTurksHead
python: 2.7
| language: python
python:
- "2.7"
dist: trusty
sudo: false
addons:
apt:
packages:
- libboost-all-dev
- libcairomm-1.0-dev
install:
- pip install --upgrade pip setuptools coverage sphinx coveralls
- pip install --upgrade matplotlib pycairo
script:
- coverage run --include=DrawTurksHead*,build/lib/DrawTurksHead* setup.py test
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then python setup.py build_sphinx --builder=doctest; fi
after_success:
- coveralls
deploy:
provider: pypi
user: jacquev6
password:
secure: IxZkM+jLb2kdI836H4h5dAXFu33D7J1FUuJw/Os752XqH0wBK5Xkk/LFz383Nw6auz6ppwjgmnvKdogH+KZwZ/9E5UaNb3cA0veJJDxwdl1c3iZP8z5i0Bk+KsnqJgaUnNuEIWO46Y9LB6VzazhOwE3Ftc+5kzrnEXUU7285iE8=
skip_upload_docs: true
on:
tags: true
repo: jacquev6/DrawTurksHead
python: 2.7
| Revert "(Try to) fix Travis CI" | Revert "(Try to) fix Travis CI"
This reverts commit 240f643842e535610f304d70554b73f06478bc96.
| YAML | mit | jacquev6/DrawTurksHead,jacquev6/DrawTurksHead,jacquev6/DrawTurksHead | yaml | ## Code Before:
language: python
python:
- "2.7"
dist: trusty
sudo: false
addons:
apt:
packages:
- libboost-all-dev
- libcairomm-1.0-dev
install:
- pip install --upgrade pip setuptools coverage sphinx coveralls
- pip install --upgrade matplotlib pycairo
# Temporary workaround for https://travis-ci.org/jacquev6/DrawTurksHead/builds/523061857#L1358
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then pip install urllib3==1.24.2; fi
script:
- coverage run --include=DrawTurksHead*,build/lib/DrawTurksHead* setup.py test
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then python setup.py build_sphinx --builder=doctest; fi
after_success:
- coveralls
deploy:
provider: pypi
user: jacquev6
password:
secure: IxZkM+jLb2kdI836H4h5dAXFu33D7J1FUuJw/Os752XqH0wBK5Xkk/LFz383Nw6auz6ppwjgmnvKdogH+KZwZ/9E5UaNb3cA0veJJDxwdl1c3iZP8z5i0Bk+KsnqJgaUnNuEIWO46Y9LB6VzazhOwE3Ftc+5kzrnEXUU7285iE8=
skip_upload_docs: true
on:
tags: true
repo: jacquev6/DrawTurksHead
python: 2.7
## Instruction:
Revert "(Try to) fix Travis CI"
This reverts commit 240f643842e535610f304d70554b73f06478bc96.
## Code After:
language: python
python:
- "2.7"
dist: trusty
sudo: false
addons:
apt:
packages:
- libboost-all-dev
- libcairomm-1.0-dev
install:
- pip install --upgrade pip setuptools coverage sphinx coveralls
- pip install --upgrade matplotlib pycairo
script:
- coverage run --include=DrawTurksHead*,build/lib/DrawTurksHead* setup.py test
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then python setup.py build_sphinx --builder=doctest; fi
after_success:
- coveralls
deploy:
provider: pypi
user: jacquev6
password:
secure: IxZkM+jLb2kdI836H4h5dAXFu33D7J1FUuJw/Os752XqH0wBK5Xkk/LFz383Nw6auz6ppwjgmnvKdogH+KZwZ/9E5UaNb3cA0veJJDxwdl1c3iZP8z5i0Bk+KsnqJgaUnNuEIWO46Y9LB6VzazhOwE3Ftc+5kzrnEXUU7285iE8=
skip_upload_docs: true
on:
tags: true
repo: jacquev6/DrawTurksHead
python: 2.7
| language: python
python:
- "2.7"
dist: trusty
sudo: false
addons:
apt:
packages:
- libboost-all-dev
- libcairomm-1.0-dev
install:
- pip install --upgrade pip setuptools coverage sphinx coveralls
- pip install --upgrade matplotlib pycairo
- # Temporary workaround for https://travis-ci.org/jacquev6/DrawTurksHead/builds/523061857#L1358
- - if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then pip install urllib3==1.24.2; fi
script:
- coverage run --include=DrawTurksHead*,build/lib/DrawTurksHead* setup.py test
- if [ "v$TRAVIS_PYTHON_VERSION" == "v2.7" ]; then python setup.py build_sphinx --builder=doctest; fi
after_success:
- coveralls
deploy:
provider: pypi
user: jacquev6
password:
secure: IxZkM+jLb2kdI836H4h5dAXFu33D7J1FUuJw/Os752XqH0wBK5Xkk/LFz383Nw6auz6ppwjgmnvKdogH+KZwZ/9E5UaNb3cA0veJJDxwdl1c3iZP8z5i0Bk+KsnqJgaUnNuEIWO46Y9LB6VzazhOwE3Ftc+5kzrnEXUU7285iE8=
skip_upload_docs: true
on:
tags: true
repo: jacquev6/DrawTurksHead
python: 2.7 | 2 | 0.066667 | 0 | 2 |
e1f53ff613de4ecd143840ff13aeea2ff51e9730 | .travis/scripts/apache-vhosts.sh | .travis/scripts/apache-vhosts.sh |
echo "ServerName localhost" | sudo tee /etc/apache2/conf-available/fqdn.conf
sudo a2enconf fqdn
echo "---> Starting $(tput bold ; tput setaf 2)virtual host creation$(tput sgr0)"
sudo cp -f .travis/apache2/www_simplemappr_local.conf /etc/apache2/sites-available/www_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/www_simplemappr_local.conf
sudo a2ensite www_simplemappr_local.conf
sudo cp -f .travis/apache2/img_simplemappr_local.conf /etc/apache2/sites-available/img_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/img_simplemappr_local.conf
sudo a2ensite img_simplemappr_local.conf
sudo a2enmod actions rewrite expires headers
sudo touch /var/run/php-fpm.sock
sudo chmod 777 /var/run/php-fpm.sock |
echo "---> Starting $(tput bold ; tput setaf 2)virtual host creation$(tput sgr0)"
sudo cp -f .travis/apache2/www_simplemappr_local.conf /etc/apache2/sites-available/www_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/www_simplemappr_local.conf
sudo a2ensite www_simplemappr_local.conf
sudo cp -f .travis/apache2/img_simplemappr_local.conf /etc/apache2/sites-available/img_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/img_simplemappr_local.conf
sudo a2ensite img_simplemappr_local.conf
sudo a2enmod actions rewrite expires headers
sudo touch /var/run/php-fpm.sock
sudo chmod 777 /var/run/php-fpm.sock | Comment out FQDN entry for Travis-CI | Comment out FQDN entry for Travis-CI
| Shell | mit | dshorthouse/SimpleMappr,dshorthouse/SimpleMappr,dshorthouse/SimpleMappr,dshorthouse/SimpleMappr,dshorthouse/SimpleMappr | shell | ## Code Before:
echo "ServerName localhost" | sudo tee /etc/apache2/conf-available/fqdn.conf
sudo a2enconf fqdn
echo "---> Starting $(tput bold ; tput setaf 2)virtual host creation$(tput sgr0)"
sudo cp -f .travis/apache2/www_simplemappr_local.conf /etc/apache2/sites-available/www_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/www_simplemappr_local.conf
sudo a2ensite www_simplemappr_local.conf
sudo cp -f .travis/apache2/img_simplemappr_local.conf /etc/apache2/sites-available/img_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/img_simplemappr_local.conf
sudo a2ensite img_simplemappr_local.conf
sudo a2enmod actions rewrite expires headers
sudo touch /var/run/php-fpm.sock
sudo chmod 777 /var/run/php-fpm.sock
## Instruction:
Comment out FQDN entry for Travis-CI
## Code After:
echo "---> Starting $(tput bold ; tput setaf 2)virtual host creation$(tput sgr0)"
sudo cp -f .travis/apache2/www_simplemappr_local.conf /etc/apache2/sites-available/www_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/www_simplemappr_local.conf
sudo a2ensite www_simplemappr_local.conf
sudo cp -f .travis/apache2/img_simplemappr_local.conf /etc/apache2/sites-available/img_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/img_simplemappr_local.conf
sudo a2ensite img_simplemappr_local.conf
sudo a2enmod actions rewrite expires headers
sudo touch /var/run/php-fpm.sock
sudo chmod 777 /var/run/php-fpm.sock | -
- echo "ServerName localhost" | sudo tee /etc/apache2/conf-available/fqdn.conf
- sudo a2enconf fqdn
echo "---> Starting $(tput bold ; tput setaf 2)virtual host creation$(tput sgr0)"
sudo cp -f .travis/apache2/www_simplemappr_local.conf /etc/apache2/sites-available/www_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/www_simplemappr_local.conf
sudo a2ensite www_simplemappr_local.conf
sudo cp -f .travis/apache2/img_simplemappr_local.conf /etc/apache2/sites-available/img_simplemappr_local.conf
sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/img_simplemappr_local.conf
sudo a2ensite img_simplemappr_local.conf
sudo a2enmod actions rewrite expires headers
sudo touch /var/run/php-fpm.sock
sudo chmod 777 /var/run/php-fpm.sock | 3 | 0.166667 | 0 | 3 |
832acff4bf420f04a231eb7da51a83194a467dc2 | src/angular-ladda.js | src/angular-ladda.js | /**!
* AngularJS Ladda directive
* @author Chungsub Kim <subicura@subicura.com>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
element.addClass('ladda-success');
setTimeout(function () {
element.removeClass('ladda-success');
}, 1000);
}
}
});
}
};
}
]
);
})();
| /**!
* AngularJS Ladda directive
* @author Chungsub Kim <subicura@subicura.com>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
element.append(' <span style="display:none" class="glyphicon glyphicon-remove"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
console.log(scope.btn_error);
var ladda_class='ladda-success';
if(scope.btn_error){
var ladda_class='ladda-remove';
}
element.addClass(ladda_class);
setTimeout(function () {
element.removeClass(ladda_class);
}, 2000);
}
}
});
}
};
}
]
);
})();
| Add glyphicon with remove icon in case of failure | Add glyphicon with remove icon in case of failure
| JavaScript | mit | jrlaforge/angular-ladda-success-failure | javascript | ## Code Before:
/**!
* AngularJS Ladda directive
* @author Chungsub Kim <subicura@subicura.com>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
element.addClass('ladda-success');
setTimeout(function () {
element.removeClass('ladda-success');
}, 1000);
}
}
});
}
};
}
]
);
})();
## Instruction:
Add glyphicon with remove icon in case of failure
## Code After:
/**!
* AngularJS Ladda directive
* @author Chungsub Kim <subicura@subicura.com>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
element.append(' <span style="display:none" class="glyphicon glyphicon-remove"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
console.log(scope.btn_error);
var ladda_class='ladda-success';
if(scope.btn_error){
var ladda_class='ladda-remove';
}
element.addClass(ladda_class);
setTimeout(function () {
element.removeClass(ladda_class);
}, 2000);
}
}
});
}
};
}
]
);
})();
| /**!
* AngularJS Ladda directive
* @author Chungsub Kim <subicura@subicura.com>
*/
/* global Ladda */
(function () {
'use strict';
angular.module('angular-ladda', []).directive(
'ladda',
[
'$compile',
function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.addClass('ladda-button');
element.append(' <span style="display:none" class="glyphicon glyphicon-ok"></span>');
+ element.append(' <span style="display:none" class="glyphicon glyphicon-remove"></span>');
if(angular.isUndefined(element.attr('data-style'))) {
element.attr('data-style', 'zoom-in');
}
var ladda = Ladda.create( element[0] );
$compile(angular.element(element.children()[0]).contents())(scope);
scope.$watch(attrs.ladda, function(loading) {
if(loading || angular.isNumber(loading)) {
if(!ladda.isLoading()) {
ladda.start();
}
if(angular.isNumber(loading)) {
ladda.setProgress(loading);
}
} else {
if (ladda.isLoading()) {
ladda.stop();
+ console.log(scope.btn_error);
+ var ladda_class='ladda-success';
+ if(scope.btn_error){
+ var ladda_class='ladda-remove';
+
+ }
- element.addClass('ladda-success');
? - ^^^ ^^ -
+ element.addClass(ladda_class);
? ^ ^^
setTimeout(function () {
- element.removeClass('ladda-success');
? - ^^^ ^^ -
+ element.removeClass(ladda_class);
? ^ ^^
- }, 1000);
? ^
+ }, 2000);
? ^
}
}
});
}
};
}
]
);
})(); | 13 | 0.265306 | 10 | 3 |
425cd4a88c66510914fb5b34ce980c785389f64d | vagrant/README.md | vagrant/README.md | * [Install VirtualBox](https://www.virtualbox.org/wiki/Downloads)
* [Install Vagrant](https://www.vagrantup.com/downloads.html)
## Create dev environment
### Change working directory to <vespa-source>/vagrant
cd <vespa-source>/vagrant
### Start and provision the environment
vagrant up
### Connect to machine via SSH
SSH agent forwarding is enabled to ensure easy interaction with GitHub inside the machine.
vagrant ssh
### Checkout vespa source inside machine
This is needed in order to compile and run tests fast on the local file system inside the machine.
git clone git@github.com:vespa-engine/vespa.git
## Build C++ modules
Please follow the instructions described [here](../README.md#build-c-modules).
| * [Install VirtualBox](https://www.virtualbox.org/wiki/Downloads)
* [Install Vagrant](https://www.vagrantup.com/downloads.html)
## Create dev environment
1. Change working directory to <vespa-source>/vagrant
cd <vespa-source>/vagrant
1. Install Vagrant VirtualBox Guest Additions plugin
This is required for mounting shared folders and get mouse pointer integration and seamless windows in the virtual CentOS desktop.
vagrant plugin install vagrant-vbguest
1. Start and provision the environment
vagrant up
1. Connect to machine via SSH
SSH agent forwarding is enabled to ensure easy interaction with GitHub inside the machine.
vagrant ssh
1. Checkout vespa source inside virtual machine
This is needed in order to compile and run tests fast on the local file system inside the virtual machine.
git clone git@github.com:vespa-engine/vespa.git
## Build C++ modules
Please follow the build instructions described [here](../README.md#build-c-modules).
Skip these steps if doing development with CLion.
## Build and Develop using CLion
CLion is installed as part of the environment and is recommended for C++ development.
1. Bootstrap C++ building
Go to <vespa-source> directory and execute:
./bootstrap-cpp.sh . .
1. Start CLion
Open a terminal inside the virtual CentOS desktop and run:
clion
1. Open the Vespa Project
Go to *File* -> *Open* and choose <vespa-source>/CMakeLists.txt.
1. Set compiler threads
Go to *File* -> *Settings* -> *Build, Execution, Deployment* -> *CMake*.
Under *Build Options* specify "-j 4" and click *Apply*.
1. Build all modules
Choose target **all_modules** from the set of build targets and click build.
| Add section on development using CLion. | Add section on development using CLion.
| Markdown | apache-2.0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | markdown | ## Code Before:
* [Install VirtualBox](https://www.virtualbox.org/wiki/Downloads)
* [Install Vagrant](https://www.vagrantup.com/downloads.html)
## Create dev environment
### Change working directory to <vespa-source>/vagrant
cd <vespa-source>/vagrant
### Start and provision the environment
vagrant up
### Connect to machine via SSH
SSH agent forwarding is enabled to ensure easy interaction with GitHub inside the machine.
vagrant ssh
### Checkout vespa source inside machine
This is needed in order to compile and run tests fast on the local file system inside the machine.
git clone git@github.com:vespa-engine/vespa.git
## Build C++ modules
Please follow the instructions described [here](../README.md#build-c-modules).
## Instruction:
Add section on development using CLion.
## Code After:
* [Install VirtualBox](https://www.virtualbox.org/wiki/Downloads)
* [Install Vagrant](https://www.vagrantup.com/downloads.html)
## Create dev environment
1. Change working directory to <vespa-source>/vagrant
cd <vespa-source>/vagrant
1. Install Vagrant VirtualBox Guest Additions plugin
This is required for mounting shared folders and get mouse pointer integration and seamless windows in the virtual CentOS desktop.
vagrant plugin install vagrant-vbguest
1. Start and provision the environment
vagrant up
1. Connect to machine via SSH
SSH agent forwarding is enabled to ensure easy interaction with GitHub inside the machine.
vagrant ssh
1. Checkout vespa source inside virtual machine
This is needed in order to compile and run tests fast on the local file system inside the virtual machine.
git clone git@github.com:vespa-engine/vespa.git
## Build C++ modules
Please follow the build instructions described [here](../README.md#build-c-modules).
Skip these steps if doing development with CLion.
## Build and Develop using CLion
CLion is installed as part of the environment and is recommended for C++ development.
1. Bootstrap C++ building
Go to <vespa-source> directory and execute:
./bootstrap-cpp.sh . .
1. Start CLion
Open a terminal inside the virtual CentOS desktop and run:
clion
1. Open the Vespa Project
Go to *File* -> *Open* and choose <vespa-source>/CMakeLists.txt.
1. Set compiler threads
Go to *File* -> *Settings* -> *Build, Execution, Deployment* -> *CMake*.
Under *Build Options* specify "-j 4" and click *Apply*.
1. Build all modules
Choose target **all_modules** from the set of build targets and click build.
| * [Install VirtualBox](https://www.virtualbox.org/wiki/Downloads)
* [Install Vagrant](https://www.vagrantup.com/downloads.html)
## Create dev environment
- ### Change working directory to <vespa-source>/vagrant
? ^^^
+ 1. Change working directory to <vespa-source>/vagrant
? ^^
cd <vespa-source>/vagrant
+ 1. Install Vagrant VirtualBox Guest Additions plugin
+ This is required for mounting shared folders and get mouse pointer integration and seamless windows in the virtual CentOS desktop.
+
+ vagrant plugin install vagrant-vbguest
+
- ### Start and provision the environment
? ^^^
+ 1. Start and provision the environment
? ^^
vagrant up
- ### Connect to machine via SSH
? ^^^
+ 1. Connect to machine via SSH
? ^^
SSH agent forwarding is enabled to ensure easy interaction with GitHub inside the machine.
vagrant ssh
- ### Checkout vespa source inside machine
? ^^^
+ 1. Checkout vespa source inside virtual machine
? ^^ ++++++++
- This is needed in order to compile and run tests fast on the local file system inside the machine.
+ This is needed in order to compile and run tests fast on the local file system inside the virtual machine.
? ++++++++
git clone git@github.com:vespa-engine/vespa.git
## Build C++ modules
- Please follow the instructions described [here](../README.md#build-c-modules).
+ Please follow the build instructions described [here](../README.md#build-c-modules).
? ++++++
+ Skip these steps if doing development with CLion.
+
+
+ ## Build and Develop using CLion
+ CLion is installed as part of the environment and is recommended for C++ development.
+
+ 1. Bootstrap C++ building
+ Go to <vespa-source> directory and execute:
+
+ ./bootstrap-cpp.sh . .
+
+ 1. Start CLion
+ Open a terminal inside the virtual CentOS desktop and run:
+
+ clion
+
+ 1. Open the Vespa Project
+ Go to *File* -> *Open* and choose <vespa-source>/CMakeLists.txt.
+
+ 1. Set compiler threads
+ Go to *File* -> *Settings* -> *Build, Execution, Deployment* -> *CMake*.
+ Under *Build Options* specify "-j 4" and click *Apply*.
+
+ 1. Build all modules
+ Choose target **all_modules** from the set of build targets and click build. | 42 | 1.75 | 36 | 6 |
023b06a76ac544447c626eae70d7484377f7538b | .github/workflows/deploy.yml | .github/workflows/deploy.yml | name: Deploy
on:
push:
tags:
- '*'
jobs:
deploy:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Push to GitHub Packages
uses: docker/build-push-action@v1
with:
username: ${{ github.actor }}
password: ${{ github.token }}
registry: docker.pkg.github.com
repository: theleagueof/fontship/fontship
tag_with_ref: true
| name: Deploy
on:
push:
tags:
- '*'
jobs:
deploy:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Push to GitHub Packages
uses: docker/build-push-action@v1
with:
username: ${{ github.actor }}
password: ${{ github.token }}
registry: docker.pkg.github.com
repository: sile-typesetter/casile/casile
tag_with_ref: true
| Correct name of GH package repository where releases are pushed | fix(ci): Correct name of GH package repository where releases are pushed
| YAML | agpl-3.0 | alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile | yaml | ## Code Before:
name: Deploy
on:
push:
tags:
- '*'
jobs:
deploy:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Push to GitHub Packages
uses: docker/build-push-action@v1
with:
username: ${{ github.actor }}
password: ${{ github.token }}
registry: docker.pkg.github.com
repository: theleagueof/fontship/fontship
tag_with_ref: true
## Instruction:
fix(ci): Correct name of GH package repository where releases are pushed
## Code After:
name: Deploy
on:
push:
tags:
- '*'
jobs:
deploy:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Push to GitHub Packages
uses: docker/build-push-action@v1
with:
username: ${{ github.actor }}
password: ${{ github.token }}
registry: docker.pkg.github.com
repository: sile-typesetter/casile/casile
tag_with_ref: true
| name: Deploy
on:
push:
tags:
- '*'
jobs:
deploy:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Push to GitHub Packages
uses: docker/build-push-action@v1
with:
username: ${{ github.actor }}
password: ${{ github.token }}
registry: docker.pkg.github.com
- repository: theleagueof/fontship/fontship
+ repository: sile-typesetter/casile/casile
tag_with_ref: true | 2 | 0.086957 | 1 | 1 |
35216fde00419bfabae2421c3cadd943945ea86c | source/workerlib.ts | source/workerlib.ts | export { SurfaceWorker } from "./workers/target/surfaceworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; | export { SurfaceWorker } from "./workers/target/surfaceworker";
export { ParticlesWorker } from "./workers/target/particlesworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; | Add particles worker code to worker lib | Add particles worker code to worker lib
| TypeScript | apache-2.0 | Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d | typescript | ## Code Before:
export { SurfaceWorker } from "./workers/target/surfaceworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config";
## Instruction:
Add particles worker code to worker lib
## Code After:
export { SurfaceWorker } from "./workers/target/surfaceworker";
export { ParticlesWorker } from "./workers/target/particlesworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; | export { SurfaceWorker } from "./workers/target/surfaceworker";
+ export { ParticlesWorker } from "./workers/target/particlesworker";
export { WorkerEvent } from "./workers/workerevent";
export { Config } from "./app/config"; | 1 | 0.333333 | 1 | 0 |
76b680bf7eb667b0f88a9c2ab10958d5ecb3c81c | lib/my_mongoid/document.rb | lib/my_mongoid/document.rb | module MyMongoid
def self.models
@models ||= []
end
module Document
module ClassMethods
def is_mongoid_model?
true
end
end
def self.included(klass)
MyMongoid.models << klass
klass.extend ClassMethods
end
end
end
| module MyMongoid
def self.models
@models ||= []
end
module Document
attr_reader :attributes
module ClassMethods
def is_mongoid_model?
true
end
end
def self.included(klass)
MyMongoid.models << klass
klass.extend ClassMethods
end
def initialize(attrs = nil)
raise ArgumentError unless attrs.is_a?(Hash)
@attributes = attrs
end
def read_attribute(key)
@attributes[key]
end
def write_attribute(key, value)
@attributes[key] = valus
end
def new_record?
true
end
end
end
| Implement attributes for a model | Implement attributes for a model
| Ruby | mit | luin/my_mongoid | ruby | ## Code Before:
module MyMongoid
def self.models
@models ||= []
end
module Document
module ClassMethods
def is_mongoid_model?
true
end
end
def self.included(klass)
MyMongoid.models << klass
klass.extend ClassMethods
end
end
end
## Instruction:
Implement attributes for a model
## Code After:
module MyMongoid
def self.models
@models ||= []
end
module Document
attr_reader :attributes
module ClassMethods
def is_mongoid_model?
true
end
end
def self.included(klass)
MyMongoid.models << klass
klass.extend ClassMethods
end
def initialize(attrs = nil)
raise ArgumentError unless attrs.is_a?(Hash)
@attributes = attrs
end
def read_attribute(key)
@attributes[key]
end
def write_attribute(key, value)
@attributes[key] = valus
end
def new_record?
true
end
end
end
| module MyMongoid
def self.models
@models ||= []
end
module Document
-
+ attr_reader :attributes
module ClassMethods
def is_mongoid_model?
true
end
end
def self.included(klass)
MyMongoid.models << klass
klass.extend ClassMethods
end
+ def initialize(attrs = nil)
+ raise ArgumentError unless attrs.is_a?(Hash)
+ @attributes = attrs
+ end
+
+ def read_attribute(key)
+ @attributes[key]
+ end
+
+ def write_attribute(key, value)
+ @attributes[key] = valus
+ end
+
+ def new_record?
+ true
+ end
+
end
end | 19 | 0.95 | 18 | 1 |
b331d9b5cb1ce6122737a4b1136f0ae83449d282 | lib/info-iframe-receiver.js | lib/info-iframe-receiver.js | 'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
function InfoReceiverIframe(transUrl, baseUrl) {
var self = this;
EventEmitter.call(this);
this.ir = new InfoAjax(baseUrl, XHRLocalObject);
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe;
| 'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
function InfoReceiverIframe(transUrl) {
var self = this;
EventEmitter.call(this);
this.ir = new InfoAjax(transUrl, XHRLocalObject);
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe;
| Fix iframe info receiver using wrong url | Fix iframe info receiver using wrong url
| JavaScript | mit | modulexcite/sockjs-client,the1sky/sockjs-client,bulentv/sockjs-client,webmechanicx/sockjs-client,vkorehov/sockjs-client,jmptrader/sockjs-client,JohnKossa/sockjs-client,sockjs/sockjs-client,woosoobar/sockjs-client,bulentv/sockjs-client,jmptrader/sockjs-client,reergymerej/sockjs-client,arusakov/sockjs-client,modulexcite/sockjs-client,sockjs/sockjs-client,sockjs/sockjs-client,woosoobar/sockjs-client,JohnKossa/sockjs-client,the1sky/sockjs-client,webmechanicx/sockjs-client,reergymerej/sockjs-client,vkorehov/sockjs-client,arusakov/sockjs-client | javascript | ## Code Before:
'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
function InfoReceiverIframe(transUrl, baseUrl) {
var self = this;
EventEmitter.call(this);
this.ir = new InfoAjax(baseUrl, XHRLocalObject);
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe;
## Instruction:
Fix iframe info receiver using wrong url
## Code After:
'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
function InfoReceiverIframe(transUrl) {
var self = this;
EventEmitter.call(this);
this.ir = new InfoAjax(transUrl, XHRLocalObject);
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe;
| 'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
- function InfoReceiverIframe(transUrl, baseUrl) {
? ---------
+ function InfoReceiverIframe(transUrl) {
var self = this;
EventEmitter.call(this);
- this.ir = new InfoAjax(baseUrl, XHRLocalObject);
? ^ -
+ this.ir = new InfoAjax(transUrl, XHRLocalObject);
? ^^ +
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe; | 4 | 0.121212 | 2 | 2 |
f06692ee3d6a12f13d425e7b0aaa88ea8cd6ac94 | rhinoInSpring/src/java/org/szegedi/spring/web/jsflow/ScriptSelectionStrategy.java | rhinoInSpring/src/java/org/szegedi/spring/web/jsflow/ScriptSelectionStrategy.java | package org.szegedi.spring.web.jsflow;
import javax.servlet.http.HttpServletRequest;
/**
* Interface for objects that select a script for a particular initial HTTP
* request.
* @author Attila Szegedi
* @version $Id: $
*/
public interface ScriptSelectionStrategy
{
/**
* Returns the pathname of the script that should run for a particular
* initial HTTP request.
* @param request the HTTP request
* @return the path of the script. null can be returned to indicate that
* this strategy is unable to select a script (i.e. because some data is
* missing in the request). The controller will respond to this by sending
* back a HTTP 400 "Bad Request" status.
*/
public String getScriptPath(HttpServletRequest request);
}
| package org.szegedi.spring.web.jsflow;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.ModelAndViewDefiningException;
/**
* Interface for objects that select a script for a particular initial HTTP
* request.
* @author Attila Szegedi
* @version $Id: $
*/
public interface ScriptSelectionStrategy
{
/**
* Returns the pathname of the script that should run for a particular
* initial HTTP request.
* @param request the HTTP request
* @return the path of the script. null can be returned to indicate that
* this strategy is unable to select a script (i.e. because some data is
* missing in the request). The controller will respond to this by sending
* back a HTTP 400 "Bad Request" status. Alternatively, the strategy can
* throw an instance of {@link ModelAndViewDefiningException}.
*/
public String getScriptPath(HttpServletRequest request)
throws ModelAndViewDefiningException;
}
| Allow it to throw a ModelAndViewDefiningException | Allow it to throw a ModelAndViewDefiningException | Java | apache-2.0 | szegedi/spring-web-jsflow,szegedi/spring-web-jsflow,szegedi/spring-web-jsflow | java | ## Code Before:
package org.szegedi.spring.web.jsflow;
import javax.servlet.http.HttpServletRequest;
/**
* Interface for objects that select a script for a particular initial HTTP
* request.
* @author Attila Szegedi
* @version $Id: $
*/
public interface ScriptSelectionStrategy
{
/**
* Returns the pathname of the script that should run for a particular
* initial HTTP request.
* @param request the HTTP request
* @return the path of the script. null can be returned to indicate that
* this strategy is unable to select a script (i.e. because some data is
* missing in the request). The controller will respond to this by sending
* back a HTTP 400 "Bad Request" status.
*/
public String getScriptPath(HttpServletRequest request);
}
## Instruction:
Allow it to throw a ModelAndViewDefiningException
## Code After:
package org.szegedi.spring.web.jsflow;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.ModelAndViewDefiningException;
/**
* Interface for objects that select a script for a particular initial HTTP
* request.
* @author Attila Szegedi
* @version $Id: $
*/
public interface ScriptSelectionStrategy
{
/**
* Returns the pathname of the script that should run for a particular
* initial HTTP request.
* @param request the HTTP request
* @return the path of the script. null can be returned to indicate that
* this strategy is unable to select a script (i.e. because some data is
* missing in the request). The controller will respond to this by sending
* back a HTTP 400 "Bad Request" status. Alternatively, the strategy can
* throw an instance of {@link ModelAndViewDefiningException}.
*/
public String getScriptPath(HttpServletRequest request)
throws ModelAndViewDefiningException;
}
| package org.szegedi.spring.web.jsflow;
import javax.servlet.http.HttpServletRequest;
+
+ import org.springframework.web.servlet.ModelAndViewDefiningException;
/**
* Interface for objects that select a script for a particular initial HTTP
* request.
* @author Attila Szegedi
* @version $Id: $
*/
public interface ScriptSelectionStrategy
{
/**
* Returns the pathname of the script that should run for a particular
* initial HTTP request.
* @param request the HTTP request
* @return the path of the script. null can be returned to indicate that
* this strategy is unable to select a script (i.e. because some data is
* missing in the request). The controller will respond to this by sending
- * back a HTTP 400 "Bad Request" status.
+ * back a HTTP 400 "Bad Request" status. Alternatively, the strategy can
+ * throw an instance of {@link ModelAndViewDefiningException}.
*/
- public String getScriptPath(HttpServletRequest request);
? ^
+ public String getScriptPath(HttpServletRequest request)
? ^
+ throws ModelAndViewDefiningException;
} | 8 | 0.347826 | 6 | 2 |
7494aab0684929f50c23a1a8b0de301880eb2c50 | cmake/bld.bat | cmake/bld.bat | @echo off
copy /y bin\*.dll %PREFIX%\ > nul
copy /y bin\cmake.exe %PREFIX%\ > nul
xcopy share %PREFIX%\share /E /I > nul
| @echo off
xcopy bin %LIBRARY_BIN%\bin /E /I > nul
xcopy share %LIBRARY_BIN%\share /E /I > nul
| Put bin and share in same place | Put bin and share in same place
Fixes CMAKE_ROOT issue
| Batchfile | bsd-3-clause | menpo/conda-recipes,menpo/conda-recipes | batchfile | ## Code Before:
@echo off
copy /y bin\*.dll %PREFIX%\ > nul
copy /y bin\cmake.exe %PREFIX%\ > nul
xcopy share %PREFIX%\share /E /I > nul
## Instruction:
Put bin and share in same place
Fixes CMAKE_ROOT issue
## Code After:
@echo off
xcopy bin %LIBRARY_BIN%\bin /E /I > nul
xcopy share %LIBRARY_BIN%\share /E /I > nul
| @echo off
+ xcopy bin %LIBRARY_BIN%\bin /E /I > nul
- copy /y bin\*.dll %PREFIX%\ > nul
- copy /y bin\cmake.exe %PREFIX%\ > nul
- xcopy share %PREFIX%\share /E /I > nul
? ^ ^^ ^
+ xcopy share %LIBRARY_BIN%\share /E /I > nul
? ^^^ ^^^^^ ^
| 5 | 1.25 | 2 | 3 |
22465e0ae238a6584a8549796f4dfbae21db73dc | ooni/tests/test_geoip.py | ooni/tests/test_geoip.py | import os
from twisted.internet import defer
from twisted.trial import unittest
from ooni.tests import is_internet_connected
from ooni.settings import config
from ooni import geoip
class TestGeoIP(unittest.TestCase):
def test_ip_to_location(self):
location = geoip.IPToLocation('8.8.8.8')
assert 'countrycode' in location
assert 'asn' in location
assert 'city' in location
@defer.inlineCallbacks
def test_probe_ip(self):
if not is_internet_connected():
self.skipTest(
"You must be connected to the internet to run this test"
)
probe_ip = geoip.ProbeIP()
res = yield probe_ip.lookup()
assert len(res.split('.')) == 4
|
from twisted.internet import defer
from twisted.trial import unittest
from ooni.tests import is_internet_connected
from ooni import geoip
class TestGeoIP(unittest.TestCase):
def test_ip_to_location(self):
location = geoip.IPToLocation('8.8.8.8')
assert 'countrycode' in location
assert 'asn' in location
assert 'city' in location
@defer.inlineCallbacks
def test_probe_ip(self):
if not is_internet_connected():
self.skipTest(
"You must be connected to the internet to run this test"
)
probe_ip = geoip.ProbeIP()
res = yield probe_ip.lookup()
assert len(res.split('.')) == 4
def test_geoip_database_version(self):
version = geoip.database_version()
assert 'GeoIP' in version.keys()
assert 'GeoIPASNum' in version.keys()
assert 'GeoLiteCity' in version.keys()
assert len(version['GeoIP']['sha256']) == 64
assert isinstance(version['GeoIP']['timestamp'], float)
assert len(version['GeoIPASNum']['sha256']) == 64
assert isinstance(version['GeoIPASNum']['timestamp'], float)
| Add unittests for geoip database version | Add unittests for geoip database version
| Python | bsd-2-clause | juga0/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe | python | ## Code Before:
import os
from twisted.internet import defer
from twisted.trial import unittest
from ooni.tests import is_internet_connected
from ooni.settings import config
from ooni import geoip
class TestGeoIP(unittest.TestCase):
def test_ip_to_location(self):
location = geoip.IPToLocation('8.8.8.8')
assert 'countrycode' in location
assert 'asn' in location
assert 'city' in location
@defer.inlineCallbacks
def test_probe_ip(self):
if not is_internet_connected():
self.skipTest(
"You must be connected to the internet to run this test"
)
probe_ip = geoip.ProbeIP()
res = yield probe_ip.lookup()
assert len(res.split('.')) == 4
## Instruction:
Add unittests for geoip database version
## Code After:
from twisted.internet import defer
from twisted.trial import unittest
from ooni.tests import is_internet_connected
from ooni import geoip
class TestGeoIP(unittest.TestCase):
def test_ip_to_location(self):
location = geoip.IPToLocation('8.8.8.8')
assert 'countrycode' in location
assert 'asn' in location
assert 'city' in location
@defer.inlineCallbacks
def test_probe_ip(self):
if not is_internet_connected():
self.skipTest(
"You must be connected to the internet to run this test"
)
probe_ip = geoip.ProbeIP()
res = yield probe_ip.lookup()
assert len(res.split('.')) == 4
def test_geoip_database_version(self):
version = geoip.database_version()
assert 'GeoIP' in version.keys()
assert 'GeoIPASNum' in version.keys()
assert 'GeoLiteCity' in version.keys()
assert len(version['GeoIP']['sha256']) == 64
assert isinstance(version['GeoIP']['timestamp'], float)
assert len(version['GeoIPASNum']['sha256']) == 64
assert isinstance(version['GeoIPASNum']['timestamp'], float)
| - import os
from twisted.internet import defer
from twisted.trial import unittest
from ooni.tests import is_internet_connected
- from ooni.settings import config
from ooni import geoip
class TestGeoIP(unittest.TestCase):
def test_ip_to_location(self):
location = geoip.IPToLocation('8.8.8.8')
assert 'countrycode' in location
assert 'asn' in location
assert 'city' in location
@defer.inlineCallbacks
def test_probe_ip(self):
if not is_internet_connected():
self.skipTest(
"You must be connected to the internet to run this test"
)
probe_ip = geoip.ProbeIP()
res = yield probe_ip.lookup()
assert len(res.split('.')) == 4
+
+ def test_geoip_database_version(self):
+ version = geoip.database_version()
+ assert 'GeoIP' in version.keys()
+ assert 'GeoIPASNum' in version.keys()
+ assert 'GeoLiteCity' in version.keys()
+
+ assert len(version['GeoIP']['sha256']) == 64
+ assert isinstance(version['GeoIP']['timestamp'], float)
+ assert len(version['GeoIPASNum']['sha256']) == 64
+ assert isinstance(version['GeoIPASNum']['timestamp'], float) | 13 | 0.5 | 11 | 2 |
012e4e0cc7a3539906222e35fdd44359c475ca28 | README.md | README.md | This library is responsible for handling all of the routing.
See godoc.org/github.com/AutoRoute/node for the full documentation
And see https://docs.google.com/document/d/1NBk83bfj6MLgDD6USidSethKqV6-cNa-ZO4odNrdcCc/edit?usp=sharing for a high level description of the project.
See https://docs.google.com/presentation/d/1b_Gl22d4e5oD5Z_4RMf-gjaCdrmqAzev6fSIaG7-uHw/edit?usp=sharing for a presentation about the project.
| This library is responsible for handling all of the routing.
See godoc.org/github.com/AutoRoute/node for the full documentation
And see https://docs.google.com/document/d/1NBk83bfj6MLgDD6USidSethKqV6-cNa-ZO4odNrdcCc/edit?usp=sharing for a high level description of the project.
See https://docs.google.com/presentation/d/1b_Gl22d4e5oD5Z_4RMf-gjaCdrmqAzev6fSIaG7-uHw/edit?usp=sharing for a presentation about the project.
If you'd like to just spin up a node and start playing around with it, you can either run build and run them locally, or just use docker.
```
sudo docker run -p 30000:34321 --name p1 c00w/autoroute:latest
sudo docker run -p 30001:34321 --name p2 --link=p1:p1 c00w/autoroute:latest -connect p1:34321
```
| Add some more information to the readme | Add some more information to the readme
| Markdown | mit | AutoRoute/node,AutoRoute/node | markdown | ## Code Before:
This library is responsible for handling all of the routing.
See godoc.org/github.com/AutoRoute/node for the full documentation
And see https://docs.google.com/document/d/1NBk83bfj6MLgDD6USidSethKqV6-cNa-ZO4odNrdcCc/edit?usp=sharing for a high level description of the project.
See https://docs.google.com/presentation/d/1b_Gl22d4e5oD5Z_4RMf-gjaCdrmqAzev6fSIaG7-uHw/edit?usp=sharing for a presentation about the project.
## Instruction:
Add some more information to the readme
## Code After:
This library is responsible for handling all of the routing.
See godoc.org/github.com/AutoRoute/node for the full documentation
And see https://docs.google.com/document/d/1NBk83bfj6MLgDD6USidSethKqV6-cNa-ZO4odNrdcCc/edit?usp=sharing for a high level description of the project.
See https://docs.google.com/presentation/d/1b_Gl22d4e5oD5Z_4RMf-gjaCdrmqAzev6fSIaG7-uHw/edit?usp=sharing for a presentation about the project.
If you'd like to just spin up a node and start playing around with it, you can either run build and run them locally, or just use docker.
```
sudo docker run -p 30000:34321 --name p1 c00w/autoroute:latest
sudo docker run -p 30001:34321 --name p2 --link=p1:p1 c00w/autoroute:latest -connect p1:34321
```
| This library is responsible for handling all of the routing.
See godoc.org/github.com/AutoRoute/node for the full documentation
And see https://docs.google.com/document/d/1NBk83bfj6MLgDD6USidSethKqV6-cNa-ZO4odNrdcCc/edit?usp=sharing for a high level description of the project.
See https://docs.google.com/presentation/d/1b_Gl22d4e5oD5Z_4RMf-gjaCdrmqAzev6fSIaG7-uHw/edit?usp=sharing for a presentation about the project.
+
+
+ If you'd like to just spin up a node and start playing around with it, you can either run build and run them locally, or just use docker.
+
+ ```
+ sudo docker run -p 30000:34321 --name p1 c00w/autoroute:latest
+ sudo docker run -p 30001:34321 --name p2 --link=p1:p1 c00w/autoroute:latest -connect p1:34321
+ ``` | 8 | 1.333333 | 8 | 0 |
101a7bf84e36c4232c6b7128a67481f45123f6cb | CONTRIBUTING.md | CONTRIBUTING.md | Like with Clojure and most other big OSS projects, we have a [Contributor's Agreement](https://docs.google.com/a/kodowa.com/forms/d/1ME_PT6qLKUcALUEz1h1yerLF7vP_Rnohpb9RvMLDALg/viewform) that you have to agree to before we can merge. It's a simple adaptation of Twitter's own Contributor's Agreement and just says that by signing this you can't take the code back from us or sue us into oblivion for using it later. | See [Light Table's CONTRIBUTING.md](https://github.com/LightTable/LightTable/blob/master/CONTRIBUTING.md).
| Remove CA and link to main contributing | Remove CA and link to main contributing
| Markdown | mit | robinhoud/Javascript,kenny-evitt/Javascript,WOBvx/Javascript,LightTable/Javascript | markdown | ## Code Before:
Like with Clojure and most other big OSS projects, we have a [Contributor's Agreement](https://docs.google.com/a/kodowa.com/forms/d/1ME_PT6qLKUcALUEz1h1yerLF7vP_Rnohpb9RvMLDALg/viewform) that you have to agree to before we can merge. It's a simple adaptation of Twitter's own Contributor's Agreement and just says that by signing this you can't take the code back from us or sue us into oblivion for using it later.
## Instruction:
Remove CA and link to main contributing
## Code After:
See [Light Table's CONTRIBUTING.md](https://github.com/LightTable/LightTable/blob/master/CONTRIBUTING.md).
| - Like with Clojure and most other big OSS projects, we have a [Contributor's Agreement](https://docs.google.com/a/kodowa.com/forms/d/1ME_PT6qLKUcALUEz1h1yerLF7vP_Rnohpb9RvMLDALg/viewform) that you have to agree to before we can merge. It's a simple adaptation of Twitter's own Contributor's Agreement and just says that by signing this you can't take the code back from us or sue us into oblivion for using it later.
+ See [Light Table's CONTRIBUTING.md](https://github.com/LightTable/LightTable/blob/master/CONTRIBUTING.md). | 2 | 2 | 1 | 1 |
378a5a0b8884f1ec59597dde63c6f95144e8e94c | lib/util.js | lib/util.js | var utilConfig = {
regexList : [
{
type : "attr",
attrName : "ng-model",
match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "attr",
attrName : "ng-repeat",
match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "cssAttr",
match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi
},
{
type : "attr",
attrName : "ng-bind",
match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi
}
],
getRegexList : function(){
return this.regexList;
}
};
module.exports = utilConfig; | var utilConfig = {
regexList : [
{
type : "attr",
attrName : "ng-model",
match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "attr",
attrName : "ng-repeat",
match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "cssAttr",
match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi
},
{
type : "attr",
attrName : "ng-bind",
match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type: "attr",
attrName : "ng-repeat",
match: /[b|B]y\.repeater\(\s*['|"](.*? in .*?)['|"]\s*\)/gi
}
],
getRegexList : function(){
return this.regexList;
}
};
module.exports = utilConfig; | Add regex rule for repeater selector | Add regex rule for repeater selector
| JavaScript | mit | cor03rock/gulp-protractor-qa,ramonvictor/gulp-protractor-qa,ramonvictor/gulp-protractor-qa | javascript | ## Code Before:
var utilConfig = {
regexList : [
{
type : "attr",
attrName : "ng-model",
match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "attr",
attrName : "ng-repeat",
match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "cssAttr",
match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi
},
{
type : "attr",
attrName : "ng-bind",
match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi
}
],
getRegexList : function(){
return this.regexList;
}
};
module.exports = utilConfig;
## Instruction:
Add regex rule for repeater selector
## Code After:
var utilConfig = {
regexList : [
{
type : "attr",
attrName : "ng-model",
match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "attr",
attrName : "ng-repeat",
match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "cssAttr",
match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi
},
{
type : "attr",
attrName : "ng-bind",
match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type: "attr",
attrName : "ng-repeat",
match: /[b|B]y\.repeater\(\s*['|"](.*? in .*?)['|"]\s*\)/gi
}
],
getRegexList : function(){
return this.regexList;
}
};
module.exports = utilConfig; | var utilConfig = {
regexList : [
{
type : "attr",
attrName : "ng-model",
match : /[b|B]y\.model\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "attr",
attrName : "ng-repeat",
match : /[b|B]y\.repeater\(\s*['|"](.*?)['|"]\s*\)/gi
},
{
type : "cssAttr",
match : /[b|B]y\.css\(['|"]\[(.+=.+)\]['|"]\)/gi
},
{
type : "attr",
attrName : "ng-bind",
match : /[b|B]y\.binding\(\s*['|"](.*?)['|"]\s*\)/gi
- }
+ },
? +
+ {
+ type: "attr",
+ attrName : "ng-repeat",
+ match: /[b|B]y\.repeater\(\s*['|"](.*? in .*?)['|"]\s*\)/gi
+ }
],
getRegexList : function(){
return this.regexList;
}
};
module.exports = utilConfig; | 7 | 0.241379 | 6 | 1 |
a3770819ebc9c90af06f2c18a8919c25f63709a2 | Tests/Request/MetadatasRequestTest.php | Tests/Request/MetadatasRequestTest.php | <?php
namespace Navitia\Component\Test\Request;
use Navitia\Component\Request\MetadatasRequest;
/**
* Description of MetadatasRequestTest
*
* @author rndiaye
*/
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
/**
* Test for addToPathFilter
*
* @expectedException Navitia\Component\Exception\BadParametersException
*/
public function testAddToPathFilter()
{
$service = new MetadatasRequest();
$service->addtoPathFilter('bar', 'foo');
}
}
| <?php
namespace Navitia\Tests\Request;
use Navitia\Component\Request\MetadatasRequest;
/**
* Description of MetadatasRequestTest
*
* @author rndiaye
*/
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
/**
* Test for addToPathFilter
*
* @expectedException Navitia\Component\Exception\BadParametersException
*/
public function testAddToPathFilter()
{
$service = new MetadatasRequest();
$service->addtoPathFilter('bar', 'foo');
}
}
| Fix namespace for test class | Fix namespace for test class
| PHP | mit | CanalTP/NavitiaComponent | php | ## Code Before:
<?php
namespace Navitia\Component\Test\Request;
use Navitia\Component\Request\MetadatasRequest;
/**
* Description of MetadatasRequestTest
*
* @author rndiaye
*/
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
/**
* Test for addToPathFilter
*
* @expectedException Navitia\Component\Exception\BadParametersException
*/
public function testAddToPathFilter()
{
$service = new MetadatasRequest();
$service->addtoPathFilter('bar', 'foo');
}
}
## Instruction:
Fix namespace for test class
## Code After:
<?php
namespace Navitia\Tests\Request;
use Navitia\Component\Request\MetadatasRequest;
/**
* Description of MetadatasRequestTest
*
* @author rndiaye
*/
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
/**
* Test for addToPathFilter
*
* @expectedException Navitia\Component\Exception\BadParametersException
*/
public function testAddToPathFilter()
{
$service = new MetadatasRequest();
$service->addtoPathFilter('bar', 'foo');
}
}
| <?php
- namespace Navitia\Component\Test\Request;
? ----------
+ namespace Navitia\Tests\Request;
? +
use Navitia\Component\Request\MetadatasRequest;
/**
* Description of MetadatasRequestTest
*
* @author rndiaye
*/
class MetadatasRequestTest extends \PHPUnit_Framework_TestCase
{
/**
* Test for addToPathFilter
*
* @expectedException Navitia\Component\Exception\BadParametersException
*/
public function testAddToPathFilter()
{
$service = new MetadatasRequest();
$service->addtoPathFilter('bar', 'foo');
}
} | 2 | 0.083333 | 1 | 1 |
1b55bfd142856c2d2fcda4a21a23df323e4ad5b1 | addon/pods/components/frost-tabs/component.js | addon/pods/components/frost-tabs/component.js | import Ember from 'ember'
import layout from './template'
import PropTypesMixin, { PropTypes } from 'ember-prop-types'
import uuid from 'ember-simple-uuid'
export default Ember.Component.extend(PropTypesMixin, {
// == Component properties ==================================================
layout: layout,
classNames: ['frost-tabs'],
// == State properties ======================================================
propTypes: {
tabs: PropTypes.array.isRequired,
selectedTab: PropTypes.string,
targetOutlet: PropTypes.string,
onChange: PropTypes.func,
hook: PropTypes.string
},
getDefaultProps () {
return {
targetOutlet: `frost-tab-content-${uuid()}`
}
}
})
| import Ember from 'ember'
import layout from './template'
import PropTypesMixin, { PropTypes } from 'ember-prop-types'
import uuid from 'ember-simple-uuid'
export default Ember.Component.extend(PropTypesMixin, {
// == Component properties ==================================================
layout: layout,
classNames: ['frost-tabs'],
// == State properties ======================================================
propTypes: {
tabs: PropTypes.array.isRequired,
selectedTab: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
hook: PropTypes.string.isRequired,
targetOutlet: PropTypes.string
},
getDefaultProps () {
return {
targetOutlet: `frost-tab-content-${uuid()}`
}
}
})
| Put some property as required. | Put some property as required.
| JavaScript | mit | ciena-frost/ember-frost-tabs,ciena-frost/ember-frost-tabs,ciena-frost/ember-frost-tabs | javascript | ## Code Before:
import Ember from 'ember'
import layout from './template'
import PropTypesMixin, { PropTypes } from 'ember-prop-types'
import uuid from 'ember-simple-uuid'
export default Ember.Component.extend(PropTypesMixin, {
// == Component properties ==================================================
layout: layout,
classNames: ['frost-tabs'],
// == State properties ======================================================
propTypes: {
tabs: PropTypes.array.isRequired,
selectedTab: PropTypes.string,
targetOutlet: PropTypes.string,
onChange: PropTypes.func,
hook: PropTypes.string
},
getDefaultProps () {
return {
targetOutlet: `frost-tab-content-${uuid()}`
}
}
})
## Instruction:
Put some property as required.
## Code After:
import Ember from 'ember'
import layout from './template'
import PropTypesMixin, { PropTypes } from 'ember-prop-types'
import uuid from 'ember-simple-uuid'
export default Ember.Component.extend(PropTypesMixin, {
// == Component properties ==================================================
layout: layout,
classNames: ['frost-tabs'],
// == State properties ======================================================
propTypes: {
tabs: PropTypes.array.isRequired,
selectedTab: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
hook: PropTypes.string.isRequired,
targetOutlet: PropTypes.string
},
getDefaultProps () {
return {
targetOutlet: `frost-tab-content-${uuid()}`
}
}
})
| import Ember from 'ember'
import layout from './template'
import PropTypesMixin, { PropTypes } from 'ember-prop-types'
import uuid from 'ember-simple-uuid'
export default Ember.Component.extend(PropTypesMixin, {
// == Component properties ==================================================
layout: layout,
classNames: ['frost-tabs'],
// == State properties ======================================================
propTypes: {
tabs: PropTypes.array.isRequired,
- selectedTab: PropTypes.string,
+ selectedTab: PropTypes.string.isRequired,
? +++++++++++
+ onChange: PropTypes.func.isRequired,
+ hook: PropTypes.string.isRequired,
- targetOutlet: PropTypes.string,
? -
+ targetOutlet: PropTypes.string
- onChange: PropTypes.func,
- hook: PropTypes.string
},
getDefaultProps () {
return {
targetOutlet: `frost-tab-content-${uuid()}`
}
}
}) | 8 | 0.296296 | 4 | 4 |
b9afea9a10c09cb81f55866602b89162adcb1600 | circle.yml | circle.yml | machine:
xcode:
version: 9.1
environment:
LANG: en_US.UTF-8
dependencies:
override:
- echo "Skipping CocoaPods Specs install."
test:
override:
- set -o pipefail
- xcodebuild test -scheme 'RxAlamofireTests' -workspace 'RxAlamofire/RxAlamofire.xcworkspace' -sdk iphonesimulator -destination "name=iPhone 8" | xcpretty -c | machine:
xcode:
version: 9.1
environment:
LANG: en_US.UTF-8
dependencies:
override:
- echo "Skipping CocoaPods Specs install."
test:
override:
- set -o pipefail
- xcodebuild test -scheme 'RxAlamofireTests' -workspace 'RxAlamofire/RxAlamofire.xcworkspace' -sdk iphonesimulator -destination "name=iPhone 8" | xcpretty -c
deployment:
release:
tag: /[0-9]+(\.[0-9]+)*/
commands:
- pod setup
- rm ~/.cocoapods/config.yaml # This hack is needed since CircleCI forces --verbose
- pod trunk push --skip-tests --allow-warnings
| Add auto-deploy mechanism for new tags in Circle CI | Add auto-deploy mechanism for new tags in Circle CI | YAML | mit | RxSwiftCommunity/RxAlamofire,RxSwiftCommunity/RxAlamofire,bontoJR/RxAlamofire,bontoJR/RxAlamofire,RxSwiftCommunity/RxAlamofire | yaml | ## Code Before:
machine:
xcode:
version: 9.1
environment:
LANG: en_US.UTF-8
dependencies:
override:
- echo "Skipping CocoaPods Specs install."
test:
override:
- set -o pipefail
- xcodebuild test -scheme 'RxAlamofireTests' -workspace 'RxAlamofire/RxAlamofire.xcworkspace' -sdk iphonesimulator -destination "name=iPhone 8" | xcpretty -c
## Instruction:
Add auto-deploy mechanism for new tags in Circle CI
## Code After:
machine:
xcode:
version: 9.1
environment:
LANG: en_US.UTF-8
dependencies:
override:
- echo "Skipping CocoaPods Specs install."
test:
override:
- set -o pipefail
- xcodebuild test -scheme 'RxAlamofireTests' -workspace 'RxAlamofire/RxAlamofire.xcworkspace' -sdk iphonesimulator -destination "name=iPhone 8" | xcpretty -c
deployment:
release:
tag: /[0-9]+(\.[0-9]+)*/
commands:
- pod setup
- rm ~/.cocoapods/config.yaml # This hack is needed since CircleCI forces --verbose
- pod trunk push --skip-tests --allow-warnings
| machine:
xcode:
version: 9.1
environment:
LANG: en_US.UTF-8
dependencies:
override:
- echo "Skipping CocoaPods Specs install."
test:
override:
- set -o pipefail
- xcodebuild test -scheme 'RxAlamofireTests' -workspace 'RxAlamofire/RxAlamofire.xcworkspace' -sdk iphonesimulator -destination "name=iPhone 8" | xcpretty -c
+
+ deployment:
+ release:
+ tag: /[0-9]+(\.[0-9]+)*/
+ commands:
+ - pod setup
+ - rm ~/.cocoapods/config.yaml # This hack is needed since CircleCI forces --verbose
+ - pod trunk push --skip-tests --allow-warnings | 8 | 0.571429 | 8 | 0 |
f1bed47f6c1005f35ff153ef8d9d4ebbbd74cccf | src/org/adaptlab/chpir/android/survey/QuestionFragments/FreeResponseQuestionFragment.java | src/org/adaptlab/chpir/android/survey/QuestionFragments/FreeResponseQuestionFragment.java | package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
beforeAddViewHook(mFreeText);
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
} | package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
beforeAddViewHook(mFreeText);
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
} | Fix delete free response subclass response deletion on rotation bug | Fix delete free response subclass response deletion on rotation bug
| Java | mit | mnipper/AndroidSurvey,mnipper/AndroidSurvey,mnipper/AndroidSurvey,DukeMobileTech/AndroidSurvey | java | ## Code Before:
package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
beforeAddViewHook(mFreeText);
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
}
## Instruction:
Fix delete free response subclass response deletion on rotation bug
## Code After:
package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
beforeAddViewHook(mFreeText);
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
} | package org.adaptlab.chpir.android.survey.QuestionFragments;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
public class FreeResponseQuestionFragment extends QuestionFragment {
private String mText = "";
private EditText mFreeText;
// This is used to restrict allowed input in subclasses.
protected void beforeAddViewHook(EditText editText) {
}
@Override
public void createQuestionComponent(ViewGroup questionComponent) {
mFreeText = new EditText(getActivity());
+ beforeAddViewHook(mFreeText);
mFreeText.setHint(R.string.free_response_edittext);
mFreeText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mText = s.toString();
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
- beforeAddViewHook(mFreeText);
questionComponent.addView(mFreeText);
}
@Override
protected String serialize() {
return mText;
}
@Override
protected void deserialize(String responseText) {
mFreeText.setText(responseText);
}
} | 2 | 0.040816 | 1 | 1 |
027c98b410653974594b5195c97446631cf85a94 | web/locales/ast/cross-locale.ftl | web/locales/ast/cross-locale.ftl |
contribute = Collaborar
get-involved-button = Andechar
get-involved-email =
.label = Corréu
get-involved-opt-in = Sí, unviáime correos. Prestaríame tar informáu tocante al progresu d'esta llingua en Common Voice.
get-involved-submit = Unviar
get-involved-privacy-info = Prometémoste que vamos remanar la to información con curiáu. Llei más na nuesa <privacyLink>Noticia de privacidá</privacyLink>
get-involved-success-title = Rexistréstite con ésitu pa collaborar en { $language }. Gracies.
get-involved-success-text = Vamos ponenos en contautu contigo con más información a midida que tea disponible.
get-involved-return-to-languages = Volver a Llingües
|
contribute = Collaborar
get-involved-button = Andechar
get-involved-title = Collaboración en { $lang }
get-involved-form-title = Rexistráime pa los anovamientos de { $lang }:
get-involved-email =
.label = Corréu
get-involved-opt-in = Sí, unviáime correos. Prestaríame tar informáu tocante al progresu d'esta llingua en Common Voice.
get-involved-submit = Unviar
get-involved-stayintouch = En Mozilla tamos construyendo una comunidá alredor de la teunoloxía per voz. Prestaríanos siguir en contautu con anovamientos, fontes de datos nueves y oyer más tocante a cómo uses estos datos.
get-involved-privacy-info = Prometémoste que vamos remanar la to información con curiáu. Llei más na nuesa <privacyLink>Noticia de privacidá</privacyLink>
get-involved-success-title = Rexistréstite con ésitu pa collaborar en { $language }. Gracies.
get-involved-success-text = Vamos ponenos en contautu contigo con más información a midida que tea disponible.
get-involved-return-to-languages = Volver a Llingües
| Update Asturian (ast) localization of Common Voice | Pontoon: Update Asturian (ast) localization of Common Voice
Localization authors:
- Enol <enolp@softastur.org>
| FreeMarker | mpl-2.0 | gozer/voice-web,common-voice/common-voice,gozer/voice-web,gozer/voice-web,common-voice/common-voice,gozer/voice-web,gozer/voice-web,common-voice/common-voice,common-voice/common-voice,gozer/voice-web,gozer/voice-web | freemarker | ## Code Before:
contribute = Collaborar
get-involved-button = Andechar
get-involved-email =
.label = Corréu
get-involved-opt-in = Sí, unviáime correos. Prestaríame tar informáu tocante al progresu d'esta llingua en Common Voice.
get-involved-submit = Unviar
get-involved-privacy-info = Prometémoste que vamos remanar la to información con curiáu. Llei más na nuesa <privacyLink>Noticia de privacidá</privacyLink>
get-involved-success-title = Rexistréstite con ésitu pa collaborar en { $language }. Gracies.
get-involved-success-text = Vamos ponenos en contautu contigo con más información a midida que tea disponible.
get-involved-return-to-languages = Volver a Llingües
## Instruction:
Pontoon: Update Asturian (ast) localization of Common Voice
Localization authors:
- Enol <enolp@softastur.org>
## Code After:
contribute = Collaborar
get-involved-button = Andechar
get-involved-title = Collaboración en { $lang }
get-involved-form-title = Rexistráime pa los anovamientos de { $lang }:
get-involved-email =
.label = Corréu
get-involved-opt-in = Sí, unviáime correos. Prestaríame tar informáu tocante al progresu d'esta llingua en Common Voice.
get-involved-submit = Unviar
get-involved-stayintouch = En Mozilla tamos construyendo una comunidá alredor de la teunoloxía per voz. Prestaríanos siguir en contautu con anovamientos, fontes de datos nueves y oyer más tocante a cómo uses estos datos.
get-involved-privacy-info = Prometémoste que vamos remanar la to información con curiáu. Llei más na nuesa <privacyLink>Noticia de privacidá</privacyLink>
get-involved-success-title = Rexistréstite con ésitu pa collaborar en { $language }. Gracies.
get-involved-success-text = Vamos ponenos en contautu contigo con más información a midida que tea disponible.
get-involved-return-to-languages = Volver a Llingües
|
contribute = Collaborar
get-involved-button = Andechar
+ get-involved-title = Collaboración en { $lang }
+ get-involved-form-title = Rexistráime pa los anovamientos de { $lang }:
get-involved-email =
.label = Corréu
get-involved-opt-in = Sí, unviáime correos. Prestaríame tar informáu tocante al progresu d'esta llingua en Common Voice.
get-involved-submit = Unviar
+ get-involved-stayintouch = En Mozilla tamos construyendo una comunidá alredor de la teunoloxía per voz. Prestaríanos siguir en contautu con anovamientos, fontes de datos nueves y oyer más tocante a cómo uses estos datos.
get-involved-privacy-info = Prometémoste que vamos remanar la to información con curiáu. Llei más na nuesa <privacyLink>Noticia de privacidá</privacyLink>
get-involved-success-title = Rexistréstite con ésitu pa collaborar en { $language }. Gracies.
get-involved-success-text = Vamos ponenos en contautu contigo con más información a midida que tea disponible.
get-involved-return-to-languages = Volver a Llingües | 3 | 0.272727 | 3 | 0 |
d82d543c83e8f03be8b7ec62f456b896e9a7f854 | source/known_limits.rst | source/known_limits.rst | .. _known-limits:
Known limits
============
The following is a catalogue of known limits in ASDF |version|.
Tree
----
While there is no hard limit on the size of the Tree, in most
practical implementations it will need to be read entirely into main
memory in order to interpret it, particularly to support forward
references. This imposes a practical limit on its size relative to
the system memory on the machine. It is not recommended to store
large data sets in the tree directly, instead it should reference
blocks.
Literal integer values in the Tree
----------------------------------
Different programming languages deal with numbers differently. For
example, Python has arbitrary-length integers, while Javascript stores
all numbers as 64-bit double-precision floats. It may be possible to
write long integers from Python into the Tree, and upon reading in
Javascript have undefined loss of information when reading those
values back in.
Therefore, for practical reasons, integer literals in the Tree must
be at most 52-bits.
As of version **1.3.0** of the standard, arbitrary precision integers are
supported using `integer <schemas/stsci.edu/asdf/core/integer-1.0.0.html>`_.
Like all tags, use of this type requires library support.
Blocks
------
The maximum size of a block header is 65536 bytes.
Since the size of the block is stored in a 64-bit unsigned integer,
the largest possible block size is around 18 exabytes. It is likely
that other limitations on file size, such as an operating system's
filesystem limitations, will be met long before that.
| .. _known-limits:
Known limits
============
The following is a catalogue of known limits in ASDF |version|.
Tree
----
While there is no hard limit on the size of the Tree, in most
practical implementations it will need to be read entirely into main
memory in order to interpret it, particularly to support forward
references. This imposes a practical limit on its size relative to
the system memory on the machine. It is not recommended to store
large data sets in the tree directly, instead it should reference
blocks.
Literal integer values in the Tree
----------------------------------
Different programming languages deal with numbers differently. For
example, Python has arbitrary-length integers, while Javascript stores
all numbers as 64-bit double-precision floats. It may be possible to
write long integers from Python into the Tree, and upon reading in
Javascript have undefined loss of information when reading those
values back in.
Therefore, for practical reasons, integer literals in the Tree must
be at most 52-bits.
As of version **1.3.0** of the standard, arbitrary precision integers are
supported using :ref:`integer <core/integer-1.0.0>`. Like all tags, use of
this type requires library support.
Blocks
------
The maximum size of a block header is 65536 bytes.
Since the size of the block is stored in a 64-bit unsigned integer,
the largest possible block size is around 18 exabytes. It is likely
that other limitations on file size, such as an operating system's
filesystem limitations, will be met long before that.
| Fix reference to integer schema in Known Limits | Fix reference to integer schema in Known Limits
| reStructuredText | bsd-3-clause | spacetelescope/asdf-standard | restructuredtext | ## Code Before:
.. _known-limits:
Known limits
============
The following is a catalogue of known limits in ASDF |version|.
Tree
----
While there is no hard limit on the size of the Tree, in most
practical implementations it will need to be read entirely into main
memory in order to interpret it, particularly to support forward
references. This imposes a practical limit on its size relative to
the system memory on the machine. It is not recommended to store
large data sets in the tree directly, instead it should reference
blocks.
Literal integer values in the Tree
----------------------------------
Different programming languages deal with numbers differently. For
example, Python has arbitrary-length integers, while Javascript stores
all numbers as 64-bit double-precision floats. It may be possible to
write long integers from Python into the Tree, and upon reading in
Javascript have undefined loss of information when reading those
values back in.
Therefore, for practical reasons, integer literals in the Tree must
be at most 52-bits.
As of version **1.3.0** of the standard, arbitrary precision integers are
supported using `integer <schemas/stsci.edu/asdf/core/integer-1.0.0.html>`_.
Like all tags, use of this type requires library support.
Blocks
------
The maximum size of a block header is 65536 bytes.
Since the size of the block is stored in a 64-bit unsigned integer,
the largest possible block size is around 18 exabytes. It is likely
that other limitations on file size, such as an operating system's
filesystem limitations, will be met long before that.
## Instruction:
Fix reference to integer schema in Known Limits
## Code After:
.. _known-limits:
Known limits
============
The following is a catalogue of known limits in ASDF |version|.
Tree
----
While there is no hard limit on the size of the Tree, in most
practical implementations it will need to be read entirely into main
memory in order to interpret it, particularly to support forward
references. This imposes a practical limit on its size relative to
the system memory on the machine. It is not recommended to store
large data sets in the tree directly, instead it should reference
blocks.
Literal integer values in the Tree
----------------------------------
Different programming languages deal with numbers differently. For
example, Python has arbitrary-length integers, while Javascript stores
all numbers as 64-bit double-precision floats. It may be possible to
write long integers from Python into the Tree, and upon reading in
Javascript have undefined loss of information when reading those
values back in.
Therefore, for practical reasons, integer literals in the Tree must
be at most 52-bits.
As of version **1.3.0** of the standard, arbitrary precision integers are
supported using :ref:`integer <core/integer-1.0.0>`. Like all tags, use of
this type requires library support.
Blocks
------
The maximum size of a block header is 65536 bytes.
Since the size of the block is stored in a 64-bit unsigned integer,
the largest possible block size is around 18 exabytes. It is likely
that other limitations on file size, such as an operating system's
filesystem limitations, will be met long before that.
| .. _known-limits:
Known limits
============
The following is a catalogue of known limits in ASDF |version|.
Tree
----
While there is no hard limit on the size of the Tree, in most
practical implementations it will need to be read entirely into main
memory in order to interpret it, particularly to support forward
references. This imposes a practical limit on its size relative to
the system memory on the machine. It is not recommended to store
large data sets in the tree directly, instead it should reference
blocks.
Literal integer values in the Tree
----------------------------------
Different programming languages deal with numbers differently. For
example, Python has arbitrary-length integers, while Javascript stores
all numbers as 64-bit double-precision floats. It may be possible to
write long integers from Python into the Tree, and upon reading in
Javascript have undefined loss of information when reading those
values back in.
Therefore, for practical reasons, integer literals in the Tree must
be at most 52-bits.
As of version **1.3.0** of the standard, arbitrary precision integers are
- supported using `integer <schemas/stsci.edu/asdf/core/integer-1.0.0.html>`_.
+ supported using :ref:`integer <core/integer-1.0.0>`. Like all tags, use of
- Like all tags, use of this type requires library support.
? ----------------------
+ this type requires library support.
Blocks
------
The maximum size of a block header is 65536 bytes.
Since the size of the block is stored in a 64-bit unsigned integer,
the largest possible block size is around 18 exabytes. It is likely
that other limitations on file size, such as an operating system's
filesystem limitations, will be met long before that. | 4 | 0.090909 | 2 | 2 |
346f6887e9088e3803c3d48dfaeca89757619443 | sites/all/themes/book/custom.tpl.php | sites/all/themes/book/custom.tpl.php | <?php
include("mustache.php");
/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
- $application_data: contains the application data required to render the
views such as:
- the current user name
- the list of all available languages with ISO2 code, language name, and
a selected attribute in the selected language
- the ISO2 code of the selected language
- the server name
- the API url
- the Sparql endpoint url
- $theme_path: contains the full path of the theme root folder.
- $mustache_data: contains all the data required to render the views
- $mustache_template: contains the name of the template to load
- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path);
| <?php
require_once("mustache.php");
/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
- $application_data: contains the application data required to render the
views such as:
- the current user name
- the list of all available languages with ISO2 code, language name, and
a selected attribute in the selected language
- the ISO2 code of the selected language
- the server name
- the API url
- the Sparql endpoint url
- $theme_path: contains the full path of the theme root folder.
- $mustache_data: contains all the data required to render the views
- $mustache_template: contains the name of the template to load
- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path);
| Fix bug in login form | Fix bug in login form
| PHP | mit | landportal/drupal,landportal/drupal | php | ## Code Before:
<?php
include("mustache.php");
/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
- $application_data: contains the application data required to render the
views such as:
- the current user name
- the list of all available languages with ISO2 code, language name, and
a selected attribute in the selected language
- the ISO2 code of the selected language
- the server name
- the API url
- the Sparql endpoint url
- $theme_path: contains the full path of the theme root folder.
- $mustache_data: contains all the data required to render the views
- $mustache_template: contains the name of the template to load
- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path);
## Instruction:
Fix bug in login form
## Code After:
<?php
require_once("mustache.php");
/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
- $application_data: contains the application data required to render the
views such as:
- the current user name
- the list of all available languages with ISO2 code, language name, and
a selected attribute in the selected language
- the ISO2 code of the selected language
- the server name
- the API url
- the Sparql endpoint url
- $theme_path: contains the full path of the theme root folder.
- $mustache_data: contains all the data required to render the views
- $mustache_template: contains the name of the template to load
- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path);
| <?php
- include("mustache.php");
? ---
+ require_once("mustache.php");
? ++++ ++++
/*
At this point THE FOLLOWING VARIABLES ARE AVAILABLE (from template.php::book_preprocess)
- $application_data: contains the application data required to render the
views such as:
- the current user name
- the list of all available languages with ISO2 code, language name, and
a selected attribute in the selected language
- the ISO2 code of the selected language
- the server name
- the API url
- the Sparql endpoint url
- $theme_path: contains the full path of the theme root folder.
- $mustache_data: contains all the data required to render the views
- $mustache_template: contains the name of the template to load
- $mustache_navigation: contains the name of the upper level of navigation
*/
render_mustache($mustache_data, $mustache_template, $mustache_navigation, $application_data, $theme_path); | 2 | 0.1 | 1 | 1 |
a0a497be5fe57b4afc2fb84d59fe597b974a3f73 | ruby_event_store-rom/lib/ruby_event_store/rom/adapters/memory/unit_of_work.rb | ruby_event_store-rom/lib/ruby_event_store/rom/adapters/memory/unit_of_work.rb | module RubyEventStore
module ROM
module Memory
class UnitOfWork < ROM::UnitOfWork
def self.mutex
@mutex ||= Mutex.new
end
def commit!(gateway, changesets, **options)
self.class.mutex.synchronize do
committed = []
while changesets.size > 0
changeset = changesets.shift
begin
relation = env.container.relations[changeset.relation.name]
case changeset
when ROM::Repositories::Events::Create
relation.by_pk(changeset.to_a.map{ |e| e[:id] }).each do |tuple|
raise TupleUniquenessError.for_event_id(tuple[:id])
end
when ROM::Repositories::StreamEntries::Create
changeset.to_a.each do |tuple|
relation.send(:verify_uniquness!, tuple)
end
else
raise ArgumentError, 'Unknown changeset'
end
committed << [changeset, relation]
changeset.commit
rescue => ex
committed.reverse.each do |changeset, relation|
relation
.by_pk(changeset.to_a.map { |e| e[:id] })
.command(:delete, result: :many).call
end
raise
end
end
end
end
end
end
end
end
| module RubyEventStore
module ROM
module Memory
class UnitOfWork < ROM::UnitOfWork
def self.mutex
@mutex ||= Mutex.new
end
def commit!(gateway, changesets, **options)
self.class.mutex.synchronize do
committed = []
while changesets.size > 0
changeset = changesets.shift
begin
relation = env.container.relations[changeset.relation.name]
case changeset
when ROM::Repositories::Events::Create
relation.by_pk(changeset.to_a.map{ |e| e[:id] }).each do |tuple|
raise TupleUniquenessError.for_event_id(tuple[:id])
end
when ROM::Repositories::StreamEntries::Create
changeset.to_a.each do |tuple|
relation.send(:verify_uniquness!, tuple)
end
else
raise ArgumentError, 'Unknown changeset'
end
committed << [changeset, relation]
changeset.commit
rescue => ex
committed.reverse.each do |changeset, relation|
relation
.restrict(id: changeset.to_a.map { |e| e[:id] })
.command(:delete, result: :many).call
end
raise
end
end
end
end
end
end
end
end
| Fix "rollback" in Memory adapter to query tuples using built-in relation method | Fix "rollback" in Memory adapter to query tuples using built-in relation method
| Ruby | mit | RailsEventStore/rails_event_store,mpraglowski/rails_event_store,arkency/rails_event_store,arkency/rails_event_store,mpraglowski/rails_event_store,RailsEventStore/rails_event_store,arkency/rails_event_store,mpraglowski/rails_event_store,RailsEventStore/rails_event_store,mpraglowski/rails_event_store,RailsEventStore/rails_event_store,arkency/rails_event_store | ruby | ## Code Before:
module RubyEventStore
module ROM
module Memory
class UnitOfWork < ROM::UnitOfWork
def self.mutex
@mutex ||= Mutex.new
end
def commit!(gateway, changesets, **options)
self.class.mutex.synchronize do
committed = []
while changesets.size > 0
changeset = changesets.shift
begin
relation = env.container.relations[changeset.relation.name]
case changeset
when ROM::Repositories::Events::Create
relation.by_pk(changeset.to_a.map{ |e| e[:id] }).each do |tuple|
raise TupleUniquenessError.for_event_id(tuple[:id])
end
when ROM::Repositories::StreamEntries::Create
changeset.to_a.each do |tuple|
relation.send(:verify_uniquness!, tuple)
end
else
raise ArgumentError, 'Unknown changeset'
end
committed << [changeset, relation]
changeset.commit
rescue => ex
committed.reverse.each do |changeset, relation|
relation
.by_pk(changeset.to_a.map { |e| e[:id] })
.command(:delete, result: :many).call
end
raise
end
end
end
end
end
end
end
end
## Instruction:
Fix "rollback" in Memory adapter to query tuples using built-in relation method
## Code After:
module RubyEventStore
module ROM
module Memory
class UnitOfWork < ROM::UnitOfWork
def self.mutex
@mutex ||= Mutex.new
end
def commit!(gateway, changesets, **options)
self.class.mutex.synchronize do
committed = []
while changesets.size > 0
changeset = changesets.shift
begin
relation = env.container.relations[changeset.relation.name]
case changeset
when ROM::Repositories::Events::Create
relation.by_pk(changeset.to_a.map{ |e| e[:id] }).each do |tuple|
raise TupleUniquenessError.for_event_id(tuple[:id])
end
when ROM::Repositories::StreamEntries::Create
changeset.to_a.each do |tuple|
relation.send(:verify_uniquness!, tuple)
end
else
raise ArgumentError, 'Unknown changeset'
end
committed << [changeset, relation]
changeset.commit
rescue => ex
committed.reverse.each do |changeset, relation|
relation
.restrict(id: changeset.to_a.map { |e| e[:id] })
.command(:delete, result: :many).call
end
raise
end
end
end
end
end
end
end
end
| module RubyEventStore
module ROM
module Memory
class UnitOfWork < ROM::UnitOfWork
def self.mutex
@mutex ||= Mutex.new
end
def commit!(gateway, changesets, **options)
self.class.mutex.synchronize do
committed = []
while changesets.size > 0
changeset = changesets.shift
begin
relation = env.container.relations[changeset.relation.name]
case changeset
when ROM::Repositories::Events::Create
relation.by_pk(changeset.to_a.map{ |e| e[:id] }).each do |tuple|
raise TupleUniquenessError.for_event_id(tuple[:id])
end
when ROM::Repositories::StreamEntries::Create
changeset.to_a.each do |tuple|
relation.send(:verify_uniquness!, tuple)
end
else
raise ArgumentError, 'Unknown changeset'
end
committed << [changeset, relation]
changeset.commit
rescue => ex
committed.reverse.each do |changeset, relation|
relation
- .by_pk(changeset.to_a.map { |e| e[:id] })
? ^^^^^
+ .restrict(id: changeset.to_a.map { |e| e[:id] })
? ^^^^^^^^ ++++
.command(:delete, result: :many).call
end
raise
end
end
end
end
end
end
end
end | 2 | 0.04 | 1 | 1 |
e7c1eea3d041462eeb209a3cb71cb7f2df49b533 | templates/Includes/GoogleMapShortCode.ss | templates/Includes/GoogleMapShortCode.ss | <% include GoogleJavaScript %>
<div class="googlemapcontainer">
<div id="$DomID" class="map googlemap"><!-- map is rendered here --></div>
<% if $Caption %><p class="caption">$Caption</p><% end_if %>
</div>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: $Latitude, lng: $Longitude},
zoom: $Zoom,
mapTypeId: google.maps.MapTypeId.{$MapType}
};
var map = new google.maps.Map(document.getElementById('$DomID'),
mapOptions);
if ($AllowFullScreen) {
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(
FullScreenControl(map, "Full Screen", "Original Size")
);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
| <% include GoogleJavaScript %>
<div class="googlemapcontainer">
<div id="$DomID" class="map googlemap" style="background: #EEE; border: solid red 1px;height: 500px;"><!-- map is rendered here --></div>
<% if $Caption %><p class="caption">$Caption</p><% end_if %>
</div>
| Move JavaScript to a template that can be rendered at the end of the page | FIX: Move JavaScript to a template that can be rendered at the end of the page
| Scheme | bsd-3-clause | gordonbanderson/Mappable,gordonbanderson/Mappable | scheme | ## Code Before:
<% include GoogleJavaScript %>
<div class="googlemapcontainer">
<div id="$DomID" class="map googlemap"><!-- map is rendered here --></div>
<% if $Caption %><p class="caption">$Caption</p><% end_if %>
</div>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: $Latitude, lng: $Longitude},
zoom: $Zoom,
mapTypeId: google.maps.MapTypeId.{$MapType}
};
var map = new google.maps.Map(document.getElementById('$DomID'),
mapOptions);
if ($AllowFullScreen) {
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(
FullScreenControl(map, "Full Screen", "Original Size")
);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
## Instruction:
FIX: Move JavaScript to a template that can be rendered at the end of the page
## Code After:
<% include GoogleJavaScript %>
<div class="googlemapcontainer">
<div id="$DomID" class="map googlemap" style="background: #EEE; border: solid red 1px;height: 500px;"><!-- map is rendered here --></div>
<% if $Caption %><p class="caption">$Caption</p><% end_if %>
</div>
| <% include GoogleJavaScript %>
<div class="googlemapcontainer">
- <div id="$DomID" class="map googlemap"><!-- map is rendered here --></div>
+ <div id="$DomID" class="map googlemap" style="background: #EEE; border: solid red 1px;height: 500px;"><!-- map is rendered here --></div>
<% if $Caption %><p class="caption">$Caption</p><% end_if %>
</div>
- <script type="text/javascript">
- function initialize() {
- var mapOptions = {
- center: { lat: $Latitude, lng: $Longitude},
- zoom: $Zoom,
- mapTypeId: google.maps.MapTypeId.{$MapType}
- };
- var map = new google.maps.Map(document.getElementById('$DomID'),
- mapOptions);
- if ($AllowFullScreen) {
- map.controls[google.maps.ControlPosition.TOP_RIGHT].push(
- FullScreenControl(map, "Full Screen", "Original Size")
- );
- }
- }
- google.maps.event.addDomListener(window, 'load', initialize);
- </script> | 19 | 0.863636 | 1 | 18 |
d7146d7b794ddcaf22e93b5621d9c39898ec3624 | source/filters/filter.ts | source/filters/filter.ts | 'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
protected onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
} | 'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
} | Make onChange public for the tests. It still isn't visible on the interface, so most consumer won't care | Make onChange public for the tests. It still isn't visible on the interface, so most consumer won't care
| TypeScript | mit | RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities | typescript | ## Code Before:
'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
protected onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
}
## Instruction:
Make onChange public for the tests. It still isn't visible on the interface, so most consumer won't care
## Code After:
'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
} | 'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
- protected onChange(force: boolean = true): void {
? ----------
+ onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
} | 2 | 0.037037 | 1 | 1 |
c350b48b9c249edd62b22373f9cb41afbc21b1e3 | src/main/java/com/lassekoskela/maven/BuildEventsExtension.java | src/main/java/com/lassekoskela/maven/BuildEventsExtension.java | package com.lassekoskela.maven;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.rtinfo.RuntimeInformation;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;
@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {
@Requirement
private Logger logger;
@Requirement
RuntimeInformation runtime;
@Override
public void afterProjectsRead(MavenSession session)
throws MavenExecutionException {
ExecutionListener original = session.getRequest()
.getExecutionListener();
BuildEventLog log = new BuildEventLog(logger);
ExecutionListener injected = new BuildEventListener(log);
ExecutionListener chain = new ExecutionListenerChain(original, injected);
session.getRequest().setExecutionListener(chain);
}
void log(CharSequence message) {
logger.info(message.toString());
}
}
| package com.lassekoskela.maven;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;
@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {
@Requirement
private Logger logger;
@Override
public void afterProjectsRead(MavenSession session)
throws MavenExecutionException {
ExecutionListener original = session.getRequest()
.getExecutionListener();
BuildEventLog log = new BuildEventLog(logger);
ExecutionListener injected = new BuildEventListener(log);
ExecutionListener chain = new ExecutionListenerChain(original, injected);
session.getRequest().setExecutionListener(chain);
}
void log(CharSequence message) {
logger.info(message.toString());
}
}
| Drop @Requirement RuntimeInformation because we don't need it | Drop @Requirement RuntimeInformation because we don't need it
| Java | apache-2.0 | lkoskela/maven-build-utils | java | ## Code Before:
package com.lassekoskela.maven;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.rtinfo.RuntimeInformation;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;
@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {
@Requirement
private Logger logger;
@Requirement
RuntimeInformation runtime;
@Override
public void afterProjectsRead(MavenSession session)
throws MavenExecutionException {
ExecutionListener original = session.getRequest()
.getExecutionListener();
BuildEventLog log = new BuildEventLog(logger);
ExecutionListener injected = new BuildEventListener(log);
ExecutionListener chain = new ExecutionListenerChain(original, injected);
session.getRequest().setExecutionListener(chain);
}
void log(CharSequence message) {
logger.info(message.toString());
}
}
## Instruction:
Drop @Requirement RuntimeInformation because we don't need it
## Code After:
package com.lassekoskela.maven;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;
@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {
@Requirement
private Logger logger;
@Override
public void afterProjectsRead(MavenSession session)
throws MavenExecutionException {
ExecutionListener original = session.getRequest()
.getExecutionListener();
BuildEventLog log = new BuildEventLog(logger);
ExecutionListener injected = new BuildEventListener(log);
ExecutionListener chain = new ExecutionListenerChain(original, injected);
session.getRequest().setExecutionListener(chain);
}
void log(CharSequence message) {
logger.info(message.toString());
}
}
| package com.lassekoskela.maven;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
- import org.apache.maven.rtinfo.RuntimeInformation;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;
@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {
@Requirement
private Logger logger;
-
- @Requirement
- RuntimeInformation runtime;
@Override
public void afterProjectsRead(MavenSession session)
throws MavenExecutionException {
ExecutionListener original = session.getRequest()
.getExecutionListener();
BuildEventLog log = new BuildEventLog(logger);
ExecutionListener injected = new BuildEventListener(log);
ExecutionListener chain = new ExecutionListenerChain(original, injected);
session.getRequest().setExecutionListener(chain);
}
void log(CharSequence message) {
logger.info(message.toString());
}
} | 4 | 0.102564 | 0 | 4 |
955383ca18b978c9ed616a4b792b912e02a211ff | jenkins.sh | jenkins.sh | bundle install --path "${HOME}/bundles/${JOB_NAME}"
dropdb transition_test
createdb --encoding=UTF8 --template=template0 transition_test
sudo -u postgres psql -d transition_test -c 'CREATE EXTENSION IF NOT EXISTS pgcrypto'
cat db/structure.sql | psql -d transition_test
RACK_ENV=test bundle exec rake --trace
| git merge --no-commit origin/master || git merge --abort
bundle install --path "${HOME}/bundles/${JOB_NAME}"
dropdb transition_test
createdb --encoding=UTF8 --template=template0 transition_test
sudo -u postgres psql -d transition_test -c 'CREATE EXTENSION IF NOT EXISTS pgcrypto'
cat db/structure.sql | psql -d transition_test
RACK_ENV=test bundle exec rake --trace
| Check if there are conflicts on master when running the build | Check if there are conflicts on master when running the build
- This is taken from
https://github.com/alphagov/specialist-publisher/commit/9a097249c142c6e7146706dfd5fc0282c92f4886,
as a thing discussed in tech lead standup that could be useful and
passed to me to do via Jamie.
| Shell | mit | alphagov/bouncer,alphagov/bouncer,alphagov/bouncer | shell | ## Code Before:
bundle install --path "${HOME}/bundles/${JOB_NAME}"
dropdb transition_test
createdb --encoding=UTF8 --template=template0 transition_test
sudo -u postgres psql -d transition_test -c 'CREATE EXTENSION IF NOT EXISTS pgcrypto'
cat db/structure.sql | psql -d transition_test
RACK_ENV=test bundle exec rake --trace
## Instruction:
Check if there are conflicts on master when running the build
- This is taken from
https://github.com/alphagov/specialist-publisher/commit/9a097249c142c6e7146706dfd5fc0282c92f4886,
as a thing discussed in tech lead standup that could be useful and
passed to me to do via Jamie.
## Code After:
git merge --no-commit origin/master || git merge --abort
bundle install --path "${HOME}/bundles/${JOB_NAME}"
dropdb transition_test
createdb --encoding=UTF8 --template=template0 transition_test
sudo -u postgres psql -d transition_test -c 'CREATE EXTENSION IF NOT EXISTS pgcrypto'
cat db/structure.sql | psql -d transition_test
RACK_ENV=test bundle exec rake --trace
| + git merge --no-commit origin/master || git merge --abort
+
bundle install --path "${HOME}/bundles/${JOB_NAME}"
dropdb transition_test
createdb --encoding=UTF8 --template=template0 transition_test
sudo -u postgres psql -d transition_test -c 'CREATE EXTENSION IF NOT EXISTS pgcrypto'
cat db/structure.sql | psql -d transition_test
RACK_ENV=test bundle exec rake --trace | 2 | 0.25 | 2 | 0 |
30b483bc0d02cf0659c937c83c87824859c64452 | packages/app/source/client/components/registration-form/registration-form.js | packages/app/source/client/components/registration-form/registration-form.js | Space.flux.BlazeComponent.extend(Donations, 'OrgRegistrationForm', {
dependencies: {
store: 'Donations.OrgRegistrationsStore'
},
state() {
return this.store;
},
isCountry(country) {
return this.store.orgCountry() === country ? true : false;
},
events() {
return [{
'keyup input': this._onInputChange,
'change .org-country': this._onInputChange,
'click .submit': this._onSubmit
}];
},
_onInputChange() {
this.publish(new Donations.OrgRegistrationInputsChanged({
orgName: this.$('.org-name').val(),
orgCountry: this.$('.org-country option:selected').val(),
contactEmail: this.$('.contact-email').val(),
contactName: this.$('.contact-name').val(),
contactPhone: this.$('.contact-phone').val(),
password: this.$('.password').val()
}));
},
_onSubmit(event) {
event.preventDefault();
this.publish(new Donations.OrgRegistrationFormSubmitted());
}
});
Donations.OrgRegistrationForm.register('registration_form');
| Space.flux.BlazeComponent.extend(Donations, 'OrgRegistrationForm', {
ENTER: 13,
dependencies: {
store: 'Donations.OrgRegistrationsStore'
},
state() {
return this.store;
},
isCountry(country) {
return this.store.orgCountry() === country ? true : false;
},
events() {
return [{
'keyup input': this._onInputChange,
'change .org-country': this._onInputChange,
'click .submit': this._onSubmit
}];
},
_onInputChange(event) {
if(event.keyCode === this.ENTER) {
this._onSubmit(event)
}
this.publish(new Donations.OrgRegistrationInputsChanged({
orgName: this.$('.org-name').val(),
orgCountry: this.$('.org-country option:selected').val(),
contactEmail: this.$('.contact-email').val(),
contactName: this.$('.contact-name').val(),
contactPhone: this.$('.contact-phone').val(),
password: this.$('.password').val()
}));
},
_onSubmit(event) {
event.preventDefault();
this.publish(new Donations.OrgRegistrationFormSubmitted());
}
});
Donations.OrgRegistrationForm.register('registration_form');
| Add enter keymap to OrgRegistration | Add enter keymap to OrgRegistration
| JavaScript | mit | meteor-space/donations,meteor-space/donations,meteor-space/donations | javascript | ## Code Before:
Space.flux.BlazeComponent.extend(Donations, 'OrgRegistrationForm', {
dependencies: {
store: 'Donations.OrgRegistrationsStore'
},
state() {
return this.store;
},
isCountry(country) {
return this.store.orgCountry() === country ? true : false;
},
events() {
return [{
'keyup input': this._onInputChange,
'change .org-country': this._onInputChange,
'click .submit': this._onSubmit
}];
},
_onInputChange() {
this.publish(new Donations.OrgRegistrationInputsChanged({
orgName: this.$('.org-name').val(),
orgCountry: this.$('.org-country option:selected').val(),
contactEmail: this.$('.contact-email').val(),
contactName: this.$('.contact-name').val(),
contactPhone: this.$('.contact-phone').val(),
password: this.$('.password').val()
}));
},
_onSubmit(event) {
event.preventDefault();
this.publish(new Donations.OrgRegistrationFormSubmitted());
}
});
Donations.OrgRegistrationForm.register('registration_form');
## Instruction:
Add enter keymap to OrgRegistration
## Code After:
Space.flux.BlazeComponent.extend(Donations, 'OrgRegistrationForm', {
ENTER: 13,
dependencies: {
store: 'Donations.OrgRegistrationsStore'
},
state() {
return this.store;
},
isCountry(country) {
return this.store.orgCountry() === country ? true : false;
},
events() {
return [{
'keyup input': this._onInputChange,
'change .org-country': this._onInputChange,
'click .submit': this._onSubmit
}];
},
_onInputChange(event) {
if(event.keyCode === this.ENTER) {
this._onSubmit(event)
}
this.publish(new Donations.OrgRegistrationInputsChanged({
orgName: this.$('.org-name').val(),
orgCountry: this.$('.org-country option:selected').val(),
contactEmail: this.$('.contact-email').val(),
contactName: this.$('.contact-name').val(),
contactPhone: this.$('.contact-phone').val(),
password: this.$('.password').val()
}));
},
_onSubmit(event) {
event.preventDefault();
this.publish(new Donations.OrgRegistrationFormSubmitted());
}
});
Donations.OrgRegistrationForm.register('registration_form');
| Space.flux.BlazeComponent.extend(Donations, 'OrgRegistrationForm', {
+
+ ENTER: 13,
dependencies: {
store: 'Donations.OrgRegistrationsStore'
},
state() {
return this.store;
},
isCountry(country) {
return this.store.orgCountry() === country ? true : false;
},
events() {
return [{
'keyup input': this._onInputChange,
'change .org-country': this._onInputChange,
'click .submit': this._onSubmit
}];
},
- _onInputChange() {
+ _onInputChange(event) {
? +++++
+ if(event.keyCode === this.ENTER) {
+ this._onSubmit(event)
+ }
this.publish(new Donations.OrgRegistrationInputsChanged({
orgName: this.$('.org-name').val(),
orgCountry: this.$('.org-country option:selected').val(),
contactEmail: this.$('.contact-email').val(),
contactName: this.$('.contact-name').val(),
contactPhone: this.$('.contact-phone').val(),
password: this.$('.password').val()
}));
},
_onSubmit(event) {
event.preventDefault();
this.publish(new Donations.OrgRegistrationFormSubmitted());
}
});
Donations.OrgRegistrationForm.register('registration_form'); | 7 | 0.175 | 6 | 1 |
8ad6237da887961b02fe50ec9027be45a08e4e0e | coinx.js | coinx.js |
var program = require('commander');
program
.version('0.2.1')
.command('price [symbol]', 'get the price of a coin from all exchanges').alias('p')
.command('buy [symbol]', 'buy a coin from an exchange. Auto finds the best price.').alias('b')
.command('config [exchange]', 'set your api keys for an exchange').alias('c')
.command('funds', 'get a list of your funds from the exchanges').alias('f')
.command('update', 'updates the list of known coins').alias('u')
.parse(process.argv); |
var program = require('commander');
program
.version(require('./package.json').version)
.command('price [symbol]', 'get the price of a coin from all exchanges').alias('p')
.command('buy [symbol]', 'buy a coin from an exchange. Auto finds the best price.').alias('b')
.command('config [exchange]', 'set your api keys for an exchange').alias('c')
.command('funds', 'get a list of your funds from the exchanges').alias('f')
.command('update', 'updates the list of known coins').alias('u')
.parse(process.argv); | Fix version number displayed with -V | Fix version number displayed with -V
| JavaScript | mit | johntitus/coinx | javascript | ## Code Before:
var program = require('commander');
program
.version('0.2.1')
.command('price [symbol]', 'get the price of a coin from all exchanges').alias('p')
.command('buy [symbol]', 'buy a coin from an exchange. Auto finds the best price.').alias('b')
.command('config [exchange]', 'set your api keys for an exchange').alias('c')
.command('funds', 'get a list of your funds from the exchanges').alias('f')
.command('update', 'updates the list of known coins').alias('u')
.parse(process.argv);
## Instruction:
Fix version number displayed with -V
## Code After:
var program = require('commander');
program
.version(require('./package.json').version)
.command('price [symbol]', 'get the price of a coin from all exchanges').alias('p')
.command('buy [symbol]', 'buy a coin from an exchange. Auto finds the best price.').alias('b')
.command('config [exchange]', 'set your api keys for an exchange').alias('c')
.command('funds', 'get a list of your funds from the exchanges').alias('f')
.command('update', 'updates the list of known coins').alias('u')
.parse(process.argv); |
var program = require('commander');
program
- .version('0.2.1')
+ .version(require('./package.json').version)
.command('price [symbol]', 'get the price of a coin from all exchanges').alias('p')
.command('buy [symbol]', 'buy a coin from an exchange. Auto finds the best price.').alias('b')
.command('config [exchange]', 'set your api keys for an exchange').alias('c')
.command('funds', 'get a list of your funds from the exchanges').alias('f')
.command('update', 'updates the list of known coins').alias('u')
.parse(process.argv); | 2 | 0.166667 | 1 | 1 |
78c5a1463d51d8a1e92545d4dfda18845e1f23c4 | zend/fastcall.cpp | zend/fastcall.cpp | /**
* fastcall.cpp
*
* This file holds some PHP functions implementation in C directly.
*
*/
#include "includes.h"
namespace Php {
bool class_exists(const std::string &classname, bool autoload) {
// we need the tsrm_ls variable
TSRMLS_FETCH();
zend_class_entry **ce;
int found;
const char * str = classname.c_str();
int32_t len = (int32_t)classname.length();
if (autoload) {
char lc_name[len + 1];
zend_str_tolower_copy(lc_name, str, len);
char *name = lc_name;
if (lc_name[0] == '\\') {
name = &lc_name[1];
--len;
}
found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
}
if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
}
return false;
}
} | /**
* fastcall.cpp
*
* This file holds some PHP functions implementation in C directly.
*
*/
#include "includes.h"
namespace Php {
bool class_exists(const std::string &classname, bool autoload) {
// we need the tsrm_ls variable
TSRMLS_FETCH();
zend_class_entry **ce;
int found;
const char * str = classname.c_str();
int32_t len = (int32_t)classname.length();
if (autoload) {
char *lc_name = new char[len + 1];
zend_str_tolower_copy(lc_name, str, len);
char *name = lc_name;
if (lc_name[0] == '\\') {
name = &lc_name[1];
--len;
}
found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
delete [] lc_name;
return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
}
if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
}
return false;
}
} | Change C99 VLA C++ dynamic array | Change C99 VLA C++ dynamic array
| C++ | apache-2.0 | CopernicaMarketingSoftware/PHP-CPP-LEGACY,CopernicaMarketingSoftware/PHP-CPP,dreamsxin/PHP-CPP,sjinks/PHP-CPP,sjinks/PHP-CPP,carlmcdade/PHP-CPP,carlmcdade/PHP-CPP,CopernicaMarketingSoftware/PHP-CPP,dreamsxin/PHP-CPP,CopernicaMarketingSoftware/PHP-CPP-LEGACY,sjinks/PHP-CPP,carlmcdade/PHP-CPP,carlmcdade/PHP-CPP,sjinks/PHP-CPP | c++ | ## Code Before:
/**
* fastcall.cpp
*
* This file holds some PHP functions implementation in C directly.
*
*/
#include "includes.h"
namespace Php {
bool class_exists(const std::string &classname, bool autoload) {
// we need the tsrm_ls variable
TSRMLS_FETCH();
zend_class_entry **ce;
int found;
const char * str = classname.c_str();
int32_t len = (int32_t)classname.length();
if (autoload) {
char lc_name[len + 1];
zend_str_tolower_copy(lc_name, str, len);
char *name = lc_name;
if (lc_name[0] == '\\') {
name = &lc_name[1];
--len;
}
found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
}
if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
}
return false;
}
}
## Instruction:
Change C99 VLA C++ dynamic array
## Code After:
/**
* fastcall.cpp
*
* This file holds some PHP functions implementation in C directly.
*
*/
#include "includes.h"
namespace Php {
bool class_exists(const std::string &classname, bool autoload) {
// we need the tsrm_ls variable
TSRMLS_FETCH();
zend_class_entry **ce;
int found;
const char * str = classname.c_str();
int32_t len = (int32_t)classname.length();
if (autoload) {
char *lc_name = new char[len + 1];
zend_str_tolower_copy(lc_name, str, len);
char *name = lc_name;
if (lc_name[0] == '\\') {
name = &lc_name[1];
--len;
}
found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
delete [] lc_name;
return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
}
if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
}
return false;
}
} | /**
* fastcall.cpp
*
* This file holds some PHP functions implementation in C directly.
*
*/
#include "includes.h"
namespace Php {
bool class_exists(const std::string &classname, bool autoload) {
// we need the tsrm_ls variable
TSRMLS_FETCH();
zend_class_entry **ce;
int found;
const char * str = classname.c_str();
int32_t len = (int32_t)classname.length();
if (autoload) {
- char lc_name[len + 1];
+ char *lc_name = new char[len + 1];
? + +++++++++++
zend_str_tolower_copy(lc_name, str, len);
char *name = lc_name;
if (lc_name[0] == '\\') {
name = &lc_name[1];
--len;
}
found = zend_hash_find(EG(class_table), name, len + 1, (void **) &ce);
+ delete [] lc_name;
return (found == SUCCESS && !(((*ce)->ce_flags & (ZEND_ACC_INTERFACE | ZEND_ACC_TRAIT)) > ZEND_ACC_EXPLICIT_ABSTRACT_CLASS));
}
if (zend_lookup_class(str, len, &ce TSRMLS_CC) == SUCCESS) {
return (((*ce)->ce_flags & (ZEND_ACC_INTERFACE | (ZEND_ACC_TRAIT - ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) == 0);
}
return false;
}
} | 3 | 0.071429 | 2 | 1 |
fc99cc844694f5917603c919b71dd2d70f1ec696 | tox.ini | tox.ini | [tox]
envlist = pypy3, py35, py36, py37, py38, py39, py310
[gh-actions]
python =
pypy-3: pypy3
3.5: py35
3.6: py36
3.7: py37
3.8: py38
3.9: py39
3.10: py310
[testenv]
commands = python -m unittest discover
| [tox]
envlist = pypy38, py36, py37, py38, py39, py310
[gh-actions]
python =
pypy-38: pypy38
3.6: py36
3.7: py37
3.8: py38
3.9: py39
3.10: py310
[testenv]
commands = python -m unittest discover
| Drop Python 3.5 support and pypy 3.6 support | Drop Python 3.5 support and pypy 3.6 support
To allow for typing annotations and enforcement of typing annotations,
we need to:
- Drop Python 3.5 support since it doesn't support the syntax
- Drop pypy 3.6 support since it doesn't support mypy
| INI | bsd-2-clause | madzak/python-json-logger | ini | ## Code Before:
[tox]
envlist = pypy3, py35, py36, py37, py38, py39, py310
[gh-actions]
python =
pypy-3: pypy3
3.5: py35
3.6: py36
3.7: py37
3.8: py38
3.9: py39
3.10: py310
[testenv]
commands = python -m unittest discover
## Instruction:
Drop Python 3.5 support and pypy 3.6 support
To allow for typing annotations and enforcement of typing annotations,
we need to:
- Drop Python 3.5 support since it doesn't support the syntax
- Drop pypy 3.6 support since it doesn't support mypy
## Code After:
[tox]
envlist = pypy38, py36, py37, py38, py39, py310
[gh-actions]
python =
pypy-38: pypy38
3.6: py36
3.7: py37
3.8: py38
3.9: py39
3.10: py310
[testenv]
commands = python -m unittest discover
| [tox]
- envlist = pypy3, py35, py36, py37, py38, py39, py310
? ^^^^^^
+ envlist = pypy38, py36, py37, py38, py39, py310
? ^
[gh-actions]
python =
- pypy-3: pypy3
+ pypy-38: pypy38
? + +
- 3.5: py35
3.6: py36
3.7: py37
3.8: py38
3.9: py39
3.10: py310
[testenv]
commands = python -m unittest discover | 5 | 0.333333 | 2 | 3 |
45290d57fd175fd265f2c116749b87540a06b4ec | app/views/master_trees/_form.html.erb | app/views/master_trees/_form.html.erb | <!-- Start of Tree Background -->
<div class="tree-back">
<%= form.error_messages %>
<%= form.inputs do -%>
<%= form.input :title %>
<%= form.label :publication_date %>
<%= form.date_select :publication_date %>
<%= form.input :citation %>
<%= form.label :abstract %>
<%= form.text_area :abstract %>
<%= form.input :creative_commons, :as => :select,
:label => "License",
:collection => Licenses::CC_LICENSES %>
<% end %>
</div>
<!-- End of Tree Background -->
| <!-- Start of Tree Background -->
<div class="tree-back">
<%= form.error_messages %>
<%= form.inputs do -%>
<%= form.input :title %>
<%= form.label :publication_date %>
<%= form.date_select :publication_date %>
<%= form.input :citation %>
<%= form.label :abstract %>
<%= form.text_area :abstract %>
<%= form.input :creative_commons, :as => :select,
:label => "License",
:include_blank => false,
:collection => Licenses::CC_LICENSES %>
<% end %>
</div>
<!-- End of Tree Background -->
| Remove blank form license option | Remove blank form license option
| HTML+ERB | mit | GlobalNamesArchitecture/GNITE,GlobalNamesArchitecture/GNITE,GlobalNamesArchitecture/GNITE | html+erb | ## Code Before:
<!-- Start of Tree Background -->
<div class="tree-back">
<%= form.error_messages %>
<%= form.inputs do -%>
<%= form.input :title %>
<%= form.label :publication_date %>
<%= form.date_select :publication_date %>
<%= form.input :citation %>
<%= form.label :abstract %>
<%= form.text_area :abstract %>
<%= form.input :creative_commons, :as => :select,
:label => "License",
:collection => Licenses::CC_LICENSES %>
<% end %>
</div>
<!-- End of Tree Background -->
## Instruction:
Remove blank form license option
## Code After:
<!-- Start of Tree Background -->
<div class="tree-back">
<%= form.error_messages %>
<%= form.inputs do -%>
<%= form.input :title %>
<%= form.label :publication_date %>
<%= form.date_select :publication_date %>
<%= form.input :citation %>
<%= form.label :abstract %>
<%= form.text_area :abstract %>
<%= form.input :creative_commons, :as => :select,
:label => "License",
:include_blank => false,
:collection => Licenses::CC_LICENSES %>
<% end %>
</div>
<!-- End of Tree Background -->
| <!-- Start of Tree Background -->
<div class="tree-back">
<%= form.error_messages %>
<%= form.inputs do -%>
<%= form.input :title %>
<%= form.label :publication_date %>
<%= form.date_select :publication_date %>
<%= form.input :citation %>
<%= form.label :abstract %>
<%= form.text_area :abstract %>
- <%= form.input :creative_commons, :as => :select,
+ <%= form.input :creative_commons, :as => :select,
? +++
- :label => "License",
+ :label => "License",
? +++
+ :include_blank => false,
- :collection => Licenses::CC_LICENSES %>
+ :collection => Licenses::CC_LICENSES %>
? +++
<% end %>
</div>
<!-- End of Tree Background --> | 7 | 0.388889 | 4 | 3 |
c2c8e4325dec929af86222e30715f67fdcbf0478 | src/main.rs | src/main.rs | use std::env;
fn multiply (a: f32, b: f32) -> f32 {
return a * b;
}
fn add (a: f32, b: f32) -> f32 {
return a + b;
}
fn divide (a: f32, b: f32) -> f32 {
return a / b;
}
fn subtract (a: f32, b: f32) -> f32 {
return a - b;
}
fn exponent (a: f32, b: f32) -> f32 {
return a.powf(b);
}
fn main () {
let args: Vec<_> = env::args().collect();
let tokens: Vec<&str> = args[1].split(" ").collect();
let mut output: Vec<i32> = vec![];
let mut operator: Vec<_> = vec![];
for i in 1..tokens.len() {
let r = tokens[i].parse::<i32>();
match r {
Ok(_) => output.push(r.unwrap()),
Err(_) => {
if operator.len() > 0 {
}
operator.push(&tokens[i])
}
}
}
}
| use std::env;
use std::collections::HashMap;
struct Operator {
precedence: i32,
func: Box<Fn(f32, f32) -> f32>
}
fn main () {
let args: Vec<_> = env::args().collect();
let tokens: Vec<&str> = args[1].split(" ").collect();
let mut output: Vec<i32> = vec![];
let mut operator: Vec<_> = vec![];
let multiply = Operator {
precedence: 3,
func: Box::new(move |a: f32, b:f32| a * b)
};
let divide = Operator {
precedence: 3,
func: Box::new(move |a: f32, b:f32| a / b)
};
let add = Operator {
precedence: 4,
func: Box::new(move |a: f32, b:f32| a + b)
};
let subtract = Operator {
precedence: 4,
func: Box::new(move |a: f32, b:f32| a - b)
};
let mut operators: HashMap<char, Operator> = HashMap::new();
operators.insert('*', multiply);
operators.insert('/', divide);
operators.insert('+', add);
operators.insert('-', subtract);
for i in 1..tokens.len() {
let r = tokens[i].parse::<i32>();
match r {
Ok(_) => output.push(r.unwrap()),
Err(_) => {
if operator.len() > 0 {
}
operator.push(&tokens[i])
}
}
}
}
| Change how we do operators | Change how we do operators
| Rust | mit | adamjc/rust_calc | rust | ## Code Before:
use std::env;
fn multiply (a: f32, b: f32) -> f32 {
return a * b;
}
fn add (a: f32, b: f32) -> f32 {
return a + b;
}
fn divide (a: f32, b: f32) -> f32 {
return a / b;
}
fn subtract (a: f32, b: f32) -> f32 {
return a - b;
}
fn exponent (a: f32, b: f32) -> f32 {
return a.powf(b);
}
fn main () {
let args: Vec<_> = env::args().collect();
let tokens: Vec<&str> = args[1].split(" ").collect();
let mut output: Vec<i32> = vec![];
let mut operator: Vec<_> = vec![];
for i in 1..tokens.len() {
let r = tokens[i].parse::<i32>();
match r {
Ok(_) => output.push(r.unwrap()),
Err(_) => {
if operator.len() > 0 {
}
operator.push(&tokens[i])
}
}
}
}
## Instruction:
Change how we do operators
## Code After:
use std::env;
use std::collections::HashMap;
struct Operator {
precedence: i32,
func: Box<Fn(f32, f32) -> f32>
}
fn main () {
let args: Vec<_> = env::args().collect();
let tokens: Vec<&str> = args[1].split(" ").collect();
let mut output: Vec<i32> = vec![];
let mut operator: Vec<_> = vec![];
let multiply = Operator {
precedence: 3,
func: Box::new(move |a: f32, b:f32| a * b)
};
let divide = Operator {
precedence: 3,
func: Box::new(move |a: f32, b:f32| a / b)
};
let add = Operator {
precedence: 4,
func: Box::new(move |a: f32, b:f32| a + b)
};
let subtract = Operator {
precedence: 4,
func: Box::new(move |a: f32, b:f32| a - b)
};
let mut operators: HashMap<char, Operator> = HashMap::new();
operators.insert('*', multiply);
operators.insert('/', divide);
operators.insert('+', add);
operators.insert('-', subtract);
for i in 1..tokens.len() {
let r = tokens[i].parse::<i32>();
match r {
Ok(_) => output.push(r.unwrap()),
Err(_) => {
if operator.len() > 0 {
}
operator.push(&tokens[i])
}
}
}
}
| use std::env;
+ use std::collections::HashMap;
+ struct Operator {
+ precedence: i32,
+ func: Box<Fn(f32, f32) -> f32>
- fn multiply (a: f32, b: f32) -> f32 {
- return a * b;
- }
-
- fn add (a: f32, b: f32) -> f32 {
- return a + b;
- }
-
- fn divide (a: f32, b: f32) -> f32 {
- return a / b;
- }
-
- fn subtract (a: f32, b: f32) -> f32 {
- return a - b;
- }
-
- fn exponent (a: f32, b: f32) -> f32 {
- return a.powf(b);
}
fn main () {
let args: Vec<_> = env::args().collect();
let tokens: Vec<&str> = args[1].split(" ").collect();
let mut output: Vec<i32> = vec![];
let mut operator: Vec<_> = vec![];
+
+ let multiply = Operator {
+ precedence: 3,
+ func: Box::new(move |a: f32, b:f32| a * b)
+ };
+
+ let divide = Operator {
+ precedence: 3,
+ func: Box::new(move |a: f32, b:f32| a / b)
+ };
+
+ let add = Operator {
+ precedence: 4,
+ func: Box::new(move |a: f32, b:f32| a + b)
+ };
+
+ let subtract = Operator {
+ precedence: 4,
+ func: Box::new(move |a: f32, b:f32| a - b)
+ };
+
+ let mut operators: HashMap<char, Operator> = HashMap::new();
+
+ operators.insert('*', multiply);
+ operators.insert('/', divide);
+ operators.insert('+', add);
+ operators.insert('-', subtract);
for i in 1..tokens.len() {
let r = tokens[i].parse::<i32>();
match r {
Ok(_) => output.push(r.unwrap()),
Err(_) => {
if operator.len() > 0 {
}
operator.push(&tokens[i])
}
}
}
} | 49 | 1.166667 | 31 | 18 |
ca2447e851a31d5aa53d4e52c801f2263f6cf0a7 | README.md | README.md |
[](https://travis-ci.org/zurb/foundation)
Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices.
To get started, check out <http://foundation.zurb.com/docs>
## Quickstart
To get going with Foundation you can:
* [Download the latest release](http://foundation.zurb.com/develop/download.html)
* [Install with Bower](http://bower.io): `bower install zurb/bower-foundation`
## Documentation
Foundation uses [Assemble.io](http://assemble.io) and [Grunt](http://gruntjs.com/) to generate its [documentation pages](http://foundation.zurb.com/docs). Documentation can also be run from your local computer:
### View documentation locally
You'll want to clone the Foundation repo first and install all the dependencies. You can do this using the following commands:
```
git clone git@github.com:zurb/foundation.git
cd foundation
npm install -g grunt-cli bower
npm install
bower install
```
Then just run `grunt build` and the documentation will be compiled:
```
foundation/
├── dist/
│ └── ...
├────── docs/
│ └── ...
```
Copyright (c) 2015 ZURB, inc.
|
[](https://travis-ci.org/zurb/foundation)
Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices.
To get started, check out <http://foundation.zurb.com/docs>
## Quickstart
To get going with Foundation you can:
* [Download the latest release](http://foundation.zurb.com/develop/download.html)
* [Install with Bower](http://bower.io): `bower install foundation`
* [Install with npm](http://npmjs.com): `npm install foundation-sites`
## Documentation
Foundation uses [Assemble.io](http://assemble.io) and [Grunt](http://gruntjs.com/) to generate its [documentation pages](http://foundation.zurb.com/docs). Documentation can also be run from your local computer:
### View documentation locally
You'll want to clone the Foundation repo first and install all the dependencies. You can do this using the following commands:
```
git clone git@github.com:zurb/foundation.git
cd foundation
npm install -g grunt-cli bower
npm install
bower install
```
Then just run `grunt build` and the documentation will be compiled:
```
foundation/
├── dist/
│ └── ...
├────── docs/
│ └── ...
```
Copyright (c) 2015 ZURB, inc.
| Update readme with proper Bower and npm package names | Update readme with proper Bower and npm package names | Markdown | mit | DouglasAllen/css-foundation,karland/foundation-sites,pdeffendol/foundation,designerno1/foundation-sites,lizzwestman/foundation,pdeffendol/foundation,jeromelebleu/foundation-sites,asommer70/foundation,karland/foundation-sites,sethkane/foundation-sites,brettsmason/foundation-sites,zurb/foundation-sites,mbencharrada/foundation,Teino1978-Corp/Teino1978-Corp-foundation,carey/foundation,Larzans/foundation,IamManchanda/foundation-sites,robottomw/foundation,vrkansagara/foundation,denisahac/foundation-sites,wikieswan/foundation,jxnblk/foundation,robottomw/foundation,abdullahsalem/foundation-sites,ucla/foundation-sites,socketz/foundation-multilevel-offcanvas,r14r-work/fork_foundation_master,joe-watkins/foundation,karland/foundation-sites,BerndtGroup/TBG-foundation-sites,r14r-work/fork_foundation_master,djlotus/foundation,JihemC/Foundation-Demo,joe-watkins/foundation,laantorchaweb/foundation,laantorchaweb/foundation,RichardLee1978/foundation,glizer/foundation,BerndtGroup/TBG-foundation-sites,gnepal7/foundation,birthdayalex/foundation,wikieswan/foundation,barnyp/foundation,PassKitInc/foundation-sites,laantorchaweb/foundation,glizer/foundation,DouglasAllen/css-foundation,birthdayalex/foundation,signal/foundation,ibroadfo/foundation,asommer70/foundation,PassKitInc/foundation-sites,sashaegorov/foundation-sites,walbo/foundation,gnepal7/foundation,vrkansagara/foundation,Iamronan/foundation,r14r/fork_foundation_master,IamManchanda/foundation-sites,ibroadfo/foundation,Iamronan/foundation,zurb/foundation,Klaudit/foundation,getoutfitted/reaction-foundation-theme,marcosvicente/foundation,atmmarketing/foundation-sites,djlotus/foundation,NeonWilderness/foundation,vita10gy/foundation,jxnblk/foundation,jxnblk/foundation,signal/foundation,vrkansagara/foundation,pdeffendol/foundation,atmmarketing/foundation-sites,jamesstoneco/foundation-sites,socketz/foundation-multilevel-offcanvas,samuelmc/foundation-sites,ysalmin/foundation,mbarlock/foundation,asommer70/foundation,anbestephen/foundation,carey/foundation,DaSchTour/foundation-sites,dimamedia/foundation-6-sites-simple-scss-and-js,jeromelebleu/foundation-sites,lizzwestman/foundation,brettsmason/foundation-sites,marcosvicente/foundation,pauleds/foundation,r14r/fork_foundation_master,Larzans/foundation,DaSchTour/foundation-sites,Teino1978-Corp/Teino1978-Corp-foundation,PassKitInc/foundation-sites,NeonWilderness/foundation,glizer/foundation,jamesstoneco/foundation-sites,adstyles/foundation,designerno1/foundation-sites,Klaudit/foundation,robottomw/foundation,elkingtonmcb/foundation,barnyp/foundation,sethkane/foundation-sites,aoimedia/foundation,vita10gy/foundation,iwikmu/foundation,wikieswan/foundation,asommer70/foundation,youprofit/foundation,vita10gy/foundation,aoimedia/foundation,gnepal7/foundation,dragthor/foundation-sites,mbarlock/foundation,r14r/fork_foundation_master,andycochran/foundation-sites,walbo/foundation,lizzwestman/foundation,glizer/foundation,pauleds/foundation,denisahac/foundation-sites,adstyles/foundation,r14r/fork_foundation_master,sitexa/foundation,vita10gy/foundation,walbo/foundation,JihemC/Foundation-Demo,djlotus/foundation,Owlbertz/foundation,iwikmu/foundation,socketz/foundation-multilevel-offcanvas,ysalmin/foundation,getoutfitted/reaction-foundation-theme,r14r-work/fork_foundation_master,Teino1978-Corp/Teino1978-Corp-foundation,a-dg/foundation,jlegendary/foundation,natewiebe13/foundation-sites,Larzans/foundation,youprofit/foundation,jaylensoeur/foundation-sites-6,mbencharrada/foundation,lizzwestman/foundation,NeonWilderness/foundation,youprofit/foundation,mbencharrada/foundation,anbestephen/foundation,andycochran/foundation-sites,natewiebe13/foundation-sites,elkingtonmcb/foundation,mbencharrada/foundation,sitexa/foundation,ucla/foundation-sites,glunco/foundation,ibroadfo/foundation,birthdayalex/foundation,birthdayalex/foundation,leo-guinan/foundation,barnyp/foundation,colin-marshall/foundation-sites,leo-guinan/foundation,marcosvicente/foundation,jeromelebleu/foundation-sites,sitexa/foundation,carey/foundation,gnepal7/foundation,anbestephen/foundation,zurb/foundation,Owlbertz/foundation,dragthor/foundation-sites,pdeffendol/foundation,zurb/foundation-sites,brettsmason/foundation-sites,laantorchaweb/foundation,iwikmu/foundation,samuelmc/foundation-sites,Teino1978-Corp/Teino1978-Corp-foundation,sashaegorov/foundation-sites,NeonWilderness/foundation,ucla/foundation-sites,leo-guinan/foundation,elkingtonmcb/foundation,Iamronan/foundation,dimamedia/foundation-6-sites-simple-scss-and-js,glunco/foundation,sashaegorov/foundation-sites,a-dg/foundation,pauleds/foundation,IamManchanda/foundation-sites,dragthor/foundation-sites,BerndtGroup/TBG-foundation-sites,jamesstoneco/foundation-sites,ysalmin/foundation,Mango-information-systems/foundation,RichardLee1978/foundation,andycochran/foundation-sites,RichardLee1978/foundation,colin-marshall/foundation-sites,DouglasAllen/css-foundation,aoimedia/foundation,djlotus/foundation,Owlbertz/foundation,barnyp/foundation,Larzans/foundation,signal/foundation,adstyles/foundation,iwikmu/foundation,elkingtonmcb/foundation,glunco/foundation,youprofit/foundation,Owlbertz/foundation,jaylensoeur/foundation-sites-6,mbarlock/foundation,designerno1/foundation-sites,anbestephen/foundation,abdullahsalem/foundation-sites,jlegendary/foundation,sethkane/foundation-sites,jxnblk/foundation,zurb/foundation-sites,mbarlock/foundation,pauleds/foundation,adstyles/foundation,a-dg/foundation,Mango-information-systems/foundation,signal/foundation,joe-watkins/foundation,jaylensoeur/foundation-sites-6,wikieswan/foundation,walbo/foundation,JihemC/Foundation-Demo,Klaudit/foundation,denisahac/foundation-sites,a-dg/foundation,jlegendary/foundation,sitexa/foundation,Mango-information-systems/foundation,marcosvicente/foundation,vrkansagara/foundation,carey/foundation,r14r-work/fork_foundation_master,ibroadfo/foundation,abdullahsalem/foundation-sites,colin-marshall/foundation-sites,Klaudit/foundation,zurb/foundation,glunco/foundation,leo-guinan/foundation,ysalmin/foundation,natewiebe13/foundation-sites,DouglasAllen/css-foundation,jlegendary/foundation,RichardLee1978/foundation,joe-watkins/foundation,getoutfitted/reaction-foundation-theme,atmmarketing/foundation-sites,robottomw/foundation,JihemC/Foundation-Demo,samuelmc/foundation-sites | markdown | ## Code Before:
[](https://travis-ci.org/zurb/foundation)
Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices.
To get started, check out <http://foundation.zurb.com/docs>
## Quickstart
To get going with Foundation you can:
* [Download the latest release](http://foundation.zurb.com/develop/download.html)
* [Install with Bower](http://bower.io): `bower install zurb/bower-foundation`
## Documentation
Foundation uses [Assemble.io](http://assemble.io) and [Grunt](http://gruntjs.com/) to generate its [documentation pages](http://foundation.zurb.com/docs). Documentation can also be run from your local computer:
### View documentation locally
You'll want to clone the Foundation repo first and install all the dependencies. You can do this using the following commands:
```
git clone git@github.com:zurb/foundation.git
cd foundation
npm install -g grunt-cli bower
npm install
bower install
```
Then just run `grunt build` and the documentation will be compiled:
```
foundation/
├── dist/
│ └── ...
├────── docs/
│ └── ...
```
Copyright (c) 2015 ZURB, inc.
## Instruction:
Update readme with proper Bower and npm package names
## Code After:
[](https://travis-ci.org/zurb/foundation)
Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices.
To get started, check out <http://foundation.zurb.com/docs>
## Quickstart
To get going with Foundation you can:
* [Download the latest release](http://foundation.zurb.com/develop/download.html)
* [Install with Bower](http://bower.io): `bower install foundation`
* [Install with npm](http://npmjs.com): `npm install foundation-sites`
## Documentation
Foundation uses [Assemble.io](http://assemble.io) and [Grunt](http://gruntjs.com/) to generate its [documentation pages](http://foundation.zurb.com/docs). Documentation can also be run from your local computer:
### View documentation locally
You'll want to clone the Foundation repo first and install all the dependencies. You can do this using the following commands:
```
git clone git@github.com:zurb/foundation.git
cd foundation
npm install -g grunt-cli bower
npm install
bower install
```
Then just run `grunt build` and the documentation will be compiled:
```
foundation/
├── dist/
│ └── ...
├────── docs/
│ └── ...
```
Copyright (c) 2015 ZURB, inc.
|
[](https://travis-ci.org/zurb/foundation)
Foundation is the most advanced responsive front-end framework in the world. You can quickly prototype and build sites or apps that work on any kind of device with Foundation, which includes layout constructs (like a fully responsive grid), elements and best practices.
To get started, check out <http://foundation.zurb.com/docs>
## Quickstart
To get going with Foundation you can:
* [Download the latest release](http://foundation.zurb.com/develop/download.html)
- * [Install with Bower](http://bower.io): `bower install zurb/bower-foundation`
? -----------
+ * [Install with Bower](http://bower.io): `bower install foundation`
+ * [Install with npm](http://npmjs.com): `npm install foundation-sites`
## Documentation
Foundation uses [Assemble.io](http://assemble.io) and [Grunt](http://gruntjs.com/) to generate its [documentation pages](http://foundation.zurb.com/docs). Documentation can also be run from your local computer:
### View documentation locally
You'll want to clone the Foundation repo first and install all the dependencies. You can do this using the following commands:
```
git clone git@github.com:zurb/foundation.git
cd foundation
npm install -g grunt-cli bower
npm install
bower install
```
Then just run `grunt build` and the documentation will be compiled:
```
foundation/
├── dist/
│ └── ...
├────── docs/
│ └── ...
```
Copyright (c) 2015 ZURB, inc. | 3 | 0.069767 | 2 | 1 |
0c27af096679163fb0d51294adc8e7e4a0bad419 | lib/mactag/config.rb | lib/mactag/config.rb | module Mactag
# Configuration options.
#
# ==== Binary
# The command to run when creating the TAGS-file.
# Mactag::Config.binary = "etags -o TAGS"
#
# ==== Gem Home
# The folder where the gems are stored.
# Mactag::Config.gem_home = "/usr/lib/ruby/gems/1.9/gems"
class Config
@@binary = "ctags -o TAGS -e"
cattr_accessor :binary
@@gem_home = "/usr/lib/ruby/gems/1.8/gems"
cattr_accessor :gem_home
end
end
| module Mactag
# Configuration options.
#
# ==== Binary
# The command to run when creating the TAGS-file.
# Mactag::Config.binary = "etags -o TAGS"
#
# ==== Gem Home
# The folder where the gems are stored.
# Mactag::Config.gem_home = "/Library/Ruby/Gems/1.8/gems"
class Config
@@binary = "ctags -o TAGS -e"
cattr_accessor :binary
@@gem_home = "/Library/Ruby/Gems/1.8/gems"
cattr_accessor :gem_home
end
end
| Make standard gem home the one on MacOS. | Make standard gem home the one on MacOS.
| Ruby | mit | rejeep/mactag | ruby | ## Code Before:
module Mactag
# Configuration options.
#
# ==== Binary
# The command to run when creating the TAGS-file.
# Mactag::Config.binary = "etags -o TAGS"
#
# ==== Gem Home
# The folder where the gems are stored.
# Mactag::Config.gem_home = "/usr/lib/ruby/gems/1.9/gems"
class Config
@@binary = "ctags -o TAGS -e"
cattr_accessor :binary
@@gem_home = "/usr/lib/ruby/gems/1.8/gems"
cattr_accessor :gem_home
end
end
## Instruction:
Make standard gem home the one on MacOS.
## Code After:
module Mactag
# Configuration options.
#
# ==== Binary
# The command to run when creating the TAGS-file.
# Mactag::Config.binary = "etags -o TAGS"
#
# ==== Gem Home
# The folder where the gems are stored.
# Mactag::Config.gem_home = "/Library/Ruby/Gems/1.8/gems"
class Config
@@binary = "ctags -o TAGS -e"
cattr_accessor :binary
@@gem_home = "/Library/Ruby/Gems/1.8/gems"
cattr_accessor :gem_home
end
end
| module Mactag
# Configuration options.
#
# ==== Binary
# The command to run when creating the TAGS-file.
# Mactag::Config.binary = "etags -o TAGS"
#
# ==== Gem Home
# The folder where the gems are stored.
- # Mactag::Config.gem_home = "/usr/lib/ruby/gems/1.9/gems"
? ^^^^^ ^ ^ ^
+ # Mactag::Config.gem_home = "/Library/Ruby/Gems/1.8/gems"
? ^ ++++ ^ ^ ^
class Config
@@binary = "ctags -o TAGS -e"
cattr_accessor :binary
- @@gem_home = "/usr/lib/ruby/gems/1.8/gems"
? ^^^^^ ^ ^
+ @@gem_home = "/Library/Ruby/Gems/1.8/gems"
? ^ ++++ ^ ^
cattr_accessor :gem_home
end
end | 4 | 0.2 | 2 | 2 |
37c65be9ef90c59baea4167d18371e314261e311 | build/doAll.sh | build/doAll.sh |
cd /home/ubuntu/rawdata
./doGetRawdata.sh
cd /home/ubuntu/genome
./doGetChr20.sh
cd /home/ubuntu/bwa
./doBWA.sh
cd /home/ubuntu/hisat
./doHISAT.sh
cd /home/ubuntu/star
./doSTAR.sh
cd /home/ubuntu/blastmapper
./doBlastmapper.sh
cd /home/ubuntu/csaw
Rscript runCsaw.R ../blastmapper/blastmapper.sorted.bam ../hisat/hisat.sorted.bam ../star/star.sorted.bam ../bwa/bwa.sorted.bam
cd /home/ubuntu/bamdiff
./bamDiff.py ../csaw/csaw.bam.results.csv ../hisat/hisat.sorted.bam ../star/star.sorted.bam > hisatVSstar
|
cd /home/ubuntu/rawdata
./doGetRawdata.sh
cd /home/ubuntu/genome
./doGetChr20.sh
cd /home/ubuntu/bwa
./doBWA.sh
cd /home/ubuntu/hisat
./doHISAT.sh
cd /home/ubuntu/star
./doSTAR.sh
cd /home/ubuntu/blastmapper
./doBlastmapper.sh
cd /home/ubuntu/csaw
Rscript runCsaw.R ../blastmapper/blastmapper.sorted.bam ../hisat/hisat.sorted.bam ../star/star.sorted.bam ../bwa/bwa.sorted.bam
cd /home/ubuntu/bamdiff
./bamDiff.py ../csaw/csaw.bam.results.csv ../hisat/hisat.sorted.bam ../star/star.sorted.bam
| Send bamDiff.py output to screen | Send bamDiff.py output to screen | Shell | cc0-1.0 | DCGenomics/ngs_education_hackathon_v002,DCGenomics/ngs_education_hackathon_v002,DCGenomics/ngs_education_hackathon_v002 | shell | ## Code Before:
cd /home/ubuntu/rawdata
./doGetRawdata.sh
cd /home/ubuntu/genome
./doGetChr20.sh
cd /home/ubuntu/bwa
./doBWA.sh
cd /home/ubuntu/hisat
./doHISAT.sh
cd /home/ubuntu/star
./doSTAR.sh
cd /home/ubuntu/blastmapper
./doBlastmapper.sh
cd /home/ubuntu/csaw
Rscript runCsaw.R ../blastmapper/blastmapper.sorted.bam ../hisat/hisat.sorted.bam ../star/star.sorted.bam ../bwa/bwa.sorted.bam
cd /home/ubuntu/bamdiff
./bamDiff.py ../csaw/csaw.bam.results.csv ../hisat/hisat.sorted.bam ../star/star.sorted.bam > hisatVSstar
## Instruction:
Send bamDiff.py output to screen
## Code After:
cd /home/ubuntu/rawdata
./doGetRawdata.sh
cd /home/ubuntu/genome
./doGetChr20.sh
cd /home/ubuntu/bwa
./doBWA.sh
cd /home/ubuntu/hisat
./doHISAT.sh
cd /home/ubuntu/star
./doSTAR.sh
cd /home/ubuntu/blastmapper
./doBlastmapper.sh
cd /home/ubuntu/csaw
Rscript runCsaw.R ../blastmapper/blastmapper.sorted.bam ../hisat/hisat.sorted.bam ../star/star.sorted.bam ../bwa/bwa.sorted.bam
cd /home/ubuntu/bamdiff
./bamDiff.py ../csaw/csaw.bam.results.csv ../hisat/hisat.sorted.bam ../star/star.sorted.bam
|
cd /home/ubuntu/rawdata
./doGetRawdata.sh
cd /home/ubuntu/genome
./doGetChr20.sh
cd /home/ubuntu/bwa
./doBWA.sh
cd /home/ubuntu/hisat
./doHISAT.sh
cd /home/ubuntu/star
./doSTAR.sh
cd /home/ubuntu/blastmapper
./doBlastmapper.sh
cd /home/ubuntu/csaw
Rscript runCsaw.R ../blastmapper/blastmapper.sorted.bam ../hisat/hisat.sorted.bam ../star/star.sorted.bam ../bwa/bwa.sorted.bam
cd /home/ubuntu/bamdiff
- ./bamDiff.py ../csaw/csaw.bam.results.csv ../hisat/hisat.sorted.bam ../star/star.sorted.bam > hisatVSstar
? --------------
+ ./bamDiff.py ../csaw/csaw.bam.results.csv ../hisat/hisat.sorted.bam ../star/star.sorted.bam | 2 | 0.083333 | 1 | 1 |
e785014f8ef37cce066b7b25c845ec37e3acf019 | power.go | power.go | package gogopro
import (
"io/ioutil"
)
type Power struct {
APIRequester *APIRequester
}
func (p *Power) Init() *Power {
return p
}
func CreatePower(APIRequester *APIRequester) *Power {
power := &Power{}
power.APIRequester = APIRequester
return power
}
func (p *Power) GetPowerStatus() (string, error) {
resp, err := p.APIRequester.get("/bacpac/se")
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if body[len(body)-1] == 0 {
return "off", nil
}
return "on", nil
}
| package gogopro
import ()
type Power struct {
APIRequester *APIRequester
StatusCommands map[string]StatusCommand
}
func (p *Power) Init() *Power {
return p
}
func CreatePower(APIRequester *APIRequester) *Power {
power := &Power{}
power.APIRequester = APIRequester
statusCommands := CreateStatusCommands()
power.StatusCommands = statusCommands
return power
}
func CreateStatusCommands() map[string]StatusCommand {
sc := make(map[string]StatusCommand)
sc["power"] = StatusCommand{Endpoint: "/bacpac/se", ResultByte: -1,
Translaters: []StatusTranslater{
StatusTranslater{
Result: 0,
ExpectedReturn: "off"},
StatusTranslater{
Result: 1,
ExpectedReturn: "on"}}}
return sc
}
func (p *Power) GetPowerStatus() (string, error) {
result, err := p.StatusCommands["power"].RunStatusCommand(p.APIRequester)
if err != nil {
return "", err
}
return result, nil
}
| Move status command to generic object | Move status command to generic object
- The StatusCommand type now runs api command and determines the
correct value to return.
- The Power type will create predetermined StatusCommands with
translaters. Power functions will use the correct StatusCommand
matching the function called.
| Go | apache-2.0 | wagnerm/gogopro | go | ## Code Before:
package gogopro
import (
"io/ioutil"
)
type Power struct {
APIRequester *APIRequester
}
func (p *Power) Init() *Power {
return p
}
func CreatePower(APIRequester *APIRequester) *Power {
power := &Power{}
power.APIRequester = APIRequester
return power
}
func (p *Power) GetPowerStatus() (string, error) {
resp, err := p.APIRequester.get("/bacpac/se")
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if body[len(body)-1] == 0 {
return "off", nil
}
return "on", nil
}
## Instruction:
Move status command to generic object
- The StatusCommand type now runs api command and determines the
correct value to return.
- The Power type will create predetermined StatusCommands with
translaters. Power functions will use the correct StatusCommand
matching the function called.
## Code After:
package gogopro
import ()
type Power struct {
APIRequester *APIRequester
StatusCommands map[string]StatusCommand
}
func (p *Power) Init() *Power {
return p
}
func CreatePower(APIRequester *APIRequester) *Power {
power := &Power{}
power.APIRequester = APIRequester
statusCommands := CreateStatusCommands()
power.StatusCommands = statusCommands
return power
}
func CreateStatusCommands() map[string]StatusCommand {
sc := make(map[string]StatusCommand)
sc["power"] = StatusCommand{Endpoint: "/bacpac/se", ResultByte: -1,
Translaters: []StatusTranslater{
StatusTranslater{
Result: 0,
ExpectedReturn: "off"},
StatusTranslater{
Result: 1,
ExpectedReturn: "on"}}}
return sc
}
func (p *Power) GetPowerStatus() (string, error) {
result, err := p.StatusCommands["power"].RunStatusCommand(p.APIRequester)
if err != nil {
return "", err
}
return result, nil
}
| package gogopro
- import (
+ import ()
? +
- "io/ioutil"
- )
type Power struct {
- APIRequester *APIRequester
+ APIRequester *APIRequester
? ++
+ StatusCommands map[string]StatusCommand
}
func (p *Power) Init() *Power {
return p
}
func CreatePower(APIRequester *APIRequester) *Power {
power := &Power{}
power.APIRequester = APIRequester
+ statusCommands := CreateStatusCommands()
+ power.StatusCommands = statusCommands
return power
}
+ func CreateStatusCommands() map[string]StatusCommand {
+ sc := make(map[string]StatusCommand)
+ sc["power"] = StatusCommand{Endpoint: "/bacpac/se", ResultByte: -1,
+ Translaters: []StatusTranslater{
+ StatusTranslater{
+ Result: 0,
+ ExpectedReturn: "off"},
+ StatusTranslater{
+ Result: 1,
+ ExpectedReturn: "on"}}}
+ return sc
+ }
+
func (p *Power) GetPowerStatus() (string, error) {
- resp, err := p.APIRequester.get("/bacpac/se")
+ result, err := p.StatusCommands["power"].RunStatusCommand(p.APIRequester)
if err != nil {
return "", err
}
+ return result, nil
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- if body[len(body)-1] == 0 {
- return "off", nil
- }
- return "on", nil
} | 31 | 0.96875 | 20 | 11 |
446084aa59ea4aac7d0d53c4f3b923514b13ba99 | .travis.yml | .travis.yml | sudo: false
language: ruby
before_script:
- env RACK_ENV=test bundle exec rake db:bootstrap
install: bundle install --deployment --without development production
rvm: 2.1.3
cache: bundle
addons:
postgresql: "9.4"
apt:
packages:
- postgresql-server-dev-9.4 | sudo: false
language: ruby
before_script:
- 'env git clone git@github.com:CocoaPods/Humus.git'
- 'env RACK_ENV=test cd Humus && bundle exec rake db:bootstrap'
install: bundle install --deployment --without development production
rvm: 2.1.3
cache: bundle
addons:
postgresql: "9.4"
apt:
packages:
- postgresql-server-dev-9.4 | Set up test database via Humus. | [Travis] Set up test database via Humus.
| YAML | mit | k0nserv/trunk.cocoapods.org,CocoaPods/trunk.cocoapods.org,k0nserv/trunk.cocoapods.org,k0nserv/trunk.cocoapods.org,CocoaPods/trunk.cocoapods.org | yaml | ## Code Before:
sudo: false
language: ruby
before_script:
- env RACK_ENV=test bundle exec rake db:bootstrap
install: bundle install --deployment --without development production
rvm: 2.1.3
cache: bundle
addons:
postgresql: "9.4"
apt:
packages:
- postgresql-server-dev-9.4
## Instruction:
[Travis] Set up test database via Humus.
## Code After:
sudo: false
language: ruby
before_script:
- 'env git clone git@github.com:CocoaPods/Humus.git'
- 'env RACK_ENV=test cd Humus && bundle exec rake db:bootstrap'
install: bundle install --deployment --without development production
rvm: 2.1.3
cache: bundle
addons:
postgresql: "9.4"
apt:
packages:
- postgresql-server-dev-9.4 | sudo: false
language: ruby
before_script:
+ - 'env git clone git@github.com:CocoaPods/Humus.git'
- - env RACK_ENV=test bundle exec rake db:bootstrap
+ - 'env RACK_ENV=test cd Humus && bundle exec rake db:bootstrap'
? + ++++++++++++ +
install: bundle install --deployment --without development production
rvm: 2.1.3
cache: bundle
addons:
postgresql: "9.4"
apt:
packages:
- postgresql-server-dev-9.4 | 3 | 0.25 | 2 | 1 |
ae9cf04fb6ef5df90954046a663af2a9d93387de | src/gallery.reveal.js | src/gallery.reveal.js | (function() {
if( typeof window.addEventListener === 'function' ) {
Reveal.addEventListener("slidechanged", function (event) {
if (event.previousSlide.querySelector('.gallery') || document.querySelector('.reveal > .gallery')) {
Gallery.stop();
}
Gallery.start(event.currentSlide);
});
// during initial load
if (Reveal.getCurrentSlide()) {
Gallery.start(Reveal.getCurrentSlide());
}
}
})(); | (function() {
if( typeof window.addEventListener === 'function' ) {
Reveal.addEventListener("slidechanged", function (event) {
if (event.previousSlide.querySelector('.gallery') || document.querySelector('.reveal > .gallery')) {
Gallery.stop();
}
var galleryNode = event.currentSlide.querySelector('.gallery');
if (galleryNode) {
Gallery.start(galleryNode);
}
});
// during initial load
if (Reveal.getCurrentSlide()) {
var galleryNode = Reveal.getCurrentSlide().querySelector('.gallery');
if (galleryNode) {
Gallery.start(galleryNode);
}
}
}
})(); | Fix plugin to pass right node in | Fix plugin to pass right node in
| JavaScript | mit | marcins/revealjs-simple-gallery | javascript | ## Code Before:
(function() {
if( typeof window.addEventListener === 'function' ) {
Reveal.addEventListener("slidechanged", function (event) {
if (event.previousSlide.querySelector('.gallery') || document.querySelector('.reveal > .gallery')) {
Gallery.stop();
}
Gallery.start(event.currentSlide);
});
// during initial load
if (Reveal.getCurrentSlide()) {
Gallery.start(Reveal.getCurrentSlide());
}
}
})();
## Instruction:
Fix plugin to pass right node in
## Code After:
(function() {
if( typeof window.addEventListener === 'function' ) {
Reveal.addEventListener("slidechanged", function (event) {
if (event.previousSlide.querySelector('.gallery') || document.querySelector('.reveal > .gallery')) {
Gallery.stop();
}
var galleryNode = event.currentSlide.querySelector('.gallery');
if (galleryNode) {
Gallery.start(galleryNode);
}
});
// during initial load
if (Reveal.getCurrentSlide()) {
var galleryNode = Reveal.getCurrentSlide().querySelector('.gallery');
if (galleryNode) {
Gallery.start(galleryNode);
}
}
}
})(); | (function() {
if( typeof window.addEventListener === 'function' ) {
Reveal.addEventListener("slidechanged", function (event) {
if (event.previousSlide.querySelector('.gallery') || document.querySelector('.reveal > .gallery')) {
Gallery.stop();
}
- Gallery.start(event.currentSlide);
+ var galleryNode = event.currentSlide.querySelector('.gallery');
+ if (galleryNode) {
+ Gallery.start(galleryNode);
+ }
+
});
// during initial load
if (Reveal.getCurrentSlide()) {
- Gallery.start(Reveal.getCurrentSlide());
+ var galleryNode = Reveal.getCurrentSlide().querySelector('.gallery');
+ if (galleryNode) {
+ Gallery.start(galleryNode);
+ }
}
}
})(); | 11 | 0.6875 | 9 | 2 |
03802d28001e0fb705a80954d54052b2ec56e153 | doc/source/dev/governance/people.rst | doc/source/dev/governance/people.rst | .. _governance-people:
Current steering council and institutional partners
===================================================
Steering council
----------------
* Sebastian Berg
* Jaime Fernández del Río
* Ralf Gommers
* Charles Harris
* Nathaniel Smith
* Julian Taylor
* Pauli Virtanen
* Eric Wieser
* Marten van Kerkwijk
* Stephan Hoyer
* Allan Haldane
* Stefan van der Walt
Emeritus members
----------------
* Travis Oliphant - Project Founder / Emeritus Leader (served: 2005-2012)
* Alex Griffing (served: 2015-2017)
NumFOCUS Subcommittee
---------------------
* Chuck Harris
* Ralf Gommers
* Jaime Fernández del Río
* Nathaniel Smith
* External member: Thomas Caswell
Institutional Partners
----------------------
* UC Berkeley (Stefan van der Walt, Matti Picus, Tyler Reddy)
* Quansight (Ralf Gommers, Hameer Abbasi)
| .. _governance-people:
Current steering council and institutional partners
===================================================
Steering council
----------------
* Sebastian Berg
* Jaime Fernández del Río
* Ralf Gommers
* Charles Harris
* Nathaniel Smith
* Julian Taylor
* Pauli Virtanen
* Eric Wieser
* Marten van Kerkwijk
* Stephan Hoyer
* Allan Haldane
* Stefan van der Walt
Emeritus members
----------------
* Travis Oliphant - Project Founder / Emeritus Leader (served: 2005-2012)
* Alex Griffing (served: 2015-2017)
NumFOCUS Subcommittee
---------------------
* Chuck Harris
* Ralf Gommers
* Jaime Fernández del Río
* Nathaniel Smith
* External member: Thomas Caswell
Institutional Partners
----------------------
* UC Berkeley (Stefan van der Walt, Matti Picus, Tyler Reddy, Sebastian Berg)
* Quansight (Ralf Gommers, Hameer Abbasi)
| Add Sebastian Berg as sponsored by BIDS | DOC: Add Sebastian Berg as sponsored by BIDS
| reStructuredText | bsd-3-clause | numpy/numpy,pdebuyl/numpy,WarrenWeckesser/numpy,ahaldane/numpy,mhvk/numpy,jakirkham/numpy,numpy/numpy,pdebuyl/numpy,grlee77/numpy,mhvk/numpy,ahaldane/numpy,seberg/numpy,mhvk/numpy,abalkin/numpy,pizzathief/numpy,shoyer/numpy,simongibbons/numpy,shoyer/numpy,grlee77/numpy,charris/numpy,rgommers/numpy,mattip/numpy,pbrod/numpy,ahaldane/numpy,abalkin/numpy,pbrod/numpy,charris/numpy,mattip/numpy,ahaldane/numpy,MSeifert04/numpy,MSeifert04/numpy,pdebuyl/numpy,mhvk/numpy,anntzer/numpy,pizzathief/numpy,madphysicist/numpy,rgommers/numpy,shoyer/numpy,WarrenWeckesser/numpy,MSeifert04/numpy,shoyer/numpy,MSeifert04/numpy,pbrod/numpy,pbrod/numpy,jorisvandenbossche/numpy,jakirkham/numpy,seberg/numpy,pizzathief/numpy,seberg/numpy,grlee77/numpy,WarrenWeckesser/numpy,endolith/numpy,jakirkham/numpy,ahaldane/numpy,jorisvandenbossche/numpy,madphysicist/numpy,jorisvandenbossche/numpy,madphysicist/numpy,pizzathief/numpy,WarrenWeckesser/numpy,simongibbons/numpy,madphysicist/numpy,mattip/numpy,endolith/numpy,numpy/numpy,endolith/numpy,mattip/numpy,simongibbons/numpy,shoyer/numpy,anntzer/numpy,jorisvandenbossche/numpy,MSeifert04/numpy,jakirkham/numpy,pbrod/numpy,simongibbons/numpy,anntzer/numpy,rgommers/numpy,endolith/numpy,anntzer/numpy,jakirkham/numpy,simongibbons/numpy,pdebuyl/numpy,madphysicist/numpy,charris/numpy,mhvk/numpy,grlee77/numpy,charris/numpy,jorisvandenbossche/numpy,seberg/numpy,rgommers/numpy,grlee77/numpy,WarrenWeckesser/numpy,pizzathief/numpy,abalkin/numpy,numpy/numpy | restructuredtext | ## Code Before:
.. _governance-people:
Current steering council and institutional partners
===================================================
Steering council
----------------
* Sebastian Berg
* Jaime Fernández del Río
* Ralf Gommers
* Charles Harris
* Nathaniel Smith
* Julian Taylor
* Pauli Virtanen
* Eric Wieser
* Marten van Kerkwijk
* Stephan Hoyer
* Allan Haldane
* Stefan van der Walt
Emeritus members
----------------
* Travis Oliphant - Project Founder / Emeritus Leader (served: 2005-2012)
* Alex Griffing (served: 2015-2017)
NumFOCUS Subcommittee
---------------------
* Chuck Harris
* Ralf Gommers
* Jaime Fernández del Río
* Nathaniel Smith
* External member: Thomas Caswell
Institutional Partners
----------------------
* UC Berkeley (Stefan van der Walt, Matti Picus, Tyler Reddy)
* Quansight (Ralf Gommers, Hameer Abbasi)
## Instruction:
DOC: Add Sebastian Berg as sponsored by BIDS
## Code After:
.. _governance-people:
Current steering council and institutional partners
===================================================
Steering council
----------------
* Sebastian Berg
* Jaime Fernández del Río
* Ralf Gommers
* Charles Harris
* Nathaniel Smith
* Julian Taylor
* Pauli Virtanen
* Eric Wieser
* Marten van Kerkwijk
* Stephan Hoyer
* Allan Haldane
* Stefan van der Walt
Emeritus members
----------------
* Travis Oliphant - Project Founder / Emeritus Leader (served: 2005-2012)
* Alex Griffing (served: 2015-2017)
NumFOCUS Subcommittee
---------------------
* Chuck Harris
* Ralf Gommers
* Jaime Fernández del Río
* Nathaniel Smith
* External member: Thomas Caswell
Institutional Partners
----------------------
* UC Berkeley (Stefan van der Walt, Matti Picus, Tyler Reddy, Sebastian Berg)
* Quansight (Ralf Gommers, Hameer Abbasi)
| .. _governance-people:
Current steering council and institutional partners
===================================================
Steering council
----------------
* Sebastian Berg
* Jaime Fernández del Río
* Ralf Gommers
* Charles Harris
* Nathaniel Smith
* Julian Taylor
* Pauli Virtanen
* Eric Wieser
* Marten van Kerkwijk
* Stephan Hoyer
* Allan Haldane
* Stefan van der Walt
Emeritus members
----------------
* Travis Oliphant - Project Founder / Emeritus Leader (served: 2005-2012)
* Alex Griffing (served: 2015-2017)
NumFOCUS Subcommittee
---------------------
* Chuck Harris
* Ralf Gommers
* Jaime Fernández del Río
* Nathaniel Smith
* External member: Thomas Caswell
Institutional Partners
----------------------
- * UC Berkeley (Stefan van der Walt, Matti Picus, Tyler Reddy)
+ * UC Berkeley (Stefan van der Walt, Matti Picus, Tyler Reddy, Sebastian Berg)
? ++++++++++++++++
* Quansight (Ralf Gommers, Hameer Abbasi)
| 2 | 0.032258 | 1 | 1 |
15a0632e4eca073b2ab8fa2729c3ffb31b782e3b | docs/breaking_changes.md | docs/breaking_changes.md | A list of known limitations and behavior changes when using HTML2JS:
## Common
- Relative URLs
- URLs in CSS are not relativized like they were as HTML documents
- Polymer.ResolveUrl doesn't have relative URL information
- Polymer.importHref uses HTML Imports and is not supported.
- most users should switch to using [dynamic imports](https://github.com/tc39/proposal-dynamic-import)
- uses that must have HTML Imports should ensure they're loading the polyfill
and use the [imperative API](https://stackoverflow.com/a/21649225/101).
- `'use strict'` is implied in modules code
- e.g. assigning to an undeclared variable is an error
## Rare
- ElementClass.template
- this is a rarely used static property on the element class. when the template
is defined using a dom-module it is an HTMLTemplateElement, but after inlining it is a string.
- `document.currentScript`
- this was a way to get access to the script element of the currently executing
script. it is `null` in a module.
| A list of known limitations and behavior changes when using HTML2JS:
## Common
- Relative URLs
- URLs in CSS are not relativized like they were as HTML documents
- Polymer.ResolveUrl doesn't have relative URL information
- Polymer.importHref uses HTML Imports and is not supported.
- most users should switch to using [dynamic imports](https://github.com/tc39/proposal-dynamic-import)
- uses that must have HTML Imports should ensure they're loading the polyfill
and use the [imperative API](https://stackoverflow.com/a/21649225/101).
- `'use strict'` is implied in modules code
- e.g. assigning to an undeclared variable is an error
## Rare
- Evaluation order
- An HTML Import could interleave HTML with JS. html2js injects all HTML into the document first, then it runs the rest of the script in the file.
- JS Modules are deferred, so they run after all HTML has been parsed, and `document.write` is a noop.
- ElementClass.template
- this is a rarely used static property on the element class. when the template
is defined using a `<dom-module>` it is an HTMLTemplateElement, but after inlining it is a string.
- `document.currentScript`
- this was a way to get access to the script element of the currently executing
script. it is `null` in a module.
| Document a few more breaking changes | Document a few more breaking changes | Markdown | bsd-3-clause | Polymer/tools,Polymer/tools,Polymer/tools,Polymer/tools | markdown | ## Code Before:
A list of known limitations and behavior changes when using HTML2JS:
## Common
- Relative URLs
- URLs in CSS are not relativized like they were as HTML documents
- Polymer.ResolveUrl doesn't have relative URL information
- Polymer.importHref uses HTML Imports and is not supported.
- most users should switch to using [dynamic imports](https://github.com/tc39/proposal-dynamic-import)
- uses that must have HTML Imports should ensure they're loading the polyfill
and use the [imperative API](https://stackoverflow.com/a/21649225/101).
- `'use strict'` is implied in modules code
- e.g. assigning to an undeclared variable is an error
## Rare
- ElementClass.template
- this is a rarely used static property on the element class. when the template
is defined using a dom-module it is an HTMLTemplateElement, but after inlining it is a string.
- `document.currentScript`
- this was a way to get access to the script element of the currently executing
script. it is `null` in a module.
## Instruction:
Document a few more breaking changes
## Code After:
A list of known limitations and behavior changes when using HTML2JS:
## Common
- Relative URLs
- URLs in CSS are not relativized like they were as HTML documents
- Polymer.ResolveUrl doesn't have relative URL information
- Polymer.importHref uses HTML Imports and is not supported.
- most users should switch to using [dynamic imports](https://github.com/tc39/proposal-dynamic-import)
- uses that must have HTML Imports should ensure they're loading the polyfill
and use the [imperative API](https://stackoverflow.com/a/21649225/101).
- `'use strict'` is implied in modules code
- e.g. assigning to an undeclared variable is an error
## Rare
- Evaluation order
- An HTML Import could interleave HTML with JS. html2js injects all HTML into the document first, then it runs the rest of the script in the file.
- JS Modules are deferred, so they run after all HTML has been parsed, and `document.write` is a noop.
- ElementClass.template
- this is a rarely used static property on the element class. when the template
is defined using a `<dom-module>` it is an HTMLTemplateElement, but after inlining it is a string.
- `document.currentScript`
- this was a way to get access to the script element of the currently executing
script. it is `null` in a module.
| A list of known limitations and behavior changes when using HTML2JS:
## Common
- Relative URLs
- URLs in CSS are not relativized like they were as HTML documents
- Polymer.ResolveUrl doesn't have relative URL information
- Polymer.importHref uses HTML Imports and is not supported.
- most users should switch to using [dynamic imports](https://github.com/tc39/proposal-dynamic-import)
- uses that must have HTML Imports should ensure they're loading the polyfill
and use the [imperative API](https://stackoverflow.com/a/21649225/101).
- `'use strict'` is implied in modules code
- e.g. assigning to an undeclared variable is an error
## Rare
+ - Evaluation order
+ - An HTML Import could interleave HTML with JS. html2js injects all HTML into the document first, then it runs the rest of the script in the file.
+ - JS Modules are deferred, so they run after all HTML has been parsed, and `document.write` is a noop.
+
- ElementClass.template
- this is a rarely used static property on the element class. when the template
- is defined using a dom-module it is an HTMLTemplateElement, but after inlining it is a string.
+ is defined using a `<dom-module>` it is an HTMLTemplateElement, but after inlining it is a string.
? ++ ++
- `document.currentScript`
- this was a way to get access to the script element of the currently executing
script. it is `null` in a module. | 6 | 0.24 | 5 | 1 |
8e6eb00286f160e1e02fd971f2db67b6f2d01b98 | app/templates/components/task-list.html | app/templates/components/task-list.html | {% macro task_list_item(completed, label, link) %}
<li class="task-list-item">
<span aria-describedby="{{ label|id_safe }}"><a class="govuk-link govuk-link--no-visited-state" href="{{ link }}">{{ label }}</a></span>
{% if completed %}
<strong class="task-list-indicator-completed" id="{{ label|id_safe }}">Completed</strong>
{% else %}
<strong class="task-list-indicator-not-completed" id="{{ label|id_safe }}">Not completed</strong>
{% endif %}
</li>
{% endmacro %}
{% macro task_list_wrapper() %}
<ul class="task-list">
{{ caller() }}
</ul>
{% endmacro %}
| {% macro task_list_item(completed, label, link) %}
<li class="task-list-item">
<span aria-describedby="{{ label|id_safe }}"><a class="govuk-link govuk-link--no-visited-state" href="{{ link }}">{{ label }}</a></span>
{% if completed %}
<strong class="task-list-indicator-completed" id="{{ label|id_safe }}">Completed</strong>
{% else %}
<strong class="task-list-indicator-not-completed" id="{{ label|id_safe }}">Not completed</strong>
{% endif %}
</li>
{% endmacro %}
{% macro task_list_wrapper() %}
<ul class="govuk-list task-list">
{{ caller() }}
</ul>
{% endmacro %}
| Fix list in task list | Fix list in task list
Needs the `govuk-list` class to reset its default
list-styling so there are no bullets and no
additional spacing.
| HTML | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | html | ## Code Before:
{% macro task_list_item(completed, label, link) %}
<li class="task-list-item">
<span aria-describedby="{{ label|id_safe }}"><a class="govuk-link govuk-link--no-visited-state" href="{{ link }}">{{ label }}</a></span>
{% if completed %}
<strong class="task-list-indicator-completed" id="{{ label|id_safe }}">Completed</strong>
{% else %}
<strong class="task-list-indicator-not-completed" id="{{ label|id_safe }}">Not completed</strong>
{% endif %}
</li>
{% endmacro %}
{% macro task_list_wrapper() %}
<ul class="task-list">
{{ caller() }}
</ul>
{% endmacro %}
## Instruction:
Fix list in task list
Needs the `govuk-list` class to reset its default
list-styling so there are no bullets and no
additional spacing.
## Code After:
{% macro task_list_item(completed, label, link) %}
<li class="task-list-item">
<span aria-describedby="{{ label|id_safe }}"><a class="govuk-link govuk-link--no-visited-state" href="{{ link }}">{{ label }}</a></span>
{% if completed %}
<strong class="task-list-indicator-completed" id="{{ label|id_safe }}">Completed</strong>
{% else %}
<strong class="task-list-indicator-not-completed" id="{{ label|id_safe }}">Not completed</strong>
{% endif %}
</li>
{% endmacro %}
{% macro task_list_wrapper() %}
<ul class="govuk-list task-list">
{{ caller() }}
</ul>
{% endmacro %}
| {% macro task_list_item(completed, label, link) %}
<li class="task-list-item">
<span aria-describedby="{{ label|id_safe }}"><a class="govuk-link govuk-link--no-visited-state" href="{{ link }}">{{ label }}</a></span>
{% if completed %}
<strong class="task-list-indicator-completed" id="{{ label|id_safe }}">Completed</strong>
{% else %}
<strong class="task-list-indicator-not-completed" id="{{ label|id_safe }}">Not completed</strong>
{% endif %}
</li>
{% endmacro %}
{% macro task_list_wrapper() %}
- <ul class="task-list">
+ <ul class="govuk-list task-list">
? +++++++++++
{{ caller() }}
</ul>
{% endmacro %} | 2 | 0.125 | 1 | 1 |
3fe99c3cc5b44ebc463ed36b07bf2ad4b214af76 | lib/hanoi.rb | lib/hanoi.rb | class Hanoi
class Board
def initialize(num_disks)
end
def towers
[1, 2, 3]
end
end
end
| class Hanoi
class Board
def initialize(num_disks)
end
def towers
[1, 2, 3]
end
end
class Tower
end
end
| Test update now fails correctly | Test update now fails correctly
| Ruby | mit | elight/hanoi | ruby | ## Code Before:
class Hanoi
class Board
def initialize(num_disks)
end
def towers
[1, 2, 3]
end
end
end
## Instruction:
Test update now fails correctly
## Code After:
class Hanoi
class Board
def initialize(num_disks)
end
def towers
[1, 2, 3]
end
end
class Tower
end
end
| class Hanoi
class Board
def initialize(num_disks)
end
def towers
[1, 2, 3]
end
end
+
+ class Tower
+ end
end | 3 | 0.3 | 3 | 0 |
ed4f311bc48d3a0557b0d9ff861414ee3b94d34e | en/developers.html | en/developers.html | ---
layout: default
title: Mu Development
i18n: en
---
<h1>Mu Development</h1>
<p>Would you like to contribute to the development of Mu? (If you think this
is only something for experienced developers, please reconsider, there are
plenty of ways to contribute to Mu, no matter your level of experience or
skill set).</p>
<p>Our technical documentation is hosted on the wonderful
service that is <a href="https://mu.readthedocs.io/en/latest/" target="_blank">Read the
Docs (http://mu.readthedocs.io/)</a>.</p>
<p>Not only does it contain details needed in order to make code
contributions to Mu, but it outlines plenty of other ways in which you can
contribute (including making updates to this website). Finally it provides a
guide to our processes and expectations for the various types of contribution
you can make to Mu.</p>
<p>If in doubt, just <a href="/en/discuss">ask in our discussion area</a> and
someone will be able to point you in the right direction.</p>
| ---
layout: default
title: Mu Development
i18n: en
---
<h1>Mu Development</h1>
<p>Would you like to contribute to the development of Mu? (If you think this
is only something for experienced developers, please reconsider, there are
plenty of ways to contribute to Mu, no matter your level of experience or
skill set).</p>
<p>Our technical documentation is hosted on the wonderful
service that is <a href="https://mu.readthedocs.io/en/latest/" target="_blank">Read the
Docs (http://mu.readthedocs.io/)</a>. Not only does it contain details needed
in order to make code
contributions to Mu, but it outlines plenty of other ways in which you can
contribute (including making updates to this website). Finally it provides a
guide to our processes and expectations for the various types of contribution
you can make to Mu.</p>
<p>The source code is <a href="https://github.com/mu-editor/mu">hosted on
GitHub</a>.</p>
<p>If in doubt, just <a href="/en/discuss">ask in our discussion area</a> and
someone will be able to point you in the right direction.</p>
| Add link to source code in developer page. | Add link to source code in developer page.
| HTML | mit | mu-editor/mu-editor.github.io,mu-editor/mu-editor.github.io,mu-editor/mu-editor.github.io | html | ## Code Before:
---
layout: default
title: Mu Development
i18n: en
---
<h1>Mu Development</h1>
<p>Would you like to contribute to the development of Mu? (If you think this
is only something for experienced developers, please reconsider, there are
plenty of ways to contribute to Mu, no matter your level of experience or
skill set).</p>
<p>Our technical documentation is hosted on the wonderful
service that is <a href="https://mu.readthedocs.io/en/latest/" target="_blank">Read the
Docs (http://mu.readthedocs.io/)</a>.</p>
<p>Not only does it contain details needed in order to make code
contributions to Mu, but it outlines plenty of other ways in which you can
contribute (including making updates to this website). Finally it provides a
guide to our processes and expectations for the various types of contribution
you can make to Mu.</p>
<p>If in doubt, just <a href="/en/discuss">ask in our discussion area</a> and
someone will be able to point you in the right direction.</p>
## Instruction:
Add link to source code in developer page.
## Code After:
---
layout: default
title: Mu Development
i18n: en
---
<h1>Mu Development</h1>
<p>Would you like to contribute to the development of Mu? (If you think this
is only something for experienced developers, please reconsider, there are
plenty of ways to contribute to Mu, no matter your level of experience or
skill set).</p>
<p>Our technical documentation is hosted on the wonderful
service that is <a href="https://mu.readthedocs.io/en/latest/" target="_blank">Read the
Docs (http://mu.readthedocs.io/)</a>. Not only does it contain details needed
in order to make code
contributions to Mu, but it outlines plenty of other ways in which you can
contribute (including making updates to this website). Finally it provides a
guide to our processes and expectations for the various types of contribution
you can make to Mu.</p>
<p>The source code is <a href="https://github.com/mu-editor/mu">hosted on
GitHub</a>.</p>
<p>If in doubt, just <a href="/en/discuss">ask in our discussion area</a> and
someone will be able to point you in the right direction.</p>
| ---
layout: default
title: Mu Development
i18n: en
---
<h1>Mu Development</h1>
<p>Would you like to contribute to the development of Mu? (If you think this
is only something for experienced developers, please reconsider, there are
plenty of ways to contribute to Mu, no matter your level of experience or
skill set).</p>
<p>Our technical documentation is hosted on the wonderful
service that is <a href="https://mu.readthedocs.io/en/latest/" target="_blank">Read the
+ Docs (http://mu.readthedocs.io/)</a>. Not only does it contain details needed
+ in order to make code
- Docs (http://mu.readthedocs.io/)</a>.</p>
-
- <p>Not only does it contain details needed in order to make code
contributions to Mu, but it outlines plenty of other ways in which you can
contribute (including making updates to this website). Finally it provides a
guide to our processes and expectations for the various types of contribution
you can make to Mu.</p>
+ <p>The source code is <a href="https://github.com/mu-editor/mu">hosted on
+ GitHub</a>.</p>
+
<p>If in doubt, just <a href="/en/discuss">ask in our discussion area</a> and
someone will be able to point you in the right direction.</p> | 8 | 0.32 | 5 | 3 |
f242d10bd9c4f9189407d685429ee40958e9deb9 | app/views/appointment_summaries/create.html.erb | app/views/appointment_summaries/create.html.erb | <h2>Done!</h2>
<p>Appointment details have been saved. An output document will be printed and dispatched to the
customer shortly.</p>
<p style='padding-top: 1em'><%= link_to 'Generate another', root_path, class: %w(btn-success btn-lg) %></p>
| <h2>Done!</h2>
<p>Appointment details have been saved. A Pension Wise Summary Document will be printed and dispatched to the
customer shortly.</p>
<p style='padding-top: 1em'><%= link_to 'Generate another', root_path, class: %w(btn-success btn-lg) %></p>
| Use the term ‘Summary Document’ | Use the term ‘Summary Document’ | HTML+ERB | mit | guidance-guarantee-programme/output,guidance-guarantee-programme/output,guidance-guarantee-programme/output | html+erb | ## Code Before:
<h2>Done!</h2>
<p>Appointment details have been saved. An output document will be printed and dispatched to the
customer shortly.</p>
<p style='padding-top: 1em'><%= link_to 'Generate another', root_path, class: %w(btn-success btn-lg) %></p>
## Instruction:
Use the term ‘Summary Document’
## Code After:
<h2>Done!</h2>
<p>Appointment details have been saved. A Pension Wise Summary Document will be printed and dispatched to the
customer shortly.</p>
<p style='padding-top: 1em'><%= link_to 'Generate another', root_path, class: %w(btn-success btn-lg) %></p>
| <h2>Done!</h2>
- <p>Appointment details have been saved. An output document will be printed and dispatched to the
? ^ ^^^^ ^
+ <p>Appointment details have been saved. A Pension Wise Summary Document will be printed and dispatched to the
? +++++++ ^^^^^^ ^^^^^ ^
customer shortly.</p>
<p style='padding-top: 1em'><%= link_to 'Generate another', root_path, class: %w(btn-success btn-lg) %></p> | 2 | 0.333333 | 1 | 1 |
5438b11fcbc12944c0531fdda865b915bb25d745 | tips/package-managers/bower/register-component.md | tips/package-managers/bower/register-component.md | Tell bower how to find your component so others can use it as well.
To register a new package you must comply with the following:
- The package name must adhere to the bower.json spec.
- There must be a valid bower.json in the project’s root directory.
- Your package should use [semver](http://semver.org/) Git tags. The v prefix is allowed.
- Your package must be publicly available at a Git endpoint (e.g., GitHub).
- For private packages (e.g. GitHub Enterprise), please consider running a private Bower registry.
### Syntax
bower install <package-name> <git-endpoint>
| | Option | Description |
| :-----------: | ------------ | --------------------------------------------- |
| :exclamation: | package-name | The name of the package to be registered |
| :exclamation: | git-endpoint | The git endpoint where your package is hosted |
### Example
```bash
$ bower install cloudine https://www.github.com/weirdpattern/cloudine.git
```
### References
Bower Creating Packages \([https://bower.io/docs/creating-packages/#register](https://bower.io/docs/creating-packages/#register)\)
### Tags
[#tip](../../tips.md)
[#package-managers](../package-managers.md)
[#bower](bower.md) | Tell bower how to find your component so others can use it as well.
To register a new package you must comply with the following:
- The package name must adhere to the bower.json spec.
- There must be a valid bower.json in the project’s root directory.
- Your package should use [semver](http://semver.org/) Git tags. The v prefix is allowed.
- Your package must be publicly available at a Git endpoint (e.g., GitHub).
- For private packages (e.g. GitHub Enterprise), please consider running a private Bower registry.
### Syntax
```bash
bower install <package-name> <git-endpoint>
```
| | Option | Description |
| :-----------: | ------------ | --------------------------------------------- |
| :exclamation: | package-name | The name of the package to be registered |
| :exclamation: | git-endpoint | The git endpoint where your package is hosted |
### Example
```bash
$ bower install cloudine https://www.github.com/weirdpattern/cloudine.git
```
### References
Bower Creating Packages \([https://bower.io/docs/creating-packages/#register](https://bower.io/docs/creating-packages/#register)\)
### Tags
[#tip](../../tips.md)
[#package-managers](../package-managers.md)
[#bower](bower.md) | Add block scope to syntax | Add block scope to syntax
changelog:
tipit/
tips/
package-managers/
bower/
register-component.md
- Add block scope to syntax
| Markdown | mit | weirdpattern/tipit | markdown | ## Code Before:
Tell bower how to find your component so others can use it as well.
To register a new package you must comply with the following:
- The package name must adhere to the bower.json spec.
- There must be a valid bower.json in the project’s root directory.
- Your package should use [semver](http://semver.org/) Git tags. The v prefix is allowed.
- Your package must be publicly available at a Git endpoint (e.g., GitHub).
- For private packages (e.g. GitHub Enterprise), please consider running a private Bower registry.
### Syntax
bower install <package-name> <git-endpoint>
| | Option | Description |
| :-----------: | ------------ | --------------------------------------------- |
| :exclamation: | package-name | The name of the package to be registered |
| :exclamation: | git-endpoint | The git endpoint where your package is hosted |
### Example
```bash
$ bower install cloudine https://www.github.com/weirdpattern/cloudine.git
```
### References
Bower Creating Packages \([https://bower.io/docs/creating-packages/#register](https://bower.io/docs/creating-packages/#register)\)
### Tags
[#tip](../../tips.md)
[#package-managers](../package-managers.md)
[#bower](bower.md)
## Instruction:
Add block scope to syntax
changelog:
tipit/
tips/
package-managers/
bower/
register-component.md
- Add block scope to syntax
## Code After:
Tell bower how to find your component so others can use it as well.
To register a new package you must comply with the following:
- The package name must adhere to the bower.json spec.
- There must be a valid bower.json in the project’s root directory.
- Your package should use [semver](http://semver.org/) Git tags. The v prefix is allowed.
- Your package must be publicly available at a Git endpoint (e.g., GitHub).
- For private packages (e.g. GitHub Enterprise), please consider running a private Bower registry.
### Syntax
```bash
bower install <package-name> <git-endpoint>
```
| | Option | Description |
| :-----------: | ------------ | --------------------------------------------- |
| :exclamation: | package-name | The name of the package to be registered |
| :exclamation: | git-endpoint | The git endpoint where your package is hosted |
### Example
```bash
$ bower install cloudine https://www.github.com/weirdpattern/cloudine.git
```
### References
Bower Creating Packages \([https://bower.io/docs/creating-packages/#register](https://bower.io/docs/creating-packages/#register)\)
### Tags
[#tip](../../tips.md)
[#package-managers](../package-managers.md)
[#bower](bower.md) | Tell bower how to find your component so others can use it as well.
To register a new package you must comply with the following:
- The package name must adhere to the bower.json spec.
- There must be a valid bower.json in the project’s root directory.
- Your package should use [semver](http://semver.org/) Git tags. The v prefix is allowed.
- Your package must be publicly available at a Git endpoint (e.g., GitHub).
- For private packages (e.g. GitHub Enterprise), please consider running a private Bower registry.
### Syntax
+ ```bash
bower install <package-name> <git-endpoint>
+ ```
| | Option | Description |
| :-----------: | ------------ | --------------------------------------------- |
| :exclamation: | package-name | The name of the package to be registered |
| :exclamation: | git-endpoint | The git endpoint where your package is hosted |
### Example
```bash
$ bower install cloudine https://www.github.com/weirdpattern/cloudine.git
```
### References
Bower Creating Packages \([https://bower.io/docs/creating-packages/#register](https://bower.io/docs/creating-packages/#register)\)
### Tags
[#tip](../../tips.md)
[#package-managers](../package-managers.md)
[#bower](bower.md) | 2 | 0.071429 | 2 | 0 |
c52b959186218c5dac520e5af8a4bd8f32664d52 | spec/factories/miq_request.rb | spec/factories/miq_request.rb | FactoryGirl.define do
factory :miq_request do
requester { create(:user) }
factory :miq_host_provision_request, :class => "MiqHostProvisionRequest"
factory :service_reconfigure_request, :class => "ServiceReconfigureRequest"
factory :service_template_provision_request, :class => "ServiceTemplateProvisionRequest" do
source { create(:service_template) }
end
factory :vm_migrate_request, :class => "VmMigrateRequest"
factory :vm_reconfigure_request, :class => "VmReconfigureRequest"
factory :miq_provision_request, :class => "MiqProvisionRequest" do
source { create(:miq_template) }
end
end
end
| FactoryGirl.define do
factory :miq_request do
requester { create(:user) }
factory :miq_host_provision_request, :class => "MiqHostProvisionRequest"
factory :service_reconfigure_request, :class => "ServiceReconfigureRequest"
factory :service_template_provision_request, :class => "ServiceTemplateProvisionRequest" do
source { create(:service_template) }
end
factory :vm_migrate_request, :class => "VmMigrateRequest"
factory :vm_reconfigure_request, :class => "VmReconfigureRequest"
factory :miq_provision_request, :class => "MiqProvisionRequest" do
source { create(:miq_template) }
end
trait :with_approval do
transient do
reason ""
end
after(:create) do |request, evaluator|
request.miq_approvals << FactoryGirl.create(:miq_approval, :reason => evaluator.reason)
end
end
end
end
| Add MiqRequest factory with MiqApproval | Add MiqRequest factory with MiqApproval
| Ruby | apache-2.0 | hstastna/manageiq,chessbyte/manageiq,lpichler/manageiq,NickLaMuro/manageiq,aufi/manageiq,aufi/manageiq,agrare/manageiq,tinaafitz/manageiq,borod108/manageiq,tinaafitz/manageiq,skateman/manageiq,djberg96/manageiq,d-m-u/manageiq,jameswnl/manageiq,romanblanco/manageiq,kbrock/manageiq,jvlcek/manageiq,skateman/manageiq,gerikis/manageiq,jrafanie/manageiq,billfitzgerald0120/manageiq,NickLaMuro/manageiq,lpichler/manageiq,agrare/manageiq,gmcculloug/manageiq,hstastna/manageiq,mzazrivec/manageiq,juliancheal/manageiq,mzazrivec/manageiq,lpichler/manageiq,borod108/manageiq,andyvesel/manageiq,lpichler/manageiq,NickLaMuro/manageiq,chessbyte/manageiq,tinaafitz/manageiq,pkomanek/manageiq,mkanoor/manageiq,juliancheal/manageiq,yaacov/manageiq,borod108/manageiq,jrafanie/manageiq,ManageIQ/manageiq,jvlcek/manageiq,gmcculloug/manageiq,billfitzgerald0120/manageiq,skateman/manageiq,mkanoor/manageiq,syncrou/manageiq,djberg96/manageiq,branic/manageiq,djberg96/manageiq,jrafanie/manageiq,skateman/manageiq,mzazrivec/manageiq,kbrock/manageiq,pkomanek/manageiq,branic/manageiq,jvlcek/manageiq,romanblanco/manageiq,chessbyte/manageiq,syncrou/manageiq,andyvesel/manageiq,borod108/manageiq,romanblanco/manageiq,d-m-u/manageiq,djberg96/manageiq,kbrock/manageiq,jrafanie/manageiq,ManageIQ/manageiq,pkomanek/manageiq,gerikis/manageiq,gmcculloug/manageiq,mkanoor/manageiq,ManageIQ/manageiq,jameswnl/manageiq,agrare/manageiq,d-m-u/manageiq,jameswnl/manageiq,mzazrivec/manageiq,hstastna/manageiq,kbrock/manageiq,jameswnl/manageiq,yaacov/manageiq,branic/manageiq,ManageIQ/manageiq,mkanoor/manageiq,tinaafitz/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,d-m-u/manageiq,andyvesel/manageiq,NickLaMuro/manageiq,agrare/manageiq,andyvesel/manageiq,juliancheal/manageiq,jvlcek/manageiq,pkomanek/manageiq,romanblanco/manageiq,juliancheal/manageiq,aufi/manageiq,syncrou/manageiq,gmcculloug/manageiq,syncrou/manageiq,branic/manageiq,gerikis/manageiq,hstastna/manageiq,gerikis/manageiq,chessbyte/manageiq,yaacov/manageiq,billfitzgerald0120/manageiq,aufi/manageiq | ruby | ## Code Before:
FactoryGirl.define do
factory :miq_request do
requester { create(:user) }
factory :miq_host_provision_request, :class => "MiqHostProvisionRequest"
factory :service_reconfigure_request, :class => "ServiceReconfigureRequest"
factory :service_template_provision_request, :class => "ServiceTemplateProvisionRequest" do
source { create(:service_template) }
end
factory :vm_migrate_request, :class => "VmMigrateRequest"
factory :vm_reconfigure_request, :class => "VmReconfigureRequest"
factory :miq_provision_request, :class => "MiqProvisionRequest" do
source { create(:miq_template) }
end
end
end
## Instruction:
Add MiqRequest factory with MiqApproval
## Code After:
FactoryGirl.define do
factory :miq_request do
requester { create(:user) }
factory :miq_host_provision_request, :class => "MiqHostProvisionRequest"
factory :service_reconfigure_request, :class => "ServiceReconfigureRequest"
factory :service_template_provision_request, :class => "ServiceTemplateProvisionRequest" do
source { create(:service_template) }
end
factory :vm_migrate_request, :class => "VmMigrateRequest"
factory :vm_reconfigure_request, :class => "VmReconfigureRequest"
factory :miq_provision_request, :class => "MiqProvisionRequest" do
source { create(:miq_template) }
end
trait :with_approval do
transient do
reason ""
end
after(:create) do |request, evaluator|
request.miq_approvals << FactoryGirl.create(:miq_approval, :reason => evaluator.reason)
end
end
end
end
| FactoryGirl.define do
factory :miq_request do
requester { create(:user) }
factory :miq_host_provision_request, :class => "MiqHostProvisionRequest"
factory :service_reconfigure_request, :class => "ServiceReconfigureRequest"
factory :service_template_provision_request, :class => "ServiceTemplateProvisionRequest" do
source { create(:service_template) }
end
factory :vm_migrate_request, :class => "VmMigrateRequest"
factory :vm_reconfigure_request, :class => "VmReconfigureRequest"
factory :miq_provision_request, :class => "MiqProvisionRequest" do
source { create(:miq_template) }
end
+
+ trait :with_approval do
+ transient do
+ reason ""
+ end
+
+ after(:create) do |request, evaluator|
+ request.miq_approvals << FactoryGirl.create(:miq_approval, :reason => evaluator.reason)
+ end
+ end
end
end | 10 | 0.625 | 10 | 0 |
64eb3a7bb20730001c4c47d7f2ed768ba2d7f90b | src/tray.js | src/tray.js | 'use strict'
void (function () {
const remote = require('remote')
const Tray = remote.require('tray')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')
const dialog = remote.require('dialog')
const ipc = require('ipc')
const grunt = require('./lib/Grunt')
// Set up tray menu.
let tray = new Tray('IconTemplate.png')
let trayMenu = new Menu()
trayMenu.append(new MenuItem({
label: window.localStorage.getItem('current'),
click: function () {
dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) {
if (dir !== undefined) {
window.localStorage.setItem('current', dir)
}
})
}
}))
trayMenu.append(new MenuItem({type: 'separator'}))
grunt.getTasks()
.then(function (tasks) {
for (let task of tasks) {
trayMenu.append(new MenuItem({
label: task,
click: function () {
grunt.runTask(task)
}
}))
}
trayMenu.append(new MenuItem({type: 'separator'}))
trayMenu.append(new MenuItem({
label: 'Quit',
click: function () {
ipc.send('app-quit')
}
}))
tray.setContextMenu(trayMenu)
})
})()
| 'use strict'
void (function () {
const remote = require('remote')
const Tray = remote.require('tray')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')
const dialog = remote.require('dialog')
const ipc = require('ipc')
const grunt = require('./lib/Grunt')
// Set up tray menu.
let tray = new Tray('IconTemplate.png')
let trayMenu = new Menu()
build()
function build () {
trayMenu.append(new MenuItem({
label: window.localStorage.getItem('current'),
click: function () {
dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) {
if (dir !== undefined) {
window.localStorage.setItem('current', dir)
}
})
}
}))
trayMenu.append(new MenuItem({type: 'separator'}))
grunt.getTasks()
.then(function (tasks) {
for (let task of tasks) {
let item = {
label: task,
click: function () {
grunt.runTask(task, function () {
// Rebuild menu
trayMenu = new Menu()
build()
})
}
}
if (global.processes[task]) {
item.icon = 'running.png'
}
trayMenu.append(new MenuItem(item))
}
trayMenu.append(new MenuItem({type: 'separator'}))
trayMenu.append(new MenuItem({
label: 'Quit',
click: function () {
ipc.send('app-quit')
}
}))
trayMenu.items[0].label = ':D'
tray.setContextMenu(trayMenu)
})
}
})()
| Make sure we can rebuild the menu | Make sure we can rebuild the menu
| JavaScript | mit | jenslind/piglet,jenslind/piglet | javascript | ## Code Before:
'use strict'
void (function () {
const remote = require('remote')
const Tray = remote.require('tray')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')
const dialog = remote.require('dialog')
const ipc = require('ipc')
const grunt = require('./lib/Grunt')
// Set up tray menu.
let tray = new Tray('IconTemplate.png')
let trayMenu = new Menu()
trayMenu.append(new MenuItem({
label: window.localStorage.getItem('current'),
click: function () {
dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) {
if (dir !== undefined) {
window.localStorage.setItem('current', dir)
}
})
}
}))
trayMenu.append(new MenuItem({type: 'separator'}))
grunt.getTasks()
.then(function (tasks) {
for (let task of tasks) {
trayMenu.append(new MenuItem({
label: task,
click: function () {
grunt.runTask(task)
}
}))
}
trayMenu.append(new MenuItem({type: 'separator'}))
trayMenu.append(new MenuItem({
label: 'Quit',
click: function () {
ipc.send('app-quit')
}
}))
tray.setContextMenu(trayMenu)
})
})()
## Instruction:
Make sure we can rebuild the menu
## Code After:
'use strict'
void (function () {
const remote = require('remote')
const Tray = remote.require('tray')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')
const dialog = remote.require('dialog')
const ipc = require('ipc')
const grunt = require('./lib/Grunt')
// Set up tray menu.
let tray = new Tray('IconTemplate.png')
let trayMenu = new Menu()
build()
function build () {
trayMenu.append(new MenuItem({
label: window.localStorage.getItem('current'),
click: function () {
dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) {
if (dir !== undefined) {
window.localStorage.setItem('current', dir)
}
})
}
}))
trayMenu.append(new MenuItem({type: 'separator'}))
grunt.getTasks()
.then(function (tasks) {
for (let task of tasks) {
let item = {
label: task,
click: function () {
grunt.runTask(task, function () {
// Rebuild menu
trayMenu = new Menu()
build()
})
}
}
if (global.processes[task]) {
item.icon = 'running.png'
}
trayMenu.append(new MenuItem(item))
}
trayMenu.append(new MenuItem({type: 'separator'}))
trayMenu.append(new MenuItem({
label: 'Quit',
click: function () {
ipc.send('app-quit')
}
}))
trayMenu.items[0].label = ':D'
tray.setContextMenu(trayMenu)
})
}
})()
| 'use strict'
void (function () {
const remote = require('remote')
const Tray = remote.require('tray')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')
const dialog = remote.require('dialog')
const ipc = require('ipc')
const grunt = require('./lib/Grunt')
// Set up tray menu.
let tray = new Tray('IconTemplate.png')
let trayMenu = new Menu()
+ build()
+
+ function build () {
- trayMenu.append(new MenuItem({
+ trayMenu.append(new MenuItem({
? ++
- label: window.localStorage.getItem('current'),
+ label: window.localStorage.getItem('current'),
? ++
- click: function () {
+ click: function () {
? ++
- dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) {
+ dialog.showOpenDialog({ properties: ['openDirectory']}, function (dir) {
? ++
- if (dir !== undefined) {
+ if (dir !== undefined) {
? ++
- window.localStorage.setItem('current', dir)
+ window.localStorage.setItem('current', dir)
? ++
+ }
+ })
+ }
+ }))
+
+ trayMenu.append(new MenuItem({type: 'separator'}))
+
+ grunt.getTasks()
+ .then(function (tasks) {
+ for (let task of tasks) {
+ let item = {
+ label: task,
+ click: function () {
+ grunt.runTask(task, function () {
+ // Rebuild menu
+ trayMenu = new Menu()
+ build()
+ })
+ }
+ }
+
+ if (global.processes[task]) {
+ item.icon = 'running.png'
+ }
+
+ trayMenu.append(new MenuItem(item))
}
- })
- }
- }))
- trayMenu.append(new MenuItem({type: 'separator'}))
+ trayMenu.append(new MenuItem({type: 'separator'}))
? ++++++
- grunt.getTasks()
- .then(function (tasks) {
- for (let task of tasks) {
trayMenu.append(new MenuItem({
- label: task,
? ^^^
+ label: 'Quit',
? ++++ ^
click: function () {
- grunt.runTask(task)
+ ipc.send('app-quit')
}
}))
- }
- trayMenu.append(new MenuItem({type: 'separator'}))
+ trayMenu.items[0].label = ':D'
- trayMenu.append(new MenuItem({
- label: 'Quit',
- click: function () {
- ipc.send('app-quit')
- }
- }))
-
- tray.setContextMenu(trayMenu)
+ tray.setContextMenu(trayMenu)
? ++
- })
+ })
? ++
+ }
})() | 68 | 1.333333 | 42 | 26 |
6854323889aa724c964b3b466fea090987aa8cdc | notify.js | notify.js | var request = require('./request');
var config = require('./config');
var notifierVersion = require('./version').notifierVersion;
function merge(target, obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
target[key] = obj[key];
}
}
return target;
}
function notify(err, options) {
if (!options) options = {};
request(config.endpoint, {
payloadVersion: '3',
notifierVersion: notifierVersion,
apiKey: config.apiKey,
projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host,
context: config.context || window.location.pathname,
user: config.user,
metaData: merge({}, merge(options.metaData || {}, config.metaData)),
releaseStage: config.releaseStage,
appVersion: config.appVersion,
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: options.severity || config.severity,
name: err.name,
message: err.message,
stacktrace: err.stack || err.backtrace || err.stacktrace,
file: err.fileName || err.sourceURL,
lineNumber: -1,
columnNumber: -1,
breadcrumbs: []
});
}
module.exports = notify;
| var request = require('./request');
var config = require('./config');
var notifierVersion = require('./version').notifierVersion;
function merge(target, obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
target[key] = obj[key];
}
}
return target;
}
function notify(err, options) {
if (!options) options = {};
request(config.endpoint, {
payloadVersion: '3',
notifierVersion: notifierVersion,
apiKey: config.apiKey,
projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host,
context: config.context || window.location.pathname,
user: config.user,
metaData: merge(merge({}, config.metaData), config.metaData || {}),
releaseStage: config.releaseStage,
appVersion: config.appVersion,
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: options.severity || config.severity,
name: err.name,
message: err.message,
stacktrace: err.stack || err.backtrace || err.stacktrace,
file: err.fileName || err.sourceURL,
lineNumber: -1,
columnNumber: -1,
breadcrumbs: []
});
}
module.exports = notify;
| Add support for overriding global metaData | Add support for overriding global metaData
| JavaScript | mit | jacobmarshall-pkg/bugsnag-js | javascript | ## Code Before:
var request = require('./request');
var config = require('./config');
var notifierVersion = require('./version').notifierVersion;
function merge(target, obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
target[key] = obj[key];
}
}
return target;
}
function notify(err, options) {
if (!options) options = {};
request(config.endpoint, {
payloadVersion: '3',
notifierVersion: notifierVersion,
apiKey: config.apiKey,
projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host,
context: config.context || window.location.pathname,
user: config.user,
metaData: merge({}, merge(options.metaData || {}, config.metaData)),
releaseStage: config.releaseStage,
appVersion: config.appVersion,
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: options.severity || config.severity,
name: err.name,
message: err.message,
stacktrace: err.stack || err.backtrace || err.stacktrace,
file: err.fileName || err.sourceURL,
lineNumber: -1,
columnNumber: -1,
breadcrumbs: []
});
}
module.exports = notify;
## Instruction:
Add support for overriding global metaData
## Code After:
var request = require('./request');
var config = require('./config');
var notifierVersion = require('./version').notifierVersion;
function merge(target, obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
target[key] = obj[key];
}
}
return target;
}
function notify(err, options) {
if (!options) options = {};
request(config.endpoint, {
payloadVersion: '3',
notifierVersion: notifierVersion,
apiKey: config.apiKey,
projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host,
context: config.context || window.location.pathname,
user: config.user,
metaData: merge(merge({}, config.metaData), config.metaData || {}),
releaseStage: config.releaseStage,
appVersion: config.appVersion,
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: options.severity || config.severity,
name: err.name,
message: err.message,
stacktrace: err.stack || err.backtrace || err.stacktrace,
file: err.fileName || err.sourceURL,
lineNumber: -1,
columnNumber: -1,
breadcrumbs: []
});
}
module.exports = notify;
| var request = require('./request');
var config = require('./config');
var notifierVersion = require('./version').notifierVersion;
function merge(target, obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
target[key] = obj[key];
}
}
return target;
}
function notify(err, options) {
if (!options) options = {};
request(config.endpoint, {
payloadVersion: '3',
notifierVersion: notifierVersion,
apiKey: config.apiKey,
projectRoot: config.projectRoot || window.location.protocol + '//' + window.location.host,
context: config.context || window.location.pathname,
user: config.user,
- metaData: merge({}, merge(options.metaData || {}, config.metaData)),
+ metaData: merge(merge({}, config.metaData), config.metaData || {}),
releaseStage: config.releaseStage,
appVersion: config.appVersion,
url: window.location.href,
userAgent: navigator.userAgent,
language: navigator.language || navigator.userLanguage,
severity: options.severity || config.severity,
name: err.name,
message: err.message,
stacktrace: err.stack || err.backtrace || err.stacktrace,
file: err.fileName || err.sourceURL,
lineNumber: -1,
columnNumber: -1,
breadcrumbs: []
});
}
module.exports = notify; | 2 | 0.045455 | 1 | 1 |
ff0186f69e6dcf8f32f66dd42afa49187d10509f | tox.ini | tox.ini | [tox]
envlist =
lint
py36
py37
py38
py39
pypy3
minversion = 3.14.2
requires =
# https://github.com/tox-dev/tox/issues/765
virtualenv >= 16.7.9
pip >= 19.3.1
[testenv]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pytest --cov=cookiecutter --cov-report=term {posargs:tests}
cov-report: coverage html
cov-report: coverage xml
deps = -rtest_requirements.txt
skip_install = true
[testenv:lint]
commands =
python -m pre_commit run {posargs:--all}
deps = pre-commit>=1.20.0
skip_install = true
usedevelop = false
[testenv:docs]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pip install -r test_requirements.txt
pip install -r docs/requirements.txt
make docs
whitelist_externals = make
deps = -rtest_requirements.txt
skip_install = true
| [tox]
envlist =
lint
py36
py37
py38
py39
pypy3
minversion = 3.14.2
requires =
# https://github.com/tox-dev/tox/issues/765
virtualenv >= 16.7.9
pip >= 19.3.1
[testenv]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pytest --cov=cookiecutter --cov-report=term --cov-fail-under=100 {posargs:tests}
cov-report: coverage html
cov-report: coverage xml
deps = -rtest_requirements.txt
skip_install = true
[testenv:lint]
commands =
python -m pre_commit run {posargs:--all}
deps = pre-commit>=1.20.0
skip_install = true
usedevelop = false
[testenv:docs]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pip install -r test_requirements.txt
pip install -r docs/requirements.txt
make docs
whitelist_externals = make
deps = -rtest_requirements.txt
skip_install = true
| Add fail under 100% coverage | Add fail under 100% coverage
| INI | bsd-3-clause | audreyr/cookiecutter,pjbull/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter | ini | ## Code Before:
[tox]
envlist =
lint
py36
py37
py38
py39
pypy3
minversion = 3.14.2
requires =
# https://github.com/tox-dev/tox/issues/765
virtualenv >= 16.7.9
pip >= 19.3.1
[testenv]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pytest --cov=cookiecutter --cov-report=term {posargs:tests}
cov-report: coverage html
cov-report: coverage xml
deps = -rtest_requirements.txt
skip_install = true
[testenv:lint]
commands =
python -m pre_commit run {posargs:--all}
deps = pre-commit>=1.20.0
skip_install = true
usedevelop = false
[testenv:docs]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pip install -r test_requirements.txt
pip install -r docs/requirements.txt
make docs
whitelist_externals = make
deps = -rtest_requirements.txt
skip_install = true
## Instruction:
Add fail under 100% coverage
## Code After:
[tox]
envlist =
lint
py36
py37
py38
py39
pypy3
minversion = 3.14.2
requires =
# https://github.com/tox-dev/tox/issues/765
virtualenv >= 16.7.9
pip >= 19.3.1
[testenv]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pytest --cov=cookiecutter --cov-report=term --cov-fail-under=100 {posargs:tests}
cov-report: coverage html
cov-report: coverage xml
deps = -rtest_requirements.txt
skip_install = true
[testenv:lint]
commands =
python -m pre_commit run {posargs:--all}
deps = pre-commit>=1.20.0
skip_install = true
usedevelop = false
[testenv:docs]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pip install -r test_requirements.txt
pip install -r docs/requirements.txt
make docs
whitelist_externals = make
deps = -rtest_requirements.txt
skip_install = true
| [tox]
envlist =
lint
py36
py37
py38
py39
pypy3
minversion = 3.14.2
requires =
# https://github.com/tox-dev/tox/issues/765
virtualenv >= 16.7.9
pip >= 19.3.1
[testenv]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
- pytest --cov=cookiecutter --cov-report=term {posargs:tests}
+ pytest --cov=cookiecutter --cov-report=term --cov-fail-under=100 {posargs:tests}
? +++++++++++++++++++++
cov-report: coverage html
cov-report: coverage xml
deps = -rtest_requirements.txt
skip_install = true
[testenv:lint]
commands =
python -m pre_commit run {posargs:--all}
deps = pre-commit>=1.20.0
skip_install = true
usedevelop = false
[testenv:docs]
passenv =
LC_ALL
LANG
HOME
commands =
pip install -e .
pip install -r test_requirements.txt
pip install -r docs/requirements.txt
make docs
whitelist_externals = make
deps = -rtest_requirements.txt
skip_install = true | 2 | 0.042553 | 1 | 1 |
9052b511e9ec2c3bd6f9a04eadf1ba1ee0899ca5 | PUBLISH.md | PUBLISH.md |
Sync latest changes from `origin`.
```
git pull
```
Run tests locally and make sure they pass.
```
npm run test
```
Publish a new version for each package. (Use `--dry-run` to preview results without actually publishing.)
```
for package in `ls packages/`;
do npm publish --access public --otp <OTP> packages/$package [--dry-run];
done
```
|
Sync latest changes from `origin`.
```
git pull
```
Build the native compiler locally to make sure it works.
```
npm run build
```
Run tests locally and make sure they pass.
```
npm run test
```
Publish a new version for each package. (Use `--dry-run` to preview results without actually publishing.)
```
for package in `ls packages/`;
do npm publish --access public --otp <OTP> packages/$package [--dry-run];
done
```
| Update publish instructions to include building | Update publish instructions to include building [UPDATE] | Markdown | apache-2.0 | ampproject/amp-closure-compiler,ampproject/amp-closure-compiler | markdown | ## Code Before:
Sync latest changes from `origin`.
```
git pull
```
Run tests locally and make sure they pass.
```
npm run test
```
Publish a new version for each package. (Use `--dry-run` to preview results without actually publishing.)
```
for package in `ls packages/`;
do npm publish --access public --otp <OTP> packages/$package [--dry-run];
done
```
## Instruction:
Update publish instructions to include building [UPDATE]
## Code After:
Sync latest changes from `origin`.
```
git pull
```
Build the native compiler locally to make sure it works.
```
npm run build
```
Run tests locally and make sure they pass.
```
npm run test
```
Publish a new version for each package. (Use `--dry-run` to preview results without actually publishing.)
```
for package in `ls packages/`;
do npm publish --access public --otp <OTP> packages/$package [--dry-run];
done
```
|
Sync latest changes from `origin`.
```
git pull
+ ```
+
+ Build the native compiler locally to make sure it works.
+
+ ```
+ npm run build
```
Run tests locally and make sure they pass.
```
npm run test
```
Publish a new version for each package. (Use `--dry-run` to preview results without actually publishing.)
```
for package in `ls packages/`;
do npm publish --access public --otp <OTP> packages/$package [--dry-run];
done
``` | 6 | 0.3 | 6 | 0 |
a97e9ca1d26271b9edb9f9bd9dc1154ccdda59ff | NOTICE.txt | NOTICE.txt | The Galileo Project is licensed under the 2-clause BSD license:
http://opensource.org/licenses/BSD-2-Clause
This project includes additional software dependencies:
================================================================================
Apache Commons Math
Copyright 2001-2014 The Apache Software Foundation (http://www.apache.org/)
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
JavaEWAH
Copyright 2009-2014 Lemire et al.
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
| The Galileo Project is licensed under the 2-clause BSD license:
http://opensource.org/licenses/BSD-2-Clause
This project includes additional software dependencies:
================================================================================
Apache Commons Math
Copyright 2001-2014 The Apache Software Foundation (http://www.apache.org/)
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
JavaEWAH
Copyright 2009-2014 Lemire et al.
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
Text copies of the relevant license(s) are located in the /docs directory.
| Add note about text copies of licenses | Add note about text copies of licenses
| Text | bsd-2-clause | 10000TB/galileo,10000TB/galileo | text | ## Code Before:
The Galileo Project is licensed under the 2-clause BSD license:
http://opensource.org/licenses/BSD-2-Clause
This project includes additional software dependencies:
================================================================================
Apache Commons Math
Copyright 2001-2014 The Apache Software Foundation (http://www.apache.org/)
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
JavaEWAH
Copyright 2009-2014 Lemire et al.
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
## Instruction:
Add note about text copies of licenses
## Code After:
The Galileo Project is licensed under the 2-clause BSD license:
http://opensource.org/licenses/BSD-2-Clause
This project includes additional software dependencies:
================================================================================
Apache Commons Math
Copyright 2001-2014 The Apache Software Foundation (http://www.apache.org/)
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
JavaEWAH
Copyright 2009-2014 Lemire et al.
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
Text copies of the relevant license(s) are located in the /docs directory.
| The Galileo Project is licensed under the 2-clause BSD license:
http://opensource.org/licenses/BSD-2-Clause
-
This project includes additional software dependencies:
================================================================================
Apache Commons Math
Copyright 2001-2014 The Apache Software Foundation (http://www.apache.org/)
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
JavaEWAH
Copyright 2009-2014 Lemire et al.
License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
================================================================================
+
+ Text copies of the relevant license(s) are located in the /docs directory. | 3 | 0.2 | 2 | 1 |
704a159d5dc0e0e8e816d58562b5aa60aa66a90c | project/test/DatastoreService.scala | project/test/DatastoreService.scala | import com.google.appengine.api.datastore.dev.LocalDatastoreService
import com.google.appengine.tools.development.ApiProxyLocalImpl
import com.google.apphosting.api.ApiProxy
import com.google.apphosting.api.ApiProxy.Environment
import java.io.File
object DatastoreService {
class GaeEnvironment(private val requestNamespace:String) extends Environment {
def this() = this("")
def getAppId = "Quotidian Specs"
def getVersionId = "1.0"
def getRequestNamespace = requestNamespace
def getAuthDomain = "gmail.com"
def isLoggedIn = throw new UnsupportedOperationException()
def getEmail = ""
def isAdmin = throw new UnsupportedOperationException()
def getAttributes = new java.util.HashMap[String,Object]()
}
val proxy = new ApiProxyLocalImpl(new File("./target/")){ }
val service = proxy.getService("datastore_v3").asInstanceOf[LocalDatastoreService]
def start = {
proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY,true.toString)
ApiProxy.setEnvironmentForCurrentThread(new GaeEnvironment)
ApiProxy.setDelegate(proxy)
}
def stop = {
service.clearProfiles
proxy.stop
service.stop
ApiProxy.setDelegate(null)
ApiProxy.setEnvironmentForCurrentThread(null)
ApiProxy.clearEnvironmentForCurrentThread()
}
}
| import com.google.appengine.api.datastore.dev.LocalDatastoreService
import com.google.appengine.tools.development.ApiProxyLocalImpl
import com.google.apphosting.api.ApiProxy
import com.google.apphosting.api.ApiProxy.Environment
import java.io.File
import java.util.zip.{Checksum,CRC32}
import org.apache.lucene.index._
import org.apache.lucene.store._
import quotidian.search._
object DatastoreService {
class GaeEnvironment(private val requestNamespace:String) extends Environment {
def this() = this("")
def getAppId = "Quotidian Specs"
def getVersionId = "1.0"
def getRequestNamespace = requestNamespace
def getAuthDomain = "gmail.com"
def isLoggedIn = throw new UnsupportedOperationException()
def getEmail = ""
def isAdmin = throw new UnsupportedOperationException()
def getAttributes = new java.util.HashMap[String,Object]()
}
val proxy = new ApiProxyLocalImpl(new File("./target/")){ }
val service = proxy.getService("datastore_v3").asInstanceOf[LocalDatastoreService]
def start = {
proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY,true.toString)
ApiProxy.setEnvironmentForCurrentThread(new GaeEnvironment)
ApiProxy.setDelegate(proxy)
}
def stop = {
service.clearProfiles
proxy.stop
service.stop
ApiProxy.setDelegate(null)
ApiProxy.setEnvironmentForCurrentThread(null)
ApiProxy.clearEnvironmentForCurrentThread()
}
}
| Add lucene and checksum packages to imports | Add lucene and checksum packages to imports
| Scala | mit | bryanjswift/quotidian,bryanjswift/quotidian | scala | ## Code Before:
import com.google.appengine.api.datastore.dev.LocalDatastoreService
import com.google.appengine.tools.development.ApiProxyLocalImpl
import com.google.apphosting.api.ApiProxy
import com.google.apphosting.api.ApiProxy.Environment
import java.io.File
object DatastoreService {
class GaeEnvironment(private val requestNamespace:String) extends Environment {
def this() = this("")
def getAppId = "Quotidian Specs"
def getVersionId = "1.0"
def getRequestNamespace = requestNamespace
def getAuthDomain = "gmail.com"
def isLoggedIn = throw new UnsupportedOperationException()
def getEmail = ""
def isAdmin = throw new UnsupportedOperationException()
def getAttributes = new java.util.HashMap[String,Object]()
}
val proxy = new ApiProxyLocalImpl(new File("./target/")){ }
val service = proxy.getService("datastore_v3").asInstanceOf[LocalDatastoreService]
def start = {
proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY,true.toString)
ApiProxy.setEnvironmentForCurrentThread(new GaeEnvironment)
ApiProxy.setDelegate(proxy)
}
def stop = {
service.clearProfiles
proxy.stop
service.stop
ApiProxy.setDelegate(null)
ApiProxy.setEnvironmentForCurrentThread(null)
ApiProxy.clearEnvironmentForCurrentThread()
}
}
## Instruction:
Add lucene and checksum packages to imports
## Code After:
import com.google.appengine.api.datastore.dev.LocalDatastoreService
import com.google.appengine.tools.development.ApiProxyLocalImpl
import com.google.apphosting.api.ApiProxy
import com.google.apphosting.api.ApiProxy.Environment
import java.io.File
import java.util.zip.{Checksum,CRC32}
import org.apache.lucene.index._
import org.apache.lucene.store._
import quotidian.search._
object DatastoreService {
class GaeEnvironment(private val requestNamespace:String) extends Environment {
def this() = this("")
def getAppId = "Quotidian Specs"
def getVersionId = "1.0"
def getRequestNamespace = requestNamespace
def getAuthDomain = "gmail.com"
def isLoggedIn = throw new UnsupportedOperationException()
def getEmail = ""
def isAdmin = throw new UnsupportedOperationException()
def getAttributes = new java.util.HashMap[String,Object]()
}
val proxy = new ApiProxyLocalImpl(new File("./target/")){ }
val service = proxy.getService("datastore_v3").asInstanceOf[LocalDatastoreService]
def start = {
proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY,true.toString)
ApiProxy.setEnvironmentForCurrentThread(new GaeEnvironment)
ApiProxy.setDelegate(proxy)
}
def stop = {
service.clearProfiles
proxy.stop
service.stop
ApiProxy.setDelegate(null)
ApiProxy.setEnvironmentForCurrentThread(null)
ApiProxy.clearEnvironmentForCurrentThread()
}
}
| import com.google.appengine.api.datastore.dev.LocalDatastoreService
import com.google.appengine.tools.development.ApiProxyLocalImpl
import com.google.apphosting.api.ApiProxy
import com.google.apphosting.api.ApiProxy.Environment
import java.io.File
+ import java.util.zip.{Checksum,CRC32}
+ import org.apache.lucene.index._
+ import org.apache.lucene.store._
+ import quotidian.search._
object DatastoreService {
class GaeEnvironment(private val requestNamespace:String) extends Environment {
def this() = this("")
def getAppId = "Quotidian Specs"
def getVersionId = "1.0"
def getRequestNamespace = requestNamespace
def getAuthDomain = "gmail.com"
def isLoggedIn = throw new UnsupportedOperationException()
def getEmail = ""
def isAdmin = throw new UnsupportedOperationException()
def getAttributes = new java.util.HashMap[String,Object]()
}
val proxy = new ApiProxyLocalImpl(new File("./target/")){ }
val service = proxy.getService("datastore_v3").asInstanceOf[LocalDatastoreService]
def start = {
proxy.setProperty(LocalDatastoreService.NO_STORAGE_PROPERTY,true.toString)
ApiProxy.setEnvironmentForCurrentThread(new GaeEnvironment)
ApiProxy.setDelegate(proxy)
}
def stop = {
service.clearProfiles
proxy.stop
service.stop
ApiProxy.setDelegate(null)
ApiProxy.setEnvironmentForCurrentThread(null)
ApiProxy.clearEnvironmentForCurrentThread()
}
} | 4 | 0.117647 | 4 | 0 |
02cd0c281115af1d1fab8af948d9a83e8c8b6899 | .travis.yml | .travis.yml | language: ruby
rvm:
- 1.9.3
- 1.8.7
env:
- PUPPET_VERSION=2.7.16
- PUPPET_VERSION=2.7.17
- PUPPET_VERSION=2.7.18
- PUPPET_VERSION=2.7.19
- PUPPET_VERSION=2.7.20
- PUPPET_VERSION=3.0.0
- PUPPET_VERSION=3.0.1
| language: ruby
rvm:
- 1.9.3
- 1.8.7
env:
- PUPPET_VERSION=2.7.6
- PUPPET_VERSION=2.7.13
- PUPPET_VERSION=2.7.20
- PUPPET_VERSION=3.0.1
| Reduce number of puppet versions we test against | Reduce number of puppet versions we test against
| YAML | mit | johanek/puppet-parse | yaml | ## Code Before:
language: ruby
rvm:
- 1.9.3
- 1.8.7
env:
- PUPPET_VERSION=2.7.16
- PUPPET_VERSION=2.7.17
- PUPPET_VERSION=2.7.18
- PUPPET_VERSION=2.7.19
- PUPPET_VERSION=2.7.20
- PUPPET_VERSION=3.0.0
- PUPPET_VERSION=3.0.1
## Instruction:
Reduce number of puppet versions we test against
## Code After:
language: ruby
rvm:
- 1.9.3
- 1.8.7
env:
- PUPPET_VERSION=2.7.6
- PUPPET_VERSION=2.7.13
- PUPPET_VERSION=2.7.20
- PUPPET_VERSION=3.0.1
| language: ruby
rvm:
- 1.9.3
- 1.8.7
env:
- - PUPPET_VERSION=2.7.16
? -
+ - PUPPET_VERSION=2.7.6
- - PUPPET_VERSION=2.7.17
? ^
+ - PUPPET_VERSION=2.7.13
? ^
- - PUPPET_VERSION=2.7.18
- - PUPPET_VERSION=2.7.19
- PUPPET_VERSION=2.7.20
- - PUPPET_VERSION=3.0.0
- PUPPET_VERSION=3.0.1 | 7 | 0.583333 | 2 | 5 |
f3d3c0ce81ba8717f5839b502e57d75ebbc1f6e7 | meetuppizza/views.py | meetuppizza/views.py | from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService
def index(request):
meetups = Meetup.objects.all()
meetup_presenters = []
for meetup in meetups:
service = MeetupService(meetup)
meetup_presenters.append(service.get_decorated_meetup())
return render(request, 'index.html', {"meetups": meetup_presenters})
| from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService
def index(request):
meetups = Meetup.objects.all()
meetup_presenters = [MeetupService(meetup).get_decorated_meetup() for meetup in meetups]
return render(request, 'index.html', {"meetups": meetup_presenters})
| Use list comprehension to generate MeetupPresentor list in index view | Use list comprehension to generate MeetupPresentor list in index view
| Python | mit | nicole-a-tesla/meetup.pizza,nicole-a-tesla/meetup.pizza | python | ## Code Before:
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService
def index(request):
meetups = Meetup.objects.all()
meetup_presenters = []
for meetup in meetups:
service = MeetupService(meetup)
meetup_presenters.append(service.get_decorated_meetup())
return render(request, 'index.html', {"meetups": meetup_presenters})
## Instruction:
Use list comprehension to generate MeetupPresentor list in index view
## Code After:
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService
def index(request):
meetups = Meetup.objects.all()
meetup_presenters = [MeetupService(meetup).get_decorated_meetup() for meetup in meetups]
return render(request, 'index.html', {"meetups": meetup_presenters})
| from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from meetuppizza.forms import RegistrationForm
from meetup.models import Meetup
from meetup.services.meetup_service import MeetupService
def index(request):
meetups = Meetup.objects.all()
+ meetup_presenters = [MeetupService(meetup).get_decorated_meetup() for meetup in meetups]
+
- meetup_presenters = []
- for meetup in meetups:
- service = MeetupService(meetup)
- meetup_presenters.append(service.get_decorated_meetup())
return render(request, 'index.html', {"meetups": meetup_presenters}) | 6 | 0.428571 | 2 | 4 |
92fd5d8a143fae34b7ae9a1a202fe136db5a3f46 | src/web/CMakeLists.txt | src/web/CMakeLists.txt | find_package(Qt4 4.6 COMPONENTS QtCore QtNetwork QtXml REQUIRED)
set(QT_DONT_USE_QTGUI TRUE)
set(QT_USE_QTNETWORK TRUE)
set(QT_USE_QTXML TRUE)
include(${QT_USE_FILE})
set(HEADERS
proteindatabank.h
pubchem.h
web.h
)
set(SOURCES
downloadthread.cpp
proteindatabank.cpp
pubchem.cpp
pubchemquery.cpp
pubchemquerythread.cpp
web.cpp
)
set(MOC_HEADERS
downloadthread.h
pubchemquerythread.h
)
qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS})
add_definitions(
-DCHEMKIT_WEB_LIBRARY
)
include_directories(../../include)
add_library(chemkit-web SHARED ${SOURCES} ${MOC_SOURCES})
target_link_libraries(chemkit-web chemkit ${QT_LIBRARIES})
install(TARGETS chemkit-web DESTINATION lib)
# install header files
install(FILES ${HEADERS} DESTINATION include/chemkit/)
| find_package(Qt4 4.6 COMPONENTS QtCore QtNetwork QtXml REQUIRED)
set(QT_DONT_USE_QTGUI TRUE)
set(QT_USE_QTNETWORK TRUE)
set(QT_USE_QTXML TRUE)
include(${QT_USE_FILE})
find_package(Boost REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
set(HEADERS
proteindatabank.h
pubchem.h
web.h
)
set(SOURCES
downloadthread.cpp
proteindatabank.cpp
pubchem.cpp
pubchemquery.cpp
pubchemquerythread.cpp
web.cpp
)
set(MOC_HEADERS
downloadthread.h
pubchemquerythread.h
)
qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS})
add_definitions(
-DCHEMKIT_WEB_LIBRARY
)
include_directories(../../include)
add_library(chemkit-web SHARED ${SOURCES} ${MOC_SOURCES})
target_link_libraries(chemkit-web chemkit ${QT_LIBRARIES})
install(TARGETS chemkit-web DESTINATION lib)
# install header files
install(FILES ${HEADERS} DESTINATION include/chemkit/)
| Add find_package() for Boost to libchemkit-web | Add find_package() for Boost to libchemkit-web
This adds a call to find_package() for Boost to the
CMakeLists.txt file for the libchemkit-web library
which fixes a compilation error on Windows.
| Text | bsd-3-clause | kylelutz/chemkit,kylelutz/chemkit,kylelutz/chemkit,kylelutz/chemkit | text | ## Code Before:
find_package(Qt4 4.6 COMPONENTS QtCore QtNetwork QtXml REQUIRED)
set(QT_DONT_USE_QTGUI TRUE)
set(QT_USE_QTNETWORK TRUE)
set(QT_USE_QTXML TRUE)
include(${QT_USE_FILE})
set(HEADERS
proteindatabank.h
pubchem.h
web.h
)
set(SOURCES
downloadthread.cpp
proteindatabank.cpp
pubchem.cpp
pubchemquery.cpp
pubchemquerythread.cpp
web.cpp
)
set(MOC_HEADERS
downloadthread.h
pubchemquerythread.h
)
qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS})
add_definitions(
-DCHEMKIT_WEB_LIBRARY
)
include_directories(../../include)
add_library(chemkit-web SHARED ${SOURCES} ${MOC_SOURCES})
target_link_libraries(chemkit-web chemkit ${QT_LIBRARIES})
install(TARGETS chemkit-web DESTINATION lib)
# install header files
install(FILES ${HEADERS} DESTINATION include/chemkit/)
## Instruction:
Add find_package() for Boost to libchemkit-web
This adds a call to find_package() for Boost to the
CMakeLists.txt file for the libchemkit-web library
which fixes a compilation error on Windows.
## Code After:
find_package(Qt4 4.6 COMPONENTS QtCore QtNetwork QtXml REQUIRED)
set(QT_DONT_USE_QTGUI TRUE)
set(QT_USE_QTNETWORK TRUE)
set(QT_USE_QTXML TRUE)
include(${QT_USE_FILE})
find_package(Boost REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
set(HEADERS
proteindatabank.h
pubchem.h
web.h
)
set(SOURCES
downloadthread.cpp
proteindatabank.cpp
pubchem.cpp
pubchemquery.cpp
pubchemquerythread.cpp
web.cpp
)
set(MOC_HEADERS
downloadthread.h
pubchemquerythread.h
)
qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS})
add_definitions(
-DCHEMKIT_WEB_LIBRARY
)
include_directories(../../include)
add_library(chemkit-web SHARED ${SOURCES} ${MOC_SOURCES})
target_link_libraries(chemkit-web chemkit ${QT_LIBRARIES})
install(TARGETS chemkit-web DESTINATION lib)
# install header files
install(FILES ${HEADERS} DESTINATION include/chemkit/)
| find_package(Qt4 4.6 COMPONENTS QtCore QtNetwork QtXml REQUIRED)
set(QT_DONT_USE_QTGUI TRUE)
set(QT_USE_QTNETWORK TRUE)
set(QT_USE_QTXML TRUE)
include(${QT_USE_FILE})
+
+ find_package(Boost REQUIRED)
+ include_directories(${Boost_INCLUDE_DIRS})
set(HEADERS
proteindatabank.h
pubchem.h
web.h
)
set(SOURCES
downloadthread.cpp
proteindatabank.cpp
pubchem.cpp
pubchemquery.cpp
pubchemquerythread.cpp
web.cpp
)
set(MOC_HEADERS
downloadthread.h
pubchemquerythread.h
)
qt4_wrap_cpp(MOC_SOURCES ${MOC_HEADERS})
add_definitions(
-DCHEMKIT_WEB_LIBRARY
)
include_directories(../../include)
add_library(chemkit-web SHARED ${SOURCES} ${MOC_SOURCES})
target_link_libraries(chemkit-web chemkit ${QT_LIBRARIES})
install(TARGETS chemkit-web DESTINATION lib)
# install header files
install(FILES ${HEADERS} DESTINATION include/chemkit/) | 3 | 0.075 | 3 | 0 |
5914b9a4d1d086f1a92309c0895aa7dd11761776 | conf_site/accounts/tests/test_registration.py | conf_site/accounts/tests/test_registration.py | from factory import Faker, fuzzy
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
EMAIL = Faker("email").generate()
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL)
| from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from factory import fuzzy
from faker import Faker
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
EMAIL = Faker().email()
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL)
| Change imports in user registration test. | Change imports in user registration test.
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site | python | ## Code Before:
from factory import Faker, fuzzy
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
EMAIL = Faker("email").generate()
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL)
## Instruction:
Change imports in user registration test.
## Code After:
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from factory import fuzzy
from faker import Faker
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
EMAIL = Faker().email()
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL)
| - from factory import Faker, fuzzy
-
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
+
+ from factory import fuzzy
+ from faker import Faker
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
- EMAIL = Faker("email").generate()
? ^ -----------
+ EMAIL = Faker().email()
? ^^
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL) | 7 | 0.194444 | 4 | 3 |
169a9314b3b9c352fa58a8e216d6db670df721f4 | puppet/hiera/gerrit.yaml | puppet/hiera/gerrit.yaml | gerrit:
repo_base_path: git
weburl: sf-gerrit
sshd_listen_address: '*:29418'
issues_tracker_address: sf-redmine
issues_tracker_api_key: REDMINE_API_KEY
issues_tracker_version: 1.4
gerrit_mysql_address: sf-mysql
gerrit_mysql_db: gerrit
gerrit_mysql_username: gerrit
gerrit_mysql_port: 3306
gerrit_mysql_secret: secret
ldap_address: sf-ldap
ldap_username: cn=admin,dc=enovance,dc=com
ldap_password: secret
ldap_account_base: ou=Users,dc=enovance,dc=com
ldap_account_pattern: (&(objectClass=inetOrgPerson)(cn=${username}))
ldap_account_email_address: mail
ldap_account_ssh_username: cn
http_basic_auth: true
smtp_server:
smtp_server_port:
smtp_user:
smtp_pass:
gerrit_admin_username: GERRIT_ADMIN
gerrit_admin_mail: GERRIT_ADMIN_MAIL
gerrit_admin_sshkey: GERRIT_ADMIN_PUB_KEY
gerrit_jenkins_sshkey: JENKINS_PUB_KEY
gerrit_local_sshkey: GERRIT_SERV_PUB_KEY
| gerrit:
repo_base_path: git
weburl: sf-gerrit
sshd_listen_address: '*:29418'
issues_tracker_address: sf-redmine
issues_tracker_api_key: REDMINE_API_KEY
issues_tracker_version: 1.4
gerrit_mysql_address: sf-mysql
gerrit_mysql_db: gerrit
gerrit_mysql_username: gerrit
gerrit_mysql_port: 3306
gerrit_mysql_secret: secret
ldap_address: sf-ldap
ldap_username: cn=admin,dc=enovance,dc=com
ldap_password: secret
ldap_account_base: ou=Users,dc=enovance,dc=com
ldap_account_pattern: (&(objectClass=inetOrgPerson)(cn=${username}))
ldap_account_email_address: mail
ldap_account_ssh_username: cn
http_basic_auth: true
smtp_server: mail.enovance.com
smtp_server_port:
smtp_user:
smtp_pass:
gerrit_admin_username: GERRIT_ADMIN
gerrit_admin_mail: GERRIT_ADMIN_MAIL
gerrit_admin_sshkey: GERRIT_ADMIN_PUB_KEY
gerrit_jenkins_sshkey: JENKINS_PUB_KEY
gerrit_local_sshkey: GERRIT_SERV_PUB_KEY
| Add eNovance SMTP server to Gerrit config | Add eNovance SMTP server to Gerrit config
Change-Id: I912b1ec5613ef5929a89d2d581593db765ef7893
| YAML | apache-2.0 | invenfantasy/software-factory,enovance/software-factory,invenfantasy/software-factory,enovance/software-factory,enovance/software-factory,enovance/software-factory,invenfantasy/software-factory,enovance/software-factory,invenfantasy/software-factory,invenfantasy/software-factory | yaml | ## Code Before:
gerrit:
repo_base_path: git
weburl: sf-gerrit
sshd_listen_address: '*:29418'
issues_tracker_address: sf-redmine
issues_tracker_api_key: REDMINE_API_KEY
issues_tracker_version: 1.4
gerrit_mysql_address: sf-mysql
gerrit_mysql_db: gerrit
gerrit_mysql_username: gerrit
gerrit_mysql_port: 3306
gerrit_mysql_secret: secret
ldap_address: sf-ldap
ldap_username: cn=admin,dc=enovance,dc=com
ldap_password: secret
ldap_account_base: ou=Users,dc=enovance,dc=com
ldap_account_pattern: (&(objectClass=inetOrgPerson)(cn=${username}))
ldap_account_email_address: mail
ldap_account_ssh_username: cn
http_basic_auth: true
smtp_server:
smtp_server_port:
smtp_user:
smtp_pass:
gerrit_admin_username: GERRIT_ADMIN
gerrit_admin_mail: GERRIT_ADMIN_MAIL
gerrit_admin_sshkey: GERRIT_ADMIN_PUB_KEY
gerrit_jenkins_sshkey: JENKINS_PUB_KEY
gerrit_local_sshkey: GERRIT_SERV_PUB_KEY
## Instruction:
Add eNovance SMTP server to Gerrit config
Change-Id: I912b1ec5613ef5929a89d2d581593db765ef7893
## Code After:
gerrit:
repo_base_path: git
weburl: sf-gerrit
sshd_listen_address: '*:29418'
issues_tracker_address: sf-redmine
issues_tracker_api_key: REDMINE_API_KEY
issues_tracker_version: 1.4
gerrit_mysql_address: sf-mysql
gerrit_mysql_db: gerrit
gerrit_mysql_username: gerrit
gerrit_mysql_port: 3306
gerrit_mysql_secret: secret
ldap_address: sf-ldap
ldap_username: cn=admin,dc=enovance,dc=com
ldap_password: secret
ldap_account_base: ou=Users,dc=enovance,dc=com
ldap_account_pattern: (&(objectClass=inetOrgPerson)(cn=${username}))
ldap_account_email_address: mail
ldap_account_ssh_username: cn
http_basic_auth: true
smtp_server: mail.enovance.com
smtp_server_port:
smtp_user:
smtp_pass:
gerrit_admin_username: GERRIT_ADMIN
gerrit_admin_mail: GERRIT_ADMIN_MAIL
gerrit_admin_sshkey: GERRIT_ADMIN_PUB_KEY
gerrit_jenkins_sshkey: JENKINS_PUB_KEY
gerrit_local_sshkey: GERRIT_SERV_PUB_KEY
| gerrit:
repo_base_path: git
weburl: sf-gerrit
sshd_listen_address: '*:29418'
issues_tracker_address: sf-redmine
issues_tracker_api_key: REDMINE_API_KEY
issues_tracker_version: 1.4
gerrit_mysql_address: sf-mysql
gerrit_mysql_db: gerrit
gerrit_mysql_username: gerrit
gerrit_mysql_port: 3306
gerrit_mysql_secret: secret
ldap_address: sf-ldap
ldap_username: cn=admin,dc=enovance,dc=com
ldap_password: secret
ldap_account_base: ou=Users,dc=enovance,dc=com
ldap_account_pattern: (&(objectClass=inetOrgPerson)(cn=${username}))
ldap_account_email_address: mail
ldap_account_ssh_username: cn
http_basic_auth: true
- smtp_server:
+ smtp_server: mail.enovance.com
smtp_server_port:
smtp_user:
smtp_pass:
gerrit_admin_username: GERRIT_ADMIN
gerrit_admin_mail: GERRIT_ADMIN_MAIL
gerrit_admin_sshkey: GERRIT_ADMIN_PUB_KEY
gerrit_jenkins_sshkey: JENKINS_PUB_KEY
gerrit_local_sshkey: GERRIT_SERV_PUB_KEY | 2 | 0.068966 | 1 | 1 |
1e462f7748ce5bc1b8268d81d955747dc1ef1f82 | demo/index.html | demo/index.html | <html>
<head>
<title>react-mde</title>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
</head>
<body>
<div>
<div id="#app_container"></div>
</div>
<script src='bundle.js'></script>
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-89807105-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html> | <html>
<head>
<title>react-mde</title>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
</head>
<body>
<div>
<div id="#app_container"></div>
</div>
<script src='bundle.js'></script>
</body>
</html> | Stop tracking the demo on my Google Analytics | Stop tracking the demo on my Google Analytics
| HTML | mit | andrerpena/react-mde,andrerpena/react-mde,andrerpena/react-mde | html | ## Code Before:
<html>
<head>
<title>react-mde</title>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
</head>
<body>
<div>
<div id="#app_container"></div>
</div>
<script src='bundle.js'></script>
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-89807105-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
## Instruction:
Stop tracking the demo on my Google Analytics
## Code After:
<html>
<head>
<title>react-mde</title>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
</head>
<body>
<div>
<div id="#app_container"></div>
</div>
<script src='bundle.js'></script>
</body>
</html> | <html>
<head>
<title>react-mde</title>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" integrity="sha384-kW+oWsYx3YpxvjtZjFXqazFpA7UP/MbiY4jvs+RWZo2+N94PFZ36T6TFkc9O3qoB" crossorigin="anonymous"></script>
</head>
<body>
<div>
<div id="#app_container"></div>
</div>
<script src='bundle.js'></script>
- <script>
- (function (i, s, o, g, r, a, m) {
- i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
- (i[r].q = i[r].q || []).push(arguments)
- }, i[r].l = 1 * new Date(); a = s.createElement(o),
- m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
- })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
-
- ga('create', 'UA-89807105-1', 'auto');
- ga('send', 'pageview');
-
- </script>
</body>
</html> | 12 | 0.413793 | 0 | 12 |
b12b936d25779e1f9b1a2ee01e9644139b611fa7 | client/src/js/hmm/api.js | client/src/js/hmm/api.js | import Request from "superagent";
export const find = () => (
Request.get(`/api/hmms${window.location.search}`)
);
export const install = () => (
Request.patch("/api/hmms/install")
);
export const get = ({ hmmId }) => (
Request.get(`/api/hmms/${hmmId}`)
);
| import Request from "superagent";
export const find = () => (
Request.get(`/api/hmms${window.location.search}`)
);
export const install = () => (
Request.post("/api/status/hmm")
);
export const get = ({ hmmId }) => (
Request.get(`/api/hmms/${hmmId}`)
);
| Update client API call for HMM install | Update client API call for HMM install | JavaScript | mit | igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool | javascript | ## Code Before:
import Request from "superagent";
export const find = () => (
Request.get(`/api/hmms${window.location.search}`)
);
export const install = () => (
Request.patch("/api/hmms/install")
);
export const get = ({ hmmId }) => (
Request.get(`/api/hmms/${hmmId}`)
);
## Instruction:
Update client API call for HMM install
## Code After:
import Request from "superagent";
export const find = () => (
Request.get(`/api/hmms${window.location.search}`)
);
export const install = () => (
Request.post("/api/status/hmm")
);
export const get = ({ hmmId }) => (
Request.get(`/api/hmms/${hmmId}`)
);
| import Request from "superagent";
export const find = () => (
Request.get(`/api/hmms${window.location.search}`)
);
export const install = () => (
- Request.patch("/api/hmms/install")
+ Request.post("/api/status/hmm")
);
export const get = ({ hmmId }) => (
Request.get(`/api/hmms/${hmmId}`)
); | 2 | 0.153846 | 1 | 1 |
264b5371290169136bcf617965692afd4dba75af | tests/TermBuilderTest.php | tests/TermBuilderTest.php | <?php
namespace Swis\LaravelFulltext\Tests;
use Swis\LaravelFulltext\TermBuilder;
class TermBuilderTest extends AbstractTestCase
{
public function test_termbuilder_builds_terms_array()
{
global $configReturn;
$configReturn= false;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$diff = $terms->diff($termsResult);
$this->assertCount(0, $diff);
}
public function test_termbuilder_builds_terms_array_with_wildcard()
{
global $configReturn;
$configReturn = true;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithWildcard = ['hi*', 'im*', 'a*', 'few*', 'terms*'];
$diff = $terms->diff($termsResultWithWildcard);
$this->assertCount(0, $diff);
}
}
namespace Swis\LaravelFulltext;
function config($arg)
{
global $configReturn;
return $configReturn;
}
| <?php
namespace Swis\LaravelFulltext\Tests;
use Swis\LaravelFulltext\TermBuilder;
class TermBuilderTest extends AbstractTestCase
{
public function test_termbuilder_builds_terms_array()
{
global $configReturn;
$configReturn= false;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$diff = $terms->diff($termsResult);
$this->assertCount(0, $diff);
}
public function test_termbuilder_does_not_build_empty_terms()
{
global $configReturn;
$configReturn = false;
$termsResult = ['<hi', 'im', 'a', 'few', 'terms>'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithoutSpecialChars = ['hi', 'im', 'a', 'few', 'terms'];
$diff = $terms->diff($termsResultWithoutSpecialChars);
$this->assertCount(0, $diff);
}
public function test_termbuilder_builds_terms_array_with_wildcard()
{
global $configReturn;
$configReturn = true;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithWildcard = ['hi*', 'im*', 'a*', 'few*', 'terms*'];
$diff = $terms->diff($termsResultWithWildcard);
$this->assertCount(0, $diff);
}
}
namespace Swis\LaravelFulltext;
function config($arg)
{
global $configReturn;
return $configReturn;
}
| Add test to assert TermBuilder does not build empty terms | Add test to assert TermBuilder does not build empty terms
| PHP | mit | swisnl/laravel-fulltext | php | ## Code Before:
<?php
namespace Swis\LaravelFulltext\Tests;
use Swis\LaravelFulltext\TermBuilder;
class TermBuilderTest extends AbstractTestCase
{
public function test_termbuilder_builds_terms_array()
{
global $configReturn;
$configReturn= false;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$diff = $terms->diff($termsResult);
$this->assertCount(0, $diff);
}
public function test_termbuilder_builds_terms_array_with_wildcard()
{
global $configReturn;
$configReturn = true;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithWildcard = ['hi*', 'im*', 'a*', 'few*', 'terms*'];
$diff = $terms->diff($termsResultWithWildcard);
$this->assertCount(0, $diff);
}
}
namespace Swis\LaravelFulltext;
function config($arg)
{
global $configReturn;
return $configReturn;
}
## Instruction:
Add test to assert TermBuilder does not build empty terms
## Code After:
<?php
namespace Swis\LaravelFulltext\Tests;
use Swis\LaravelFulltext\TermBuilder;
class TermBuilderTest extends AbstractTestCase
{
public function test_termbuilder_builds_terms_array()
{
global $configReturn;
$configReturn= false;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$diff = $terms->diff($termsResult);
$this->assertCount(0, $diff);
}
public function test_termbuilder_does_not_build_empty_terms()
{
global $configReturn;
$configReturn = false;
$termsResult = ['<hi', 'im', 'a', 'few', 'terms>'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithoutSpecialChars = ['hi', 'im', 'a', 'few', 'terms'];
$diff = $terms->diff($termsResultWithoutSpecialChars);
$this->assertCount(0, $diff);
}
public function test_termbuilder_builds_terms_array_with_wildcard()
{
global $configReturn;
$configReturn = true;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithWildcard = ['hi*', 'im*', 'a*', 'few*', 'terms*'];
$diff = $terms->diff($termsResultWithWildcard);
$this->assertCount(0, $diff);
}
}
namespace Swis\LaravelFulltext;
function config($arg)
{
global $configReturn;
return $configReturn;
}
| <?php
namespace Swis\LaravelFulltext\Tests;
use Swis\LaravelFulltext\TermBuilder;
class TermBuilderTest extends AbstractTestCase
{
public function test_termbuilder_builds_terms_array()
{
global $configReturn;
$configReturn= false;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$diff = $terms->diff($termsResult);
+ $this->assertCount(0, $diff);
+ }
+
+ public function test_termbuilder_does_not_build_empty_terms()
+ {
+ global $configReturn;
+ $configReturn = false;
+
+ $termsResult = ['<hi', 'im', 'a', 'few', 'terms>'];
+ $terms = TermBuilder::terms(implode(' ', $termsResult));
+ $termsResultWithoutSpecialChars = ['hi', 'im', 'a', 'few', 'terms'];
+ $diff = $terms->diff($termsResultWithoutSpecialChars);
$this->assertCount(0, $diff);
}
public function test_termbuilder_builds_terms_array_with_wildcard()
{
global $configReturn;
$configReturn = true;
$termsResult = ['hi', 'im', 'a', 'few', 'terms'];
$terms = TermBuilder::terms(implode(' ', $termsResult));
$termsResultWithWildcard = ['hi*', 'im*', 'a*', 'few*', 'terms*'];
$diff = $terms->diff($termsResultWithWildcard);
$this->assertCount(0, $diff);
}
}
namespace Swis\LaravelFulltext;
function config($arg)
{
global $configReturn;
return $configReturn;
} | 12 | 0.307692 | 12 | 0 |
cc5717720bb9d34af87353e390ecd6305aba6ffa | src/drive/web/modules/upload/UploadButton.jsx | src/drive/web/modules/upload/UploadButton.jsx | import React from 'react'
import { Icon } from 'cozy-ui/react'
const styles = {
parent: {
position: 'relative',
width: '100%',
boxSizing: 'border-box'
},
input: {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
width: '100%',
height: '100%',
zIndex: 1,
cursor: 'pointer'
}
}
const UploadButton = ({ label, disabled, onUpload, className }) => (
<label
role="button"
disabled={disabled}
className={className}
style={styles.parent}
>
<span
style={{
display: 'flex',
alignItems: 'center'
}}
>
<Icon icon="upload" />
<span>{label}</span>
<input
type="file"
multiple
style={styles.input}
disabled={disabled}
onChange={e => {
if (e.target.files) {
onUpload(Array.from(e.target.files))
}
}}
/>
</span>
</label>
)
export default UploadButton
| import React from 'react'
import { Icon } from 'cozy-ui/react'
const styles = {
parent: {
position: 'relative',
overflow: 'hidden'
},
input: {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
width: '100%',
height: '100%',
zIndex: 1
}
}
const UploadButton = ({ label, disabled, onUpload, className }) => (
<label
role="button"
disabled={disabled}
className={className}
style={styles.parent}
>
<span>
<Icon icon="upload" />
<span>{label}</span>
<input
type="file"
multiple
style={styles.input}
disabled={disabled}
onChange={e => {
if (e.target.files) {
onUpload(Array.from(e.target.files))
}
}}
/>
</span>
</label>
)
export default UploadButton
| Revert "Fix. Upload Item has the right size and svg icon is aligned" | Revert "Fix. Upload Item has the right size and svg icon is aligned"
This reverts commit ded9138999e0d1d9fa4a8dddf982f116b5ba0c11 as this is not needed anymore and buggy as well
| JSX | agpl-3.0 | cozy/cozy-files-v3,y-lohse/cozy-drive,nono/cozy-files-v3,y-lohse/cozy-drive,y-lohse/cozy-drive,nono/cozy-files-v3,y-lohse/cozy-drive,cozy/cozy-files-v3,cozy/cozy-files-v3,y-lohse/cozy-files-v3,nono/cozy-files-v3,y-lohse/cozy-files-v3,y-lohse/cozy-files-v3,nono/cozy-files-v3,cozy/cozy-files-v3 | jsx | ## Code Before:
import React from 'react'
import { Icon } from 'cozy-ui/react'
const styles = {
parent: {
position: 'relative',
width: '100%',
boxSizing: 'border-box'
},
input: {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
width: '100%',
height: '100%',
zIndex: 1,
cursor: 'pointer'
}
}
const UploadButton = ({ label, disabled, onUpload, className }) => (
<label
role="button"
disabled={disabled}
className={className}
style={styles.parent}
>
<span
style={{
display: 'flex',
alignItems: 'center'
}}
>
<Icon icon="upload" />
<span>{label}</span>
<input
type="file"
multiple
style={styles.input}
disabled={disabled}
onChange={e => {
if (e.target.files) {
onUpload(Array.from(e.target.files))
}
}}
/>
</span>
</label>
)
export default UploadButton
## Instruction:
Revert "Fix. Upload Item has the right size and svg icon is aligned"
This reverts commit ded9138999e0d1d9fa4a8dddf982f116b5ba0c11 as this is not needed anymore and buggy as well
## Code After:
import React from 'react'
import { Icon } from 'cozy-ui/react'
const styles = {
parent: {
position: 'relative',
overflow: 'hidden'
},
input: {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
width: '100%',
height: '100%',
zIndex: 1
}
}
const UploadButton = ({ label, disabled, onUpload, className }) => (
<label
role="button"
disabled={disabled}
className={className}
style={styles.parent}
>
<span>
<Icon icon="upload" />
<span>{label}</span>
<input
type="file"
multiple
style={styles.input}
disabled={disabled}
onChange={e => {
if (e.target.files) {
onUpload(Array.from(e.target.files))
}
}}
/>
</span>
</label>
)
export default UploadButton
| import React from 'react'
import { Icon } from 'cozy-ui/react'
const styles = {
parent: {
position: 'relative',
+ overflow: 'hidden'
- width: '100%',
- boxSizing: 'border-box'
},
input: {
position: 'absolute',
top: 0,
left: 0,
opacity: 0,
width: '100%',
height: '100%',
- zIndex: 1,
? -
+ zIndex: 1
- cursor: 'pointer'
}
}
const UploadButton = ({ label, disabled, onUpload, className }) => (
<label
role="button"
disabled={disabled}
className={className}
style={styles.parent}
>
- <span
+ <span>
? +
- style={{
- display: 'flex',
- alignItems: 'center'
- }}
- >
<Icon icon="upload" />
<span>{label}</span>
<input
type="file"
multiple
style={styles.input}
disabled={disabled}
onChange={e => {
if (e.target.files) {
onUpload(Array.from(e.target.files))
}
}}
/>
</span>
</label>
)
export default UploadButton | 13 | 0.25 | 3 | 10 |
bac4b048533c7cd9205c70ea2fc0c1498c1e3a05 | script.js | script.js | var md = window.markdownit();
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
};
rawFile.send(null);
}
// readTextFile("./README.md");
// fetch("./README.md")
// .then(response => response.text())
// .then(text => {
// document.getElementById("markdown-container").innerHTML = text;
// });
| var md = window.markdownit();
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
};
rawFile.send(null);
}
// readTextFile("./README.md");
fetch("./README.md")
.then(response => response.text())
.then(text => {
document.getElementById("markdown-container").innerHTML = text;
});
| Test to load README.md in homepage | Test to load README.md in homepage
| JavaScript | mit | mangabot/mangabot.github.io | javascript | ## Code Before:
var md = window.markdownit();
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
};
rawFile.send(null);
}
// readTextFile("./README.md");
// fetch("./README.md")
// .then(response => response.text())
// .then(text => {
// document.getElementById("markdown-container").innerHTML = text;
// });
## Instruction:
Test to load README.md in homepage
## Code After:
var md = window.markdownit();
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
};
rawFile.send(null);
}
// readTextFile("./README.md");
fetch("./README.md")
.then(response => response.text())
.then(text => {
document.getElementById("markdown-container").innerHTML = text;
});
| var md = window.markdownit();
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
};
rawFile.send(null);
}
// readTextFile("./README.md");
- // fetch("./README.md")
? ---
+ fetch("./README.md")
- // .then(response => response.text())
? ---
+ .then(response => response.text())
- // .then(text => {
? ---
+ .then(text => {
- // document.getElementById("markdown-container").innerHTML = text;
? ---
+ document.getElementById("markdown-container").innerHTML = text;
- // });
? ---
+ }); | 10 | 0.434783 | 5 | 5 |
8032b99c445f1c3ef38581f95bcc981ed089d59c | pelican-bootstrap3/templates/includes/sidebar/social.html | pelican-bootstrap3/templates/includes/sidebar/social.html | {% if SOCIAL %}
{% from 'includes/sidebar/macros.jinja' import title %}
<!-- Sidebar/Social -->
<li class="list-group-item">
<h4>{{ title(_('Social'), DISABLE_SIDEBAR_TITLE_ICONS) }}</h4>
<ul class="list-group" id="social">
{% for s in SOCIAL %}
{% if s[2] %}
{% set name_sanitized = s[2]|lower|replace('+','-plus')|replace(' ','-') %}
{% else %}
{% set name_sanitized = s[0]|lower|replace('+','-plus')|replace(' ','-') %}
{% endif %}
{% if name_sanitized in ['flickr', 'slideshare', 'instagram', 'spotify', 'stack-overflow', 'weibo', 'line-chart', 'home', 'user', 'users', 'envelope', 'envelope-o', 'stack-exchange', 'hacker-news'] %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ ' fa-lg"' %}
{% else %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ '-square fa-lg"' %}
{% endif %}
<li class="list-group-item"><a href="{{ s[1] }}"><i class={{ iconattributes }}></i> {{ s[0] }}</a></li>
{% endfor %}
</ul>
</li>
<!-- End Sidebar/Social -->
{% endif %}
| {% if SOCIAL %}
{% from 'includes/sidebar/macros.jinja' import title %}
<!-- Sidebar/Social -->
<li class="list-group-item">
<h4>{{ title(_('Social'), DISABLE_SIDEBAR_TITLE_ICONS) }}</h4>
<ul class="list-group" id="social">
{% for s in SOCIAL %}
{% if s[2] %}
{% set name_sanitized = s[2]|lower|replace('+','-plus')|replace(' ','-') %}
{% else %}
{% set name_sanitized = s[0]|lower|replace('+','-plus')|replace(' ','-') %}
{% endif %}
{% if name_sanitized in ['flickr', 'slideshare', 'instagram', 'spotify', 'stack-overflow', 'weibo', 'line-chart', 'home', 'user', 'users', 'envelope', 'envelope-o', 'stack-exchange', 'hacker-news', 'gitlab'] %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ ' fa-lg"' %}
{% else %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ '-square fa-lg"' %}
{% endif %}
<li class="list-group-item"><a href="{{ s[1] }}"><i class={{ iconattributes }}></i> {{ s[0] }}</a></li>
{% endfor %}
</ul>
</li>
<!-- End Sidebar/Social -->
{% endif %}
| Add gitlab to non-square icon in pelican-bootstrap3 | Add gitlab to non-square icon in pelican-bootstrap3
This commit adds gitlab to the list of non-square icons in
pelican-bootstrap3.
Cherry picked from commit
getpelican/pelican-themes@c6b9d6610a7fa9ce89ccd4a28f6c8b19f7cf27c9.
| HTML | mit | StevenMaude/pelican-bootstrap3-sm,StevenMaude/pelican-bootstrap3-sm | html | ## Code Before:
{% if SOCIAL %}
{% from 'includes/sidebar/macros.jinja' import title %}
<!-- Sidebar/Social -->
<li class="list-group-item">
<h4>{{ title(_('Social'), DISABLE_SIDEBAR_TITLE_ICONS) }}</h4>
<ul class="list-group" id="social">
{% for s in SOCIAL %}
{% if s[2] %}
{% set name_sanitized = s[2]|lower|replace('+','-plus')|replace(' ','-') %}
{% else %}
{% set name_sanitized = s[0]|lower|replace('+','-plus')|replace(' ','-') %}
{% endif %}
{% if name_sanitized in ['flickr', 'slideshare', 'instagram', 'spotify', 'stack-overflow', 'weibo', 'line-chart', 'home', 'user', 'users', 'envelope', 'envelope-o', 'stack-exchange', 'hacker-news'] %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ ' fa-lg"' %}
{% else %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ '-square fa-lg"' %}
{% endif %}
<li class="list-group-item"><a href="{{ s[1] }}"><i class={{ iconattributes }}></i> {{ s[0] }}</a></li>
{% endfor %}
</ul>
</li>
<!-- End Sidebar/Social -->
{% endif %}
## Instruction:
Add gitlab to non-square icon in pelican-bootstrap3
This commit adds gitlab to the list of non-square icons in
pelican-bootstrap3.
Cherry picked from commit
getpelican/pelican-themes@c6b9d6610a7fa9ce89ccd4a28f6c8b19f7cf27c9.
## Code After:
{% if SOCIAL %}
{% from 'includes/sidebar/macros.jinja' import title %}
<!-- Sidebar/Social -->
<li class="list-group-item">
<h4>{{ title(_('Social'), DISABLE_SIDEBAR_TITLE_ICONS) }}</h4>
<ul class="list-group" id="social">
{% for s in SOCIAL %}
{% if s[2] %}
{% set name_sanitized = s[2]|lower|replace('+','-plus')|replace(' ','-') %}
{% else %}
{% set name_sanitized = s[0]|lower|replace('+','-plus')|replace(' ','-') %}
{% endif %}
{% if name_sanitized in ['flickr', 'slideshare', 'instagram', 'spotify', 'stack-overflow', 'weibo', 'line-chart', 'home', 'user', 'users', 'envelope', 'envelope-o', 'stack-exchange', 'hacker-news', 'gitlab'] %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ ' fa-lg"' %}
{% else %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ '-square fa-lg"' %}
{% endif %}
<li class="list-group-item"><a href="{{ s[1] }}"><i class={{ iconattributes }}></i> {{ s[0] }}</a></li>
{% endfor %}
</ul>
</li>
<!-- End Sidebar/Social -->
{% endif %}
| {% if SOCIAL %}
{% from 'includes/sidebar/macros.jinja' import title %}
<!-- Sidebar/Social -->
<li class="list-group-item">
<h4>{{ title(_('Social'), DISABLE_SIDEBAR_TITLE_ICONS) }}</h4>
<ul class="list-group" id="social">
{% for s in SOCIAL %}
{% if s[2] %}
{% set name_sanitized = s[2]|lower|replace('+','-plus')|replace(' ','-') %}
{% else %}
{% set name_sanitized = s[0]|lower|replace('+','-plus')|replace(' ','-') %}
{% endif %}
- {% if name_sanitized in ['flickr', 'slideshare', 'instagram', 'spotify', 'stack-overflow', 'weibo', 'line-chart', 'home', 'user', 'users', 'envelope', 'envelope-o', 'stack-exchange', 'hacker-news'] %}
+ {% if name_sanitized in ['flickr', 'slideshare', 'instagram', 'spotify', 'stack-overflow', 'weibo', 'line-chart', 'home', 'user', 'users', 'envelope', 'envelope-o', 'stack-exchange', 'hacker-news', 'gitlab'] %}
? ++++++++++
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ ' fa-lg"' %}
{% else %}
{% set iconattributes = '"fa fa-' ~ name_sanitized ~ '-square fa-lg"' %}
{% endif %}
<li class="list-group-item"><a href="{{ s[1] }}"><i class={{ iconattributes }}></i> {{ s[0] }}</a></li>
{% endfor %}
</ul>
</li>
<!-- End Sidebar/Social -->
{% endif %} | 2 | 0.083333 | 1 | 1 |
902fd84984fc4b86ea1d3e814eb17174c536e046 | src/Frontend/Modules/Profiles/Tests/Engine/AuthenticationTest.php | src/Frontend/Modules/Profiles/Tests/Engine/AuthenticationTest.php | <?php
namespace Frontend\Modules\Profiles\Tests\Engine;
use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;
final class AuthenticationTest extends WebTestCase
{
/** @var SpoonDatabase */
private $database;
public function setUp(): void
{
parent::setUp();
if (!defined('APPLICATION')) {
define('APPLICATION', 'Frontend');
}
$client = self::createClient();
$this->loadFixtures($client, [LoadProfiles::class]);
$this->database = FrontendModel::get('database');
}
public function testOldSessionCleanUp()
{
$this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
Authentication::cleanupOldSessions();
$this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
}
}
| <?php
namespace Frontend\Modules\Profiles\Tests\Engine;
use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;
final class AuthenticationTest extends WebTestCase
{
/** @var SpoonDatabase */
private $database;
public function setUp(): void
{
parent::setUp();
if (!defined('APPLICATION')) {
define('APPLICATION', 'Frontend');
}
$client = self::createClient();
$this->loadFixtures($client, [LoadProfiles::class]);
$this->database = FrontendModel::get('database');
}
public function testOldSessionCleanUp()
{
$this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
Authentication::cleanupOldSessions();
$this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
}
public function testGettingLoginStatusForNonExistingUser()
{
$this->assertEquals('invalid', Authentication::getLoginStatus('non@existe.nt', 'wrong'));
}
public function testGettingLoginStatusForUserWithWrongPassword()
{
$this->assertEquals('invalid', Authentication::getLoginStatus('test-active@fork-cms.com', 'wrong'));
}
public function testGettingLoginStatusForActiveUserWithCorrectPassword()
{
$this->assertEquals('active', Authentication::getLoginStatus('test-active@fork-cms.com', 'forkcms'));
}
public function testGettingLoginStatusForInactiveUserWithCorrectPassword()
{
$this->assertEquals('inactive', Authentication::getLoginStatus('test-inactive@fork-cms.com', 'forkcms'));
}
public function testGettingLoginStatusForDeletedUserWithCorrectPassword()
{
$this->assertEquals('deleted', Authentication::getLoginStatus('test-deleted@fork-cms.com', 'forkcms'));
}
public function testGettingLoginStatusForBlockedUserWithCorrectPassword()
{
$this->assertEquals('blocked', Authentication::getLoginStatus('test-blocked@fork-cms.com', 'forkcms'));
}
}
| Test getting the login status of a profile | Test getting the login status of a profile
| PHP | mit | carakas/forkcms,bartdc/forkcms,forkcms/forkcms,bartdc/forkcms,jonasdekeukelaere/forkcms,carakas/forkcms,sumocoders/forkcms,jessedobbelaere/forkcms,forkcms/forkcms,sumocoders/forkcms,jacob-v-dam/forkcms,jessedobbelaere/forkcms,jacob-v-dam/forkcms,jacob-v-dam/forkcms,carakas/forkcms,jessedobbelaere/forkcms,sumocoders/forkcms,justcarakas/forkcms,jessedobbelaere/forkcms,jacob-v-dam/forkcms,bartdc/forkcms,carakas/forkcms,justcarakas/forkcms,jonasdekeukelaere/forkcms,jonasdekeukelaere/forkcms,sumocoders/forkcms,forkcms/forkcms,forkcms/forkcms,jonasdekeukelaere/forkcms,jonasdekeukelaere/forkcms,sumocoders/forkcms,carakas/forkcms,justcarakas/forkcms | php | ## Code Before:
<?php
namespace Frontend\Modules\Profiles\Tests\Engine;
use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;
final class AuthenticationTest extends WebTestCase
{
/** @var SpoonDatabase */
private $database;
public function setUp(): void
{
parent::setUp();
if (!defined('APPLICATION')) {
define('APPLICATION', 'Frontend');
}
$client = self::createClient();
$this->loadFixtures($client, [LoadProfiles::class]);
$this->database = FrontendModel::get('database');
}
public function testOldSessionCleanUp()
{
$this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
Authentication::cleanupOldSessions();
$this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
}
}
## Instruction:
Test getting the login status of a profile
## Code After:
<?php
namespace Frontend\Modules\Profiles\Tests\Engine;
use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;
final class AuthenticationTest extends WebTestCase
{
/** @var SpoonDatabase */
private $database;
public function setUp(): void
{
parent::setUp();
if (!defined('APPLICATION')) {
define('APPLICATION', 'Frontend');
}
$client = self::createClient();
$this->loadFixtures($client, [LoadProfiles::class]);
$this->database = FrontendModel::get('database');
}
public function testOldSessionCleanUp()
{
$this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
Authentication::cleanupOldSessions();
$this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
}
public function testGettingLoginStatusForNonExistingUser()
{
$this->assertEquals('invalid', Authentication::getLoginStatus('non@existe.nt', 'wrong'));
}
public function testGettingLoginStatusForUserWithWrongPassword()
{
$this->assertEquals('invalid', Authentication::getLoginStatus('test-active@fork-cms.com', 'wrong'));
}
public function testGettingLoginStatusForActiveUserWithCorrectPassword()
{
$this->assertEquals('active', Authentication::getLoginStatus('test-active@fork-cms.com', 'forkcms'));
}
public function testGettingLoginStatusForInactiveUserWithCorrectPassword()
{
$this->assertEquals('inactive', Authentication::getLoginStatus('test-inactive@fork-cms.com', 'forkcms'));
}
public function testGettingLoginStatusForDeletedUserWithCorrectPassword()
{
$this->assertEquals('deleted', Authentication::getLoginStatus('test-deleted@fork-cms.com', 'forkcms'));
}
public function testGettingLoginStatusForBlockedUserWithCorrectPassword()
{
$this->assertEquals('blocked', Authentication::getLoginStatus('test-blocked@fork-cms.com', 'forkcms'));
}
}
| <?php
namespace Frontend\Modules\Profiles\Tests\Engine;
use Common\WebTestCase;
use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Modules\Profiles\Engine\Authentication;
use Frontend\Modules\Profiles\Tests\DataFixtures\LoadProfiles;
use SpoonDatabase;
final class AuthenticationTest extends WebTestCase
{
/** @var SpoonDatabase */
private $database;
public function setUp(): void
{
parent::setUp();
if (!defined('APPLICATION')) {
define('APPLICATION', 'Frontend');
}
$client = self::createClient();
$this->loadFixtures($client, [LoadProfiles::class]);
$this->database = FrontendModel::get('database');
}
public function testOldSessionCleanUp()
{
$this->assertEquals('2', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
Authentication::cleanupOldSessions();
$this->assertEquals('1', $this->database->getVar('SELECT COUNT(session_id) FROM profiles_sessions'));
}
+
+ public function testGettingLoginStatusForNonExistingUser()
+ {
+ $this->assertEquals('invalid', Authentication::getLoginStatus('non@existe.nt', 'wrong'));
+ }
+
+ public function testGettingLoginStatusForUserWithWrongPassword()
+ {
+ $this->assertEquals('invalid', Authentication::getLoginStatus('test-active@fork-cms.com', 'wrong'));
+ }
+
+ public function testGettingLoginStatusForActiveUserWithCorrectPassword()
+ {
+ $this->assertEquals('active', Authentication::getLoginStatus('test-active@fork-cms.com', 'forkcms'));
+ }
+
+ public function testGettingLoginStatusForInactiveUserWithCorrectPassword()
+ {
+ $this->assertEquals('inactive', Authentication::getLoginStatus('test-inactive@fork-cms.com', 'forkcms'));
+ }
+
+ public function testGettingLoginStatusForDeletedUserWithCorrectPassword()
+ {
+ $this->assertEquals('deleted', Authentication::getLoginStatus('test-deleted@fork-cms.com', 'forkcms'));
+ }
+
+ public function testGettingLoginStatusForBlockedUserWithCorrectPassword()
+ {
+ $this->assertEquals('blocked', Authentication::getLoginStatus('test-blocked@fork-cms.com', 'forkcms'));
+ }
} | 30 | 0.789474 | 30 | 0 |
515e040a35806af3c52f49fa12d33786daa2055b | README.md | README.md | dp832-gui
=========
Rigol DP832 GUI. This is a simple graphing GUI for the Rigol DP832 connected via VISA (tested over USB although other IO connections should work).
To use this you'll need to install:
* Ultra Sigma from Rigol
* Python 2.7 with PySide, suggested to just install WinPython (see http://winpython.sourceforge.net/)
* PyQtGraph, see http://www.pyqtgraph.org/
* pyvisa, use easy_install
Once your system is running, just run dpgui.py via your installed Python. Supply the address string (open Ultra Sigma, make sure it finds your
Power Supply, and copy-paste address string from that). Will look something like USB0::0x1AB1::0x0E11::DP8XXXXXXXX::INSTR
Bugs
=======
* Can only set number of windows before connecting
* Doesn't validate instrument state before doing anything, so crashes are likely. Check python output for reasons.
Notes
========
While connected remotely you CANNOT control the power supply from the front panel. You can turn outputs on/off seems to be about it. So setup your
required voltages etc first then hit connect. If you want to change anything just disconnect, modify settings on the panel, and connect again. You
don't need to restart the dp832gui application. | dp832-gui
=========
Rigol DP832 GUI. This is a simple graphing GUI for the Rigol DP832 connected via VISA (tested over USB although other IO connections should work).
To use this you'll need to install:
* Ultra Sigma from Rigol [OPTIONAL: Can also just copy/paste the address from the DP832 display]
* Python 2.7 with PySide, suggested to just install WinPython (see http://winpython.sourceforge.net/)
* PyQtGraph, see http://www.pyqtgraph.org/
* pyvisa, use easy_install
Once your system is running, just run dpgui.py via your installed Python. Supply the address string (open Ultra Sigma, make sure it finds your Power Supply, and copy-paste address string from that, OR just look in the 'utilities' menu). Will look something like USB0::0x1AB1::0x0E11::DP8XXXXXXXX::INSTR
If the address copied from the DP832 display doesn't work, install Ultra Sigma to confirm it is detected there. If Ultra Sigma didn't see the power supply something else is up...
Bugs
=======
* Can only set number of windows before connecting
* Doesn't validate instrument state before doing anything, so crashes are likely. Check python output for reasons.
Notes
========
While connected remotely you CANNOT control the power supply from the front panel. You can turn outputs on/off seems to be about it. So setup your required voltages etc first then hit connect. If you want to change anything just disconnect, modify settings on the panel, and connect again. You don't need to restart the dp832gui application.
| Add note that ultra sigma not needed | Add note that ultra sigma not needed | Markdown | mit | colinoflynn/dp832-gui | markdown | ## Code Before:
dp832-gui
=========
Rigol DP832 GUI. This is a simple graphing GUI for the Rigol DP832 connected via VISA (tested over USB although other IO connections should work).
To use this you'll need to install:
* Ultra Sigma from Rigol
* Python 2.7 with PySide, suggested to just install WinPython (see http://winpython.sourceforge.net/)
* PyQtGraph, see http://www.pyqtgraph.org/
* pyvisa, use easy_install
Once your system is running, just run dpgui.py via your installed Python. Supply the address string (open Ultra Sigma, make sure it finds your
Power Supply, and copy-paste address string from that). Will look something like USB0::0x1AB1::0x0E11::DP8XXXXXXXX::INSTR
Bugs
=======
* Can only set number of windows before connecting
* Doesn't validate instrument state before doing anything, so crashes are likely. Check python output for reasons.
Notes
========
While connected remotely you CANNOT control the power supply from the front panel. You can turn outputs on/off seems to be about it. So setup your
required voltages etc first then hit connect. If you want to change anything just disconnect, modify settings on the panel, and connect again. You
don't need to restart the dp832gui application.
## Instruction:
Add note that ultra sigma not needed
## Code After:
dp832-gui
=========
Rigol DP832 GUI. This is a simple graphing GUI for the Rigol DP832 connected via VISA (tested over USB although other IO connections should work).
To use this you'll need to install:
* Ultra Sigma from Rigol [OPTIONAL: Can also just copy/paste the address from the DP832 display]
* Python 2.7 with PySide, suggested to just install WinPython (see http://winpython.sourceforge.net/)
* PyQtGraph, see http://www.pyqtgraph.org/
* pyvisa, use easy_install
Once your system is running, just run dpgui.py via your installed Python. Supply the address string (open Ultra Sigma, make sure it finds your Power Supply, and copy-paste address string from that, OR just look in the 'utilities' menu). Will look something like USB0::0x1AB1::0x0E11::DP8XXXXXXXX::INSTR
If the address copied from the DP832 display doesn't work, install Ultra Sigma to confirm it is detected there. If Ultra Sigma didn't see the power supply something else is up...
Bugs
=======
* Can only set number of windows before connecting
* Doesn't validate instrument state before doing anything, so crashes are likely. Check python output for reasons.
Notes
========
While connected remotely you CANNOT control the power supply from the front panel. You can turn outputs on/off seems to be about it. So setup your required voltages etc first then hit connect. If you want to change anything just disconnect, modify settings on the panel, and connect again. You don't need to restart the dp832gui application.
| dp832-gui
=========
Rigol DP832 GUI. This is a simple graphing GUI for the Rigol DP832 connected via VISA (tested over USB although other IO connections should work).
To use this you'll need to install:
- * Ultra Sigma from Rigol
+ * Ultra Sigma from Rigol [OPTIONAL: Can also just copy/paste the address from the DP832 display]
* Python 2.7 with PySide, suggested to just install WinPython (see http://winpython.sourceforge.net/)
* PyQtGraph, see http://www.pyqtgraph.org/
* pyvisa, use easy_install
- Once your system is running, just run dpgui.py via your installed Python. Supply the address string (open Ultra Sigma, make sure it finds your
- Power Supply, and copy-paste address string from that). Will look something like USB0::0x1AB1::0x0E11::DP8XXXXXXXX::INSTR
+ Once your system is running, just run dpgui.py via your installed Python. Supply the address string (open Ultra Sigma, make sure it finds your Power Supply, and copy-paste address string from that, OR just look in the 'utilities' menu). Will look something like USB0::0x1AB1::0x0E11::DP8XXXXXXXX::INSTR
+
+ If the address copied from the DP832 display doesn't work, install Ultra Sigma to confirm it is detected there. If Ultra Sigma didn't see the power supply something else is up...
Bugs
=======
* Can only set number of windows before connecting
* Doesn't validate instrument state before doing anything, so crashes are likely. Check python output for reasons.
Notes
========
+ While connected remotely you CANNOT control the power supply from the front panel. You can turn outputs on/off seems to be about it. So setup your required voltages etc first then hit connect. If you want to change anything just disconnect, modify settings on the panel, and connect again. You don't need to restart the dp832gui application.
- While connected remotely you CANNOT control the power supply from the front panel. You can turn outputs on/off seems to be about it. So setup your
- required voltages etc first then hit connect. If you want to change anything just disconnect, modify settings on the panel, and connect again. You
- don't need to restart the dp832gui application. | 11 | 0.407407 | 5 | 6 |
49c1eafbc7eccdd74bc3aa7055042c8f11e0b36b | tests/json/connection_uri/valid-warnings.json | tests/json/connection_uri/valid-warnings.json | {
"tests": [
{
"description": "Unrecognized option keys are ignored",
"uri": "mongodb://example.com/?foo=bar",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Repeated option keys",
"uri": "mongodb://example.com/?replicaSet=test&replicaSet=test",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"replicaset": "test"
}
},
{
"description": "Deprecated (or unknown) options are ignored if replacement exists",
"uri": "mongodb://example.com/?wtimeout=5&wtimeoutMS=10",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"wtimeoutms": 10
}
}
]
}
| {
"tests": [
{
"description": "Unrecognized option keys are ignored",
"uri": "mongodb://example.com/?foo=bar",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Unsupported option values are ignored",
"uri": "mongodb://example.com/?fsync=ifPossible",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Repeated option keys",
"uri": "mongodb://example.com/?replicaSet=test&replicaSet=test",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"replicaset": "test"
}
},
{
"description": "Deprecated (or unknown) options are ignored if replacement exists",
"uri": "mongodb://example.com/?wtimeout=5&wtimeoutMS=10",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"wtimeoutms": 10
}
}
]
} | Revert "CDRIVER-2022 Missing support for fsync in connection uri" | Revert "CDRIVER-2022 Missing support for fsync in connection uri"
This reverts commit 632da6a1b97cccf31121bc043e350de5b8e95e6c.
| JSON | apache-2.0 | ajdavis/mongo-c-driver,ajdavis/mongo-c-driver,malexzx/mongo-c-driver,rcsanchez97/mongo-c-driver,remicollet/mongo-c-driver,beingmeta/mongo-c-driver,derickr/mongo-c-driver,rcsanchez97/mongo-c-driver,mongodb/mongo-c-driver,acmorrow/mongo-c-driver,malexzx/mongo-c-driver,mongodb/mongo-c-driver,ajdavis/mongo-c-driver,mongodb/mongo-c-driver,beingmeta/mongo-c-driver,jmikola/mongo-c-driver,mongodb/mongo-c-driver,jmikola/mongo-c-driver,acmorrow/mongo-c-driver,beingmeta/mongo-c-driver,rcsanchez97/mongo-c-driver,remicollet/mongo-c-driver,malexzx/mongo-c-driver,bjori/mongo-c-driver,acmorrow/mongo-c-driver,bjori/mongo-c-driver,jmikola/mongo-c-driver,acmorrow/mongo-c-driver,jmikola/mongo-c-driver,ajdavis/mongo-c-driver,beingmeta/mongo-c-driver,remicollet/mongo-c-driver,jmikola/mongo-c-driver,jmikola/mongo-c-driver,acmorrow/mongo-c-driver,acmorrow/mongo-c-driver,remicollet/mongo-c-driver,ajdavis/mongo-c-driver,bjori/mongo-c-driver,mongodb/mongo-c-driver,bjori/mongo-c-driver,bjori/mongo-c-driver,beingmeta/mongo-c-driver,derickr/mongo-c-driver,rcsanchez97/mongo-c-driver,acmorrow/mongo-c-driver,rcsanchez97/mongo-c-driver,mongodb/mongo-c-driver,derickr/mongo-c-driver,rcsanchez97/mongo-c-driver,remicollet/mongo-c-driver,derickr/mongo-c-driver,derickr/mongo-c-driver,ajdavis/mongo-c-driver,bjori/mongo-c-driver,beingmeta/mongo-c-driver,jmikola/mongo-c-driver,malexzx/mongo-c-driver,mongodb/mongo-c-driver,rcsanchez97/mongo-c-driver,beingmeta/mongo-c-driver,bjori/mongo-c-driver,remicollet/mongo-c-driver,remicollet/mongo-c-driver,derickr/mongo-c-driver,beingmeta/mongo-c-driver,ajdavis/mongo-c-driver,derickr/mongo-c-driver | json | ## Code Before:
{
"tests": [
{
"description": "Unrecognized option keys are ignored",
"uri": "mongodb://example.com/?foo=bar",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Repeated option keys",
"uri": "mongodb://example.com/?replicaSet=test&replicaSet=test",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"replicaset": "test"
}
},
{
"description": "Deprecated (or unknown) options are ignored if replacement exists",
"uri": "mongodb://example.com/?wtimeout=5&wtimeoutMS=10",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"wtimeoutms": 10
}
}
]
}
## Instruction:
Revert "CDRIVER-2022 Missing support for fsync in connection uri"
This reverts commit 632da6a1b97cccf31121bc043e350de5b8e95e6c.
## Code After:
{
"tests": [
{
"description": "Unrecognized option keys are ignored",
"uri": "mongodb://example.com/?foo=bar",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Unsupported option values are ignored",
"uri": "mongodb://example.com/?fsync=ifPossible",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Repeated option keys",
"uri": "mongodb://example.com/?replicaSet=test&replicaSet=test",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"replicaset": "test"
}
},
{
"description": "Deprecated (or unknown) options are ignored if replacement exists",
"uri": "mongodb://example.com/?wtimeout=5&wtimeoutMS=10",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"wtimeoutms": 10
}
}
]
} | {
"tests": [
{
"description": "Unrecognized option keys are ignored",
"uri": "mongodb://example.com/?foo=bar",
+ "valid": true,
+ "warning": true,
+ "hosts": [
+ {
+ "type": "hostname",
+ "host": "example.com",
+ "port": null
+ }
+ ],
+ "auth": null,
+ "options": null
+ },
+ {
+ "description": "Unsupported option values are ignored",
+ "uri": "mongodb://example.com/?fsync=ifPossible",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": null
},
{
"description": "Repeated option keys",
"uri": "mongodb://example.com/?replicaSet=test&replicaSet=test",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"replicaset": "test"
}
},
{
"description": "Deprecated (or unknown) options are ignored if replacement exists",
"uri": "mongodb://example.com/?wtimeout=5&wtimeoutMS=10",
"valid": true,
"warning": true,
"hosts": [
{
"type": "hostname",
"host": "example.com",
"port": null
}
],
"auth": null,
"options": {
"wtimeoutms": 10
}
}
]
} | 15 | 0.283019 | 15 | 0 |
6a0fb90790006de9f1fc67725323d2c530e4555d | src/elements/land-registry/search-form/template.hbs | src/elements/land-registry/search-form/template.hbs | <form method="post" class="search-form" data-clientside-validation="search_form_validation{{id}}" data-clientside-validation-no-summary>
<div class="form-group spacing-bottom-half">
{{#if h1}}<h1>{{/if}}
<label class="form-label bold-medium spacing-bottom-half" for="search{{id}}">{{label}}</label>
{{#if h1}}</h1>{{/if}}
<input class="form-control" id="search{{id}}" name="search" type="text" value="{{value}}">
<input class="button" type="submit" name="search-button" value="Search">
</div>
</form>
<script type="application/json" id="search_form_validation{{id}}">
{
"search": {
"presence": {
"message": "Please enter a search term"
}
}
}
</script>
| <form method="post" class="search-form" data-clientside-validation="search_form_validation{{id}}" data-clientside-validation-no-summary>
<div class="form-group spacing-bottom-half">
{{#if h1}}<h1>{{/if}}
<label class="form-label bold-medium spacing-bottom-half" for="search{{id}}">
{{label}}
{{#if h1}}
<span class="visuallyhidden">{{value}}</span>
{{/if}}
</label>
{{#if h1}}</h1>{{/if}}
<input class="form-control" id="search{{id}}" name="search" type="text" value="{{value}}">
<input class="button" type="submit" name="search-button" value="Search">
</div>
</form>
<script type="application/json" id="search_form_validation{{id}}">
{
"search": {
"presence": {
"message": "Please enter a search term"
}
}
}
</script>
| Add hidden search term to search results page title | Add hidden search term to search results page title
| Handlebars | mit | LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements | handlebars | ## Code Before:
<form method="post" class="search-form" data-clientside-validation="search_form_validation{{id}}" data-clientside-validation-no-summary>
<div class="form-group spacing-bottom-half">
{{#if h1}}<h1>{{/if}}
<label class="form-label bold-medium spacing-bottom-half" for="search{{id}}">{{label}}</label>
{{#if h1}}</h1>{{/if}}
<input class="form-control" id="search{{id}}" name="search" type="text" value="{{value}}">
<input class="button" type="submit" name="search-button" value="Search">
</div>
</form>
<script type="application/json" id="search_form_validation{{id}}">
{
"search": {
"presence": {
"message": "Please enter a search term"
}
}
}
</script>
## Instruction:
Add hidden search term to search results page title
## Code After:
<form method="post" class="search-form" data-clientside-validation="search_form_validation{{id}}" data-clientside-validation-no-summary>
<div class="form-group spacing-bottom-half">
{{#if h1}}<h1>{{/if}}
<label class="form-label bold-medium spacing-bottom-half" for="search{{id}}">
{{label}}
{{#if h1}}
<span class="visuallyhidden">{{value}}</span>
{{/if}}
</label>
{{#if h1}}</h1>{{/if}}
<input class="form-control" id="search{{id}}" name="search" type="text" value="{{value}}">
<input class="button" type="submit" name="search-button" value="Search">
</div>
</form>
<script type="application/json" id="search_form_validation{{id}}">
{
"search": {
"presence": {
"message": "Please enter a search term"
}
}
}
</script>
| <form method="post" class="search-form" data-clientside-validation="search_form_validation{{id}}" data-clientside-validation-no-summary>
<div class="form-group spacing-bottom-half">
{{#if h1}}<h1>{{/if}}
- <label class="form-label bold-medium spacing-bottom-half" for="search{{id}}">{{label}}</label>
? -----------------
+ <label class="form-label bold-medium spacing-bottom-half" for="search{{id}}">
+ {{label}}
+
+ {{#if h1}}
+ <span class="visuallyhidden">{{value}}</span>
+ {{/if}}
+ </label>
{{#if h1}}</h1>{{/if}}
<input class="form-control" id="search{{id}}" name="search" type="text" value="{{value}}">
<input class="button" type="submit" name="search-button" value="Search">
</div>
</form>
<script type="application/json" id="search_form_validation{{id}}">
{
"search": {
"presence": {
"message": "Please enter a search term"
}
}
}
</script> | 8 | 0.4 | 7 | 1 |
7437a8453bfdfc8515629ee405df37d791305a77 | lib/rspec/junklet.rb | lib/rspec/junklet.rb | require_relative "./junklet/version"
require_relative "./junklet/junk"
require_relative "./junklet/junklet"
RSpec.configure do |config|
config.extend(RSpec::Junklet::Junklet)
config.extend(RSpec::Junklet::Junk) # when metaprogramming cases, you may need junk in ExampleGroups
config.include(RSpec::Junklet::Junk)
end
| require_relative "./junklet/version"
require_relative "./junklet/junk"
require_relative "./junklet/junklet"
# Automatically hook into RSpec when you `include "rspec-junklet"`
RSpec.configure do |config|
config.extend(RSpec::Junklet::Junklet) # This lets us say junklet() in describes and contexts
config.extend(RSpec::Junklet::Junk) # This lets us say junk() in describes and contexts
config.include(RSpec::Junklet::Junk) # This lets us say junk() in lets
end
| Add comments to better document RSpec includes and extends | Add comments to better document RSpec includes and extends
| Ruby | mit | dbrady/rspec-junklet | ruby | ## Code Before:
require_relative "./junklet/version"
require_relative "./junklet/junk"
require_relative "./junklet/junklet"
RSpec.configure do |config|
config.extend(RSpec::Junklet::Junklet)
config.extend(RSpec::Junklet::Junk) # when metaprogramming cases, you may need junk in ExampleGroups
config.include(RSpec::Junklet::Junk)
end
## Instruction:
Add comments to better document RSpec includes and extends
## Code After:
require_relative "./junklet/version"
require_relative "./junklet/junk"
require_relative "./junklet/junklet"
# Automatically hook into RSpec when you `include "rspec-junklet"`
RSpec.configure do |config|
config.extend(RSpec::Junklet::Junklet) # This lets us say junklet() in describes and contexts
config.extend(RSpec::Junklet::Junk) # This lets us say junk() in describes and contexts
config.include(RSpec::Junklet::Junk) # This lets us say junk() in lets
end
| require_relative "./junklet/version"
require_relative "./junklet/junk"
require_relative "./junklet/junklet"
+ # Automatically hook into RSpec when you `include "rspec-junklet"`
RSpec.configure do |config|
- config.extend(RSpec::Junklet::Junklet)
- config.extend(RSpec::Junklet::Junk) # when metaprogramming cases, you may need junk in ExampleGroups
- config.include(RSpec::Junklet::Junk)
+ config.extend(RSpec::Junklet::Junklet) # This lets us say junklet() in describes and contexts
+ config.extend(RSpec::Junklet::Junk) # This lets us say junk() in describes and contexts
+ config.include(RSpec::Junklet::Junk) # This lets us say junk() in lets
end | 7 | 0.777778 | 4 | 3 |
1e320def46d886031900b61230efe925ee1a2017 | README.md | README.md | Online Graphbviz Generator
=========================
This is a simple Go webapp that lets you type in Graphviz graph language
and display the generated image.
Building
========
1. Check out the gvweb repo to your $GOPATH/src/
2. cd $GOPATH/src/gvweb/
3. go build && ./gvweb -port=4444
| Online Graphbviz Generator
=========================
This is a simple Go webapp that lets you type in Graphviz graph language
and display the generated image.
Building
========
1. Check out the gvweb repo to your $GOPATH/src/
2. cd $GOPATH/src/gvweb/
3. go build && ./gvweb -port=4444
Example
=======
See http://fiane.mooo.com:8080/graphvizweb/ for a running instance
| Add URL for running instance | Add URL for running instance
| Markdown | mit | noselasd/gvweb,noselasd/gvweb,noselasd/gvweb,noselasd/gvweb | markdown | ## Code Before:
Online Graphbviz Generator
=========================
This is a simple Go webapp that lets you type in Graphviz graph language
and display the generated image.
Building
========
1. Check out the gvweb repo to your $GOPATH/src/
2. cd $GOPATH/src/gvweb/
3. go build && ./gvweb -port=4444
## Instruction:
Add URL for running instance
## Code After:
Online Graphbviz Generator
=========================
This is a simple Go webapp that lets you type in Graphviz graph language
and display the generated image.
Building
========
1. Check out the gvweb repo to your $GOPATH/src/
2. cd $GOPATH/src/gvweb/
3. go build && ./gvweb -port=4444
Example
=======
See http://fiane.mooo.com:8080/graphvizweb/ for a running instance
| Online Graphbviz Generator
=========================
This is a simple Go webapp that lets you type in Graphviz graph language
and display the generated image.
Building
========
1. Check out the gvweb repo to your $GOPATH/src/
2. cd $GOPATH/src/gvweb/
3. go build && ./gvweb -port=4444
+ Example
+ =======
+ See http://fiane.mooo.com:8080/graphvizweb/ for a running instance | 3 | 0.25 | 3 | 0 |
083597ef0d398e40ac23ea5e2423730538d3ad9f | lib/minimap-find-results-view.coffee | lib/minimap-find-results-view.coffee | {CompositeDisposable} = require 'event-kit'
module.exports = (findAndReplace, minimapPackage) ->
class MinimapFindResultsView
constructor: (@model) ->
@subscriptions = new CompositeDisposable
@subscriptions.add @model.onDidUpdate @markersUpdated
@decorationsByMarkerId = {}
destroy: ->
@subscriptions.dispose()
@destroyDecorations()
@decorationsByMarkerId = {}
@markers = null
destroyDecorations: ->
decoration.destroy() for id, decoration of @decorationsByMarkerId
getMinimap: -> minimapPackage.getActiveMinimap()
markersUpdated: (markers) =>
minimap = @getMinimap()
return unless minimap?
for marker in markers
decoration = minimap.decorateMarker(marker, type: 'highlight', scope: '.minimap .search-result')
@decorationsByMarkerId[marker.id] = decoration
activePaneItemChanged: ->
@destroyDecorations()
setImmediate => @markersUpdated(@model.markers) if @markers?
| {CompositeDisposable} = require 'event-kit'
module.exports = (findAndReplace, minimapPackage) ->
class MinimapFindResultsView
constructor: (@model) ->
@subscriptions = new CompositeDisposable
@subscriptions.add @model.onDidUpdate @markersUpdated
@decorationsByMarkerId = {}
destroy: ->
@subscriptions.dispose()
@destroyDecorations()
@decorationsByMarkerId = {}
@markers = null
destroyDecorations: ->
for id, decoration of @getMinimap().decorationsById
if decoration.getProperties().scope is '.minimap .search-result'
decoration.destroy()
getMinimap: -> minimapPackage.getActiveMinimap()
markersUpdated: (markers) =>
minimap = @getMinimap()
return unless minimap?
for marker in markers
decoration = minimap.decorateMarker(marker, type: 'highlight', scope: '.minimap .search-result')
@decorationsByMarkerId[marker.id] = decoration
activePaneItemChanged: ->
@destroyDecorations()
setImmediate => @markersUpdated(@model.markers) if @markers?
| Fix markers persisting after disabling the plugin | :bug: Fix markers persisting after disabling the plugin
| CoffeeScript | mit | atom-minimap/minimap-find-and-replace | coffeescript | ## Code Before:
{CompositeDisposable} = require 'event-kit'
module.exports = (findAndReplace, minimapPackage) ->
class MinimapFindResultsView
constructor: (@model) ->
@subscriptions = new CompositeDisposable
@subscriptions.add @model.onDidUpdate @markersUpdated
@decorationsByMarkerId = {}
destroy: ->
@subscriptions.dispose()
@destroyDecorations()
@decorationsByMarkerId = {}
@markers = null
destroyDecorations: ->
decoration.destroy() for id, decoration of @decorationsByMarkerId
getMinimap: -> minimapPackage.getActiveMinimap()
markersUpdated: (markers) =>
minimap = @getMinimap()
return unless minimap?
for marker in markers
decoration = minimap.decorateMarker(marker, type: 'highlight', scope: '.minimap .search-result')
@decorationsByMarkerId[marker.id] = decoration
activePaneItemChanged: ->
@destroyDecorations()
setImmediate => @markersUpdated(@model.markers) if @markers?
## Instruction:
:bug: Fix markers persisting after disabling the plugin
## Code After:
{CompositeDisposable} = require 'event-kit'
module.exports = (findAndReplace, minimapPackage) ->
class MinimapFindResultsView
constructor: (@model) ->
@subscriptions = new CompositeDisposable
@subscriptions.add @model.onDidUpdate @markersUpdated
@decorationsByMarkerId = {}
destroy: ->
@subscriptions.dispose()
@destroyDecorations()
@decorationsByMarkerId = {}
@markers = null
destroyDecorations: ->
for id, decoration of @getMinimap().decorationsById
if decoration.getProperties().scope is '.minimap .search-result'
decoration.destroy()
getMinimap: -> minimapPackage.getActiveMinimap()
markersUpdated: (markers) =>
minimap = @getMinimap()
return unless minimap?
for marker in markers
decoration = minimap.decorateMarker(marker, type: 'highlight', scope: '.minimap .search-result')
@decorationsByMarkerId[marker.id] = decoration
activePaneItemChanged: ->
@destroyDecorations()
setImmediate => @markersUpdated(@model.markers) if @markers?
| {CompositeDisposable} = require 'event-kit'
module.exports = (findAndReplace, minimapPackage) ->
class MinimapFindResultsView
constructor: (@model) ->
@subscriptions = new CompositeDisposable
@subscriptions.add @model.onDidUpdate @markersUpdated
@decorationsByMarkerId = {}
destroy: ->
@subscriptions.dispose()
@destroyDecorations()
@decorationsByMarkerId = {}
@markers = null
destroyDecorations: ->
- decoration.destroy() for id, decoration of @decorationsByMarkerId
+ for id, decoration of @getMinimap().decorationsById
+ if decoration.getProperties().scope is '.minimap .search-result'
+ decoration.destroy()
getMinimap: -> minimapPackage.getActiveMinimap()
markersUpdated: (markers) =>
minimap = @getMinimap()
return unless minimap?
for marker in markers
decoration = minimap.decorateMarker(marker, type: 'highlight', scope: '.minimap .search-result')
@decorationsByMarkerId[marker.id] = decoration
activePaneItemChanged: ->
@destroyDecorations()
setImmediate => @markersUpdated(@model.markers) if @markers? | 4 | 0.121212 | 3 | 1 |
e8b728202de10ba35aa0cb1e85ae873c273a1b07 | resources/lang/en/pagination.php | resources/lang/en/pagination.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« Previous',
'next' => 'Next »',
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => 'Previous',
'next' => 'Next',
];
| Remove arrows from the tl string itself | Remove arrows from the tl string itself
| PHP | bsd-2-clause | kbkyzd/eien,kbkyzd/eien | php | ## Code Before:
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '« Previous',
'next' => 'Next »',
];
## Instruction:
Remove arrows from the tl string itself
## Code After:
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => 'Previous',
'next' => 'Next',
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
- 'previous' => '« Previous',
? --------
+ 'previous' => 'Previous',
- 'next' => 'Next »',
? --------
+ 'next' => 'Next',
]; | 4 | 0.210526 | 2 | 2 |
95a1b5a48ac95f6838eeff89efc1490aa978ca74 | lib/page.js | lib/page.js | const wd = require('wd');
const Promise = require('bluebird');
const browser = require('./browser');
const normalise = require('./normalise-logs');
function test (opts) {
return function () {
return Promise.using(browser(opts.browser), (session) => {
return session
.get(opts.url)
.then(() => {
return Promise.resolve()
.then(() => {
if (opts.scroll || opts.reporter === 'fps') {
return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
}
})
.then(() => {
if (typeof opts.inject === 'function') {
return opts.inject(session);
}
})
.then(() => {
return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
.catch(() => {
console.error('Page loading timed out after 120s');
});
})
.then(() => {
return session;
});
})
.sleep(opts.sleep)
.log('performance')
.then((logs) => {
return normalise(logs, opts.url);
});
});
};
}
module.exports = test;
| const wd = require('wd');
const Promise = require('bluebird');
const browser = require('./browser');
const normalise = require('./normalise-logs');
function test (opts) {
return function () {
return Promise.using(browser(opts.browser), (session) => {
return session
.setWindowSize(1024, 768)
.get(opts.url)
.then(() => {
return Promise.resolve()
.then(() => {
if (opts.scroll || opts.reporter === 'fps') {
return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
}
})
.then(() => {
if (typeof opts.inject === 'function') {
return opts.inject(session);
}
})
.then(() => {
return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
.catch(() => {
console.error('Page loading timed out after 120s');
});
})
.then(() => {
return session;
});
})
.sleep(opts.sleep)
.log('performance')
.then((logs) => {
return normalise(logs, opts.url);
});
});
};
}
module.exports = test;
| Fix window size before running tests | Fix window size before running tests
To make tests as repeatable as possible.
| JavaScript | mit | lennym/timeliner,newsuk/timeliner | javascript | ## Code Before:
const wd = require('wd');
const Promise = require('bluebird');
const browser = require('./browser');
const normalise = require('./normalise-logs');
function test (opts) {
return function () {
return Promise.using(browser(opts.browser), (session) => {
return session
.get(opts.url)
.then(() => {
return Promise.resolve()
.then(() => {
if (opts.scroll || opts.reporter === 'fps') {
return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
}
})
.then(() => {
if (typeof opts.inject === 'function') {
return opts.inject(session);
}
})
.then(() => {
return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
.catch(() => {
console.error('Page loading timed out after 120s');
});
})
.then(() => {
return session;
});
})
.sleep(opts.sleep)
.log('performance')
.then((logs) => {
return normalise(logs, opts.url);
});
});
};
}
module.exports = test;
## Instruction:
Fix window size before running tests
To make tests as repeatable as possible.
## Code After:
const wd = require('wd');
const Promise = require('bluebird');
const browser = require('./browser');
const normalise = require('./normalise-logs');
function test (opts) {
return function () {
return Promise.using(browser(opts.browser), (session) => {
return session
.setWindowSize(1024, 768)
.get(opts.url)
.then(() => {
return Promise.resolve()
.then(() => {
if (opts.scroll || opts.reporter === 'fps') {
return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
}
})
.then(() => {
if (typeof opts.inject === 'function') {
return opts.inject(session);
}
})
.then(() => {
return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
.catch(() => {
console.error('Page loading timed out after 120s');
});
})
.then(() => {
return session;
});
})
.sleep(opts.sleep)
.log('performance')
.then((logs) => {
return normalise(logs, opts.url);
});
});
};
}
module.exports = test;
| const wd = require('wd');
const Promise = require('bluebird');
const browser = require('./browser');
const normalise = require('./normalise-logs');
function test (opts) {
return function () {
return Promise.using(browser(opts.browser), (session) => {
return session
+ .setWindowSize(1024, 768)
.get(opts.url)
.then(() => {
return Promise.resolve()
.then(() => {
if (opts.scroll || opts.reporter === 'fps') {
return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);');
}
})
.then(() => {
if (typeof opts.inject === 'function') {
return opts.inject(session);
}
})
.then(() => {
return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000)
.catch(() => {
console.error('Page loading timed out after 120s');
});
})
.then(() => {
return session;
});
})
.sleep(opts.sleep)
.log('performance')
.then((logs) => {
return normalise(logs, opts.url);
});
});
};
}
module.exports = test; | 1 | 0.02381 | 1 | 0 |
df48cbcc96a671010ed9a215cfa5efc4e95c8d82 | lib/documentsToCsv.js | lib/documentsToCsv.js | var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
var entries = doc[handlerName];
entries.forEach(function (entryObject) {
var row = objectToRow(entryObject);
row.unshift(doc._id);
csvWriter.writeRecord(row);
});
});
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv;
| var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
var rows = documentToRows(handlerName, doc);
rows.forEach(function (row) {
csvWriter.writeRecord(row);
});
});
}
function documentToRows(handlerName, doc) {
var rows = [];
(doc[handlerName] || []).forEach(function (entryObject) {
var row = objectToRow(entryObject);
row.unshift(doc._id);
rows.push(row);
});
return rows;
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv;
| Split out an inner loop into a separate function. | Split out an inner loop into a separate function.
| JavaScript | bsd-3-clause | alexjeffburke/express-couchdb-arraysofobjects | javascript | ## Code Before:
var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
var entries = doc[handlerName];
entries.forEach(function (entryObject) {
var row = objectToRow(entryObject);
row.unshift(doc._id);
csvWriter.writeRecord(row);
});
});
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv;
## Instruction:
Split out an inner loop into a separate function.
## Code After:
var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
var rows = documentToRows(handlerName, doc);
rows.forEach(function (row) {
csvWriter.writeRecord(row);
});
});
}
function documentToRows(handlerName, doc) {
var rows = [];
(doc[handlerName] || []).forEach(function (entryObject) {
var row = objectToRow(entryObject);
row.unshift(doc._id);
rows.push(row);
});
return rows;
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv;
| var csv = require('ya-csv');
function documentsToCsv(writer, handlerName, documents) {
var csvWriter = new csv.CsvWriter(writer);
(documents || []).forEach(function (doc) {
- var entries = doc[handlerName];
+ var rows = documentToRows(handlerName, doc);
- entries.forEach(function (entryObject) {
? --- ^^ --- ^^^^^^^
+ rows.forEach(function (row) {
? ^^ ^^
- var row = objectToRow(entryObject);
-
- row.unshift(doc._id);
-
csvWriter.writeRecord(row);
});
});
+ }
+
+ function documentToRows(handlerName, doc) {
+ var rows = [];
+
+ (doc[handlerName] || []).forEach(function (entryObject) {
+ var row = objectToRow(entryObject);
+
+ row.unshift(doc._id);
+
+ rows.push(row);
+ });
+
+ return rows;
}
function objectToRow(entryObject) {
var row = [];
Object.keys(entryObject).forEach(function (prop) {
row.push(entryObject[prop]);
});
return row;
}
module.exports = documentsToCsv; | 22 | 0.758621 | 16 | 6 |
2e150a8214e181730cce297b2e0fcf3a7965cec0 | app/components/search.js | app/components/search.js | const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
handleKeyPress (event) {
if (event.keyCode === 13 && event.keyCode === 27) {
return false
}
},
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
onKeyPress={this.handleKeyPress}
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search
| const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search
| Revert "Fix alert beep on osx" | Revert "Fix alert beep on osx"
| JavaScript | mit | tinytacoteam/zazu,tinytacoteam/zazu | javascript | ## Code Before:
const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
handleKeyPress (event) {
if (event.keyCode === 13 && event.keyCode === 27) {
return false
}
},
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
onKeyPress={this.handleKeyPress}
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search
## Instruction:
Revert "Fix alert beep on osx"
## Code After:
const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search
| const React = require('react')
const Search = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
handleQueryChange: React.PropTypes.func.isRequired,
},
getInitialState () {
return {
input: null,
}
},
focus () {
this.state.input && this.state.input.focus()
},
componentDidMount () {
this.focus()
},
componentDidUpdate () {
if (this.props.value === '') {
this.focus()
}
},
- handleKeyPress (event) {
- if (event.keyCode === 13 && event.keyCode === 27) {
- return false
- }
- },
-
handleQueryChange (event) {
const query = event.target.value
this.props.handleQueryChange(query)
},
setReference (input) {
this.setState({
input,
})
},
render () {
const { value } = this.props
return (
<input
title='Search Zazu'
className='mousetrap'
ref={this.setReference}
type='text'
- onKeyPress={this.handleKeyPress}
onChange={this.handleQueryChange}
value={value}/>
)
},
})
module.exports = Search | 7 | 0.112903 | 0 | 7 |
80d80318aaad7cdea6850210be225fef6dd5fabd | lib/api.js | lib/api.js | // telegram.link
// Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
// Released under the MIT License
// http://telegram.link
// Import dependencies
var tl = require('telegram-tl-node');
// API TL schema as provided by Telegram
var apiTlSchema = require('./api-tlschema.json');
// Declare the `type` module
var type = {_id: 'api.type'};
// List the `api` constructors
var constructors = ['Bool', 'Error', 'Null', 'auth.SentCode'];
// Build the constructors
tl.TypeBuilder.buildTypes(apiTlSchema.constructors, constructors, type);
// Export the 'type' module
exports.type = type;
// Declare the `service` module
var service = { _id: 'api.service'};
// List the `api' methods
var methods = ['auth.sendCode'];
// Build registered methods
tl.TypeBuilder.buildTypes(apiTlSchema.methods, methods, service, true);
// Export the 'service' module
exports.service = service; | // telegram.link
// Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
// Released under the MIT License
// http://telegram.link
// Import dependencies
var tl = require('telegram-tl-node');
// API TL schema as provided by Telegram
var apiTlSchema = require('./api-tlschema.json');
// Declare the `type` module
var type = {_id: 'api.type'};
// Build the constructors
tl.TypeBuilder.buildTypes(apiTlSchema.constructors, null, type);
// Export the 'type' module
exports.type = type;
// Declare the `service` module
var service = { _id: 'api.service'};
// List the `api' methods
var methods = ['auth.sendCode', 'help.getNearestDc', 'help.getConfig'];
// Build registered methods
tl.TypeBuilder.buildTypes(apiTlSchema.methods, methods, service, true);
// Export the 'service' module
exports.service = service; | Include all (!!) the API Type constructors.. Add some API methods | Include all (!!) the API Type constructors..
Add some API methods
| JavaScript | mit | m4h4n/telegram.link,enricostara/telegram.link,lukefx/telegram.link,cgvarela/telegram.link | javascript | ## Code Before:
// telegram.link
// Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
// Released under the MIT License
// http://telegram.link
// Import dependencies
var tl = require('telegram-tl-node');
// API TL schema as provided by Telegram
var apiTlSchema = require('./api-tlschema.json');
// Declare the `type` module
var type = {_id: 'api.type'};
// List the `api` constructors
var constructors = ['Bool', 'Error', 'Null', 'auth.SentCode'];
// Build the constructors
tl.TypeBuilder.buildTypes(apiTlSchema.constructors, constructors, type);
// Export the 'type' module
exports.type = type;
// Declare the `service` module
var service = { _id: 'api.service'};
// List the `api' methods
var methods = ['auth.sendCode'];
// Build registered methods
tl.TypeBuilder.buildTypes(apiTlSchema.methods, methods, service, true);
// Export the 'service' module
exports.service = service;
## Instruction:
Include all (!!) the API Type constructors..
Add some API methods
## Code After:
// telegram.link
// Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
// Released under the MIT License
// http://telegram.link
// Import dependencies
var tl = require('telegram-tl-node');
// API TL schema as provided by Telegram
var apiTlSchema = require('./api-tlschema.json');
// Declare the `type` module
var type = {_id: 'api.type'};
// Build the constructors
tl.TypeBuilder.buildTypes(apiTlSchema.constructors, null, type);
// Export the 'type' module
exports.type = type;
// Declare the `service` module
var service = { _id: 'api.service'};
// List the `api' methods
var methods = ['auth.sendCode', 'help.getNearestDc', 'help.getConfig'];
// Build registered methods
tl.TypeBuilder.buildTypes(apiTlSchema.methods, methods, service, true);
// Export the 'service' module
exports.service = service; | // telegram.link
// Copyright 2014 Enrico Stara 'enrico.stara@gmail.com'
// Released under the MIT License
// http://telegram.link
// Import dependencies
var tl = require('telegram-tl-node');
// API TL schema as provided by Telegram
var apiTlSchema = require('./api-tlschema.json');
// Declare the `type` module
var type = {_id: 'api.type'};
- // List the `api` constructors
- var constructors = ['Bool', 'Error', 'Null', 'auth.SentCode'];
// Build the constructors
- tl.TypeBuilder.buildTypes(apiTlSchema.constructors, constructors, type);
? -- --- ^^^^^
+ tl.TypeBuilder.buildTypes(apiTlSchema.constructors, null, type);
? ^^
// Export the 'type' module
exports.type = type;
// Declare the `service` module
var service = { _id: 'api.service'};
// List the `api' methods
- var methods = ['auth.sendCode'];
+ var methods = ['auth.sendCode', 'help.getNearestDc', 'help.getConfig'];
// Build registered methods
tl.TypeBuilder.buildTypes(apiTlSchema.methods, methods, service, true);
// Export the 'service' module
exports.service = service; | 6 | 0.214286 | 2 | 4 |
377154254676118214c82cf7ea415146e99e5b2d | test/axisym_reacting_low_mach_antioch_cea_constant_regression.sh.in | test/axisym_reacting_low_mach_antioch_cea_constant_regression.sh.in |
PROG="@top_builddir@/test/axisym_reacting_low_mach_regression"
INPUT="@top_builddir@/test/input_files/axisym_reacting_low_mach_antioch_cea_constant_regression.in"
DATA="@top_srcdir@/test/test_data/axisym_reacting_low_mach_antioch_cea_constant_regression.xdr"
${LIBMESH_RUN:-} $PROG input=$INPUT soln-data=$DATA vars='u v T p w_N2 w_N' norms='L2 H1' tol='1.0e-9'
|
PROG="@top_builddir@/test/axisym_reacting_low_mach_regression"
INPUT="@top_builddir@/test/input_files/axisym_reacting_low_mach_antioch_cea_constant_regression.in"
DATA="@top_srcdir@/test/test_data/axisym_reacting_low_mach_antioch_cea_constant_regression.xdr"
# A MOAB preconditioner
PETSC_OPTIONS="-pc_type asm -pc_asm_overlap 10 -sub_pc_type ilu -sub_pc_factor_levels 10"
${LIBMESH_RUN:-} $PROG input=$INPUT soln-data=$DATA vars='u v T p w_N2 w_N' norms='L2 H1' tol='1.0e-9' $PETSC_OPTIONS
| Use MOAB preconditioning on Paul's new test | Use MOAB preconditioning on Paul's new test
Previously "make check" was failing for me on 4 (and possibly other
counts of) processors. Now it works for at least -np 1 through -np 16
| unknown | lgpl-2.1 | cahaynes/grins,vikramvgarg/grins,vikramvgarg/grins,vikramvgarg/grins,cahaynes/grins,vikramvgarg/grins,vikramvgarg/grins,cahaynes/grins,cahaynes/grins,nicholasmalaya/grins,cahaynes/grins,nicholasmalaya/grins,nicholasmalaya/grins,cahaynes/grins,nicholasmalaya/grins,vikramvgarg/grins | unknown | ## Code Before:
PROG="@top_builddir@/test/axisym_reacting_low_mach_regression"
INPUT="@top_builddir@/test/input_files/axisym_reacting_low_mach_antioch_cea_constant_regression.in"
DATA="@top_srcdir@/test/test_data/axisym_reacting_low_mach_antioch_cea_constant_regression.xdr"
${LIBMESH_RUN:-} $PROG input=$INPUT soln-data=$DATA vars='u v T p w_N2 w_N' norms='L2 H1' tol='1.0e-9'
## Instruction:
Use MOAB preconditioning on Paul's new test
Previously "make check" was failing for me on 4 (and possibly other
counts of) processors. Now it works for at least -np 1 through -np 16
## Code After:
PROG="@top_builddir@/test/axisym_reacting_low_mach_regression"
INPUT="@top_builddir@/test/input_files/axisym_reacting_low_mach_antioch_cea_constant_regression.in"
DATA="@top_srcdir@/test/test_data/axisym_reacting_low_mach_antioch_cea_constant_regression.xdr"
# A MOAB preconditioner
PETSC_OPTIONS="-pc_type asm -pc_asm_overlap 10 -sub_pc_type ilu -sub_pc_factor_levels 10"
${LIBMESH_RUN:-} $PROG input=$INPUT soln-data=$DATA vars='u v T p w_N2 w_N' norms='L2 H1' tol='1.0e-9' $PETSC_OPTIONS
|
PROG="@top_builddir@/test/axisym_reacting_low_mach_regression"
INPUT="@top_builddir@/test/input_files/axisym_reacting_low_mach_antioch_cea_constant_regression.in"
DATA="@top_srcdir@/test/test_data/axisym_reacting_low_mach_antioch_cea_constant_regression.xdr"
+ # A MOAB preconditioner
+ PETSC_OPTIONS="-pc_type asm -pc_asm_overlap 10 -sub_pc_type ilu -sub_pc_factor_levels 10"
+
- ${LIBMESH_RUN:-} $PROG input=$INPUT soln-data=$DATA vars='u v T p w_N2 w_N' norms='L2 H1' tol='1.0e-9'
+ ${LIBMESH_RUN:-} $PROG input=$INPUT soln-data=$DATA vars='u v T p w_N2 w_N' norms='L2 H1' tol='1.0e-9' $PETSC_OPTIONS
? +++++++++++++++
| 5 | 0.714286 | 4 | 1 |
ff163bfb68caf00240a345426be033e86b60da92 | app/users/users.service.js | app/users/users.service.js | {
class UsersService {
create(user) {
console.log('CREATED!');
console.log(user);
}
}
angular.module('meganote.users')
.service('UsersService', UsersService);
}
| {
angular.module('meganote.users')
.service('UsersService', [
'$http',
'API_BASE',
($http, API_BASE) => {
class UsersService {
create(user) {
return $http.post(`${API_BASE}users`, {
user,
})
.then(
res => {
console.log(res.data);
}
);
}
}
return new UsersService();
}
]);
}
| Make a POST request to create a user. | Make a POST request to create a user.
| JavaScript | mit | xternbootcamp16/meganote,xternbootcamp16/meganote | javascript | ## Code Before:
{
class UsersService {
create(user) {
console.log('CREATED!');
console.log(user);
}
}
angular.module('meganote.users')
.service('UsersService', UsersService);
}
## Instruction:
Make a POST request to create a user.
## Code After:
{
angular.module('meganote.users')
.service('UsersService', [
'$http',
'API_BASE',
($http, API_BASE) => {
class UsersService {
create(user) {
return $http.post(`${API_BASE}users`, {
user,
})
.then(
res => {
console.log(res.data);
}
);
}
}
return new UsersService();
}
]);
}
| {
+ angular.module('meganote.users')
+ .service('UsersService', [
+ '$http',
+ 'API_BASE',
+ ($http, API_BASE) => {
- class UsersService {
- create(user) {
- console.log('CREATED!');
- console.log(user);
- }
- }
- angular.module('meganote.users')
- .service('UsersService', UsersService);
+ class UsersService {
+ create(user) {
+ return $http.post(`${API_BASE}users`, {
+ user,
+ })
+ .then(
+ res => {
+ console.log(res.data);
+ }
+ );
+ }
+ }
+ return new UsersService();
+
+ }
+ ]);
} | 29 | 2.636364 | 21 | 8 |
219afb54a070a938a43bcd2e1e517ec2439282ca | cookbooks/bach_common/templates/default/motd/bach-variables.erb | cookbooks/bach_common/templates/default/motd/bach-variables.erb |
<% mfg = node['dmi']['system']['manufacturer']
product = node['dmi']['system']['product_name']
gb = (node['memory']['total'].to_f / 1024 / 1024).round
cores = node[:cpu]['0'][:cores].to_i * node[:cpu][:real] %>
cat << EOF
You have logged into a member of a BACH cluster.
<% if node[:virtualization][:role] == 'guest' %>
This is a virtual machine with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% else %>
This system is a <%= mfg %> <%= product %>.
It is equipped with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% end %>
Environment: <%= node.chef_environment %>
Zabbix URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:zabbix][:web_port] %>
Graphite URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:graphite][:web_port] %>
Bootstrap node IP: <%= node[:bcpc][:bootstrap][:server] %>
Roles:
<% node.run_list.each do |entry| %>
<%= " - #{entry.to_s}" %>
<% end %>
EOF
|
<%
mfg = node['dmi']['system']['manufacturer']
product = node['dmi']['system']['product_name']
gb = (node['memory']['total'].to_f / 1024 / 1024).round
cores = node[:cpu]['0'][:cores].to_i * node[:cpu][:real]
chef_bach_version =
node.run_context.cookbook_collection['bach_common'].version rescue nil
%>
cat << EOF
You have logged into a member of a BACH cluster.
<% if node[:virtualization][:role] == 'guest' %>
This is a virtual machine with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% else %>
This system is a <%= mfg %> <%= product %>.
It is equipped with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% end %>
Chef-bach version: <%= chef_bach_version || 'UNKNOWN' %>
Environment: <%= node.chef_environment %>
Zabbix URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:zabbix][:web_port] %>
Graphite URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:graphite][:web_port] %>
Bootstrap node IP: <%= node[:bcpc][:bootstrap][:server] %>
Roles:
<% node.run_list.each do |entry| %>
<%= " - #{entry.to_s}" %>
<% end %>
EOF
| Add chef-bach version to the MotD | Add chef-bach version to the MotD
| HTML+ERB | apache-2.0 | NinjaLabib/chef-bach,leochen4891/chef-bach,amithkanand/chef-bach,amithkanand/chef-bach,amithkanand/chef-bach,kiiranh/chef-bach,leochen4891/chef-bach,pu239ppy/chef-bach,bloomberg/chef-bach,leochen4891/chef-bach,pu239ppy/chef-bach,amithkanand/chef-bach,bijugs/chef-bach,NinjaLabib/chef-bach,bijugs/chef-bach,kiiranh/chef-bach,http-418/chef-bach,bloomberg/chef-bach,http-418/chef-bach,bloomberg/chef-bach,http-418/chef-bach,cbaenziger/chef-bach,NinjaLabib/chef-bach,bijugs/chef-bach,leochen4891/chef-bach,kiiranh/chef-bach,bloomberg/chef-bach,http-418/chef-bach,cbaenziger/chef-bach,pu239ppy/chef-bach,bijugs/chef-bach,kiiranh/chef-bach,cbaenziger/chef-bach,pu239ppy/chef-bach,NinjaLabib/chef-bach,cbaenziger/chef-bach | html+erb | ## Code Before:
<% mfg = node['dmi']['system']['manufacturer']
product = node['dmi']['system']['product_name']
gb = (node['memory']['total'].to_f / 1024 / 1024).round
cores = node[:cpu]['0'][:cores].to_i * node[:cpu][:real] %>
cat << EOF
You have logged into a member of a BACH cluster.
<% if node[:virtualization][:role] == 'guest' %>
This is a virtual machine with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% else %>
This system is a <%= mfg %> <%= product %>.
It is equipped with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% end %>
Environment: <%= node.chef_environment %>
Zabbix URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:zabbix][:web_port] %>
Graphite URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:graphite][:web_port] %>
Bootstrap node IP: <%= node[:bcpc][:bootstrap][:server] %>
Roles:
<% node.run_list.each do |entry| %>
<%= " - #{entry.to_s}" %>
<% end %>
EOF
## Instruction:
Add chef-bach version to the MotD
## Code After:
<%
mfg = node['dmi']['system']['manufacturer']
product = node['dmi']['system']['product_name']
gb = (node['memory']['total'].to_f / 1024 / 1024).round
cores = node[:cpu]['0'][:cores].to_i * node[:cpu][:real]
chef_bach_version =
node.run_context.cookbook_collection['bach_common'].version rescue nil
%>
cat << EOF
You have logged into a member of a BACH cluster.
<% if node[:virtualization][:role] == 'guest' %>
This is a virtual machine with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% else %>
This system is a <%= mfg %> <%= product %>.
It is equipped with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% end %>
Chef-bach version: <%= chef_bach_version || 'UNKNOWN' %>
Environment: <%= node.chef_environment %>
Zabbix URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:zabbix][:web_port] %>
Graphite URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:graphite][:web_port] %>
Bootstrap node IP: <%= node[:bcpc][:bootstrap][:server] %>
Roles:
<% node.run_list.each do |entry| %>
<%= " - #{entry.to_s}" %>
<% end %>
EOF
|
+ <%
- <% mfg = node['dmi']['system']['manufacturer']
? --
+ mfg = node['dmi']['system']['manufacturer']
- product = node['dmi']['system']['product_name']
? --
+ product = node['dmi']['system']['product_name']
- gb = (node['memory']['total'].to_f / 1024 / 1024).round
? --
+ gb = (node['memory']['total'].to_f / 1024 / 1024).round
- cores = node[:cpu]['0'][:cores].to_i * node[:cpu][:real] %>
? -- ---
+ cores = node[:cpu]['0'][:cores].to_i * node[:cpu][:real]
+
+ chef_bach_version =
+ node.run_context.cookbook_collection['bach_common'].version rescue nil
+ %>
cat << EOF
You have logged into a member of a BACH cluster.
<% if node[:virtualization][:role] == 'guest' %>
This is a virtual machine with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% else %>
This system is a <%= mfg %> <%= product %>.
It is equipped with <%= gb %> GB of RAM and <%= cores %> CPU cores.
<% end %>
+ Chef-bach version: <%= chef_bach_version || 'UNKNOWN' %>
Environment: <%= node.chef_environment %>
Zabbix URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:zabbix][:web_port] %>
Graphite URL: https://<%= node[:bcpc][:management][:vip] %>:<%= node[:bcpc][:graphite][:web_port] %>
Bootstrap node IP: <%= node[:bcpc][:bootstrap][:server] %>
Roles:
<% node.run_list.each do |entry| %>
<%= " - #{entry.to_s}" %>
<% end %>
EOF
- | 15 | 0.535714 | 10 | 5 |
b718ae78b8cbc0c728966ef0c38942e5f0f5ac62 | lib/index.js | lib/index.js | const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
const numResults = options.numResults || 50;
const palette = options.palette || createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier;
| const Color = require('color');
const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
if (options.pallette) {
if (Array.isArray(options.pallette)) {
throw new Error('options.pallette must be an array of colors');
} else if (options.pallette.length < 1) {
throw new Error('options.pallette array cannot be empty');
}
}
const numResults = options.numResults || 50;
const palette = options.palette ? options.palette.map(c => Color(c))
: createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier;
| Check for correct palette type and map to color objects in classify function | Check for correct palette type and map to color objects in classify function
| JavaScript | mit | malwilley/color-of | javascript | ## Code Before:
const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
const numResults = options.numResults || 50;
const palette = options.palette || createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier;
## Instruction:
Check for correct palette type and map to color objects in classify function
## Code After:
const Color = require('color');
const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
if (options.pallette) {
if (Array.isArray(options.pallette)) {
throw new Error('options.pallette must be an array of colors');
} else if (options.pallette.length < 1) {
throw new Error('options.pallette array cannot be empty');
}
}
const numResults = options.numResults || 50;
const palette = options.palette ? options.palette.map(c => Color(c))
: createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier;
| + const Color = require('color');
const fetchQueryColors = require('./bing').fetchQueryColors;
const createDefaultPalette = require('./palette').createDefaultPalette;
const matchTermToColor = require('./matcher').matchTermToColor;
const ColorClassifier = {
classify: (term, options) => {
if (!term || (typeof term !== 'string') || term.length === 0) {
throw new Error('Must provide a valid search term string');
}
if (!options) {
throw new Error('Must provide an options object');
}
if (!options.bingApiKey) {
throw new Error('Must provide a Bing search API string');
}
+ if (options.pallette) {
+ if (Array.isArray(options.pallette)) {
+ throw new Error('options.pallette must be an array of colors');
+ } else if (options.pallette.length < 1) {
+ throw new Error('options.pallette array cannot be empty');
+ }
+ }
const numResults = options.numResults || 50;
- const palette = options.palette || createDefaultPalette();
+ const palette = options.palette ? options.palette.map(c => Color(c))
+ : createDefaultPalette();
return fetchQueryColors(options.bingApiKey, term, numResults)
.then(colors => matchTermToColor(colors, palette));
},
};
module.exports = ColorClassifier; | 11 | 0.44 | 10 | 1 |
8ae8fbfed388bc1dedbcf160be618f5f99903784 | tests/phpunit.xml | tests/phpunit.xml | <?xml version="1.0"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!-- see http://www.phpunit.de/wiki/Documentation -->
<phpunit bootstrap="bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
</phpunit>
| <?xml version="1.0"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!-- see http://www.phpunit.de/wiki/Documentation -->
<phpunit bootstrap="bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Default">
<directory suffix="Test.php">.</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
| Add the clover test logs for code coverage. | Add the clover test logs for code coverage. | XML | mit | vanilla/snidely,vanilla/snidely,vanilla/snidely | xml | ## Code Before:
<?xml version="1.0"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!-- see http://www.phpunit.de/wiki/Documentation -->
<phpunit bootstrap="bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
</phpunit>
## Instruction:
Add the clover test logs for code coverage.
## Code After:
<?xml version="1.0"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!-- see http://www.phpunit.de/wiki/Documentation -->
<phpunit bootstrap="bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Default">
<directory suffix="Test.php">.</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
| <?xml version="1.0"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!-- see http://www.phpunit.de/wiki/Documentation -->
<phpunit bootstrap="bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false">
+
+ <testsuites>
+ <testsuite name="Default">
+ <directory suffix="Test.php">.</directory>
+ </testsuite>
+ </testsuites>
+
+ <logging>
+ <log type="coverage-clover" target="build/logs/clover.xml"/>
+ </logging>
</phpunit> | 10 | 0.666667 | 10 | 0 |
734b38fc3f8763a749ec48632c60fbd0e5d32bca | frontend-admin/src/app/index.less | frontend-admin/src/app/index.less | /**
* Do not remove the comments below. It's the markers used by wiredep to inject
* less dependencies when defined in the bower.json of your dependencies
*/
// bower:less
// endbower
/**
* If you want to override some bootstrap variables, you have to change values here.
* The list of variables are listed here bower_components/bootstrap/less/variables.less
*/
@icon-font-path: '../../bower_components/bootstrap/fonts/';
@fa-font-path: "../../bower_components/font-awesome/fonts";
body {
background: #f3f3f3;
font-family: Montserrat;
color: #333!important;
}
.widget .widget-header {
padding: 10px 15px 0px 15px;
}
/**
* Do not remove the comments below. It's the markers used by gulp-inject to inject
* all your less files automatically
*/
// injector
// endinjector
| /**
* Do not remove the comments below. It's the markers used by wiredep to inject
* less dependencies when defined in the bower.json of your dependencies
*/
// bower:less
// endbower
/**
* If you want to override some bootstrap variables, you have to change values here.
* The list of variables are listed here bower_components/bootstrap/less/variables.less
*/
@icon-font-path: '../../bower_components/bootstrap/fonts/';
@fa-font-path: "../../bower_components/font-awesome/fonts";
body {
background: #f3f3f3;
font-family: Montserrat;
color: #333!important;
}
// Fix RDash widgets header height
.widget .widget-header {
.row > div {
margin-bottom: 0px;
}
}
/**
* Do not remove the comments below. It's the markers used by gulp-inject to inject
* all your less files automatically
*/
// injector
// endinjector
| Fix RDash widgets header height | Fix RDash widgets header height
| Less | apache-2.0 | hedudelgado/mno-enterprise,hedudelgado/mno-enterprise,hedudelgado/mno-enterprise,maestrano/mno-enterprise,maestrano/mno-enterprise,maestrano/mno-enterprise,maestrano/mno-enterprise,hedudelgado/mno-enterprise | less | ## Code Before:
/**
* Do not remove the comments below. It's the markers used by wiredep to inject
* less dependencies when defined in the bower.json of your dependencies
*/
// bower:less
// endbower
/**
* If you want to override some bootstrap variables, you have to change values here.
* The list of variables are listed here bower_components/bootstrap/less/variables.less
*/
@icon-font-path: '../../bower_components/bootstrap/fonts/';
@fa-font-path: "../../bower_components/font-awesome/fonts";
body {
background: #f3f3f3;
font-family: Montserrat;
color: #333!important;
}
.widget .widget-header {
padding: 10px 15px 0px 15px;
}
/**
* Do not remove the comments below. It's the markers used by gulp-inject to inject
* all your less files automatically
*/
// injector
// endinjector
## Instruction:
Fix RDash widgets header height
## Code After:
/**
* Do not remove the comments below. It's the markers used by wiredep to inject
* less dependencies when defined in the bower.json of your dependencies
*/
// bower:less
// endbower
/**
* If you want to override some bootstrap variables, you have to change values here.
* The list of variables are listed here bower_components/bootstrap/less/variables.less
*/
@icon-font-path: '../../bower_components/bootstrap/fonts/';
@fa-font-path: "../../bower_components/font-awesome/fonts";
body {
background: #f3f3f3;
font-family: Montserrat;
color: #333!important;
}
// Fix RDash widgets header height
.widget .widget-header {
.row > div {
margin-bottom: 0px;
}
}
/**
* Do not remove the comments below. It's the markers used by gulp-inject to inject
* all your less files automatically
*/
// injector
// endinjector
| /**
* Do not remove the comments below. It's the markers used by wiredep to inject
* less dependencies when defined in the bower.json of your dependencies
*/
// bower:less
// endbower
/**
* If you want to override some bootstrap variables, you have to change values here.
* The list of variables are listed here bower_components/bootstrap/less/variables.less
*/
@icon-font-path: '../../bower_components/bootstrap/fonts/';
@fa-font-path: "../../bower_components/font-awesome/fonts";
body {
background: #f3f3f3;
font-family: Montserrat;
color: #333!important;
}
+ // Fix RDash widgets header height
.widget .widget-header {
- padding: 10px 15px 0px 15px;
+ .row > div {
+ margin-bottom: 0px;
+ }
}
/**
* Do not remove the comments below. It's the markers used by gulp-inject to inject
* all your less files automatically
*/
// injector
// endinjector | 5 | 0.166667 | 4 | 1 |
0ac9f362906e6d55d10d4c6ee1e0ce1f288821ee | rst2pdf/sectnumlinks.py | rst2pdf/sectnumlinks.py | import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ')
class SectRefExpander(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, sectnums):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = sectnums
def visit_reference(self, node):
if node.get('refid', None) in self.sectnums:
node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
| import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ')
def unknown_visit(self, node):
pass
class SectRefExpander(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, sectnums):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = sectnums
def visit_reference(self, node):
if node.get('refid', None) in self.sectnums:
node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
def unknown_visit(self, node):
pass
| Support visiting unknown nodes in SectNumFolder and SectRefExpander | Support visiting unknown nodes in SectNumFolder and SectRefExpander
| Python | mit | rst2pdf/rst2pdf,rst2pdf/rst2pdf | python | ## Code Before:
import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ')
class SectRefExpander(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, sectnums):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = sectnums
def visit_reference(self, node):
if node.get('refid', None) in self.sectnums:
node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
## Instruction:
Support visiting unknown nodes in SectNumFolder and SectRefExpander
## Code After:
import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ')
def unknown_visit(self, node):
pass
class SectRefExpander(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, sectnums):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = sectnums
def visit_reference(self, node):
if node.get('refid', None) in self.sectnums:
node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
def unknown_visit(self, node):
pass
| import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ')
+ def unknown_visit(self, node):
+ pass
+
class SectRefExpander(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, sectnums):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = sectnums
def visit_reference(self, node):
if node.get('refid', None) in self.sectnums:
node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
+
+ def unknown_visit(self, node):
+ pass | 6 | 0.315789 | 6 | 0 |
709bccdb6d67206f0e255ad9cd37c1ea174912c9 | src/assets/main.js | src/assets/main.js | $(function() {
// your code will go here
});
| $.ajax({
url: 'https://www.codeschool.com/users/imaguz.json',
dataType: 'jsonp',
success: function(response) {
var badgeElements = $.map(response.courses.completed, function (badge, index){
var badgeDiv = $('<div class="course"></div>');
$('<h3>'+badge.title+'</h3>').appendTo(badgeDiv);
$('<img src="'+badge.badge+'">').appendTo(badgeDiv);
$('<a href="'+badge.url+'" target="_blank" class="btn btn-primary">See Course</a>').appendTo(badgeDiv);
return badgeDiv;
});
$('#badges').html(badgeElements);
}
});
| Use jQuery to Fetch and Show Code School Badges Using Ajax | Use jQuery to Fetch and Show Code School Badges Using Ajax
| JavaScript | mit | iMaguz/jQueryBadgesProject,iMaguz/jQueryBadgesProject | javascript | ## Code Before:
$(function() {
// your code will go here
});
## Instruction:
Use jQuery to Fetch and Show Code School Badges Using Ajax
## Code After:
$.ajax({
url: 'https://www.codeschool.com/users/imaguz.json',
dataType: 'jsonp',
success: function(response) {
var badgeElements = $.map(response.courses.completed, function (badge, index){
var badgeDiv = $('<div class="course"></div>');
$('<h3>'+badge.title+'</h3>').appendTo(badgeDiv);
$('<img src="'+badge.badge+'">').appendTo(badgeDiv);
$('<a href="'+badge.url+'" target="_blank" class="btn btn-primary">See Course</a>').appendTo(badgeDiv);
return badgeDiv;
});
$('#badges').html(badgeElements);
}
});
| - $(function() {
-
- // your code will go here
-
+ $.ajax({
+ url: 'https://www.codeschool.com/users/imaguz.json',
+ dataType: 'jsonp',
+ success: function(response) {
+ var badgeElements = $.map(response.courses.completed, function (badge, index){
+ var badgeDiv = $('<div class="course"></div>');
+ $('<h3>'+badge.title+'</h3>').appendTo(badgeDiv);
+ $('<img src="'+badge.badge+'">').appendTo(badgeDiv);
+ $('<a href="'+badge.url+'" target="_blank" class="btn btn-primary">See Course</a>').appendTo(badgeDiv);
+ return badgeDiv;
+ });
+ $('#badges').html(badgeElements);
+ }
}); | 17 | 3.4 | 13 | 4 |
2f6229b8155d953efda6af6b7e0f144d45538847 | app/services/admin_reservation_expirer.rb | app/services/admin_reservation_expirer.rb |
class AdminReservationExpirer
def expire!
expired_reservations.destroy_all
end
private
def expired_reservations
if NUCore::Database.oracle?
AdminReservation.where("reserve_start_at - expires_mins_before / (60*24) < ?", Time.current)
else
AdminReservation.where("SUBTIME(reserve_start_at, MAKETIME(expires_mins_before DIV 60, expires_mins_before MOD 60, 0)) < ?", Time.current)
end
end
end
|
class AdminReservationExpirer
def expire!
expired_reservations.destroy_all
end
private
def expired_reservations
if NUCore::Database.oracle?
AdminReservation.where("reserve_start_at - expires_mins_before / (60*24) < TO_TIMESTAMP(?)", Time.current)
else
AdminReservation.where("SUBTIME(reserve_start_at, MAKETIME(expires_mins_before DIV 60, expires_mins_before MOD 60, 0)) < ?", Time.current)
end
end
end
| Use TO_TIMESTAMP in Oracle comparison with Time.current | Use TO_TIMESTAMP in Oracle comparison with Time.current
| Ruby | mit | tablexi/nucore-open,tablexi/nucore-open,tablexi/nucore-open,tablexi/nucore-open | ruby | ## Code Before:
class AdminReservationExpirer
def expire!
expired_reservations.destroy_all
end
private
def expired_reservations
if NUCore::Database.oracle?
AdminReservation.where("reserve_start_at - expires_mins_before / (60*24) < ?", Time.current)
else
AdminReservation.where("SUBTIME(reserve_start_at, MAKETIME(expires_mins_before DIV 60, expires_mins_before MOD 60, 0)) < ?", Time.current)
end
end
end
## Instruction:
Use TO_TIMESTAMP in Oracle comparison with Time.current
## Code After:
class AdminReservationExpirer
def expire!
expired_reservations.destroy_all
end
private
def expired_reservations
if NUCore::Database.oracle?
AdminReservation.where("reserve_start_at - expires_mins_before / (60*24) < TO_TIMESTAMP(?)", Time.current)
else
AdminReservation.where("SUBTIME(reserve_start_at, MAKETIME(expires_mins_before DIV 60, expires_mins_before MOD 60, 0)) < ?", Time.current)
end
end
end
|
class AdminReservationExpirer
def expire!
expired_reservations.destroy_all
end
private
def expired_reservations
if NUCore::Database.oracle?
- AdminReservation.where("reserve_start_at - expires_mins_before / (60*24) < ?", Time.current)
+ AdminReservation.where("reserve_start_at - expires_mins_before / (60*24) < TO_TIMESTAMP(?)", Time.current)
? +++++++++++++ +
else
AdminReservation.where("SUBTIME(reserve_start_at, MAKETIME(expires_mins_before DIV 60, expires_mins_before MOD 60, 0)) < ?", Time.current)
end
end
end | 2 | 0.111111 | 1 | 1 |
7007fcfbe9da250dd6b51174acabae86599af860 | recipes/default.rb | recipes/default.rb | if node[:omnibus_updater][:disabled]
Chef::Log.info 'Omnibus update disabled as requested'
elsif node[:omnibus_updater][:install_via]
case node[:omnibus_updater][:install_via]
when 'deb'
include_recipe 'omnibus_updater::deb_package'
when 'rpm'
include_recipe 'omnibus_updater::rpm_package'
when 'script'
include_recipe 'omnibus_updater::script'
else
raise "Unknown omnibus update method requested: #{node[:omnibus_updater]}"
end
else
case node.platform_family
when 'debian'
include_recipe 'omnibus_updater::deb_package'
when 'fedora', 'rhel'
include_recipe 'omnibus_updater::rpm_package'
else
include_recipe 'omnibus_updater::script'
end
end
include_recipe 'omnibus_updater::remove_chef_system_gem' if node[:omnibus_updater][:remove_chef_system_gem]
| if node[:omnibus_updater][:disabled]
Chef::Log.info 'Omnibus update disabled as requested'
elsif node[:omnibus_updater][:install_via]
case node[:omnibus_updater][:install_via]
when 'deb'
include_recipe 'omnibus_updater::deb_package'
when 'rpm'
include_recipe 'omnibus_updater::rpm_package'
when 'script'
include_recipe 'omnibus_updater::script'
else
raise "Unknown omnibus update method requested: #{node[:omnibus_updater][:install_via]}"
end
else
case node.platform_family
when 'debian'
include_recipe 'omnibus_updater::deb_package'
when 'fedora', 'rhel'
include_recipe 'omnibus_updater::rpm_package'
else
include_recipe 'omnibus_updater::script'
end
end
include_recipe 'omnibus_updater::remove_chef_system_gem' if node[:omnibus_updater][:remove_chef_system_gem]
| Fix node attribute in an error message | Fix node attribute in an error message
| Ruby | apache-2.0 | hw-cookbooks/omnibus_updater,Parametric/chef_omnibus_updater,Sauraus/omnibus_updater,crap-cookbooks/omnibus_updater,tas50/omnibus_updater,chef-cookbooks/omnibus_updater | ruby | ## Code Before:
if node[:omnibus_updater][:disabled]
Chef::Log.info 'Omnibus update disabled as requested'
elsif node[:omnibus_updater][:install_via]
case node[:omnibus_updater][:install_via]
when 'deb'
include_recipe 'omnibus_updater::deb_package'
when 'rpm'
include_recipe 'omnibus_updater::rpm_package'
when 'script'
include_recipe 'omnibus_updater::script'
else
raise "Unknown omnibus update method requested: #{node[:omnibus_updater]}"
end
else
case node.platform_family
when 'debian'
include_recipe 'omnibus_updater::deb_package'
when 'fedora', 'rhel'
include_recipe 'omnibus_updater::rpm_package'
else
include_recipe 'omnibus_updater::script'
end
end
include_recipe 'omnibus_updater::remove_chef_system_gem' if node[:omnibus_updater][:remove_chef_system_gem]
## Instruction:
Fix node attribute in an error message
## Code After:
if node[:omnibus_updater][:disabled]
Chef::Log.info 'Omnibus update disabled as requested'
elsif node[:omnibus_updater][:install_via]
case node[:omnibus_updater][:install_via]
when 'deb'
include_recipe 'omnibus_updater::deb_package'
when 'rpm'
include_recipe 'omnibus_updater::rpm_package'
when 'script'
include_recipe 'omnibus_updater::script'
else
raise "Unknown omnibus update method requested: #{node[:omnibus_updater][:install_via]}"
end
else
case node.platform_family
when 'debian'
include_recipe 'omnibus_updater::deb_package'
when 'fedora', 'rhel'
include_recipe 'omnibus_updater::rpm_package'
else
include_recipe 'omnibus_updater::script'
end
end
include_recipe 'omnibus_updater::remove_chef_system_gem' if node[:omnibus_updater][:remove_chef_system_gem]
| if node[:omnibus_updater][:disabled]
Chef::Log.info 'Omnibus update disabled as requested'
elsif node[:omnibus_updater][:install_via]
case node[:omnibus_updater][:install_via]
when 'deb'
include_recipe 'omnibus_updater::deb_package'
when 'rpm'
include_recipe 'omnibus_updater::rpm_package'
when 'script'
include_recipe 'omnibus_updater::script'
else
- raise "Unknown omnibus update method requested: #{node[:omnibus_updater]}"
+ raise "Unknown omnibus update method requested: #{node[:omnibus_updater][:install_via]}"
? ++++++++++++++
end
else
case node.platform_family
when 'debian'
include_recipe 'omnibus_updater::deb_package'
when 'fedora', 'rhel'
include_recipe 'omnibus_updater::rpm_package'
else
include_recipe 'omnibus_updater::script'
end
end
include_recipe 'omnibus_updater::remove_chef_system_gem' if node[:omnibus_updater][:remove_chef_system_gem] | 2 | 0.08 | 1 | 1 |
6db920ab503d5fe5473c259be161acb7592ac244 | app/views/shared/_navi_cfp_account.html.haml | app/views/shared/_navi_cfp_account.html.haml | - conferences = Conference.creation_order.has_submission(current_user.person).limit(5)
- if conferences.to_a.count > 1
%li.dropdown
= link_to t("switch_conference", default: "Switch conference"), "#", class: "dropdown-toggle"
%ul.dropdown-menu
- conferences.each do |conference|
- unless @conference == conference
%li= link_to conference.acronym, cfp_person_path(conference_acronym: conference.acronym)
%li= link_to t("logout", default: "Logout"), destroy_user_session_path, method: :delete
| %li
- if @conference && policy(@conference).manage?
= link_to t("manage_conference", default: "Manage this conference"), conference_path(conference_acronym: @conference.acronym)
- conferences = Conference.creation_order.has_submission(current_user.person).limit(5)
- if conferences.to_a.count > 1
%li.dropdown
= link_to t("switch_conference", default: "Switch conference"), "#", class: "dropdown-toggle"
%ul.dropdown-menu
- conferences.each do |conference|
- unless @conference == conference
%li= link_to conference.acronym, cfp_person_path(conference_acronym: conference.acronym)
%li= link_to t("logout", default: "Logout"), destroy_user_session_path, method: :delete
| Add "manage this" link to cfp view for admins | Add "manage this" link to cfp view for admins
| Haml | mit | fossgis/frab,fossgis/frab,fossgis/frab,fossgis/frab | haml | ## Code Before:
- conferences = Conference.creation_order.has_submission(current_user.person).limit(5)
- if conferences.to_a.count > 1
%li.dropdown
= link_to t("switch_conference", default: "Switch conference"), "#", class: "dropdown-toggle"
%ul.dropdown-menu
- conferences.each do |conference|
- unless @conference == conference
%li= link_to conference.acronym, cfp_person_path(conference_acronym: conference.acronym)
%li= link_to t("logout", default: "Logout"), destroy_user_session_path, method: :delete
## Instruction:
Add "manage this" link to cfp view for admins
## Code After:
%li
- if @conference && policy(@conference).manage?
= link_to t("manage_conference", default: "Manage this conference"), conference_path(conference_acronym: @conference.acronym)
- conferences = Conference.creation_order.has_submission(current_user.person).limit(5)
- if conferences.to_a.count > 1
%li.dropdown
= link_to t("switch_conference", default: "Switch conference"), "#", class: "dropdown-toggle"
%ul.dropdown-menu
- conferences.each do |conference|
- unless @conference == conference
%li= link_to conference.acronym, cfp_person_path(conference_acronym: conference.acronym)
%li= link_to t("logout", default: "Logout"), destroy_user_session_path, method: :delete
| + %li
+ - if @conference && policy(@conference).manage?
+ = link_to t("manage_conference", default: "Manage this conference"), conference_path(conference_acronym: @conference.acronym)
- conferences = Conference.creation_order.has_submission(current_user.person).limit(5)
- if conferences.to_a.count > 1
%li.dropdown
= link_to t("switch_conference", default: "Switch conference"), "#", class: "dropdown-toggle"
%ul.dropdown-menu
- conferences.each do |conference|
- unless @conference == conference
%li= link_to conference.acronym, cfp_person_path(conference_acronym: conference.acronym)
%li= link_to t("logout", default: "Logout"), destroy_user_session_path, method: :delete | 3 | 0.333333 | 3 | 0 |
ada006bbcee7e855f9ee44acbd777928a0c58d1b | addon/initializers/mutation-observer.js | addon/initializers/mutation-observer.js | /**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
const config = app.lookupFactory ?
app.lookupFactory('config:environment') :
app.__container__.lookupFactory('config:environment');
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
}; | /**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
let config;
try {
// Ember 2.15+
config = app.resolveRegistration('config:environment');
} catch (e) {
// Older Ember approach
config = app.lookupFactory ?
app.lookupFactory('config:environment') :
app.__container__.lookupFactory('config:environment');
}
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
}; | Fix initializer for Ember 2.15+ | Fix initializer for Ember 2.15+
| JavaScript | mit | zzarcon/ember-cli-Mutation-Observer,zzarcon/ember-cli-Mutation-Observer | javascript | ## Code Before:
/**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
const config = app.lookupFactory ?
app.lookupFactory('config:environment') :
app.__container__.lookupFactory('config:environment');
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
};
## Instruction:
Fix initializer for Ember 2.15+
## Code After:
/**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
let config;
try {
// Ember 2.15+
config = app.resolveRegistration('config:environment');
} catch (e) {
// Older Ember approach
config = app.lookupFactory ?
app.lookupFactory('config:environment') :
app.__container__.lookupFactory('config:environment');
}
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
}; | /**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
+ let config;
+ try {
+ // Ember 2.15+
+ config = app.resolveRegistration('config:environment');
+ } catch (e) {
+ // Older Ember approach
- const config = app.lookupFactory ?
? ^^^^^ -
+ config = app.lookupFactory ?
? ^
- app.lookupFactory('config:environment') :
+ app.lookupFactory('config:environment') :
? ++
- app.__container__.lookupFactory('config:environment');
+ app.__container__.lookupFactory('config:environment');
? ++
-
+ }
? +
+
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
}; | 15 | 0.652174 | 11 | 4 |
1afb6254113bd8013e20a9da0efda7d7d2f5c333 | sensu/templates/client.json | sensu/templates/client.json | {% set roles = grains['roles'] or [] %}
{
"client": {
"name": "{{grains['fqdn']}}",
"address": "{{grains['fqdn_ip4']}}",
"metric_prefix": "{{ grains['fqdn'].split('.')|reverse| join('.') }}",
"subscriptions": {{(roles|list + ['all']|list) |json}}
}
}
| {% if 'roles' in grains -%}
{% set roles = grains['roles'] -%}
{% else -%}
{% set roles = [] -%}
{% endif -%}
{
"client": {
"name": "{{grains['fqdn']}}",
"address": "{{grains['fqdn_ip4']}}",
"metric_prefix": "{{ grains['fqdn'].split('.')|reverse| join('.') }}",
"subscriptions": {{(roles|list + ['all']|list) |json}}
}
}
| Fix corner case where no roles are defined. | Fix corner case where no roles are defined.
| JSON | apache-2.0 | ministryofjustice/sensu-formula,ministryofjustice/sensu-formula | json | ## Code Before:
{% set roles = grains['roles'] or [] %}
{
"client": {
"name": "{{grains['fqdn']}}",
"address": "{{grains['fqdn_ip4']}}",
"metric_prefix": "{{ grains['fqdn'].split('.')|reverse| join('.') }}",
"subscriptions": {{(roles|list + ['all']|list) |json}}
}
}
## Instruction:
Fix corner case where no roles are defined.
## Code After:
{% if 'roles' in grains -%}
{% set roles = grains['roles'] -%}
{% else -%}
{% set roles = [] -%}
{% endif -%}
{
"client": {
"name": "{{grains['fqdn']}}",
"address": "{{grains['fqdn_ip4']}}",
"metric_prefix": "{{ grains['fqdn'].split('.')|reverse| join('.') }}",
"subscriptions": {{(roles|list + ['all']|list) |json}}
}
}
| + {% if 'roles' in grains -%}
- {% set roles = grains['roles'] or [] %}
? ^^^^^^
+ {% set roles = grains['roles'] -%}
? ++ ^
+ {% else -%}
+ {% set roles = [] -%}
+ {% endif -%}
{
"client": {
"name": "{{grains['fqdn']}}",
"address": "{{grains['fqdn_ip4']}}",
"metric_prefix": "{{ grains['fqdn'].split('.')|reverse| join('.') }}",
"subscriptions": {{(roles|list + ['all']|list) |json}}
}
} | 6 | 0.666667 | 5 | 1 |
0bec8fc34b1255cbbe771026d64cc00681f53a6e | app/controllers/api/tags_controller.rb | app/controllers/api/tags_controller.rb | require 'byebug'
class Api::TagsController < ApplicationController
before_action :ensure_logged_in
def index
@tags = current_user.tags
render json: @tags
end
def show
@tag = Tag.includes(:notes).find(params[:id])
render :show
end
def create
@tag = current_user.tags.new(tag_params)
if @tag.save
@tag.note_ids = [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def update
@tag = Tag.find(params[:id])
if @tag.update(tag_params)
@tag.note_ids += [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def destroy
@tag = Tag.find(params[:id])
# if the tag has multiple notes and a note_id is received with the destroy
# request, don't destroy the tag but the tagging
if params[:note_id] && @tag.notes.length > 1
@tag.note_ids -= [params[:note_id].to_i]
else
@tag.destroy
end
render json: {}
end
private
def tag_params
params.require(:tag).permit(:id, :label)
end
end
| class Api::TagsController < ApplicationController
before_action :ensure_logged_in
def index
@tags = current_user.tags
render json: @tags
end
def show
@tag = Tag.includes(:notes).find(params[:id])
render :show
end
def create
@tag = current_user.tags.new(tag_params)
if @tag.save
@tag.note_ids = [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def update
@tag = Tag.find(params[:id])
if @tag.update(tag_params)
@tag.note_ids += [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def destroy
@tag = Tag.find(params[:id])
# if the tag has multiple notes and a note_id is received with the destroy
# request, don't destroy the tag but the tagging
if params[:note_id] && @tag.notes.length > 1
@tag.note_ids -= [params[:note_id].to_i]
else
@tag.destroy
end
render json: {}
end
private
def tag_params
params.require(:tag).permit(:id, :label)
end
end
| Remove byebug from tags controller | Remove byebug from tags controller
| Ruby | mit | wahabs/Dulynote,wahabs/Dulynote,wahabs/Dulynote | ruby | ## Code Before:
require 'byebug'
class Api::TagsController < ApplicationController
before_action :ensure_logged_in
def index
@tags = current_user.tags
render json: @tags
end
def show
@tag = Tag.includes(:notes).find(params[:id])
render :show
end
def create
@tag = current_user.tags.new(tag_params)
if @tag.save
@tag.note_ids = [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def update
@tag = Tag.find(params[:id])
if @tag.update(tag_params)
@tag.note_ids += [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def destroy
@tag = Tag.find(params[:id])
# if the tag has multiple notes and a note_id is received with the destroy
# request, don't destroy the tag but the tagging
if params[:note_id] && @tag.notes.length > 1
@tag.note_ids -= [params[:note_id].to_i]
else
@tag.destroy
end
render json: {}
end
private
def tag_params
params.require(:tag).permit(:id, :label)
end
end
## Instruction:
Remove byebug from tags controller
## Code After:
class Api::TagsController < ApplicationController
before_action :ensure_logged_in
def index
@tags = current_user.tags
render json: @tags
end
def show
@tag = Tag.includes(:notes).find(params[:id])
render :show
end
def create
@tag = current_user.tags.new(tag_params)
if @tag.save
@tag.note_ids = [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def update
@tag = Tag.find(params[:id])
if @tag.update(tag_params)
@tag.note_ids += [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def destroy
@tag = Tag.find(params[:id])
# if the tag has multiple notes and a note_id is received with the destroy
# request, don't destroy the tag but the tagging
if params[:note_id] && @tag.notes.length > 1
@tag.note_ids -= [params[:note_id].to_i]
else
@tag.destroy
end
render json: {}
end
private
def tag_params
params.require(:tag).permit(:id, :label)
end
end
| - require 'byebug'
class Api::TagsController < ApplicationController
before_action :ensure_logged_in
def index
@tags = current_user.tags
render json: @tags
end
def show
@tag = Tag.includes(:notes).find(params[:id])
render :show
end
def create
@tag = current_user.tags.new(tag_params)
if @tag.save
@tag.note_ids = [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def update
@tag = Tag.find(params[:id])
if @tag.update(tag_params)
@tag.note_ids += [params[:note_id]] if params[:note_id]
render json: @tag
else
render json: @tag.errors.full_messages, status: 422
end
end
def destroy
@tag = Tag.find(params[:id])
# if the tag has multiple notes and a note_id is received with the destroy
# request, don't destroy the tag but the tagging
if params[:note_id] && @tag.notes.length > 1
@tag.note_ids -= [params[:note_id].to_i]
else
@tag.destroy
end
render json: {}
end
private
def tag_params
params.require(:tag).permit(:id, :label)
end
end | 1 | 0.017857 | 0 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.