file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
common.js
/** * Common utilities * @module glMatrix */ // Configuration Constants export var EPSILON = 0.000001; export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; export var RANDOM = Math.random; /** * Sets the type of array used when creating new vectors and matrices * * @param {Type} type Array type, such as Float32Array or Array */ export function setMatrixArrayType(type) { ARRAY_TYPE = type; } var degree = Math.PI / 180; /** * Convert Degree To Radian * * @param {Number} a Angle in Degrees */ export function toRadian(a) { return a * degree;
* * @param {Number} a The first number to test. * @param {Number} b The second number to test. * @returns {Boolean} True if the numbers are approximately equal, false otherwise. */ export function equals(a, b) { return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); } if (!Math.hypot) Math.hypot = function () { var y = 0, i = arguments.length; while (i--) { y += arguments[i] * arguments[i]; } return Math.sqrt(y); };
} /** * Tests whether or not the arguments have approximately the same value, within an absolute * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less * than or equal to 1.0, and a relative tolerance is used for larger values)
random_line_split
common.js
/** * Common utilities * @module glMatrix */ // Configuration Constants export var EPSILON = 0.000001; export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; export var RANDOM = Math.random; /** * Sets the type of array used when creating new vectors and matrices * * @param {Type} type Array type, such as Float32Array or Array */ export function setMatrixArrayType(type) { ARRAY_TYPE = type; } var degree = Math.PI / 180; /** * Convert Degree To Radian * * @param {Number} a Angle in Degrees */ export function
(a) { return a * degree; } /** * Tests whether or not the arguments have approximately the same value, within an absolute * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less * than or equal to 1.0, and a relative tolerance is used for larger values) * * @param {Number} a The first number to test. * @param {Number} b The second number to test. * @returns {Boolean} True if the numbers are approximately equal, false otherwise. */ export function equals(a, b) { return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); } if (!Math.hypot) Math.hypot = function () { var y = 0, i = arguments.length; while (i--) { y += arguments[i] * arguments[i]; } return Math.sqrt(y); };
toRadian
identifier_name
NavigationReducer.test.js
import reducer from '../../src/reducers/NavigationReducer'; import * as types from '../../src/actions/types'; describe('navigation reducer', () => { it('should return the initial state', () => { expect(reducer(undefined, {})).toEqual( { leftClicked: false, rightClicked: false, currentView: '', updateAchievementsView: false, updateProfileView: false, updateHighscoreView: false } ); }); it('should click left', () => { expect( reducer([], { type: types.LEFT_CLICK, payload: { show: true, view: 'view' } }) ).toEqual( { leftClicked: true, currentView: 'view' } ); }); it('should click right', () => { expect( reducer([], { type: types.RIGHT_CLICK, payload: { show: true, view: 'view' } }) ).toEqual( { rightClicked: true, currentView: 'view' } ); }); it('should update view highscore', () => { expect( reducer([], { type: types.UPDATE_VIEW_HIGHSCORE, payload: true }) ).toEqual( { updateHighscoreView: true } ); }); it('should update view achievements', () => { expect( reducer([], { type: types.UPDATE_VIEW_ACHIEVEMENTS, payload: true }) ).toEqual( { updateAchievementsView: true } ); }); it('should update ivew profile', () => { expect( reducer([], { type: types.UPDATE_VIEW_PROFILE,
} ); }); });
payload: true }) ).toEqual( { updateProfileView: true
random_line_split
future-prelude-collision-turbofish.rs
// See https://github.com/rust-lang/rust/issues/88442 // run-rustfix // edition:2018 // check-pass #![allow(unused)] #![warn(rust_2021_prelude_collisions)] trait AnnotatableTryInto { fn try_into<T>(self) -> Result<T, Self::Error> where Self: std::convert::TryInto<T> { std::convert::TryInto::try_into(self) } } impl<T> AnnotatableTryInto for T where T: From<u8> {} fn main() -> Result<(), &'static str>
{ let x: u64 = 1; x.try_into::<usize>().or(Err("foo"))?.checked_sub(1); //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! x.try_into::<usize>().or(Err("foo"))?; //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! Ok(()) }
identifier_body
future-prelude-collision-turbofish.rs
// See https://github.com/rust-lang/rust/issues/88442
// run-rustfix // edition:2018 // check-pass #![allow(unused)] #![warn(rust_2021_prelude_collisions)] trait AnnotatableTryInto { fn try_into<T>(self) -> Result<T, Self::Error> where Self: std::convert::TryInto<T> { std::convert::TryInto::try_into(self) } } impl<T> AnnotatableTryInto for T where T: From<u8> {} fn main() -> Result<(), &'static str> { let x: u64 = 1; x.try_into::<usize>().or(Err("foo"))?.checked_sub(1); //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! x.try_into::<usize>().or(Err("foo"))?; //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! Ok(()) }
random_line_split
future-prelude-collision-turbofish.rs
// See https://github.com/rust-lang/rust/issues/88442 // run-rustfix // edition:2018 // check-pass #![allow(unused)] #![warn(rust_2021_prelude_collisions)] trait AnnotatableTryInto { fn try_into<T>(self) -> Result<T, Self::Error> where Self: std::convert::TryInto<T> { std::convert::TryInto::try_into(self) } } impl<T> AnnotatableTryInto for T where T: From<u8> {} fn
() -> Result<(), &'static str> { let x: u64 = 1; x.try_into::<usize>().or(Err("foo"))?.checked_sub(1); //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! x.try_into::<usize>().or(Err("foo"))?; //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! Ok(()) }
main
identifier_name
capturing-logging.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast // ignore-android (FIXME #11419) // exec-env:RUST_LOG=info #[feature(phase)]; #[phase(syntax, link)] extern crate log; extern crate native; use std::fmt;
impl Logger for MyWriter { fn log(&mut self, _level: u32, args: &fmt::Arguments) { let MyWriter(ref mut inner) = *self; fmt::writeln(inner as &mut Writer, args); } } #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, proc() { main(); }) } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); spawn(proc() { set_logger(~MyWriter(w) as ~Logger:Send); debug!("debug"); info!("info"); }); assert_eq!(r.read_to_str().unwrap(), ~"info\n"); }
use std::io::{ChanReader, ChanWriter}; use log::{set_logger, Logger}; struct MyWriter(ChanWriter);
random_line_split
capturing-logging.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast // ignore-android (FIXME #11419) // exec-env:RUST_LOG=info #[feature(phase)]; #[phase(syntax, link)] extern crate log; extern crate native; use std::fmt; use std::io::{ChanReader, ChanWriter}; use log::{set_logger, Logger}; struct MyWriter(ChanWriter); impl Logger for MyWriter { fn log(&mut self, _level: u32, args: &fmt::Arguments) { let MyWriter(ref mut inner) = *self; fmt::writeln(inner as &mut Writer, args); } } #[start] fn
(argc: int, argv: **u8) -> int { native::start(argc, argv, proc() { main(); }) } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); spawn(proc() { set_logger(~MyWriter(w) as ~Logger:Send); debug!("debug"); info!("info"); }); assert_eq!(r.read_to_str().unwrap(), ~"info\n"); }
start
identifier_name
capturing-logging.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-fast // ignore-android (FIXME #11419) // exec-env:RUST_LOG=info #[feature(phase)]; #[phase(syntax, link)] extern crate log; extern crate native; use std::fmt; use std::io::{ChanReader, ChanWriter}; use log::{set_logger, Logger}; struct MyWriter(ChanWriter); impl Logger for MyWriter { fn log(&mut self, _level: u32, args: &fmt::Arguments)
} #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, proc() { main(); }) } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); spawn(proc() { set_logger(~MyWriter(w) as ~Logger:Send); debug!("debug"); info!("info"); }); assert_eq!(r.read_to_str().unwrap(), ~"info\n"); }
{ let MyWriter(ref mut inner) = *self; fmt::writeln(inner as &mut Writer, args); }
identifier_body
output.py
import sublime, sublime_plugin def clean_layout(layout): row_set = set() col_set = set() for cell in layout["cells"]: row_set.add(cell[1]) row_set.add(cell[3]) col_set.add(cell[0]) col_set.add(cell[2]) row_set = sorted(row_set) col_set = sorted(col_set) rows = layout["rows"] cols = layout["cols"] layout["rows"] = [row for i, row in enumerate(rows) if i in row_set] layout["cols"] = [col for i, col in enumerate(cols) if i in col_set] row_map = { row : i for i, row in enumerate(row_set) } col_map = { col : i for i, col in enumerate(col_set) } layout["cells"] = [[col_map[cell[0]], row_map[cell[1]], col_map[cell[2]], row_map[cell[3]]] for cell in layout["cells"]] return layout def collapse_group(group): LEFT = 0 TOP = 1 RIGHT = 2 BOTTOM = 3 window = sublime.active_window() layout = window.get_layout() cells = layout["cells"] new_cells = [] group_cell = cells[group] cells = cells[:group] + cells[group + 1:] for cell in cells: if cell[BOTTOM] == group_cell[TOP] and cell[LEFT] >= group_cell[LEFT] and cell[RIGHT] <= group_cell[RIGHT]: new_cells.append([ cell[LEFT], cell[TOP], cell[RIGHT], group_cell[BOTTOM] ]) elif cell != group_cell: new_cells.append(cell) layout["cells"] = new_cells window.set_layout(clean_layout(layout)) class OutputView: content = "" position = 0.0 id = None def __init__(self, view): self.view = view def __getattr__(self, name): if self.view.id() != id: output = OutputView.find_view() if output: self.view = output.view return getattr(self.view, name) def clear(self): OutputView.content = "" self.run_command("output_view_clear") def append(self, text): OutputView.content += text self.run_command("output_view_append", { "text" : text }) def append_finish_message(self, command, working_dir, return_code, elapsed_time): if return_code != 0: templ = "[Finished in {:.2f}s with exit code {}]\n" self.append(templ.format(elapsed_time, return_code)) self.append("[cmd: {}]\n".format(command)) self.append("[dir: {}]\n".format(working_dir)) else: self.append("[Finished in {:.2f}s]\n".format(elapsed_time)) def _collapse(self, group): window = sublime.active_window() views = window.views_in_group(group) if (len(views) == 0 or len(views) == 1 and views[0].id() == self.view.id()): collapse_group(group) def _close(self): window = sublime.active_window() group, index = window.get_view_index(self.view) window.run_command("close_by_index", {"group": group, "index": index}) self._collapse(group) OutputView.id = None @staticmethod def close(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": OutputView(view)._close() @staticmethod def find_view(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": return OutputView(view) return None @staticmethod def create(): view = OutputView.request() view.clear() return view @staticmethod def request(): window = sublime.active_window() num_groups = window.num_groups() if num_groups < 3: layout = window.get_layout() num_rows = len(layout["rows"]) - 1 num_cols = len(layout["cols"]) - 1 if len(layout["rows"]) < 3: begin = layout["rows"][-2] end = layout["rows"][-1] layout["rows"] = layout["rows"][:-1] + [begin * 0.33 + end * 0.66, layout["rows"][-1]] cells = [] new_num_rows = len(layout["rows"]) - 1 for cell in layout["cells"]: if cell[3] == num_rows and cell[2] != num_cols: cells.append([cell[0], cell[1], cell[2], new_num_rows]) else: cells.append(cell) cells.append([num_cols - 1, new_num_rows - 1, num_cols, new_num_rows]) layout["cells"] = cells window.set_layout(layout) num_groups = window.num_groups() views = window.views_in_group(num_groups - 1) output = None for view in views: if view.name() == "Output" and view.is_scratch(): output = view if output == None:
return OutputView(output) class OutputViewClearCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.erase(edit, sublime.Region(0, self.view.size())) class OutputViewAppendCommand(sublime_plugin.TextCommand): def run(self, edit, text): scroll = self.view.visible_region().end() == self.view.size() view = self.view view.insert(edit, view.size(), text) if scroll: viewport = view.viewport_extent() last_line = view.text_to_layout(view.size()) view.set_viewport_position((0, last_line[1] - viewport[1]), False) class OpenOutputCommand(sublime_plugin.WindowCommand): def run(self): OutputView.request() class CloseOutputCommand(sublime_plugin.ApplicationCommand): def run(self): OutputView.close() class OutputEventListener(sublime_plugin.EventListener): def on_query_context(self, view, key, operator, operand, match_all): print(key) if key == "output_visible": return OutputView.find_view() != None else: return None def on_close(self, view): if view.is_scratch() and view.name() == "Output": OutputView.position = view.viewport_position()[1]
active = window.active_view() output = window.new_file() output.settings().set("line_numbers", False) output.settings().set("scroll_past_end", False) output.settings().set("scroll_speed", 0.0) output.settings().set("gutter", False) output.settings().set("spell_check", False) output.set_scratch(True) output.set_name("Output") output.run_command("output_view_append", { "text" : OutputView.content }) def update(): output.set_viewport_position((0, OutputView.position), False) sublime.set_timeout(update, 0.0) OutputView.id = output.id() window.set_view_index(output, num_groups - 1, len(views)) window.focus_view(active)
conditional_block
output.py
import sublime, sublime_plugin def clean_layout(layout): row_set = set() col_set = set() for cell in layout["cells"]: row_set.add(cell[1]) row_set.add(cell[3]) col_set.add(cell[0]) col_set.add(cell[2]) row_set = sorted(row_set) col_set = sorted(col_set) rows = layout["rows"] cols = layout["cols"] layout["rows"] = [row for i, row in enumerate(rows) if i in row_set] layout["cols"] = [col for i, col in enumerate(cols) if i in col_set] row_map = { row : i for i, row in enumerate(row_set) } col_map = { col : i for i, col in enumerate(col_set) } layout["cells"] = [[col_map[cell[0]], row_map[cell[1]], col_map[cell[2]], row_map[cell[3]]] for cell in layout["cells"]] return layout def collapse_group(group): LEFT = 0 TOP = 1 RIGHT = 2 BOTTOM = 3 window = sublime.active_window() layout = window.get_layout() cells = layout["cells"] new_cells = [] group_cell = cells[group] cells = cells[:group] + cells[group + 1:] for cell in cells: if cell[BOTTOM] == group_cell[TOP] and cell[LEFT] >= group_cell[LEFT] and cell[RIGHT] <= group_cell[RIGHT]: new_cells.append([ cell[LEFT], cell[TOP], cell[RIGHT], group_cell[BOTTOM] ]) elif cell != group_cell: new_cells.append(cell) layout["cells"] = new_cells window.set_layout(clean_layout(layout)) class OutputView: content = "" position = 0.0 id = None def __init__(self, view): self.view = view def __getattr__(self, name): if self.view.id() != id: output = OutputView.find_view() if output: self.view = output.view return getattr(self.view, name) def clear(self): OutputView.content = "" self.run_command("output_view_clear") def append(self, text): OutputView.content += text self.run_command("output_view_append", { "text" : text }) def append_finish_message(self, command, working_dir, return_code, elapsed_time): if return_code != 0: templ = "[Finished in {:.2f}s with exit code {}]\n" self.append(templ.format(elapsed_time, return_code)) self.append("[cmd: {}]\n".format(command)) self.append("[dir: {}]\n".format(working_dir)) else: self.append("[Finished in {:.2f}s]\n".format(elapsed_time)) def _collapse(self, group): window = sublime.active_window() views = window.views_in_group(group) if (len(views) == 0 or len(views) == 1 and views[0].id() == self.view.id()): collapse_group(group) def _close(self): window = sublime.active_window() group, index = window.get_view_index(self.view) window.run_command("close_by_index", {"group": group, "index": index}) self._collapse(group) OutputView.id = None @staticmethod def close(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": OutputView(view)._close() @staticmethod def find_view(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": return OutputView(view) return None @staticmethod def create(): view = OutputView.request() view.clear() return view @staticmethod def request(): window = sublime.active_window() num_groups = window.num_groups() if num_groups < 3: layout = window.get_layout() num_rows = len(layout["rows"]) - 1 num_cols = len(layout["cols"]) - 1 if len(layout["rows"]) < 3: begin = layout["rows"][-2] end = layout["rows"][-1] layout["rows"] = layout["rows"][:-1] + [begin * 0.33 + end * 0.66, layout["rows"][-1]] cells = [] new_num_rows = len(layout["rows"]) - 1 for cell in layout["cells"]: if cell[3] == num_rows and cell[2] != num_cols: cells.append([cell[0], cell[1], cell[2], new_num_rows]) else: cells.append(cell) cells.append([num_cols - 1, new_num_rows - 1, num_cols, new_num_rows]) layout["cells"] = cells window.set_layout(layout) num_groups = window.num_groups() views = window.views_in_group(num_groups - 1) output = None for view in views: if view.name() == "Output" and view.is_scratch(): output = view if output == None: active = window.active_view() output = window.new_file() output.settings().set("line_numbers", False) output.settings().set("scroll_past_end", False) output.settings().set("scroll_speed", 0.0) output.settings().set("gutter", False) output.settings().set("spell_check", False) output.set_scratch(True) output.set_name("Output") output.run_command("output_view_append", { "text" : OutputView.content }) def update(): output.set_viewport_position((0, OutputView.position), False) sublime.set_timeout(update, 0.0) OutputView.id = output.id() window.set_view_index(output, num_groups - 1, len(views)) window.focus_view(active) return OutputView(output) class OutputViewClearCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.erase(edit, sublime.Region(0, self.view.size())) class OutputViewAppendCommand(sublime_plugin.TextCommand): def run(self, edit, text): scroll = self.view.visible_region().end() == self.view.size() view = self.view view.insert(edit, view.size(), text) if scroll: viewport = view.viewport_extent() last_line = view.text_to_layout(view.size()) view.set_viewport_position((0, last_line[1] - viewport[1]), False) class OpenOutputCommand(sublime_plugin.WindowCommand): def run(self): OutputView.request() class CloseOutputCommand(sublime_plugin.ApplicationCommand): def run(self): OutputView.close() class OutputEventListener(sublime_plugin.EventListener): def
(self, view, key, operator, operand, match_all): print(key) if key == "output_visible": return OutputView.find_view() != None else: return None def on_close(self, view): if view.is_scratch() and view.name() == "Output": OutputView.position = view.viewport_position()[1]
on_query_context
identifier_name
output.py
import sublime, sublime_plugin def clean_layout(layout): row_set = set() col_set = set() for cell in layout["cells"]: row_set.add(cell[1]) row_set.add(cell[3]) col_set.add(cell[0]) col_set.add(cell[2]) row_set = sorted(row_set) col_set = sorted(col_set) rows = layout["rows"] cols = layout["cols"] layout["rows"] = [row for i, row in enumerate(rows) if i in row_set] layout["cols"] = [col for i, col in enumerate(cols) if i in col_set] row_map = { row : i for i, row in enumerate(row_set) } col_map = { col : i for i, col in enumerate(col_set) } layout["cells"] = [[col_map[cell[0]], row_map[cell[1]], col_map[cell[2]], row_map[cell[3]]] for cell in layout["cells"]] return layout def collapse_group(group): LEFT = 0 TOP = 1 RIGHT = 2 BOTTOM = 3 window = sublime.active_window() layout = window.get_layout() cells = layout["cells"] new_cells = [] group_cell = cells[group] cells = cells[:group] + cells[group + 1:] for cell in cells: if cell[BOTTOM] == group_cell[TOP] and cell[LEFT] >= group_cell[LEFT] and cell[RIGHT] <= group_cell[RIGHT]: new_cells.append([ cell[LEFT], cell[TOP], cell[RIGHT], group_cell[BOTTOM] ]) elif cell != group_cell: new_cells.append(cell) layout["cells"] = new_cells window.set_layout(clean_layout(layout)) class OutputView: content = "" position = 0.0 id = None def __init__(self, view): self.view = view def __getattr__(self, name): if self.view.id() != id: output = OutputView.find_view() if output: self.view = output.view return getattr(self.view, name) def clear(self):
def append(self, text): OutputView.content += text self.run_command("output_view_append", { "text" : text }) def append_finish_message(self, command, working_dir, return_code, elapsed_time): if return_code != 0: templ = "[Finished in {:.2f}s with exit code {}]\n" self.append(templ.format(elapsed_time, return_code)) self.append("[cmd: {}]\n".format(command)) self.append("[dir: {}]\n".format(working_dir)) else: self.append("[Finished in {:.2f}s]\n".format(elapsed_time)) def _collapse(self, group): window = sublime.active_window() views = window.views_in_group(group) if (len(views) == 0 or len(views) == 1 and views[0].id() == self.view.id()): collapse_group(group) def _close(self): window = sublime.active_window() group, index = window.get_view_index(self.view) window.run_command("close_by_index", {"group": group, "index": index}) self._collapse(group) OutputView.id = None @staticmethod def close(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": OutputView(view)._close() @staticmethod def find_view(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": return OutputView(view) return None @staticmethod def create(): view = OutputView.request() view.clear() return view @staticmethod def request(): window = sublime.active_window() num_groups = window.num_groups() if num_groups < 3: layout = window.get_layout() num_rows = len(layout["rows"]) - 1 num_cols = len(layout["cols"]) - 1 if len(layout["rows"]) < 3: begin = layout["rows"][-2] end = layout["rows"][-1] layout["rows"] = layout["rows"][:-1] + [begin * 0.33 + end * 0.66, layout["rows"][-1]] cells = [] new_num_rows = len(layout["rows"]) - 1 for cell in layout["cells"]: if cell[3] == num_rows and cell[2] != num_cols: cells.append([cell[0], cell[1], cell[2], new_num_rows]) else: cells.append(cell) cells.append([num_cols - 1, new_num_rows - 1, num_cols, new_num_rows]) layout["cells"] = cells window.set_layout(layout) num_groups = window.num_groups() views = window.views_in_group(num_groups - 1) output = None for view in views: if view.name() == "Output" and view.is_scratch(): output = view if output == None: active = window.active_view() output = window.new_file() output.settings().set("line_numbers", False) output.settings().set("scroll_past_end", False) output.settings().set("scroll_speed", 0.0) output.settings().set("gutter", False) output.settings().set("spell_check", False) output.set_scratch(True) output.set_name("Output") output.run_command("output_view_append", { "text" : OutputView.content }) def update(): output.set_viewport_position((0, OutputView.position), False) sublime.set_timeout(update, 0.0) OutputView.id = output.id() window.set_view_index(output, num_groups - 1, len(views)) window.focus_view(active) return OutputView(output) class OutputViewClearCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.erase(edit, sublime.Region(0, self.view.size())) class OutputViewAppendCommand(sublime_plugin.TextCommand): def run(self, edit, text): scroll = self.view.visible_region().end() == self.view.size() view = self.view view.insert(edit, view.size(), text) if scroll: viewport = view.viewport_extent() last_line = view.text_to_layout(view.size()) view.set_viewport_position((0, last_line[1] - viewport[1]), False) class OpenOutputCommand(sublime_plugin.WindowCommand): def run(self): OutputView.request() class CloseOutputCommand(sublime_plugin.ApplicationCommand): def run(self): OutputView.close() class OutputEventListener(sublime_plugin.EventListener): def on_query_context(self, view, key, operator, operand, match_all): print(key) if key == "output_visible": return OutputView.find_view() != None else: return None def on_close(self, view): if view.is_scratch() and view.name() == "Output": OutputView.position = view.viewport_position()[1]
OutputView.content = "" self.run_command("output_view_clear")
identifier_body
output.py
import sublime, sublime_plugin def clean_layout(layout): row_set = set() col_set = set() for cell in layout["cells"]: row_set.add(cell[1]) row_set.add(cell[3]) col_set.add(cell[0]) col_set.add(cell[2]) row_set = sorted(row_set) col_set = sorted(col_set) rows = layout["rows"] cols = layout["cols"] layout["rows"] = [row for i, row in enumerate(rows) if i in row_set] layout["cols"] = [col for i, col in enumerate(cols) if i in col_set] row_map = { row : i for i, row in enumerate(row_set) } col_map = { col : i for i, col in enumerate(col_set) } layout["cells"] = [[col_map[cell[0]], row_map[cell[1]], col_map[cell[2]], row_map[cell[3]]] for cell in layout["cells"]] return layout def collapse_group(group): LEFT = 0 TOP = 1 RIGHT = 2 BOTTOM = 3 window = sublime.active_window() layout = window.get_layout() cells = layout["cells"] new_cells = [] group_cell = cells[group] cells = cells[:group] + cells[group + 1:] for cell in cells: if cell[BOTTOM] == group_cell[TOP] and cell[LEFT] >= group_cell[LEFT] and cell[RIGHT] <= group_cell[RIGHT]: new_cells.append([ cell[LEFT], cell[TOP], cell[RIGHT], group_cell[BOTTOM] ]) elif cell != group_cell: new_cells.append(cell) layout["cells"] = new_cells window.set_layout(clean_layout(layout)) class OutputView: content = "" position = 0.0 id = None def __init__(self, view): self.view = view def __getattr__(self, name): if self.view.id() != id: output = OutputView.find_view() if output: self.view = output.view return getattr(self.view, name) def clear(self): OutputView.content = "" self.run_command("output_view_clear") def append(self, text): OutputView.content += text self.run_command("output_view_append", { "text" : text }) def append_finish_message(self, command, working_dir, return_code, elapsed_time): if return_code != 0: templ = "[Finished in {:.2f}s with exit code {}]\n" self.append(templ.format(elapsed_time, return_code)) self.append("[cmd: {}]\n".format(command)) self.append("[dir: {}]\n".format(working_dir)) else: self.append("[Finished in {:.2f}s]\n".format(elapsed_time)) def _collapse(self, group): window = sublime.active_window() views = window.views_in_group(group) if (len(views) == 0 or len(views) == 1 and views[0].id() == self.view.id()): collapse_group(group) def _close(self): window = sublime.active_window() group, index = window.get_view_index(self.view)
def close(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": OutputView(view)._close() @staticmethod def find_view(): window = sublime.active_window() for view in window.views(): if view.is_scratch() and view.name() == "Output": return OutputView(view) return None @staticmethod def create(): view = OutputView.request() view.clear() return view @staticmethod def request(): window = sublime.active_window() num_groups = window.num_groups() if num_groups < 3: layout = window.get_layout() num_rows = len(layout["rows"]) - 1 num_cols = len(layout["cols"]) - 1 if len(layout["rows"]) < 3: begin = layout["rows"][-2] end = layout["rows"][-1] layout["rows"] = layout["rows"][:-1] + [begin * 0.33 + end * 0.66, layout["rows"][-1]] cells = [] new_num_rows = len(layout["rows"]) - 1 for cell in layout["cells"]: if cell[3] == num_rows and cell[2] != num_cols: cells.append([cell[0], cell[1], cell[2], new_num_rows]) else: cells.append(cell) cells.append([num_cols - 1, new_num_rows - 1, num_cols, new_num_rows]) layout["cells"] = cells window.set_layout(layout) num_groups = window.num_groups() views = window.views_in_group(num_groups - 1) output = None for view in views: if view.name() == "Output" and view.is_scratch(): output = view if output == None: active = window.active_view() output = window.new_file() output.settings().set("line_numbers", False) output.settings().set("scroll_past_end", False) output.settings().set("scroll_speed", 0.0) output.settings().set("gutter", False) output.settings().set("spell_check", False) output.set_scratch(True) output.set_name("Output") output.run_command("output_view_append", { "text" : OutputView.content }) def update(): output.set_viewport_position((0, OutputView.position), False) sublime.set_timeout(update, 0.0) OutputView.id = output.id() window.set_view_index(output, num_groups - 1, len(views)) window.focus_view(active) return OutputView(output) class OutputViewClearCommand(sublime_plugin.TextCommand): def run(self, edit): self.view.erase(edit, sublime.Region(0, self.view.size())) class OutputViewAppendCommand(sublime_plugin.TextCommand): def run(self, edit, text): scroll = self.view.visible_region().end() == self.view.size() view = self.view view.insert(edit, view.size(), text) if scroll: viewport = view.viewport_extent() last_line = view.text_to_layout(view.size()) view.set_viewport_position((0, last_line[1] - viewport[1]), False) class OpenOutputCommand(sublime_plugin.WindowCommand): def run(self): OutputView.request() class CloseOutputCommand(sublime_plugin.ApplicationCommand): def run(self): OutputView.close() class OutputEventListener(sublime_plugin.EventListener): def on_query_context(self, view, key, operator, operand, match_all): print(key) if key == "output_visible": return OutputView.find_view() != None else: return None def on_close(self, view): if view.is_scratch() and view.name() == "Output": OutputView.position = view.viewport_position()[1]
window.run_command("close_by_index", {"group": group, "index": index}) self._collapse(group) OutputView.id = None @staticmethod
random_line_split
new-room.ts
import { Component } from '@angular/core'; import { IonicPage, NavParams, ViewController, } from 'ionic-angular'; import { Validators, FormBuilder, FormGroup, } from '@angular/forms'; import { RoomsProvider, } from '../../providers/providers'; @IonicPage() @Component({ selector: 'page-new-room', templateUrl: 'new-room.html', }) export class NewRoomPage { form: FormGroup; isCodeTaken: boolean = false; constructor( public navParams: NavParams, public formBuilder: FormBuilder, public rs: RoomsProvider, public viewCtrl: ViewController, ) { this.initForm(); } ionViewDidLoad() { }
() { this.form = this.formBuilder.group({ name: ['', Validators.required], code: ['', Validators.required], // default: [false, Validators.required] }); } submit() { // clear warnings this.isCodeTaken = false; // uuper case code string this.form.value.code = this.form.value.code.toUpperCase(); this.rs.create(this.form.value) .then(() => this.close()) .catch((error) => { this.isCodeTaken = true; }); } close() { this.viewCtrl.dismiss(); } }
initForm
identifier_name
new-room.ts
import { Component } from '@angular/core'; import { IonicPage, NavParams, ViewController, } from 'ionic-angular'; import { Validators, FormBuilder, FormGroup, } from '@angular/forms'; import { RoomsProvider, } from '../../providers/providers'; @IonicPage() @Component({ selector: 'page-new-room', templateUrl: 'new-room.html', }) export class NewRoomPage { form: FormGroup; isCodeTaken: boolean = false; constructor( public navParams: NavParams, public formBuilder: FormBuilder, public rs: RoomsProvider, public viewCtrl: ViewController, ) { this.initForm(); } ionViewDidLoad()
initForm() { this.form = this.formBuilder.group({ name: ['', Validators.required], code: ['', Validators.required], // default: [false, Validators.required] }); } submit() { // clear warnings this.isCodeTaken = false; // uuper case code string this.form.value.code = this.form.value.code.toUpperCase(); this.rs.create(this.form.value) .then(() => this.close()) .catch((error) => { this.isCodeTaken = true; }); } close() { this.viewCtrl.dismiss(); } }
{ }
identifier_body
new-room.ts
import { Component } from '@angular/core'; import { IonicPage, NavParams, ViewController, } from 'ionic-angular'; import { Validators, FormBuilder, FormGroup, } from '@angular/forms'; import { RoomsProvider, } from '../../providers/providers'; @IonicPage() @Component({ selector: 'page-new-room', templateUrl: 'new-room.html', }) export class NewRoomPage { form: FormGroup; isCodeTaken: boolean = false; constructor( public navParams: NavParams, public formBuilder: FormBuilder, public rs: RoomsProvider, public viewCtrl: ViewController, ) { this.initForm(); } ionViewDidLoad() { } initForm() { this.form = this.formBuilder.group({ name: ['', Validators.required], code: ['', Validators.required], // default: [false, Validators.required] }); } submit() { // clear warnings this.isCodeTaken = false; // uuper case code string this.form.value.code = this.form.value.code.toUpperCase(); this.rs.create(this.form.value) .then(() => this.close()) .catch((error) => { this.isCodeTaken = true;
close() { this.viewCtrl.dismiss(); } }
}); }
random_line_split
mn-langs-en.js
/** * TinyMCE 3.x language strings * * Loaded only when external plugins are added to TinyMCE. */ ( function() { var main = {}, lang = 'en'; if ( typeof tinyMCEPreInit !== 'undefined' && tinyMCEPreInit.ref.language !== 'en' )
main[lang] = { common: { edit_confirm: "Do you want to use the WYSIWYG mode for this textarea?", apply: "Apply", insert: "Insert", update: "Update", cancel: "Cancel", close: "Close", browse: "Browse", class_name: "Class", not_set: "-- Not set --", clipboard_msg: "Copy/Cut/Paste is not available in Mozilla and Firefox.", clipboard_no_support: "Currently not supported by your browser, use keyboard shortcuts instead.", popup_blocked: "Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.", invalid_data: "ERROR: Invalid values entered, these are marked in red.", invalid_data_number: "{#field} must be a number", invalid_data_min: "{#field} must be a number greater than {#min}", invalid_data_size: "{#field} must be a number or percentage", more_colors: "More colors" }, colors: { "000000": "Black", "993300": "Burnt orange", "333300": "Dark olive", "003300": "Dark green", "003366": "Dark azure", "000080": "Navy Blue", "333399": "Indigo", "333333": "Very dark gray", "800000": "Maroon", "FF6600": "Orange", "808000": "Olive", "008000": "Green", "008080": "Teal", "0000FF": "Blue", "666699": "Grayish blue", "808080": "Gray", "FF0000": "Red", "FF9900": "Amber", "99CC00": "Yellow green", "339966": "Sea green", "33CCCC": "Turquoise", "3366FF": "Royal blue", "800080": "Purple", "999999": "Medium gray", "FF00FF": "Magenta", "FFCC00": "Gold", "FFFF00": "Yellow", "00FF00": "Lime", "00FFFF": "Aqua", "00CCFF": "Sky blue", "993366": "Brown", "C0C0C0": "Silver", "FF99CC": "Pink", "FFCC99": "Peach", "FFFF99": "Light yellow", "CCFFCC": "Pale green", "CCFFFF": "Pale cyan", "99CCFF": "Light sky blue", "CC99FF": "Plum", "FFFFFF": "White" }, contextmenu: { align: "Alignment", left: "Left", center: "Center", right: "Right", full: "Full" }, insertdatetime: { date_fmt: "%Y-%m-%d", time_fmt: "%H:%M:%S", insertdate_desc: "Insert date", inserttime_desc: "Insert time", months_long: "January,February,March,April,May,June,July,August,September,October,November,December", months_short: "Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation", day_long: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday", day_short: "Sun,Mon,Tue,Wed,Thu,Fri,Sat" }, print: { print_desc: "Print" }, preview: { preview_desc: "Preview" }, directionality: { ltr_desc: "Direction left to right", rtl_desc: "Direction right to left" }, layer: { insertlayer_desc: "Insert new layer", forward_desc: "Move forward", backward_desc: "Move backward", absolute_desc: "Toggle absolute positioning", content: "New layer..." }, save: { save_desc: "Save", cancel_desc: "Cancel all changes" }, nonbreaking: { nonbreaking_desc: "Insert non-breaking space character" }, iespell: { iespell_desc: "Run spell checking", download: "ieSpell not detected. Do you want to install it now?" }, advhr: { advhr_desc: "Horizontal rule" }, emotions: { emotions_desc: "Emotions" }, searchreplace: { search_desc: "Find", replace_desc: "Find/Replace" }, advimage: { image_desc: "Insert/edit image" }, advlink: { link_desc: "Insert/edit link" }, xhtmlxtras: { cite_desc: "Citation", abbr_desc: "Abbreviation", acronym_desc: "Acronym", del_desc: "Deletion", ins_desc: "Insertion", attribs_desc: "Insert/Edit Attributes" }, style: { desc: "Edit CSS Style" }, paste: { paste_text_desc: "Paste as Plain Text", paste_word_desc: "Paste from Word", selectall_desc: "Select All", plaintext_mode_sticky: "Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.", plaintext_mode: "Paste is now in plain text mode. Click again to toggle back to regular paste mode." }, paste_dlg: { text_title: "Use CTRL + V on your keyboard to paste the text into the window.", text_linebreaks: "Keep linebreaks", word_title: "Use CTRL + V on your keyboard to paste the text into the window." }, table: { desc: "Inserts a new table", row_before_desc: "Insert row before", row_after_desc: "Insert row after", delete_row_desc: "Delete row", col_before_desc: "Insert column before", col_after_desc: "Insert column after", delete_col_desc: "Remove column", split_cells_desc: "Split merged table cells", merge_cells_desc: "Merge table cells", row_desc: "Table row properties", cell_desc: "Table cell properties", props_desc: "Table properties", paste_row_before_desc: "Paste table row before", paste_row_after_desc: "Paste table row after", cut_row_desc: "Cut table row", copy_row_desc: "Copy table row", del: "Delete table", row: "Row", col: "Column", cell: "Cell" }, autosave: { unload_msg: "The changes you made will be lost if you navigate away from this page." }, fullscreen: { desc: "Toggle fullscreen mode (Alt + Shift + G)" }, media: { desc: "Insert / edit embedded media", edit: "Edit embedded media" }, fullpage: { desc: "Document properties" }, template: { desc: "Insert predefined template content" }, visualchars: { desc: "Visual control characters on/off." }, spellchecker: { desc: "Toggle spellchecker (Alt + Shift + N)", menu: "Spellchecker settings", ignore_word: "Ignore word", ignore_words: "Ignore all", langs: "Languages", wait: "Please wait...", sug: "Suggestions", no_sug: "No suggestions", no_mpell: "No misspellings found.", learn_word: "Learn word" }, pagebreak: { desc: "Insert Page Break" }, advlist:{ types: "Types", def: "Default", lower_alpha: "Lower alpha", lower_greek: "Lower greek", lower_roman: "Lower roman", upper_alpha: "Upper alpha", upper_roman: "Upper roman", circle: "Circle", disc: "Disc", square: "Square" }, aria: { rich_text_area: "Rich Text Area" }, wordcount:{ words: "Words: " } }; tinyMCE.addI18n( main ); tinyMCE.addI18n( lang + ".advanced", { style_select: "Styles", font_size: "Font size", fontdefault: "Font family", block: "Format", paragraph: "Paragraph", div: "Div", address: "Address", pre: "Preformatted", h1: "Heading 1", h2: "Heading 2", h3: "Heading 3", h4: "Heading 4", h5: "Heading 5", h6: "Heading 6", blockquote: "Blockquote", code: "Code", samp: "Code sample", dt: "Definition term ", dd: "Definition description", bold_desc: "Bold (Ctrl + B)", italic_desc: "Italic (Ctrl + I)", underline_desc: "Underline", striketrough_desc: "Strikethrough (Alt + Shift + D)", justifyleft_desc: "Align Left (Alt + Shift + L)", justifycenter_desc: "Align Center (Alt + Shift + C)", justifyright_desc: "Align Right (Alt + Shift + R)", justifyfull_desc: "Align Full (Alt + Shift + J)", bullist_desc: "Unordered list (Alt + Shift + U)", numlist_desc: "Ordered list (Alt + Shift + O)", outdent_desc: "Outdent", indent_desc: "Indent", undo_desc: "Undo (Ctrl + Z)", redo_desc: "Redo (Ctrl + Y)", link_desc: "Insert/edit link (Alt + Shift + A)", unlink_desc: "Unlink (Alt + Shift + S)", image_desc: "Insert/edit image (Alt + Shift + M)", cleanup_desc: "Cleanup messy code", code_desc: "Edit HTML Source", sub_desc: "Subscript", sup_desc: "Superscript", hr_desc: "Insert horizontal ruler", removeformat_desc: "Remove formatting", forecolor_desc: "Select text color", backcolor_desc: "Select background color", charmap_desc: "Insert custom character", visualaid_desc: "Toggle guidelines/invisible elements", anchor_desc: "Insert/edit anchor", cut_desc: "Cut", copy_desc: "Copy", paste_desc: "Paste", image_props_desc: "Image properties", newdocument_desc: "New document", help_desc: "Help", blockquote_desc: "Blockquote (Alt + Shift + Q)", clipboard_msg: "Copy/Cut/Paste is not available in Mozilla and Firefox.", path: "Path", newdocument: "Are you sure you want to clear all contents?", toolbar_focus: "Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X", more_colors: "More colors", shortcuts_desc: "Accessibility Help", help_shortcut: " Press ALT F10 for toolbar. Press ALT 0 for help.", rich_text_area: "Rich Text Area", toolbar: "Toolbar" }); tinyMCE.addI18n( lang + ".advanced_dlg", { about_title: "About TinyMCE", about_general: "About", about_help: "Help", about_license: "License", about_plugins: "Plugins", about_plugin: "Plugin", about_author: "Author", about_version: "Version", about_loaded: "Loaded plugins", anchor_title: "Insert/edit anchor", anchor_name: "Anchor name", code_title: "HTML Source Editor", code_wordwrap: "Word wrap", colorpicker_title: "Select a color", colorpicker_picker_tab: "Picker", colorpicker_picker_title: "Color picker", colorpicker_palette_tab: "Palette", colorpicker_palette_title: "Palette colors", colorpicker_named_tab: "Named", colorpicker_named_title: "Named colors", colorpicker_color: "Color: ", colorpicker_name: "Name: ", charmap_title: "Select custom character", charmap_usage: "Use left and right arrows to navigate.", image_title: "Insert/edit image", image_src: "Image URL", image_alt: "Image description", image_list: "Image list", image_border: "Border", image_dimensions: "Dimensions", image_vspace: "Vertical space", image_hspace: "Horizontal space", image_align: "Alignment", image_align_baseline: "Baseline", image_align_top: "Top", image_align_middle: "Middle", image_align_bottom: "Bottom", image_align_texttop: "Text top", image_align_textbottom: "Text bottom", image_align_left: "Left", image_align_right: "Right", link_title: "Insert/edit link", link_url: "Link URL", link_target: "Target", link_target_same: "Open link in the same window", link_target_blank: "Open link in a new window", link_titlefield: "Title", link_is_email: "The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", link_is_external: "The URL you entered seems to be an external link, do you want to add the required http:// prefix?", link_list: "Link list", accessibility_help: "Accessibility Help", accessibility_usage_title: "General Usage" }); tinyMCE.addI18n( lang + ".media_dlg", { title: "Insert / edit embedded media", general: "General", advanced: "Advanced", file: "File/URL", list: "List", size: "Dimensions", preview: "Preview", constrain_proportions: "Constrain proportions", type: "Type", id: "Id", name: "Name", class_name: "Class", vspace: "V-Space", hspace: "H-Space", play: "Auto play", loop: "Loop", menu: "Show menu", quality: "Quality", scale: "Scale", align: "Align", salign: "SAlign", wmode: "WMode", bgcolor: "Background", base: "Base", flashvars: "Flashvars", liveconnect: "SWLiveConnect", autohref: "AutoHREF", cache: "Cache", hidden: "Hidden", controller: "Controller", kioskmode: "Kiosk mode", playeveryframe: "Play every frame", targetcache: "Target cache", correction: "No correction", enablejavascript: "Enable JavaScript", starttime: "Start time", endtime: "End time", href: "href", qtsrcchokespeed: "Choke speed", target: "Target", volume: "Volume", autostart: "Auto start", enabled: "Enabled", fullscreen: "Fullscreen", invokeurls: "Invoke URLs", mute: "Mute", stretchtofit: "Stretch to fit", windowlessvideo: "Windowless video", balance: "Balance", baseurl: "Base URL", captioningid: "Captioning id", currentmarker: "Current marker", currentposition: "Current position", defaultframe: "Default frame", playcount: "Play count", rate: "Rate", uimode: "UI Mode", flash_options: "Flash options", qt_options: "QuickTime options", wmp_options: "Windows media player options", rmp_options: "Real media player options", shockwave_options: "Shockwave options", autogotourl: "Auto goto URL", center: "Center", imagestatus: "Image status", maintainaspect: "Maintain aspect", nojava: "No java", prefetch: "Prefetch", shuffle: "Shuffle", console: "Console", numloop: "Num loops", controls: "Controls", scriptcallbacks: "Script callbacks", swstretchstyle: "Stretch style", swstretchhalign: "Stretch H-Align", swstretchvalign: "Stretch V-Align", sound: "Sound", progress: "Progress", qtsrc: "QT Src", qt_stream_warn: "Streamed rtsp resources should be added to the QT Src field under the advanced tab.", align_top: "Top", align_right: "Right", align_bottom: "Bottom", align_left: "Left", align_center: "Center", align_top_left: "Top left", align_top_right: "Top right", align_bottom_left: "Bottom left", align_bottom_right: "Bottom right", flv_options: "Flash video options", flv_scalemode: "Scale mode", flv_buffer: "Buffer", flv_startimage: "Start image", flv_starttime: "Start time", flv_defaultvolume: "Default volume", flv_hiddengui: "Hidden GUI", flv_autostart: "Auto start", flv_loop: "Loop", flv_showscalemodes: "Show scale modes", flv_smoothvideo: "Smooth video", flv_jscallback: "JS Callback", html5_video_options: "HTML5 Video Options", altsource1: "Alternative source 1", altsource2: "Alternative source 2", preload: "Preload", poster: "Poster", source: "Source" }); tinyMCE.addI18n( lang + ".Mtaandao", { mn_adv_desc: "Show/Hide Kitchen Sink (Alt + Shift + Z)", mn_more_desc: "Insert More Tag (Alt + Shift + T)", mn_page_desc: "Insert Page break (Alt + Shift + P)", mn_help_desc: "Help (Alt + Shift + H)", mn_more_alt: "More...", mn_page_alt: "Next page...", add_media: "Add Media", add_image: "Add an Image", add_video: "Add Video", add_audio: "Add Audio", editgallery: "Edit Gallery", delgallery: "Delete Gallery", mn_fullscreen_desc: "Distraction-free writing mode (Alt + Shift + W)" }); tinyMCE.addI18n( lang + ".mneditimage", { edit_img: "Edit Image", del_img: "Delete Image", adv_settings: "Advanced Settings", none: "None", size: "Size", thumbnail: "Thumbnail", medium: "Medium", full_size: "Full Size", current_link: "Current Link", link_to_img: "Link to Image", link_help: "Enter a link URL or click above for presets.", adv_img_settings: "Advanced Image Settings", source: "Source", width: "Width", height: "Height", orig_size: "Original Size", css: "CSS Class", adv_link_settings: "Advanced Link Settings", link_rel: "Link Rel", height: "Height", orig_size: "Original Size", css: "CSS Class", s60: "60%", s70: "70%", s80: "80%", s90: "90%", s100: "100%", s110: "110%", s120: "120%", s130: "130%", img_title: "Title", caption: "Caption", alt: "Alternative Text" }); }());
{ lang = tinyMCEPreInit.ref.language; }
conditional_block
mn-langs-en.js
/** * TinyMCE 3.x language strings * * Loaded only when external plugins are added to TinyMCE. */ ( function() { var main = {}, lang = 'en'; if ( typeof tinyMCEPreInit !== 'undefined' && tinyMCEPreInit.ref.language !== 'en' ) { lang = tinyMCEPreInit.ref.language; } main[lang] = { common: { edit_confirm: "Do you want to use the WYSIWYG mode for this textarea?", apply: "Apply", insert: "Insert", update: "Update", cancel: "Cancel", close: "Close", browse: "Browse", class_name: "Class", not_set: "-- Not set --", clipboard_msg: "Copy/Cut/Paste is not available in Mozilla and Firefox.", clipboard_no_support: "Currently not supported by your browser, use keyboard shortcuts instead.", popup_blocked: "Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.", invalid_data: "ERROR: Invalid values entered, these are marked in red.", invalid_data_number: "{#field} must be a number", invalid_data_min: "{#field} must be a number greater than {#min}", invalid_data_size: "{#field} must be a number or percentage", more_colors: "More colors" }, colors: { "000000": "Black", "993300": "Burnt orange", "333300": "Dark olive", "003300": "Dark green", "003366": "Dark azure", "000080": "Navy Blue", "333399": "Indigo", "333333": "Very dark gray", "800000": "Maroon", "FF6600": "Orange", "808000": "Olive", "008000": "Green", "008080": "Teal", "0000FF": "Blue", "666699": "Grayish blue", "808080": "Gray", "FF0000": "Red", "FF9900": "Amber", "99CC00": "Yellow green", "339966": "Sea green", "33CCCC": "Turquoise", "3366FF": "Royal blue", "800080": "Purple", "999999": "Medium gray", "FF00FF": "Magenta", "FFCC00": "Gold", "FFFF00": "Yellow", "00FF00": "Lime", "00FFFF": "Aqua", "00CCFF": "Sky blue", "993366": "Brown", "C0C0C0": "Silver", "FF99CC": "Pink", "FFCC99": "Peach", "FFFF99": "Light yellow", "CCFFCC": "Pale green", "CCFFFF": "Pale cyan", "99CCFF": "Light sky blue", "CC99FF": "Plum", "FFFFFF": "White" }, contextmenu: { align: "Alignment", left: "Left", center: "Center", right: "Right", full: "Full" }, insertdatetime: { date_fmt: "%Y-%m-%d", time_fmt: "%H:%M:%S", insertdate_desc: "Insert date", inserttime_desc: "Insert time", months_long: "January,February,March,April,May,June,July,August,September,October,November,December", months_short: "Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation", day_long: "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday", day_short: "Sun,Mon,Tue,Wed,Thu,Fri,Sat" }, print: { print_desc: "Print" }, preview: { preview_desc: "Preview" }, directionality: { ltr_desc: "Direction left to right", rtl_desc: "Direction right to left" }, layer: { insertlayer_desc: "Insert new layer", forward_desc: "Move forward", backward_desc: "Move backward", absolute_desc: "Toggle absolute positioning", content: "New layer..." }, save: { save_desc: "Save", cancel_desc: "Cancel all changes" }, nonbreaking: { nonbreaking_desc: "Insert non-breaking space character" }, iespell: { iespell_desc: "Run spell checking", download: "ieSpell not detected. Do you want to install it now?" }, advhr: { advhr_desc: "Horizontal rule" }, emotions: { emotions_desc: "Emotions" }, searchreplace: { search_desc: "Find", replace_desc: "Find/Replace" }, advimage: { image_desc: "Insert/edit image" }, advlink: { link_desc: "Insert/edit link" }, xhtmlxtras: { cite_desc: "Citation", abbr_desc: "Abbreviation", acronym_desc: "Acronym", del_desc: "Deletion", ins_desc: "Insertion", attribs_desc: "Insert/Edit Attributes" }, style: { desc: "Edit CSS Style" }, paste: { paste_text_desc: "Paste as Plain Text", paste_word_desc: "Paste from Word", selectall_desc: "Select All", plaintext_mode_sticky: "Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.", plaintext_mode: "Paste is now in plain text mode. Click again to toggle back to regular paste mode." }, paste_dlg: { text_title: "Use CTRL + V on your keyboard to paste the text into the window.", text_linebreaks: "Keep linebreaks", word_title: "Use CTRL + V on your keyboard to paste the text into the window." }, table: { desc: "Inserts a new table", row_before_desc: "Insert row before", row_after_desc: "Insert row after", delete_row_desc: "Delete row", col_before_desc: "Insert column before", col_after_desc: "Insert column after", delete_col_desc: "Remove column", split_cells_desc: "Split merged table cells", merge_cells_desc: "Merge table cells", row_desc: "Table row properties", cell_desc: "Table cell properties", props_desc: "Table properties", paste_row_before_desc: "Paste table row before", paste_row_after_desc: "Paste table row after", cut_row_desc: "Cut table row", copy_row_desc: "Copy table row", del: "Delete table",
cell: "Cell" }, autosave: { unload_msg: "The changes you made will be lost if you navigate away from this page." }, fullscreen: { desc: "Toggle fullscreen mode (Alt + Shift + G)" }, media: { desc: "Insert / edit embedded media", edit: "Edit embedded media" }, fullpage: { desc: "Document properties" }, template: { desc: "Insert predefined template content" }, visualchars: { desc: "Visual control characters on/off." }, spellchecker: { desc: "Toggle spellchecker (Alt + Shift + N)", menu: "Spellchecker settings", ignore_word: "Ignore word", ignore_words: "Ignore all", langs: "Languages", wait: "Please wait...", sug: "Suggestions", no_sug: "No suggestions", no_mpell: "No misspellings found.", learn_word: "Learn word" }, pagebreak: { desc: "Insert Page Break" }, advlist:{ types: "Types", def: "Default", lower_alpha: "Lower alpha", lower_greek: "Lower greek", lower_roman: "Lower roman", upper_alpha: "Upper alpha", upper_roman: "Upper roman", circle: "Circle", disc: "Disc", square: "Square" }, aria: { rich_text_area: "Rich Text Area" }, wordcount:{ words: "Words: " } }; tinyMCE.addI18n( main ); tinyMCE.addI18n( lang + ".advanced", { style_select: "Styles", font_size: "Font size", fontdefault: "Font family", block: "Format", paragraph: "Paragraph", div: "Div", address: "Address", pre: "Preformatted", h1: "Heading 1", h2: "Heading 2", h3: "Heading 3", h4: "Heading 4", h5: "Heading 5", h6: "Heading 6", blockquote: "Blockquote", code: "Code", samp: "Code sample", dt: "Definition term ", dd: "Definition description", bold_desc: "Bold (Ctrl + B)", italic_desc: "Italic (Ctrl + I)", underline_desc: "Underline", striketrough_desc: "Strikethrough (Alt + Shift + D)", justifyleft_desc: "Align Left (Alt + Shift + L)", justifycenter_desc: "Align Center (Alt + Shift + C)", justifyright_desc: "Align Right (Alt + Shift + R)", justifyfull_desc: "Align Full (Alt + Shift + J)", bullist_desc: "Unordered list (Alt + Shift + U)", numlist_desc: "Ordered list (Alt + Shift + O)", outdent_desc: "Outdent", indent_desc: "Indent", undo_desc: "Undo (Ctrl + Z)", redo_desc: "Redo (Ctrl + Y)", link_desc: "Insert/edit link (Alt + Shift + A)", unlink_desc: "Unlink (Alt + Shift + S)", image_desc: "Insert/edit image (Alt + Shift + M)", cleanup_desc: "Cleanup messy code", code_desc: "Edit HTML Source", sub_desc: "Subscript", sup_desc: "Superscript", hr_desc: "Insert horizontal ruler", removeformat_desc: "Remove formatting", forecolor_desc: "Select text color", backcolor_desc: "Select background color", charmap_desc: "Insert custom character", visualaid_desc: "Toggle guidelines/invisible elements", anchor_desc: "Insert/edit anchor", cut_desc: "Cut", copy_desc: "Copy", paste_desc: "Paste", image_props_desc: "Image properties", newdocument_desc: "New document", help_desc: "Help", blockquote_desc: "Blockquote (Alt + Shift + Q)", clipboard_msg: "Copy/Cut/Paste is not available in Mozilla and Firefox.", path: "Path", newdocument: "Are you sure you want to clear all contents?", toolbar_focus: "Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X", more_colors: "More colors", shortcuts_desc: "Accessibility Help", help_shortcut: " Press ALT F10 for toolbar. Press ALT 0 for help.", rich_text_area: "Rich Text Area", toolbar: "Toolbar" }); tinyMCE.addI18n( lang + ".advanced_dlg", { about_title: "About TinyMCE", about_general: "About", about_help: "Help", about_license: "License", about_plugins: "Plugins", about_plugin: "Plugin", about_author: "Author", about_version: "Version", about_loaded: "Loaded plugins", anchor_title: "Insert/edit anchor", anchor_name: "Anchor name", code_title: "HTML Source Editor", code_wordwrap: "Word wrap", colorpicker_title: "Select a color", colorpicker_picker_tab: "Picker", colorpicker_picker_title: "Color picker", colorpicker_palette_tab: "Palette", colorpicker_palette_title: "Palette colors", colorpicker_named_tab: "Named", colorpicker_named_title: "Named colors", colorpicker_color: "Color: ", colorpicker_name: "Name: ", charmap_title: "Select custom character", charmap_usage: "Use left and right arrows to navigate.", image_title: "Insert/edit image", image_src: "Image URL", image_alt: "Image description", image_list: "Image list", image_border: "Border", image_dimensions: "Dimensions", image_vspace: "Vertical space", image_hspace: "Horizontal space", image_align: "Alignment", image_align_baseline: "Baseline", image_align_top: "Top", image_align_middle: "Middle", image_align_bottom: "Bottom", image_align_texttop: "Text top", image_align_textbottom: "Text bottom", image_align_left: "Left", image_align_right: "Right", link_title: "Insert/edit link", link_url: "Link URL", link_target: "Target", link_target_same: "Open link in the same window", link_target_blank: "Open link in a new window", link_titlefield: "Title", link_is_email: "The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", link_is_external: "The URL you entered seems to be an external link, do you want to add the required http:// prefix?", link_list: "Link list", accessibility_help: "Accessibility Help", accessibility_usage_title: "General Usage" }); tinyMCE.addI18n( lang + ".media_dlg", { title: "Insert / edit embedded media", general: "General", advanced: "Advanced", file: "File/URL", list: "List", size: "Dimensions", preview: "Preview", constrain_proportions: "Constrain proportions", type: "Type", id: "Id", name: "Name", class_name: "Class", vspace: "V-Space", hspace: "H-Space", play: "Auto play", loop: "Loop", menu: "Show menu", quality: "Quality", scale: "Scale", align: "Align", salign: "SAlign", wmode: "WMode", bgcolor: "Background", base: "Base", flashvars: "Flashvars", liveconnect: "SWLiveConnect", autohref: "AutoHREF", cache: "Cache", hidden: "Hidden", controller: "Controller", kioskmode: "Kiosk mode", playeveryframe: "Play every frame", targetcache: "Target cache", correction: "No correction", enablejavascript: "Enable JavaScript", starttime: "Start time", endtime: "End time", href: "href", qtsrcchokespeed: "Choke speed", target: "Target", volume: "Volume", autostart: "Auto start", enabled: "Enabled", fullscreen: "Fullscreen", invokeurls: "Invoke URLs", mute: "Mute", stretchtofit: "Stretch to fit", windowlessvideo: "Windowless video", balance: "Balance", baseurl: "Base URL", captioningid: "Captioning id", currentmarker: "Current marker", currentposition: "Current position", defaultframe: "Default frame", playcount: "Play count", rate: "Rate", uimode: "UI Mode", flash_options: "Flash options", qt_options: "QuickTime options", wmp_options: "Windows media player options", rmp_options: "Real media player options", shockwave_options: "Shockwave options", autogotourl: "Auto goto URL", center: "Center", imagestatus: "Image status", maintainaspect: "Maintain aspect", nojava: "No java", prefetch: "Prefetch", shuffle: "Shuffle", console: "Console", numloop: "Num loops", controls: "Controls", scriptcallbacks: "Script callbacks", swstretchstyle: "Stretch style", swstretchhalign: "Stretch H-Align", swstretchvalign: "Stretch V-Align", sound: "Sound", progress: "Progress", qtsrc: "QT Src", qt_stream_warn: "Streamed rtsp resources should be added to the QT Src field under the advanced tab.", align_top: "Top", align_right: "Right", align_bottom: "Bottom", align_left: "Left", align_center: "Center", align_top_left: "Top left", align_top_right: "Top right", align_bottom_left: "Bottom left", align_bottom_right: "Bottom right", flv_options: "Flash video options", flv_scalemode: "Scale mode", flv_buffer: "Buffer", flv_startimage: "Start image", flv_starttime: "Start time", flv_defaultvolume: "Default volume", flv_hiddengui: "Hidden GUI", flv_autostart: "Auto start", flv_loop: "Loop", flv_showscalemodes: "Show scale modes", flv_smoothvideo: "Smooth video", flv_jscallback: "JS Callback", html5_video_options: "HTML5 Video Options", altsource1: "Alternative source 1", altsource2: "Alternative source 2", preload: "Preload", poster: "Poster", source: "Source" }); tinyMCE.addI18n( lang + ".Mtaandao", { mn_adv_desc: "Show/Hide Kitchen Sink (Alt + Shift + Z)", mn_more_desc: "Insert More Tag (Alt + Shift + T)", mn_page_desc: "Insert Page break (Alt + Shift + P)", mn_help_desc: "Help (Alt + Shift + H)", mn_more_alt: "More...", mn_page_alt: "Next page...", add_media: "Add Media", add_image: "Add an Image", add_video: "Add Video", add_audio: "Add Audio", editgallery: "Edit Gallery", delgallery: "Delete Gallery", mn_fullscreen_desc: "Distraction-free writing mode (Alt + Shift + W)" }); tinyMCE.addI18n( lang + ".mneditimage", { edit_img: "Edit Image", del_img: "Delete Image", adv_settings: "Advanced Settings", none: "None", size: "Size", thumbnail: "Thumbnail", medium: "Medium", full_size: "Full Size", current_link: "Current Link", link_to_img: "Link to Image", link_help: "Enter a link URL or click above for presets.", adv_img_settings: "Advanced Image Settings", source: "Source", width: "Width", height: "Height", orig_size: "Original Size", css: "CSS Class", adv_link_settings: "Advanced Link Settings", link_rel: "Link Rel", height: "Height", orig_size: "Original Size", css: "CSS Class", s60: "60%", s70: "70%", s80: "80%", s90: "90%", s100: "100%", s110: "110%", s120: "120%", s130: "130%", img_title: "Title", caption: "Caption", alt: "Alternative Text" }); }());
row: "Row", col: "Column",
random_line_split
main.rs
extern crate ncurses; use std::io; use std::convert::AsRef; use ncurses::*; const CONFIRM_STRING: &'static str = "y"; const OUTPUT_EXAMPLE: &'static str = "Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。"; fn ex1(s: &str)
initscr(); printw(s); refresh(); getch(); endwin(); } fn main() { let mylocale = LcCategory::all; setlocale(mylocale, "zh_CN.UTF-8"); let mut input = String::new(); println!("[ncurses-rs examples]\n"); println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING); io::stdin().read_line(&mut input) .ok() .expect("Fail to get keyboard input"); match input.trim().as_ref() { CONFIRM_STRING | "" => ex1(OUTPUT_EXAMPLE), _ => println!("...Go to next step.") } println!("example_2. Press [Enter] to run it..."); // ex2(); }
{
identifier_name
main.rs
extern crate ncurses; use std::io; use std::convert::AsRef; use ncurses::*; const CONFIRM_STRING: &'static str = "y"; const OUTPUT_EXAMPLE: &'static str = "Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。"; fn ex1(s: &str) { initscr(); printw(s);
fn main() { let mylocale = LcCategory::all; setlocale(mylocale, "zh_CN.UTF-8"); let mut input = String::new(); println!("[ncurses-rs examples]\n"); println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING); io::stdin().read_line(&mut input) .ok() .expect("Fail to get keyboard input"); match input.trim().as_ref() { CONFIRM_STRING | "" => ex1(OUTPUT_EXAMPLE), _ => println!("...Go to next step.") } println!("example_2. Press [Enter] to run it..."); // ex2(); }
refresh(); getch(); endwin(); }
random_line_split
main.rs
extern crate ncurses; use std::io; use std::convert::AsRef; use ncurses::*; const CONFIRM_STRING: &'static str = "y"; const OUTPUT_EXAMPLE: &'static str = "Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。"; fn ex1(s: &str) { initsc
{ let mylocale = LcCategory::all; setlocale(mylocale, "zh_CN.UTF-8"); let mut input = String::new(); println!("[ncurses-rs examples]\n"); println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING); io::stdin().read_line(&mut input) .ok() .expect("Fail to get keyboard input"); match input.trim().as_ref() { CONFIRM_STRING | "" => ex1(OUTPUT_EXAMPLE), _ => println!("...Go to next step.") } println!("example_2. Press [Enter] to run it..."); // ex2(); }
r(); printw(s); refresh(); getch(); endwin(); } fn main()
identifier_body
dates.ts
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { parse } from 'date-fns'; import { ParsableDate } from '../types/dates'; function pad(number: number)
export function parseDate(rawDate: ParsableDate): Date { return parse(rawDate); } export function toShortNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } export function toNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return date.toISOString().replace(/\..+Z$/, '+0000'); } export function isValidDate(date: Date): boolean { return !isNaN(date.getTime()); }
{ if (number < 10) { return '0' + number.toString(); } return number; }
identifier_body
dates.ts
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { parse } from 'date-fns'; import { ParsableDate } from '../types/dates'; function pad(number: number) { if (number < 10)
return number; } export function parseDate(rawDate: ParsableDate): Date { return parse(rawDate); } export function toShortNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } export function toNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return date.toISOString().replace(/\..+Z$/, '+0000'); } export function isValidDate(date: Date): boolean { return !isNaN(date.getTime()); }
{ return '0' + number.toString(); }
conditional_block
dates.ts
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { parse } from 'date-fns'; import { ParsableDate } from '../types/dates'; function pad(number: number) { if (number < 10) { return '0' + number.toString(); } return number; } export function parseDate(rawDate: ParsableDate): Date { return parse(rawDate); } export function toShortNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } export function
(rawDate: ParsableDate): string { const date = parseDate(rawDate); return date.toISOString().replace(/\..+Z$/, '+0000'); } export function isValidDate(date: Date): boolean { return !isNaN(date.getTime()); }
toNotSoISOString
identifier_name
dates.ts
/* * SonarQube
* Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { parse } from 'date-fns'; import { ParsableDate } from '../types/dates'; function pad(number: number) { if (number < 10) { return '0' + number.toString(); } return number; } export function parseDate(rawDate: ParsableDate): Date { return parse(rawDate); } export function toShortNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } export function toNotSoISOString(rawDate: ParsableDate): string { const date = parseDate(rawDate); return date.toISOString().replace(/\..+Z$/, '+0000'); } export function isValidDate(date: Date): boolean { return !isNaN(date.getTime()); }
random_line_split
test_parsable.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # name: test_parsable.py # author: Harold Bradley III # email: harold@bradleystudio.net # created on: 01/16/2016 # # pylint: disable=invalid-name,no-member """ A unit test for ext_pylib file module's Parsable mixin class. """ import pytest from . import utils from ext_pylib.files import File, Parsable class ParsableFile(Parsable, File): """Dummy class extending Parsable and File."""
DEBUG = True SECURE = False DocumentRoot /var/www/example.com LIST = first_item LIST = second_item """ EMPTY_FILE = '' def test_parsable_parse_with_existing_attribute(): """Test Parsable setup_parsing() method on an existing attribute.""" parsable = ParsableFile() parsable.existing = 'already exists' # pylint: disable=attribute-defined-outside-init with pytest.raises(AttributeError): parsable.setup_parsing({'existing' : '*'}) def test_parsable_setup_parsing(): """Test Parsable setup_parsing() method.""" the_file = Parsable() Parsable.read = utils.mock_read_data the_file.data = FILE the_file.setup_parsing({ 'htdocs' : ('DocumentRoot (.*)',), 'debug' : 'DEBUG = (.*)', 'secure' : ('SECURE[ ]*=[ ]*([^ \n]*)', 'SECURE = {0}'), 'speed' : ('SPEED[ ]*=[ ]*([^ \n]*)', 'SPEED = {0}'), 'list' : ('LIST[ ]*=[ ]*([^ \n]*)', 'LIST = {0}'), }) assert the_file.htdocs[0] == '/var/www/google.com' assert the_file.htdocs[1] == '/var/www/example.com' assert the_file.debug == 'True' assert the_file.secure == 'False' the_file.secure = 'True' assert the_file.secure == 'True' assert the_file.speed is None the_file.speed = 'fastest' assert the_file.speed == 'fastest' the_file.speed = 'fastest' # setting it more than once with the same value # shouldn't affect the number of times it is added. assert isinstance(the_file.speed, str) \ or isinstance(the_file.speed, unicode) # Shouldn't be a list, checking unicode # for Python 2 support. assert len(the_file.list) == 2 # Should be a list def test_parsable_setup_parsing_on_empty_file(): """Test Parsable setup_paring() using an empty file.""" the_file = Parsable() Parsable.read = utils.mock_read_data the_file.data = EMPTY_FILE the_file.setup_parsing({ 'htdocs' : ('DocumentRoot (.*)', 'DocumentRoot {0}'), 'secure' : ('SECURE[ ]*=[ ]*([^ \n]*)', 'SECURE = {0}'), }) assert the_file.htdocs is None the_file.htdocs = '/var/www/google.com' assert the_file.htdocs == '/var/www/google.com' assert the_file.secure is None the_file.secure = 'True' assert the_file.secure == 'True'
FILE = """This is a sample file. This is a sample file. This is a sample file. DocumentRoot /var/www/google.com This is a sample file.
random_line_split
test_parsable.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # name: test_parsable.py # author: Harold Bradley III # email: harold@bradleystudio.net # created on: 01/16/2016 # # pylint: disable=invalid-name,no-member """ A unit test for ext_pylib file module's Parsable mixin class. """ import pytest from . import utils from ext_pylib.files import File, Parsable class
(Parsable, File): """Dummy class extending Parsable and File.""" FILE = """This is a sample file. This is a sample file. This is a sample file. DocumentRoot /var/www/google.com This is a sample file. DEBUG = True SECURE = False DocumentRoot /var/www/example.com LIST = first_item LIST = second_item """ EMPTY_FILE = '' def test_parsable_parse_with_existing_attribute(): """Test Parsable setup_parsing() method on an existing attribute.""" parsable = ParsableFile() parsable.existing = 'already exists' # pylint: disable=attribute-defined-outside-init with pytest.raises(AttributeError): parsable.setup_parsing({'existing' : '*'}) def test_parsable_setup_parsing(): """Test Parsable setup_parsing() method.""" the_file = Parsable() Parsable.read = utils.mock_read_data the_file.data = FILE the_file.setup_parsing({ 'htdocs' : ('DocumentRoot (.*)',), 'debug' : 'DEBUG = (.*)', 'secure' : ('SECURE[ ]*=[ ]*([^ \n]*)', 'SECURE = {0}'), 'speed' : ('SPEED[ ]*=[ ]*([^ \n]*)', 'SPEED = {0}'), 'list' : ('LIST[ ]*=[ ]*([^ \n]*)', 'LIST = {0}'), }) assert the_file.htdocs[0] == '/var/www/google.com' assert the_file.htdocs[1] == '/var/www/example.com' assert the_file.debug == 'True' assert the_file.secure == 'False' the_file.secure = 'True' assert the_file.secure == 'True' assert the_file.speed is None the_file.speed = 'fastest' assert the_file.speed == 'fastest' the_file.speed = 'fastest' # setting it more than once with the same value # shouldn't affect the number of times it is added. assert isinstance(the_file.speed, str) \ or isinstance(the_file.speed, unicode) # Shouldn't be a list, checking unicode # for Python 2 support. assert len(the_file.list) == 2 # Should be a list def test_parsable_setup_parsing_on_empty_file(): """Test Parsable setup_paring() using an empty file.""" the_file = Parsable() Parsable.read = utils.mock_read_data the_file.data = EMPTY_FILE the_file.setup_parsing({ 'htdocs' : ('DocumentRoot (.*)', 'DocumentRoot {0}'), 'secure' : ('SECURE[ ]*=[ ]*([^ \n]*)', 'SECURE = {0}'), }) assert the_file.htdocs is None the_file.htdocs = '/var/www/google.com' assert the_file.htdocs == '/var/www/google.com' assert the_file.secure is None the_file.secure = 'True' assert the_file.secure == 'True'
ParsableFile
identifier_name
test_parsable.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # name: test_parsable.py # author: Harold Bradley III # email: harold@bradleystudio.net # created on: 01/16/2016 # # pylint: disable=invalid-name,no-member """ A unit test for ext_pylib file module's Parsable mixin class. """ import pytest from . import utils from ext_pylib.files import File, Parsable class ParsableFile(Parsable, File): """Dummy class extending Parsable and File.""" FILE = """This is a sample file. This is a sample file. This is a sample file. DocumentRoot /var/www/google.com This is a sample file. DEBUG = True SECURE = False DocumentRoot /var/www/example.com LIST = first_item LIST = second_item """ EMPTY_FILE = '' def test_parsable_parse_with_existing_attribute():
def test_parsable_setup_parsing(): """Test Parsable setup_parsing() method.""" the_file = Parsable() Parsable.read = utils.mock_read_data the_file.data = FILE the_file.setup_parsing({ 'htdocs' : ('DocumentRoot (.*)',), 'debug' : 'DEBUG = (.*)', 'secure' : ('SECURE[ ]*=[ ]*([^ \n]*)', 'SECURE = {0}'), 'speed' : ('SPEED[ ]*=[ ]*([^ \n]*)', 'SPEED = {0}'), 'list' : ('LIST[ ]*=[ ]*([^ \n]*)', 'LIST = {0}'), }) assert the_file.htdocs[0] == '/var/www/google.com' assert the_file.htdocs[1] == '/var/www/example.com' assert the_file.debug == 'True' assert the_file.secure == 'False' the_file.secure = 'True' assert the_file.secure == 'True' assert the_file.speed is None the_file.speed = 'fastest' assert the_file.speed == 'fastest' the_file.speed = 'fastest' # setting it more than once with the same value # shouldn't affect the number of times it is added. assert isinstance(the_file.speed, str) \ or isinstance(the_file.speed, unicode) # Shouldn't be a list, checking unicode # for Python 2 support. assert len(the_file.list) == 2 # Should be a list def test_parsable_setup_parsing_on_empty_file(): """Test Parsable setup_paring() using an empty file.""" the_file = Parsable() Parsable.read = utils.mock_read_data the_file.data = EMPTY_FILE the_file.setup_parsing({ 'htdocs' : ('DocumentRoot (.*)', 'DocumentRoot {0}'), 'secure' : ('SECURE[ ]*=[ ]*([^ \n]*)', 'SECURE = {0}'), }) assert the_file.htdocs is None the_file.htdocs = '/var/www/google.com' assert the_file.htdocs == '/var/www/google.com' assert the_file.secure is None the_file.secure = 'True' assert the_file.secure == 'True'
"""Test Parsable setup_parsing() method on an existing attribute.""" parsable = ParsableFile() parsable.existing = 'already exists' # pylint: disable=attribute-defined-outside-init with pytest.raises(AttributeError): parsable.setup_parsing({'existing' : '*'})
identifier_body
conf.py
# -*- coding: utf-8 -*- # # cloudtracker documentation build configuration file, created by # sphinx-quickstart on Fri Aug 5 12:45:40 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('../cloudtracker/')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.pngmath'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'cloudtracker' copyright = u'2011, Jordan Dawe' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'cloudtrackerdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'cloudtracker.tex', u'cloudtracker Documentation', u'Jordan Dawe', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'cloudtracker', u'cloudtracker Documentation', [u'Jordan Dawe'], 1) ]
#needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
random_line_split
options.js
var expect = require('expect.js'), options = require('../lib/options'); describe("options", function() { describe("#firstNumberTest", function() { it("should be true when divisble by 3", function() { expect(options.firstNumberTest(3,3)).to.be(true); }); it("should be false when divisble by 3", function() {
describe("#secondNumberTest", function() { it("should be true when divisble by 5", function() { expect(options.secondNumberTest(5,5)).to.be(true); }); it("should be false when divisble by 5", function() { expect(options.secondNumberTest(8,5)).to.be(false); }); }); describe("#noSuccess", function() { it("should return a string of the number given", function() { expect(options.noSuccess(4)).to.equal("4"); }); }); });
expect(options.firstNumberTest(8,3)).to.be(false); }); });
random_line_split
gen_figure_rst.py
import os from example_builder import ExampleBuilder RST_TEMPLATE = """ .. _%(sphinx_tag)s: %(docstring)s %(image_list)s .. raw:: html <div class="toggle_trigger"><a href="#"> **Code output:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(stdout)s .. raw:: html </div> <div class="toggle_trigger" id="start_open"><a href="#"> **Python source code:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(fname)s :lines: %(end_line)s- .. raw:: html </div> <div align="right"> :download:`[download source: %(fname)s] <%(fname)s>` .. raw:: html </div> """ def main(app): target_dir = os.path.join(app.builder.srcdir, 'book_figures') source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) if not os.path.exists(source_dir): os.makedirs(source_dir) if not os.path.exists(target_dir):
EB = ExampleBuilder(source_dir, target_dir, execute_files=plot_gallery, contents_file='contents.txt', dir_info_file='README.rst', dir_footer_file='FOOTER.rst', sphinx_tag_base='book_fig', template_example=RST_TEMPLATE) EB.run() def setup(app): app.connect('builder-inited', main) #app.add_config_value('plot_gallery', True, 'html')
os.makedirs(target_dir)
conditional_block
gen_figure_rst.py
import os from example_builder import ExampleBuilder RST_TEMPLATE = """ .. _%(sphinx_tag)s: %(docstring)s %(image_list)s .. raw:: html <div class="toggle_trigger"><a href="#"> **Code output:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(stdout)s .. raw:: html </div> <div class="toggle_trigger" id="start_open"><a href="#"> **Python source code:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(fname)s :lines: %(end_line)s- .. raw:: html </div> <div align="right"> :download:`[download source: %(fname)s] <%(fname)s>` .. raw:: html </div> """ def main(app): target_dir = os.path.join(app.builder.srcdir, 'book_figures') source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples')
if not os.path.exists(source_dir): os.makedirs(source_dir) if not os.path.exists(target_dir): os.makedirs(target_dir) EB = ExampleBuilder(source_dir, target_dir, execute_files=plot_gallery, contents_file='contents.txt', dir_info_file='README.rst', dir_footer_file='FOOTER.rst', sphinx_tag_base='book_fig', template_example=RST_TEMPLATE) EB.run() def setup(app): app.connect('builder-inited', main) #app.add_config_value('plot_gallery', True, 'html')
try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery)
random_line_split
gen_figure_rst.py
import os from example_builder import ExampleBuilder RST_TEMPLATE = """ .. _%(sphinx_tag)s: %(docstring)s %(image_list)s .. raw:: html <div class="toggle_trigger"><a href="#"> **Code output:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(stdout)s .. raw:: html </div> <div class="toggle_trigger" id="start_open"><a href="#"> **Python source code:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(fname)s :lines: %(end_line)s- .. raw:: html </div> <div align="right"> :download:`[download source: %(fname)s] <%(fname)s>` .. raw:: html </div> """ def main(app):
def setup(app): app.connect('builder-inited', main) #app.add_config_value('plot_gallery', True, 'html')
target_dir = os.path.join(app.builder.srcdir, 'book_figures') source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) if not os.path.exists(source_dir): os.makedirs(source_dir) if not os.path.exists(target_dir): os.makedirs(target_dir) EB = ExampleBuilder(source_dir, target_dir, execute_files=plot_gallery, contents_file='contents.txt', dir_info_file='README.rst', dir_footer_file='FOOTER.rst', sphinx_tag_base='book_fig', template_example=RST_TEMPLATE) EB.run()
identifier_body
gen_figure_rst.py
import os from example_builder import ExampleBuilder RST_TEMPLATE = """ .. _%(sphinx_tag)s: %(docstring)s %(image_list)s .. raw:: html <div class="toggle_trigger"><a href="#"> **Code output:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(stdout)s .. raw:: html </div> <div class="toggle_trigger" id="start_open"><a href="#"> **Python source code:** .. raw:: html </a></div> <div class="toggle_container"> .. literalinclude:: %(fname)s :lines: %(end_line)s- .. raw:: html </div> <div align="right"> :download:`[download source: %(fname)s] <%(fname)s>` .. raw:: html </div> """ def
(app): target_dir = os.path.join(app.builder.srcdir, 'book_figures') source_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeError: plot_gallery = bool(app.builder.config.plot_gallery) if not os.path.exists(source_dir): os.makedirs(source_dir) if not os.path.exists(target_dir): os.makedirs(target_dir) EB = ExampleBuilder(source_dir, target_dir, execute_files=plot_gallery, contents_file='contents.txt', dir_info_file='README.rst', dir_footer_file='FOOTER.rst', sphinx_tag_base='book_fig', template_example=RST_TEMPLATE) EB.run() def setup(app): app.connect('builder-inited', main) #app.add_config_value('plot_gallery', True, 'html')
main
identifier_name
session.spec.ts
import { expect } from 'chai'; import * as deepFreeze from 'deep-freeze'; import {actionsEnums} from '../common/actionsEnums' import {sessionReducer} from './session' import { UserProfile } from '../model/userProfile' import { LoginEntity } from '../model/login' describe('sessionReducer', () => { describe('#handlePerformLogin', () => { it('Store successful login information in the store', () => { // Arrange const initialState = { isUserLoggedIn : false, userProfile : new UserProfile(), editingLogin : new LoginEntity() }; deepFreeze(initialState); const userFullname = 'John Doe'; const role = 'admin'; const action = { type: actionsEnums.USERPROFILE_PERFORM_LOGIN, payload: {
} } }; // Act const finalState = sessionReducer(initialState, action); // Assert expect(finalState).not.to.be.undefined; expect(finalState.isUserLoggedIn).to.be.true; expect(finalState.userProfile.fullname).to.be.equal(userFullname) expect(finalState.userProfile.role).to.be.equal(role) }); }); });
succeeded : true, userProfile : { fullname : userFullname, role : role
random_line_split
hc_domimplementationfeaturexml.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ /** * Gets URI that identifies the test. * @return uri identifier of test */ function getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml"; } var docsLoaded = -1000000; var builder = null; // // This function is called by the testing framework before // running the test suite. // // If there are no configuration exceptions, asynchronous // document loading is started. Otherwise, the status // is set to complete and the exception is immediately // raised when entering the body of the test. // function setUpPage() { setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRef, "doc", "hc_staff"); if (docsLoaded == 1) { setUpPageStatus = 'complete'; } } catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function loadComplete() { if (++docsLoaded == 1) { setUpPageStatus = 'complete'; } } /** * Retrieve the entire DOM document and invoke its "getImplementation()" method. This should create a DOMImplementation object whose "hasFeature(feature, version)" method is invoked with "feature" equal to "html" or "xml". The method should return a boolean "true". * @author Curt Arnold * @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-5CED94D7 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=245 */ function hc_domimplementationfeaturexml() {
nction runTest() { hc_domimplementationfeaturexml(); }
var success; if(checkInitialization(builder, "hc_domimplementationfeaturexml") != null) return; var doc; var domImpl; var state; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "hc_staff"); domImpl = doc.implementation; if( (builder.contentType == "text/html") ) { state = domImpl.hasFeature("html","1.0"); assertTrue("supports_html_1.0",state); } else { state = domImpl.hasFeature("xml","1.0"); assertTrue("supports_xml_1.0",state); } } fu
identifier_body
hc_domimplementationfeaturexml.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ /** * Gets URI that identifies the test. * @return uri identifier of test */ function getT
return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml"; } var docsLoaded = -1000000; var builder = null; // // This function is called by the testing framework before // running the test suite. // // If there are no configuration exceptions, asynchronous // document loading is started. Otherwise, the status // is set to complete and the exception is immediately // raised when entering the body of the test. // function setUpPage() { setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRef, "doc", "hc_staff"); if (docsLoaded == 1) { setUpPageStatus = 'complete'; } } catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function loadComplete() { if (++docsLoaded == 1) { setUpPageStatus = 'complete'; } } /** * Retrieve the entire DOM document and invoke its "getImplementation()" method. This should create a DOMImplementation object whose "hasFeature(feature, version)" method is invoked with "feature" equal to "html" or "xml". The method should return a boolean "true". * @author Curt Arnold * @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-5CED94D7 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=245 */ function hc_domimplementationfeaturexml() { var success; if(checkInitialization(builder, "hc_domimplementationfeaturexml") != null) return; var doc; var domImpl; var state; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "hc_staff"); domImpl = doc.implementation; if( (builder.contentType == "text/html") ) { state = domImpl.hasFeature("html","1.0"); assertTrue("supports_html_1.0",state); } else { state = domImpl.hasFeature("xml","1.0"); assertTrue("supports_xml_1.0",state); } } function runTest() { hc_domimplementationfeaturexml(); }
argetURI() {
identifier_name
hc_domimplementationfeaturexml.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ /** * Gets URI that identifies the test. * @return uri identifier of test */ function getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml"; } var docsLoaded = -1000000; var builder = null; // // This function is called by the testing framework before // running the test suite. // // If there are no configuration exceptions, asynchronous // document loading is started. Otherwise, the status // is set to complete and the exception is immediately // raised when entering the body of the test. // function setUpPage() { setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRef, "doc", "hc_staff"); if (docsLoaded == 1) { setUpPageStatus = 'complete'; } } catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function loadComplete() { if (++docsLoaded == 1) {
/** * Retrieve the entire DOM document and invoke its "getImplementation()" method. This should create a DOMImplementation object whose "hasFeature(feature, version)" method is invoked with "feature" equal to "html" or "xml". The method should return a boolean "true". * @author Curt Arnold * @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-5CED94D7 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=245 */ function hc_domimplementationfeaturexml() { var success; if(checkInitialization(builder, "hc_domimplementationfeaturexml") != null) return; var doc; var domImpl; var state; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "hc_staff"); domImpl = doc.implementation; if( (builder.contentType == "text/html") ) { state = domImpl.hasFeature("html","1.0"); assertTrue("supports_html_1.0",state); } else { state = domImpl.hasFeature("xml","1.0"); assertTrue("supports_xml_1.0",state); } } function runTest() { hc_domimplementationfeaturexml(); }
setUpPageStatus = 'complete'; } }
conditional_block
hc_domimplementationfeaturexml.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/** * Gets URI that identifies the test. * @return uri identifier of test */ function getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_domimplementationfeaturexml"; } var docsLoaded = -1000000; var builder = null; // // This function is called by the testing framework before // running the test suite. // // If there are no configuration exceptions, asynchronous // document loading is started. Otherwise, the status // is set to complete and the exception is immediately // raised when entering the body of the test. // function setUpPage() { setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRef, "doc", "hc_staff"); if (docsLoaded == 1) { setUpPageStatus = 'complete'; } } catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function loadComplete() { if (++docsLoaded == 1) { setUpPageStatus = 'complete'; } } /** * Retrieve the entire DOM document and invoke its "getImplementation()" method. This should create a DOMImplementation object whose "hasFeature(feature, version)" method is invoked with "feature" equal to "html" or "xml". The method should return a boolean "true". * @author Curt Arnold * @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-5CED94D7 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=245 */ function hc_domimplementationfeaturexml() { var success; if(checkInitialization(builder, "hc_domimplementationfeaturexml") != null) return; var doc; var domImpl; var state; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "hc_staff"); domImpl = doc.implementation; if( (builder.contentType == "text/html") ) { state = domImpl.hasFeature("html","1.0"); assertTrue("supports_html_1.0",state); } else { state = domImpl.hasFeature("xml","1.0"); assertTrue("supports_xml_1.0",state); } } function runTest() { hc_domimplementationfeaturexml(); }
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */
random_line_split
MotivationBtnView.js
define([ 'backbone', 'metro', 'util' ], function(Backbone, Metro, Util) { var MotivationBtnView = Backbone.View.extend({ className: 'motivation-btn-view menu-btn', events: { 'click': 'toggle', 'mouseover': 'over', 'mouseout': 'out', }, initialize: function(){ //ensure correct scope _.bindAll(this, 'render', 'unrender', 'toggle', 'over', 'out'); //initial param this.motivationView = new MotivationView(); //add to page this.render(); }, render: function() { var $button = $('<span class="mif-compass">'); $(this.el).html($button); $(this.el).attr('title', 'motivation...'); $('body > .container').append($(this.el)); return this; }, unrender: function() { this.drawElementsView.unrender(); $(this.el).remove(); }, toggle: function() { this.drawElementsView.toggle(); }, over: function() { $(this.el).addClass('expand'); }, out: function() { $(this.el).removeClass('expand'); } }); var MotivationView = Backbone.View.extend({ className: 'motivation-view', events: { 'click .draw': 'draw', 'click .clean': 'clean', 'change .input-type > select': 'clean' }, initialize: function(){ //ensure correct scope _.bindAll(this, 'render', 'unrender', 'toggle', 'drawMotivation', 'drawGPS', 'drawAssignedSection', 'drawAugmentedSection'); //motivation param this.param = {}; this.param.o_lng = 114.05604600906372; this.param.o_lat = 22.551225247189432; this.param.d_lng = 114.09120440483093; this.param.d_lat = 22.545463347318833; this.param.path = "33879,33880,33881,33882,33883,33884,33885,41084,421,422,423,2383,2377,2376,2334,2335,2565,2566,2567,2568,2569,2570,2571,2572,2573,39716,39717,39718,39719,39720,39721,39722,39723,448,39677,39678"; //GPS param this.param.gps = "114.05538082122803,22.551086528436926#114.05844390392303,22.551324331927283#114.06151771545409,22.551264881093118#114.06260132789612,22.54908499948478#114.06269788742065,22.5456862971879#114.06271934509277,22.54315951091646#114.06271934509277,22.538938188315093#114.06284809112547,22.53441944644356"; //assigned section param this.param.assign = "33878,33881,33883,2874,2877,2347,937,941"; //augmented section param //33878,33879,33880,33881,33882,33883,2874,2875,2876,2877,2878,2347,935,936,937,938,939,940,941, this.param.augment = "33879,33880,33882,2875,2876,2878,935,936,938,939,940"; //add to page this.render(); }, render: function() { //this.drawMotivation(); this.drawAssignedSection(); this.drawAugmentedSection(); this.drawGPS(); return this; }, unrender: function() { $(this.el).remove(); }, toggle: function() { $(this.el).css('display') == 'none' ? $(this.el).show() : $(this.el).hide(); }, drawMotivation: function() { $.get('api/trajectories/motivation', this.param, function(data){ Backbone.trigger('MapView:drawMotivation', data); }); }, drawGPS: function() { var self = this; setTimeout(function() { var points = self.param.gps.split('#'); _.each(points, function(point_text, index) { var data = {}; data.geojson = self._getPoint(point_text); data.options = {};
}, 2000); }, drawAssignedSection: function() { $.get('api/elements/sections', {id: this.param.assign}, function(data){ Backbone.trigger('MapView:drawSampleAssignedSection', data); }); }, drawAugmentedSection: function() { $.get('api/elements/sections', {id: this.param.augment}, function(data){ Backbone.trigger('MapView:drawSampleAugmentedSection', data); }); }, _getPoint: function(text) { var point = text.split(','); var geojson = { "type": "FeatureCollection", "features":[{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [parseFloat(point[0]), parseFloat(point[1])] } }] }; return geojson; }, }); return MotivationBtnView; });
Backbone.trigger('MapView:drawSampleGPSPoint', data); });
random_line_split
plot_caustic_3d.py
import numpy as np import sys import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D if len(sys.argv) != 2: print "Correct usage: $ %s caustic_file" % sys.argv[1] exit(1) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") rows = np.loadtxt(sys.argv[1]) rs = np.array(zip(*cols)[-1]) max_r = np.max(rs) for row in rows: x, y, z, r = row line_r = max_r if np.isnan(r) else r term_x, term_y, term_z = x * line_r, y * line_r, z * line_r ax.plot([0, term_x], [0, term_y], [0, term_z], c="k") if not np.isnan(r):
plt.show()
ax.scatter([term_x], [term_y], [term_z], c="r")
conditional_block
plot_caustic_3d.py
import numpy as np import sys
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D if len(sys.argv) != 2: print "Correct usage: $ %s caustic_file" % sys.argv[1] exit(1) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") rows = np.loadtxt(sys.argv[1]) rs = np.array(zip(*cols)[-1]) max_r = np.max(rs) for row in rows: x, y, z, r = row line_r = max_r if np.isnan(r) else r term_x, term_y, term_z = x * line_r, y * line_r, z * line_r ax.plot([0, term_x], [0, term_y], [0, term_z], c="k") if not np.isnan(r): ax.scatter([term_x], [term_y], [term_z], c="r") plt.show()
random_line_split
geo_mutagenesis.py
__author__ = 'Matteo' __doc__='''This could be made into a handy mutagenesis library if I had time.''' from Bio.Seq import Seq,MutableSeq from Bio import SeqIO from Bio.Alphabet import IUPAC from difflib import Differ def Gthg01471(): ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) mut=MutableSeq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) a="AGTCGA" b="GACTAG" for i,v in enumerate([259,277,282,295,299,306]): print(mut[v-1]+a[i]) mut[v-1]=b[i] print(ori.translate()) print(mut.toseq().translate()) def Gthg04369(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[3583975:3585290].translate(to_stop=1) x=genome[0].seq[3583975:3585290].tomutable() print(x.pop(895-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg01115(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[891404:892205].reverse_complement().translate(to_stop=1) x=genome[0].seq[891404:892205].reverse_complement().tomutable() print(x.pop(421-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg03544():
if __name__ == "main": pass
filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1) x=genome[0].seq[2885410:2887572].reverse_complement().tomutable() print(x.pop(1748-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y))
identifier_body
geo_mutagenesis.py
__author__ = 'Matteo' __doc__='''This could be made into a handy mutagenesis library if I had time.''' from Bio.Seq import Seq,MutableSeq from Bio import SeqIO from Bio.Alphabet import IUPAC from difflib import Differ def Gthg01471(): ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) mut=MutableSeq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) a="AGTCGA" b="GACTAG" for i,v in enumerate([259,277,282,295,299,306]): print(mut[v-1]+a[i]) mut[v-1]=b[i] print(ori.translate()) print(mut.toseq().translate()) def Gthg04369(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[3583975:3585290].translate(to_stop=1) x=genome[0].seq[3583975:3585290].tomutable() print(x.pop(895-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg01115(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[891404:892205].reverse_complement().translate(to_stop=1) x=genome[0].seq[891404:892205].reverse_complement().tomutable() print(x.pop(421-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg03544(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank"))
x=genome[0].seq[2885410:2887572].reverse_complement().tomutable() print(x.pop(1748-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) if __name__ == "main": pass
z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1)
random_line_split
geo_mutagenesis.py
__author__ = 'Matteo' __doc__='''This could be made into a handy mutagenesis library if I had time.''' from Bio.Seq import Seq,MutableSeq from Bio import SeqIO from Bio.Alphabet import IUPAC from difflib import Differ def Gthg01471(): ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) mut=MutableSeq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) a="AGTCGA" b="GACTAG" for i,v in enumerate([259,277,282,295,299,306]):
print(ori.translate()) print(mut.toseq().translate()) def Gthg04369(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[3583975:3585290].translate(to_stop=1) x=genome[0].seq[3583975:3585290].tomutable() print(x.pop(895-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg01115(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[891404:892205].reverse_complement().translate(to_stop=1) x=genome[0].seq[891404:892205].reverse_complement().tomutable() print(x.pop(421-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg03544(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1) x=genome[0].seq[2885410:2887572].reverse_complement().tomutable() print(x.pop(1748-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) if __name__ == "main": pass
print(mut[v-1]+a[i]) mut[v-1]=b[i]
conditional_block
geo_mutagenesis.py
__author__ = 'Matteo' __doc__='''This could be made into a handy mutagenesis library if I had time.''' from Bio.Seq import Seq,MutableSeq from Bio import SeqIO from Bio.Alphabet import IUPAC from difflib import Differ def Gthg01471(): ori=Seq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) mut=MutableSeq("ATGAGCATAAGTTTATCGGTTCCAAAATGGTTATTAACAGTTTTATCAATTTTATCTTTAGTCGTAGCATTTATTTTCGGTACCGTTTCCAATGCATCAGCAACAATTAACTATGGGGAGGAAGTCGCGGCAGTAGCAAATGACTATGTAGGAAGCCCATATAAATATGGAGGTACAACGCCAAAAGGATTTGATGCGAGTGGCTTTACTCAGTATGTGTATAAAAATGCTGCAACCAAATTGGCTATTCCGCGAACGAGTGCCGCACAGTATAAAGTCGGTAAATTTGTTAAACAAAGTGCGTTACAAAGAGGCGATTTAGTGTTTTATGCAACAGGAGCAAAAGGAAAGGTATCCTTTGTGGGAATTTATAATGGAAATGGTACGTTTATTGGTGCCACATCAAAAGGGGTAAAAGTGGTTAAAATGAGTGATAAATATTGGAAAGACCGGTATATAGGGGCTAAGCGAGTCATTAAGTAA", IUPAC.unambiguous_dna) a="AGTCGA" b="GACTAG" for i,v in enumerate([259,277,282,295,299,306]): print(mut[v-1]+a[i]) mut[v-1]=b[i] print(ori.translate()) print(mut.toseq().translate()) def Gthg04369(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[3583975:3585290].translate(to_stop=1) x=genome[0].seq[3583975:3585290].tomutable() print(x.pop(895-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def Gthg01115(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[891404:892205].reverse_complement().translate(to_stop=1) x=genome[0].seq[891404:892205].reverse_complement().tomutable() print(x.pop(421-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) def
(): filepath="Gthg_from_embl_pfamed.gb" genome = list(SeqIO.parse(open(filepath, "rU"), "genbank")) z=genome[0].seq[2885410:2887572].reverse_complement().translate(to_stop=1) x=genome[0].seq[2885410:2887572].reverse_complement().tomutable() print(x.pop(1748-1)) y=x.toseq().translate(to_stop=1) print(z) print(y) print(list(Differ().compare(str(z),str(y)))) print(len(z),len(y)) if __name__ == "main": pass
Gthg03544
identifier_name
header.component.spec.ts
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { TranslateService, TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { HttpModule, Http } from '@angular/http'; import { SharedModule } from '../../shared/shared.module'; import { HeaderComponent } from './header.component'; import { SearchComponent } from './search/search.component'; import { TranslatorService } from '../../core/translator/translator.service'; import { createTranslateLoader } from '../../app.module'; describe('HeaderComponent', () => { let component: HeaderComponent; let fixture: ComponentFixture<HeaderComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ SharedModule, HttpModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [Http] } }) ], providers: [TranslatorService], declarations: [HeaderComponent, SearchComponent] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(HeaderComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
random_line_split
models.ts
import { SelectableItem, LoadableItem } from '../core/classes'; import { Company, CompanyDetail } from './contracts'; import { StorageItem } from './storage/models'; export class CompanyItem extends SelectableItem { private _item : Company; get item() { return this._item; } set item(i : Company) { this._item = i; } constructor(i : Company) { super();
get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } } export class CompanyDetailItem extends LoadableItem { private _item : CompanyDetail; private _storage : StorageItem[]; constructor(i? : CompanyDetail) { super(); if(!!i) { this._item = i; this.checkLoading(); } this.isOpen = false; } checkLoading() { if(!!this._item && !!this._storage) this.isLoading = false; else this.isLoading = true; } get item() { return this._item; } set item(i : CompanyDetail) { this._item = i; this.checkLoading(); } get storage() { return this._storage; } set storage(list : StorageItem[]) { this._storage = list; this.checkLoading(); } private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } }
this._item = i; this.isOpen = false; } private _isOpen : boolean;
random_line_split
models.ts
import { SelectableItem, LoadableItem } from '../core/classes'; import { Company, CompanyDetail } from './contracts'; import { StorageItem } from './storage/models'; export class CompanyItem extends SelectableItem { private _item : Company; get item() { return this._item; } set item(i : Company) { this._item = i; } constructor(i : Company) { super(); this._item = i; this.isOpen = false; } private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } } export class CompanyDetailItem extends LoadableItem { private _item : CompanyDetail; private _storage : StorageItem[]; constructor(i? : CompanyDetail) { super(); if(!!i)
this.isOpen = false; } checkLoading() { if(!!this._item && !!this._storage) this.isLoading = false; else this.isLoading = true; } get item() { return this._item; } set item(i : CompanyDetail) { this._item = i; this.checkLoading(); } get storage() { return this._storage; } set storage(list : StorageItem[]) { this._storage = list; this.checkLoading(); } private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } }
{ this._item = i; this.checkLoading(); }
conditional_block
models.ts
import { SelectableItem, LoadableItem } from '../core/classes'; import { Company, CompanyDetail } from './contracts'; import { StorageItem } from './storage/models'; export class CompanyItem extends SelectableItem { private _item : Company; get item() { return this._item; } set item(i : Company) { this._item = i; } constructor(i : Company)
private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } } export class CompanyDetailItem extends LoadableItem { private _item : CompanyDetail; private _storage : StorageItem[]; constructor(i? : CompanyDetail) { super(); if(!!i) { this._item = i; this.checkLoading(); } this.isOpen = false; } checkLoading() { if(!!this._item && !!this._storage) this.isLoading = false; else this.isLoading = true; } get item() { return this._item; } set item(i : CompanyDetail) { this._item = i; this.checkLoading(); } get storage() { return this._storage; } set storage(list : StorageItem[]) { this._storage = list; this.checkLoading(); } private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } }
{ super(); this._item = i; this.isOpen = false; }
identifier_body
models.ts
import { SelectableItem, LoadableItem } from '../core/classes'; import { Company, CompanyDetail } from './contracts'; import { StorageItem } from './storage/models'; export class CompanyItem extends SelectableItem { private _item : Company; get item() { return this._item; } set item(i : Company) { this._item = i; } constructor(i : Company) { super(); this._item = i; this.isOpen = false; } private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } } export class CompanyDetailItem extends LoadableItem { private _item : CompanyDetail; private _storage : StorageItem[]; constructor(i? : CompanyDetail) { super(); if(!!i) { this._item = i; this.checkLoading(); } this.isOpen = false; }
() { if(!!this._item && !!this._storage) this.isLoading = false; else this.isLoading = true; } get item() { return this._item; } set item(i : CompanyDetail) { this._item = i; this.checkLoading(); } get storage() { return this._storage; } set storage(list : StorageItem[]) { this._storage = list; this.checkLoading(); } private _isOpen : boolean; get isOpen() { return !!this._isOpen; } set isOpen(val : boolean) { this._isOpen = val; } }
checkLoading
identifier_name
category.server.model.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; var mongoosePaginate = require('mongoose-paginate'); /** * Article Schema */ var CategorySchema = new Schema({ created: { type: Date, default: Date.now }, title: { type: String, default: '', trim: true, required: 'Title cannot be blank'
link: { type: String, default: '', trim: true }, sourceImage: { type: String, default: '', trim: true }, sourceName: { type: String, default: '', trim: true }, // items: [{type: Schema.Types.ObjectId,ref: 'Item'}] // user: { // type: Schema.ObjectId, // ref: 'User' // } }); CategorySchema.plugin(mongoosePaginate); mongoose.model('Category', CategorySchema);
},
random_line_split
dialogs.py
# -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*- # -*- coding: UTF-8 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """generic dialogs such as progress, error and about""" import gettext import os import gobject import gtk from flumotion.configure import configure from flumotion.common.errors import AlreadyConnectedError, \ AlreadyConnectingError, ConnectionFailedError, \ ConnectionRefusedError __version__ = "$Rev: 7833 $" _ = gettext.gettext def exceptionHandler(exctype, value, tb): """ Opens a dialog showing an exception in a nice dialog allowing the users to report it directly to trac. @param exctype : The class of the catched exception. @type exctype : type @param value : The exception itself. @type value : exctype @param tb : Contains the full traceback information. @type tb : traceback """ if exctype is KeyboardInterrupt: return from flumotion.extern.exceptiondialog import ExceptionDialog dialog = ExceptionDialog((exctype, value, tb)) response = dialog.run() if response != ExceptionDialog.RESPONSE_BUG: dialog.destroy() return from flumotion.common.bugreporter import BugReporter br = BugReporter() br.submit(dialog.getFilenames(), dialog.getDescription(), dialog.getSummary()) dialog.destroy() class ProgressDialog(gtk.Dialog): def __init__(self, title, message, parent = None): gtk.Dialog.__init__(self, title, parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT) self.label = gtk.Label(message) self.vbox.pack_start(self.label, True, True, 6) self.label.show() self.bar = gtk.ProgressBar() self.bar.show() self.vbox.pack_end(self.bar, True, True, 6) self.active = False self._timeout_id = None self.connect('destroy', self._destroy_cb) def start(self): "Show the dialog and start pulsating." self.active = True self.show() self.bar.pulse() self._timeout_id = gobject.timeout_add(200, self._pulse) def stop(self): "Remove the dialog and stop pulsating." self.active = False if self._timeout_id: gobject.source_remove(self._timeout_id) self._timeout_id = None def message(self, message): "Set the message on the dialog." self.label.set_text(message) def _pulse(self): if not self.active: # we were disabled, so stop pulsating return False self.bar.pulse() return True def _destroy_cb(self, widget): self.stop() class
(gtk.MessageDialog): def __init__(self, message, parent=None, close_on_response=True, secondary_text=None): gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) b = self.action_area.get_children()[0] b.set_name('ok_button') self.message = message if close_on_response: self.connect("response", lambda self, response: self.hide()) # GTK 2.4 does not have format_secondary_text if not hasattr(self, 'format_secondary_text'): self.format_secondary_text = self._format_secondary_text_backport if secondary_text: self.format_secondary_text(secondary_text) def _format_secondary_text_backport(self, secondary_text): self.set_markup('<span weight="bold" size="larger">%s</span>' '\n\n%s' % (self.message, secondary_text)) def run(self): # can't run a recursive mainloop, because that mucks with # twisted's reactor. from twisted.internet import defer deferred = defer.Deferred() def callback(_, response, deferred): self.destroy() deferred.callback(None) self.connect('response', callback, deferred) self.show() return deferred class AboutDialog(gtk.Dialog): def __init__(self, parent=None): gtk.Dialog.__init__(self, _('About Flumotion'), parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.set_has_separator(False) self.set_resizable(False) self.set_border_width(12) self.vbox.set_spacing(6) image = gtk.Image() self.vbox.pack_start(image) image.set_from_file(os.path.join(configure.imagedir, 'flumotion.png')) image.show() version = gtk.Label( '<span size="xx-large"><b>Flumotion %s</b></span>' % configure.version) version.set_selectable(True) self.vbox.pack_start(version) version.set_use_markup(True) version.show() text = _('Flumotion is a streaming media server.\n\n' '© 2004, 2005, 2006, 2007, 2008 Fluendo S.L.') authors = ( 'Johan Dahlin', 'Pedro Gracia Fajardo', 'Arek Korbik', 'Julien Le Goff', 'Xavier Martinez', 'Jordi Massaguer Pla', 'Zaheer Abbas Merali', 'Sébastien Merle', 'Xavier Queralt Mateu', 'Mike Smith', 'Wim Taymans', 'Jan Urbański', 'Thomas Vander Stichele', 'Andy Wingo', ) text += '\n\n<small>' + _('Authors') + ':\n' for author in authors: text += ' %s\n' % author text += '</small>' info = gtk.Label(text) self.vbox.pack_start(info) info.set_use_markup(True) info.set_selectable(True) info.set_justify(gtk.JUSTIFY_FILL) info.set_line_wrap(True) info.show() def showConnectionErrorDialog(failure, info, parent=None): if failure.check(ConnectionRefusedError): title = _('Connection Refused') message = ( _('"%s" refused your connection.\n' 'Check your user name and password and try again.') % (info.host, )) elif failure.check(ConnectionFailedError): title = _('Connection Failed') message = (_("Connection to manager on %s failed (%s).") % (str(info), str(failure.getErrorMessage()))) elif failure.check(AlreadyConnectedError, AlreadyConnectingError): title =_('Already Connected to %s') % (info, ) message = _("You cannot connect twice to the same manager. Try " "disconnecting first.") else: raise AssertionError(failure) dialog = ErrorDialog(title, parent, True, message) return dialog.run()
ErrorDialog
identifier_name
dialogs.py
# -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*- # -*- coding: UTF-8 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """generic dialogs such as progress, error and about""" import gettext import os import gobject import gtk from flumotion.configure import configure from flumotion.common.errors import AlreadyConnectedError, \ AlreadyConnectingError, ConnectionFailedError, \ ConnectionRefusedError __version__ = "$Rev: 7833 $" _ = gettext.gettext def exceptionHandler(exctype, value, tb): """ Opens a dialog showing an exception in a nice dialog allowing the users to report it directly to trac. @param exctype : The class of the catched exception. @type exctype : type @param value : The exception itself. @type value : exctype @param tb : Contains the full traceback information. @type tb : traceback """ if exctype is KeyboardInterrupt: return from flumotion.extern.exceptiondialog import ExceptionDialog dialog = ExceptionDialog((exctype, value, tb)) response = dialog.run() if response != ExceptionDialog.RESPONSE_BUG: dialog.destroy() return from flumotion.common.bugreporter import BugReporter br = BugReporter() br.submit(dialog.getFilenames(), dialog.getDescription(), dialog.getSummary()) dialog.destroy() class ProgressDialog(gtk.Dialog): def __init__(self, title, message, parent = None):
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT) self.label = gtk.Label(message) self.vbox.pack_start(self.label, True, True, 6) self.label.show() self.bar = gtk.ProgressBar() self.bar.show() self.vbox.pack_end(self.bar, True, True, 6) self.active = False self._timeout_id = None self.connect('destroy', self._destroy_cb) def start(self): "Show the dialog and start pulsating." self.active = True self.show() self.bar.pulse() self._timeout_id = gobject.timeout_add(200, self._pulse) def stop(self): "Remove the dialog and stop pulsating." self.active = False if self._timeout_id: gobject.source_remove(self._timeout_id) self._timeout_id = None def message(self, message): "Set the message on the dialog." self.label.set_text(message) def _pulse(self): if not self.active: # we were disabled, so stop pulsating return False self.bar.pulse() return True def _destroy_cb(self, widget): self.stop() class ErrorDialog(gtk.MessageDialog): def __init__(self, message, parent=None, close_on_response=True, secondary_text=None): gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) b = self.action_area.get_children()[0] b.set_name('ok_button') self.message = message if close_on_response: self.connect("response", lambda self, response: self.hide()) # GTK 2.4 does not have format_secondary_text if not hasattr(self, 'format_secondary_text'): self.format_secondary_text = self._format_secondary_text_backport if secondary_text: self.format_secondary_text(secondary_text) def _format_secondary_text_backport(self, secondary_text): self.set_markup('<span weight="bold" size="larger">%s</span>' '\n\n%s' % (self.message, secondary_text)) def run(self): # can't run a recursive mainloop, because that mucks with # twisted's reactor. from twisted.internet import defer deferred = defer.Deferred() def callback(_, response, deferred): self.destroy() deferred.callback(None) self.connect('response', callback, deferred) self.show() return deferred class AboutDialog(gtk.Dialog): def __init__(self, parent=None): gtk.Dialog.__init__(self, _('About Flumotion'), parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.set_has_separator(False) self.set_resizable(False) self.set_border_width(12) self.vbox.set_spacing(6) image = gtk.Image() self.vbox.pack_start(image) image.set_from_file(os.path.join(configure.imagedir, 'flumotion.png')) image.show() version = gtk.Label( '<span size="xx-large"><b>Flumotion %s</b></span>' % configure.version) version.set_selectable(True) self.vbox.pack_start(version) version.set_use_markup(True) version.show() text = _('Flumotion is a streaming media server.\n\n' '© 2004, 2005, 2006, 2007, 2008 Fluendo S.L.') authors = ( 'Johan Dahlin', 'Pedro Gracia Fajardo', 'Arek Korbik', 'Julien Le Goff', 'Xavier Martinez', 'Jordi Massaguer Pla', 'Zaheer Abbas Merali', 'Sébastien Merle', 'Xavier Queralt Mateu', 'Mike Smith', 'Wim Taymans', 'Jan Urbański', 'Thomas Vander Stichele', 'Andy Wingo', ) text += '\n\n<small>' + _('Authors') + ':\n' for author in authors: text += ' %s\n' % author text += '</small>' info = gtk.Label(text) self.vbox.pack_start(info) info.set_use_markup(True) info.set_selectable(True) info.set_justify(gtk.JUSTIFY_FILL) info.set_line_wrap(True) info.show() def showConnectionErrorDialog(failure, info, parent=None): if failure.check(ConnectionRefusedError): title = _('Connection Refused') message = ( _('"%s" refused your connection.\n' 'Check your user name and password and try again.') % (info.host, )) elif failure.check(ConnectionFailedError): title = _('Connection Failed') message = (_("Connection to manager on %s failed (%s).") % (str(info), str(failure.getErrorMessage()))) elif failure.check(AlreadyConnectedError, AlreadyConnectingError): title =_('Already Connected to %s') % (info, ) message = _("You cannot connect twice to the same manager. Try " "disconnecting first.") else: raise AssertionError(failure) dialog = ErrorDialog(title, parent, True, message) return dialog.run()
gtk.Dialog.__init__(self, title, parent,
random_line_split
dialogs.py
# -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*- # -*- coding: UTF-8 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """generic dialogs such as progress, error and about""" import gettext import os import gobject import gtk from flumotion.configure import configure from flumotion.common.errors import AlreadyConnectedError, \ AlreadyConnectingError, ConnectionFailedError, \ ConnectionRefusedError __version__ = "$Rev: 7833 $" _ = gettext.gettext def exceptionHandler(exctype, value, tb): """ Opens a dialog showing an exception in a nice dialog allowing the users to report it directly to trac. @param exctype : The class of the catched exception. @type exctype : type @param value : The exception itself. @type value : exctype @param tb : Contains the full traceback information. @type tb : traceback """ if exctype is KeyboardInterrupt: return from flumotion.extern.exceptiondialog import ExceptionDialog dialog = ExceptionDialog((exctype, value, tb)) response = dialog.run() if response != ExceptionDialog.RESPONSE_BUG: dialog.destroy() return from flumotion.common.bugreporter import BugReporter br = BugReporter() br.submit(dialog.getFilenames(), dialog.getDescription(), dialog.getSummary()) dialog.destroy() class ProgressDialog(gtk.Dialog): def __init__(self, title, message, parent = None): gtk.Dialog.__init__(self, title, parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT) self.label = gtk.Label(message) self.vbox.pack_start(self.label, True, True, 6) self.label.show() self.bar = gtk.ProgressBar() self.bar.show() self.vbox.pack_end(self.bar, True, True, 6) self.active = False self._timeout_id = None self.connect('destroy', self._destroy_cb) def start(self): "Show the dialog and start pulsating." self.active = True self.show() self.bar.pulse() self._timeout_id = gobject.timeout_add(200, self._pulse) def stop(self): "Remove the dialog and stop pulsating." self.active = False if self._timeout_id: gobject.source_remove(self._timeout_id) self._timeout_id = None def message(self, message): "Set the message on the dialog." self.label.set_text(message) def _pulse(self): if not self.active: # we were disabled, so stop pulsating return False self.bar.pulse() return True def _destroy_cb(self, widget): self.stop() class ErrorDialog(gtk.MessageDialog): def __init__(self, message, parent=None, close_on_response=True, secondary_text=None):
def _format_secondary_text_backport(self, secondary_text): self.set_markup('<span weight="bold" size="larger">%s</span>' '\n\n%s' % (self.message, secondary_text)) def run(self): # can't run a recursive mainloop, because that mucks with # twisted's reactor. from twisted.internet import defer deferred = defer.Deferred() def callback(_, response, deferred): self.destroy() deferred.callback(None) self.connect('response', callback, deferred) self.show() return deferred class AboutDialog(gtk.Dialog): def __init__(self, parent=None): gtk.Dialog.__init__(self, _('About Flumotion'), parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.set_has_separator(False) self.set_resizable(False) self.set_border_width(12) self.vbox.set_spacing(6) image = gtk.Image() self.vbox.pack_start(image) image.set_from_file(os.path.join(configure.imagedir, 'flumotion.png')) image.show() version = gtk.Label( '<span size="xx-large"><b>Flumotion %s</b></span>' % configure.version) version.set_selectable(True) self.vbox.pack_start(version) version.set_use_markup(True) version.show() text = _('Flumotion is a streaming media server.\n\n' '© 2004, 2005, 2006, 2007, 2008 Fluendo S.L.') authors = ( 'Johan Dahlin', 'Pedro Gracia Fajardo', 'Arek Korbik', 'Julien Le Goff', 'Xavier Martinez', 'Jordi Massaguer Pla', 'Zaheer Abbas Merali', 'Sébastien Merle', 'Xavier Queralt Mateu', 'Mike Smith', 'Wim Taymans', 'Jan Urbański', 'Thomas Vander Stichele', 'Andy Wingo', ) text += '\n\n<small>' + _('Authors') + ':\n' for author in authors: text += ' %s\n' % author text += '</small>' info = gtk.Label(text) self.vbox.pack_start(info) info.set_use_markup(True) info.set_selectable(True) info.set_justify(gtk.JUSTIFY_FILL) info.set_line_wrap(True) info.show() def showConnectionErrorDialog(failure, info, parent=None): if failure.check(ConnectionRefusedError): title = _('Connection Refused') message = ( _('"%s" refused your connection.\n' 'Check your user name and password and try again.') % (info.host, )) elif failure.check(ConnectionFailedError): title = _('Connection Failed') message = (_("Connection to manager on %s failed (%s).") % (str(info), str(failure.getErrorMessage()))) elif failure.check(AlreadyConnectedError, AlreadyConnectingError): title =_('Already Connected to %s') % (info, ) message = _("You cannot connect twice to the same manager. Try " "disconnecting first.") else: raise AssertionError(failure) dialog = ErrorDialog(title, parent, True, message) return dialog.run()
gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) b = self.action_area.get_children()[0] b.set_name('ok_button') self.message = message if close_on_response: self.connect("response", lambda self, response: self.hide()) # GTK 2.4 does not have format_secondary_text if not hasattr(self, 'format_secondary_text'): self.format_secondary_text = self._format_secondary_text_backport if secondary_text: self.format_secondary_text(secondary_text)
identifier_body
dialogs.py
# -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*- # -*- coding: UTF-8 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """generic dialogs such as progress, error and about""" import gettext import os import gobject import gtk from flumotion.configure import configure from flumotion.common.errors import AlreadyConnectedError, \ AlreadyConnectingError, ConnectionFailedError, \ ConnectionRefusedError __version__ = "$Rev: 7833 $" _ = gettext.gettext def exceptionHandler(exctype, value, tb): """ Opens a dialog showing an exception in a nice dialog allowing the users to report it directly to trac. @param exctype : The class of the catched exception. @type exctype : type @param value : The exception itself. @type value : exctype @param tb : Contains the full traceback information. @type tb : traceback """ if exctype is KeyboardInterrupt: return from flumotion.extern.exceptiondialog import ExceptionDialog dialog = ExceptionDialog((exctype, value, tb)) response = dialog.run() if response != ExceptionDialog.RESPONSE_BUG: dialog.destroy() return from flumotion.common.bugreporter import BugReporter br = BugReporter() br.submit(dialog.getFilenames(), dialog.getDescription(), dialog.getSummary()) dialog.destroy() class ProgressDialog(gtk.Dialog): def __init__(self, title, message, parent = None): gtk.Dialog.__init__(self, title, parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT) self.label = gtk.Label(message) self.vbox.pack_start(self.label, True, True, 6) self.label.show() self.bar = gtk.ProgressBar() self.bar.show() self.vbox.pack_end(self.bar, True, True, 6) self.active = False self._timeout_id = None self.connect('destroy', self._destroy_cb) def start(self): "Show the dialog and start pulsating." self.active = True self.show() self.bar.pulse() self._timeout_id = gobject.timeout_add(200, self._pulse) def stop(self): "Remove the dialog and stop pulsating." self.active = False if self._timeout_id: gobject.source_remove(self._timeout_id) self._timeout_id = None def message(self, message): "Set the message on the dialog." self.label.set_text(message) def _pulse(self): if not self.active: # we were disabled, so stop pulsating return False self.bar.pulse() return True def _destroy_cb(self, widget): self.stop() class ErrorDialog(gtk.MessageDialog): def __init__(self, message, parent=None, close_on_response=True, secondary_text=None): gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message) b = self.action_area.get_children()[0] b.set_name('ok_button') self.message = message if close_on_response: self.connect("response", lambda self, response: self.hide()) # GTK 2.4 does not have format_secondary_text if not hasattr(self, 'format_secondary_text'): self.format_secondary_text = self._format_secondary_text_backport if secondary_text: self.format_secondary_text(secondary_text) def _format_secondary_text_backport(self, secondary_text): self.set_markup('<span weight="bold" size="larger">%s</span>' '\n\n%s' % (self.message, secondary_text)) def run(self): # can't run a recursive mainloop, because that mucks with # twisted's reactor. from twisted.internet import defer deferred = defer.Deferred() def callback(_, response, deferred): self.destroy() deferred.callback(None) self.connect('response', callback, deferred) self.show() return deferred class AboutDialog(gtk.Dialog): def __init__(self, parent=None): gtk.Dialog.__init__(self, _('About Flumotion'), parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.set_has_separator(False) self.set_resizable(False) self.set_border_width(12) self.vbox.set_spacing(6) image = gtk.Image() self.vbox.pack_start(image) image.set_from_file(os.path.join(configure.imagedir, 'flumotion.png')) image.show() version = gtk.Label( '<span size="xx-large"><b>Flumotion %s</b></span>' % configure.version) version.set_selectable(True) self.vbox.pack_start(version) version.set_use_markup(True) version.show() text = _('Flumotion is a streaming media server.\n\n' '© 2004, 2005, 2006, 2007, 2008 Fluendo S.L.') authors = ( 'Johan Dahlin', 'Pedro Gracia Fajardo', 'Arek Korbik', 'Julien Le Goff', 'Xavier Martinez', 'Jordi Massaguer Pla', 'Zaheer Abbas Merali', 'Sébastien Merle', 'Xavier Queralt Mateu', 'Mike Smith', 'Wim Taymans', 'Jan Urbański', 'Thomas Vander Stichele', 'Andy Wingo', ) text += '\n\n<small>' + _('Authors') + ':\n' for author in authors: tex
text += '</small>' info = gtk.Label(text) self.vbox.pack_start(info) info.set_use_markup(True) info.set_selectable(True) info.set_justify(gtk.JUSTIFY_FILL) info.set_line_wrap(True) info.show() def showConnectionErrorDialog(failure, info, parent=None): if failure.check(ConnectionRefusedError): title = _('Connection Refused') message = ( _('"%s" refused your connection.\n' 'Check your user name and password and try again.') % (info.host, )) elif failure.check(ConnectionFailedError): title = _('Connection Failed') message = (_("Connection to manager on %s failed (%s).") % (str(info), str(failure.getErrorMessage()))) elif failure.check(AlreadyConnectedError, AlreadyConnectingError): title =_('Already Connected to %s') % (info, ) message = _("You cannot connect twice to the same manager. Try " "disconnecting first.") else: raise AssertionError(failure) dialog = ErrorDialog(title, parent, True, message) return dialog.run()
t += ' %s\n' % author
conditional_block
borrowck-preserve-box-in-discr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_POISON_ON_FREE=1 use std::ptr;
@F {f: ref b_x} => { assert_eq!(**b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); assert_eq!(**b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x))); } } }
struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; match x {
random_line_split
borrowck-preserve-box-in-discr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_POISON_ON_FREE=1 use std::ptr; struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; match x { @F {f: ref b_x} =>
} }
{ assert_eq!(**b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); assert_eq!(**b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x))); }
conditional_block
borrowck-preserve-box-in-discr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // exec-env:RUST_POISON_ON_FREE=1 use std::ptr; struct F { f: ~int } pub fn
() { let mut x = @F {f: ~3}; match x { @F {f: ref b_x} => { assert_eq!(**b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); assert_eq!(**b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x))); } } }
main
identifier_name
3da51a88205a_ckan_api_key_constraint.py
"""ckan api key constraint Revision ID: 3da51a88205a Revises: 46c3f68e950a Create Date: 2014-04-01 11:33:01.394220 """ # revision identifiers, used by Alembic. revision = '3da51a88205a' down_revision = '46c3f68e950a' from alembic import op import sqlalchemy as sa def upgrade():
def downgrade(): op.drop_constraint('ckan_api_uq', 'user')
query = '''UPDATE "user" SET ckan_api=null WHERE id IN (SELECT id FROM (SELECT id, row_number() over (partition BY ckan_api ORDER BY id) AS rnum FROM "user") t WHERE t.rnum > 1); ''' op.execute(query) op.create_unique_constraint('ckan_api_uq', 'user', ['ckan_api'])
identifier_body
3da51a88205a_ckan_api_key_constraint.py
"""ckan api key constraint Revision ID: 3da51a88205a Revises: 46c3f68e950a Create Date: 2014-04-01 11:33:01.394220 """ # revision identifiers, used by Alembic. revision = '3da51a88205a' down_revision = '46c3f68e950a' from alembic import op import sqlalchemy as sa def
(): query = '''UPDATE "user" SET ckan_api=null WHERE id IN (SELECT id FROM (SELECT id, row_number() over (partition BY ckan_api ORDER BY id) AS rnum FROM "user") t WHERE t.rnum > 1); ''' op.execute(query) op.create_unique_constraint('ckan_api_uq', 'user', ['ckan_api']) def downgrade(): op.drop_constraint('ckan_api_uq', 'user')
upgrade
identifier_name
3da51a88205a_ckan_api_key_constraint.py
"""ckan api key constraint Revision ID: 3da51a88205a Revises: 46c3f68e950a Create Date: 2014-04-01 11:33:01.394220 """ # revision identifiers, used by Alembic. revision = '3da51a88205a' down_revision = '46c3f68e950a' from alembic import op import sqlalchemy as sa def upgrade(): query = '''UPDATE "user" SET ckan_api=null WHERE id IN (SELECT id FROM (SELECT id, row_number() over (partition BY ckan_api ORDER BY id) AS rnum
def downgrade(): op.drop_constraint('ckan_api_uq', 'user')
FROM "user") t WHERE t.rnum > 1); ''' op.execute(query) op.create_unique_constraint('ckan_api_uq', 'user', ['ckan_api'])
random_line_split
state.rs
use specs::{Component, VecStorage}; use specs_derive::*; use super::intent::{AttackType, DefendType, XAxis, YAxis}; use super::Facing; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum HitType { Chopped, Sliced, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Action { Idle, Move { x: XAxis, y: YAxis }, Attack(AttackType), AttackRecovery, Defend(DefendType), Hit(HitType), Death(String), Dead, Entrance, } impl Action { pub fn is_attack(&self) -> bool { if let Action::Attack(..) = self { true } else { false } } pub fn is_throw_dagger(&self) -> bool { if let Action::Attack(AttackType::ThrowDagger) = self { true } else { false } } } impl Default for Action { fn default() -> Action { Action::Entrance } } #[derive(Component, Clone, Debug, Default)] #[storage(VecStorage)] pub struct State { pub action: Action,
pub direction: Facing, pub length: u32, pub ticks: u32, }
random_line_split
state.rs
use specs::{Component, VecStorage}; use specs_derive::*; use super::intent::{AttackType, DefendType, XAxis, YAxis}; use super::Facing; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum
{ Chopped, Sliced, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Action { Idle, Move { x: XAxis, y: YAxis }, Attack(AttackType), AttackRecovery, Defend(DefendType), Hit(HitType), Death(String), Dead, Entrance, } impl Action { pub fn is_attack(&self) -> bool { if let Action::Attack(..) = self { true } else { false } } pub fn is_throw_dagger(&self) -> bool { if let Action::Attack(AttackType::ThrowDagger) = self { true } else { false } } } impl Default for Action { fn default() -> Action { Action::Entrance } } #[derive(Component, Clone, Debug, Default)] #[storage(VecStorage)] pub struct State { pub action: Action, pub direction: Facing, pub length: u32, pub ticks: u32, }
HitType
identifier_name
state.rs
use specs::{Component, VecStorage}; use specs_derive::*; use super::intent::{AttackType, DefendType, XAxis, YAxis}; use super::Facing; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum HitType { Chopped, Sliced, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Action { Idle, Move { x: XAxis, y: YAxis }, Attack(AttackType), AttackRecovery, Defend(DefendType), Hit(HitType), Death(String), Dead, Entrance, } impl Action { pub fn is_attack(&self) -> bool { if let Action::Attack(..) = self
else { false } } pub fn is_throw_dagger(&self) -> bool { if let Action::Attack(AttackType::ThrowDagger) = self { true } else { false } } } impl Default for Action { fn default() -> Action { Action::Entrance } } #[derive(Component, Clone, Debug, Default)] #[storage(VecStorage)] pub struct State { pub action: Action, pub direction: Facing, pub length: u32, pub ticks: u32, }
{ true }
conditional_block
eclipse_gen.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import pkgutil from collections import defaultdict from twitter.common.collections import OrderedSet from pants.backend.jvm.tasks.ide_gen import IdeGen from pants.base.build_environment import get_buildroot from pants.base.generator import Generator, TemplateData from pants.util.dirutil import safe_delete, safe_mkdir, safe_open _TEMPLATE_BASEDIR = os.path.join('templates', 'eclipse') _VERSIONS = { '3.5': '3.7', # 3.5-3.7 are .project/.classpath compatible '3.6': '3.7', '3.7': '3.7', } _SETTINGS = ( 'org.eclipse.core.resources.prefs', 'org.eclipse.jdt.ui.prefs', ) class
(IdeGen): @classmethod def register_options(cls, register): super(EclipseGen, cls).register_options(register) register('--version', choices=sorted(list(_VERSIONS.keys())), default='3.6', help='The Eclipse version the project configuration should be generated for.') def __init__(self, *args, **kwargs): super(EclipseGen, self).__init__(*args, **kwargs) version = _VERSIONS[self.get_options().version] self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mustache' % version) self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mustache' % version) self.apt_template = os.path.join(_TEMPLATE_BASEDIR, 'factorypath-%s.mustache' % version) self.pydev_template = os.path.join(_TEMPLATE_BASEDIR, 'pydevproject-%s.mustache' % version) self.debug_template = os.path.join(_TEMPLATE_BASEDIR, 'debug-launcher-%s.mustache' % version) self.coreprefs_template = os.path.join(_TEMPLATE_BASEDIR, 'org.eclipse.jdt.core.prefs-%s.mustache' % version) self.project_filename = os.path.join(self.cwd, '.project') self.classpath_filename = os.path.join(self.cwd, '.classpath') self.apt_filename = os.path.join(self.cwd, '.factorypath') self.pydev_filename = os.path.join(self.cwd, '.pydevproject') self.coreprefs_filename = os.path.join(self.cwd, '.settings', 'org.eclipse.jdt.core.prefs') def generate_project(self, project): def linked_folder_id(source_set): return source_set.source_base.replace(os.path.sep, '.') def base_path(source_set): return os.path.join(source_set.root_dir, source_set.source_base) def create_source_base_template(source_set): source_base = base_path(source_set) return source_base, TemplateData( id=linked_folder_id(source_set), path=source_base ) source_bases = dict(map(create_source_base_template, project.sources)) if project.has_python: source_bases.update(map(create_source_base_template, project.py_sources)) source_bases.update(map(create_source_base_template, project.py_libs)) def create_source_template(base_id, includes=None, excludes=None): return TemplateData( base=base_id, includes='|'.join(OrderedSet(includes)) if includes else None, excludes='|'.join(OrderedSet(excludes)) if excludes else None, ) def create_sourcepath(base_id, sources): def normalize_path_pattern(path): return '%s/' % path if not path.endswith('/') else path includes = [normalize_path_pattern(src_set.path) for src_set in sources if src_set.path] excludes = [] for source_set in sources: excludes.extend(normalize_path_pattern(exclude) for exclude in source_set.excludes) return create_source_template(base_id, includes, excludes) pythonpaths = [] if project.has_python: for source_set in project.py_sources: pythonpaths.append(create_source_template(linked_folder_id(source_set))) for source_set in project.py_libs: lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path pythonpaths.append(create_source_template(linked_folder_id(source_set), includes=[lib_path])) configured_project = TemplateData( name=self.project_name, java=TemplateData( jdk=self.java_jdk, language_level=('1.%d' % self.java_language_level) ), python=project.has_python, scala=project.has_scala and not project.skip_scala, source_bases=source_bases.values(), pythonpaths=pythonpaths, debug_port=project.debug_port, ) outdir = os.path.abspath(os.path.join(self.gen_project_workdir, 'bin')) safe_mkdir(outdir) source_sets = defaultdict(OrderedSet) # base_id -> source_set for source_set in project.sources: source_sets[linked_folder_id(source_set)].add(source_set) sourcepaths = [create_sourcepath(base_id, sources) for base_id, sources in source_sets.items()] libs = list(project.internal_jars) libs.extend(project.external_jars) configured_classpath = TemplateData( sourcepaths=sourcepaths, has_tests=project.has_tests, libs=libs, scala=project.has_scala, # Eclipse insists the outdir be a relative path unlike other paths outdir=os.path.relpath(outdir, get_buildroot()), ) def apply_template(output_path, template_relpath, **template_data): with safe_open(output_path, 'w') as output: Generator(pkgutil.get_data(__name__, template_relpath), **template_data).write(output) apply_template(self.project_filename, self.project_template, project=configured_project) apply_template(self.classpath_filename, self.classpath_template, classpath=configured_classpath) apply_template(os.path.join(self.gen_project_workdir, 'Debug on port %d.launch' % project.debug_port), self.debug_template, project=configured_project) apply_template(self.coreprefs_filename, self.coreprefs_template, project=configured_project) for resource in _SETTINGS: with safe_open(os.path.join(self.cwd, '.settings', resource), 'w') as prefs: prefs.write(pkgutil.get_data(__name__, os.path.join(_TEMPLATE_BASEDIR, resource))) factorypath = TemplateData( project_name=self.project_name, # The easiest way to make sure eclipse sees all annotation processors is to put all libs on # the apt factorypath - this does not seem to hurt eclipse performance in any noticeable way. jarpaths=libs ) apply_template(self.apt_filename, self.apt_template, factorypath=factorypath) if project.has_python: apply_template(self.pydev_filename, self.pydev_template, project=configured_project) else: safe_delete(self.pydev_filename) print('\nGenerated project at %s%s' % (self.gen_project_workdir, os.sep))
EclipseGen
identifier_name
eclipse_gen.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import pkgutil from collections import defaultdict from twitter.common.collections import OrderedSet from pants.backend.jvm.tasks.ide_gen import IdeGen from pants.base.build_environment import get_buildroot from pants.base.generator import Generator, TemplateData from pants.util.dirutil import safe_delete, safe_mkdir, safe_open _TEMPLATE_BASEDIR = os.path.join('templates', 'eclipse') _VERSIONS = { '3.5': '3.7', # 3.5-3.7 are .project/.classpath compatible '3.6': '3.7', '3.7': '3.7', } _SETTINGS = ( 'org.eclipse.core.resources.prefs', 'org.eclipse.jdt.ui.prefs', ) class EclipseGen(IdeGen): @classmethod def register_options(cls, register): super(EclipseGen, cls).register_options(register) register('--version', choices=sorted(list(_VERSIONS.keys())), default='3.6', help='The Eclipse version the project configuration should be generated for.') def __init__(self, *args, **kwargs): super(EclipseGen, self).__init__(*args, **kwargs) version = _VERSIONS[self.get_options().version] self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mustache' % version) self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mustache' % version) self.apt_template = os.path.join(_TEMPLATE_BASEDIR, 'factorypath-%s.mustache' % version) self.pydev_template = os.path.join(_TEMPLATE_BASEDIR, 'pydevproject-%s.mustache' % version) self.debug_template = os.path.join(_TEMPLATE_BASEDIR, 'debug-launcher-%s.mustache' % version) self.coreprefs_template = os.path.join(_TEMPLATE_BASEDIR, 'org.eclipse.jdt.core.prefs-%s.mustache' % version) self.project_filename = os.path.join(self.cwd, '.project') self.classpath_filename = os.path.join(self.cwd, '.classpath') self.apt_filename = os.path.join(self.cwd, '.factorypath') self.pydev_filename = os.path.join(self.cwd, '.pydevproject') self.coreprefs_filename = os.path.join(self.cwd, '.settings', 'org.eclipse.jdt.core.prefs') def generate_project(self, project): def linked_folder_id(source_set): return source_set.source_base.replace(os.path.sep, '.') def base_path(source_set): return os.path.join(source_set.root_dir, source_set.source_base) def create_source_base_template(source_set): source_base = base_path(source_set) return source_base, TemplateData( id=linked_folder_id(source_set), path=source_base ) source_bases = dict(map(create_source_base_template, project.sources)) if project.has_python: source_bases.update(map(create_source_base_template, project.py_sources)) source_bases.update(map(create_source_base_template, project.py_libs)) def create_source_template(base_id, includes=None, excludes=None): return TemplateData( base=base_id, includes='|'.join(OrderedSet(includes)) if includes else None, excludes='|'.join(OrderedSet(excludes)) if excludes else None, ) def create_sourcepath(base_id, sources): def normalize_path_pattern(path): return '%s/' % path if not path.endswith('/') else path includes = [normalize_path_pattern(src_set.path) for src_set in sources if src_set.path] excludes = [] for source_set in sources: excludes.extend(normalize_path_pattern(exclude) for exclude in source_set.excludes) return create_source_template(base_id, includes, excludes) pythonpaths = [] if project.has_python:
configured_project = TemplateData( name=self.project_name, java=TemplateData( jdk=self.java_jdk, language_level=('1.%d' % self.java_language_level) ), python=project.has_python, scala=project.has_scala and not project.skip_scala, source_bases=source_bases.values(), pythonpaths=pythonpaths, debug_port=project.debug_port, ) outdir = os.path.abspath(os.path.join(self.gen_project_workdir, 'bin')) safe_mkdir(outdir) source_sets = defaultdict(OrderedSet) # base_id -> source_set for source_set in project.sources: source_sets[linked_folder_id(source_set)].add(source_set) sourcepaths = [create_sourcepath(base_id, sources) for base_id, sources in source_sets.items()] libs = list(project.internal_jars) libs.extend(project.external_jars) configured_classpath = TemplateData( sourcepaths=sourcepaths, has_tests=project.has_tests, libs=libs, scala=project.has_scala, # Eclipse insists the outdir be a relative path unlike other paths outdir=os.path.relpath(outdir, get_buildroot()), ) def apply_template(output_path, template_relpath, **template_data): with safe_open(output_path, 'w') as output: Generator(pkgutil.get_data(__name__, template_relpath), **template_data).write(output) apply_template(self.project_filename, self.project_template, project=configured_project) apply_template(self.classpath_filename, self.classpath_template, classpath=configured_classpath) apply_template(os.path.join(self.gen_project_workdir, 'Debug on port %d.launch' % project.debug_port), self.debug_template, project=configured_project) apply_template(self.coreprefs_filename, self.coreprefs_template, project=configured_project) for resource in _SETTINGS: with safe_open(os.path.join(self.cwd, '.settings', resource), 'w') as prefs: prefs.write(pkgutil.get_data(__name__, os.path.join(_TEMPLATE_BASEDIR, resource))) factorypath = TemplateData( project_name=self.project_name, # The easiest way to make sure eclipse sees all annotation processors is to put all libs on # the apt factorypath - this does not seem to hurt eclipse performance in any noticeable way. jarpaths=libs ) apply_template(self.apt_filename, self.apt_template, factorypath=factorypath) if project.has_python: apply_template(self.pydev_filename, self.pydev_template, project=configured_project) else: safe_delete(self.pydev_filename) print('\nGenerated project at %s%s' % (self.gen_project_workdir, os.sep))
for source_set in project.py_sources: pythonpaths.append(create_source_template(linked_folder_id(source_set))) for source_set in project.py_libs: lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path pythonpaths.append(create_source_template(linked_folder_id(source_set), includes=[lib_path]))
conditional_block
eclipse_gen.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import pkgutil from collections import defaultdict from twitter.common.collections import OrderedSet from pants.backend.jvm.tasks.ide_gen import IdeGen from pants.base.build_environment import get_buildroot from pants.base.generator import Generator, TemplateData from pants.util.dirutil import safe_delete, safe_mkdir, safe_open _TEMPLATE_BASEDIR = os.path.join('templates', 'eclipse') _VERSIONS = { '3.5': '3.7', # 3.5-3.7 are .project/.classpath compatible '3.6': '3.7', '3.7': '3.7', } _SETTINGS = ( 'org.eclipse.core.resources.prefs', 'org.eclipse.jdt.ui.prefs', ) class EclipseGen(IdeGen): @classmethod def register_options(cls, register): super(EclipseGen, cls).register_options(register) register('--version', choices=sorted(list(_VERSIONS.keys())), default='3.6', help='The Eclipse version the project configuration should be generated for.') def __init__(self, *args, **kwargs): super(EclipseGen, self).__init__(*args, **kwargs) version = _VERSIONS[self.get_options().version] self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mustache' % version) self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mustache' % version) self.apt_template = os.path.join(_TEMPLATE_BASEDIR, 'factorypath-%s.mustache' % version) self.pydev_template = os.path.join(_TEMPLATE_BASEDIR, 'pydevproject-%s.mustache' % version) self.debug_template = os.path.join(_TEMPLATE_BASEDIR, 'debug-launcher-%s.mustache' % version) self.coreprefs_template = os.path.join(_TEMPLATE_BASEDIR, 'org.eclipse.jdt.core.prefs-%s.mustache' % version) self.project_filename = os.path.join(self.cwd, '.project') self.classpath_filename = os.path.join(self.cwd, '.classpath') self.apt_filename = os.path.join(self.cwd, '.factorypath') self.pydev_filename = os.path.join(self.cwd, '.pydevproject') self.coreprefs_filename = os.path.join(self.cwd, '.settings', 'org.eclipse.jdt.core.prefs') def generate_project(self, project): def linked_folder_id(source_set): return source_set.source_base.replace(os.path.sep, '.') def base_path(source_set): return os.path.join(source_set.root_dir, source_set.source_base) def create_source_base_template(source_set): source_base = base_path(source_set) return source_base, TemplateData( id=linked_folder_id(source_set), path=source_base ) source_bases = dict(map(create_source_base_template, project.sources)) if project.has_python: source_bases.update(map(create_source_base_template, project.py_sources)) source_bases.update(map(create_source_base_template, project.py_libs)) def create_source_template(base_id, includes=None, excludes=None): return TemplateData( base=base_id, includes='|'.join(OrderedSet(includes)) if includes else None, excludes='|'.join(OrderedSet(excludes)) if excludes else None, ) def create_sourcepath(base_id, sources): def normalize_path_pattern(path): return '%s/' % path if not path.endswith('/') else path includes = [normalize_path_pattern(src_set.path) for src_set in sources if src_set.path] excludes = [] for source_set in sources: excludes.extend(normalize_path_pattern(exclude) for exclude in source_set.excludes) return create_source_template(base_id, includes, excludes) pythonpaths = [] if project.has_python: for source_set in project.py_sources: pythonpaths.append(create_source_template(linked_folder_id(source_set))) for source_set in project.py_libs: lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path pythonpaths.append(create_source_template(linked_folder_id(source_set), includes=[lib_path]))
language_level=('1.%d' % self.java_language_level) ), python=project.has_python, scala=project.has_scala and not project.skip_scala, source_bases=source_bases.values(), pythonpaths=pythonpaths, debug_port=project.debug_port, ) outdir = os.path.abspath(os.path.join(self.gen_project_workdir, 'bin')) safe_mkdir(outdir) source_sets = defaultdict(OrderedSet) # base_id -> source_set for source_set in project.sources: source_sets[linked_folder_id(source_set)].add(source_set) sourcepaths = [create_sourcepath(base_id, sources) for base_id, sources in source_sets.items()] libs = list(project.internal_jars) libs.extend(project.external_jars) configured_classpath = TemplateData( sourcepaths=sourcepaths, has_tests=project.has_tests, libs=libs, scala=project.has_scala, # Eclipse insists the outdir be a relative path unlike other paths outdir=os.path.relpath(outdir, get_buildroot()), ) def apply_template(output_path, template_relpath, **template_data): with safe_open(output_path, 'w') as output: Generator(pkgutil.get_data(__name__, template_relpath), **template_data).write(output) apply_template(self.project_filename, self.project_template, project=configured_project) apply_template(self.classpath_filename, self.classpath_template, classpath=configured_classpath) apply_template(os.path.join(self.gen_project_workdir, 'Debug on port %d.launch' % project.debug_port), self.debug_template, project=configured_project) apply_template(self.coreprefs_filename, self.coreprefs_template, project=configured_project) for resource in _SETTINGS: with safe_open(os.path.join(self.cwd, '.settings', resource), 'w') as prefs: prefs.write(pkgutil.get_data(__name__, os.path.join(_TEMPLATE_BASEDIR, resource))) factorypath = TemplateData( project_name=self.project_name, # The easiest way to make sure eclipse sees all annotation processors is to put all libs on # the apt factorypath - this does not seem to hurt eclipse performance in any noticeable way. jarpaths=libs ) apply_template(self.apt_filename, self.apt_template, factorypath=factorypath) if project.has_python: apply_template(self.pydev_filename, self.pydev_template, project=configured_project) else: safe_delete(self.pydev_filename) print('\nGenerated project at %s%s' % (self.gen_project_workdir, os.sep))
configured_project = TemplateData( name=self.project_name, java=TemplateData( jdk=self.java_jdk,
random_line_split
eclipse_gen.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import pkgutil from collections import defaultdict from twitter.common.collections import OrderedSet from pants.backend.jvm.tasks.ide_gen import IdeGen from pants.base.build_environment import get_buildroot from pants.base.generator import Generator, TemplateData from pants.util.dirutil import safe_delete, safe_mkdir, safe_open _TEMPLATE_BASEDIR = os.path.join('templates', 'eclipse') _VERSIONS = { '3.5': '3.7', # 3.5-3.7 are .project/.classpath compatible '3.6': '3.7', '3.7': '3.7', } _SETTINGS = ( 'org.eclipse.core.resources.prefs', 'org.eclipse.jdt.ui.prefs', ) class EclipseGen(IdeGen): @classmethod def register_options(cls, register): super(EclipseGen, cls).register_options(register) register('--version', choices=sorted(list(_VERSIONS.keys())), default='3.6', help='The Eclipse version the project configuration should be generated for.') def __init__(self, *args, **kwargs):
def generate_project(self, project): def linked_folder_id(source_set): return source_set.source_base.replace(os.path.sep, '.') def base_path(source_set): return os.path.join(source_set.root_dir, source_set.source_base) def create_source_base_template(source_set): source_base = base_path(source_set) return source_base, TemplateData( id=linked_folder_id(source_set), path=source_base ) source_bases = dict(map(create_source_base_template, project.sources)) if project.has_python: source_bases.update(map(create_source_base_template, project.py_sources)) source_bases.update(map(create_source_base_template, project.py_libs)) def create_source_template(base_id, includes=None, excludes=None): return TemplateData( base=base_id, includes='|'.join(OrderedSet(includes)) if includes else None, excludes='|'.join(OrderedSet(excludes)) if excludes else None, ) def create_sourcepath(base_id, sources): def normalize_path_pattern(path): return '%s/' % path if not path.endswith('/') else path includes = [normalize_path_pattern(src_set.path) for src_set in sources if src_set.path] excludes = [] for source_set in sources: excludes.extend(normalize_path_pattern(exclude) for exclude in source_set.excludes) return create_source_template(base_id, includes, excludes) pythonpaths = [] if project.has_python: for source_set in project.py_sources: pythonpaths.append(create_source_template(linked_folder_id(source_set))) for source_set in project.py_libs: lib_path = source_set.path if source_set.path.endswith('.egg') else '%s/' % source_set.path pythonpaths.append(create_source_template(linked_folder_id(source_set), includes=[lib_path])) configured_project = TemplateData( name=self.project_name, java=TemplateData( jdk=self.java_jdk, language_level=('1.%d' % self.java_language_level) ), python=project.has_python, scala=project.has_scala and not project.skip_scala, source_bases=source_bases.values(), pythonpaths=pythonpaths, debug_port=project.debug_port, ) outdir = os.path.abspath(os.path.join(self.gen_project_workdir, 'bin')) safe_mkdir(outdir) source_sets = defaultdict(OrderedSet) # base_id -> source_set for source_set in project.sources: source_sets[linked_folder_id(source_set)].add(source_set) sourcepaths = [create_sourcepath(base_id, sources) for base_id, sources in source_sets.items()] libs = list(project.internal_jars) libs.extend(project.external_jars) configured_classpath = TemplateData( sourcepaths=sourcepaths, has_tests=project.has_tests, libs=libs, scala=project.has_scala, # Eclipse insists the outdir be a relative path unlike other paths outdir=os.path.relpath(outdir, get_buildroot()), ) def apply_template(output_path, template_relpath, **template_data): with safe_open(output_path, 'w') as output: Generator(pkgutil.get_data(__name__, template_relpath), **template_data).write(output) apply_template(self.project_filename, self.project_template, project=configured_project) apply_template(self.classpath_filename, self.classpath_template, classpath=configured_classpath) apply_template(os.path.join(self.gen_project_workdir, 'Debug on port %d.launch' % project.debug_port), self.debug_template, project=configured_project) apply_template(self.coreprefs_filename, self.coreprefs_template, project=configured_project) for resource in _SETTINGS: with safe_open(os.path.join(self.cwd, '.settings', resource), 'w') as prefs: prefs.write(pkgutil.get_data(__name__, os.path.join(_TEMPLATE_BASEDIR, resource))) factorypath = TemplateData( project_name=self.project_name, # The easiest way to make sure eclipse sees all annotation processors is to put all libs on # the apt factorypath - this does not seem to hurt eclipse performance in any noticeable way. jarpaths=libs ) apply_template(self.apt_filename, self.apt_template, factorypath=factorypath) if project.has_python: apply_template(self.pydev_filename, self.pydev_template, project=configured_project) else: safe_delete(self.pydev_filename) print('\nGenerated project at %s%s' % (self.gen_project_workdir, os.sep))
super(EclipseGen, self).__init__(*args, **kwargs) version = _VERSIONS[self.get_options().version] self.project_template = os.path.join(_TEMPLATE_BASEDIR, 'project-%s.mustache' % version) self.classpath_template = os.path.join(_TEMPLATE_BASEDIR, 'classpath-%s.mustache' % version) self.apt_template = os.path.join(_TEMPLATE_BASEDIR, 'factorypath-%s.mustache' % version) self.pydev_template = os.path.join(_TEMPLATE_BASEDIR, 'pydevproject-%s.mustache' % version) self.debug_template = os.path.join(_TEMPLATE_BASEDIR, 'debug-launcher-%s.mustache' % version) self.coreprefs_template = os.path.join(_TEMPLATE_BASEDIR, 'org.eclipse.jdt.core.prefs-%s.mustache' % version) self.project_filename = os.path.join(self.cwd, '.project') self.classpath_filename = os.path.join(self.cwd, '.classpath') self.apt_filename = os.path.join(self.cwd, '.factorypath') self.pydev_filename = os.path.join(self.cwd, '.pydevproject') self.coreprefs_filename = os.path.join(self.cwd, '.settings', 'org.eclipse.jdt.core.prefs')
identifier_body
play.service.spec.ts
import { PlayService } from './play.service'; describe('Play Service', () => { let playService: PlayService; let mockedSeed: any; beforeAll(() => { playService = new PlayService(); mockedSeed = [ [ { coordinates: {x: 0, y: 0}, isAlive: false }, { coordinates: {x: 0, y: 1}, isAlive: true }, { coordinates: {x: 0, y: 2}, isAlive: false } ], [ { coordinates: {x: 1, y: 0}, isAlive: false }, { coordinates: {x: 1, y: 1}, isAlive: true }, { coordinates: {x: 1, y: 2}, isAlive: false } ], [ { coordinates: {x: 2, y: 0}, isAlive: false }, { coordinates: {x: 2, y: 1}, isAlive: true }, { coordinates: {x: 2, y: 2}, isAlive: false } ] ]; }); it('should initialize the seed to defined value', () => { expect(playService.getSeed()).toBeDefined(); }); it('should initialize the prev gen seed to undefined value', () => { expect(playService.getPreviousGenSeed()).toBeUndefined(); }); it('should initialize ticker to undefined value', () => { expect(playService.ticker).toBeUndefined(); }); it('should initialize tickerspeed to 500 value', () => { expect(playService.getTickSpeed()).toEqual(500); }); it('should follow Conway\'s Game Of Rules', () => { playService.setSeed(mockedSeed); playService.setPreviousGenSeed(mockedSeed); playService.processNextGen(); playService.getSeed().forEach(row => { row.forEach(cell => { if ((cell.coordinates.y >= 0 && cell.coordinates.y <= 2) && cell.coordinates.x === 1)
}); }); }); });
{ expect(cell.isAlive).toBeTruthy(); }
conditional_block
play.service.spec.ts
import { PlayService } from './play.service'; describe('Play Service', () => { let playService: PlayService; let mockedSeed: any; beforeAll(() => { playService = new PlayService(); mockedSeed = [ [ { coordinates: {x: 0, y: 0}, isAlive: false }, { coordinates: {x: 0, y: 1}, isAlive: true }, { coordinates: {x: 0, y: 2}, isAlive: false } ], [ { coordinates: {x: 1, y: 0}, isAlive: false }, { coordinates: {x: 1, y: 1}, isAlive: true }, { coordinates: {x: 1, y: 2}, isAlive: false } ], [ { coordinates: {x: 2, y: 0}, isAlive: false }, { coordinates: {x: 2, y: 1}, isAlive: true }, { coordinates: {x: 2, y: 2}, isAlive: false } ] ]; }); it('should initialize the seed to defined value', () => { expect(playService.getSeed()).toBeDefined(); }); it('should initialize the prev gen seed to undefined value', () => { expect(playService.getPreviousGenSeed()).toBeUndefined(); }); it('should initialize ticker to undefined value', () => { expect(playService.ticker).toBeUndefined(); }); it('should initialize tickerspeed to 500 value', () => { expect(playService.getTickSpeed()).toEqual(500); }); it('should follow Conway\'s Game Of Rules', () => { playService.setSeed(mockedSeed); playService.setPreviousGenSeed(mockedSeed); playService.processNextGen();
playService.getSeed().forEach(row => { row.forEach(cell => { if ((cell.coordinates.y >= 0 && cell.coordinates.y <= 2) && cell.coordinates.x === 1) { expect(cell.isAlive).toBeTruthy(); } }); }); }); });
random_line_split
regions-variance-contravariant-use-contravariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a type which is contravariant with respect to its region // parameter compiles successfully when used in a contravariant way. // // Note: see compile-fail/variance-regions-*.rs for the tests that check that the // variance inference works in the first place. struct Contravariant<'a> { f: &'a int }
// if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b int, c: Contravariant<'b>) { } } pub fn main() {}
fn use_<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true
random_line_split
regions-variance-contravariant-use-contravariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a type which is contravariant with respect to its region // parameter compiles successfully when used in a contravariant way. // // Note: see compile-fail/variance-regions-*.rs for the tests that check that the // variance inference works in the first place. struct Contravariant<'a> { f: &'a int } fn
<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true // if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b int, c: Contravariant<'b>) { } } pub fn main() {}
use_
identifier_name
regions-variance-contravariant-use-contravariant.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that a type which is contravariant with respect to its region // parameter compiles successfully when used in a contravariant way. // // Note: see compile-fail/variance-regions-*.rs for the tests that check that the // variance inference works in the first place. struct Contravariant<'a> { f: &'a int } fn use_<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true // if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b int, c: Contravariant<'b>)
} pub fn main() {}
{ }
identifier_body
htmlbaseelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node}; use dom::virtualmethods::VirtualMethods; use url::{Url, UrlParser}; use util::str::DOMString; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement } impl HTMLBaseElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLBaseElement> { let element = HTMLBaseElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap) } /// https://html.spec.whatwg.org/multipage/#frozen-base-url pub fn
(&self) -> Url { let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = UrlParser::new().base_url(&base).parse(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if !tree_in_doc { return; } if self.upcast::<Element>().has_attribute(&atom!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } impl VirtualMethods for HTMLBaseElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == atom!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } fn unbind_from_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().unbind_from_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } }
frozen_base_url
identifier_name
htmlbaseelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node}; use dom::virtualmethods::VirtualMethods; use url::{Url, UrlParser}; use util::str::DOMString; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement } impl HTMLBaseElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document)
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLBaseElement> { let element = HTMLBaseElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap) } /// https://html.spec.whatwg.org/multipage/#frozen-base-url pub fn frozen_base_url(&self) -> Url { let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = UrlParser::new().base_url(&base).parse(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if !tree_in_doc { return; } if self.upcast::<Element>().has_attribute(&atom!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } impl VirtualMethods for HTMLBaseElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == atom!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } fn unbind_from_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().unbind_from_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } }
} }
random_line_split
htmlbaseelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node}; use dom::virtualmethods::VirtualMethods; use url::{Url, UrlParser}; use util::str::DOMString; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement } impl HTMLBaseElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLBaseElement> { let element = HTMLBaseElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap) } /// https://html.spec.whatwg.org/multipage/#frozen-base-url pub fn frozen_base_url(&self) -> Url { let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = UrlParser::new().base_url(&base).parse(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if !tree_in_doc
if self.upcast::<Element>().has_attribute(&atom!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } impl VirtualMethods for HTMLBaseElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == atom!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } fn unbind_from_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().unbind_from_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } }
{ return; }
conditional_block
htmlbaseelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node}; use dom::virtualmethods::VirtualMethods; use url::{Url, UrlParser}; use util::str::DOMString; #[dom_struct] pub struct HTMLBaseElement { htmlelement: HTMLElement } impl HTMLBaseElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLBaseElement { HTMLBaseElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLBaseElement>
/// https://html.spec.whatwg.org/multipage/#frozen-base-url pub fn frozen_base_url(&self) -> Url { let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); let document = document_from_node(self); let base = document.fallback_base_url(); let parsed = UrlParser::new().base_url(&base).parse(&href.value()); parsed.unwrap_or(base) } /// Update the cached base element in response to binding or unbinding from /// a tree. pub fn bind_unbind(&self, tree_in_doc: bool) { if !tree_in_doc { return; } if self.upcast::<Element>().has_attribute(&atom!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } impl VirtualMethods for HTMLBaseElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == atom!("href") { document_from_node(self).refresh_base_element(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } fn unbind_from_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().unbind_from_tree(tree_in_doc); self.bind_unbind(tree_in_doc); } }
{ let element = HTMLBaseElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap) }
identifier_body
AnalyticsUtils.js
import { Map, List, fromJS } from 'immutable'; import * as _ from 'lodash'; import appPackage from '../package.json'; import { getPromotions, filterPromotions } from '../utils/marketingUtils'; const productPropertiesMap = Map({ prod_id: ['code'], prod_name: ['name'], prod_brand: ['brand', 'name'], prod_category: ['mainCategoryName'], prod_univers: ['mainCategoryRooms', '0'], prod_price: ['price', 'selling', 'gross'], prod_avail_online: ['vendible'], prod_avail_store: ['isClickCollectProduct'], prod_gamma: ['gamma'], prod_sconto: ['price', 'selling', 'discount'] }); const layerMap = Map({ filter_name: List(), filter_value: List() }); const LABEL = { PROD_SCONTO: 'prod_sconto', PROD_AVAIL_ONLINE: 'prod_avail_online', PROD_AVAIL_STORE: 'prod_avail_store', PROD_VARIANT: 'prod_variant', PROD_PUNTI_OMAGGIO: 'prod_puntiomaggio', PROD_IDEAPIU: 'prod_idepiu', PROD_BUNDLE: 'prod_bundle', FILTER_NAME: 'filter_name', FILTER_VALUE: 'filter_value', FILTER_RESULT: 'filter_result', PROD_POSITION: 'prod_position', PROD_LIST: 'prod_list', PROD_GAMMA: 'prod_gamma', PROD_NEW: 'prod_new', PROD_PRICE: 'prod_price' }; const relatedProductsSize = 12; const buildCommonLayer = (product) => { const commonPropertiesLayer = productPropertiesMap.reduce((acc, property, key) => { const productProperty = product.hasIn(property) ? product.getIn(property) : ''; return acc.set(key, List().push(productProperty)); }, Map({})); const normalizedCommonPropertiesLayer = normalizeProperties( commonPropertiesLayer ); return normalizedCommonPropertiesLayer; }; const normalizeProperties = (layer) => layer .set(LABEL.PROD_SCONTO, normalizeSconto(layer.get(LABEL.PROD_SCONTO))) .set(LABEL.PROD_AVAIL_ONLINE, normalizeAvail(layer.get(LABEL.PROD_AVAIL_ONLINE))) .set(LABEL.PROD_AVAIL_STORE, normalizeAvail(layer.get(LABEL.PROD_AVAIL_STORE))) .set(LABEL.PROD_PRICE, normalizePrice(layer.get(LABEL.PROD_PRICE))); const normalizeSconto = (value = Map({})) => { const sconto = value.get(0); return List().push(sconto !== '' ? Math.round(sconto * 10).toString() : sconto); }; const normalizePrice = (value = Map({})) => { const price = value.get(0); return List().push(price !== '' ? price.toFixed(2) : ''); }; const normalizeAvail = (field = List()) => List().push(field.get(0) ? '1' : '0'); const isProductNew = product => { const marketingAttributes = product.get('marketingAttributes'); const loyaltyProgram = product.get('loyaltyProgram'); if (marketingAttributes && loyaltyProgram) { const promotions = getPromotions(marketingAttributes, loyaltyProgram); const filteredPromotions = filterPromotions(promotions); const isNew = filteredPromotions.reduce( (acc, promotion) => promotion.get('code') === 'NOVITA', false ); const prodNew = isNew ? '1' : '0'; return Map({ prod_new: List().push(prodNew) }); } }; const getVariant = product => { const masterProductCode = product.get('masterProductCode'); const value = masterProductCode ? `${product.get('code')}_${masterProductCode}` : 'master'; return Map({ [LABEL.PROD_VARIANT]: List().push(value) }); }; const getGiftPoints = product => { const giftPoints = product.getIn(['loyaltyProgram', 'type']); const list = List(); let layer = Map({}); if (giftPoints && giftPoints === 'ADDITIONAL_POINTS') { const points = list.push( Math.round(product.getIn(['loyaltyProgram', 'value']) * 10) ); layer = layer.set(LABEL.PROD_PUNTI_OMAGGIO, points); } return layer; }; const getIdeapiuPoints = product => { const ideapiuPointsType = product.getIn(['loyaltyProgram', 'type']); const list = List(); let layer = Map({}); if (ideapiuPointsType && ideapiuPointsType === 'DISCOUNT') { const points = list.push( Math.round(product.getIn(['loyaltyProgram', 'value']) * 10) ); layer = layer.set(LABEL.PROD_IDEAPIU, points); } return layer; }; const getBundle = product => { const isBundle = product.getIn(['bundleInformation', 'isBundle']); const list = List(); let layer = Map({ prod_bundle: list.push('0') }); if (isBundle) { layer = layer.set(LABEL.PROD_BUNDLE, list.push('1')); } return layer; }; const getProdList = (product, path) => { const mainCategory = product.get('mainCategory'); const mainCategoryName = product.get('mainCategoryName'); const pageContext = getPageContext(path[0]); return `${pageContext} > ${mainCategoryName}/${mainCategory}`; }; const customizer = (objValue, srcValue) => { if (_.isArray(objValue)) { return objValue.concat(srcValue); } }; const buildNavigationStore = (navigationStore = Map()) => { let storeName = ''; if (navigationStore.size > 0) { const storeN = navigationStore.get('name'); const storeCode = navigationStore.get('code'); storeName = `${storeCode} - ${storeN}`; } return Map({ navigation_store: storeName }); }; const buildAppliedFilters = (filterGroup, appliedFilters) => { const dataLayer = filterGroup.reduce((acc, group) => { const groupName = group.get('group'); let accumulator = acc; const activeFilters = group .get('filters') .filter(filter => appliedFilters.includes(filter.get('code'))); if (activeFilters.size) { const newLayer = buildLayer(activeFilters, groupName); accumulator = accumulator .updateIn([LABEL.FILTER_NAME], arr => arr.concat(newLayer.get(LABEL.FILTER_NAME)) ) .updateIn([LABEL.FILTER_VALUE], arr => arr.concat(newLayer.get(LABEL.FILTER_VALUE)) ); } return accumulator; }, layerMap); return dataLayer; }; const buildLayer = (activeFilters = List(), groupName = '') => activeFilters.reduce( (acc, activeFilter) => acc .updateIn([LABEL.FILTER_NAME], arr => arr.push(groupName)) .updateIn([LABEL.FILTER_VALUE], arr => arr.push(activeFilter.get('name')) ), layerMap ); const buildSellingAid = (sellingAids, currentAid) => { const aidGroupName = sellingAids.get('userText'); const { name } = sellingAids .get('aids') .filter(aid => aid.get('code') === currentAid) .get(0) .toJS(); return layerMap .updateIn([LABEL.FILTER_NAME], arr => arr.push(aidGroupName)) .updateIn([LABEL.FILTER_VALUE], arr => arr.push(name)); }; const buildFiltersDataLayer = (layerDataList = []) => layerDataList.reduce( (acc, data) => acc .updateIn([LABEL.FILTER_NAME], arr => arr.concat(data.get(LABEL.FILTER_NAME)) ) .updateIn([LABEL.FILTER_VALUE], arr => arr.concat(data.get(LABEL.FILTER_VALUE)) ), layerMap ); const addResultToLayer = (productsNumber = 0, dataLayer = Map({})) => dataLayer.set( LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString() ); const getPageContext = (value) => { const map = Map({ catalogue: 'gallery-prodotto', product: 'scheda-prodotto' }); return map.get(value); }; const resetOldLevels = (list, start, end) => list.slice(start, end); // --------------------- EXPORTED FUNCTIONS -------------------> const buildPageName = (type, data, pageName = List()) => { const { worldName = '', pathArray = [], categoryCode = '', categoryName = '', prodName = '', prodCode = '' } = data; const isSessionStarting = pageName.size === 0 && type && type === 'session'; const isCatalogStarting = pageName.size > 1 && type && type === 'catalogue'; const isProductStarting = pageName.size > 1 && type && type === 'product'; let levels = pageName; if (isSessionStarting) { levels = levels.push(worldName).push('homepage'); } if (isCatalogStarting) { levels = resetOldLevels(levels, 0, 1); levels = levels .push('prodotti') .push(getPageContext(pathArray[0])) .push(categoryName) .push(categoryCode); } if (isProductStarting) { levels = resetOldLevels(levels, 0, 5); levels = levels .push(prodName) .push(prodCode) .set(2, getPageContext(pathArray[0])); } return levels; }; const buildProductLayer = (product = {}, action = 'detail') => { let productLayer = Map({}); if (!_.isEmpty(product)) { const commonProperties = buildCommonLayer(product); const newProductProperty = isProductNew(product); const variantProperty = getVariant(product); const giftPoints = getGiftPoints(product); const ideapiuPoints = getIdeapiuPoints(product); const isBundle = getBundle(product); const prodAction = Map({ prod_action: action }); productLayer = productLayer.merge( commonProperties, newProductProperty, variantProperty, giftPoints, ideapiuPoints, isBundle, prodAction ); return productLayer; } }; const buildRelatedProductsLayer = ({ products = List(), pathArray = [] }) => { const productList = products.size > relatedProductsSize ? List(products).setSize(relatedProductsSize) : products; let prodPositionCount = 0; if (products.size) { const listOfProductsLayer = productList.map(product => { const prodPosition = List().push((prodPositionCount += 1)); const prodListList = List().push(getProdList(product, pathArray)); let productLayer = buildCommonLayer(product); // add additional properties to productLayer productLayer = productLayer.set(LABEL.PROD_POSITION, prodPosition); productLayer = productLayer.set(LABEL.PROD_LIST, prodListList); return productLayer .set(LABEL.PROD_POSITION, prodPosition) .set(LABEL.PROD_LIST, prodListList) .delete(LABEL.PROD_GAMMA); }); const mergedlistOfProductsLayer = listOfProductsLayer.reduce( (acc, productLayer) => { const mergedValues = _.mergeWith( acc.toJS(), productLayer.toJS(), customizer ); return Map(mergedValues); } ); const normalizeFinalLayer = mergedlistOfProductsLayer.mapKeys(key => _.replace(key, 'prod', 'imp') ); return normalizeFinalLayer; } }; const buildActiveFilters = (filtersData = {}) => { const { sellingAids = Map({}), filterGroup = List(), productsNumber = 0, activeFilters = Map({}), } = filtersData; const aid = activeFilters.get('aid'); const filters = activeFilters.get('filters'); const availability = activeFilters.get('availability'); let appliedFilters = layerMap; let aidFilters = appliedFilters; let availabilityFilters = appliedFilters; if (aid !== '') { aidFilters = buildSellingAid(sellingAids, aid); } if (!_.isEmpty(filters)) { appliedFilters = buildAppliedFilters(filterGroup, filters); } if (availability) { availabilityFilters = fromJS({ filter_name: ['disponibilità in negozio'], filter_value: ['true'] }); } const dataLayer = buildFiltersDataLayer([ aidFilters, appliedFilters, availabilityFilters ]); const dataLayerWithResult = addResultToLayer(productsNumber, dataLayer);
const clearFilters = (dataLayer = Map({}), productsNumber = 0) => dataLayer .set(LABEL.FILTER_VALUE, List()) .set(LABEL.FILTER_NAME, List()) .set(LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString()); const buildReleaseVersion = (worldName = '') => `${_.snakeCase(worldName)}_${appPackage.version}`; const normalizeProductClickLayer = (productLayer, index, product, pathArray) => productLayer .delete(LABEL.PROD_BUNDLE) .delete(LABEL.PROD_GAMMA) .delete(LABEL.PROD_NEW) .delete(LABEL.PROD_VARIANT) .set(LABEL.PROD_POSITION, List().push(index)) .set(LABEL.PROD_LIST, List().push(getProdList(product, pathArray))); const getProductProperty = (product = Map({})) => { const jsonProduct = product.toJS(); let prodCode = 0; let prodCategory = ''; Object.keys(jsonProduct).forEach(key => { Object.keys(jsonProduct[key]).forEach(productProperty => { if (productProperty === 'code') { prodCode = jsonProduct[key][productProperty]; } if (productProperty === 'mainCategoryName') { prodCategory = jsonProduct[key][productProperty]; } }); }); return { prodCode, prodCategory }; }; export { buildPageName, buildProductLayer, buildRelatedProductsLayer, buildActiveFilters, clearFilters, buildNavigationStore, buildReleaseVersion, normalizeProductClickLayer, getProductProperty };
return dataLayerWithResult; };
random_line_split
AnalyticsUtils.js
import { Map, List, fromJS } from 'immutable'; import * as _ from 'lodash'; import appPackage from '../package.json'; import { getPromotions, filterPromotions } from '../utils/marketingUtils'; const productPropertiesMap = Map({ prod_id: ['code'], prod_name: ['name'], prod_brand: ['brand', 'name'], prod_category: ['mainCategoryName'], prod_univers: ['mainCategoryRooms', '0'], prod_price: ['price', 'selling', 'gross'], prod_avail_online: ['vendible'], prod_avail_store: ['isClickCollectProduct'], prod_gamma: ['gamma'], prod_sconto: ['price', 'selling', 'discount'] }); const layerMap = Map({ filter_name: List(), filter_value: List() }); const LABEL = { PROD_SCONTO: 'prod_sconto', PROD_AVAIL_ONLINE: 'prod_avail_online', PROD_AVAIL_STORE: 'prod_avail_store', PROD_VARIANT: 'prod_variant', PROD_PUNTI_OMAGGIO: 'prod_puntiomaggio', PROD_IDEAPIU: 'prod_idepiu', PROD_BUNDLE: 'prod_bundle', FILTER_NAME: 'filter_name', FILTER_VALUE: 'filter_value', FILTER_RESULT: 'filter_result', PROD_POSITION: 'prod_position', PROD_LIST: 'prod_list', PROD_GAMMA: 'prod_gamma', PROD_NEW: 'prod_new', PROD_PRICE: 'prod_price' }; const relatedProductsSize = 12; const buildCommonLayer = (product) => { const commonPropertiesLayer = productPropertiesMap.reduce((acc, property, key) => { const productProperty = product.hasIn(property) ? product.getIn(property) : ''; return acc.set(key, List().push(productProperty)); }, Map({})); const normalizedCommonPropertiesLayer = normalizeProperties( commonPropertiesLayer ); return normalizedCommonPropertiesLayer; }; const normalizeProperties = (layer) => layer .set(LABEL.PROD_SCONTO, normalizeSconto(layer.get(LABEL.PROD_SCONTO))) .set(LABEL.PROD_AVAIL_ONLINE, normalizeAvail(layer.get(LABEL.PROD_AVAIL_ONLINE))) .set(LABEL.PROD_AVAIL_STORE, normalizeAvail(layer.get(LABEL.PROD_AVAIL_STORE))) .set(LABEL.PROD_PRICE, normalizePrice(layer.get(LABEL.PROD_PRICE))); const normalizeSconto = (value = Map({})) => { const sconto = value.get(0); return List().push(sconto !== '' ? Math.round(sconto * 10).toString() : sconto); }; const normalizePrice = (value = Map({})) => { const price = value.get(0); return List().push(price !== '' ? price.toFixed(2) : ''); }; const normalizeAvail = (field = List()) => List().push(field.get(0) ? '1' : '0'); const isProductNew = product => { const marketingAttributes = product.get('marketingAttributes'); const loyaltyProgram = product.get('loyaltyProgram'); if (marketingAttributes && loyaltyProgram) { const promotions = getPromotions(marketingAttributes, loyaltyProgram); const filteredPromotions = filterPromotions(promotions); const isNew = filteredPromotions.reduce( (acc, promotion) => promotion.get('code') === 'NOVITA', false ); const prodNew = isNew ? '1' : '0'; return Map({ prod_new: List().push(prodNew) }); } }; const getVariant = product => { const masterProductCode = product.get('masterProductCode'); const value = masterProductCode ? `${product.get('code')}_${masterProductCode}` : 'master'; return Map({ [LABEL.PROD_VARIANT]: List().push(value) }); }; const getGiftPoints = product => { const giftPoints = product.getIn(['loyaltyProgram', 'type']); const list = List(); let layer = Map({}); if (giftPoints && giftPoints === 'ADDITIONAL_POINTS') { const points = list.push( Math.round(product.getIn(['loyaltyProgram', 'value']) * 10) ); layer = layer.set(LABEL.PROD_PUNTI_OMAGGIO, points); } return layer; }; const getIdeapiuPoints = product => { const ideapiuPointsType = product.getIn(['loyaltyProgram', 'type']); const list = List(); let layer = Map({}); if (ideapiuPointsType && ideapiuPointsType === 'DISCOUNT') { const points = list.push( Math.round(product.getIn(['loyaltyProgram', 'value']) * 10) ); layer = layer.set(LABEL.PROD_IDEAPIU, points); } return layer; }; const getBundle = product => { const isBundle = product.getIn(['bundleInformation', 'isBundle']); const list = List(); let layer = Map({ prod_bundle: list.push('0') }); if (isBundle) { layer = layer.set(LABEL.PROD_BUNDLE, list.push('1')); } return layer; }; const getProdList = (product, path) => { const mainCategory = product.get('mainCategory'); const mainCategoryName = product.get('mainCategoryName'); const pageContext = getPageContext(path[0]); return `${pageContext} > ${mainCategoryName}/${mainCategory}`; }; const customizer = (objValue, srcValue) => { if (_.isArray(objValue))
}; const buildNavigationStore = (navigationStore = Map()) => { let storeName = ''; if (navigationStore.size > 0) { const storeN = navigationStore.get('name'); const storeCode = navigationStore.get('code'); storeName = `${storeCode} - ${storeN}`; } return Map({ navigation_store: storeName }); }; const buildAppliedFilters = (filterGroup, appliedFilters) => { const dataLayer = filterGroup.reduce((acc, group) => { const groupName = group.get('group'); let accumulator = acc; const activeFilters = group .get('filters') .filter(filter => appliedFilters.includes(filter.get('code'))); if (activeFilters.size) { const newLayer = buildLayer(activeFilters, groupName); accumulator = accumulator .updateIn([LABEL.FILTER_NAME], arr => arr.concat(newLayer.get(LABEL.FILTER_NAME)) ) .updateIn([LABEL.FILTER_VALUE], arr => arr.concat(newLayer.get(LABEL.FILTER_VALUE)) ); } return accumulator; }, layerMap); return dataLayer; }; const buildLayer = (activeFilters = List(), groupName = '') => activeFilters.reduce( (acc, activeFilter) => acc .updateIn([LABEL.FILTER_NAME], arr => arr.push(groupName)) .updateIn([LABEL.FILTER_VALUE], arr => arr.push(activeFilter.get('name')) ), layerMap ); const buildSellingAid = (sellingAids, currentAid) => { const aidGroupName = sellingAids.get('userText'); const { name } = sellingAids .get('aids') .filter(aid => aid.get('code') === currentAid) .get(0) .toJS(); return layerMap .updateIn([LABEL.FILTER_NAME], arr => arr.push(aidGroupName)) .updateIn([LABEL.FILTER_VALUE], arr => arr.push(name)); }; const buildFiltersDataLayer = (layerDataList = []) => layerDataList.reduce( (acc, data) => acc .updateIn([LABEL.FILTER_NAME], arr => arr.concat(data.get(LABEL.FILTER_NAME)) ) .updateIn([LABEL.FILTER_VALUE], arr => arr.concat(data.get(LABEL.FILTER_VALUE)) ), layerMap ); const addResultToLayer = (productsNumber = 0, dataLayer = Map({})) => dataLayer.set( LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString() ); const getPageContext = (value) => { const map = Map({ catalogue: 'gallery-prodotto', product: 'scheda-prodotto' }); return map.get(value); }; const resetOldLevels = (list, start, end) => list.slice(start, end); // --------------------- EXPORTED FUNCTIONS -------------------> const buildPageName = (type, data, pageName = List()) => { const { worldName = '', pathArray = [], categoryCode = '', categoryName = '', prodName = '', prodCode = '' } = data; const isSessionStarting = pageName.size === 0 && type && type === 'session'; const isCatalogStarting = pageName.size > 1 && type && type === 'catalogue'; const isProductStarting = pageName.size > 1 && type && type === 'product'; let levels = pageName; if (isSessionStarting) { levels = levels.push(worldName).push('homepage'); } if (isCatalogStarting) { levels = resetOldLevels(levels, 0, 1); levels = levels .push('prodotti') .push(getPageContext(pathArray[0])) .push(categoryName) .push(categoryCode); } if (isProductStarting) { levels = resetOldLevels(levels, 0, 5); levels = levels .push(prodName) .push(prodCode) .set(2, getPageContext(pathArray[0])); } return levels; }; const buildProductLayer = (product = {}, action = 'detail') => { let productLayer = Map({}); if (!_.isEmpty(product)) { const commonProperties = buildCommonLayer(product); const newProductProperty = isProductNew(product); const variantProperty = getVariant(product); const giftPoints = getGiftPoints(product); const ideapiuPoints = getIdeapiuPoints(product); const isBundle = getBundle(product); const prodAction = Map({ prod_action: action }); productLayer = productLayer.merge( commonProperties, newProductProperty, variantProperty, giftPoints, ideapiuPoints, isBundle, prodAction ); return productLayer; } }; const buildRelatedProductsLayer = ({ products = List(), pathArray = [] }) => { const productList = products.size > relatedProductsSize ? List(products).setSize(relatedProductsSize) : products; let prodPositionCount = 0; if (products.size) { const listOfProductsLayer = productList.map(product => { const prodPosition = List().push((prodPositionCount += 1)); const prodListList = List().push(getProdList(product, pathArray)); let productLayer = buildCommonLayer(product); // add additional properties to productLayer productLayer = productLayer.set(LABEL.PROD_POSITION, prodPosition); productLayer = productLayer.set(LABEL.PROD_LIST, prodListList); return productLayer .set(LABEL.PROD_POSITION, prodPosition) .set(LABEL.PROD_LIST, prodListList) .delete(LABEL.PROD_GAMMA); }); const mergedlistOfProductsLayer = listOfProductsLayer.reduce( (acc, productLayer) => { const mergedValues = _.mergeWith( acc.toJS(), productLayer.toJS(), customizer ); return Map(mergedValues); } ); const normalizeFinalLayer = mergedlistOfProductsLayer.mapKeys(key => _.replace(key, 'prod', 'imp') ); return normalizeFinalLayer; } }; const buildActiveFilters = (filtersData = {}) => { const { sellingAids = Map({}), filterGroup = List(), productsNumber = 0, activeFilters = Map({}), } = filtersData; const aid = activeFilters.get('aid'); const filters = activeFilters.get('filters'); const availability = activeFilters.get('availability'); let appliedFilters = layerMap; let aidFilters = appliedFilters; let availabilityFilters = appliedFilters; if (aid !== '') { aidFilters = buildSellingAid(sellingAids, aid); } if (!_.isEmpty(filters)) { appliedFilters = buildAppliedFilters(filterGroup, filters); } if (availability) { availabilityFilters = fromJS({ filter_name: ['disponibilità in negozio'], filter_value: ['true'] }); } const dataLayer = buildFiltersDataLayer([ aidFilters, appliedFilters, availabilityFilters ]); const dataLayerWithResult = addResultToLayer(productsNumber, dataLayer); return dataLayerWithResult; }; const clearFilters = (dataLayer = Map({}), productsNumber = 0) => dataLayer .set(LABEL.FILTER_VALUE, List()) .set(LABEL.FILTER_NAME, List()) .set(LABEL.FILTER_RESULT, productsNumber > 12 ? '12' : productsNumber.toString()); const buildReleaseVersion = (worldName = '') => `${_.snakeCase(worldName)}_${appPackage.version}`; const normalizeProductClickLayer = (productLayer, index, product, pathArray) => productLayer .delete(LABEL.PROD_BUNDLE) .delete(LABEL.PROD_GAMMA) .delete(LABEL.PROD_NEW) .delete(LABEL.PROD_VARIANT) .set(LABEL.PROD_POSITION, List().push(index)) .set(LABEL.PROD_LIST, List().push(getProdList(product, pathArray))); const getProductProperty = (product = Map({})) => { const jsonProduct = product.toJS(); let prodCode = 0; let prodCategory = ''; Object.keys(jsonProduct).forEach(key => { Object.keys(jsonProduct[key]).forEach(productProperty => { if (productProperty === 'code') { prodCode = jsonProduct[key][productProperty]; } if (productProperty === 'mainCategoryName') { prodCategory = jsonProduct[key][productProperty]; } }); }); return { prodCode, prodCategory }; }; export { buildPageName, buildProductLayer, buildRelatedProductsLayer, buildActiveFilters, clearFilters, buildNavigationStore, buildReleaseVersion, normalizeProductClickLayer, getProductProperty };
{ return objValue.concat(srcValue); }
conditional_block
interrupt.rs
use alloc::boxed::Box; use collections::string::ToString; use fs::{KScheme, Resource, Url, VecResource}; use system::error::Result; pub struct InterruptScheme; static IRQ_NAME: [&'static str; 16] = [ "Programmable Interval Timer", "Keyboard", "Cascade", "Serial 2 and 4", "Serial 1 and 3", "Parallel 2", "Floppy", "Parallel 1", "Realtime Clock", "PCI 1", "PCI 2", "PCI 3", "Mouse", "Coprocessor", "IDE Primary", "IDE Secondary", ]; impl KScheme for InterruptScheme { fn scheme(&self) -> &str { "interrupt" } fn open(&mut self, _: Url, _: usize) -> Result<Box<Resource>> { let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION"); { let interrupts = unsafe { &mut *::env().interrupts.get() }; for interrupt in 0..interrupts.len() { let count = interrupts[interrupt]; if count > 0 { let description = match interrupt { i @ 0x20 ... 0x30 => IRQ_NAME[i - 0x20], 0x80 => "System Call", 0x0 => "Divide by zero exception", 0x1 => "Debug exception", 0x2 => "Non-maskable interrupt", 0x3 => "Breakpoint exception", 0x4 => "Overflow exception", 0x5 => "Bound range exceeded exception", 0x6 => "Invalid opcode exception", 0x7 => "Device not available exception", 0x8 => "Double fault", 0xA => "Invalid TSS exception", 0xB => "Segment not present exception", 0xC => "Stack-segment fault", 0xD => "General protection fault", 0xE => "Page fault", 0x10 => "x87 floating-point exception", 0x11 => "Alignment check exception", 0x12 => "Machine check exception", 0x13 => "SIMD floating-point exception",
_ => "Unknown Interrupt", }; string.push_str(&format!("{:<6X}{:<16}{}\n", interrupt, count, description)); } } } Ok(box VecResource::new("interrupt:".to_string(), string.into_bytes())) } }
0x14 => "Virtualization exception", 0x1E => "Security exception",
random_line_split
interrupt.rs
use alloc::boxed::Box; use collections::string::ToString; use fs::{KScheme, Resource, Url, VecResource}; use system::error::Result; pub struct InterruptScheme; static IRQ_NAME: [&'static str; 16] = [ "Programmable Interval Timer", "Keyboard", "Cascade", "Serial 2 and 4", "Serial 1 and 3", "Parallel 2", "Floppy", "Parallel 1", "Realtime Clock", "PCI 1", "PCI 2", "PCI 3", "Mouse", "Coprocessor", "IDE Primary", "IDE Secondary", ]; impl KScheme for InterruptScheme { fn scheme(&self) -> &str { "interrupt" } fn
(&mut self, _: Url, _: usize) -> Result<Box<Resource>> { let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION"); { let interrupts = unsafe { &mut *::env().interrupts.get() }; for interrupt in 0..interrupts.len() { let count = interrupts[interrupt]; if count > 0 { let description = match interrupt { i @ 0x20 ... 0x30 => IRQ_NAME[i - 0x20], 0x80 => "System Call", 0x0 => "Divide by zero exception", 0x1 => "Debug exception", 0x2 => "Non-maskable interrupt", 0x3 => "Breakpoint exception", 0x4 => "Overflow exception", 0x5 => "Bound range exceeded exception", 0x6 => "Invalid opcode exception", 0x7 => "Device not available exception", 0x8 => "Double fault", 0xA => "Invalid TSS exception", 0xB => "Segment not present exception", 0xC => "Stack-segment fault", 0xD => "General protection fault", 0xE => "Page fault", 0x10 => "x87 floating-point exception", 0x11 => "Alignment check exception", 0x12 => "Machine check exception", 0x13 => "SIMD floating-point exception", 0x14 => "Virtualization exception", 0x1E => "Security exception", _ => "Unknown Interrupt", }; string.push_str(&format!("{:<6X}{:<16}{}\n", interrupt, count, description)); } } } Ok(box VecResource::new("interrupt:".to_string(), string.into_bytes())) } }
open
identifier_name
interrupt.rs
use alloc::boxed::Box; use collections::string::ToString; use fs::{KScheme, Resource, Url, VecResource}; use system::error::Result; pub struct InterruptScheme; static IRQ_NAME: [&'static str; 16] = [ "Programmable Interval Timer", "Keyboard", "Cascade", "Serial 2 and 4", "Serial 1 and 3", "Parallel 2", "Floppy", "Parallel 1", "Realtime Clock", "PCI 1", "PCI 2", "PCI 3", "Mouse", "Coprocessor", "IDE Primary", "IDE Secondary", ]; impl KScheme for InterruptScheme { fn scheme(&self) -> &str
fn open(&mut self, _: Url, _: usize) -> Result<Box<Resource>> { let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION"); { let interrupts = unsafe { &mut *::env().interrupts.get() }; for interrupt in 0..interrupts.len() { let count = interrupts[interrupt]; if count > 0 { let description = match interrupt { i @ 0x20 ... 0x30 => IRQ_NAME[i - 0x20], 0x80 => "System Call", 0x0 => "Divide by zero exception", 0x1 => "Debug exception", 0x2 => "Non-maskable interrupt", 0x3 => "Breakpoint exception", 0x4 => "Overflow exception", 0x5 => "Bound range exceeded exception", 0x6 => "Invalid opcode exception", 0x7 => "Device not available exception", 0x8 => "Double fault", 0xA => "Invalid TSS exception", 0xB => "Segment not present exception", 0xC => "Stack-segment fault", 0xD => "General protection fault", 0xE => "Page fault", 0x10 => "x87 floating-point exception", 0x11 => "Alignment check exception", 0x12 => "Machine check exception", 0x13 => "SIMD floating-point exception", 0x14 => "Virtualization exception", 0x1E => "Security exception", _ => "Unknown Interrupt", }; string.push_str(&format!("{:<6X}{:<16}{}\n", interrupt, count, description)); } } } Ok(box VecResource::new("interrupt:".to_string(), string.into_bytes())) } }
{ "interrupt" }
identifier_body
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::fmt; use proto::error::*; use thiserror::Error; use crate::proto::{trace, ExtBacktrace}; /// An alias for results returned by functions of this crate pub type Result<T> = ::std::result::Result<T, Error>; /// The error kind for errors that get returned in the crate #[derive(Debug, Error)] pub enum
{ /// An error that occurred when recovering from journal #[error("error recovering from journal: {}", _0)] Recovery(&'static str), /// The number of inserted records didn't match the expected amount #[error("wrong insert count: {} expect: {}", got, expect)] WrongInsertCount { /// The number of inserted records got: usize, /// The number of records expected to be inserted expect: usize, }, // foreign /// An error got returned by the trust-dns-proto crate #[error("proto error: {0}")] Proto(#[from] ProtoError), /// An error got returned from the rusqlite crate #[cfg(feature = "sqlite")] #[error("sqlite error: {0}")] Sqlite(#[from] rusqlite::Error), /// A request timed out #[error("request timed out")] Timeout, } /// The error type for errors that get returned in the crate #[derive(Debug, Error)] pub struct Error { kind: ErrorKind, backtrack: Option<ExtBacktrace>, } impl Error { /// Get the kind of the error pub fn kind(&self) -> &ErrorKind { &self.kind } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(ref backtrace) = self.backtrack { fmt::Display::fmt(&self.kind, f)?; fmt::Debug::fmt(backtrace, f) } else { fmt::Display::fmt(&self.kind, f) } } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error { Error { kind, backtrack: trace!(), } } } impl From<ProtoError> for Error { fn from(e: ProtoError) -> Error { match *e.kind() { ProtoErrorKind::Timeout => ErrorKind::Timeout.into(), _ => ErrorKind::from(e).into(), } } } #[cfg(feature = "sqlite")] impl From<rusqlite::Error> for Error { fn from(e: rusqlite::Error) -> Error { ErrorKind::from(e).into() } }
ErrorKind
identifier_name
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::fmt; use proto::error::*; use thiserror::Error; use crate::proto::{trace, ExtBacktrace}; /// An alias for results returned by functions of this crate pub type Result<T> = ::std::result::Result<T, Error>; /// The error kind for errors that get returned in the crate #[derive(Debug, Error)] pub enum ErrorKind { /// An error that occurred when recovering from journal #[error("error recovering from journal: {}", _0)] Recovery(&'static str), /// The number of inserted records didn't match the expected amount #[error("wrong insert count: {} expect: {}", got, expect)] WrongInsertCount { /// The number of inserted records got: usize, /// The number of records expected to be inserted expect: usize, }, // foreign /// An error got returned by the trust-dns-proto crate #[error("proto error: {0}")] Proto(#[from] ProtoError), /// An error got returned from the rusqlite crate #[cfg(feature = "sqlite")] #[error("sqlite error: {0}")] Sqlite(#[from] rusqlite::Error), /// A request timed out #[error("request timed out")] Timeout, } /// The error type for errors that get returned in the crate #[derive(Debug, Error)] pub struct Error { kind: ErrorKind, backtrack: Option<ExtBacktrace>, } impl Error { /// Get the kind of the error pub fn kind(&self) -> &ErrorKind { &self.kind } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(ref backtrace) = self.backtrack { fmt::Display::fmt(&self.kind, f)?; fmt::Debug::fmt(backtrace, f) } else
} } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error { Error { kind, backtrack: trace!(), } } } impl From<ProtoError> for Error { fn from(e: ProtoError) -> Error { match *e.kind() { ProtoErrorKind::Timeout => ErrorKind::Timeout.into(), _ => ErrorKind::from(e).into(), } } } #[cfg(feature = "sqlite")] impl From<rusqlite::Error> for Error { fn from(e: rusqlite::Error) -> Error { ErrorKind::from(e).into() } }
{ fmt::Display::fmt(&self.kind, f) }
conditional_block
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::fmt; use proto::error::*; use thiserror::Error; use crate::proto::{trace, ExtBacktrace}; /// An alias for results returned by functions of this crate pub type Result<T> = ::std::result::Result<T, Error>; /// The error kind for errors that get returned in the crate #[derive(Debug, Error)] pub enum ErrorKind { /// An error that occurred when recovering from journal #[error("error recovering from journal: {}", _0)] Recovery(&'static str), /// The number of inserted records didn't match the expected amount #[error("wrong insert count: {} expect: {}", got, expect)] WrongInsertCount {
// foreign /// An error got returned by the trust-dns-proto crate #[error("proto error: {0}")] Proto(#[from] ProtoError), /// An error got returned from the rusqlite crate #[cfg(feature = "sqlite")] #[error("sqlite error: {0}")] Sqlite(#[from] rusqlite::Error), /// A request timed out #[error("request timed out")] Timeout, } /// The error type for errors that get returned in the crate #[derive(Debug, Error)] pub struct Error { kind: ErrorKind, backtrack: Option<ExtBacktrace>, } impl Error { /// Get the kind of the error pub fn kind(&self) -> &ErrorKind { &self.kind } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(ref backtrace) = self.backtrack { fmt::Display::fmt(&self.kind, f)?; fmt::Debug::fmt(backtrace, f) } else { fmt::Display::fmt(&self.kind, f) } } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error { Error { kind, backtrack: trace!(), } } } impl From<ProtoError> for Error { fn from(e: ProtoError) -> Error { match *e.kind() { ProtoErrorKind::Timeout => ErrorKind::Timeout.into(), _ => ErrorKind::from(e).into(), } } } #[cfg(feature = "sqlite")] impl From<rusqlite::Error> for Error { fn from(e: rusqlite::Error) -> Error { ErrorKind::from(e).into() } }
/// The number of inserted records got: usize, /// The number of records expected to be inserted expect: usize, },
random_line_split
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::fmt; use proto::error::*; use thiserror::Error; use crate::proto::{trace, ExtBacktrace}; /// An alias for results returned by functions of this crate pub type Result<T> = ::std::result::Result<T, Error>; /// The error kind for errors that get returned in the crate #[derive(Debug, Error)] pub enum ErrorKind { /// An error that occurred when recovering from journal #[error("error recovering from journal: {}", _0)] Recovery(&'static str), /// The number of inserted records didn't match the expected amount #[error("wrong insert count: {} expect: {}", got, expect)] WrongInsertCount { /// The number of inserted records got: usize, /// The number of records expected to be inserted expect: usize, }, // foreign /// An error got returned by the trust-dns-proto crate #[error("proto error: {0}")] Proto(#[from] ProtoError), /// An error got returned from the rusqlite crate #[cfg(feature = "sqlite")] #[error("sqlite error: {0}")] Sqlite(#[from] rusqlite::Error), /// A request timed out #[error("request timed out")] Timeout, } /// The error type for errors that get returned in the crate #[derive(Debug, Error)] pub struct Error { kind: ErrorKind, backtrack: Option<ExtBacktrace>, } impl Error { /// Get the kind of the error pub fn kind(&self) -> &ErrorKind { &self.kind } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(ref backtrace) = self.backtrack { fmt::Display::fmt(&self.kind, f)?; fmt::Debug::fmt(backtrace, f) } else { fmt::Display::fmt(&self.kind, f) } } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error
} impl From<ProtoError> for Error { fn from(e: ProtoError) -> Error { match *e.kind() { ProtoErrorKind::Timeout => ErrorKind::Timeout.into(), _ => ErrorKind::from(e).into(), } } } #[cfg(feature = "sqlite")] impl From<rusqlite::Error> for Error { fn from(e: rusqlite::Error) -> Error { ErrorKind::from(e).into() } }
{ Error { kind, backtrack: trace!(), } }
identifier_body
VelocityOverTime.py
# -*- coding: Latin-1 -*- """ @file VelocityOverTime.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-05-29 Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors All rights reserved """ from pylab import * import profile import util.Path as path import util.Reader as reader from cPickle import load from analysis.Taxi import * from matplotlib.collections import LineCollection from matplotlib.colors import colorConverter #global vars WEE=True #=withoutEmptyEdges decide which analysis file should be used edgeDict={} taxis=[] def main(): print "start program" global taxis, edgeDict #decide if you want to save charts for every taxi or show a single one all=False; taxiId="316_3" #load data edgeDict=load(open(path.edgeLengthDict,'r')) taxis=reader.readAnalysisInfo(WEE) #reader.readEdgesLength() if all: plotAllTaxis() else: plotIt(taxiId) show() print "end" def plotAllTaxis(): """plot all taxis to an folder.""" #kind of progress bar :-) allT=len(taxis) lastProz=0 for i in range(5,105,5): s="%02d" %i print s, print "%" for i in range(allT): actProz=(100*i/allT) if actProz!=lastProz and actProz%5==0: print "**", lastProz=actProz if plotIt(taxis[i].id)!=-1: savefig(path.vOverTimeDir+"taxi_"+str(taxis[i].id)+".png", format="png") close() #close the figure def fetchData(taxiId):
def plotIt(taxiId): """draws the chart""" width=12 #1200px height=9 #900px #fetch data route,values=fetchData(taxiId) #check if a route exists for this vehicle if len(route[1])<1 or len(route[3])<1: return -1 #make nice labels maxRoute=max((route[1][-1]),route[3][-1]) minDist=(maxRoute/(width-4.5)) def makethemNice(source=SOURCE_FCD): """create labels of the x-Axis for the FCD and simFCD chart""" if source==SOURCE_FCD: label=0; loc=1 elif source==SOURCE_SIMFCD: label=2; loc=3 else: assert False lastShown=route[loc][0] for i in range(len(route[label])): if i==0 or i==len(route[label])-1: route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] elif route[loc][i]-lastShown>minDist: #if distance between last Label location and actual location big enough route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] lastShown=route[loc][i] else: route[label][i]="" if route[loc][-1]-lastShown<minDist: #check if the last shown element troubles the last route[label][route[loc].index(lastShown)]="" makethemNice(SOURCE_FCD) makethemNice(SOURCE_SIMFCD) #plot the results fig=figure(figsize=(width,height), dpi=96) subplot(211) title(U"Geschwindigkeit \u00FCber Zeit pro Kante") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[1],route[0]) plot(values[0],values[1], label='FCD') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) subplot(212) xlabel("\n\nt (s) unterteilt in Routenabschnitte (Kanten)\n\n") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[3],route[2]) plot(values[2],values[3], label='simulierte FCD', color='g') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) return 1 #start the program #profile.run('main()') main()
"""fetch the data for the given taxi""" route=[[],[],[],[]] #route of the taxi (edge, length, edgeSimFCD(to find doubles)) values=[[],[],[],[]] #x,y1,x2,y2 (position, vFCD,vSIMFCD) actLen=0 x=0 def getTime(s,v): if v==0: return 0 return s/(v/3.6) for step in taxis[taxis.index(taxiId)].getSteps(): if step.source==SOURCE_FCD or step.source==SOURCE_SIMFCD: routeLen=edgeDict[step.edge] #save the simFCD infos in apart Lists if step.source==SOURCE_SIMFCD and len(values[2])<=0: x=2 actLen=0 if len(route[0+x])>0 and step.edge==route[0+x][-1]: #print step.edge values[1+x][-1]=(values[1+x][-1]+step.speed)/2.0 values[1+x][-2]=values[1+x][-1] else: #start point of route values[0+x].append(actLen) values[1+x].append(step.speed) actLen+=getTime(routeLen,step.speed) print "l ",actLen," rL ",routeLen," s ",step.speed route[0+x].append(step.edge) #label route[1+x].append(actLen) #location #end point of route values[0+x].append(actLen) values[1+x].append(step.speed) return route,values
identifier_body
VelocityOverTime.py
# -*- coding: Latin-1 -*- """ @file VelocityOverTime.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-05-29 Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors All rights reserved """ from pylab import * import profile import util.Path as path import util.Reader as reader from cPickle import load from analysis.Taxi import * from matplotlib.collections import LineCollection from matplotlib.colors import colorConverter #global vars WEE=True #=withoutEmptyEdges decide which analysis file should be used edgeDict={} taxis=[] def main(): print "start program" global taxis, edgeDict #decide if you want to save charts for every taxi or show a single one all=False; taxiId="316_3" #load data edgeDict=load(open(path.edgeLengthDict,'r')) taxis=reader.readAnalysisInfo(WEE) #reader.readEdgesLength() if all: plotAllTaxis() else: plotIt(taxiId) show() print "end" def plotAllTaxis(): """plot all taxis to an folder.""" #kind of progress bar :-) allT=len(taxis) lastProz=0 for i in range(5,105,5): s="%02d" %i print s, print "%" for i in range(allT): actProz=(100*i/allT) if actProz!=lastProz and actProz%5==0: print "**", lastProz=actProz if plotIt(taxis[i].id)!=-1: savefig(path.vOverTimeDir+"taxi_"+str(taxis[i].id)+".png", format="png") close() #close the figure def fetchData(taxiId): """fetch the data for the given taxi""" route=[[],[],[],[]] #route of the taxi (edge, length, edgeSimFCD(to find doubles)) values=[[],[],[],[]] #x,y1,x2,y2 (position, vFCD,vSIMFCD) actLen=0 x=0 def getTime(s,v): if v==0: return 0 return s/(v/3.6) for step in taxis[taxis.index(taxiId)].getSteps(): if step.source==SOURCE_FCD or step.source==SOURCE_SIMFCD: routeLen=edgeDict[step.edge] #save the simFCD infos in apart Lists if step.source==SOURCE_SIMFCD and len(values[2])<=0: x=2 actLen=0 if len(route[0+x])>0 and step.edge==route[0+x][-1]: #print step.edge values[1+x][-1]=(values[1+x][-1]+step.speed)/2.0 values[1+x][-2]=values[1+x][-1] else: #start point of route values[0+x].append(actLen) values[1+x].append(step.speed) actLen+=getTime(routeLen,step.speed) print "l ",actLen," rL ",routeLen," s ",step.speed route[0+x].append(step.edge) #label route[1+x].append(actLen) #location #end point of route values[0+x].append(actLen) values[1+x].append(step.speed) return route,values def plotIt(taxiId): """draws the chart"""
height=9 #900px #fetch data route,values=fetchData(taxiId) #check if a route exists for this vehicle if len(route[1])<1 or len(route[3])<1: return -1 #make nice labels maxRoute=max((route[1][-1]),route[3][-1]) minDist=(maxRoute/(width-4.5)) def makethemNice(source=SOURCE_FCD): """create labels of the x-Axis for the FCD and simFCD chart""" if source==SOURCE_FCD: label=0; loc=1 elif source==SOURCE_SIMFCD: label=2; loc=3 else: assert False lastShown=route[loc][0] for i in range(len(route[label])): if i==0 or i==len(route[label])-1: route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] elif route[loc][i]-lastShown>minDist: #if distance between last Label location and actual location big enough route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] lastShown=route[loc][i] else: route[label][i]="" if route[loc][-1]-lastShown<minDist: #check if the last shown element troubles the last route[label][route[loc].index(lastShown)]="" makethemNice(SOURCE_FCD) makethemNice(SOURCE_SIMFCD) #plot the results fig=figure(figsize=(width,height), dpi=96) subplot(211) title(U"Geschwindigkeit \u00FCber Zeit pro Kante") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[1],route[0]) plot(values[0],values[1], label='FCD') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) subplot(212) xlabel("\n\nt (s) unterteilt in Routenabschnitte (Kanten)\n\n") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[3],route[2]) plot(values[2],values[3], label='simulierte FCD', color='g') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) return 1 #start the program #profile.run('main()') main()
width=12 #1200px
random_line_split
VelocityOverTime.py
# -*- coding: Latin-1 -*- """ @file VelocityOverTime.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-05-29 Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors All rights reserved """ from pylab import * import profile import util.Path as path import util.Reader as reader from cPickle import load from analysis.Taxi import * from matplotlib.collections import LineCollection from matplotlib.colors import colorConverter #global vars WEE=True #=withoutEmptyEdges decide which analysis file should be used edgeDict={} taxis=[] def main(): print "start program" global taxis, edgeDict #decide if you want to save charts for every taxi or show a single one all=False; taxiId="316_3" #load data edgeDict=load(open(path.edgeLengthDict,'r')) taxis=reader.readAnalysisInfo(WEE) #reader.readEdgesLength() if all: plotAllTaxis() else: plotIt(taxiId) show() print "end" def
(): """plot all taxis to an folder.""" #kind of progress bar :-) allT=len(taxis) lastProz=0 for i in range(5,105,5): s="%02d" %i print s, print "%" for i in range(allT): actProz=(100*i/allT) if actProz!=lastProz and actProz%5==0: print "**", lastProz=actProz if plotIt(taxis[i].id)!=-1: savefig(path.vOverTimeDir+"taxi_"+str(taxis[i].id)+".png", format="png") close() #close the figure def fetchData(taxiId): """fetch the data for the given taxi""" route=[[],[],[],[]] #route of the taxi (edge, length, edgeSimFCD(to find doubles)) values=[[],[],[],[]] #x,y1,x2,y2 (position, vFCD,vSIMFCD) actLen=0 x=0 def getTime(s,v): if v==0: return 0 return s/(v/3.6) for step in taxis[taxis.index(taxiId)].getSteps(): if step.source==SOURCE_FCD or step.source==SOURCE_SIMFCD: routeLen=edgeDict[step.edge] #save the simFCD infos in apart Lists if step.source==SOURCE_SIMFCD and len(values[2])<=0: x=2 actLen=0 if len(route[0+x])>0 and step.edge==route[0+x][-1]: #print step.edge values[1+x][-1]=(values[1+x][-1]+step.speed)/2.0 values[1+x][-2]=values[1+x][-1] else: #start point of route values[0+x].append(actLen) values[1+x].append(step.speed) actLen+=getTime(routeLen,step.speed) print "l ",actLen," rL ",routeLen," s ",step.speed route[0+x].append(step.edge) #label route[1+x].append(actLen) #location #end point of route values[0+x].append(actLen) values[1+x].append(step.speed) return route,values def plotIt(taxiId): """draws the chart""" width=12 #1200px height=9 #900px #fetch data route,values=fetchData(taxiId) #check if a route exists for this vehicle if len(route[1])<1 or len(route[3])<1: return -1 #make nice labels maxRoute=max((route[1][-1]),route[3][-1]) minDist=(maxRoute/(width-4.5)) def makethemNice(source=SOURCE_FCD): """create labels of the x-Axis for the FCD and simFCD chart""" if source==SOURCE_FCD: label=0; loc=1 elif source==SOURCE_SIMFCD: label=2; loc=3 else: assert False lastShown=route[loc][0] for i in range(len(route[label])): if i==0 or i==len(route[label])-1: route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] elif route[loc][i]-lastShown>minDist: #if distance between last Label location and actual location big enough route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] lastShown=route[loc][i] else: route[label][i]="" if route[loc][-1]-lastShown<minDist: #check if the last shown element troubles the last route[label][route[loc].index(lastShown)]="" makethemNice(SOURCE_FCD) makethemNice(SOURCE_SIMFCD) #plot the results fig=figure(figsize=(width,height), dpi=96) subplot(211) title(U"Geschwindigkeit \u00FCber Zeit pro Kante") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[1],route[0]) plot(values[0],values[1], label='FCD') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) subplot(212) xlabel("\n\nt (s) unterteilt in Routenabschnitte (Kanten)\n\n") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[3],route[2]) plot(values[2],values[3], label='simulierte FCD', color='g') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) return 1 #start the program #profile.run('main()') main()
plotAllTaxis
identifier_name
VelocityOverTime.py
# -*- coding: Latin-1 -*- """ @file VelocityOverTime.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-05-29 Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors All rights reserved """ from pylab import * import profile import util.Path as path import util.Reader as reader from cPickle import load from analysis.Taxi import * from matplotlib.collections import LineCollection from matplotlib.colors import colorConverter #global vars WEE=True #=withoutEmptyEdges decide which analysis file should be used edgeDict={} taxis=[] def main(): print "start program" global taxis, edgeDict #decide if you want to save charts for every taxi or show a single one all=False; taxiId="316_3" #load data edgeDict=load(open(path.edgeLengthDict,'r')) taxis=reader.readAnalysisInfo(WEE) #reader.readEdgesLength() if all: plotAllTaxis() else: plotIt(taxiId) show() print "end" def plotAllTaxis(): """plot all taxis to an folder.""" #kind of progress bar :-) allT=len(taxis) lastProz=0 for i in range(5,105,5): s="%02d" %i print s, print "%" for i in range(allT): actProz=(100*i/allT) if actProz!=lastProz and actProz%5==0: print "**", lastProz=actProz if plotIt(taxis[i].id)!=-1: savefig(path.vOverTimeDir+"taxi_"+str(taxis[i].id)+".png", format="png") close() #close the figure def fetchData(taxiId): """fetch the data for the given taxi""" route=[[],[],[],[]] #route of the taxi (edge, length, edgeSimFCD(to find doubles)) values=[[],[],[],[]] #x,y1,x2,y2 (position, vFCD,vSIMFCD) actLen=0 x=0 def getTime(s,v): if v==0: return 0 return s/(v/3.6) for step in taxis[taxis.index(taxiId)].getSteps(): if step.source==SOURCE_FCD or step.source==SOURCE_SIMFCD: routeLen=edgeDict[step.edge] #save the simFCD infos in apart Lists if step.source==SOURCE_SIMFCD and len(values[2])<=0: x=2 actLen=0 if len(route[0+x])>0 and step.edge==route[0+x][-1]: #print step.edge values[1+x][-1]=(values[1+x][-1]+step.speed)/2.0 values[1+x][-2]=values[1+x][-1] else: #start point of route values[0+x].append(actLen) values[1+x].append(step.speed) actLen+=getTime(routeLen,step.speed) print "l ",actLen," rL ",routeLen," s ",step.speed route[0+x].append(step.edge) #label route[1+x].append(actLen) #location #end point of route values[0+x].append(actLen) values[1+x].append(step.speed) return route,values def plotIt(taxiId): """draws the chart""" width=12 #1200px height=9 #900px #fetch data route,values=fetchData(taxiId) #check if a route exists for this vehicle if len(route[1])<1 or len(route[3])<1:
#make nice labels maxRoute=max((route[1][-1]),route[3][-1]) minDist=(maxRoute/(width-4.5)) def makethemNice(source=SOURCE_FCD): """create labels of the x-Axis for the FCD and simFCD chart""" if source==SOURCE_FCD: label=0; loc=1 elif source==SOURCE_SIMFCD: label=2; loc=3 else: assert False lastShown=route[loc][0] for i in range(len(route[label])): if i==0 or i==len(route[label])-1: route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] elif route[loc][i]-lastShown>minDist: #if distance between last Label location and actual location big enough route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] lastShown=route[loc][i] else: route[label][i]="" if route[loc][-1]-lastShown<minDist: #check if the last shown element troubles the last route[label][route[loc].index(lastShown)]="" makethemNice(SOURCE_FCD) makethemNice(SOURCE_SIMFCD) #plot the results fig=figure(figsize=(width,height), dpi=96) subplot(211) title(U"Geschwindigkeit \u00FCber Zeit pro Kante") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[1],route[0]) plot(values[0],values[1], label='FCD') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) subplot(212) xlabel("\n\nt (s) unterteilt in Routenabschnitte (Kanten)\n\n") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[3],route[2]) plot(values[2],values[3], label='simulierte FCD', color='g') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) return 1 #start the program #profile.run('main()') main()
return -1
conditional_block
index.d.ts
// Type definitions for non-npm package Node.js 14.14 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript <https://github.com/Microsoft> // DefinitelyTyped <https://github.com/DefinitelyTyped> // Alberto Schiabel <https://github.com/jkomyno> // Alexander T. <https://github.com/a-tarasyuk> // Alvis HT Tang <https://github.com/alvis> // Andrew Makarov <https://github.com/r3nya> // Benjamin Toueg <https://github.com/btoueg> // Bruno Scheufler <https://github.com/brunoscheufler> // Chigozirim C. <https://github.com/smac89> // David Junger <https://github.com/touffy> // Deividas Bakanas <https://github.com/DeividasBakanas> // Eugene Y. Q. Shen <https://github.com/eyqs> // Flarna <https://github.com/Flarna> // Hannes Magnusson <https://github.com/Hannes-Magnusson-CK> // Hoàng Văn Khải <https://github.com/KSXGitHub> // Huw <https://github.com/hoo29> // Kelvin Jin <https://github.com/kjin> // Klaus Meinhardt <https://github.com/ajafff> // Lishude <https://github.com/islishude> // Mariusz Wiktorczyk <https://github.com/mwiktorczyk> // Mohsen Azimi <https://github.com/mohsen1> // Nicolas Even <https://github.com/n-e> // Nikita Galkin <https://github.com/galkin> // Parambir Singh <https://github.com/parambirs> // Sebastian Silbermann <https://github.com/eps1lon> // Simon Schick <https://github.com/SimonSchick> // Thomas den Hollander <https://github.com/ThomasdenH> // Wilco Bakker <https://github.com/WilcoBakker> // wwwy3y3 <https://github.com/wwwy3y3> // Samuel Ainsworth <https://github.com/samuela> // Kyle Uehlein <https://github.com/kuehlein> // Jordi Oliveras Rovira <https://github.com/j-oliveras> // Thanik Bhongbhibhat <https://github.com/bhongy>
// Marcin Kopacz <https://github.com/chyzwar> // Trivikram Kamat <https://github.com/trivikr> // Minh Son Nguyen <https://github.com/nguymin4> // Junxiao Shi <https://github.com/yoursunny> // Ilia Baryshnikov <https://github.com/qwelias> // ExE Boss <https://github.com/ExE-Boss> // Surasak Chaisurin <https://github.com/Ryan-Willpower> // Piotr Błażejewicz <https://github.com/peterblazejewicz> // Anna Henningsen <https://github.com/addaleax> // Jason Kwok <https://github.com/JasonHK> // Victor Perin <https://github.com/victorperin> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // NOTE: These definitions support NodeJS and TypeScript 3.7. // Typically type modifications should be made in base.d.ts instead of here /// <reference path="base.d.ts" /> // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.8 // - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 // NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides // within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions // prior to TypeScript 3.5, so the older definitions will be found here.
random_line_split
manipulando_o_dom.js
$(function() { var resposta = $.ajax({ url:"http://localhost:8080/estados", method: "GET", dataType: "jsonp"//usado por estar em domínios diferentes }); //A requisição Ajax pode demorar a retornar uma resposta //com Promises é possível utilizar o método done() que executa //assim que a requisição retornar uma resposta. Pode-se utilizar mais //de uma vez.
comboEstado.html("<option>Selecione o estado</option>") estados.forEach(function(estado) { //cria uma elemento 'option' e adiciona no select var optionEstado = $("<option>").val(estado.uf).text(estado.nome); comboEstado.append(optionEstado); }); }); resposta.fail(function() { alert("Erro carregando dados do servidor."); }); });
resposta.done(function(estados) { var comboEstado = $("#combo-estado"); //comboEstado.empty();
random_line_split
thrift_util.py
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import re from builtins import open INCLUDE_PARSER = re.compile(r'^\s*include\s+"([^"]+)"\s*([\/\/|\#].*)*$') def
(basedirs, source, log=None): """Finds all thrift files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger """ all_basedirs = [os.path.dirname(source)] all_basedirs.extend(basedirs) includes = set() with open(source, 'r') as thrift: for line in thrift.readlines(): match = INCLUDE_PARSER.match(line) if match: capture = match.group(1) added = False for basedir in all_basedirs: include = os.path.join(basedir, capture) if os.path.exists(include): if log: log.debug('{} has include {}'.format(source, include)) includes.add(include) added = True if not added: raise ValueError("{} included in {} not found in bases {}" .format(include, source, all_basedirs)) return includes def find_root_thrifts(basedirs, sources, log=None): """Finds the root thrift files in the graph formed by sources and their recursive includes. :basedirs: A set of thrift source file base directories to look for includes in. :sources: Seed thrift files to examine. :log: An optional logger. """ root_sources = set(sources) for source in sources: root_sources.difference_update(find_includes(basedirs, source, log=log)) return root_sources def calculate_include_paths(targets, is_thrift_target): """Calculates the set of import paths for the given targets. :targets: The targets to examine. :is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis. :returns: Include basedirs for the target. """ basedirs = set() def collect_paths(target): basedirs.add(target.target_base) for target in targets: target.walk(collect_paths, predicate=is_thrift_target) return basedirs
find_includes
identifier_name
thrift_util.py
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import re from builtins import open INCLUDE_PARSER = re.compile(r'^\s*include\s+"([^"]+)"\s*([\/\/|\#].*)*$') def find_includes(basedirs, source, log=None): """Finds all thrift files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger """ all_basedirs = [os.path.dirname(source)] all_basedirs.extend(basedirs) includes = set() with open(source, 'r') as thrift: for line in thrift.readlines(): match = INCLUDE_PARSER.match(line) if match: capture = match.group(1) added = False for basedir in all_basedirs: include = os.path.join(basedir, capture) if os.path.exists(include): if log: log.debug('{} has include {}'.format(source, include)) includes.add(include) added = True if not added: raise ValueError("{} included in {} not found in bases {}" .format(include, source, all_basedirs)) return includes def find_root_thrifts(basedirs, sources, log=None): """Finds the root thrift files in the graph formed by sources and their recursive includes. :basedirs: A set of thrift source file base directories to look for includes in. :sources: Seed thrift files to examine. :log: An optional logger. """ root_sources = set(sources) for source in sources:
return root_sources def calculate_include_paths(targets, is_thrift_target): """Calculates the set of import paths for the given targets. :targets: The targets to examine. :is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis. :returns: Include basedirs for the target. """ basedirs = set() def collect_paths(target): basedirs.add(target.target_base) for target in targets: target.walk(collect_paths, predicate=is_thrift_target) return basedirs
root_sources.difference_update(find_includes(basedirs, source, log=log))
conditional_block
thrift_util.py
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import re from builtins import open INCLUDE_PARSER = re.compile(r'^\s*include\s+"([^"]+)"\s*([\/\/|\#].*)*$') def find_includes(basedirs, source, log=None): """Finds all thrift files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger """ all_basedirs = [os.path.dirname(source)] all_basedirs.extend(basedirs) includes = set() with open(source, 'r') as thrift: for line in thrift.readlines(): match = INCLUDE_PARSER.match(line) if match: capture = match.group(1)
for basedir in all_basedirs: include = os.path.join(basedir, capture) if os.path.exists(include): if log: log.debug('{} has include {}'.format(source, include)) includes.add(include) added = True if not added: raise ValueError("{} included in {} not found in bases {}" .format(include, source, all_basedirs)) return includes def find_root_thrifts(basedirs, sources, log=None): """Finds the root thrift files in the graph formed by sources and their recursive includes. :basedirs: A set of thrift source file base directories to look for includes in. :sources: Seed thrift files to examine. :log: An optional logger. """ root_sources = set(sources) for source in sources: root_sources.difference_update(find_includes(basedirs, source, log=log)) return root_sources def calculate_include_paths(targets, is_thrift_target): """Calculates the set of import paths for the given targets. :targets: The targets to examine. :is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis. :returns: Include basedirs for the target. """ basedirs = set() def collect_paths(target): basedirs.add(target.target_base) for target in targets: target.walk(collect_paths, predicate=is_thrift_target) return basedirs
added = False
random_line_split
thrift_util.py
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import re from builtins import open INCLUDE_PARSER = re.compile(r'^\s*include\s+"([^"]+)"\s*([\/\/|\#].*)*$') def find_includes(basedirs, source, log=None): """Finds all thrift files included by the given thrift source. :basedirs: A set of thrift source file base directories to look for includes in. :source: The thrift source file to scan for includes. :log: An optional logger """ all_basedirs = [os.path.dirname(source)] all_basedirs.extend(basedirs) includes = set() with open(source, 'r') as thrift: for line in thrift.readlines(): match = INCLUDE_PARSER.match(line) if match: capture = match.group(1) added = False for basedir in all_basedirs: include = os.path.join(basedir, capture) if os.path.exists(include): if log: log.debug('{} has include {}'.format(source, include)) includes.add(include) added = True if not added: raise ValueError("{} included in {} not found in bases {}" .format(include, source, all_basedirs)) return includes def find_root_thrifts(basedirs, sources, log=None):
def calculate_include_paths(targets, is_thrift_target): """Calculates the set of import paths for the given targets. :targets: The targets to examine. :is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis. :returns: Include basedirs for the target. """ basedirs = set() def collect_paths(target): basedirs.add(target.target_base) for target in targets: target.walk(collect_paths, predicate=is_thrift_target) return basedirs
"""Finds the root thrift files in the graph formed by sources and their recursive includes. :basedirs: A set of thrift source file base directories to look for includes in. :sources: Seed thrift files to examine. :log: An optional logger. """ root_sources = set(sources) for source in sources: root_sources.difference_update(find_includes(basedirs, source, log=log)) return root_sources
identifier_body
round_trip.rs
// Copyright 2019 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use peek_poke::{Peek, PeekPoke, Poke}; use std::{fmt::Debug, marker::PhantomData}; fn poke_into<V: Peek + Poke>(a: &V) -> Vec<u8> { let mut v = <Vec<u8>>::with_capacity(<V>::max_size()); let end_ptr = unsafe { a.poke_into(v.as_mut_ptr()) }; let new_size = end_ptr as usize - v.as_ptr() as usize; assert!(new_size <= v.capacity()); unsafe { v.set_len(new_size); } v } #[cfg(not(feature = "option_copy"))] fn the_same<V>(a: V) where V: Debug + Default + PartialEq + Peek + Poke, { let v = poke_into(&a); let (b, end_ptr) = unsafe { peek_poke::peek_from_default(v.as_ptr()) }; let size = end_ptr as usize - v.as_ptr() as usize; assert_eq!(size, v.len()); assert_eq!(a, b); } #[cfg(feature = "option_copy")] fn the_same<V>(a: V) where V: Copy + Debug + PartialEq + Peek + Poke, { let v = poke_into(&a); let mut b = a; let end_ptr = unsafe { b.peek_from(v.as_ptr()) }; let size = end_ptr as usize - v.as_ptr() as usize; assert_eq!(size, v.len()); assert_eq!(a, b); } #[test] fn test_numbers() { // unsigned positive the_same(5u8); the_same(5u16); the_same(5u32); the_same(5u64); the_same(5usize); // signed positive the_same(5i8); the_same(5i16); the_same(5i32); the_same(5i64); the_same(5isize); // signed negative the_same(-5i8); the_same(-5i16); the_same(-5i32); the_same(-5i64); the_same(-5isize); // floating the_same(-100f32); the_same(0f32); the_same(5f32); the_same(-100f64); the_same(5f64); } #[test] fn test_bool() { the_same(true); the_same(false); } #[cfg(any(feature = "option_copy", feature = "option_default"))] #[test] fn test_option() { the_same(Some(5usize)); //the_same(Some("foo bar".to_string())); the_same(None::<usize>); } #[test] fn test_fixed_size_array() { the_same([24u32; 32]); the_same([1u64, 2, 3, 4, 5, 6, 7, 8]); the_same([0u8; 19]); } #[test] fn test_tuple() { the_same((1isize, )); the_same((1isize, 2isize, 3isize)); the_same((1isize, ())); } #[test] fn test_basic_struct() { #[derive(Copy, Clone, Debug, Default, PartialEq, PeekPoke)] struct Bar { a: u32, b: u32, c: u32, #[cfg(any(feature = "option_copy", feature = "option_default"))] d: Option<u32>, } the_same(Bar { a: 2, b: 4, c: 42, #[cfg(any(feature = "option_copy", feature = "option_default"))] d: None, }); } #[test] fn test_enum() { #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] enum TestEnum { NoArg, OneArg(usize), Args(usize, usize), AnotherNoArg, StructLike { x: usize, y: f32 }, } impl Default for TestEnum { fn default() -> Self { TestEnum::NoArg } } the_same(TestEnum::NoArg); the_same(TestEnum::OneArg(4)); the_same(TestEnum::Args(4, 5)); the_same(TestEnum::AnotherNoArg); the_same(TestEnum::StructLike { x: 4, y: 3.14159 }); } #[test] fn test_enum_cstyle()
#[test] fn test_phantom_data() { struct Bar; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)] struct Foo { x: u32, y: u32, _marker: PhantomData<Bar>, } the_same(Foo { x: 19, y: 42, _marker: PhantomData, }); } #[test] fn test_generic() { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)] struct Foo<T> { x: T, y: T, } the_same(Foo { x: 19.0, y: 42.0 }); } #[test] fn test_generic_enum() { #[derive(Clone, Copy, Debug, Default, PartialEq, PeekPoke)] pub struct PropertyBindingKey<T> { pub id: usize, _phantom: PhantomData<T>, } #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] pub enum PropertyBinding<T> { Value(T), Binding(PropertyBindingKey<T>, T), } impl<T: Default> Default for PropertyBinding<T> { fn default() -> Self { PropertyBinding::Value(Default::default()) } } } #[cfg(all(feature = "extras", feature = "option_copy"))] mod extra_tests { use super::*; use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Transform3D, Vector2D}; use std::mem::size_of; #[test] fn euclid_types() { the_same(Point2D::<f32>::new(1.0, 2.0)); assert_eq!(Point2D::<f32>::max_size(), 2 * size_of::<f32>()); the_same(Rect::<f32>::new( Point2D::<f32>::new(0.0, 0.0), Size2D::<f32>::new(100.0, 80.0), )); assert_eq!(Rect::<f32>::max_size(), 4 * size_of::<f32>()); the_same(SideOffsets2D::<f32>::new(0.0, 10.0, -1.0, -10.0)); assert_eq!(SideOffsets2D::<f32>::max_size(), 4 * size_of::<f32>()); the_same(Transform3D::<f32>::identity()); assert_eq!(Transform3D::<f32>::max_size(), 16 * size_of::<f32>()); the_same(Vector2D::<f32>::new(1.0, 2.0)); assert_eq!(Vector2D::<f32>::max_size(), 2 * size_of::<f32>()); } #[test] fn webrender_api_types() { type PipelineSourceId = i32; #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct PipelineId(pub PipelineSourceId, pub u32); #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct ClipChainId(pub u64, pub PipelineId); #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct SpatialId(pub usize, pub PipelineId); the_same(PipelineId(42, 2)); the_same(ClipChainId(19u64, PipelineId(42, 2))); the_same(SpatialId(19usize, PipelineId(42, 2))); } }
{ #[repr(u32)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PeekPoke)] enum BorderStyle { None = 0, Solid = 1, Double = 2, Dotted = 3, Dashed = 4, Hidden = 5, Groove = 6, Ridge = 7, Inset = 8, Outset = 9, } impl Default for BorderStyle { fn default() -> Self { BorderStyle::None } } the_same(BorderStyle::None); the_same(BorderStyle::Solid); the_same(BorderStyle::Double); the_same(BorderStyle::Dotted); the_same(BorderStyle::Dashed); the_same(BorderStyle::Hidden); the_same(BorderStyle::Groove); the_same(BorderStyle::Ridge); the_same(BorderStyle::Inset); the_same(BorderStyle::Outset); }
identifier_body
round_trip.rs
// Copyright 2019 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use peek_poke::{Peek, PeekPoke, Poke}; use std::{fmt::Debug, marker::PhantomData}; fn poke_into<V: Peek + Poke>(a: &V) -> Vec<u8> { let mut v = <Vec<u8>>::with_capacity(<V>::max_size()); let end_ptr = unsafe { a.poke_into(v.as_mut_ptr()) }; let new_size = end_ptr as usize - v.as_ptr() as usize; assert!(new_size <= v.capacity()); unsafe { v.set_len(new_size); } v } #[cfg(not(feature = "option_copy"))] fn the_same<V>(a: V) where V: Debug + Default + PartialEq + Peek + Poke, { let v = poke_into(&a); let (b, end_ptr) = unsafe { peek_poke::peek_from_default(v.as_ptr()) }; let size = end_ptr as usize - v.as_ptr() as usize; assert_eq!(size, v.len()); assert_eq!(a, b); } #[cfg(feature = "option_copy")] fn the_same<V>(a: V) where V: Copy + Debug + PartialEq + Peek + Poke, { let v = poke_into(&a); let mut b = a; let end_ptr = unsafe { b.peek_from(v.as_ptr()) }; let size = end_ptr as usize - v.as_ptr() as usize; assert_eq!(size, v.len()); assert_eq!(a, b); } #[test] fn test_numbers() { // unsigned positive the_same(5u8); the_same(5u16); the_same(5u32); the_same(5u64); the_same(5usize); // signed positive the_same(5i8); the_same(5i16); the_same(5i32); the_same(5i64); the_same(5isize); // signed negative the_same(-5i8); the_same(-5i16); the_same(-5i32); the_same(-5i64); the_same(-5isize); // floating the_same(-100f32); the_same(0f32); the_same(5f32); the_same(-100f64); the_same(5f64); } #[test] fn test_bool() { the_same(true); the_same(false); } #[cfg(any(feature = "option_copy", feature = "option_default"))] #[test] fn test_option() { the_same(Some(5usize)); //the_same(Some("foo bar".to_string())); the_same(None::<usize>); } #[test] fn test_fixed_size_array() { the_same([24u32; 32]); the_same([1u64, 2, 3, 4, 5, 6, 7, 8]); the_same([0u8; 19]); } #[test] fn test_tuple() { the_same((1isize, )); the_same((1isize, 2isize, 3isize)); the_same((1isize, ())); } #[test] fn test_basic_struct() { #[derive(Copy, Clone, Debug, Default, PartialEq, PeekPoke)] struct Bar { a: u32, b: u32, c: u32, #[cfg(any(feature = "option_copy", feature = "option_default"))] d: Option<u32>, } the_same(Bar { a: 2, b: 4, c: 42, #[cfg(any(feature = "option_copy", feature = "option_default"))] d: None, }); } #[test] fn test_enum() { #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] enum TestEnum { NoArg, OneArg(usize), Args(usize, usize), AnotherNoArg, StructLike { x: usize, y: f32 }, } impl Default for TestEnum { fn default() -> Self { TestEnum::NoArg } } the_same(TestEnum::NoArg); the_same(TestEnum::OneArg(4)); the_same(TestEnum::Args(4, 5)); the_same(TestEnum::AnotherNoArg); the_same(TestEnum::StructLike { x: 4, y: 3.14159 }); } #[test] fn test_enum_cstyle() { #[repr(u32)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PeekPoke)] enum BorderStyle { None = 0, Solid = 1, Double = 2, Dotted = 3, Dashed = 4, Hidden = 5, Groove = 6, Ridge = 7, Inset = 8, Outset = 9, } impl Default for BorderStyle { fn
() -> Self { BorderStyle::None } } the_same(BorderStyle::None); the_same(BorderStyle::Solid); the_same(BorderStyle::Double); the_same(BorderStyle::Dotted); the_same(BorderStyle::Dashed); the_same(BorderStyle::Hidden); the_same(BorderStyle::Groove); the_same(BorderStyle::Ridge); the_same(BorderStyle::Inset); the_same(BorderStyle::Outset); } #[test] fn test_phantom_data() { struct Bar; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)] struct Foo { x: u32, y: u32, _marker: PhantomData<Bar>, } the_same(Foo { x: 19, y: 42, _marker: PhantomData, }); } #[test] fn test_generic() { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)] struct Foo<T> { x: T, y: T, } the_same(Foo { x: 19.0, y: 42.0 }); } #[test] fn test_generic_enum() { #[derive(Clone, Copy, Debug, Default, PartialEq, PeekPoke)] pub struct PropertyBindingKey<T> { pub id: usize, _phantom: PhantomData<T>, } #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] pub enum PropertyBinding<T> { Value(T), Binding(PropertyBindingKey<T>, T), } impl<T: Default> Default for PropertyBinding<T> { fn default() -> Self { PropertyBinding::Value(Default::default()) } } } #[cfg(all(feature = "extras", feature = "option_copy"))] mod extra_tests { use super::*; use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Transform3D, Vector2D}; use std::mem::size_of; #[test] fn euclid_types() { the_same(Point2D::<f32>::new(1.0, 2.0)); assert_eq!(Point2D::<f32>::max_size(), 2 * size_of::<f32>()); the_same(Rect::<f32>::new( Point2D::<f32>::new(0.0, 0.0), Size2D::<f32>::new(100.0, 80.0), )); assert_eq!(Rect::<f32>::max_size(), 4 * size_of::<f32>()); the_same(SideOffsets2D::<f32>::new(0.0, 10.0, -1.0, -10.0)); assert_eq!(SideOffsets2D::<f32>::max_size(), 4 * size_of::<f32>()); the_same(Transform3D::<f32>::identity()); assert_eq!(Transform3D::<f32>::max_size(), 16 * size_of::<f32>()); the_same(Vector2D::<f32>::new(1.0, 2.0)); assert_eq!(Vector2D::<f32>::max_size(), 2 * size_of::<f32>()); } #[test] fn webrender_api_types() { type PipelineSourceId = i32; #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct PipelineId(pub PipelineSourceId, pub u32); #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct ClipChainId(pub u64, pub PipelineId); #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct SpatialId(pub usize, pub PipelineId); the_same(PipelineId(42, 2)); the_same(ClipChainId(19u64, PipelineId(42, 2))); the_same(SpatialId(19usize, PipelineId(42, 2))); } }
default
identifier_name
round_trip.rs
// Copyright 2019 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use peek_poke::{Peek, PeekPoke, Poke}; use std::{fmt::Debug, marker::PhantomData}; fn poke_into<V: Peek + Poke>(a: &V) -> Vec<u8> { let mut v = <Vec<u8>>::with_capacity(<V>::max_size()); let end_ptr = unsafe { a.poke_into(v.as_mut_ptr()) }; let new_size = end_ptr as usize - v.as_ptr() as usize; assert!(new_size <= v.capacity()); unsafe { v.set_len(new_size); } v } #[cfg(not(feature = "option_copy"))] fn the_same<V>(a: V) where V: Debug + Default + PartialEq + Peek + Poke, { let v = poke_into(&a); let (b, end_ptr) = unsafe { peek_poke::peek_from_default(v.as_ptr()) }; let size = end_ptr as usize - v.as_ptr() as usize; assert_eq!(size, v.len()); assert_eq!(a, b); } #[cfg(feature = "option_copy")] fn the_same<V>(a: V) where V: Copy + Debug + PartialEq + Peek + Poke, { let v = poke_into(&a); let mut b = a; let end_ptr = unsafe { b.peek_from(v.as_ptr()) }; let size = end_ptr as usize - v.as_ptr() as usize; assert_eq!(size, v.len()); assert_eq!(a, b); } #[test] fn test_numbers() { // unsigned positive the_same(5u8); the_same(5u16); the_same(5u32); the_same(5u64); the_same(5usize); // signed positive the_same(5i8); the_same(5i16); the_same(5i32); the_same(5i64); the_same(5isize); // signed negative the_same(-5i8); the_same(-5i16); the_same(-5i32); the_same(-5i64); the_same(-5isize); // floating the_same(-100f32); the_same(0f32); the_same(5f32); the_same(-100f64); the_same(5f64); } #[test] fn test_bool() { the_same(true); the_same(false); } #[cfg(any(feature = "option_copy", feature = "option_default"))] #[test] fn test_option() { the_same(Some(5usize)); //the_same(Some("foo bar".to_string())); the_same(None::<usize>); } #[test] fn test_fixed_size_array() { the_same([24u32; 32]); the_same([1u64, 2, 3, 4, 5, 6, 7, 8]); the_same([0u8; 19]); } #[test] fn test_tuple() { the_same((1isize, )); the_same((1isize, 2isize, 3isize)); the_same((1isize, ())); } #[test] fn test_basic_struct() { #[derive(Copy, Clone, Debug, Default, PartialEq, PeekPoke)] struct Bar { a: u32, b: u32, c: u32, #[cfg(any(feature = "option_copy", feature = "option_default"))] d: Option<u32>, } the_same(Bar { a: 2, b: 4, c: 42, #[cfg(any(feature = "option_copy", feature = "option_default"))] d: None, }); } #[test] fn test_enum() { #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] enum TestEnum { NoArg, OneArg(usize), Args(usize, usize), AnotherNoArg, StructLike { x: usize, y: f32 }, } impl Default for TestEnum { fn default() -> Self { TestEnum::NoArg } } the_same(TestEnum::NoArg); the_same(TestEnum::OneArg(4)); the_same(TestEnum::Args(4, 5)); the_same(TestEnum::AnotherNoArg); the_same(TestEnum::StructLike { x: 4, y: 3.14159 }); } #[test] fn test_enum_cstyle() { #[repr(u32)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PeekPoke)] enum BorderStyle { None = 0, Solid = 1, Double = 2, Dotted = 3, Dashed = 4, Hidden = 5, Groove = 6, Ridge = 7, Inset = 8, Outset = 9, } impl Default for BorderStyle { fn default() -> Self { BorderStyle::None } } the_same(BorderStyle::None); the_same(BorderStyle::Solid); the_same(BorderStyle::Double); the_same(BorderStyle::Dotted); the_same(BorderStyle::Dashed); the_same(BorderStyle::Hidden); the_same(BorderStyle::Groove); the_same(BorderStyle::Ridge); the_same(BorderStyle::Inset); the_same(BorderStyle::Outset); } #[test] fn test_phantom_data() { struct Bar; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)] struct Foo { x: u32, y: u32, _marker: PhantomData<Bar>, } the_same(Foo { x: 19, y: 42, _marker: PhantomData, }); } #[test] fn test_generic() { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PeekPoke)] struct Foo<T> { x: T, y: T, } the_same(Foo { x: 19.0, y: 42.0 }); } #[test] fn test_generic_enum() { #[derive(Clone, Copy, Debug, Default, PartialEq, PeekPoke)] pub struct PropertyBindingKey<T> { pub id: usize, _phantom: PhantomData<T>, } #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] pub enum PropertyBinding<T> { Value(T), Binding(PropertyBindingKey<T>, T), } impl<T: Default> Default for PropertyBinding<T> { fn default() -> Self { PropertyBinding::Value(Default::default()) } } } #[cfg(all(feature = "extras", feature = "option_copy"))] mod extra_tests { use super::*; use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Transform3D, Vector2D}; use std::mem::size_of; #[test] fn euclid_types() { the_same(Point2D::<f32>::new(1.0, 2.0)); assert_eq!(Point2D::<f32>::max_size(), 2 * size_of::<f32>()); the_same(Rect::<f32>::new( Point2D::<f32>::new(0.0, 0.0), Size2D::<f32>::new(100.0, 80.0), )); assert_eq!(Rect::<f32>::max_size(), 4 * size_of::<f32>()); the_same(SideOffsets2D::<f32>::new(0.0, 10.0, -1.0, -10.0)); assert_eq!(SideOffsets2D::<f32>::max_size(), 4 * size_of::<f32>()); the_same(Transform3D::<f32>::identity()); assert_eq!(Transform3D::<f32>::max_size(), 16 * size_of::<f32>()); the_same(Vector2D::<f32>::new(1.0, 2.0)); assert_eq!(Vector2D::<f32>::max_size(), 2 * size_of::<f32>()); } #[test] fn webrender_api_types() { type PipelineSourceId = i32; #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct PipelineId(pub PipelineSourceId, pub u32); #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct ClipChainId(pub u64, pub PipelineId); #[derive(Clone, Copy, Debug, PartialEq, PeekPoke)] struct SpatialId(pub usize, pub PipelineId); the_same(PipelineId(42, 2)); the_same(ClipChainId(19u64, PipelineId(42, 2))); the_same(SpatialId(19usize, PipelineId(42, 2))); } }
//
random_line_split